code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def redeem_voucher(self, id): <NEW_LINE> <INDENT> if not self.in_sandbox: <NEW_LINE> <INDENT> raise NotSupportedInProduction() <NEW_LINE> <DEDENT> return self._get('/vouchers/' + id + '/redeem') | Redeems a voucher
:param String id The ID of a specific voucher | 625941bfd6c5a10208143f7a |
def as_sql(self, qn, connection): <NEW_LINE> <INDENT> lhs, lhs_params = self.process_lhs(qn, connection) <NEW_LINE> rhs, rhs_params = self.process_rhs(qn, connection) <NEW_LINE> params = lhs_params + rhs_params <NEW_LINE> lookup_data = self.get_lookup_data() <NEW_LINE> operator = lookup_data['operator'] <NEW_LINE> look... | Looks up the json path as string | 625941bff8510a7c17cf962d |
def find_files_and_time(postpath='.'): <NEW_LINE> <INDENT> assert isdir(expanduser(postpath)), "find_files_and_time: The input must be a directory." <NEW_LINE> files_h5 = glob.glob(postpath+'/post*.h5') ; files_h5.sort() <NEW_LINE> files_xmf = glob.glob(postpath+'/post*.xmf') ; files_xmf.sort() <NEW_LINE> nfile... | Creates a list of the HDF5 and xmf files in a directory, and reads
in the time from the xmf files into an array.
Sample usage
------------
files_h5, files_xmf, time = find_files_and_time('.')
Notes
-----
The time calculation is sensitive to the format of the xmf files.
If that format changes, then this routine will h... | 625941bf60cbc95b062c6474 |
def save(self,filename,overwrite=False,save_format='h5'): <NEW_LINE> <INDENT> self.model.save_weights(filename,overwrite=overwrite,save_format=save_format) | save方法是用于保存网络模型到特定文件 | 625941bf3c8af77a43ae36d0 |
def parse_image_meta(img_meta): <NEW_LINE> <INDENT> ori_shape = img_meta[0:3] <NEW_LINE> img_shape = img_meta[3:6] <NEW_LINE> pad_shape = img_meta[6:9] <NEW_LINE> scale_factor = img_meta[9] <NEW_LINE> flip = img_meta[10] <NEW_LINE> return { 'ori_shape': ori_shape.astype(np.int32), 'img_shape': img_shape.astype(np.int32... | Parses an array that contains image attributes to its components.
Args
---
meta: [11]
Returns
---
a dict of the parsed values. | 625941bfd10714528d5ffc12 |
def event_info(self): <NEW_LINE> <INDENT> event_dict = self.event_dict() <NEW_LINE> event_string = ( 'M %(mmi)s %(date)s %(time)s ' '%(latitude-name)s: %(latitude-value)s ' '%(longitude-name)s: %(longitude-value)s ' '%(depth-name)s: %(depth-value)s%(depth-unit)s ' '%(located-label)s %(distance)s%(distance-unit)s ' '%(b... | Get a short paragraph describing the event.
:return: A string describing the event e.g.
'M 5.0 26-7-2012 2:15:35 Latitude: 0°12'36.00"S
Longitude: 124°27'0.00"E Depth: 11.0km
Located 2.50km SSW of Tondano'
:rtype: str | 625941bfa8370b77170527d2 |
def get_angle(self): <NEW_LINE> <INDENT> return 0 | Return the angle [deg] of these axes relative to the *c*, *a* axes.
| 625941bf851cf427c661a444 |
def _connection(self): <NEW_LINE> <INDENT> requests_session = requests.Session() <NEW_LINE> retries = Retry(total=self.retries, connect=self.retries, read=self.retries, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504]) <NEW_LINE> if sys.platform in ['darwin']: <NEW_LINE> <INDENT> requests_session.trust_env = F... | Enables retries to cope with CoreNLP server boot-up latency.
See: http://stackoverflow.com/a/35504626
Create a new object per connection to make multiprocessing threadsafe.
:return: | 625941bfbe383301e01b53bd |
def _integral_points_PALP(self): <NEW_LINE> <INDENT> if not self.is_compact(): <NEW_LINE> <INDENT> raise ValueError('can only enumerate points in a compact polyhedron') <NEW_LINE> <DEDENT> lp = self.lattice_polytope(True) <NEW_LINE> try: <NEW_LINE> <INDENT> del lp._points <NEW_LINE> del lp._npoints <NEW_LINE> <DEDENT> ... | Return the integral points in the polyhedron using PALP.
This method is for testing purposes and will eventually be removed.
OUTPUT:
The list of integral points in the polyhedron. If the
polyhedron is not compact, a ``ValueError`` is raised.
EXAMPLES::
sage: Polyhedron(vertices=[(-1,-1),(1,0),(1,1),(0,1)])._in... | 625941bff548e778e58cd4ae |
def widgets(self): <NEW_LINE> <INDENT> label_title = Label(self, text='CFIR - Date de notification & confinement') <NEW_LINE> label_title.grid(row=0, column=0, columnspan=2, pady=10) <NEW_LINE> """Date de notification""" <NEW_LINE> label_date = Label(self, text='Date de notification (JJ/MM/AAAA) :') <NEW_LINE> self.ent... | Configuration des widgets | 625941bf4527f215b584c38c |
def test_base_block_default_terminals(self): <NEW_LINE> <INDENT> default_input = Terminal.get_default_terminal_on_class( Block, TerminalType.input) <NEW_LINE> default_output = Terminal.get_default_terminal_on_class( Block, TerminalType.output) <NEW_LINE> self.assertIsInstance(default_input, Terminal) <NEW_LINE> self.as... | Asserts that the base block has default terminals | 625941bf5f7d997b871749c7 |
def retrieve_data(self, hatrac_store): <NEW_LINE> <INDENT> raise NotImplementedError() | Download raw CSV pointcloud data from Hatrac object store and register it.
Registered pointclouds are saved to self.n1, self.n2 | 625941bfd18da76e23532405 |
def get_copybutton_path(): <NEW_LINE> <INDENT> import easydev <NEW_LINE> try: <NEW_LINE> <INDENT> packagedir = easydev.__path__[0] <NEW_LINE> packagedir = os.path.realpath(pj(packagedir, "share")) <NEW_LINE> os.listdir(packagedir) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> packaged... | Return the path where the to find the copybutton javascript
Copy the copybutton.js javascript in the share directory of easydev so
that it is accesible by all packages that required it by typing:
.. doctest::
>>> from easydev import get_copybutton_path
>>> p = get_copybutton_path()
It can then be added with... | 625941bf15fb5d323cde0a3e |
def underlying(self, **config): <NEW_LINE> <INDENT> return self._parse_response(attribute='underlying', **config) | Return the underlying symbol for the contract. | 625941bf76e4537e8c3515a3 |
def drop_least_imp_cols(rf_model, df, n): <NEW_LINE> <INDENT> importance = rf_model.feature_importances_ <NEW_LINE> indices = np.argsort(importance) <NEW_LINE> indices_to_drop = indices[:n] <NEW_LINE> cols_to_drop = np.array(df.columns)[indices_to_drop] <NEW_LINE> df = df.drop(columns=cols_to_drop) <NEW_LINE> return df... | Drop the n least important features from rf model. | 625941bf442bda511e8be34e |
def pre_popup_menu_callback(self, *args): <NEW_LINE> <INDENT> state, sensitive = self.shell.props.shell_player.get_playing() <NEW_LINE> if not state: <NEW_LINE> <INDENT> sensitive = False <NEW_LINE> <DEDENT> self.popup.set_sensitive('ev_compact_add_to_playing_menu_item', sensitive) <NEW_LINE> self.popup.set_sensitive('... | Callback when the popup menu is about to be displayed | 625941bfa8ecb033257d3001 |
def test_variants(self): <NEW_LINE> <INDENT> for r, t in self._allRows(): <NEW_LINE> <INDENT> l = langtag(r['Lang_Id']) <NEW_LINE> if t.vars is None and l.vars is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if sorted(t.vars) != sorted(l.vars): <NEW_LINE> <INDENT> self.fail("{Lang_Id} and {likely_subtag} have... | Test that all variants are in IANA | 625941bfc4546d3d9de72964 |
def EbookIterator(*args, **kwargs): <NEW_LINE> <INDENT> from calibre.ebooks.oeb.iterator.book import EbookIterator <NEW_LINE> return EbookIterator(*args, **kwargs) | For backwards compatibility | 625941bf187af65679ca5050 |
def addAtHead(self, val): <NEW_LINE> <INDENT> node = ListNode(val) <NEW_LINE> self.size += 1 <NEW_LINE> node.next = self.head <NEW_LINE> self.head = node | Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
:type val: int
:rtype: void | 625941bfad47b63b2c509eb2 |
def clean_subconstituency_id(self): <NEW_LINE> <INDENT> subconstituency_id = self.cleaned_data['subconstituency_id'] <NEW_LINE> try: <NEW_LINE> <INDENT> subconstituency = SubConstituency.objects.get(id=subconstituency_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise forms.ValidationError(_('Subconstituency doe... | Ensure that the subconstituency_id refers to an existing subconstituency | 625941bf10dbd63aa1bd2ad8 |
def directory_entries_equal(dir1, dir2): <NEW_LINE> <INDENT> dir1_paths, dir2_paths = map(extract_directory_paths, map(ensure_trailing_slashes_in_directory, (dir1, dir2))) <NEW_LINE> return dir1_paths == dir2_paths | Compare two directory entries, considered equal if only the path items match. | 625941bf5e10d32532c5ee59 |
def get_name_info(self): <NEW_LINE> <INDENT> return { "name": self.get_name(), "shortdesc":"", "longdesc": "", "parameters": [], "actions": [], } | Get structured agent's info, only name is populated | 625941bf4a966d76dd550f3f |
def tankShot (targetBox, obstacleBox, x0, y0, v, theta, g = 9.8): <NEW_LINE> <INDENT> angle= getNumberInput("Give an angle:", [0, np.Inf]) <NEW_LINE> velocity= getNumberInput("Give a velocity:", [0, np.Inf]) <NEW_LINE> (x,y)= trajectory (x0,y0,velocity, angle,g = 9.8) <NEW_LINE> (x,y)= endTrajectoryAtIntersection (x,y,... | executes one tank shot
parameters
----------
targetBox : tuple
(left,right,bottom,top) location of the target
obstacleBox : tuple
(left,right,bottom,top) location of the central obstacle
x0,y0 :floats
origin of the shot
v : float
velocity of the shot
theta : float
angle of the shot
g : float
a... | 625941bfac7a0e7691ed4003 |
def test_medias_method_with_grappelli(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import grappelli <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> settings.INSTALLED_APPS += ('grappelli', ) <NEW_LINE> self.assertIn('grappelli', settings.INSTALLED_APPS) <NEW_LINE> admin = B... | Tests if the right css ile is triggered when grappelli is installed. | 625941bf15baa723493c3ea6 |
def __init__(self, components=[]): <NEW_LINE> <INDENT> self.compo = components | Initializes an instance of the Vector class.
components: a list of components coordinates. It starts with x, y, z, ... and so on. | 625941bfd486a94d0b98e077 |
def getFt(self, b, h): <NEW_LINE> <INDENT> return self.Ft | Return the value of Ft.
:param b: section width.
:param h: section depth | 625941bf23e79379d52ee498 |
def search_code_keyword_in_note(note, keyword_set, all_code_area): <NEW_LINE> <INDENT> result_list = list() <NEW_LINE> for each_keyword in keyword_set: <NEW_LINE> <INDENT> found = False <NEW_LINE> for each_code in all_code_area: <NEW_LINE> <INDENT> for i, each_line in enumerate(each_code.splitlines()): <NEW_LINE> <INDE... | 在某篇特定笔记中查找所有代码块, 如果查询的所有关键词都存在, 则加入结果列表
:param note: note 实例
:param keyword_set: set(), 用户查询关键词集合
:param all_code_area: list(), 包含了该笔记中所有的代码块
:return: list(), 搜索结果 | 625941bf460517430c3940be |
def _build_encoder_cell(self, hparams): <NEW_LINE> <INDENT> return model_helper.create_rnn_cell( num_units=hparams.num_units, num_layers=hparams.num_layers, keep_prob=hparams.keep_prob) | Build a multi-layer RNN cell that can be used by encoder. | 625941bf5fcc89381b1e15ef |
def contact_create_update(contact_object, raise_errors=False, log_events=True, log_transitions=True): <NEW_LINE> <INDENT> cs = contact_synchronizer.ContactSynchronizer( log_events=log_events, log_transitions=log_transitions, raise_errors=raise_errors, ) <NEW_LINE> cs.event('run', contact_object) <NEW_LINE> outputs = li... | If `epp_id` field is empty, creates a new Contact or Registrant on back-end.
Otherwise update existing object from `contact_object` info.
Returns False if error happened, or raise Exception if `raise_errors` is True, | 625941bf4428ac0f6e5ba724 |
def set_size(self, text=""): <NEW_LINE> <INDENT> self.size = text | set size of the monster object | 625941bf4c3428357757c25c |
def set_due_complete(self): <NEW_LINE> <INDENT> self._set_due_complete(True) | Set due complete
:return: None | 625941bf6fb2d068a760efcd |
def __getitem__(self, index: int) -> Tuple[Any, Any]: <NEW_LINE> <INDENT> curr_index = index <NEW_LINE> for x in range(self.total): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path, target = self.samples[curr_index] <NEW_LINE> sample = self.loader(path) <NEW_LINE> break <NEW_LINE> <DEDENT> except Exception as e: <NEW_... | Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class. | 625941bf21bff66bcd684887 |
def freeze_freeze(sbox): <NEW_LINE> <INDENT> sbox.build(create_wc=False, read_only=True) <NEW_LINE> second_repo_dir, _ = sbox.add_repo_path('backup') <NEW_LINE> svntest.actions.run_and_verify_svnadmin(None, [], "hotcopy", sbox.repo_dir, second_repo_dir) <NEW_LINE> if svntest.main.is_fs_type_fsx() or (svntest.main.i... | svnadmin freeze svnadmin freeze (some-cmd) | 625941bfbe383301e01b53be |
def test_messages_destroy(self): <NEW_LINE> <INDENT> client = app.test_client() <NEW_LINE> result = client.delete('/messages/14?user_id=1', follow_redirects=True) <NEW_LINE> self.assertEqual(result.status_code, 404) <NEW_LINE> deleted_message = Message.query.filter(Message.id == 14).first() <NEW_LINE> self.assertEqual(... | test delete message | 625941bf01c39578d7e74d6d |
def _parent_choices(self): <NEW_LINE> <INDENT> policies = self.api.list_policies() <NEW_LINE> choices = [('', '----------')] <NEW_LINE> choices.extend( [(p['id'], p['name']) for p in policies if not p['inherits_from']]) <NEW_LINE> return choices | Get a list of parent choices used for inheritance | 625941bf796e427e537b04f6 |
def change_states_of(): <NEW_LINE> <INDENT> pass | This gets called when a poll has finished.
It returns a dictionary with proposal uid as key and new state as value.
Like: {'<uid>':'approved', '<uid>', 'denied'}
It's not required to do, but if it isn't done, the proposals won't change state
and you have to do it manually | 625941bf7047854f462a133f |
def bad_key(): <NEW_LINE> <INDENT> {}['bar'] | When run, produces a KeyError. | 625941bf07f4c71912b113b3 |
def update_table_description( self, table_id, description, project_id=bq_default_project(), dataset_id=bq_default_dataset() ): <NEW_LINE> <INDENT> table_ref = self.get_table_ref(dataset_id=dataset_id, table_id=table_id, project_id=project_id) <NEW_LINE> table = self.client.get_table(table_ref) <NEW_LINE> if table.descr... | Performs a table update to fill in description for the table.
Parameters:
table_id (string): BigQuery table ID.
description (string): The descriptive text to describe the content of the table.
project_id (string): BigQuery project ID.
dataset_id (string): BigQuery dataset ID.
Raises:
BadRequest if... | 625941bf9f2886367277a7c2 |
def rankdata(a, method='average'): <NEW_LINE> <INDENT> if method not in ('average', 'min', 'max', 'dense', 'ordinal'): <NEW_LINE> <INDENT> raise ValueError('unknown method "{0}"'.format(method)) <NEW_LINE> <DEDENT> arr = np.ravel(np.asarray(a)) <NEW_LINE> algo = 'mergesort' if method == 'ordinal' else 'quicksort' <NEW_... | Assign ranks to data, dealing with ties appropriately.
Ranks begin at 1. The `method` argument controls how ranks are assigned
to equal values. See [1]_ for further discussion of ranking methods.
Parameters
----------
a : array_like
The array of values to be ranked. The array is first flattened.
method : str, ... | 625941bf30c21e258bdfa3ce |
def get_engage_group(character): <NEW_LINE> <INDENT> engagegroup = [character] <NEW_LINE> for key in character.db.Combat_Range: <NEW_LINE> <INDENT> if character.db.Combat_Range[key] == 0 and not character.db.Combat_Range[key] in engagegroup and key != character: <NEW_LINE> <INDENT> engagegroup.append(key) <NEW_LINE> <D... | Returns a list of the other characters this character is engaged with, including themself. | 625941bf24f1403a92600a9b |
def alive(self): <NEW_LINE> <INDENT> if not self.stack.parseInner(self.rxPacket): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = self.rxPacket.data <NEW_LINE> body = self.rxPacket.body.data <NEW_LINE> remote = self.stack.remotes[self.reid] <NEW_LINE> if not remote.joined: <NEW_LINE> <INDENT> remote.refresh(alive... | Process alive packet | 625941bf236d856c2ad44709 |
def str_2_bool(bool_str): <NEW_LINE> <INDENT> lower_str = bool_str.lower() <NEW_LINE> if 'true'.startswith(lower_str) or 'yes'.startswith(lower_str): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif 'false'.startswith(lower_str) or 'no'.startswith(lower_str): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT>... | Case independent function to convert a string representation of a
boolean (``'true'``/``'false'``, ``'yes'``/``'no'``) into a ``bool``. This is case
insensitive, and will also accept part of a boolean string
(``'t'``/``'f'``, ``'y'``/``'n'``).
Raises a :py:class:`toyz.utils.errors.ToyzError` if an invalid expressio... | 625941bf656771135c3eb79f |
def _make_mock_pubsub_message(task_args): <NEW_LINE> <INDENT> msg = mock.create_autospec(message.Message) <NEW_LINE> msg.data = _make_task_bytes(task_args) <NEW_LINE> msg.message_id = str(uuid.uuid4()) <NEW_LINE> return msg | Returns a mock pubsub message.
Args:
task_args: Proto message to use as args to the task to put in the pubsub
message. | 625941bf6e29344779a62547 |
def split_dictionary(train_path, valid_path=None, test_path=None): <NEW_LINE> <INDENT> source_dic = codecs.open(train_path, "r", "utf-8").readlines() <NEW_LINE> train_dic, valid_dic, test_dic = [], [], [] <NEW_LINE> if valid_path: <NEW_LINE> <INDENT> valid_dic = codecs.open(valid_path, "r", "utf-8").readlines() <NEW_LI... | Split source dictionary to train, validation and test sets.
| 625941bf7d847024c06be1ec |
def sampleBeatHunterLikelihood(signal, begin, end, referencies, RR_estimat, index, **kwargs): <NEW_LINE> <INDENT> from numpy import mean, correlate, sum, median, diff,array <NEW_LINE> percentil = 0.80 <NEW_LINE> referencies[0] = getPercentil(referencies[0],referencies[1], percentil) <NEW_LINE> alRescate = [correlate(s... | referencies[0] media del grupo
referencies[1] quantitat elements representats | 625941bfd486a94d0b98e078 |
def test_pretty_changes(self): <NEW_LINE> <INDENT> self.assertEqual( changes.pretty_change({'action': 'DELETE'}), 'Deleted') <NEW_LINE> self.assertEqual( changes.pretty_change({'action': 'RESERVE'}), 'Reserved') <NEW_LINE> self.assertEqual( changes.pretty_change({'action': 'KEEP'}), 'Mentioned but not modified') <NEW_L... | Verify the output for a variety of "changes" | 625941bf4f6381625f114970 |
def update(self, dict_or_items=None): <NEW_LINE> <INDENT> if dict_or_items is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if isinstance(dict_or_items, dict) and not isinstance(dict_or_items, OrderedDict): <NEW_LINE> <INDENT> if not set(self.keys()) == set(dict_or_items.keys()): <NEW_LINE> <INDENT> raise TypeEr... | Update from another OrderedDict or dict or sequence of
(key, value) pairs. If provided an unordered dictionary, it is
only accepted if the existing keys already exist. | 625941bf7b180e01f3dc4735 |
def maj(self): <NEW_LINE> <INDENT> if self.commande: <NEW_LINE> <INDENT> self.commande.nom_categorie = self.nom_categorie <NEW_LINE> self.commande.aide_courte = self._aide_courte <NEW_LINE> self.commande.aide_longue = str(self.aide_longue) <NEW_LINE> <DEDENT> for cle, couple in self.etats.items(): <NEW_LINE> <INDENT> r... | Mise à jour de la commande dynamique. | 625941bf38b623060ff0ad21 |
def get_callgraph(self): <NEW_LINE> <INDENT> cmd = [self.OBJDUMP_BIN, '-d'] + self._objdump_opts + [self.binary] <NEW_LINE> f = sp.run(cmd, stdout=sp.PIPE, check=True).stdout <NEW_LINE> g = defaultdict(set) <NEW_LINE> rc = re.compile(r'<(.*?)>:') <NEW_LINE> rb = re.compile(r'<([^+>]+)') <NEW_LINE> current = None <NEW_L... | Return adjacency list of all functions.
Leaves are included. Self-references are excluded.
Only direct calls are accounted for, indirect calls and storing
a pointer to a function are not accounted for. | 625941bf6aa9bd52df036cd6 |
def run_forever(self): <NEW_LINE> <INDENT> return self.gw.run() | Run the client (e.g. the :class:`GatewayClient`) in the current greenlet. | 625941bfb5575c28eb68df31 |
def updateValues(self, station, sweeptparameters=None): <NEW_LINE> <INDENT> def recursiveUpdataValues(qc_inst, data, sweeptparameters): <NEW_LINE> <INDENT> for key, val in data.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> inst_param = qc_inst.parameters[key] <NEW_LINE> value = inst_param.get_latest() <NEW_LINE... | Update the data with actual voltages from the QDac | 625941bf8c3a8732951582eb |
def addBefore(self, new_element, node): <NEW_LINE> <INDENT> previous = None <NEW_LINE> current = self.head <NEW_LINE> while current.value != node.value and current.next: <NEW_LINE> <INDENT> previous = current <NEW_LINE> current = current.next <NEW_LINE> <DEDENT> if current.value == node.value: <NEW_LINE> <INDENT> if se... | add new element/item before a position in the Linked List
Arguments:
- new_element: an object that reference to a new element to be added
- node: an object that reference to an object that tells the
method to where place the new element/item | 625941bfd7e4931a7ee9de50 |
def test_buckets(): <NEW_LINE> <INDENT> h1 = HistogramBucketDict(guesslogbuckets(0, 500, numbuckets=10)) <NEW_LINE> for x in range(0, 600): <NEW_LINE> <INDENT> h1.add(x) <NEW_LINE> <DEDENT> h2 = HistogramBucketDict(guesslogbuckets(0, 500, numbuckets=30)) <NEW_LINE> for x in range(0, 600): <NEW_LINE> <INDENT> h2.add(x) ... | Test HistogramBucketDict and gnuplot output. | 625941bf56ac1b37e6264107 |
def perform_augmentation(self, sequence_id, coordinates_1, coordinates_2): <NEW_LINE> <INDENT> sequence_boundary = self.sequence_boundaries[sequence_id] <NEW_LINE> result = augment_pair_coordinates(coordinates_1, coordinates_2, randomize_positions=self.randomize_positions, mean_scale_factor=self.mean_scale_factor, p_ho... | Augments coordinates for training
Arguments:
coordinates -- all x coordinates followed by all y coordinates | 625941bf63b5f9789fde7018 |
def returnLatAndLong(self, receivedJson): <NEW_LINE> <INDENT> return receivedJson["entry"][0]["messaging"][0].get("message").get("attachments")[0].get("payload").get("coordinates") | get the latitude and longitude received from location quick reply
Arguments:
receivedJson {json} -- received json
Returns:
json -- latitude and longitude | 625941bf23849d37ff7b2fc3 |
def testInterfaceFunctions(self): <NEW_LINE> <INDENT> ap = KMCAnalysisPlugin() <NEW_LINE> self.assertTrue( hasattr(ap, "setup") ) <NEW_LINE> self.assertTrue( hasattr(ap, "finalize") ) <NEW_LINE> self.assertTrue( hasattr(ap, "registerStep") ) <NEW_LINE> ap.setup("time-dummy", "step-dummy", "config-dummy") <NEW_LINE> ap.... | Test that we can construct a derrived class. | 625941bf5510c4643540f31d |
def main(arguments): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) <NEW_LINE> parser.add_argument('infile', help='Input file', action=check_ext({'ipv4', 'ipv6'})) <NEW_LINE> parser.add_argument("outfile", help="Output file", type=argparse... | Input files should be structured like this:
IPv4 files : ip:port extension : .ipv4
IPv6 files : ip.port extension : .ipv6 | 625941bf92d797404e3040bc |
def generate_json(json_schema): <NEW_LINE> <INDENT> dict_ = {} <NEW_LINE> for key, value in json_schema.items(): <NEW_LINE> <INDENT> generator_func = "fake." + value + "()" <NEW_LINE> dict_[key] = eval(generator_func) <NEW_LINE> <DEDENT> return json.dumps(dict_) | Function to generate json. | 625941bf596a8972360899f6 |
def OnLoadCoordFromFile(self, event): <NEW_LINE> <INDENT> dlg = wx.FileDialog(self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard="Text Files (.txt, .dat)|*.txt;*.dat", style=wx.OPEN | wx.CHANGE_DIR) <NEW_LINE> if dlg.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> path = dlg.GetPath() <NEW_LIN... | Loads label coordinates from data file | 625941bf15fb5d323cde0a3f |
def get(self, session, **filters): <NEW_LINE> <INDENT> model = session.query(self.model_class).filter_by(**filters).first() <NEW_LINE> if not model: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return model.to_data_model() | Retrieves an entity from the database.
:param session: A Sql Alchemy database session.
:param filters: Filters to decide which entity should be retrieved.
:returns: octavia.common.data_model | 625941bf82261d6c526ab3cf |
def get_store_dsn(self, filter_password=False): <NEW_LINE> <INDENT> return self._build_dsn(self.dbname, filter_password=filter_password) | Returns a uri representing the current database settings.
It's used by the orm to connect to a database.
:param filter_password: if the password should be filtered out
:returns: a string like postgresql://username@localhost/dbname | 625941bf99cbb53fe6792b1a |
def __setitem__(self, k, v): <NEW_LINE> <INDENT> self.root = self._put_to_node(self.root, k, v) | >>> s = BSTKVStore()
>>> s[2] = 'b'
>>> s.root
Node(2, 'b')
>>> s[1] = 'a'
>>> s.root.left
Node(1, 'a')
>>> s[3] = 'c'
>>> s.root.right
Node(3, 'c') | 625941bfcb5e8a47e48b79e1 |
def GetCommandArgs(self): <NEW_LINE> <INDENT> return self.command + self.common_args + self.test_args | Return the complete command-line arguments as a list. | 625941bf7d43ff24873a2bd1 |
def all_completed(futures): <NEW_LINE> <INDENT> group = FutureGroup(futures) <NEW_LINE> return group.all_completed | Return a new Future that completes when all the futures in the 'futures' list given as argument
are completed.
The new Futures returns the list of results, or sets 'OneOrMoreFuturesFailed' if one or more futures
failed. | 625941bf167d2b6e31218ac9 |
def __init__(self): <NEW_LINE> <INDENT> object.__init__(self) <NEW_LINE> self.level = None <NEW_LINE> self.section = None <NEW_LINE> self.floor_empty = None <NEW_LINE> self.floor_rock = None <NEW_LINE> self.wall_empty = None <NEW_LINE> self.wall_ground = None <NEW_LINE> self.rng = random.Random() | Default constructor | 625941bf9f2886367277a7c3 |
def random_list(my_list, list_size): <NEW_LINE> <INDENT> while len(my_list) < list_size: <NEW_LINE> <INDENT> number = random.randint(0, list_size) <NEW_LINE> my_list.append(number) <NEW_LINE> <DEDENT> return my_list | Generate a list with random numbers.
Args:
my_list (list): empty list to be filled
list_size (int): value to determine size of list
Returns:
my_list (list): list of random value with size determined by list_size value | 625941bfde87d2750b85fcc3 |
def random_mini_batches(X, Y, mini_batch_size): <NEW_LINE> <INDENT> m = X.shape[0] <NEW_LINE> mini_batches = [] <NEW_LINE> permutation = list(np.random.permutation(m)) <NEW_LINE> shuffled_X = X[permutation,:,:,:] <NEW_LINE> shuffled_Y = Y[permutation,:] <NEW_LINE> num_complete_minibatches = math.floor(m/mini_batch_size... | Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)
mini_batch_size - size of the mini-batches, integer
Returns:
mini_batches -- li... | 625941bf1f5feb6acb0c4a87 |
def model(pDict, lamSqArr_m2): <NEW_LINE> <INDENT> pArr1 = pDict["fracPol1"] * np.ones_like(lamSqArr_m2) <NEW_LINE> pArr2 = pDict["fracPol2"] * np.ones_like(lamSqArr_m2) <NEW_LINE> quArr1 = pArr1 * np.exp( 2j * (np.radians(pDict["psi01_deg"]) + pDict["RM1_radm2"] * lamSqArr_m2)) <NEW_LINE> quArr2 = pArr2 * np.exp( 2j *... | Two separate Faraday components, averaged within same telescope beam
(i.e., unresolved), with a common Burn depolarisation term. | 625941bf91f36d47f21ac423 |
def test_solar_irradiance_atlanta_georgia(): <NEW_LINE> <INDENT> loc = Location(latitude=33.64, longitude=84.43, timezone=-5) <NEW_LINE> sol = SolarDesignDay( location=loc, timeperiod=DESIGN_DAYS, tau_b=np.array( ( 0.334, 0.324, 0.355, 0.383, 0.379, 0.406, 0.440, 0.427, 0.388, 0.358, 0.354, 0.335, ) ), tau_d=np.array( ... | Test the calculation of solar irradiance. | 625941bf97e22403b379cecc |
def setUp(self): <NEW_LINE> <INDENT> self.component_manager = core.ComponentManager() <NEW_LINE> self.component = TestDriver(self.component_manager) | sets up the environment | 625941bf596a8972360899f7 |
def nvmlSystemGetTopologyGpuSet(cpuNumber): <NEW_LINE> <INDENT> c_count = c_uint(0) <NEW_LINE> fn = _nvmlGetFunctionPointer("nvmlSystemGetTopologyGpuSet") <NEW_LINE> ret = fn(cpuNumber, byref(c_count), None) <NEW_LINE> if ret != NVML_SUCCESS: <NEW_LINE> <INDENT> raise NVMLError(ret) <NEW_LINE> <DEDENT> print(c_count.va... | /**
* Retrieve the set of GPUs that have a CPU affinity with the given CPU number
* For all products.
* Supported on Linux only.
*
* @param cpuNumber The CPU number
* @param count When zero, is set to the number of matching GPUs such that \a deviceArray
*... | 625941bfdd821e528d63b0de |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> entity_id = config.get(CONF_ENTITY_ID) <NEW_LINE> start = config.get(CONF_START) <NEW_LINE> end = config.get(CONF_END) <NEW_LINE> duration = config.get(CONF_DURATION) <NEW_LINE> name = config.get(CONF_NAME) <NEW_LINE> unit = config.... | Set up the HistoryAverage sensor. | 625941bf8a349b6b435e80a7 |
def exp(x, x_min=EXP_MIN, x_max=EXP_MAX): <NEW_LINE> <INDENT> from numpy import exp, clip <NEW_LINE> x_min = max(x_min, EXP_MIN) <NEW_LINE> x_max = min(x_max, EXP_MAX) <NEW_LINE> return exp(clip(x, x_min, x_max)) | Save version of exp, clips argument such that overflow does not occur.
@param x: input
@type x: numpy array or float or int
@param x_min: lower value for clipping
@type x_min: float
@param x_max: upper value for clipping
@type x_max: float | 625941bf090684286d50ec16 |
def status(self, which): <NEW_LINE> <INDENT> stats = nest.GetConnections(self.pre_neuron, synapse_model = self.synapse_model) <NEW_LINE> return nest.GetStatus(stats, [which])[0][0] | Get synapse parameter status. | 625941bf99cbb53fe6792b1b |
def start(self, output, motion_output=None): <NEW_LINE> <INDENT> self.frame = PiVideoFrame( index=0, frame_type=None, frame_size=0, video_size=0, split_size=0, timestamp=0, complete=False, ) <NEW_LINE> if motion_output is not None: <NEW_LINE> <INDENT> self._open_output(motion_output, PiVideoFrameType.motion_data) <NEW_... | Extended to initialize video frame meta-data tracking. | 625941bfe76e3b2f99f3a744 |
@pytest.mark.parametrize("data", getdata(data_file, "test_get_hashrate")) <NEW_LINE> def test_get_hashrate(data): <NEW_LINE> <INDENT> res = get_hashrate(data["reqdata"]) <NEW_LINE> verify_code_msg(res, data["expdata"]) | 获取账户实时算力 | 625941bf3c8af77a43ae36d2 |
def show(self, **kwargs): <NEW_LINE> <INDENT> return self.api_request(self._get_method_fullname("show"), kwargs) | Shows the details for the specified auth audit.
**Inputs**
| ``api version min:`` None
| ``api version max:`` None
| ``required:`` True
| ``default:`` None
:param id: The internal NetMRI identifier of this user audit log information.
:type id: Integer
**Outputs**
| ``api version min:`` None
| ``api version... | 625941bf0a366e3fb873e74c |
def _check_crs(left, right, allow_none=False): <NEW_LINE> <INDENT> if allow_none: <NEW_LINE> <INDENT> if not left.crs or not right.crs: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> if not left.crs == right.crs: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Check if the projection of both arrays is the same.
If allow_none is True, empty CRS is treated as the same. | 625941bf9b70327d1c4e0d08 |
def __init__(self, filename, directory): <NEW_LINE> <INDENT> super().__init__(filename, directory) <NEW_LINE> self.attribute_name = 'sub_experiment_id' <NEW_LINE> self.attribute_visibility = 'global' <NEW_LINE> self.attribute_type = 'c' | Initialise the class
:param str filename: The basename of the file to process.
:param str directory: The directory that the file is currently in. | 625941bfd4950a0f3b08c285 |
def includeme(config): <NEW_LINE> <INDENT> settings = config.get_settings() <NEW_LINE> config.include('pyramid_tm') <NEW_LINE> session_factory = get_session_factory(get_engine(settings)) <NEW_LINE> config.registry['dbsession_factory'] = session_factory <NEW_LINE> config.add_request_method( lambda r: get_tm_session(sess... | Initialize the model for a Pyramid app.
Activate this setup using ``config.include('myproject.models')``. | 625941bf004d5f362079a269 |
def extractProjectPrefix(files): <NEW_LINE> <INDENT> commonprefix = os.path.commonprefix(files) <NEW_LINE> if not commonprefix or not commonprefix.endswith("."): <NEW_LINE> <INDENT> print(red("Can't extract project name from files: %s" % ", ".join(files), bold=True)) <NEW_LINE> print(red("Please ensure that all files h... | Extract a common project prefix from all files in a directory
Fails & exits if no such prefix is found
Example: [ABC.top, ABC.bot] => "ABC" | 625941bff548e778e58cd4b0 |
def init(self): <NEW_LINE> <INDENT> if not super(IFCTEXTLITERALWITHEXTENT,self).init(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> arg = self.args.getNext() <NEW_LINE> if not isUnset(arg): <NEW_LINE> <INDENT> self.Extent= spfToId(arg) <NEW_LINE> <DEDENT> arg = self.args.getNext() <NEW_LINE> if not isUnset(arg... | get every argument's value and parse inverses | 625941bf6e29344779a62548 |
def tau_plus_minus(self): <NEW_LINE> <INDENT> ct = self.cartan_type() <NEW_LINE> L,R = ct.index_set_bipartition() <NEW_LINE> return self.tau_epsilon_operator_on_almost_positive_roots(L), self.tau_epsilon_operator_on_almost_positive_roots(R) | Returns the `\tau^+` and `\tau^-` piecewise linear operators on ``self``
Those operators are induced by the bipartition `\{L,R\}` of
the simple roots of ``self``, and stabilize the almost
positive roots. Namely, `\tau_+` fixes the negative simple
roots `\alpha_i` for `i` in `R`, and acts otherwise by:
.. math::
... | 625941bf3cc13d1c6d3c72af |
def MakeChangeLog(self, commit): <NEW_LINE> <INDENT> final = [] <NEW_LINE> process_it = self.get('process_log', '').split(',') <NEW_LINE> process_it = [item.strip() for item in process_it] <NEW_LINE> need_blank = False <NEW_LINE> for change in sorted(self.changes, reverse=True): <NEW_LINE> <INDENT> out = [] <NEW_LINE> ... | Create a list of changes for each version.
Return:
The change log as a list of strings, one per line
Changes in v4:
- Jog the dial back closer to the widget
Changes in v3: None
Changes in v2:
- Fix the widget
- Jog the dial
etc. | 625941bfd58c6744b4257b94 |
def run(Model, module_size=0, option="random", scipy=False): <NEW_LINE> <INDENT> print("Reading data...") <NEW_LINE> y, X, tag = readData(config.TRAIN_FILE, return_scipy=scipy) <NEW_LINE> testY, testX, _ = readData(config.TEST_FILE, return_scipy=scipy) <NEW_LINE> train = TrainWrapper(Model, config.LIBLINEAR_TRAINING_OP... | run liblinear training
:param module_size: the data module for size for each model, 0 for no decomposition
:param option: class, nothing, random
:return: | 625941bff9cc0f698b140532 |
def serialize_model_semantics(args, architecture_hd5): <NEW_LINE> <INDENT> semantics = { 'id': args.id, 'output_labels': args.labels, 'architecture': os.path.basename(architecture_hd5), 'input_symbols': args.input_symbols, 'model_version': args.model_version, 'gatk_version': args.gatk_version, } <NEW_LINE> if args.tens... | Save a json file specifying model semantics, I/O contract.
Arguments
args.tensor_name: String which indicates tensor map to use (from defines.py) or None
args.window_size: sites included in the tensor map
args.read_limit: Maximum reads included in the tensor map
args.annotations: List of annotations or... | 625941bf283ffb24f3c55838 |
def gnomesort(list_): <NEW_LINE> <INDENT> position = 0 <NEW_LINE> while position < len(list_) - 1: <NEW_LINE> <INDENT> i = position <NEW_LINE> if list_[i] <= list_[i + 1]: <NEW_LINE> <INDENT> position += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> list_[i], list_[i + 1] = list_[i + 1], list_[i] <NEW_LINE> if positi... | Gnomesort - TODO: Explain idea
Parameters
----------
list_ : list
Sort this one
Returns
-------
list
Sorted list | 625941bfe1aae11d1e749be9 |
def call_on_exit(self): <NEW_LINE> <INDENT> self.on_exit(self.out_data, self.err_data, self.reason) | Call on_exit after processing all twisted events.
When e.g. the iperf port is already in use, processExited happens
before errReceived gets "bind failed: Address already in use".
Using callLater, on_exit is able to properly get and display stderr. | 625941bfa8370b77170527d5 |
def read_spec(self, test_name): <NEW_LINE> <INDENT> spec = self.nettests.read_one(test_name) <NEW_LINE> if not spec: <NEW_LINE> <INDENT> logging.warning("Cannot read nettest %s spec", test_name) <NEW_LINE> <DEDENT> return spec | Reads the specification of a test | 625941bfa8ecb033257d3002 |
def inorder(node): <NEW_LINE> <INDENT> if node.isLeaf(): <NEW_LINE> <INDENT> itemlist.extend(node.items) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(node.size()): <NEW_LINE> <INDENT> inorder(node.children[i]) <NEW_LINE> itemlist.append(node.items[i]) <NEW_LINE> <DEDENT> inorder(node.children[-1]) | recursively fills itemlist with items inorder | 625941bfa17c0f6771cbdf87 |
def execute(self, request): <NEW_LINE> <INDENT> url = request.uri <NEW_LINE> if request.parameters: <NEW_LINE> <INDENT> url += '?' + urlencode(request.parameters) <NEW_LINE> <DEDENT> if request.headers: <NEW_LINE> <INDENT> headers = dict(self._headers, **request.headers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> he... | Execute a request and return a response | 625941bfdd821e528d63b0df |
def SailForces(self, thetaw, vw, deltas): <NEW_LINE> <INDENT> alphas = -Norm(thetaw + deltas + np.pi) <NEW_LINE> atanC, deltaatan = self.sail.atanClCd(alphas) <NEW_LINE> Fs, deltaFs = self.sail.F(alphas, vw) <NEW_LINE> gammas = Norm(atanC - thetaw) <NEW_LINE> deltaFs = deltaFs * -1.0 <NEW_LINE> deltagamma = deltaatan *... | Calculates and returns forces from the sail.
Arguments:
thetaw: Wind, 0 = running downwind, +pi / 2 = wind from port
vw: Wind speed, m / s
deltas: Sail angle, 0 = all in, +pi / 2 = sail on starboard
heel: Boat heel, 0 = upright
Returns:
Fs: Magnitude of force from sail (N)
gammas: Angle of force from sail (... | 625941bf4a966d76dd550f41 |
def getMeterInfo(self, filterJson=None, useFilter: bool=False): <NEW_LINE> <INDENT> self.getAllMeterInfo() <NEW_LINE> meters = self.METER_JSONCOLLECTION <NEW_LINE> tempFilteredMeter=[] <NEW_LINE> if not useFilter or filterJson is None or len(filterJson)==0: <NEW_LINE> <INDENT> self.METER_JSONCOLLECTION = meters <NEW_L... | Return `getAllMeterInfo()` but selected meters is based on filter | 625941bf21a7993f00bc7c20 |
def reverse_transform(self, lvar_lname, rvar_lname, indices, adjust_hdim=None, flip_vdim=None): <NEW_LINE> <INDENT> if self.has_dim_transforms: <NEW_LINE> <INDENT> dtrans = self.__dim_transforms <NEW_LINE> lhs_term = dtrans.reverse_transform(lvar_lname, indices, adjust_hdim=adjust_hdim, flip_vdim=flip_vdim) <NEW_LINE> ... | Compute and return the the reverse transform from "var2" to "var1".
<lvar_lname> is the local name of "var1".
<rvar_lname> is the local name of "var2".
<indices> is a tuple of the loop indices for "var2" (i.e., "var2"
will show up in the RHS of the transform as "var2(indices)".
If <adjust_hdim> is not None, it shoul... | 625941bf8e71fb1e9831d6de |
def publish_to_consortium(self, id, dataset, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.publish_to_consortium_with_http_info(id, dataset, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.publish_to_co... | initiates a batch job to extract and publish a dataset and knowledge graph # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.publish_to_consortium(id, dataset, async_req=True)
>>> result = thread.get()
:param async... | 625941bf925a0f43d2549da9 |
def project_to(self, var_list=[]): <NEW_LINE> <INDENT> var_list = colloc.intersect(ascertain_list(var_list), self.vars()) <NEW_LINE> if var_list: <NEW_LINE> <INDENT> return Pot(self.tb[var_list + ['pval']].groupby(var_list).sum().reset_index()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Pot(pd.DataFrame({'pva... | project to a subset of variables (marginalize out other variables) | 625941bfd486a94d0b98e079 |
def __init__(self, name, description): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.owner = 'owner' <NEW_LINE> self.version = '1' <NEW_LINE> self.suites = [] | high level support for doing this and that. | 625941bfa05bb46b383ec758 |
def set_queued(self, queued=True): <NEW_LINE> <INDENT> is_queued = self.is_queued() <NEW_LINE> if queued and not is_queued: <NEW_LINE> <INDENT> from madgui.util.qt import Queued <NEW_LINE> self._trigger = Queued(self._invoke) <NEW_LINE> <DEDENT> elif not queued and is_queued: <NEW_LINE> <INDENT> self._trigger = self._i... | Set the signal to *queued mode*, i.e. signal will be emitted in
another mainloop iteration.
Note that queued mode requires at least a ``QCoreApplication``. | 625941bf711fe17d825422a4 |
def _get_subdir_paths(root_path): <NEW_LINE> <INDENT> if not os.path.isdir(root_path): <NEW_LINE> <INDENT> logger.warning("Transfer path %s is not a path to a directory", root_path) <NEW_LINE> raise DirsUUIDsException <NEW_LINE> <DEDENT> exclude_paths = (root_path, os.path.join(root_path, "objects")) <NEW_LINE> return ... | Return a generator of subdirectory paths in ``root_path``. | 625941bf460517430c3940c0 |
@app_views.route('states/<state_id>/cities', methods=['POST'], strict_slashes=False) <NEW_LINE> def create_city(state_id): <NEW_LINE> <INDENT> my_state = storage.get('State', state_id) <NEW_LINE> if my_state is None: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> if not request.json: <NEW_LINE> <INDENT> abort(400, ... | Creates a City object | 625941bf627d3e7fe0d68d83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.