code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def p_declaration4(p): <NEW_LINE> <INDENT> p[0] = enaml_ast.Declaration(p[2], p[4], p[7], '', [], p.lineno(1)) | declaration : ENAMLDEF NAME LPAR NAME RPAR COLON NAME COLON PASS NEWLINE | 625941d35e10d32532c5f0ff |
def prevf(x): <NEW_LINE> <INDENT> return -nextf(-x) | Get the floating point value right before x | 625941d366673b3332b9226a |
def validate_email(self): <NEW_LINE> <INDENT> if len(self.email) > 6: <NEW_LINE> <INDENT> if re.match(r'\w[\w\.-]*@\w[\w\.-]+\.\w+', self.email) is not None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Validate email regex. | 625941d3be383301e01b565c |
def outerTrees(self, points): <NEW_LINE> <INDENT> def clockwise(p, q, r): <NEW_LINE> <INDENT> return (p.x - r.x) * (q.y - r.y) < (q.x - r.x) * (p.y - r.y) <NEW_LINE> <DEDENT> def findhull(hull, p): <NEW_LINE> <INDENT> hull.append(p) <NEW_LINE> while len(hull) > 2 and clockwise(*hull[-3:]): <NEW_LINE> <INDENT> hull.pop(... | :type points: List[Point]
:rtype: List[Point] | 625941d33c8af77a43ae3979 |
def do_exit(self, arg): <NEW_LINE> <INDENT> exit(1) | Exit the program | 625941d3e64d504609d74a18 |
def Description(i: dict) -> str: <NEW_LINE> <INDENT> if 'description' not in i.keys(): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> out = "<details><summary>(more)</summary>" <NEW_LINE> out = out + i['description'] + "\n</details>\n\n" <NEW_LINE> return out | given an instance dictionary,
return the markdown for the long description | 625941d39c8ee82313fbb94e |
def jpg2arr(image_path,imfrmt='CHW'): <NEW_LINE> <INDENT> with PIL.Image.open(image_path) as image: <NEW_LINE> <INDENT> im_arr = np.fromstring(image.tobytes(), dtype=np.uint8) <NEW_LINE> im_arr = im_arr.reshape((image.size[1], image.size[0], 3)) <NEW_LINE> if imfrmt=='CHW': <NEW_LINE> <INDENT> im_arr = np.transpose(im_... | Loads JPEG image into 3D Numpy array of shape
(width, height, channels) | 625941d3d486a94d0b98e31e |
def hasPathSum(self, root, sum): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if root.left == None and root.right == None and sum == root.val: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(... | :type root: TreeNode
:type sum: int
:rtype: bool | 625941d34d74a7450ccd439c |
@contextmanager <NEW_LINE> def reading_ancillary_files(metadata): <NEW_LINE> <INDENT> metadata.reading_ancillary_files = True <NEW_LINE> yield metadata <NEW_LINE> metadata.reading_ancillary_files = False | context manager to be used when reading metadata so no errors are risen.
This is useful because we want to be able to get as much as possible out
of malformed input
:param metadata: the metadata object
:type metadata: BaseMetadata | 625941d3c4546d3d9de72c0d |
@enroll_app.route('/profile', methods=['GET', 'POST']) <NEW_LINE> def enroll(): <NEW_LINE> <INDENT> ca = get_ca() <NEW_LINE> key, csr = ca.create_device_csr('device-identity') <NEW_LINE> device_certificate = ca.sign(csr) <NEW_LINE> pkcs12_payload = identity_payload(key, device_certificate, 'sekret') <NEW_LINE> profile ... | Generate an enrollment profile. | 625941d38c3a873295158593 |
def get_store_info(self, value): <NEW_LINE> <INDENT> flags = 0 <NEW_LINE> if isinstance(value, str): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if isinstance(value, unicode): <NEW_LINE> <INDENT> value = value.encode('utf-8') <NEW_LINE> <DEDENT> elif isinstance(value, int): <NEW_LINE> <INDENT> flags |= _FLAG_INTEGER <... | Transform val to a storable representation, returning a tuple of the flags, and the new value itself. | 625941d301c39578d7e75014 |
def _import_dependencies(self): <NEW_LINE> <INDENT> super(CarepointPhoneStoreImporter, self)._import_dependencies() <NEW_LINE> self._import_dependency(self.carepoint_record['store_id'], 'carepoint.carepoint.store') | Import depends for record | 625941d3f8510a7c17cf98d4 |
def get_multilabel(data_frame, column, groups): <NEW_LINE> <INDENT> binarizer = MultiLabelBinarizer() <NEW_LINE> y_multi = data_frame[column].apply(lambda x: groups[x]) <NEW_LINE> values = binarizer.fit_transform(y_multi) <NEW_LINE> return pd.DataFrame(data=values, columns=binarizer.classes_, index=data_frame.index) | Convert a class attribute to a binary matrix.
By indicating the presence of a class label in the instance with 0,1.
Args:
data_frame: data frame with the column
column: column to extract the feature values
groups: dictionary as key the class, value list of groups
Returns:
Binary data frame with the pr... | 625941d33617ad0b5ed680cf |
@jit <NEW_LINE> def sub_elwise(a: Iterable, b: Iterable): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for i in zip(a, b): <NEW_LINE> <INDENT> result.append(i[0] - i[1]) <NEW_LINE> <DEDENT> return result | Subtract the second iterable from the first, element-wise. | 625941d3d164cc6175782f26 |
def myrange(start, end, step): <NEW_LINE> <INDENT> R = 1000. <NEW_LINE> start *= R <NEW_LINE> end *= R <NEW_LINE> step *= R <NEW_LINE> output = [] <NEW_LINE> tmp = start <NEW_LINE> if step >= 0: <NEW_LINE> <INDENT> while tmp < end: <NEW_LINE> <INDENT> output.append(tmp / R) <NEW_LINE> tmp += step <NEW_LINE> <DEDENT> <D... | floating point range~ | 625941d3cb5e8a47e48b7c81 |
def __getitem__(self, xy): <NEW_LINE> <INDENT> if isinstance(xy, slice) : <NEW_LINE> <INDENT> return self.values[xy.stop][xy.start] <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> x,y = xy <NEW_LINE> return self.values[y][x] | gives access to A SINGLE cell | 625941d310dbd63aa1bd2d7b |
def decode(bytes_, encoding=None): <NEW_LINE> <INDENT> if isinstance(bytes_, unicode): <NEW_LINE> <INDENT> return bytes_ <NEW_LINE> <DEDENT> if isinstance(bytes_, bytes): <NEW_LINE> <INDENT> if encoding is None: <NEW_LINE> <INDENT> enc = _get_encoding() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enc = encoding <NEW_... | Decode bytes with default locale and return (unicode) string
No-op if parameter is not bytes (assumed unicode string).
:param bytes bytes_: the bytes to decode
:param encoding: encoding to be used, default value is None
Example
-------
>>> decode(b'Südtirol')
u'Südtirol'
>>> decode(u'Südtirol')
u'Südtirol'
>>> dec... | 625941d3097d151d1a223031 |
def healpix_no_sys(nside=512, result_path=None, save_path=None): <NEW_LINE> <INDENT> if os.path.exists(save_path): <NEW_LINE> <INDENT> os.remove(save_path) <NEW_LINE> <DEDENT> results = load_analysis_results(result_path) <NEW_LINE> healpix = HealpixMap(results, nside=nside, n_samples_point=0) <NEW_LINE> healpix.write_m... | Get healpix with no sys error | 625941d3b7558d58953c50eb |
def update_template_variable(self, var_name, description="", auto_convert_var_name=True): <NEW_LINE> <INDENT> if auto_convert_var_name: <NEW_LINE> <INDENT> var_name = self.convert_variable_name(var_name) <NEW_LINE> <DEDENT> if var_name not in self.get_template_variable_names(): <NEW_LINE> <INDENT> var_name = self.conve... | add or update a Template Variable for the Config Template
:param var_name:
:param description:
:param auto_convert_var_name: enables or disables the automatic conversion of the variable names
:return: name of the variable that was updated (automatic conversion) | 625941d3090684286d50eebf |
def utcnow(): <NEW_LINE> <INDENT> return timeutils.utcnow(True) | Better version of utcnow() that returns utcnow with a correct TZ. | 625941d3be8e80087fb20e1a |
def stack(frame, level=-1, dropna=True): <NEW_LINE> <INDENT> N, K = frame.shape <NEW_LINE> if isinstance(frame.columns, MultiIndex): <NEW_LINE> <INDENT> if frame.columns._reference_duplicate_name(level): <NEW_LINE> <INDENT> msg = ("Ambiguous reference to {0}. The column " "names are not unique.".format(level)) <NEW_LIN... | Convert DataFrame to Series with multi-level Index. Columns become the
second level of the resulting hierarchical index
Returns
-------
stacked : Series | 625941d32c8b7c6e89b35999 |
def _tag_block(block, tag): <NEW_LINE> <INDENT> return f'<{tag}\n' + block + f'\n{tag}>\n' | Add the open and close tags to an input block. | 625941d34f6381625f114c14 |
def job_toggl_status(bot, job): <NEW_LINE> <INDENT> toggl = TogglClient(toggl_token) <NEW_LINE> result = toggl.get_summary_results() <NEW_LINE> if result: <NEW_LINE> <INDENT> bot.send_message(job.context, text=u'\U0001f483') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bot.send_message(job.context, text=u'\U0001f4A9') | Get toggl info | 625941d38c3a873295158594 |
def __init__(self, parent, text="", ct_type=0, wnd=None, image=-1, selImage=-1, data=None): <NEW_LINE> <INDENT> self._text = text <NEW_LINE> self._data = data <NEW_LINE> self._children = [] <NEW_LINE> self._parent = parent <NEW_LINE> self._attr = None <NEW_LINE> self._images = [-1, -1, -1, -1] <NEW_LINE> self._images[... | Default class constructor.
For internal use: do not call it in your code!
:param `parent`: the tree item parent (may be ``None`` for root items);
:param `text`: the tree item text;
:param `ct_type`: the tree item kind. May be one of the following integers:
=============== =========================================
`... | 625941d3507cdc57c6306eb6 |
def circular_ease_out(p): <NEW_LINE> <INDENT> return sqrt((2 - p) * p) | Modeled after shifted quadrant II of unit circle | 625941d3cc0a2c11143dd069 |
def dfs(g,u,discovered): <NEW_LINE> <INDENT> for e in g.incident_edges(u,outgoing=True): <NEW_LINE> <INDENT> v = e.opposite(u) <NEW_LINE> if v.element() not in discovered: <NEW_LINE> <INDENT> discovered[v.element()] = e.element() <NEW_LINE> dfs(g,v,discovered) | Perform DFS of the Graph g
starting at Vertex u.
discovered is a dictionary that maps
each vertex to the edge that was used
to discover it during the DFS. | 625941d382261d6c526ab67a |
def test_invalid_date_format(): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> read_stock_data("GOOG", "data/invaliddate.json") | Checks date format in the json file matches 'YYYY-MM-DD' . | 625941d36e29344779a627ea |
def create_security_policy(self): <NEW_LINE> <INDENT> security_policy = vim.host.NetworkPolicy.SecurityPolicy() <NEW_LINE> security_policy.allowPromiscuous = self.sec_promiscuous_mode <NEW_LINE> security_policy.macChanges = self.sec_mac_changes <NEW_LINE> security_policy.forgedTransmits = self.sec_forged_transmits <NEW... | Create a Security Policy
Returns: Security Policy object | 625941d3bde94217f3682fc8 |
def insert(table, **kw): <NEW_LINE> <INDENT> cols, args = zip(*kw.iteritems()) <NEW_LINE> sql = 'insert into `%s` (%s) values (%s)' % (table, ','.join( ['`%s`' % col for col in cols]), ','.join(['?' for i in range(len(cols))])) <NEW_LINE> return _update(sql, *args) | Execute insert SQL.
>>> u1 = dict(id=2000, name='Bob', email='bob@test.org', passwd='bobobob', last_modified=time.time())
>>> insert('user', **u1)
1
>>> u2 = select_one('select * from user where id=?', 2000)
>>> u2.name
u'Bob'
>>> insert('user', **u2)
Traceback (most recent call last):
...
IntegrityError: 1062: Dupli... | 625941d3dd821e528d63b381 |
def upgrade(): <NEW_LINE> <INDENT> if not _check_pkgng(): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> old = list_pkgs() <NEW_LINE> __salt__['cmd.run_all']('{0} upgrade -y'.format(_cmd('pkg'))) <NEW_LINE> __context__.pop('pkg.list_pkgs', None) <NEW_LINE> new = list_pkgs() <NEW_LINE> return __salt__['pkg_resource.f... | Run pkg upgrade, if pkgng used. Otherwise do nothing
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade | 625941d34e4d5625662d45af |
def diffsents(sa, sb): <NEW_LINE> <INDENT> m = len(sa) <NEW_LINE> n = len(sb) <NEW_LINE> la = lb = 0 <NEW_LINE> ra = m - 1 <NEW_LINE> rb = n - 1 <NEW_LINE> while la < m and lb < n: <NEW_LINE> <INDENT> if sa[la] == sb[lb]: <NEW_LINE> <INDENT> la += 1 <NEW_LINE> lb += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break... | tell the different part of a sentence pair | 625941d3d53ae8145f87a447 |
def write_to_read_and_location_dbs(report_db, fin, parent_db, read_group_db, location_db, records_per_txn): <NEW_LINE> <INDENT> first_loop = True <NEW_LINE> done = False <NEW_LINE> time1 = None <NEW_LINE> time2 = None <NEW_LINE> time_in_write_db = 0 <NEW_LINE> read_group_id = 1 <NEW_LINE> curr_read_group = ReadGroup() ... | Read SAM file, populate ReadGroupDb and BucketDb... | 625941d3bd1bec0571d90808 |
def update_logs(self, nlog): <NEW_LINE> <INDENT> if self.data['logs'][0] is None: <NEW_LINE> <INDENT> self.data['logs'][0] = nlog <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data['logs'][0].update(nlog) | Update log | 625941d3283ffb24f3c55ad9 |
def get_mapping(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for attr in sorted(cmds.listAttr(self.mNode)): <NEW_LINE> <INDENT> if attr == 'message': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> data[attr] = getattr(self, attr) <NEW_LINE> <DEDENT> return data | get the current mapping state and return a dict {attr:val, ...} | 625941d3462c4b4f79d1d8a9 |
def test_multitrace_adjoint_dlp_agrees_with_standard_adjoint_dlp_dual(self): <NEW_LINE> <INDENT> const_space = bempp.api.function_space(self._grid, "DUAL", 0) <NEW_LINE> lin_space_bary = bempp.api.function_space(self._grid, "B-P", 1) <NEW_LINE> parameters = bempp.api.common.global_parameters() <NEW_LINE> parameters.ass... | Multitrace ADLP agrees with standard ADLP on dual spaces. | 625941d330dc7b7665901b3e |
def unique_int_gene_from_range(self, solution, gene_index, min_val, max_val, mutation_by_replacement, gene_type, step=None): <NEW_LINE> <INDENT> if self.gene_type_single == True: <NEW_LINE> <INDENT> if step is None: <NEW_LINE> <INDENT> all_gene_values = numpy.arange(min_val, max_val, dtype=gene_type[0]) <NEW_LINE> <DED... | Finds a unique integer value for the gene.
solution: A solution with duplicate values.
gene_index: Index of the gene to find a unique value.
min_val: Minimum value of the range to sample a number randomly.
max_val: Maximum value of the range to sample a number randomly.
mutation_by_replacement: Identical to the self.m... | 625941d373bcbd0ca4b2c24f |
def get_A_r(p, q): <NEW_LINE> <INDENT> assert type(p) == np.ndarray, "p must be nd.array" <NEW_LINE> assert type(q) == np.ndarray, "q must be nd.array" <NEW_LINE> assert p.shape == q.shape, "p and q must have same shape" <NEW_LINE> return _cpp.get_A_r(p, q) | Return the (d-1)-dimensional box defined by the
intersection of the hypercubes of radius equal to
half the Chebyshev distance between p and q and
centered in these points. | 625941d37cff6e4e81117b5e |
def get_restaurant(self, restaurant_ID): <NEW_LINE> <INDENT> self.is_valid_restaurant_id(restaurant_ID) <NEW_LINE> headers = {'Accept': 'application/json', 'user-key': self.user_key} <NEW_LINE> r = (requests.get(base_url + "restaurant?res_id=" + str(restaurant_ID), headers=headers).content) <NEW_LINE> a = ast.literal_e... | Takes Restaurant ID as input.
Returns a dictionary of restaurant details. | 625941d3566aa707497f4740 |
@version(1) <NEW_LINE> def all_name_map(doc): <NEW_LINE> <INDENT> if doc['type'] == "flight": <NEW_LINE> <INDENT> yield doc['name'], None | View: ``flight/all_name``
Emits::
[name] -> null
Sort by flight name.
Show all flights, even those unapproved.
Used where the UI must show all the flights in some usefully searchable
sense, for instance when creating a new flight document based on some old
or unapproved one, or when approving new flight docume... | 625941d315fb5d323cde0cea |
def getset(self, key, value): <NEW_LINE> <INDENT> warnings.warn("This method is invalid, Please do not use...", DeprecationWarning) <NEW_LINE> d = self.execute_command('getset', c(key), pickle_dumps(value)) <NEW_LINE> return pickle_loads(d) | :return: None or **Old Obj** | 625941d3bde94217f3682fc9 |
def initGui(self): <NEW_LINE> <INDENT> icon_path = ':/plugins/AzimuthSwath/icon.png' <NEW_LINE> self.add_action( icon_path, text=self.tr(u'Azimuth Swath Creator'), callback=self.run, parent=self.iface.mainWindow()) | Create the menu entries and toolbar icons inside the QGIS GUI. | 625941d3be7bc26dc91cd7d7 |
def parse(filename: str) -> Dict[str, bool]: <NEW_LINE> <INDENT> file = open(filename, "r", encoding="utf-8") <NEW_LINE> detection_standard = {} <NEW_LINE> for row in file: <NEW_LINE> <INDENT> fields = row.split("\t") <NEW_LINE> acronym = fields[0].strip() <NEW_LINE> valid = fields[1].strip() == 'TRUE' <NEW_LINE> detec... | Parses a .tsv-formatted detection standard into a dictionary.
:param filename:
:return: | 625941d33d592f4c4ed1d244 |
def train(self, data): <NEW_LINE> <INDENT> raise NotImplemented('The train method is not yet implemented') | Train the estimator using the given data.
:param data: The data to use for the training. The data should be split into (evidence, history) with evidence
being the evidence presented and history the history preceding the evidence. In this way on can, for example,
classify unigrams, bigrams and n-grams.
:return: Nothing | 625941d31d351010ab855cf5 |
def on_connected(self, connection): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> if not self.connection: <NEW_LINE> <INDENT> self.reconnecting = True <NEW_LINE> self.reconnect() <NEW_LINE> <DEDENT> channel = self.connection.channel() <NEW_LINE> self.on_channel_open(channel) | Callback on connection. Reconnect if connection dropped. Otherwise it
will open channel and call on_channel_open callback.
:param connection: RabbitMQ connection.
:type connection: :class:`BlockingConnection` | 625941d36fb2d068a760f278 |
def setTags(self, tags): <NEW_LINE> <INDENT> self.data.tags[:] = tags | Clears and sets the service tags.
:type: list<string>
:param: new list of service tags | 625941d3627d3e7fe0d6902a |
def partition_at_level(dendrogram, level): <NEW_LINE> <INDENT> partition = dendrogram[0].copy() <NEW_LINE> for index in range(1, level + 1): <NEW_LINE> <INDENT> for node, community in partition.items(): <NEW_LINE> <INDENT> partition[node] = dendrogram[index][community] <NEW_LINE> <DEDENT> <DEDENT> return partition | Return the partition of the nodes at the given level
A dendrogram is a tree and each level is a partition of the graph nodes.
Level 0 is the first partition, which contains the smallest communities,
and the best is len(dendrogram) - 1.
The higher the level is, the bigger are the communities
Parameters
----------
dend... | 625941d37d847024c06be497 |
def merge_pull_request(number, message=None): <NEW_LINE> <INDENT> upstream_user, upstream_repo, apiurl = get_remote('upstream', 'origin') <NEW_LINE> commit_msg = message or 'ok' <NEW_LINE> data = json.dumps({'commit_message': commit_msg}).encode('utf8') <NEW_LINE> url = apiurl + '/repos/%s/%s/pulls/%d/merge' % ( upstre... | Prompt for a comment and merge specified pull request. | 625941d32ae34c7f2600d30a |
def save(self, model_dir, model_prefix): <NEW_LINE> <INDENT> self.saver.save(self.sess, os.path.join(model_dir, model_prefix)) <NEW_LINE> self.logger.info('save model to {}, prefix is {}.'.format(model_dir, model_prefix)) | 保存模型 | 625941d363f4b57ef00012ef |
def test_formatFlatEventWithMutatedFields(self) -> None: <NEW_LINE> <INDENT> class Unpersistable: <NEW_LINE> <INDENT> destructed = False <NEW_LINE> def selfDestruct(self) -> None: <NEW_LINE> <INDENT> self.destructed = True <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> if self.destructed: <NEW_LINE>... | L{formatEvent} will prefer the stored C{str()} or C{repr()} value for
an object, in case the other version. | 625941d3fb3f5b602dac386e |
def load_mat_file(smer_dir): <NEW_LINE> <INDENT> cdist_list = ['Cdist3.mat','Cdist5.mat','Cdist7.mat','Cdist9.mat'] <NEW_LINE> remove_last_ind = [0,1,1,0] <NEW_LINE> fnames = [smer_dir+cdist for cdist in cdist_list] <NEW_LINE> mat = [] <NEW_LINE> k=0 <NEW_LINE> for fname in fnames: <NEW_LINE> <INDENT> f = h5py.File(fna... | load .mat v7.3 | 625941d3c432627299f04e20 |
def _cluster_cohesion(self, features): <NEW_LINE> <INDENT> row_mean = np.sum(features, axis=0) <NEW_LINE> row_mean /= float(len(features)) <NEW_LINE> sum = 0 <NEW_LINE> for feature in features: <NEW_LINE> <INDENT> sum += np.sum(np.square(row_mean - feature)) <NEW_LINE> <DEDENT> return float(sum) / len(features) | cluster is a list of features. | 625941d357b8e32f52483675 |
def format_decimal(number): <NEW_LINE> <INDENT> attan = Xuanzang.get_attan() <NEW_LINE> return attan.format_decimal(number) | Formats `number` for current locale. | 625941d3925a0f43d254a051 |
def _status(self): <NEW_LINE> <INDENT> return self._get("status") | Sends GET request to get raw status of server | 625941d366656f66f7cbc386 |
def get_feature(self, featname, nocheck = False): <NEW_LINE> <INDENT> featname = basename(featname) <NEW_LINE> dependlook = 0 <NEW_LINE> while featname[-1] == '^': <NEW_LINE> <INDENT> featname = featname[:-1] <NEW_LINE> dependlook += 1 <NEW_LINE> <DEDENT> if not self.features.has_key(featname): <NEW_LINE> <INDENT> rais... | Retrieve a feature object from its name | 625941d3cdde0d52a9e5320d |
def test_004_search(self): <NEW_LINE> <INDENT> query = "id:%s" % (TEST_RUN_ID) <NEW_LINE> lst_tr = TestRun.search(query) <NEW_LINE> self.assertEqual(lst_tr[0].test_run_id, TEST_RUN_ID) | This test does the following:
* Gets a TestRun
* Searches using the same query as the testrun (adding project id)
* verifies that there are number of records returned as are in the
records attribute of the TestRun | 625941d344b2445a3393226e |
def addSubscriptionFilterLanes(self, lanes, noOpposite=False, downstreamDist=None, upstreamDist=None): <NEW_LINE> <INDENT> self._connection._addSubscriptionFilter(tc.FILTER_TYPE_LANES, lanes) <NEW_LINE> if noOpposite: <NEW_LINE> <INDENT> self.addSubscriptionFilterNoOpposite() <NEW_LINE> <DEDENT> if downstreamDist is no... | addSubscriptionFilterLanes(list(integer), bool, double, double) -> None
Adds a lane-filter to the last modified vehicle context subscription (call it just after subscribing).
lanes is a list of relative lane indices (-1 -> right neighboring lane of the ego, 0 -> ego lane, etc.)
noOpposite specifies whether vehicles on ... | 625941d3c4546d3d9de72c0e |
def dguides2guidessam(cfg,dguides): <NEW_LINE> <INDENT> datatmpd=cfg['datatmpd'] <NEW_LINE> dguides=set_index(dguides,'guide: id') <NEW_LINE> guidels=dguides.loc[:,'guide+PAM length'].unique() <NEW_LINE> for guidel in guidels: <NEW_LINE> <INDENT> logging.debug(f"now aligning guides of length {guidel}") <NEW_LINE> guide... | Aligns guides to genome and gets SAM file
step#1
:param cfg: configuration dict
:param dguides: dataframe of guides | 625941d315baa723493c4150 |
def MakeRandomInput(Samples): <NEW_LINE> <INDENT> norms=np.arange(0,6) <NEW_LINE> reds=np.arange(0,8) <NEW_LINE> algs=np.arange(0,22) <NEW_LINE> container=[] <NEW_LINE> for k in range(Samples): <NEW_LINE> <INDENT> np.random.shuffle(norms) <NEW_LINE> np.random.shuffle(reds) <NEW_LINE> np.random.shuffle(algs) <NEW_LINE> ... | Parameters
----------
Samples : int
length of the list.
Returns
-------
container : list
list of lists with integer values. | 625941d350485f2cf553cf74 |
def push(self, x): <NEW_LINE> <INDENT> curMin = self.getMin() <NEW_LINE> if curMin==None or x<curMin: curMin = x <NEW_LINE> self.stack.append((x,curMin)) | :type x: int
:rtype: nothing | 625941d356ac1b37e62643a7 |
def player_v_player(won, player_object, sticks_object): <NEW_LINE> <INDENT> while not won: <NEW_LINE> <INDENT> print("There are {} sticks on the board.".format(sticks_object.get_number_of_sticks())) <NEW_LINE> temp_sticks = player_chooses_sticks(player_object.get_player(), sticks_object.get_number_of_sticks()) <NEW_LIN... | Player vs. Player part of game. | 625941d345492302aab5e49f |
def optimize(self, network_layers: List[AbstractLayer], network_gradients: List[Dict[str, np.ndarray]]): <NEW_LINE> <INDENT> for p, dJdp in zip([layer.params for layer in network_layers], network_gradients): <NEW_LINE> <INDENT> for k in p.keys(): <NEW_LINE> <INDENT> p[k] = p[k] - self.learning_rate * dJdp[k] | Optimize the network parameters, given the gradients of the cost
function wrt the network parameters for one given batch during one
training iteration
:param network_layers: the list of network layers
:param network_gradients: the network parameter gradients as a list of
dictionaries, one dictionary per layer, where ea... | 625941d33d592f4c4ed1d245 |
def is_leaf(self): <NEW_LINE> <INDENT> return True | A leaf is a sequence that does not have sub-sequences. | 625941d3046cf37aa974cf20 |
@cuda.jit <NEW_LINE> def cuda_weighted_stock(weight, x, res): <NEW_LINE> <INDENT> i = cuda.grid(1) <NEW_LINE> if i < x.shape[0]: <NEW_LINE> <INDENT> for j in range(x.shape[1]): <NEW_LINE> <INDENT> res[i, j] = weight[j] * x[i, j] | Calculate the stock multiplied by weight in parallel with GPU | 625941d31f5feb6acb0c4d28 |
def __init__(self, command_prefix='', *args, **kwargs): <NEW_LINE> <INDENT> super(LocalConnection, self).__init__(*args, **kwargs) <NEW_LINE> self._logger = None <NEW_LINE> self.command_prefix = command_prefix <NEW_LINE> self._queue = None <NEW_LINE> return | LocalConnection Constructor
:param:
- `command_prefix`: A prefix to prepend to commands (e.g. 'adb shell') | 625941d3ab23a570cc25035d |
def deleteAddr(self, addr): <NEW_LINE> <INDENT> i=0 <NEW_LINE> notFind=True <NEW_LINE> for (_,_,_,_,elem) in self.Content: <NEW_LINE> <INDENT> if addr==elem: <NEW_LINE> <INDENT> del self.Content[i] <NEW_LINE> notFind=False <NEW_LINE> break <NEW_LINE> <DEDENT> i=i+1 <NEW_LINE> <DEDENT> if notFind: <NEW_LINE> <INDENT> ra... | delete the entry at addr | 625941d321a7993f00bc7ecb |
def get_threadsrootcount( self, per_address_field: Optional[str] = None, per_year: bool = False, ) -> Union[int, dict]: <NEW_LINE> <INDENT> if per_year: <NEW_LINE> <INDENT> dics = {} <NEW_LINE> period_of_activity = self.period_of_activity() <NEW_LINE> years = [dt.year for dt in period_of_activity] <NEW_LINE> years = np... | Identify number conversation threads in mailing list.
Parameters
----------
per_address_field: Aggregate results for each address field, which can
be, e.g., `from`, `send-to`, `received-by`.
per_year : Aggregate results for each year. | 625941d38c0ade5d55d3eb95 |
def get_all_dependencies(self, var_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.all_dependencies_cache[var_name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if var_name not in self.assignments: <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> result = set() <... | Including recursive dependencies. | 625941d31f037a2d8b9463d7 |
def __init__(self, directory, trainset_size=3000): <NEW_LINE> <INDENT> file = "ressources/dataset/CATH_info.txt" <NEW_LINE> self.seq = [] <NEW_LINE> cath = open(file, "r") <NEW_LINE> for line in cath: <NEW_LINE> <INDENT> self.parse(directory + '/' + line.split()[0]) <NEW_LINE> <DEDENT> self.train = self.seq[:trainset_s... | Read the DSSP files and retrieve the amino acid sequences of the chains and their structures
Create a list of the sequences and structures for the training set and a list for the testing set
:param directory: str, destination folder where we can find the dssp files
:param trainset_size: number of proteins in the traini... | 625941d3379a373c97cfad1f |
def impedanceEng(self, frequency, angular=False, latex=True): <NEW_LINE> <INDENT> unit = capacitor.__IMPEDANCE_UNIT if latex else '\Omega' <NEW_LINE> value = self.impedance(frequency, angular=angular) <NEW_LINE> if value == complex(0, float('inf')): <NEW_LINE> <INDENT> return '$\inf$' if latex else '\inf' <NEW_LINE> <D... | Outputs the impedance of the capacitor in enginnering notation,
appending the Ohm unit and using the significant number of digits
defined when the object was created
The latex argument controls the wrapping of the unit. If latex=False,
then the unit has no equation latex marker, '$', wrapping the latex command
for the... | 625941d3009cb60464c6358a |
def varint_type_to_length(varint): <NEW_LINE> <INDENT> if varint == 5: <NEW_LINE> <INDENT> return (6, "") <NEW_LINE> <DEDENT> elif varint == 6 or varint == 7: <NEW_LINE> <INDENT> return (8, "") <NEW_LINE> <DEDENT> elif varint == 8: <NEW_LINE> <INDENT> return (0,0) <NEW_LINE> <DEDENT> elif varint == 9: <NEW_LINE> <INDEN... | Return the number of bytes used by a varint type | 625941d3187af65679ca52f9 |
def percolate(self): <NEW_LINE> <INDENT> for i in range(1, self.size-1): <NEW_LINE> <INDENT> for j in range(1, self.size-1): <NEW_LINE> <INDENT> r = randint(0, 100) <NEW_LINE> if r <= self.p*100: <NEW_LINE> <INDENT> self.percolation[i][j] = 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.percolation | percolate the lattice
:return: the 2D percolation numpy array | 625941d3498bea3a759b9c89 |
def run(self, result, debug=False): <NEW_LINE> <INDENT> fixtures, intercept, host, port, prefix = self._get_intercept() <NEW_LINE> try: <NEW_LINE> <INDENT> with fixture.nest([fix() for fix in fixtures]): <NEW_LINE> <INDENT> if intercept: <NEW_LINE> <INDENT> with interceptor.Urllib3Interceptor( intercept, host, port, pr... | Override TestSuite run to start suite-level fixtures.
To avoid exception confusion, use a null Fixture when there
are no fixtures. | 625941d3b545ff76a8913ff0 |
def put(self, doc_number, notice): <NEW_LINE> <INDENT> raise NotImplementedError | Documentation method. doc_number:String, notice:Dict | 625941d3ac7a0e7691ed42a4 |
def command_output(command, *command_extras, **kwargs): <NEW_LINE> <INDENT> output = [] <NEW_LINE> cwd = kwargs.get("cwd", None) <NEW_LINE> if isinstance(command, six.string_types): <NEW_LINE> <INDENT> args = shlex.split(' '.join([command] + list(command_extras))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args = co... | Get the output from a command | 625941d323849d37ff7b3269 |
def _extend(cls): <NEW_LINE> <INDENT> def make_method(attr): <NEW_LINE> <INDENT> @functools.wraps(getattr(str, attr), ('__name__', '__doc__')) <NEW_LINE> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> s = paste() <NEW_LINE> r = getattr(s, attr)(*args, **kwargs) <NEW_LINE> return self._f(r) <NEW_LINE> <DEDENT> ... | Decorator to add methods to PasteBoard so it can act like a string. | 625941d35fdd1c0f98dc040d |
def bad_request(message): <NEW_LINE> <INDENT> response = jsonify({'error': 'bad request', 'message': message}) <NEW_LINE> response.status_code = 400 <NEW_LINE> return response | 400错误处理程序
:param message:
:return: | 625941d310dbd63aa1bd2d7c |
def extract(i, j, data): <NEW_LINE> <INDENT> return data[:,i], data[:,j] | Extract data vectors
| 625941d39f2886367277aa67 |
def build_file(self, app, location, src=None, name=None): <NEW_LINE> <INDENT> if not self.should_build(app, name): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> request = None <NEW_LINE> response = None <NEW_LINE> content = None <NEW_LINE> path = None <NEW_LINE> urlparams = {} <NEW_LINE> try: <NEW_LINE> <INDENT> if sr... | Build the files for a route in this Builder
| 625941d36e29344779a627eb |
def git_path(path,limit=5): <NEW_LINE> <INDENT> cur_path = path <NEW_LINE> i = 0 <NEW_LINE> while i < limit: <NEW_LINE> <INDENT> if ".git" in os.listdir(cur_path): <NEW_LINE> <INDENT> return os.path.abspath(cur_path) <NEW_LINE> <DEDENT> if os.path.isdir(cur_path): <NEW_LINE> <INDENT> cur_path = os.path.abspath(os.path.... | Searches for GIT root directory in parents directories. | 625941d356b00c62f0f14834 |
def _ParseDefault(self, node): <NEW_LINE> <INDENT> d = _Default() <NEW_LINE> d.remote = self._get_remote(node) <NEW_LINE> d.revisionExpr = node.getAttribute('revision') <NEW_LINE> if d.revisionExpr == '': <NEW_LINE> <INDENT> d.revisionExpr = None <NEW_LINE> <DEDENT> d.destBranchExpr = node.getAttribute('dest-branch') o... | reads a <default> element from the manifest file | 625941d35e10d32532c5f101 |
def tv_show(self, name): <NEW_LINE> <INDENT> name = name.lower() <NEW_LINE> terms = name.split(' ') <NEW_LINE> req = requests.get(URL, timeout=5) <NEW_LINE> soup = BeautifulSoup(req.content, 'html.parser') <NEW_LINE> tv_shows = str( soup('select', {'name': 'SearchString'})).split('</option>') <NEW_LINE> for tv_show in ... | Fetches a show mapping $name returns a $self instance.
Might raise a TVShowNotFound exception | 625941d3adb09d7d5db6c969 |
def overlay_gmm_to_hist(source_dist, figsize=(12, 4), color='red', label='Tumor'): <NEW_LINE> <INDENT> gmm = mixture.GaussianMixture(n_components=2).fit(pd.DataFrame(source_dist)) <NEW_LINE> m1, m2 = gmm.means_ <NEW_LINE> std1, std2 = gmm.covariances_ <NEW_LINE> cutoffs = find_gaussian_intersection(m1, m2, std1, std2) ... | Given a source distribution, fit a 2-component Gaussian mixture model and return plot
:param np.array source_dist: Source distribution
:param tuple(int, int) figsize: Figure size
:return: Fig object and cutoff value
:rtype: float | 625941d316aa5153ce362652 |
def convert_to_celsius(fahrenheit: float) -> float: <NEW_LINE> <INDENT> return (fahrenheit - 32.0) * 5.0 / 9.0 | 화씨와 동일한 섭씨를 반환합니다.
>>> convert_to_celsius(75)
23.88888888888889 | 625941d3a8ecb033257d32a6 |
def populate_interface(self, types=None): <NEW_LINE> <INDENT> for s in self.services: <NEW_LINE> <INDENT> logger.debug("populating '%s.%s (%s)' types..." % (s.__module__, s.__name__, s.get_service_key())) <NEW_LINE> for method in s.public_methods.values(): <NEW_LINE> <INDENT> if method.in_header is None: <NEW_LINE> <IN... | Harvests the information stored in individual classes' _type_info
dictionaries. It starts from function definitions and includes only
the used objects. | 625941d397e22403b379d175 |
def generate_midi(abc_file, midi_file, keep_warn=False, keep_error=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = subprocess.check_output(['abc2midi', abc_file, '-o', midi_file]) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if 'Error in line'... | Save abc_file to midi_file. | 625941d376d4e153a657ed0c |
def listdir(self, where): <NEW_LINE> <INDENT> files = os.listdir(where) <NEW_LINE> return self.clean_files(files, "*.pyc", "__pycache__") | Like os.listdir, but exclude files we don't care about. | 625941d3f7d966606f6aa1e0 |
def test_assigned_user_vocabulary_values(self): <NEW_LINE> <INDENT> voc_name = 'schedule.assigned_user' <NEW_LINE> voc_factory = getUtility(IVocabularyFactory, voc_name) <NEW_LINE> vocabulary = voc_factory(self.task_config) <NEW_LINE> self.assertTrue('schedule.assign_current_user' in vocabulary) <NEW_LINE> term = vocab... | Test some assigned_user values. | 625941d33c8af77a43ae397b |
def OnSaveDefaultFilters(self, inst=None): <NEW_LINE> <INDENT> from terapy.core import filter_file <NEW_LINE> if filter_file==None: <NEW_LINE> <INDENT> pub.sendMessage("set_status_text",inst="No filter file defined. Can't save!") <NEW_LINE> return <NEW_LINE> <DEDENT> if self.bank==None: <NEW_LINE> <INDENT> pub.sendMess... | Save current list of filters as default.
Parameters:
inst - pubsub argument (not used) | 625941d3435de62698dfde27 |
def _build_wiki_url(year: str) -> str: <NEW_LINE> <INDENT> current_year = datetime.datetime.now().year <NEW_LINE> base_url = 'https://en.wikipedia.org/wiki/' <NEW_LINE> if year >= 1960 and year <= current_year: <NEW_LINE> <INDENT> url = base_url + str(year) + '_in_film' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rai... | Builds url for wikipedia 'year in film'
Parameters
----------
year : int
year to scrape movie titles from
Returns
-------
str
formatted url | 625941d3b830903b967e9ae4 |
def unpickledata(filename, log = True): <NEW_LINE> <INDENT> with open(filename, 'rb') as fileobject: <NEW_LINE> <INDENT> dataobject = pickle.load(fileobject) <NEW_LINE> <DEDENT> if log == True: <NEW_LINE> <INDENT> logscript('unpickledata','Unpickle (import serialized) data.', inputfile = filename) <NEW_LINE> <DEDENT> r... | Unpickle (import serialized) data. | 625941d3d486a94d0b98e320 |
def restart(): <NEW_LINE> <INDENT> runcmd('/etc/init.d/apache2 restart') | Redémarrage bourrin | 625941d373bcbd0ca4b2c250 |
def list_vault_ec2_certificate_configurations(self): <NEW_LINE> <INDENT> params = {'list': True} <NEW_LINE> return self._get('/v1/auth/aws-ec2/config/certificates', params=params).json() | GET /auth/aws-ec2/config/certificates?list=true | 625941d38c3a873295158595 |
def get_info(self): <NEW_LINE> <INDENT> pass | Get Driver Information
:return: Dict contains driver information | 625941d33617ad0b5ed680d0 |
def unregister_datasets(self): <NEW_LINE> <INDENT> self.register_datasets(None, None, None) | Unregisters all datasets.
This can be used before re-building the model. | 625941d38e7ae83300e4b1a7 |
def HWC(image): <NEW_LINE> <INDENT> if len(image.shape) == 2: <NEW_LINE> <INDENT> return image[:,:,np.newaxis] <NEW_LINE> <DEDENT> if len(image.shape) == 3: <NEW_LINE> <INDENT> return image.transpose((1,2,0)) <NEW_LINE> <DEDENT> elif len(image.shape) == 4: <NEW_LINE> <INDENT> return image.transpose((0,2,3,1)) <NEW_LINE... | Converts an image (or collection of images) from CHW to HWC format.
HWC format is the image format used by PIL and opencv. | 625941d32eb69b55b151ca8b |
def listAvailableReleases(self, **kwargs): <NEW_LINE> <INDENT> return self.__build_rest_answer(None, ['json', 'xml'], [], "releases", 'info/data', kwargs) | Shows the data releases available on this REST server. May return more than one release (unfrequent non-standard Ensembl configuration).
Return type: None
Valid formats: json, xml
HTTP endpoint: info/data | 625941d331939e2706e4d043 |
def guess_is_tvm_py_library(py_file_path): <NEW_LINE> <INDENT> if (not _is_extension_uncompiled_python_source(py_file_path) and not _is_extension_compiled_python_source(py_file_path)): <NEW_LINE> <INDENT> raise ValueError( "Input file path (%s) is not a Python source file." % py_file_path) <NEW_LINE> <DEDENT> py_file_p... | Guess whether a Python source file is a part of the TVM library.
Special cases:
1) Returns False for unit-test files in the library (*_test.py),
2) Returns False for files under python/debug/examples.
Args:
py_file_path: full path of the Python source file in question.
Returns:
(`bool`) Whether the file is a... | 625941d30383005118ecf7bc |
def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer['portal'] <NEW_LINE> self.installer = api.portal.get_tool('portal_quickinstaller') <NEW_LINE> self.installer.uninstallProducts([config.PROJECT_NAME]) | Custom shared utility setup for tests. | 625941d3cb5e8a47e48b7c83 |
def ObjectMaterialSource(object_ids, source=None): <NEW_LINE> <INDENT> id = rhutil.coerceguid(object_ids, False) <NEW_LINE> if id: <NEW_LINE> <INDENT> rhino_object = rhutil.coercerhinoobject(id, True, True) <NEW_LINE> rc = int(rhino_object.Attributes.MaterialSource) <NEW_LINE> if source is not None: <NEW_LINE> <INDENT>... | Returns or modifies the rendering material source of an object.
Parameters:
object_ids = one or more object identifiers
source [opt] = The new rendering material source. If omitted and a single
object is provided in object_ids, then the current material source is
returned. This parameter is required if mult... | 625941d33cc13d1c6d3c7554 |
def test_error_patch_comment_content_bad_token(self): <NEW_LINE> <INDENT> with self.client() as c: <NEW_LINE> <INDENT> with self.client() as c: <NEW_LINE> <INDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> sess[ 'user_id' ] = 2 <NEW_LINE> sess[ 'token' ] = self.bad_token <NEW_LINE> <DEDENT> c.set_cookie... | Test error patch comment content with forbidden key token will raise error | 625941d310dbd63aa1bd2d7d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.