code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def compute_source_galaxy_selection_indices( source_galaxies_host_halo_id, source_halo_ids, target_halo_ids, source_halo_props, target_halo_props, ): <NEW_LINE> <INDENT> idx_sorted_source_galaxies = np.argsort(source_galaxies_host_halo_id) <NEW_LINE> sorted_source_galaxies_host_halo_id = source_galaxies_host_halo_id[ i... | Calculate the indexing array that transfers source galaxies to target halos
Parameters
----------
source_galaxies_host_halo_id : ndarray of shape (n_source_gals, )
Integer array storing values appearing in source_halo_ids
source_halo_ids : ndarray of shape (n_source_halos, )
target_halo_ids : ndarray of shape (n... | 625941f5ff9c53063f47c835 |
def getCutPosition( uSeq, bPutBack = False, iOffset = 0 ): <NEW_LINE> <INDENT> if isinstance( uSeq, int ): <NEW_LINE> <INDENT> iLen = uSeq <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iLen = len( uSeq ) <NEW_LINE> <DEDENT> if bPutBack: <NEW_LINE> <INDENT> iCutAt = getIntegerDivisionRoundUp( iLen, 2 ) - iOffset ... | returns iCutAt, the regular index position of the place to cut,
with the first character having a regular index position of zero
string will be cut as follows:
return uSeq[ : iCutAt ], uSeq[ iCutAt : ]
getCutPosition( 26, iOffset = -13 ) returns 0
getCutPosition( 26, iOffset = 0 ) returns 13
getCutPosition( 26, iOf... | 625941f5de87d2750b8603e0 |
def chars(self, min_chars=1, max_chars=5): <NEW_LINE> <INDENT> if min_chars > max_chars: <NEW_LINE> <INDENT> raise ParameterError('min_chars greater than max_chars') <NEW_LINE> <DEDENT> chars = random.randint(min_chars, max_chars) <NEW_LINE> result = '' <NEW_LINE> for _ in range(chars): <NEW_LINE> <INDENT> result += se... | Random text with 1 word. | 625941f563d6d428bbe44b37 |
def get_plot_dict(cid_dict): <NEW_LINE> <INDENT> cluster_id_dict = {} <NEW_LINE> ref = {cl: cid for cid,cl in enumerate(sorted(set(cid_dict.values())))} <NEW_LINE> for tid,cl in cid_dict.items(): <NEW_LINE> <INDENT> cluster_id_dict[tid] = ref[cl] <NEW_LINE> <DEDENT> return cluster_id_dict | The purpose of this function is to be a lightweight way to move from a
allocated dict to a dict with unique numbers as values (keyed by tracklet id)
for plotting purposes (pass as the cluster_id_dict argument to the generate_
sky_region_files).
---------
Args: cid_dict; dict, keyed on tracklet id, with the values as th... | 625941f571ff763f4b549cdd |
def download_file(self, local_file, remote_file): <NEW_LINE> <INDENT> self.debug_print("download_file()---> local_path = %s ,remote_path = %s" % (local_file, remote_file)) <NEW_LINE> if self.is_same_size(local_file, remote_file): <NEW_LINE> <INDENT> self.debug_print('%s 文件大小相同,无需下载' % local_file) <NEW_LINE> return <NEW... | 从ftp下载文件
参数:
local_file: 本地文件
remote_file: 远程文件 | 625941f5a79ad161976cc78b |
def delay(self, time=0): <NEW_LINE> <INDENT> self.mem = Mem.AppendMemDelay(self.mem, _us(time)) | Delay in microseconds.
Input:
time: delay time in microseconds. | 625941f5bde94217f3683430 |
def deleteByID(id): <NEW_LINE> <INDENT> global __pool <NEW_LINE> if isinstance(id, int): <NEW_LINE> <INDENT> if id in __pool.keys(): <NEW_LINE> <INDENT> trigger("deletion", __pool[id]) <NEW_LINE> del __pool[id] <NEW_LINE> return __orange__.DeleteMarker(id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW... | Deletes a marker object by the given id.
Args:
id (int): marker id
Returns:
bool: True on success, False on failure
Raises:
TypeError: raises if marker id is not int | 625941f56fb2d068a760f6ed |
def main(): <NEW_LINE> <INDENT> if len(sys.argv) != 2: <NEW_LINE> <INDENT> raise SyntaxError("Usage: to_csv.py [res_file]") <NEW_LINE> <DEDENT> with open(sys.argv[1], 'r') as res_file: <NEW_LINE> <INDENT> res = res_file.read() <NEW_LINE> <DEDENT> print(','.join([ 'n_orbs_var', 'eps_var', 'n_orbs_pt', 'eps_pt', 'energy_... | main function | 625941f5a934411ee3751cdb |
def mintime(A, B, C, D, E, F): <NEW_LINE> <INDENT> timeformat = "%H:%M:%S" <NEW_LINE> valid_time = [] <NEW_LINE> for p in itertools.permutations([A, B, C, D, E, F]): <NEW_LINE> <INDENT> str_time = '{}{}:{}{}:{}{}'.format(*p) <NEW_LINE> try: <NEW_LINE> <INDENT> datetime.datetime.strptime(str_time, timeformat) <NEW_LINE>... | Given 6 digits, return minimum time in HH MM SS format
Args:
A : int [0..9]
B : int [0..9]
C : int [0..9]
D : int [0..9]
E : int [0..9]
F : int [0..9] | 625941f50383005118ecfc25 |
def naked_twins(values): <NEW_LINE> <INDENT> for unit in unitlist: <NEW_LINE> <INDENT> list_double_values = [(box, values[box]) for box in unit if len(values[box]) == 2] <NEW_LINE> if len(list_double_values) >= 2: <NEW_LINE> <INDENT> boxes_double, values_double = zip(*list_double_values) <NEW_LINE> for value in set(val... | Eliminate values using the naked twins strategy.
Args:
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
the values dictionary with the naked twins eliminated from peers. | 625941f5c432627299f05290 |
def test_class_exists(self): <NEW_LINE> <INDENT> self.assertTrue(hasattr(Certificate, self.klass_name)) | Certificate class is defined | 625941f5e76e3b2f99f3ae46 |
@greeting <NEW_LINE> def f02(x): <NEW_LINE> <INDENT> return x + 4 | just some silly function | 625941f597e22403b379d5e1 |
def write(self, obj): <NEW_LINE> <INDENT> raise NotImplementedError('write(obj)') | Writes obj to file. | 625941f550812a4eaa59c960 |
def GetBrightObject(self): <NEW_LINE> <INDENT> return _itkHessianToObjectnessMeasureImageFilterPython.itkHessianToObjectnessMeasureImageFilterISSRTD22IF2_GetBrightObject(self) | GetBrightObject(self) -> bool | 625941f5d7e4931a7ee9e565 |
def ceiling (rbt, key, comparefunction): <NEW_LINE> <INDENT> if (rbt == None): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> cmp = comparefunction (key, rbt['key']) <NEW_LINE> if (cmp == 0): <NEW_LINE> <INDENT> return rbt <NEW_LINE> <DEDENT> if (cmp < 0): <NEW_LINE> <INDENT> t = ceiling (rbt['left'], key, compar... | Retorna la llave mas pequeña en la tabla de simbolos, mayor o igual a la llave key | 625941f5796e427e537b0c11 |
def __init__(self, file_path:str, save_path:str=None): <NEW_LINE> <INDENT> self.file_path = file_path <NEW_LINE> self.save_path = save_path or file_path | Initialization for the class. | 625941f5167d2b6e312191da |
def itkMeshD3S_cast(*args): <NEW_LINE> <INDENT> return _itkMeshPython.itkMeshD3S_cast(*args) | itkMeshD3S_cast(itkLightObject obj) -> itkMeshD3S | 625941f57d43ff24873a32eb |
def _resume_checkpoint(self, resume_path): <NEW_LINE> <INDENT> resume_path = str(resume_path) <NEW_LINE> self.logger.info("Loading checkpoint: {} ...".format(resume_path)) <NEW_LINE> checkpoint = torch.load(resume_path) <NEW_LINE> self.start_epoch = checkpoint['epoch'] + 1 <NEW_LINE> self.mnt_best = checkpoint['monitor... | Resume from saved checkpoints
:param resume_path: Checkpoint path to be resumed | 625941f5090684286d50f336 |
def __init__(self): <NEW_LINE> <INDENT> self._cache = weakref.WeakValueDictionary() if CachedUmpManager.s_use_weak else dict() | 初始化_cache本体,根据s_use_weak决定使用WeakValueDictionary或者dict | 625941f5d8ef3951e3243b83 |
def SetImageSize(self, width, height): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height | assigne dimensions of the image encoded in image_string argument of SetImage.
this information is needed to retrieve the image out of the image_string. | 625941f5a05bb46b383ece61 |
def notices(request): <NEW_LINE> <INDENT> return render(request, 'substitute/notices.html') | Page for legal notices | 625941f5b830903b967e9f49 |
def __init__(self): <NEW_LINE> <INDENT> self.TotalNum = None <NEW_LINE> self.List = None <NEW_LINE> self.ServiceTypeList = None <NEW_LINE> self.RequestId = None | :param TotalNum: Total number of policies
:type TotalNum: int
:param List: Policy array. Each array contains fields including `policyId`, `policyName`, `addTime`, `type`, `description`, and `createMode`.
policyId: policy ID
policyName: policy name
addTime: policy creation time
type: 1: custom ... | 625941f53eb6a72ae02ecb35 |
def __init__(self, rolls=1, sides=6, add=0): <NEW_LINE> <INDENT> self.rolls = rolls <NEW_LINE> self.sides = sides <NEW_LINE> self.add = add | Set initial value for rolls, sides, add | 625941f5435de62698dfe293 |
def addLetters(self, newLetters, locationX, locationY, direction): <NEW_LINE> <INDENT> locationX -= 1 <NEW_LINE> locationY -= 1 <NEW_LINE> if direction == 'right' and (locationX + len(newLetters) <= 15): <NEW_LINE> <INDENT> for x in range(len(newLetters)): <NEW_LINE> <INDENT> self.board[locationX][locationY + x] = newL... | This method adds the letters to the board in three different directions
@param: newLetters are the letters to be added to the board
@param: locationX is row
@param: locationY is the column
@param: direction is the directions the word is inserted | 625941f5711fe17d825429a2 |
def get_document_revisions(self, document_id): <NEW_LINE> <INDENT> return self._service.revisions().list(fileId=document_id).execute() | Returns the list of revisions for the given document_id | 625941f5d7e4931a7ee9e566 |
def getEncoder(self, *args): <NEW_LINE> <INDENT> return _yarp.IEncoders_getEncoder(self, *args) | getEncoder(IEncoders self, int j, double * v) -> bool
getEncoder(IEncoders self, int j) -> double | 625941f5627d3e7fe0d69498 |
def send_update(self, client_id, message): <NEW_LINE> <INDENT> message = simplejson.dumps(message) <NEW_LINE> logging.debug('Sending message to client: %s - %s' % (client_id, message)) <NEW_LINE> channel.send_message(client_id, message) | Send a message as JSON to the client identified with client_id. | 625941f5379a373c97cfb18d |
@tf_export("summary.trace_export", v1=[]) <NEW_LINE> def trace_export(name, step=None, profiler_outdir=None): <NEW_LINE> <INDENT> global _current_trace_context <NEW_LINE> if ops.inside_function(): <NEW_LINE> <INDENT> logging.warn("Cannot export trace inside a tf.function.") <NEW_LINE> return <NEW_LINE> <DEDENT> if not ... | Stops and exports the active trace as a Summary and/or profile file.
Stops the trace and exports all metadata collected during the trace to the
default SummaryWriter, if one has been set.
Args:
name: A name for the summary to be written.
step: Explicit `int64`-castable monotonic step value for this summary. If
... | 625941f5ad47b63b2c50a5c6 |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> _x = self <NEW_LINE> start = end <NEW_LINE> end += 25 <NEW_LINE> (_x.type, _x.p_gain, _x.i_gain, _x.d_gain,) = _get_struct_B3d().unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error ... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941f5596a89723608a0fd |
def test_query_with_correct_parameters_containsstring_notuple(self): <NEW_LINE> <INDENT> query = self.as_connection.query('test', 'demo') <NEW_LINE> query.select('name', 'test_age') <NEW_LINE> query.where('string_list', "contains", aerospike.INDEX_TYPE_LIST, aerospike.INDEX_STRING, "str3") <NEW_LINE> records = [] <NEW_... | Invoke query() with correct a
and a string list index arguments and using predicate contains | 625941f5566aa707497f4ba5 |
def rotate_to_smallest(path): <NEW_LINE> <INDENT> n = path.index(min(path)) <NEW_LINE> return path[n:] + path[:n] | Rotate cycle path such that it begins with the smallest node | 625941f53c8af77a43ae3dee |
def config_argparser(parser): <NEW_LINE> <INDENT> add_usual_input_args(parser, doc_subdoc_required=True, help_suffix='to move from') <NEW_LINE> add_usual_output_args(parser, default_overwrite=True) <NEW_LINE> parser.add_argument('span', metavar='INT,INT', type=comma_span, help='Text span') <NEW_LINE> parser.add_argumen... | Subcommand flags.
You should create and pass in the subparser to which the flags
are to be added. | 625941f54d74a7450ccd480c |
def analyze(self, keys, total=0): <NEW_LINE> <INDENT> key_stat = { 'headers': ['Match', "Count", "Useful", "Real", "Ratio", "Encoding", "Min", "Max", "Avg"], 'data': [] } <NEW_LINE> progress = tqdm(total=total, mininterval=1, desc="Processing keys", leave=False) <NEW_LINE> for pattern, data in keys.items(): <NEW_LINE> ... | :param keys:
:param progress:
:return: | 625941f5b57a9660fec33ed3 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Model, self).__init__(**kwargs) <NEW_LINE> self.requirements.update({"domain": {"any": True, "empty": False}}) <NEW_LINE> self.required_inputs = [] <NEW_LINE> self.backup_comps = {} | Create a Model Class | 625941f5236d856c2ad44e2a |
def __init__(self, datasets): <NEW_LINE> <INDENT> self.datasets = [Dataset(i) for i in datasets] | Parameters
----------
datasets: list<string>
list of datasets to load. | 625941f521bff66bcd684f93 |
def pandas_dataframe_to_html(obj) -> str: <NEW_LINE> <INDENT> html = obj.to_html(escape=False) <NEW_LINE> return PANDAS_PATTERN.sub("", html) | Convert a pandas.DataFrame into a <table> tag. | 625941f5d164cc6175783395 |
def _get_file_header_key_info(self, key): <NEW_LINE> <INDENT> file_header_info = self.config['file_header'] <NEW_LINE> ucomment = None <NEW_LINE> udatatype = None <NEW_LINE> if key in file_header_info: <NEW_LINE> <INDENT> if 'description' in file_header_info[key]: <NEW_LINE> <INDENT> ucomment = file_header_info[key]['d... | From definitions of file header keys, return comment and fits
data type. | 625941f515baa723493c45c1 |
def begin_disconnect_p2_s_vpn_connections( self, resource_group_name, p2_s_vpn_gateway_name, request, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_toke... | Disconnect P2S vpn connections of the virtual wan P2SVpnGateway in the specified resource
group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param p2_s_vpn_gateway_name: The name of the P2S Vpn Gateway.
:type p2_s_vpn_gateway_name: str
:param request: The parameters are ... | 625941f57c178a314d6efab1 |
def length_squared(self): <NEW_LINE> <INDENT> return sum([x*x for x in self.v]) | Returns the square of the cartesian length of vector
:return: float
>>> vec3((5,0,0)).length_squared()
25.0
>>> vec3(1).length_squared()
3.0 | 625941f555399d3f05588cff |
def __init__( self, env_obs_shape: List[int], multitask_cfg: ConfigType, feature_dim: int, ): <NEW_LINE> <INDENT> super().__init__(env_obs_shape=env_obs_shape, multitask_cfg=multitask_cfg) <NEW_LINE> assert len(env_obs_shape) == 1 <NEW_LINE> self.feature_dim = feature_dim | Identity encoder that does not perform any operations.
Args:
env_obs_shape (List[int]): shape of the observation that the actor gets.
multitask_cfg (ConfigType): config for encoding the multitask knowledge.
# feature_dim (int): feature dimension.
# num_layers (int, optional): number of layers. Defaults... | 625941f50fa83653e46575fd |
def fetch(repository, commit_id=None, sha1=None, ref=None): <NEW_LINE> <INDENT> import api.impl <NEW_LINE> assert isinstance(repository, api.repository.Repository) <NEW_LINE> assert (ref is None) != ((commit_id is None) and (sha1 is None)) <NEW_LINE> return api.impl.commit.fetch(repository, commit_id, sha1, ref) | Fetch a Git commit from the given repository
The commit can be identified by its unique (internal) database id, its
SHA-1 (full 40 character string) or by an arbitrary ref that resolves to
a commit object (possibly via tag objects) when given to the
'git rev-parse' command. | 625941f5d8ef3951e3243b84 |
def test_devel_two_target_tylenol_circuit_simple_acc_test_driver_interactions_ad_enable_count(self): <NEW_LINE> <INDENT> input_data_list = ["devel", 1, "two target tylenol circuit", 0, "simple_acc_test", 34, "driver_interactions ad_enable_count"] <NEW_LINE> self.simulated_page_input_setter.set_input_data(input_data_lis... | BRANCH: devel
TEST SUITE: two target tylenol circuit
TEST CASE: simple_acc_test
KPI: driver_interactions ad_enable_count | 625941f54a966d76dd55165d |
def associate_route_table(**kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = client.associate_route_table( DryRun=kwargs['DryRun'], SubnetId=kwargs['SubnetId'], RouteTableId=kwargs['RouteTableId'] ) <NEW_LINE> return response <NEW_LINE> <DEDENT> except ClientError as e: <NEW_LINE> <INDENT> print(e) | Associates a subnet with a route table.
:param kwargs:
DryRun=True|False,
SubnetId='string',
RouteTableId='string'
:return: | 625941f5baa26c4b54cb175e |
def test_shortest_link_fail_fake_id(self): <NEW_LINE> <INDENT> fake_artist_id = 'ashkannasseri' <NEW_LINE> path = artists_services.shortest_link(fake_artist_id) <NEW_LINE> self.assertEqual(len(path), 0, "Test path is empty for non-exsting artist id") | Test path for fake artist id | 625941f58e7ae83300e4b615 |
def draw_edges(edges, fname='pamPic.tex', scale=10): <NEW_LINE> <INDENT> with open(fname,'w') as f: <NEW_LINE> <INDENT> f.write('\\begin{tikzpicture}') <NEW_LINE> f.write('[scale={}]\n'.format(scale)) <NEW_LINE> f.write('\\clip (0,0) rectangle (1,1);') <NEW_LINE> for p,q in edges: <NEW_LINE> <INDENT> f.write("\\draw ({... | Draw edges in tikz
# Arguments
edges:list of edges
fname: name of output file
scale: scale of tikz picture | 625941f507d97122c4178ee1 |
def _load_hts_lines(lines: list) -> dict: <NEW_LINE> <INDENT> labels = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line_split = line.split(maxsplit=2) <NEW_LINE> d_line = {} <NEW_LINE> d_line['time'] = list(map(int, line_split[0:2])) <NEW_LINE> str_contexts = line_split[2] <NEW_LINE> l_contexts = re.split('/.:... | 文字列のリスト(行のリスト)をもとに値を登録する。 | 625941f53eb6a72ae02ecb36 |
def test_app_for_run_with_archiving_copy_move_compress(self): <NEW_LINE> <INDENT> str_env = os.path.join(self.str_test_directory, "test_app_for_run_with_archiving_copy_move_compress") <NEW_LINE> str_env_move = os.path.join(self.str_test_directory, "test_app_for_run_with_archiving_copy_move_compress_move") <NEW_LINE> st... | Test the scenario where the example script is ran with archiving of the output directory using a copy to one location.
The output directory is then moved to another. The output directory in this case is compressed into one archive
before moving. | 625941f560cbc95b062c6b8a |
def copy(self, **attributes): <NEW_LINE> <INDENT> updated_options = attributes.pop("options", {}) <NEW_LINE> options = self.options.copy() <NEW_LINE> options.update(updated_options) <NEW_LINE> return self._replace(**attributes, options=options) | Create a copy of this message.
| 625941f57cff6e4e81117fcc |
def counting_valleys(n: int, s: str) -> int: <NEW_LINE> <INDENT> current_level = 0 <NEW_LINE> valley_counter = 0 <NEW_LINE> for i in s: <NEW_LINE> <INDENT> if i == 'U': <NEW_LINE> <INDENT> current_level += 1 <NEW_LINE> if current_level == 0: <NEW_LINE> <INDENT> valley_counter += 1 <NEW_LINE> <DEDENT> <DEDENT> elif i ==... | Input: n - number of steps (climb or descend the mountain)
s - steps sequence (U is for climbing, D is for descending)
Output: number of valleys
Default starting level is 0(sea level), there is
a valley if we climb up from the pit to sea level. | 625941f50a50d4780f6674de |
def __len__(self): <NEW_LINE> <INDENT> return len(self.meneo_divs) | Devuelve el número de meneos en la página.
Returns:
El número de meneos en la página. | 625941f530c21e258bdfaaeb |
def OnepEvent_ContainerSrvInfoRequestIDL(self, sessionHandle, eventtype, transactionID, macid, extrainfo): <NEW_LINE> <INDENT> self.log.debug('Container Info Request IDL: session Handle = ' + str(sessionHandle) + ' event type = ' + str(eventtype) + ' transaction ID = ' + str(transactionID)) <NEW_LINE> if self.terminate... | For internal use only | 625941f5187af65679ca5767 |
def test_router_outgoing_phases(self): <NEW_LINE> <INDENT> self.router.add_app(harness.MockApp) <NEW_LINE> self.router.add_backend("mockbackend", harness.MockBackend) <NEW_LINE> backend = self.create_backend(data={'name': 'mockbackend'}) <NEW_LINE> connection = self.create_connection(data={'backend': backend}) <NEW_LIN... | Outgoing messages should trigger proper router phases. | 625941f58da39b475bd655c3 |
def get_tvalue(self): <NEW_LINE> <INDENT> return self._tvalue | Returns the elements value as its type.
@return: the element value
@rtype: string/integer/float | 625941f544b2445a339326d8 |
def __init__(self, phase = 'Phase3', locust_file_name = None, unknown_args_translation = {}, **kwargs): <NEW_LINE> <INDENT> self._add_unknown_args_translation(unknown_args_translation) <NEW_LINE> self._config_dict = _set_dict_2d(self._key_dict, self._key_to_var_dict, kwargs) <NEW_LINE> self._handle_phase(phase, locust_... | Parameters
----------
phase : str
Should be either 'Phase2' or 'Phase3' and determines if
phase 2 or phase 3 simulation is run (default 'Phase3')
locust_file_name : str, optional
The name for the Locust configuration file that should
be used. This means only the file name, not the full path!
The fil... | 625941f566656f66f7cbc7f3 |
def get_new_fib(board): <NEW_LINE> <INDENT> if board == EMPTY_BOARD: <NEW_LINE> <INDENT> index = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> highest_number = max(board_iter(board)) <NEW_LINE> index = FIBS.index(highest_number) <NEW_LINE> <DEDENT> max_index = max(2, index - 2) <NEW_LINE> p = -1.5 <NEW_LINE> lower = ... | Returns a random new fibonacci number.
If the highest number on board is 21, can return fibs up to 8.
1 and 2 are always possibilities. | 625941f5cad5886f8bd2761e |
def test_math_latex_block(): <NEW_LINE> <INDENT> (RST(BLOCK_MATH_RST, math_output='latex') .assert_body( r'<pre class="math">\lambda^2 < \sum_{i=1}^n \frac{x}{y}</pre>', )) | Block math to LaTeX conversion. | 625941f51f5feb6acb0c518f |
@AJAX.route('/ajax/ticket/<int:ticket_id>/collect', methods=['POST']) <NEW_LINE> @login.login_required <NEW_LINE> @login_manager.admin_required <NEW_LINE> def collect_ticket(ticket_id): <NEW_LINE> <INDENT> ticket = models.Ticket.get_by_id(ticket_id) <NEW_LINE> if not ticket: <NEW_LINE> <INDENT> response = { 'success': ... | Mark a ticket as collected, and add a barcode.
Performs the requisite logic to check the barcode submitted for a ticket,
and marks the ticket as collected. | 625941f55fcc89381b1e1d0b |
def _apply_cdn_to_url(self, url, base_url): <NEW_LINE> <INDENT> if not url: <NEW_LINE> <INDENT> return url <NEW_LINE> <DEDENT> _, netloc, path, params, query, fragment = urlparse(url) <NEW_LINE> if netloc: <NEW_LINE> <INDENT> return url <NEW_LINE> <DEDENT> return urlunparse((None, base_url, path, params, query, fragmen... | Applies a new CDN/base URL to the given URL.
If a URL is absolute, we skip switching the host since it could
be a hostname that isn't behind our CDN, and we could unintentionally
break the URL overall. | 625941f55f7d997b871750e4 |
def get_version(self, var: str): <NEW_LINE> <INDENT> if var in self.ssa_record.var_version_list: <NEW_LINE> <INDENT> version = ( -1 if len(self.ssa_record.var_version_list[var]) == 0 else self.ssa_record.var_version_list[var][-1] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> version = -1 <NEW_LINE> <DEDENT> return ve... | get the version number of the var, create the var entry if it's not exists | 625941f5f548e778e58cdbc7 |
def import_census_data(self, data2 = None): <NEW_LINE> <INDENT> print('Importing census data') <NEW_LINE> self.df_census = GeoDataFrame.from_file( self.census_folder_loc + self.census_shapefile) <NEW_LINE> print('Census data loaded') <NEW_LINE> self.df_census['pop'] = self.df_census['SUM_TOTAL'] <NEW_LINE> self.df_cens... | Gets population density from census data
Inputs:
census_folder_loc: location of data (string)
census_shapefile: name of shapefile (string)
Returns:
df_census: GeoDataFrame with census information | 625941f550812a4eaa59c961 |
def get_all_files(path_src): <NEW_LINE> <INDENT> root_dir = ls(path_src) <NEW_LINE> files = list() <NEW_LINE> for element in root_dir: <NEW_LINE> <INDENT> element_path = path.join(path_src, element) <NEW_LINE> if path.isdir(element_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> make(element_path.replace('input', '... | this function read all files from input folder
:return: list of all files | 625941f591af0d3eaac9c064 |
def get_random_greeting(name): <NEW_LINE> <INDENT> if not is_valid_name(name): <NEW_LINE> <INDENT> raise Error("Name '%s' is not valid" % name) <NEW_LINE> <DEDENT> with open("greeting_templates.txt") as handle: <NEW_LINE> <INDENT> templates = handle.readlines() <NEW_LINE> <DEDENT> template_index = random.randint(0, len... | Get a random hello for the given name.
The name is first validated - it has to be characters-only and non-empty.
If the name is valid, read a data file with possible greetings, select one
randomly and personalize it with the name.
Args:
name: string, the person to say hello to
Returns:
string, the hello | 625941f57c178a314d6efab2 |
def apply_strategy(grf, strategy): <NEW_LINE> <INDENT> if strategy == 'basic': <NEW_LINE> <INDENT> return apply_strategy_basic(grf) <NEW_LINE> <DEDENT> elif strategy == 'entities_only': <NEW_LINE> <INDENT> return apply_strategy_entities_only(grf) | Receives an RDF graph and applies a filtering strategy to it
:param g: an rdflib Graph to apply the strategy to
:param strategy: the ID of the strategy applied
:return: an rdflib Graph (results of input with strategy applied) | 625941f54e696a04525c9a95 |
def get_identity(self): <NEW_LINE> <INDENT> return GetIdentity(*self.ipcon.send_request(self, BrickletPiezoBuzzer.FUNCTION_GET_IDENTITY, (), '', '8s 8s c 3B 3B H')) | Returns the UID, the UID where the Bricklet is connected to,
the position, the hardware and firmware version as well as the
device identifier.
The position can be 'a', 'b', 'c' or 'd'.
The device identifier numbers can be found :ref:`here <device_identifier>`.
|device_identifier_constant| | 625941f526238365f5f0f4bd |
def get_full_name(self): <NEW_LINE> <INDENT> return ' '.join(self.firstname, self.lastname) | This method is required by Django for things like handling emails.
Typically this would be the user's first and last name. If the user's real name,
not stored we return their username instead. | 625941f5379a373c97cfb18e |
def get_label(self, label): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.labels[label] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for i in self.labels.values(): <NEW_LINE> <INDENT> if i.name == label: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_... | Get label as identified by index or name
:throws KeyError: when label is not found | 625941f529b78933be1e5ceb |
def get_boxes(score, geo, score_thresh=0.9, nms_thresh=0.2): <NEW_LINE> <INDENT> score = score[0, :, :] <NEW_LINE> xy_text = np.argwhere(score > score_thresh) <NEW_LINE> print('-------------------------xy_text:',xy_text) <NEW_LINE> if xy_text.size == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> xy_text = xy_t... | get boxes from feature map
Input:
score : score map from model <numpy.ndarray, (1,row,col)>
geo : geo map from model <numpy.ndarray, (5,row,col)>
score_thresh: threshold to segment score map
nms_thresh : threshold in nms
Output:
boxes : final polys <numpy.ndarray, (n,9)> | 625941f53617ad0b5ed6853d |
def attack_vector_graph(violated_components): <NEW_LINE> <INDENT> attack_vector_graph = nx.Graph() <NEW_LINE> admissible_vertices = [] <NEW_LINE> for violated_component in violated_components: <NEW_LINE> <INDENT> for attack_vector in violated_component[1]: <NEW_LINE> <INDENT> vertex = attack_vector.db_name + "-" + atta... | Takes as input a result set
and produces the attack vector graph. | 625941f550485f2cf553d3e3 |
def main(): <NEW_LINE> <INDENT> print('>>>>> START') <NEW_LINE> dates, prices, price_diff = get_data('data.csv') <NEW_LINE> indices = [i for i in range(0, len(prices))] <NEW_LINE> delete_outlayers(dates, price_diff) <NEW_LINE> delete_outlayers(prices, price_diff) <NEW_LINE> delete_outlayers(indices, price_diff) <NEW_LI... | The main function consists of csv data parsing, svr modelling, plotting and prediction generation | 625941f58c0ade5d55d3f008 |
@raises(OSError) <NEW_LINE> @provide_tempdir <NEW_LINE> def test_read_before_write_or_tag(tempdir): <NEW_LINE> <INDENT> path = os.path.join(tempdir, 'thing') <NEW_LINE> fsfs.read(path) | Read before write or tag raises OSError | 625941f5d4950a0f3b08c98d |
def test_like_comment(self): <NEW_LINE> <INDENT> self.test_write_comment() <NEW_LINE> client = Client() <NEW_LINE> client.force_login(self.alice) <NEW_LINE> comment = Comment.objects.all()[0] <NEW_LINE> response = client.get(reverse('social_layer:like_comment', kwargs={'pk': comment.pk, 'didlike': 'like'})) <NEW_LINE> ... | Hit the like button | 625941f5498bea3a759ba0f4 |
@with_setup(pretest, posttest) <NEW_LINE> def test_bool(): <NEW_LINE> <INDENT> def internal(our_file, disable): <NEW_LINE> <INDENT> kwargs = dict(file=our_file, disable=disable) <NEW_LINE> with trange(10, **kwargs) as t: <NEW_LINE> <INDENT> assert t <NEW_LINE> <DEDENT> with trange(0, **kwargs) as t: <NEW_LINE> <INDENT>... | Test boolean cast | 625941f54428ac0f6e5bae40 |
def input_raw_tweet(self, tweet): <NEW_LINE> <INDENT> if hasattr(tweet, 'retweeted_status'): <NEW_LINE> <INDENT> if hasattr(tweet.retweeted_status, 'quoted_status'): <NEW_LINE> <INDENT> self.__input_tweet__(tweet.retweeted_status, 'Normal tweet') <NEW_LINE> self.__input_tweet__(tweet.retweeted_status, 'Quoting info') <... | This takes the raw tweet input and breaks it into its sub-parts
As each db table has PRIMARY KEY limits, uniqueness is handled by MySQL server | 625941f56aa9bd52df0373ef |
@app.route("/catalog/category/<category>") <NEW_LINE> def catalog_by_category(category): <NEW_LINE> <INDENT> part_query = db_session.query(Part, Supplier).join(Supplier) <NEW_LINE> if category == "other": <NEW_LINE> <INDENT> part_query = part_query.filter(~Part.categories.any()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | catalog page filtered by category name
| 625941f59b70327d1c4e141f |
def _get_host_metrics(self): <NEW_LINE> <INDENT> host_stats = {} <NEW_LINE> host_proc_map = {} <NEW_LINE> cmd = [self.CMD_BASE] + sorted(self._get_host_metrics_opts()) <NEW_LINE> for host in self.hosts: <NEW_LINE> <INDENT> if is_remote_host(host): <NEW_LINE> <INDENT> host_proc_map[host] = remote_cylc_cmd( cmd, stdin=No... | Run "cylc get-host-metrics" commands on hosts.
Return (dict): {host: host-metrics-dict, ...} | 625941f54527f215b584ca98 |
def test_untrack_view(self): <NEW_LINE> <INDENT> project = mommy.make(Project, name='project 1', slug='project-1', is_active=True) <NEW_LINE> project.add_user(self.user, 'viewer') <NEW_LINE> ProjectTracking.objects.get_or_create(project=project, user=self.user) <NEW_LINE> self.assertTrue(project in self.user.get_projec... | Test tracking of a project using the API. | 625941f53317a56b8693a28f |
def at(self, i): <NEW_LINE> <INDENT> return str() | str QByteArray.at(int i) | 625941f5eab8aa0e5d26e1a2 |
def test_idx_no_diagonal(self): <NEW_LINE> <INDENT> n = 4 <NEW_LINE> for x,y,i in NO_DIAG: <NEW_LINE> <INDENT> self.assertEqual(sym_idx(x,y,n,with_diagonal=False), i) | Verify index values for 4x4 matrix without diagonal. | 625941f53cc13d1c6d3c79be |
def get_pred_label(prediction_probabilities): <NEW_LINE> <INDENT> return unique_breeds[np.argmax(prediction_probabilities)] | turns an array of prediction probabilities into a label | 625941f5be383301e01b5ac0 |
def get_polyhedron(struc,maxr,siteindex): <NEW_LINE> <INDENT> site = struc.sites[siteindex] <NEW_LINE> poly = struc.get_neighbors(site,maxr) <NEW_LINE> cn = len(poly) <NEW_LINE> if (cn <= 2): <NEW_LINE> <INDENT> print("You didn't choose a polyhedron! CN <= 2") <NEW_LINE> return None <NEW_LINE> <DEDENT> return poly, cn | Finding a particular polyhedra surrounding spec1 for some distance maxr
set maxr to just slightly above nn distance
Input
struc = structure read from pymatgen
maxr = radius of search; in ang.
siteindex = string; chemical name of species of interest
Output
poly = list of sites corresponding to polyhedra
... | 625941f54e4d5625662d4a15 |
def assign(self, **kwargs): <NEW_LINE> <INDENT> kvs = list(toolz.concat(kwargs.items())) <NEW_LINE> def _assign(df, *kvs): <NEW_LINE> <INDENT> keys = kvs[::2] <NEW_LINE> values = kvs[1::2] <NEW_LINE> kwargs = OrderedDict(zip(keys, values)) <NEW_LINE> return df.assign(**kwargs) <NEW_LINE> <DEDENT> return self.map_partit... | Assign new columns to this dataframe
Alternatively use setitem syntax
Examples
--------
>>> sdf = sdf.assign(z=sdf.x + sdf.y) # doctest: +SKIP
>>> sdf['z'] = sdf.x + sdf.y # doctest: +SKIP | 625941f5d486a94d0b98e78e |
def toUTCSeconds(date): <NEW_LINE> <INDENT> return (datetime.strptime(date, '%c') - datetime.fromtimestamp(0)).total_seconds() | Converts a local-specific datetime string to an epoch
timestamp (seconds since January 1, 1970) | 625941f5627d3e7fe0d69499 |
def create_historical_dividends_csv_link(stockTicker) : <NEW_LINE> <INDENT> csvLink = "https://companyresearch-nzx-com.ezproxy.aut.ac.nz/deep_ar/divhistory_csv.php?selection=" + stockTicker <NEW_LINE> logger.info("Pulling historical dividend data from: " + csvLink) <NEW_LINE> return csvLink | Creates a csv link used to download the historical dividends csv. Using todays date, and 3 years prior
Args:
stockTicker (String): Contains the ticker of the company
Returns:
csvLink (String): url which holds the csv | 625941f5d18da76e23532b26 |
def consume_subdict(emitter, key, dct, *args, **kwargs): <NEW_LINE> <INDENT> rest = dict(dct) <NEW_LINE> obj, subrest = consume_config(emitter, rest.pop(key, {}), *args, **kwargs) <NEW_LINE> if subrest: <NEW_LINE> <INDENT> rest[key] = subrest <NEW_LINE> <DEDENT> return obj, rest | Return ``emitter(*args, **dct[key], **kwargs)`` with unused part of `dct`.
The sub-dictionary ``dct[key]`` may not exist (assumed be an empty
dictionary if so) and it is removed if all contents in
``dct[key]`` are consumed. Thus, it is safe to call this function
with the same `key` and different `emitter` multiple ti... | 625941f545492302aab5e911 |
@app.route('/', methods=['GET']) <NEW_LINE> def index() -> str: <NEW_LINE> <INDENT> return render_template("layout.html") | Root page of the api. Something will go here sometime.
Returns:
The front page with basic about and help information/ | 625941f53539df3088e2e993 |
def softmax_loss_naive(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> num_train = X.shape[0] <NEW_LINE> num_class = W.shape[1] <NEW_LINE> for i in range(num_train): <NEW_LINE> <INDENT> scores = X[i].dot(W) <NEW_LINE> scores = np.exp(scores - np.max(scores)) <NEW_LINE> loss += ... | Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) contain... | 625941f5283ffb24f3c55f41 |
def __iter__(self): <NEW_LINE> <INDENT> return self | Allows iterating over all the playlists. | 625941f5a17c0f6771cbe696 |
def recalculate_single_worm_control_points(all_labels, ncontrolpoints): <NEW_LINE> <INDENT> all_object_numbers = [ list(filter((lambda n: n > 0), numpy.unique(l))) for l in all_labels ] <NEW_LINE> if all([len(object_numbers) == 0 for object_numbers in all_object_numbers]): <NEW_LINE> <INDENT> return numpy.zeros((0, nco... | Recalculate the control points for labeled single worms
Given a labeling of single worms, recalculate the control points
for those worms.
all_labels - a sequence of label matrices
ncontrolpoints - the # of desired control points
returns a two tuple:
an N x M x 2 array where the first index is the object number,
th... | 625941f51b99ca400220b0fc |
def generate_training(self, path): <NEW_LINE> <INDENT> with open(path, 'rU') as fh: <NEW_LINE> <INDENT> db = csv.DictReader(fh, delimiter='\t') <NEW_LINE> <DEDENT> with open('data/training.txt', 'wb') as fh: <NEW_LINE> <INDENT> fieldnames = ['url', 'label'] + utilities.features <NEW_LINE> writer = csv.DictWriter(fh, fi... | Generate training data from a list of labeled articles. | 625941f5d99f1b3c44c67bca |
def draw(self): <NEW_LINE> <INDENT> self.background.clear() <NEW_LINE> self.foreground.clear() <NEW_LINE> self._maze_table.draw() <NEW_LINE> return None | Re-draw element at current position
return: None | 625941f5435de62698dfe295 |
def __init__(self, vec): <NEW_LINE> <INDENT> super(Vector, self).__init__(vec) <NEW_LINE> self.vec = vec <NEW_LINE> self._x = vec[0] <NEW_LINE> self._y = vec[1] | :param vec: list | 625941f57047854f462a1a4a |
def process_t(self, words): <NEW_LINE> <INDENT> pro_words = [] <NEW_LINE> index = 0 <NEW_LINE> temp = u'' <NEW_LINE> while True: <NEW_LINE> <INDENT> word = words[index] if index < len(words) else u'' <NEW_LINE> if u'/t' in word: <NEW_LINE> <INDENT> temp = temp.replace(u'/t', u'') + word <NEW_LINE> <DEDENT> elif temp: <... | 处理时间,合并语料库分开标注的时间词,类似: (/w 一九九七年/t 十二月/t 三十一日/t )/w | 625941f5b830903b967e9f4b |
@dispatch.receiver(django_signals.post_save, sender=SSID) <NEW_LINE> def ssid_updated(sender, instance, **kwargs): <NEW_LINE> <INDENT> if instance.default: <NEW_LINE> <INDENT> SSID.objects.exclude(pk=instance.pk).filter( project=instance.project, default=True, ).update(default=False) | Ensure that only one SSID inside a project is selected as default. | 625941f5462c4b4f79d1dd17 |
def get_indexes(self, connection, table_name, schema=None, **kw): <NEW_LINE> <INDENT> raise NotImplementedError() | Return information about indexes in `table_name`.
Given a :class:`.Connection`, a string
`table_name` and an optional string `schema`, return index
information as a list of dictionaries with these keys:
name
the index's name
column_names
list of column names in orders
unique
boolean | 625941f55fdd1c0f98dc087d |
def calendar_return(dataframe, index_name, start_year, end_year, interval): <NEW_LINE> <INDENT> Calendar_Return_df = pd.DataFrame(index = index_name) <NEW_LINE> for i in range(start_year, end_year+1, interval): <NEW_LINE> <INDENT> for j in index_name: <NEW_LINE> <INDENT> Calendar_Return_df.loc[j,i] = np.prod(dataframe[... | Calculate the calendar return across all calendar years
2007 has last six months data, they calendar return for 2007 is the last six month cumulative return.
Args:
dataframe is the dataframe passed by concat_data() function
index_name is the index we want to calculate, must be consistent with index name in th... | 625941f515baa723493c45c2 |
def _get_package_url(self, data): <NEW_LINE> <INDENT> return urljoin( self.site_url, toolkit.url_for( controller='package', action='read', id=data['name'] ) ) | Returns the full URL (HTML page) of the package. | 625941f5099cdd3c635f129f |
def clip_grad_value_(parameters, clip_value): <NEW_LINE> <INDENT> clip_value = float(clip_value) <NEW_LINE> for p in filter(lambda p: p.grad is not None, parameters): <NEW_LINE> <INDENT> p.grad.data.clamp_(min=-clip_value, max=clip_value) | Clips gradient of an iterable of parameters at specified value.
Gradients are modified in-place.
Arguments:
parameters (Iterable[Tensor]): an iterable of Tensors that will have
gradients normalized
clip_value (float or int): maximum allowed value of the gradients
The gradients are clipped in t... | 625941f5627d3e7fe0d6949a |
def job_merge_task(config, conf): <NEW_LINE> <INDENT> if 'autogenerated_task_id' in conf: <NEW_LINE> <INDENT> prefix, padding = autogenerated_task_id_settings(conf, level='job') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix, padding = autogenerated_task_id_settings( config, level='global') <NEW_LINE> <DEDENT> _t... | Gets merge task
:param dict config: configuration object
:param dict conf: job configuration object
:rtype: dict
:return: merge task | 625941f5a8ecb033257d3712 |
def __init__(self,*args,**kwargs): <NEW_LINE> <INDENT> super(MoveForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['forum2'].choices=[(forum.id, forum.name) for forum in Forum.objects.order_by("name")] | This is for collecting forums | 625941f54f6381625f115082 |
def setup_platform(hass, config, add_entities, discovery_info=None): <NEW_LINE> <INDENT> i2c_address = config.get(CONF_I2C_ADDRESS) <NEW_LINE> sensor = SHT31(address=i2c_address) <NEW_LINE> try: <NEW_LINE> <INDENT> if sensor.read_status() is None: <NEW_LINE> <INDENT> raise ValueError("CRC error while reading SHT31 stat... | Set up the sensor platform. | 625941f58a43f66fc4b546a5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.