code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _hash(self, string, M): <NEW_LINE> <INDENT> h = 0 <NEW_LINE> for i in range(M): <NEW_LINE> <INDENT> h = (self.R * h + ord(string[i])) % self.prime <NEW_LINE> <DEDENT> return h
Computing the hash code for the first M characters of the string.
625941ee01c39578d7e7537f
def lock(self): <NEW_LINE> <INDENT> return _AriaPy.ArVersalogicIO_lock(self)
lock(self) -> int
625941ee7d43ff24873a31e8
def feed_ohlcv(self, ex_ohlcvs, start, end): <NEW_LINE> <INDENT> last = self.last_ohlcv <NEW_LINE> for ex, syms in ex_ohlcvs.items(): <NEW_LINE> <INDENT> for sym, tfs in syms.items(): <NEW_LINE> <INDENT> for tf, ohlcv in tfs.items(): <NEW_LINE> <INDENT> if len(ohlcv) > 0: <NEW_LINE> <INDENT> tmp = ohlcv[start:end] <NEW...
Append new ohlcvs to data feed. Param ex_ohlcvs: contain 3 levels, exchange > symbol > timeframe { 'bitfinex': { # ex 'BTC/USD': { # tf '1m': DataFrame(...), # sym, ohlcv '5m': DataFrame(...), } ...
625941ee76d4e153a657f077
def move_file(self, dest_proj, file_id): <NEW_LINE> <INDENT> self._log.info('Moving file %s to project %s', file_id, dest_proj['_id']) <NEW_LINE> pillar.api.file_storage.moving.move_to_bucket(file_id, dest_proj['_id'], skip_storage=self.skip_gcs)
Moves a single file to another project
625941ee046cf37aa974d286
def delete_command_group(self, group_name): <NEW_LINE> <INDENT> raise NotImplementedError
Delete command group :param str group_name: Command name :return: Deleted group of commands :raises: OSError, SmmDBKeyError
625941ee4f88993c3716c5a5
def getbalance(self, ctx, user, *flags): <NEW_LINE> <INDENT> server = ctx.guild.id <NEW_LINE> try: <NEW_LINE> <INDENT> if 'int' in flags: <NEW_LINE> <INDENT> balance = int(self.data[server][user][-1][2]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> amount = str(self.data[server][user][-1][2]) <NEW_LINE> if 'prefix' in...
Returns current balance for user Flags: 'int' - returns balance as integer
625941ee5fcc89381b1e1c07
def poll(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> alarm = self._alarms[-1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> due = alarm.time <NEW_LINE> <DEDENT> return max(0, due - now())
Compute the number of seconds until the next alarm comes due. If there are no scheduled alarms, {poll} returns {None}; if alarms are overdue, it returns 0. This slightly strange logic is designed to satisfy the requirements for calling {select}.
625941ee82261d6c526ab9eb
def __init__(self, vehicleNo: int): <NEW_LINE> <INDENT> self.vehicleNo = vehicleNo <NEW_LINE> self.isAvailable = True
Creates a vehicle on which an order will be transfered. >>> vehicle = Vehicle(1) >>> vehicle.vehicleNo 1
625941ee82261d6c526ab9ec
def test_integer(self): <NEW_LINE> <INDENT> result = self.integer_decorator.process_result_value(0, self.dialect) <NEW_LINE> self.assertEqual(result, 0)
Integer should be returned as it is.
625941ee4e4d5625662d4914
def resnet18_v1(**kwargs): <NEW_LINE> <INDENT> return get_resnet(1, 18, **kwargs)
ResNet-18 V1 model from `"Deep Residual Learning for Image Recognition" <http://arxiv.org/abs/1512.03385>`_ paper. Parameters ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, ...
625941ee8c0ade5d55d3ef04
def update(self): <NEW_LINE> <INDENT> self._state = STATE_UNKNOWN <NEW_LINE> for entity_id in self.tracking: <NEW_LINE> <INDENT> state = self.hass.states.get(entity_id) <NEW_LINE> if state is not None: <NEW_LINE> <INDENT> self._process_tracked_state(state)
Query all the tracked states and determine current group state.
625941ee097d151d1a22339a
def SaveConfig(self): <NEW_LINE> <INDENT> config_value = getattr(self, APPDATA) <NEW_LINE> path_value = config_value.AbsolutePaths[0] <NEW_LINE> default_cfg_file = os.path.join(path_value, CONFIG_FILE_NAME) <NEW_LINE> temp_file = default_cfg_file + '.TEMP' <NEW_LINE> if os.path.exists(default_cfg_file): <NEW_LINE> <IND...
Save the current configuration state. :return:
625941ee94891a1f4081bff0
def stop(self): <NEW_LINE> <INDENT> logger.info("Stopping") <NEW_LINE> self._stopping = True <NEW_LINE> self.close_channel() <NEW_LINE> self.close_connection()
Close the RabbitMQ channel and connection
625941ee67a9b606de4a83fb
def sim(): <NEW_LINE> <INDENT> global count <NEW_LINE> count = count + 1 <NEW_LINE> clear_tiles() <NEW_LINE> start_time = time.time() <NEW_LINE> simulate() <NEW_LINE> elapsed_time = time.time() - start_time <NEW_LINE> print('sim', count, 'time:', elapsed_time) <NEW_LINE> if count == config.STOP_AT: <NEW_LINE> <INDENT> ...
Performs a new simulation
625941ee63d6d428bbe44a35
def match_truth_to_target(truth, targets): <NEW_LINE> <INDENT> target_found = False <NEW_LINE> for target in targets: <NEW_LINE> <INDENT> if truth["code"] in target["codes"]: <NEW_LINE> <INDENT> truth["scientific_name"] = target["scientific_name"] <NEW_LINE> truth["common_name"] = target["common_name"] <NEW_LINE> truth...
Augment the truth with scientific name, color code, etc.
625941ee99cbb53fe6793129
def pc_work_time(self): <NEW_LINE> <INDENT> return _blocks_swig5.sample_and_hold_ff_sptr_pc_work_time(self)
pc_work_time(sample_and_hold_ff_sptr self) -> float
625941eeab23a570cc2506cb
def broadcast_transaction(self, signed_transaction: SignedTransaction): <NEW_LINE> <INDENT> return self.call('broadcast_transaction', signed_transaction, api=NETWORK_BROADCAST_API)
broadcast_transaction
625941ee21a7993f00bc823e
def _check_encryptable(key): <NEW_LINE> <INDENT> meaning, trustvalue = GPG_TRUSTLEVELS[key[u"trustletter"]] <NEW_LINE> if not trustvalue: <NEW_LINE> <INDENT> return u"La confiance en la clé est : %s" % (meaning,) <NEW_LINE> <DEDENT> if u"e" in key[u"capabilities"]: <NEW_LINE> <INDENT> return u"" <NEW_LINE> <DEDENT> esu...
Vérifie qu'on peut chiffrer un message pour ``key``. C'est-à-dire, que la clé est de confiance (et non expirée). Puis qu'on peut chiffrer avec, ou qu'au moins une de ses subkeys est de chiffrement (capability e) et est de confiance et n'est pas expirée
625941ee283ffb24f3c55e40
def delete_scrapers_id_labels_id(self, scraper_target_id, label_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.delete_scrapers_id_labels_id_with_http_info(scraper_target_id, label_id, **kwargs) <NEW_LINE> <DEDENT> else: <...
Delete a label from a scraper target # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_scrapers_id_labels_id(scraper_target_id, label_id, async_req=True) >>> result = thread.get() :param async_req bool :param...
625941eecb5e8a47e48b7fe6
def profile(name='stats', _stats=stats): <NEW_LINE> <INDENT> def _profile(function): <NEW_LINE> <INDENT> def __profile(*args, **kw): <NEW_LINE> <INDENT> start_time = timer() <NEW_LINE> start_memory = _get_memory_usage() <NEW_LINE> try: <NEW_LINE> <INDENT> return function(*args, **kw) <NEW_LINE> <DEDENT> finally: <NEW_L...
Calculates a duration (wall clock time, not the CPU time) and a memory size.
625941ee442bda511e8be955
def _merge_event_ref_list(self, acquisition): <NEW_LINE> <INDENT> eventref_list = self.event_ref_list[:] <NEW_LINE> for addendum in acquisition.get_event_ref_list(): <NEW_LINE> <INDENT> for eventref in eventref_list: <NEW_LINE> <INDENT> equi = eventref.is_equivalent(addendum) <NEW_LINE> if equi == IDENTICAL: <NEW_LINE>...
Merge the list of event references from acquisition with our own. :param acquisition: the event references list of this object will be merged with the current event references list. :type acquisition: Person
625941ee498bea3a759b9ff2
def test_btn_flag(self): <NEW_LINE> <INDENT> self.assertTrue(self.widget.enable_btn)
By default, self.enable_btn should be True.
625941ee1f037a2d8b946741
def test_transform_os_release_when_non_rhel_os(self): <NEW_LINE> <INDENT> host = {'system_profile': {'os_release': 'openSUSE Leap 15.3'}} <NEW_LINE> host = self.processor._transform_single_host( self.report_record.request_id, '123', host ) <NEW_LINE> self.assertEqual(host, {'system_profile': {'os_release': '15.3'}})
Test transform host os_release when non rhel.
625941eea8370b7717052de2
def train_step(self, summary=False, session=None): <NEW_LINE> <INDENT> if session is None: <NEW_LINE> <INDENT> session = self.session <NEW_LINE> <DEDENT> for _ in range(5): <NEW_LINE> <INDENT> session.run(self.trainer_d) <NEW_LINE> <DEDENT> if summary: <NEW_LINE> <INDENT> _, smry, step, res = session.run([self.trainer_...
Do a training step
625941ee7b25080760e3999a
def classify(train, test, k=30, metric='euclidean', n_jobs=-1): <NEW_LINE> <INDENT> data, labels = preprocess(train, test) <NEW_LINE> A = create_graph(data, k, metric=metric, n_jobs=n_jobs) <NEW_LINE> P = random_walk_probabilities(A, labels) <NEW_LINE> c = np.argmax(P, axis=1) <NEW_LINE> return c, P
Semi-supervised classification by random walks on a graph :param train: list of numpy arrays. Each array has a row for each class observation :param test: numpy array of unclassified data :return c: class assignment for each row in test :return P: class probabilities for each row in test
625941ee5166f23b2e1a569d
def test_print_characters(): <NEW_LINE> <INDENT> print() <NEW_LINE> print('------------------------------------------') <NEW_LINE> print('Testing the PRINT_CHARACTERS function:') <NEW_LINE> print('------------------------------------------') <NEW_LINE> cha = print_characters(['hi', 'bye', 'a tie!']) <NEW_LINE> prin...
Tests the print_characters function.
625941ee01c39578d7e75380
def download_dxfile(dxid, filename, chunksize=DEFAULT_BUFFER_SIZE, append=False, show_progress=False, project=None, **kwargs): <NEW_LINE> <INDENT> def print_progress(bytes_downloaded, file_size): <NEW_LINE> <INDENT> num_ticks = 60 <NEW_LINE> effective_file_size = file_size or 1 <NEW_LINE> if bytes_downloaded > effectiv...
:param dxid: Remote file ID :type dxid: string :param filename: Local filename :type filename: string :param append: If True, appends to the local file (default is to truncate local file if it exists) :type append: boolean Downloads the remote file with object ID *dxid* and saves it to *filename*. Example:: down...
625941ee56b00c62f0f14ba1
def do_RandomForestRegressor_max_features(*data): <NEW_LINE> <INDENT> X_train,X_test,y_train,y_test=data <NEW_LINE> max_features=np.linspace(0.01,1.0) <NEW_LINE> fig=plt.figure() <NEW_LINE> ax=fig.add_subplot(1,1,1) <NEW_LINE> testing_scores=[] <NEW_LINE> training_scores=[] <NEW_LINE> for max_feature in max_features: <...
测试 RandomForestRegressor 的预测性能随 max_features 参数的影响 :param data: 可变参数。它是一个元组,这里要求其元素依次为:训练样本集、测试样本集、训练样本的值、测试样本的值 :return: None
625941eed4950a0f3b08c88b
def pretty_timedelta(time1, time2=None, resolution=None): <NEW_LINE> <INDENT> time1 = to_datetime(time1) <NEW_LINE> time2 = to_datetime(time2) <NEW_LINE> if time1 > time2: <NEW_LINE> <INDENT> time2, time1 = time1, time2 <NEW_LINE> <DEDENT> diff = time2 - time1 <NEW_LINE> age_s = int(diff.days * 86400 + diff.seconds) <N...
Calculate time delta between two `datetime` objects. (the result is somewhat imprecise, only use for prettyprinting). If either `time1` or `time2` is None, the current time will be used instead.
625941ee57b8e32f524839e3
def setYAxisLogarithmic(self, flag): <NEW_LINE> <INDENT> self._yAxis._setLogarithmic(flag)
Set the Y axes scale (either linear or logarithmic). :param bool flag: True to use a logarithmic scale, False for linear.
625941ee4d74a7450ccd4709
def add(self,obj): <NEW_LINE> <INDENT> if isinstance(obj,list): <NEW_LINE> <INDENT> for item in obj: <NEW_LINE> <INDENT> self.add(item) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(obj,Point): <NEW_LINE> <INDENT> self.points.append(obj) <NEW_LINE> <DEDENT> elif isinstance(obj,Task): <NEW_LINE> <INDENT> self.tasks.appen...
adds the Point or Task object to their specified list
625941ee4c3428357757c869
def get_fof_script_path(run): <NEW_LINE> <INDENT> script_dir=get_script_dir(run) <NEW_LINE> fname = '%s-make-fofs.sh' % run <NEW_LINE> return os.path.join( script_dir, fname, )
directory for scripts
625941eed8ef3951e3243a82
def gradient_descent(f, grad_f, x_init, eps = 0.001, max_iterations = 1000, alpha = 0.001): <NEW_LINE> <INDENT> x = x_init <NEW_LINE> k = 1 <NEW_LINE> f_next = f(x) <NEW_LINE> while k <= max_iterations: <NEW_LINE> <INDENT> f_eval = f_next <NEW_LINE> if(isinstance(x, list)): <NEW_LINE> <INDENT> x[:] = [var - alpha * gra...
Returns the minimum of x through gradient descent. Works in any number of variables.
625941ee85dfad0860c3b3a1
def test_join_entity_from_multiple_from_clause(self): <NEW_LINE> <INDENT> User, Order, Address, Dingaling = ( self.classes.User, self.classes.Order, self.classes.Address, self.classes.Dingaling, ) <NEW_LINE> sess = fixture_session() <NEW_LINE> q = sess.query(Address, User).join(Address.dingaling).join(User.orders) <NEW...
test adding joins onto multiple FROM clauses where it is ambiguous which FROM should be used
625941ee66656f66f7cbc6f2
def construct_bom(self, summary_table, dependencies): <NEW_LINE> <INDENT> repositories = self.source_code_manager.source_repositories <NEW_LINE> default_source_prefix = self.determine_most_common_prefix( repositories, summary_table) <NEW_LINE> services = self.make_bom_services_spec( repositories, summary_table, default...
Create a BOM specification. Args: summary_table: [dict] The {<name>: <RepositorySummary>} to include. dependencies: [dict] Inject as the 'Dependencies' section of the BOM.
625941eebf627c535bc13714
def _impersonate_mechanism(self, user, sudo_rules, users_chain=[], already_impersonated=[]): <NEW_LINE> <INDENT> for u in self._get_user_to_impersonate(sudo_rules): <NEW_LINE> <INDENT> if u not in already_impersonated: <NEW_LINE> <INDENT> sudo_list = self._impersonate_user(users_chain=[user, u]) <NEW_LINE> if sudo_list...
Recursive function to retrieve all sudo rules All rules for all possible users are stored on "all_rules"
625941ee851cf427c661aa4f
def run(self): <NEW_LINE> <INDENT> VTLOG.info("Client running!") <NEW_LINE> VTLOG.info("XMLRPC Server at " + self.conf['ip'] + ':' + self.conf['port']) <NEW_LINE> VTLOG.info("Evaluating: " + self.conf['video'] + " + " + self.conf['codec'] + " at " + self.conf['bitrate'] + " kbps and " + self.conf['framerate'] + " fps u...
Run the client and perform all the operations: * Connect to the server. * Receive video while sniffing packets. * Close connection. * Process data and extract information. * Run meters. :returns: A list of measures (see :attr:`VideoTester.measures.core.Meter.measures`) and the path to the temporary directory plus...
625941ee596a897236089ffd
def test_remove_bin_with_no_parameters(self): <NEW_LINE> <INDENT> with pytest.raises(TypeError) as typeError: <NEW_LINE> <INDENT> TestRemovebin.client.remove_bin() <NEW_LINE> <DEDENT> assert "Required argument 'key' (pos 1) not found" in str( typeError.value)
Invoke remove_bin() without any mandatory parameters.
625941ee2ae34c7f2600d675
def test_constructor_last_count_update_time(self): <NEW_LINE> <INDENT> args = { "clientId": "What.Ever.Dude", "sharedSecret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" } <NEW_LINE> cut = ClientData(**args) <NEW_LINE> expected = datetime( 1, 1, 1, 0, 0, 0, 0, self.__utz).strftime(self.isoFmt) <NEW_LINE> if expected[0:3] != "00...
Test for __init__(). Happy path last_count_update_time.
625941ee287bf620b61d3fa5
def iv_motion(self, iconview, event): <NEW_LINE> <INDENT> if self.pressed_button: <NEW_LINE> <INDENT> if iconview.drag_check_threshold(self.pressed_button.x, self.pressed_button.y, event.x, event.y): <NEW_LINE> <INDENT> iconview.drag_begin_with_coordinates(Gtk.TargetList.new(self.TARGETS_IV), Gdk.DragAction.COPY | Gdk....
Manages mouse movement on the iconview to detect drag and drop events
625941ee596a897236089ffe
def enable_ingestion_pipeline(self, ingestion_pipeline): <NEW_LINE> <INDENT> self.ingestion_pipeline = ingestion_pipeline
:param ingestion_pipeline: :return:
625941ee460517430c3946bb
def show_user(self, user_id, deleted=False): <NEW_LINE> <INDENT> return Client._get(self, id=user_id, deleted=deleted)
Display information about a user. If ``deleted`` is set to ``True``, display information about a deleted user. :type user_id: str :param user_id: User ID to inspect :type deleted: bool :param deleted: Whether to return results for a deleted user :rtype: dict :return: dictionary containing information about the user
625941eee5267d203edce1db
def __init__(self, file, validate=0,subfontIndex=0): <NEW_LINE> <INDENT> self.validate = validate <NEW_LINE> self.readFile(file) <NEW_LINE> self._filename = getattr(file,'name','') <NEW_LINE> if self._filename.startswith('<'): <NEW_LINE> <INDENT> self._filename = '' <NEW_LINE> <DEDENT> isCollection = self.readHeader() ...
Loads and parses a TrueType font file. file can be a filename or a file object. If validate is set to a false values, skips checksum validation. This can save time, especially if the font is large.
625941ee0c0af96317bb872c
def extension_from_path(path_name): <NEW_LINE> <INDENT> return os.path.splitext(os.path.basename(path_name))[1]
Returns an extension from a pathname. Args: path_name (str): The path including filename. Returns: The extension of a path. (str).
625941eebe383301e01b59c0
def escribe_valores_dia(dia, temps, fichero): <NEW_LINE> <INDENT> dia = f"{dia[8:]}-{dia[5:7]}-{dia[0:4]}" <NEW_LINE> temp_med = sum(temps['temp']) / len(temps['temp']) <NEW_LINE> temp_min = min(temps['temp_min']) <NEW_LINE> temp_max = max(temps['temp_max']) <NEW_LINE> if fichero: <NEW_LINE> <INDENT> fichero.write(fila...
Escribirá la temperatura media, mínima y máxima del día que hemos pasado como parámetro y el número de mediciones. :param fichero: manejador de fichero donde se escribe el html. None si la salida es por pantalla. :param dia: día en el que se han tomado los valores de la temperatura. :param temps: mediciones del día. :p...
625941ee71ff763f4b549bda
def __init__(self, num_layers, mlp_layers, hidden_dim, num_classes, dropout_rate, learn_eps, sparse, **kwargs): <NEW_LINE> <INDENT> super(GIN, self).__init__(**kwargs) <NEW_LINE> self.num_layers = num_layers <NEW_LINE> self.mlp_layers = mlp_layers <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.num_classes = nu...
Initializes a GIN model. Args: num_layers: (int) Number of gnn layers mlp_layers: (int) Number of mlp layers in GIN hidden_dim: (list) List of hidden layers dimension num_classes: (int) Total number of classes dropout_rate: (float) Dropout probability learn_eps: (bool) Whether to learn the epsilon weightin...
625941eed53ae8145f87a7aa
def put(self, request): <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> for i in request.data['todos']: <NEW_LINE> <INDENT> frame = Todos.objects.get(id=i['id']) <NEW_LINE> frame.title = str(i.get('title')) if i.get('title', None) is not None else frame.title <NEW_LINE> frame.done = i.get('done') if ...
updates board name by id id : board pk title : new name of board :param request: :return: all boards
625941eee8904600ed9f247b
def get_param(self, param, failobj=None, header='content-type', unquote=True): <NEW_LINE> <INDENT> if header not in self: <NEW_LINE> <INDENT> return failobj <NEW_LINE> <DEDENT> for k, v in self._get_params_preserve(failobj, header): <NEW_LINE> <INDENT> if k.lower() == param.lower(): <NEW_LINE> <INDENT> if unquote: <NEW...
Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The r...
625941eeec188e330fd5acd9
def close(self): <NEW_LINE> <INDENT> if self.con and not self._isclosed: <NEW_LINE> <INDENT> self.con.commit() <NEW_LINE> self.con.close() <NEW_LINE> self._isclosed = True
:references: :[1]: Exercise1, forum.database.py Closes the database connection, commiting all changes.
625941ee6fb2d068a760f5eb
def loss(self, y_true: tf.Tensor, y_pred: tf.Tensor) -> tf.Tensor: <NEW_LINE> <INDENT> loss_value = tf.abs(y_pred - y_true) <NEW_LINE> return loss_value
Calculate model loss Args: y_true: Experimentally measured variables y_pred: Predicted future variables Returns: tensor: Tensor object with mean absolute error loss
625941ee3317a56b8693a190
def install(self): <NEW_LINE> <INDENT> logger = logging.getLogger(self.name) <NEW_LINE> options = self.options <NEW_LINE> parts = self.buildout['buildout']['parts-directory'] <NEW_LINE> name = 'buildout-node' <NEW_LINE> node_dir = os.path.join(parts, self.name) <NEW_LINE> if not os.path.isdir(node_dir): <NEW_LINE> <IND...
Installer
625941ee10dbd63aa1bd30e7
def _create_cli_paragraph(self, feature): <NEW_LINE> <INDENT> para = nodes.paragraph() <NEW_LINE> para.append(nodes.strong(text="CLI commands:")) <NEW_LINE> commands = nodes.bullet_list() <NEW_LINE> for c in feature.cli.split(";"): <NEW_LINE> <INDENT> cli_command = nodes.list_item() <NEW_LINE> cli_command += nodes.lite...
Create a paragraph which represents the CLI commands of the feature The paragraph will have a bullet list of CLI commands.
625941eed268445f265b53b4
def get_colours_from_webcam(): <NEW_LINE> <INDENT> img = get_image() <NEW_LINE> colours_counts = get_image_colours(img) <NEW_LINE> sorted_colours = sort_colours(colours_counts) <NEW_LINE> return colour_triples_to_component_lists(sorted_colours)
Open the webcam, get the colours, sort and return the vectors
625941ee6aa9bd52df0372ec
def create(self, imsi): <NEW_LINE> <INDENT> imsi = parse_imsi(imsi) <NEW_LINE> resp = self.sendrecv('subscriber create imsi %s' % imsi) <NEW_LINE> return self._parse_show(resp)
Create a subscriber with a given IMSI. BUGS: on x86 if a subscriber already exists, it will crash osmo-nitb.
625941ee8c3a873295158906
def groups(self): <NEW_LINE> <INDENT> return self._groups.values()
Return list of groups that sprite is a member.
625941ee23e79379d52eeaa2
def get_subarea_uid(self, subarea): <NEW_LINE> <INDENT> return self.subarea_uids.get(subarea, '')
获取某个区对于的uid
625941ee167d2b6e312190da
def change_sriov_adaptermode(self, ip, managedsystem_uuid, adapter_object, x_api_session): <NEW_LINE> <INDENT> super().__init__(ip, self.root, self.content_type, x_api_session) <NEW_LINE> directory = os.path.dirname(__file__) <NEW_LINE> adapter_id = adapter_object.AdapterID.value() <NEW_LINE> if adapter_object.AdapterM...
Changes the adapter mode from shared to dedicated and dedicated to shared Args: ip : ip address of HMC managedsystem_uuid : UUID of the Managedsystem adapter_object : object of SRIOV Adapter to change the mode x_api_session : session to be used
625941ee31939e2706e4d3a7
def delete(self, request, pk, format=None): <NEW_LINE> <INDENT> report = self.get_object(pk) <NEW_LINE> self.check_object_permissions(request, report) <NEW_LINE> report.delete() <NEW_LINE> return Response(status=status.HTTP_200_OK)
Method to delete a specific report Params ------- request: Object with request data and functions. pk: reference to report to be deleted Returns -------- success message upon deletion of said report errors, if any
625941eee1aae11d1e74a202
def iter_repository_handles(self): <NEW_LINE> <INDENT> return ifilter(self.include_repository, self.db.iter_repository_handles())
Return an iterator over database handles, one handle for each Repository in the database.
625941eefbf16365ca6f6715
def biomaj_show(options, config): <NEW_LINE> <INDENT> if not options.bank: <NEW_LINE> <INDENT> return (False, "Bank option is required") <NEW_LINE> <DEDENT> bank = Bank(options.bank, options=options, no_log=True) <NEW_LINE> results = [] <NEW_LINE> headers = ["Name", "Release", "Format(s)", "Type(s)", "Tag(s)", "File(s)...
show bank details
625941eede87d2750b8602de
def __init__(self, key, master, *args, **kwargs): <NEW_LINE> <INDENT> super(UserSlaveBroadcast, self).__init__(key, master=master, *args, **kwargs) <NEW_LINE> def register(list, instance): <NEW_LINE> <INDENT> self.broadcast((self.formatted('CHANNEL_NS'), self.formatted('CHANNEL_CODE_JOINED')), filter=self._join_criteri...
Instantiates a slave broadcast by specifying a master, and register/unregister list handlers.
625941ee6aa9bd52df0372ed
def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(PersonViewSet, self).retrieve(request, *args, **kwargs)
### RETRIEVE __Method__: GET __URL__: $LINK:person-detail:instance_pk$ __Response__: %(SERIALIZER)s __Example__: curl -H "Content-Type: application/json" $URL:person-detail:1$ # output {"id": 1, "username": "test", "email": "test@example.com"}
625941ee97e22403b379d4e1
def __init__( self, processor_0, name="bus", symmetries_json=None, embedding_json=None ): <NEW_LINE> <INDENT> super(DesignerPlatformBus, self).__init__( name, symmetries_json=symmetries_json, embedding_json=embedding_json ) <NEW_LINE> if not isinstance(processor_0, Processor): <NEW_LINE> <INDENT> processor_0 = instanti...
Initializes an example platform with four processing elements connected via an shared memory. :param processor_0: the processing element for the platform :type processor_0: Processor :param name: The name for the returned platform :type name: String
625941eea934411ee3751bda
def check_bounds_cartesian(f, x, y): <NEW_LINE> <INDENT> if (-0.5 <= x < 0.5) and (-0.5 <= y < 0.5): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Returns true if (x,y) is in the cartesian bounds of f, else returns false.
625941ee21a7993f00bc823f
def max_contrast(array): <NEW_LINE> <INDENT> array[array > 0] = 1 <NEW_LINE> array[array < 0] = -1 <NEW_LINE> return None
Sets all positive values to one and all negative values to -1. Needed for first pass lookup on word table. Args: array (numpy.ndarray): target array
625941ee55399d3f05588bfd
def reinit_data(self): <NEW_LINE> <INDENT> pass
Subclass update loopback information
625941ee7b25080760e3999b
def window(L, size): <NEW_LINE> <INDENT> assert not isinstance(L, int), 'Argument order swapped: window(L, size)' <NEW_LINE> if size < 1: <NEW_LINE> <INDENT> raise ValueError('size <= 0 disallowed.') <NEW_LINE> <DEDENT> for i in range(len(L) - (size-1)): <NEW_LINE> <INDENT> yield L[i:i+size]
list * size -> window iterable Returns a sliding 'window' through the list L of size size.
625941eea79ad161976cc68b
def test_bag_name(): <NEW_LINE> <INDENT> bag = Bag('foobag') <NEW_LINE> assert bag.name == 'foobag' <NEW_LINE> bag_repr = '%s' % bag <NEW_LINE> assert 'foobag:<tiddlyweb.model.bag.Bag' in bag_repr
Confirm the bag gets its name right.
625941eeb545ff76a891435b
def test_class(self): <NEW_LINE> <INDENT> assert self.cls.backend is None <NEW_LINE> assert self.cls.methods is None <NEW_LINE> assert self.cls.properties is None <NEW_LINE> assert self.cls.params is None <NEW_LINE> assert self.cls.params_minus_pk is None <NEW_LINE> assert self.cls.takes_params == tuple()
Test the `ipalib.frontend.Object` class.
625941eebd1bec0571d90b74
def init_code(cons): <NEW_LINE> <INDENT> param_list = [p.getFullCPlusPlusName() for p in cons.parameters] <NEW_LINE> min_params_list = param_list[:cons.minArgs] <NEW_LINE> max_params_list = param_list[cons.minArgs:] <NEW_LINE> min_params = ', '.join(min_params_list) <NEW_LINE> max_params = ', '.join(max_params_list) <N...
return the init<>() code for the given contructor
625941eeb5575c28eb68e54b
def send(self, by, locator, content): <NEW_LINE> <INDENT> return self.find(by, locator).send_keys(content)
定位元素,并输入内容 :param by: 定位方法 :param locator: 元素属性值 :param content: 输入的内容 :return: 定位元素,并输入内容
625941ee8c3a873295158907
def register_trialized_volumes_slice_by_slice(images, filtSize=1, regMethod='cpwr', **kwargs): <NEW_LINE> <INDENT> stackDims = images.shape <NEW_LINE> images_ser = images.reshape(-1, *images.shape[2:]) <NEW_LINE> images_ser = np.swapaxes(images_ser, 0, 1) <NEW_LINE> if len(kwargs) > 0: <NEW_LINE> <INDENT> reg = volt.Re...
Register image volumes slice-by-slice Parameters ---------- images: array, (nTrials, nTimePoints, nSlices, imgHeight, imgWidth) Image hyperstack to perform registration on. filtSize: scalar Gaussian filter size (sigma) for smoothing of images prior to registration. The smoothing is only done to compute regi...
625941eeb7558d58953c544e
def update_matrices(self): <NEW_LINE> <INDENT> self.a_mat = _get_rest_pose_compensation_matrix(self.src_pbone, self.trg_pbone) <NEW_LINE> self.b_mat = _get_bone_matrix(self.trg_bone)
Update static matrices. These change only if the rest poses or structure of one of the two rigs changes. Should be called when both rigs are in rest pose.
625941ee4f6381625f114f81
def user_passes_test(function=None, test_func=None, redirect_field_name=REDIRECT_FIELD_NAME, fail_url=None): <NEW_LINE> <INDENT> def decorator(view_func): <NEW_LINE> <INDENT> @wraps(view_func, assigned=available_attrs(view_func)) <NEW_LINE> def _wrapped_view(request, *args, **kwargs): <NEW_LINE> <INDENT> if test_func(r...
Similar to user_passes_test in django.contrib.auth except this one can be used like this: f = user_passes_test(f) Decorator for views that checks that the user passes the given test, redirecting to `fail_url` for failures. The test should be a callable that takes the user object and returns True if the user passe...
625941ee7cff6e4e81117ecb
def rotated(image, degrees): <NEW_LINE> <INDENT> height, width = image.shape[0:2] <NEW_LINE> rot = cv2.getRotationMatrix2D((width // 2, height // 2), degrees, 1.0) <NEW_LINE> return cv2.warpAffine(image, rot, (width, height))
Return a new image, rotated by specified amount, on a black background. Where new content needs to be shifted into the image, it will appear black. :image: An OpenCV image. :degrees: The degrees of the rotation about the centre. :returns: A new OpenCV image.
625941eead47b63b2c50a4c5
def __init__(self, name, type, x, y, tileX, tileY, width, height): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = type <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.realX = x <NEW_LINE> self.realY = y <NEW_LINE> self.tileX = tileX <NEW_LINE> self.tileY = tileY <NEW_LINE> self.width = width <N...
Constructor
625941ee07d97122c4178dde
def set_neighboring_tiles_to_wall(self, pos, tavern_map): <NEW_LINE> <INDENT> for tile in tavern_map.get_neighboring_for(pos): <NEW_LINE> <INDENT> if not tile.built: <NEW_LINE> <INDENT> tile.built = True <NEW_LINE> tile.wall = True
For each tiles around a built tile, make sure those are wall if they are not built and not wall already.
625941eeac7a0e7691ed4607
def set_login(self, loginname, password): <NEW_LINE> <INDENT> if password != self.password or loginname != self.loginname: <NEW_LINE> <INDENT> self.login_ts = 0 <NEW_LINE> self.valid = True <NEW_LINE> self.loginname = loginname <NEW_LINE> self.password = password <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Updates the loginname and password and returns true if anything changed.
625941ee3617ad0b5ed6843c
def test_str_method_returns_role_info(self): <NEW_LINE> <INDENT> role = VolunteerRole(name="test role", details="a", prerequisites="b", vacancies=5) <NEW_LINE> role.save() <NEW_LINE> self.assertTrue(role.__str__() == "test role - a - b (5 vacancies)")
Assert that VolunteerRole.__str__() method returns role info
625941ee9f2886367277adcf
def __init__(self, location): <NEW_LINE> <INDENT> self.location = location
Constructor.
625941ee01c39578d7e75381
def C(n, r) : <NEW_LINE> <INDENT> if r < 0 or r > n : <NEW_LINE> <INDENT> raise ValueError("Cannot choose {} items from {}".format(r, n)) <NEW_LINE> <DEDENT> return reduce(mul, range(n - r + 1, n + 1), 1) // reduce(mul, range(1, r + 1), 1)
Computes the number of combinations of n items taken r at a time.
625941ee046cf37aa974d288
def deacs_roll(data, func, n, n_rows_back=30): <NEW_LINE> <INDENT> groupby = data.groupby('JOBNUM') <NEW_LINE> return groupby.apply(func, n, n_rows_back) .reset_index(drop=True)
Groups on JOBNUM and for each deactivation looks back a maximum of n_rows_back and sums the number of pace-ins longer than n
625941ee379a373c97cfb08c
def next_fact(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for section in self.SECTIONS: <NEW_LINE> <INDENT> if section in self.session: <NEW_LINE> <INDENT> app.logger.debug('already searched {} for facts'.format(section)) <NEW_LINE> continue <NEW_LINE> <DEDENT> data = getattr(self, section)() <NEW_LINE> if data...
Get next fact
625941ee4428ac0f6e5bad3d
def check_attrs(self): <NEW_LINE> <INDENT> return [key for key in self.template if not key in self]
Returns a list of templated attributes that do not have values. Intended to be used as a check for completeness. Returns: A list of keys with empty values
625941ee50485f2cf553d2e2
def bar(self, width, color, pos, parent, name=None, hidden=False): <NEW_LINE> <INDENT> if parent in self.elements: <NEW_LINE> <INDENT> parent = self.elements[parent] <NEW_LINE> <DEDENT> max_width = int(width)//32 <NEW_LINE> geom=parent.attach_new_node('slider') <NEW_LINE> for x in range(max_width): <NEW_LINE> <INDENT> ...
Creates a horizontal progres/status bar (like a health bar)
625941ee442bda511e8be956
def SetItemNumber(self, *args): <NEW_LINE> <INDENT> return _btk.btkForcePlatformCollection_SetItemNumber(self, *args)
SetItemNumber(self, arg2) Sets the number of force platforms
625941ee8c0ade5d55d3ef05
def test_three_between_second_third(cp, share, cptime): <NEW_LINE> <INDENT> cp.newCheckpoint(share, cptime, {"from": accounts[0]}) <NEW_LINE> cp.newCheckpoint(share, cptime + 100, {"from": accounts[0]}) <NEW_LINE> cp.newCheckpoint(share, cptime + 200, {"from": accounts[0]}) <NEW_LINE> _sleep(210) <NEW_LINE> share.mint(...
three checkpoints - mint between second and third
625941ee91af0d3eaac9bf64
def isodate(second=None): <NEW_LINE> <INDENT> if not second: second = time.time() <NEW_LINE> return strftime('%Y-%m-%d', localtime(second))
Make a date string
625941ee507cdc57c630722e
def __del__(self): <NEW_LINE> <INDENT> print("Bye rectangle...")
destructs method
625941ee4f88993c3716c5a7
def zipf(a, size=None): <NEW_LINE> <INDENT> pass
zipf(a, size=None) Draw samples from a Zipf distribution. Samples are drawn from a Zipf distribution with specified parameter `a` > 1. The Zipf distribution (also known as the zeta distribution) is a continuous probability distribution that satisfies Zipf's law: the fr...
625941eedd821e528d63b6ea
def sortColors(self, nums): <NEW_LINE> <INDENT> nums.sort()
:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
625941ee07f4c71912b119cb
def get_price_paths(self, number_of_paths): <NEW_LINE> <INDENT> M = number_of_paths <NEW_LINE> price_paths = np.zeros((M, self.N + 1)) <NEW_LINE> bm_paths, fbm_paths = self.get_joint_paths(M) <NEW_LINE> vol_paths = np.sqrt(self.v0 * np.exp(self.eta * fbm_paths)) <NEW_LINE> price_paths[:, [0]] = self.S0 * np.ones((M, 1)...
Returns required number of stock price paths. :param number_of_paths: number of required samples from price paths :type number_of_paths: int
625941eeb830903b967e9e4b
def name(self): <NEW_LINE> <INDENT> output = struct.pack("!H", self.name_alg) <NEW_LINE> digest = hashes.Hash(self.name_alg._hash_alg(), backend=default_backend()) <NEW_LINE> digest.update(self.data) <NEW_LINE> output += digest.finalize() <NEW_LINE> return output
Computing Entity Names see: https://www.trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-1-Architecture-01.38.pdf section 16 Names Name ≔ nameAlg || HnameAlg (handle→nvPublicArea) where nameAlg algorithm used to compute Name HnameAlg hash using the nameAlg parameter in the NV Index location ...
625941ee4a966d76dd55155b
def getConfigSummary(self, job): <NEW_LINE> <INDENT> self.send_getConfigSummary(job) <NEW_LINE> return self.recv_getConfigSummary()
Fetches the configuration summary of active tasks for the specified job. Parameters: - job
625941ee10dbd63aa1bd30e8
def test_getmeanfeaturevalues(): <NEW_LINE> <INDENT> import efel <NEW_LINE> efel.reset() <NEW_LINE> stim_start = 500.0 <NEW_LINE> stim_end = 900.0 <NEW_LINE> time = efel.io.load_fragment('%s#col=1' % meanfrequency1_url) <NEW_LINE> voltage = efel.io.load_fragment('%s#col=2' % meanfrequency1_url) <NEW_LINE> trace = {} <N...
basic: Test getMeanFeatureValues
625941ee097d151d1a22339c
def _prepare_upload_headers(self, object_name, object_size, extra, meta_data, blob_type): <NEW_LINE> <INDENT> headers = {} <NEW_LINE> if blob_type is None: <NEW_LINE> <INDENT> blob_type = self.ex_blob_type <NEW_LINE> <DEDENT> headers['x-ms-blob-type'] = blob_type <NEW_LINE> self._update_metadata(headers, meta_data) <NE...
Prepare headers for uploading an object :param object_name: The full name of the object being updated :type object_name: ``str`` :param object_size: The size of the object. In case of PageBlobs, this indicates the maximum size the blob can grow to :type object_size: ``int`` :param extra: Extra control data for t...
625941ee6fece00bbac2dc8b
def __init__(self, num_clusters=64, dim=128, alpha=100.0, normalize_input=True): <NEW_LINE> <INDENT> super(NetVLAD, self).__init__() <NEW_LINE> self.num_clusters = num_clusters <NEW_LINE> self.dim = dim <NEW_LINE> self.alpha = alpha <NEW_LINE> self.normalize_input = normalize_input <NEW_LINE> self.conv = nn.Conv2d(dim,...
Args: num_clusters : int The number of clusters dim : int Dimension of descriptors alpha : float Parameter of initialization. Larger value is harder assignment. normalize_input : bool If true, descriptor-wise L2 normalization is applied to input.
625941eebf627c535bc13715
def delete_order_with_http_info(self, order_id, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'order_id' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['k...
Delete purchase order by ID # noqa: E501 For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = ...
625941ee99cbb53fe679312b
def test_FirstTimeLoadCase(self): <NEW_LINE> <INDENT> loading_date = "2021-01-13" <NEW_LINE> self.client.currentday_load_ammount = 0 <NEW_LINE> self.client.daily_accum_loads = 0 <NEW_LINE> self.client.init_new_day(loading_date) <NEW_LINE> self.assertEqual(self.client.last_load_date.day, 13) <NEW_LINE> self.assertEqual(...
Test case to evaluate the first time load.
625941ee1f5feb6acb0c5090
def break_machine(self, data): <NEW_LINE> <INDENT> yield self.env.timeout(time_to_failure()) <NEW_LINE> if not self.machine.broken: <NEW_LINE> <INDENT> self.machine.process.interrupt() <NEW_LINE> <DEDENT> return self.break_machine
Break the machine every now and then.
625941ee32920d7e50b2871b