code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _http_install_apk(pkg_restapi, apk_url): <NEW_LINE> <INDENT> resp = requests.post(pkg_restapi, data={"url": apk_url}).json() <NEW_LINE> if not resp.get('success'): <NEW_LINE> <INDENT> raise RuntimeError(resp.get('description')) <NEW_LINE> <DEDENT> id = resp['data']['id'] <NEW_LINE> logger.info("install id %s", id) ... | install apk from u2init | 625941dcf9cc0f698b1408e8 |
def chunks(l, n): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for i in range(0, len(l), n): <NEW_LINE> <INDENT> result.append(l[i:i + n]) <NEW_LINE> <DEDENT> return result | returns successive n-sized chunks from l. | 625941dc8e71fb1e9831da97 |
def getConfigLine(self, includeFingerprint=False, addressClass=None, request=None, transport=None): <NEW_LINE> <INDENT> bridgeRequest = bridgerequest.BridgeRequestBase(addressClass) <NEW_LINE> bridgeRequest.client = request if request else bridgeRequest.client <NEW_LINE> bridgeRequest.isValid(True) <NEW_LINE> if transp... | Get a vanilla bridge line for this ``Bridge``.
This method is provided for backwards compatibility and should not
be relied upon.
The old ``bridgedb.Bridges.Bridge.getConfigLine()`` method didn't know
about :class:`~bridgedb.bridgerequest.BridgeRequestBase`s, and so this
modified version is backwards compatible by cr... | 625941dc3317a56b86939f41 |
def events(calendar_id: str, start: datetime, end: datetime, **kwargs) -> List[dict]: <NEW_LINE> <INDENT> args = { 'calendarId': calendar_id, 'orderBy': 'startTime', 'singleEvents': 'true', 'timeMin': start.isoformat(), 'timeMax': end.isoformat(), } <NEW_LINE> args.update(kwargs) <NEW_LINE> service = creds.build_calend... | Events in a given calendar in a given time range, ordered by startTime
Args:
calendar_id: id of the calendar to query
start: start time for events
end: end time for events
**kwargs: other args passed to the Google cal API
Returns: | 625941dc4428ac0f6e5baae3 |
def get_host_and_device(): <NEW_LINE> <INDENT> ip_list=[] <NEW_LINE> idx=0 <NEW_LINE> try: <NEW_LINE> <INDENT> resp= get(api="host") <NEW_LINE> response_json = resp.json() <NEW_LINE> i=0 <NEW_LINE> if response_json["response"] !=[]: <NEW_LINE> <INDENT> for item in response_json["response"]: <NEW_LINE> <INDENT> i+=1 <NE... | This function returns a list of all hosts and network devices with a number tag.
Return:
------
list: a list of all hosts and network devices with a number tag | 625941dc283ffb24f3c55bed |
def a_hash(img) -> int: <NEW_LINE> <INDENT> img = cv2.resize(img, (8, 8)) <NEW_LINE> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <NEW_LINE> s = 0 <NEW_LINE> ahash = 0 <NEW_LINE> for i in range(8): <NEW_LINE> <INDENT> for j in range(8): <NEW_LINE> <INDENT> s = s+gray[i, j] <NEW_LINE> <DEDENT> <DEDENT> avg = s/64 <NEW_L... | 均值哈希算法 | 625941dc57b8e32f5248378c |
def test_createThing(self): <NEW_LINE> <INDENT> st = store.Store() <NEW_LINE> thing = imaginary_basic.thingPlugin.getType()(store=st, name=u"foo") <NEW_LINE> self.assertTrue(verifyObject(iimaginary.IThing, thing)) <NEW_LINE> self.assertIdentical(thing.store, st) <NEW_LINE> self.assertEqual(thing.name, u"foo") | L{plugins.thingPlugin} creates a L{Thing} with no additional behavior. | 625941dceab8aa0e5d26de48 |
def create_fork(self, owner, repo): <NEW_LINE> <INDENT> endpoint = self.url+'repos/{}/{}/forks'.format(owner, repo) <NEW_LINE> response = requests.get(endpoint, headers=self.headers) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> data = json.loads(response.text) <NEW_LINE> for fork in data: <NEW_LINE> <... | Creates fork of a repo | 625941dca934411ee3751983 |
def main(*, time="15:00", format_time="%H:%M", out_format='{D:02}d {H:02}h {M:02}m {S:02}s', stdout=True): <NEW_LINE> <INDENT> time_now = datetime.now() <NEW_LINE> def format_time_builder(time, format_time, missing_format, ref_data): <NEW_LINE> <INDENT> if missing_format not in format_time: <NEW_LINE> <INDENT> format_t... | Display a friendly greeting.
:param str time: Number of times to display the greeting
:param str format_time: Number of times to display the greeting
:param str out_format: output format
:param bool stdout: whether to print to stdout | 625941dca8ecb033257d33bb |
def exec_source(self, source, path=''): <NEW_LINE> <INDENT> if path: <NEW_LINE> <INDENT> self._context.push_source(path) <NEW_LINE> <DEDENT> old_sandbox = self._context._sandbox <NEW_LINE> self._context._sandbox = weakref.ref(self) <NEW_LINE> try: <NEW_LINE> <INDENT> code = compile(source, path, 'exec') <NEW_LINE> exec... | Execute Python code within a string.
The passed string should contain Python code to be executed. The string
will be compiled and executed.
You should almost always go through exec_file() because exec_source()
does not perform extra path normalization. This can cause relative
paths to behave weirdly. | 625941dcd6c5a1020814433c |
def save_csv(): <NEW_LINE> <INDENT> top_countries = {k: v for k, v in sorted(country_list.items(), key=lambda item: item[1])} <NEW_LINE> with open('top_countries.csv', 'w') as csv_file: <NEW_LINE> <INDENT> writer = csv.writer(csv_file) <NEW_LINE> for key, value in top_countries.items(): <NEW_LINE> <INDENT> writer.write... | Writes country list dictionairy into top_countries.csv | 625941dc8e7ae83300e4b2bd |
def get_text_summarization_gensim(text, summary_ratio=0.4): <NEW_LINE> <INDENT> sentences = extract_sentences(text) <NEW_LINE> text = ' '.join(sentences) <NEW_LINE> summary = summarize(text, split=True, ratio=summary_ratio) <NEW_LINE> return summary | summary_ratio should be a number between 0 and Samples that determines the percentage of the number of sentences of the
original text to be chosen for the summary | 625941dc956e5f7376d7115b |
@main.command(short_help='Refresh configuration files of the site') <NEW_LINE> @click.argument('domain', type=str, required=False, default=None) <NEW_LINE> @click.option('--path', '-p', metavar='PATH', type=click.Path(exists=True, file_okay=False), default=None, help='Specify custom path') <NEW_LINE> @pass_state <NEW_L... | Rebuild configuration files for current (or specified) PATH or DOMAIN | 625941dc66656f66f7cbc49c |
def run(self): <NEW_LINE> <INDENT> frame_count = self.ffmpeg_probe_frame_count() <NEW_LINE> if frame_count == -1: <NEW_LINE> <INDENT> app.logger.debug("Probing of " + self.file.filename + " failed - aborting...") <NEW_LINE> ProcessRepository.file_failed(self.file) <NEW_LINE> return <NEW_LINE> <DEDENT> split_path = os.p... | run the encoding | 625941dcf7d966606f6aa2f7 |
def player_vs_com(self): <NEW_LINE> <INDENT> player2 = AI(self.game, 2) <NEW_LINE> self.player2 = player2 | defines the type of the players as player vs computer
:return: nothing | 625941dc7d847024c06be5ae |
def createBlankConfig(self): <NEW_LINE> <INDENT> self.cnf['GENERAL'] = {'load_last_db': False, 'last_db': '', 'create_backup_file': True, 'enable_file_recovery': False, 'ignore_non_participation': True, 'use_native_dialogs': True } <NEW_LINE> self.cnf['EDITOR'] = { 'sort_instantly': True, 'reset_results': False, '... | Erstellt eine neue Konfiguration mit den Standardwerten | 625941dca8370b7717052b8d |
def sound_speed(self, static_temperature): <NEW_LINE> <INDENT> if not 0<static_temperature<6000: <NEW_LINE> <INDENT> raise ValueError("Static temperature {}K out of bounds [0-6000]K".format(static_temperature)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> T = static_temperature <NEW_LINE> <DEDENT> a = np.sqrt(self.flu... | Local speed of sound, assuming adiabatic flow.
Inputs:
-------
+ static_temperature: float. Static temperature of the gas [K]
Outputs:
--------
+ a: speed of sound at a given static temperature, gamma and cp [m/s] | 625941dc0a366e3fb873eb0c |
def get_code_points(s): <NEW_LINE> <INDENT> return [c for c in s] | Get the Unicode code points. | 625941dc82261d6c526ab792 |
def clean_name(n): <NEW_LINE> <INDENT> return re.sub('\s+', '', n.lower()) | strip all spaces and capitalization
:type n: str
:rtype: str | 625941dca8370b7717052b8e |
def mark_unsafe(self, ship, position): <NEW_LINE> <INDENT> self.data.myDicts.positions_taken.setdefault((position.y, position.x), set()).add(ship.id) <NEW_LINE> self.data.myMatrix.locations.safe[position.y][position.x] = Matrix_val.UNSAFE | MARK POSITION PROVIDED WITH UNSAFE | 625941dc5fcc89381b1e19b1 |
def _get_snapshot_path(self, snapshot): <NEW_LINE> <INDENT> snapshot_id = ( snapshot['snapshot_id'] or snapshot['share_group_snapshot_id']) <NEW_LINE> share = snapshot.get('share') or snapshot.get('share_instance') <NEW_LINE> fs_path = self._get_dataset_path(share) <NEW_LINE> return '%s@snapshot-%s' % (fs_path, snapsho... | Return ZFS snapshot path for the snapshot. | 625941dc5166f23b2e1a5448 |
def is_annotation(instance): <NEW_LINE> <INDENT> return instance.__class__ == Annotation | Return whether a component is an Annotation. | 625941dc85dfad0860c3b14b |
def adaption_cross_entropy_loss(logits, labels, batch_size, num_classes, sigma_init, label_smoothing=0, weight=1.0, scope=None, reuse_variables=None): <NEW_LINE> <INDENT> with tf.variable_scope("ldl_loss",reuse=reuse_variables): <NEW_LINE> <INDENT> sigma = tf.get_variable('sigma', [num_classes,1], dtype=tf.float32, ini... | Define a Cross Entropy loss using softmax_cross_entropy_with_logits.
It can scale the loss by weight factor, and smooth the labels.
Args:
logits: [batch_size, num_classes] logits outputs of the network .
one_hot_labels: [batch_size, num_classes] target one_hot_encoded labels.
label_smoothing: if greater than 0 ... | 625941dccc0a2c11143dd180 |
def merge_csq(info, csq): <NEW_LINE> <INDENT> var_csq = info.split("CSQ=")[-1].split(";")[0] <NEW_LINE> csq.append(var_csq) <NEW_LINE> effects = set([]) <NEW_LINE> for csq_field in csq: <NEW_LINE> <INDENT> effects = effects | set(csq_field.split(",")) <NEW_LINE> <DEDENT> CSQ = "CSQ=" + ",".join(list(effects)) <NEW_LINE... | Merge the csq fields of bnd variants | 625941dc38b623060ff0b0dd |
def test_add_responder(self): <NEW_LINE> <INDENT> pass | Test case for add_responder
Add Responder # noqa: E501 | 625941dc442bda511e8be704 |
def _configure_job_metadata(metadata, allow_jagged_rows, allow_quoted_newlines, create_disposition, encoding, field_delimiter, ignore_unknown_values, max_bad_records, quote_character, skip_leading_rows, write_disposition, job_name): <NEW_LINE> <INDENT> load_config = metadata['configuration']['load'] <NEW_LINE> if allow... | Helper for :meth:`Table.upload_from_file`. | 625941dc711fe17d82542654 |
def spiralOrder(self, matrix): <NEW_LINE> <INDENT> n, m = len(matrix), len(matrix[0]) <NEW_LINE> res = [] <NEW_LINE> visited = set() <NEW_LINE> drct = [[0, 1], [1, 0], [0, -1], [-1, 0]] <NEW_LINE> i, j, d_idx = 0, 0, 0 <NEW_LINE> while len(res) < m * n: <NEW_LINE> <INDENT> res.append(matrix[i][j]) <NEW_LINE> if i + drc... | :type matrix: List[List[int]]
:rtype: List[int] | 625941dc7047854f462a16f6 |
def regret_from_best_da(f, maximise=True): <NEW_LINE> <INDENT> _f = _prepare_f(f) <NEW_LINE> _f = identity(_f, maximise=maximise) <NEW_LINE> best_decision_alternatives = np.amax(_f, axis=0) <NEW_LINE> regret = _f - best_decision_alternatives <NEW_LINE> return regret | T1: Regret from best decision alternative
Returns negative regret, so that from this point on,
the aim is to maximise the negative regret (towards 0).
Parameters
----------
f : np.ndarray, shape=(m, n)
Performance values, f, for m decision alternatives
and n scenarios.
maximise : bool
Is the performance m... | 625941dcb7558d58953c51ff |
def get_marker_pose(self): <NEW_LINE> <INDENT> extent = self.carla_actor.bounding_box.extent <NEW_LINE> marker_transform = self.carla_actor.get_transform() <NEW_LINE> marker_transform.location += marker_transform.get_up_vector() * extent.z <NEW_LINE> return trans.carla_transform_to_ros_pose(marker_transform) | Function to return the pose for vehicles.
:return: the pose of the vehicle
:rtype: geometry_msgs.msg.Pose | 625941dcbe7bc26dc91cd8ea |
def elapseTime(self, gameState): <NEW_LINE> <INDENT> allPossible = util.Counter() <NEW_LINE> for p in self.legalPositions: <NEW_LINE> <INDENT> if self.beliefs[p] > 0: <NEW_LINE> <INDENT> newPosDist = self.getPositionDistribution(self.setGhostPosition(gameState, p)) <NEW_LINE> for newPos, prob in newPosDist.items(): <NE... | Update self.beliefs in response to a time step passing from the current state.
The transition model is not entirely stationary: it may depend on Pacman's
current position (e.g., for DirectionalGhost). However, this is not a problem,
as Pacman's current position is known.
In order to obtain the distribution over new ... | 625941dc377c676e91272497 |
def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> closest_y = list(map(lambda idx: self.y_train[idx],np.argsort(dists[i])[:k])) <NEW_LINE> pass <NEW_LINE> freqs = {... | Given a matrix of distances between test points and training points,
predict a label for each test point.
Inputs:
- dists: A numpy array of shape (num_test, num_train) where dists[i, j]
gives the distance betwen the ith test point and the jth training point.
Returns:
- y: A numpy array of shape (num_test,) containi... | 625941dc8a43f66fc4b54352 |
def setAttrs(path, attrs): <NEW_LINE> <INDENT> pass | Set the attributes for the path.
path is the path to set attributes for as a string.
attrs is a idctionary in the same format as the attrs argument to
openFile.
This method returns when the attributes are set or a Deferred that is
called back when they are. | 625941dc0c0af96317bb84d7 |
def merge_sort(input_array): <NEW_LINE> <INDENT> if len(input_array) < 2: <NEW_LINE> <INDENT> return input_array <NEW_LINE> <DEDENT> return merge(merge_sort(input_array[:len(input_array)//2]), merge_sort(input_array[len(input_array)//2:])) | Sort input_array using the "merge sort" sorting algorithm
Time Complexity (worst-case): O(n*logn) - Splitting input_array into smaller
arrays with only one item has O(logn) time efficiency (same as binary search).
Merging the smaller arrays into a sorted whole array has O(n) time efficiency
since each small array is u... | 625941dcff9c53063f47c4e2 |
def cancel_order(self, order_id): <NEW_LINE> <INDENT> channel = self.get_trading_channel() <NEW_LINE> channel.cancel_order(order_id=order_id) | Cancel order
Parameters
----------
order_id | 625941dc96565a6dacc8f9ba |
def user_contacts(self, user_token): <NEW_LINE> <INDENT> response = OADict(**self._exec('users/%s/contacts' % (user_token,))).response <NEW_LINE> user_contacts = OADict(**response.result.data.identities) <NEW_LINE> user_contacts.response = response <NEW_LINE> return user_contacts | Get user's contacts by user token
:param str user_token: The user token
:returns OADict: User's contacts object | 625941dc5fc7496912cc3c6e |
def exec_extract(self, datastack_path, dest_dir_path): <NEW_LINE> <INDENT> self.setWindowTitle('Extracting archive') <NEW_LINE> self.title.setText('<h2>Extracting archive</h2>') <NEW_LINE> self.executor = execution.Executor( target=datastack.extract_datastack_archive, kwargs={'datastack_path': datastack_path, 'dest_dir... | Extract a datastack archive.
Presents a dialog with an indeterminate progress bar while the archive
is being extracted. The actual processing happens in a separate thread
of control.
Parameters:
datastack_path (string): The path to the datastack archive on disk
that should be extracted.
dest_dir_path... | 625941dcac7a0e7691ed43b7 |
def feed_db(): <NEW_LINE> <INDENT> return _get_shove_db("feed.sqlite") | Access feed db.
This is just a cache for feed processing, only for performance and to be nice on the web servers.
Returns
-------
Shove object
A Shove object with feed urls as keys and feed content as values. | 625941dc4f88993c3716c355 |
def _urlnorm(self, uri): <NEW_LINE> <INDENT> (scheme, authority, path, query, fragment) = parse_uri(uri) <NEW_LINE> if not scheme or not authority: <NEW_LINE> <INDENT> raise Exception("Only absolute URIs are allowed. uri = %s" % uri) <NEW_LINE> <DEDENT> authority = authority.lower() <NEW_LINE> scheme = scheme.lower() <... | Normalize the URL to create a safe key for the cache | 625941dc44b2445a33932384 |
def __add__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Duration): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return Time(self.secs + other.secs, self.nsecs + other.nsecs) | Add duration to this time
@param other: duration
@type other: L{Duration} | 625941dc5fdd1c0f98dc0524 |
def confirm_migration(self, migration, instance, network_info): <NEW_LINE> <INDENT> vm_ref = vm_util.search_vm_ref_by_identifier(self._session, instance.uuid + self._migrate_suffix) <NEW_LINE> if vm_ref is None: <NEW_LINE> <INDENT> LOG.debug("instance not present", instance=instance) <NEW_LINE> return <NEW_LINE> <DEDEN... | Confirms a resize, destroying the source VM. | 625941dcadb09d7d5db6ca7e |
def _write_json(handler, data): <NEW_LINE> <INDENT> data['pyessvVersion'] = pyessv.__version__ <NEW_LINE> handler.write(to_dict(data, to_camel_case)) <NEW_LINE> handler.set_header("Content-Type", "application/json; charset=utf-8") <NEW_LINE> handler.set_header("X-Content-Type-Options", "nosniff") <NEW_LINE> handler.set... | Writes HTTP response JSON data.
| 625941dc7b25080760e39748 |
def get_version(self, package): <NEW_LINE> <INDENT> if not self.has_pkgconfig: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> output = subprocess.check_output( [self.pkg_config, package, "--modversion"], stderr=subprocess.STDOUT) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <N... | Get the version of the package from pkg-config. | 625941dcd7e4931a7ee9e20e |
def test_epoch_end(self, outputs): <NEW_LINE> <INDENT> avg_test_acc = torch.stack([x["test_acc"] for x in outputs]).mean() <NEW_LINE> self.log("avg_test_acc", avg_test_acc) | Computes average test accuracy score
:param outputs: outputs after every epoch end
:return: output - average test loss | 625941dca934411ee3751984 |
def save(self, data_store, filename): <NEW_LINE> <INDENT> data_store.write_json_file( filename=filename, contents=self.get_dictionary()) <NEW_LINE> return None | Save the Gnosis object in json format.
:param data_store: Data store to save Gnosis in
:param filename: the file into which Gnosis is to be saved. | 625941dc8e05c05ec3eea666 |
def git_log_via_command(directory, log_count): <NEW_LINE> <INDENT> execute_command(GIT_VALID_DIRECTORY_COMMAND.format(dir=directory)) <NEW_LINE> git_log = get_output(GIT_LOG_COMMAND.format(dir=directory, number=log_count)).splitlines(keepends=True) <NEW_LINE> return create_git_log_content(git_log) | Method to get git log contents for the given directory and log count via git log command
:param directory
:param log_count:
:return: list of git log lines | 625941dc507cdc57c6306fd1 |
def ammonia_dtex(*args, **kwargs): <NEW_LINE> <INDENT> delta = kwargs.pop('delta') if 'delta' in kwargs else None <NEW_LINE> np.testing.assert_allclose(kwargs['trot'] - kwargs['tex'], delta) <NEW_LINE> return ammonia_func(*args, **kwargs) | Strip out the 'delta' keyword | 625941dc2eb69b55b151cba2 |
def filterStories(stories, triggerlist): <NEW_LINE> <INDENT> newStories = [] <NEW_LINE> for trigger in triggerlist: <NEW_LINE> <INDENT> for story in stories: <NEW_LINE> <INDENT> if trigger.evaluate(story): <NEW_LINE> <INDENT> newStories.append(story) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return newStories | Takes in a list of NewsStory instances.
Returns: a list of only the stories for which a trigger in triggerlist fires. | 625941dc8e05c05ec3eea667 |
def get_namespace_pod(self, namespace="default", **kwargs): <NEW_LINE> <INDENT> return self.client.list_namespaced_pod(namespace, **kwargs) | :param namespace: namespace of the Pod
:param label_selector: filters Pods by label
This will return a list of objects req namespace | 625941dc63d6d428bbe447e0 |
def fit_on_texts(self, words): <NEW_LINE> <INDENT> for w, c in words: <NEW_LINE> <INDENT> self.context_counts[c] = self.context_counts.get(c, 0) + 1 | Updates internal vocabulary based on a list of texts.
Required before using `texts_to_sequences` or `texts_to_matrix`.
# Arguments
texts: can be a list of strings,
or a generator of strings (for memory-efficiency) | 625941dc94891a1f4081bd9a |
def neighbour_points(map_grid, point): <NEW_LINE> <INDENT> point_x = point[0] <NEW_LINE> point_y = point[1] <NEW_LINE> neighbours = [ (point_x - 1, point_y - 1), (point_x, point_y - 1), (point_x + 1, point_y - 1), (point_x - 1, point_y), (point_x + 1, point_y), (point_x - 1, point_y + 1), (point_x, point_y + 1), (point... | Get the valid neighbouring points of a given point based on the map info.
@type map_grid: OccupancyGrid
@type point: (int, int) | 625941dcdd821e528d63b497 |
def query_yes_no(question, default="yes"): <NEW_LINE> <INDENT> valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} <NEW_LINE> if default is None: <NEW_LINE> <INDENT> prompt = " [y/n] " <NEW_LINE> <DEDENT> elif default == "yes": <NEW_LINE> <INDENT> prompt = " [Y/n] " <NEW_LINE> <DEDENT> elif default ==... | Queries user for confimration | 625941dc07d97122c4178b81 |
def __init__(self, tone=None, score=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._tone = None <NEW_LINE> self._sco... | CellTonality - a model defined in OpenAPI | 625941dc656771135c3ebb62 |
def get_groups(self): <NEW_LINE> <INDENT> result = self._make_requests_to_api("groups?all_available=true", paginated=True) <NEW_LINE> return sorted(map(lambda x: x["full_path"], result)) | :return: sorted list of groups | 625941dc60cbc95b062c6833 |
def which(program): <NEW_LINE> <INDENT> import os <NEW_LINE> def is_exe(fpath): <NEW_LINE> <INDENT> return os.path.isfile(fpath) and os.access(fpath, os.X_OK) <NEW_LINE> <DEDENT> fpath, fname = os.path.split(program) <NEW_LINE> if fpath: <NEW_LINE> <INDENT> if is_exe(program): <NEW_LINE> <INDENT> return program <NEW_LI... | Tests whether the specified program is anywhere in the environment
PATH so that it probably exists. | 625941dc3cc13d1c6d3c7669 |
def get_atomic_multilog_info(self, name): <NEW_LINE> <INDENT> self.send_get_atomic_multilog_info(name) <NEW_LINE> return self.recv_get_atomic_multilog_info() | Parameters:
- name | 625941dc76d4e153a657ee22 |
def implicit_val_and_grad(f): <NEW_LINE> <INDENT> def grad_fn(*args): <NEW_LINE> <INDENT> tape.push_new_tape() <NEW_LINE> end_node = f(*args) <NEW_LINE> variables = tape.top_tape_watched_variables() <NEW_LINE> sources = [x.handle for x in variables] <NEW_LINE> grad = imperative_grad(end_node, sources) <NEW_LINE> return... | Returns a function which differentiates f with respect to variables.
The wrapped function returns the value and the gradient of f when called with
the same arguments. The gradient is with respect to all TFE variables which
have `variable.watch()` called on them by f.
This function is useful when the exact set of vari... | 625941dc4e696a04525c973c |
def upsample_2d(incoming, kernel_size, name="UpSample2D"): <NEW_LINE> <INDENT> input_shape = utils.get_incoming_shape(incoming) <NEW_LINE> assert len(input_shape) == 4, "Incoming Tensor shape must be 4-D" <NEW_LINE> kernel = utils.autoformat_kernel_2d(kernel_size) <NEW_LINE> with tf.name_scope(name) as scope: <NEW_LINE... | UpSample 2D.
Input:
4-D Tensor [batch, height, width, in_channels].
Output:
4-D Tensor [batch, pooled height, pooled width, in_channels].
Arguments:
incoming: `Tensor`. Incoming 4-D Layer to upsample.
kernel_size: `int` or `list of int`. Upsampling kernel size.
name: A name for this layer (option... | 625941dc097d151d1a223148 |
def setup_file_dest(params, clearDestination=True): <NEW_LINE> <INDENT> if RANK == 0: <NEW_LINE> <INDENT> if not os.path.isdir(params.savefolder): <NEW_LINE> <INDENT> os.mkdir(params.savefolder) <NEW_LINE> assert(os.path.isdir(params.savefolder)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if clearDestination: <NEW_L... | Function to set up the file catalog structure for simulation output
Parameters
----------
params : object
e.g., `cellsim16popsParams.multicompartment_params()`
clear_dest : bool
Savefolder will be cleared if already existing.
Returns
-------
None | 625941dcf9cc0f698b1408e9 |
def _get_initial_stats(): <NEW_LINE> <INDENT> with db.session.create(): <NEW_LINE> <INDENT> return [{ "name": i, "counts": [], "max": None, "min": None, "avg": None } for i in dao_monitoring.get_accounting_projects() if i is not None and len(i)] | Gets initial stats prior to querying jobs table.
| 625941dc15baa723493c4268 |
def functions(self, fgraph): <NEW_LINE> <INDENT> if self in fgraph.nodes(): <NEW_LINE> <INDENT> return self.neighbors(fgraph) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] | Returns
-------
Neighbors of nodes | 625941dc21bff66bcd684c40 |
def read_config_file(): <NEW_LINE> <INDENT> configfile = open(os.path.join(defs.CONFIGMC, "config"), "r", encoding="UTF-8") <NEW_LINE> config = configfile.readlines() <NEW_LINE> configfile.close() <NEW_LINE> configuration = {} <NEW_LINE> i = 0 <NEW_LINE> for ligne in config: <NEW_LINE> <INDENT> ligne = ligne.rstrip("\n... | Reads the configuration file.
| 625941dc56b00c62f0f1494b |
def _find_nearest(self, array, value): <NEW_LINE> <INDENT> idx = (np.abs(array.values - float(value))).argmin() <NEW_LINE> val = array[idx] <NEW_LINE> return val, idx | Helper function. Used to find the nearest length because it isn't an
integer like age. | 625941dcbde94217f36830de |
def __createColumnListCtrl(self): <NEW_LINE> <INDENT> self.lcOmzet.InsertColumn(0,"Nota Transaksi", width=140) <NEW_LINE> self.lcOmzet.InsertColumn(1,"Total Penjualan", width=260) | Membuat kolom List CTrl | 625941dc7d847024c06be5af |
def _SendBattorCommandImpl(self, cmd): <NEW_LINE> <INDENT> self._battor_shell.stdin.write('%s\n' % cmd) <NEW_LINE> self._battor_shell.stdin.flush() <NEW_LINE> return self._battor_shell.stdout.readline() | Sends command to the BattOr. | 625941dcbd1bec0571d9091f |
def double_sha256(bytes, bin=False): <NEW_LINE> <INDENT> h = sha256(bytes) <NEW_LINE> if bin: <NEW_LINE> <INDENT> return sha256(h.digest()).digest() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sha256(h.digest()).hexdigest() | Returns the sha256(sha256(data)), used a lot in Bitcoin.
Args:
bytes (bytes): the data to hash.
bin (bool): if set to True, returns raw data
Returns:
str/bytes: the hash of the data passed as first parameter. | 625941dcf8510a7c17cf99ee |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self.filename <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <NEW_LINE> ... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941dcc432627299f04f38 |
def __init__(self): <NEW_LINE> <INDENT> self.k_p_p = 22 <NEW_LINE> self.k_p_q = 22 <NEW_LINE> self.k_p_r = 12 <NEW_LINE> self.z_k_p = 30.0 <NEW_LINE> self.z_k_d = 5.0 <NEW_LINE> self.k_p_yaw = 1.47 <NEW_LINE> self.k_p_roll = 0.5 <NEW_LINE> self.k_p_pitch = 0.5 <NEW_LINE> self.x_k_p = 7.5 <NEW_LINE> self.x_k_d = 2.5 <NE... | Initialize the controller object and control gains | 625941dc7cff6e4e81117c76 |
def get_actions(atype=None, state=None, coin=None, msg_id=None, created_utc=None, from_user=None, to_user=None, subr=None, ctb=None): <NEW_LINE> <INDENT> lg.debug("> get_actions(%s)", atype) <NEW_LINE> sql = "SELECT * FROM t_action" <NEW_LINE> sql_terms = [] <NEW_LINE> if atype or state or coin or msg_id or created_utc... | Return an array of CtbAction objects from database with given attributes | 625941dcdc8b845886cb5827 |
def is_ready(self): <NEW_LINE> <INDENT> self.installer() <NEW_LINE> self.validator() <NEW_LINE> return True | Check if the tool has a proper installation and test it on sample files.
:return: Boolean | 625941dc10dbd63aa1bd2e93 |
def clone(self): <NEW_LINE> <INDENT> return self.manager.clone(self.uuid) | Clone this task instance.
Returns:
:class:`saltant.models.base_task_instance.BaseTaskInstance`:
A task instance model instance representing the task
instance created due to the clone. | 625941dcbe383301e01b5771 |
def reachNewLow(pricelist,recent=3,period=60,cycle = 'D'): <NEW_LINE> <INDENT> if(cycle in ['30','15','60']): <NEW_LINE> <INDENT> thresh = 0.005 <NEW_LINE> <DEDENT> elif(cycle in ['D']): <NEW_LINE> <INDENT> thresh = 0.015 <NEW_LINE> <DEDENT> elif(cycle in ['W']): <NEW_LINE> <INDENT> thresh = 0.03 <NEW_LINE> <DEDENT> re... | :param pricelist:价格list
:param recent:近recent天
:param period:时间段
:return: 近recent天是否达到period天的最低点 | 625941dc090684286d50efd9 |
def process_iq(self, conn, iq): <NEW_LINE> <INDENT> action = self.entity.check_acp(conn, iq) <NEW_LINE> self.entity.check_perm(conn, iq, action, -1, prefix="health_") <NEW_LINE> if action == "history": <NEW_LINE> <INDENT> reply = self.iq_health_info_history(iq) <NEW_LINE> conn.send(reply) <NEW_LINE> raise xmpp.protocol... | this method is invoked when a ARCHIPEL_NS_HYPERVISOR_HEALTH IQ is received.
it understands IQ of type:
- alloc
- free
@type conn: xmpp.Dispatcher
@param conn: ths instance of the current connection that send the stanza
@type iq: xmpp.Protocol.Iq
@param iq: the received IQ | 625941dcd99f1b3c44c6787b |
def partial_tucker(tensor, modes, ranks=None, n_iter_max=100, init='svd', tol=10e-5, random_state=None, verbose=False): <NEW_LINE> <INDENT> if ranks is None: <NEW_LINE> <INDENT> ranks = [tensor.shape[mode] for mode in modes] <NEW_LINE> <DEDENT> if init == 'svd': <NEW_LINE> <INDENT> factors = [] <NEW_LINE> for index, mo... | Partial tucker decomposition via Higher Order Orthogonal Iteration (HOI)
Decomposes `tensor` into a Tucker decomposition exclusively along the provided modes.
Parameters
----------
tensor : ndarray
modes : int list
list of the modes on which to perform the decomposition
ranks : None or int list
si... | 625941dce64d504609d74b30 |
def StartShell(self): <NEW_LINE> <INDENT> subprocess.call([_Powershell(), '-NoProfile', '-NoLogo'], shell=True) | Start the PowerShell interpreter. | 625941dcb5575c28eb68e2f3 |
def _get_dataset(self): <NEW_LINE> <INDENT> if self.args.data == "Rossmann": <NEW_LINE> <INDENT> data = Rossmann(self.args.root_path, self.args.scale) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> if self.args.scale: <NEW_LINE> <INDENT> self.label_scaler = data.label_scaler... | Function creates dataset based on data name in the parsers.
Returns:
data: An instant of the dataset created | 625941dcfb3f5b602dac3987 |
def setShiftMethod(self, methodName): <NEW_LINE> <INDENT> if DEBUG: <NEW_LINE> <INDENT> print('setShiftMethod -- %s'%methodName) <NEW_LINE> <DEDENT> methodName = str(methodName) <NEW_LINE> if methodName == 'Inverse FFT shift': <NEW_LINE> <INDENT> self.shiftMethod = self.fftShift <NEW_LINE> <DEDENT> elif methodName == '... | Method receives methodName from AlignmentWidget
instance and assigns the according shift method. | 625941dcd7e4931a7ee9e20f |
def test_browserlayer(self): <NEW_LINE> <INDENT> from krks.d3print.interfaces import ( IKrksD3PrintLayer) <NEW_LINE> from plone.browserlayer import utils <NEW_LINE> self.assertIn( IKrksD3PrintLayer, utils.registered_layers()) | Test that IKrksD3PrintLayer is registered. | 625941dc24f1403a92600e55 |
def doMesher(optDict): <NEW_LINE> <INDENT> paramDict = {} <NEW_LINE> paramDict.update(optDict) <NEW_LINE> df = pd.read_pickle(paramDict["inputFile"]) <NEW_LINE> if paramDict["extNamesInput"] == None: <NEW_LINE> <INDENT> extList = [] <NEW_LINE> if paramDict["doFandA"]: <NEW_LINE> <INDENT> for extName in infoDict: <NEW_... | makes Mesh data files
| 625941dcd10714528d5fffd7 |
@admin.route("/category/edit/<int:id>", methods=["GET", "POST"]) <NEW_LINE> @admin_login <NEW_LINE> def category_edit(id=None): <NEW_LINE> <INDENT> form = CategoryForm() <NEW_LINE> form.submit.label.text = "修改" <NEW_LINE> category = Category.query.get_or_404(id) <NEW_LINE> if request.method == "GET": <NEW_LINE> <INDENT... | 菜系编辑 | 625941dc2ae34c7f2600d422 |
def runTest(self): <NEW_LINE> <INDENT> foreignkey_name = "test_foreignkey_add_%s" % (str(uuid.uuid4())[1:6]) <NEW_LINE> data = {"name": foreignkey_name, "columns": [{"local_column": "id", "references": self.foreign_table_id, "referenced": "id"}], "confupdtype": "a", "confdeltype": "a", "autoind... | This function will add foreign key table column. | 625941dcfff4ab517eb2f72e |
def run_training(): <NEW_LINE> <INDENT> data_sets = input_data.read_data_sets(FLAGS.train_dir, FLAGS.fake_data) <NEW_LINE> with tf.Graph().as_default(): <NEW_LINE> <INDENT> images_placeholder, labels_placeholder = placeholder_inputs( FLAGS.batch_size) <NEW_LINE> logits = mnist.inference(images_placeholder, FLAGS.hidden... | Train MNIST for a number of steps. | 625941dcf9cc0f698b1408ea |
def check_consumed_status(self, sku_id, key="", value="", targetmachine_ip=""): <NEW_LINE> <INDENT> cmd = "subscription-manager list --consumed" <NEW_LINE> ret, output = self.runcmd(cmd, "list consumed subscriptions", targetmachine_ip) <NEW_LINE> if ret == 0 and output is not None: <NEW_LINE> <INDENT> consumed_lines = ... | check consumed entitlements status details | 625941dc44b2445a33932385 |
@pytest.helpers.register <NEW_LINE> @contextmanager <NEW_LINE> def temp_file(name=None, contents=None, directory=None, strip_first_newline=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if directory is None: <NEW_LINE> <INDENT> directory = RUNTIME_VARS.TMP <NEW_LINE> <DEDENT> if not isinstance(directory, pathlib.P... | This helper creates a temporary file. It should be used as a context manager
which returns the temporary file path, and, once out of context, deletes it.
Can be directly imported and used, or, it can be used as a pytest helper function if
``pytest-helpers-namespace`` is installed.
.. code-block:: python
import o... | 625941dc3317a56b86939f43 |
def select(self): <NEW_LINE> <INDENT> l = sample(range(len(self)), self.pressure if self.pressure < len(self) else len(self)) <NEW_LINE> maxf, val = float('-inf'), None <NEW_LINE> for s in l: <NEW_LINE> <INDENT> actual_fitness = (self[s].fitness[0] - self[s].size*2 - self[s].fitness[1]*10 - self[s].fitness[2]*10) <NEW_... | P.choose() -> individual
Selects individual by using tournament method
In tournament selection a number of individuals are chosen
at random from the population. These are compared with each
other and the best of them is chosen to be the parent.
* In this implementation selection pressure defines a number of
individu... | 625941dc3d592f4c4ed1d358 |
def compute_similarity_matrix_my(self, G, target_entity, adj_entity, path_len): <NEW_LINE> <INDENT> self.G = G <NEW_LINE> target_nodes = [node for node, attr in G.nodes(data=True) if attr['entity'] == target_entity] <NEW_LINE> adj_nodes = [node for node, attr in G.nodes(data=True) if attr['entity'] == adj_entity] <NEW_... | Parameters
-----------
G : graph
target_entity : the entity, for the nodes of which similarities should be calculated
adj_entity : the entity, from the node of which the paths start
path_len : the length of the path between target and adj nodes
Returns
-------
sim : similarity matrix for target entity nodes | 625941dc6e29344779a62901 |
def Prepare(benchmark_spec): <NEW_LINE> <INDENT> vm = benchmark_spec.vms[0] <NEW_LINE> vm.Install('pip') <NEW_LINE> vm.RemoteCommand('sudo pip install absl-py') <NEW_LINE> edw_service_instance = benchmark_spec.edw_service <NEW_LINE> edw_service_instance.InstallAndAuthenticateRunner(vm) <NEW_LINE> _PushScripts(benchmark... | Install script execution environment on the client vm.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark. | 625941dc57b8e32f5248378e |
def create_issue(self, request, group, form_data, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('This feature is not implemented yet') | Called by the web process when the user wants to create a new Zendesk
ticket and link to the sentry issue. | 625941dcab23a570cc250475 |
def split_array(a, items_split): <NEW_LINE> <INDENT> n_splits = len(a)//items_split <NEW_LINE> splits = [] <NEW_LINE> for _ in range(n_splits): <NEW_LINE> <INDENT> splits.append(a[len(splits)*items_split:(len(splits)+1)*items_split]) <NEW_LINE> <DEDENT> return splits | returns max num of lists of size items_split from input list
IN: array to be split, number of items in each split
OUT: list of splits [list of lists]
WARNING: throws out scragglers if items_split doesnt go evenly into input | 625941dc0a366e3fb873eb0d |
def get_options(self, symbol, expiration): <NEW_LINE> <INDENT> return(self._query('options', symbol, expiration)) | Get options for a quote based on expiration date | 625941dc16aa5153ce362769 |
def unfollow(id: str, group_type: str, is_organization: bool) -> Response: <NEW_LINE> <INDENT> set_org(is_organization) <NEW_LINE> context = cast( Context, {u'model': model, u'session': model.Session, u'user': g.user}) <NEW_LINE> data_dict = {u'id': id} <NEW_LINE> try: <NEW_LINE> <INDENT> get_action(u'unfollow_group')(... | Stop following this group. | 625941dc66656f66f7cbc49d |
def getmaxyx_border(canvas: Window) -> Tuple[int, int]: <NEW_LINE> <INDENT> height, width = canvas.getmaxyx() <NEW_LINE> return height - 1, width - 1 | Returns height and width of the window with border. | 625941dca79ad161976cc437 |
def start_reporting(bot, update, user_data): <NEW_LINE> <INDENT> user = get_user(update) <NEW_LINE> assert 'reports' not in user_data; assert 'curr_index' not in user_data <NEW_LINE> if not user.trackable_names: <NEW_LINE> <INDENT> update.message.reply_text("You don't have any trackables yet. Create one by sending /ad... | prints report start dialog,
inits the userdata so that the ask_for_next_report
will work with the first trackable
and prompts user for first report | 625941dc956e5f7376d7115d |
def generate_node(node: Node, limit: int = 1000) -> str: <NEW_LINE> <INDENT> res = [] <NEW_LINE> stack = [node] <NEW_LINE> while len(stack) > 0 and len(stack) < limit: <NEW_LINE> <INDENT> item = stack.pop() <NEW_LINE> print(item) <NEW_LINE> if isinstance(item, Node): <NEW_LINE> <INDENT> if len(item.tokens) == 0: <NEW_L... | Generate node string. | 625941dcfff4ab517eb2f72f |
def motor_at_the_beg(self, bus: int, axis: int) -> bool: <NEW_LINE> <INDENT> return bool(self.__get_chan_prop(bus, axis)[8]) | Zeigt, ob der Anfang-Initiator im Moment aktiviert ist. | 625941dc71ff763f4b549982 |
def get_queryset(self): <NEW_LINE> <INDENT> list_of_visited_municipalities = VisitedMunicipality.objects.filter( user_id=self.request.user.id).order_by('-issued_date')[:10] <NEW_LINE> nr_visits = VisitedMunicipality.objects.filter( user_id=self.request.user.id).count() <NEW_LINE> return [list_of_visited_municipalities,... | Return the number of municipalities that
this user has visited. | 625941dc796e427e537b08b9 |
def test_patch_item(self): <NEW_LINE> <INDENT> instance = dict(my_item=True) <NEW_LINE> assert instance['my_item'] is True <NEW_LINE> with PatchedItem(instance, 'my_item', False) as return_value: <NEW_LINE> <INDENT> assert return_value is instance <NEW_LINE> assert instance['my_item'] is False <NEW_LINE> <DEDENT> asser... | Test :class:`humanfriendly.testing.PatchedItem`. | 625941dcf7d966606f6aa2f9 |
def testGetDirList(self): <NEW_LINE> <INDENT> existingDirPath=ufsi.Path(self.existingDirPathStr) <NEW_LINE> nonExistingDirPath=ufsi.Path(self.nonExistingDirPathStr) <NEW_LINE> d=existingDirPath.getDir() <NEW_LINE> self.assertEquals(d.getDirList(),self.existingDirDirList, 'Returned dir list was not correct') <NEW_LINE> ... | Tests the getDirList() method.
1. getDirList of existing directory
2. getDirList of non-existing directory
TODO: test re filtering | 625941dc9c8ee82313fbba67 |
def testDB(self): <NEW_LINE> <INDENT> s3store0 = S3FileStorage(); <NEW_LINE> s3store0.setupDB('test-db-name'); <NEW_LINE> s3store0.database.table_1.delete_many({ "testing" : 123 }); <NEW_LINE> self.assertEqual(s3store0.database.table_1.count({ "testing" : 123 }), 0); <NEW_LINE> s3store0.database.table_1.insert_one({ "t... | Test that we can access the mongo db and write to it | 625941dc7d847024c06be5b0 |
def round_note_length_base2(frac): <NEW_LINE> <INDENT> denominator = float(1) / frac <NEW_LINE> return float(1) / (2 ** round(math.log(denominator) / math.log(2), 0)) | Numbers will come in as something like 1/17.55, we want to
round them to 1/16 for 16th notes, etc.
This function returns the denominator of the note length, i.e.
1 for whole note, 2 for half, ... , 128 for 128th note. | 625941dc187af65679ca5410 |
def delete_query(self): <NEW_LINE> <INDENT> if self.query: <NEW_LINE> <INDENT> position = self.query_names.index(self.query) <NEW_LINE> delete = "DELETE FROM query WHERE name = ?" <NEW_LINE> self.cursor.execute(delete, self.query) <NEW_LINE> self.conn.commit() <NEW_LINE> del self._queries <NEW_LINE> position = min(posi... | Delete the currently selected query and re-draw the form. | 625941dcd53ae8145f87a55d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.