code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def distinct_digits(n): <NEW_LINE> <INDENT> v=[] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> v.append(0) <NEW_LINE> <DEDENT> ok=True <NEW_LINE> while (n>0 and ok==True): <NEW_LINE> <INDENT> v[n%10]+=1 <NEW_LINE> if v[n%10]>1: <NEW_LINE> <INDENT> ok=False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n=n//10 <NEW... | Check if a number (n) has only distincts digits.
@input: n - an integer
@output: True - if n has only distincts digits
False - otherwise | 625941e8379a373c97cfafcd |
def start_reactor(virtuals, global_config): <NEW_LINE> <INDENT> sanity_check(global_config) <NEW_LINE> check.prepare_check_modules(global_config) <NEW_LINE> check.initialize(virtuals, global_config) <NEW_LINE> reactor.addSystemEventTrigger("before", "shutdown", check.cleanup, virtuals, global_config) <NEW_LINE> reactor... | Does everything necessary before (and including) starting the reactor. This should be the last thing called when
starting PyDirectord.
:param virtuals: the list containing all virtual services.
:param global_config: the global configuration
:return: nothing | 625941e857b8e32f52483924 |
def store_balance(self, balance): <NEW_LINE> <INDENT> self.balance = balance.data | Stores gripper balance. | 625941e84a966d76dd55149a |
def lap_split(img): <NEW_LINE> <INDENT> with tf.name_scope('split'): <NEW_LINE> <INDENT> lo = tf.nn.conv2d(img, k5x5, [1,2,2,1], 'SAME') <NEW_LINE> lo2 = tf.nn.conv2d_transpose(lo, k5x5*4, tf.shape(img), [1,2,2,1]) <NEW_LINE> hi = img-lo2 <NEW_LINE> <DEDENT> return lo, hi | Split the image into lo and hi frequency components | 625941e876d4e153a657efb8 |
def _getExactMeasures(self, cgroups, returnvalue, wallTime, cpuTime): <NEW_LINE> <INDENT> cpuTime2 = None <NEW_LINE> if CPUACCT in cgroups: <NEW_LINE> <INDENT> cgroupCpuacct = cgroups[CPUACCT] <NEW_LINE> tmp = _readCpuTime(cgroupCpuacct) <NEW_LINE> tmp2 = None <NEW_LINE> while tmp != tmp2: <NEW_LINE> <INDENT> time.slee... | This method tries to extract better measures from cgroups. | 625941e8d18da76e23532962 |
def airborne_position_with_ref(msg, lat_ref, lon_ref): <NEW_LINE> <INDENT> i = oe_flag(msg) <NEW_LINE> d_lat = 360.0/59 if i else 360.0/60 <NEW_LINE> msgbin = util.hex2bin(msg) <NEW_LINE> cprlat = util.bin2int(msgbin[54:71]) / 131072.0 <NEW_LINE> cprlon = util.bin2int(msgbin[71:88]) / 131072.0 <NEW_LINE> j = util.floor... | Decode airborne position with only one message,
knowing reference nearby location, such as previously calculated location,
ground station, or airport location, etc.
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
... | 625941e876d4e153a657efb9 |
def test_exon_object_at_locus(): <NEW_LINE> <INDENT> exons = ensembl.exons_at_locus(3, 41224526, strand="+") <NEW_LINE> for exon in exons: <NEW_LINE> <INDENT> assert exon.gene_name == "CTNNB1", exon.transcript_name <NEW_LINE> assert exon.contig == "3", exon.contig <NEW_LINE> assert exon.strand == "+" <NEW_LINE> assert ... | test_exon_object_at_locus : check properties of exon 4 of CTNNB1 when looked
up by its location on the forward strand of chr3 | 625941e891f36d47f21ac97d |
def get_inverse_variance( self, tube, output_units="uK_CMB", hitmap=None, white_noise_rms=None ): <NEW_LINE> <INDENT> ret = self._load_inverse_variance_map(tube, output_units=output_units) <NEW_LINE> if ret is not None: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> fsky, hitmaps = self._get_requested_hitmaps(tube,... | Get the inverse noise variance in each pixel for the requested tube.
In the noise model, all the splits and all the I,Q,U components have the
same position dependence of the noise variance. Each split just has `nsplits`
times the noise power (or `1/nsplits` the inverse noise variance) and the
Q,U components have 2x ... | 625941e826238365f5f0f2fb |
def birth_years(df): <NEW_LINE> <INDENT> earliest_birth_year = "Earliest birth year: " + str(int(df['Birth Year'].min())) <NEW_LINE> most_recent_birth_year = "Most recent birth year: " + str(int(df['Birth Year'].max())) <NEW_LINE> birth_year_counts = df.groupby('Birth Year')['Birth Year'].count() <NEW_LINE> sorted_birt... | Given a dataframe of bikeshare data, this function returns the oldest
birth year, the most recent birth year, and the most common birth year
Args:
df: dataframe of bikeshare data
Returns:
(list) with three values:
First value: String stating the earliest birth year of anyone
who made a ... | 625941e832920d7e50b2865a |
def test_set_static_dns_clear(self): <NEW_LINE> <INDENT> mock_cmd = MagicMock() <NEW_LINE> with patch.dict(win_ip.__salt__, {"cmd.run": mock_cmd}): <NEW_LINE> <INDENT> self.assertDictEqual( win_ip.set_static_dns("Ethernet", []), {"DNS Server": [], "Interface": "Ethernet"}, ) <NEW_LINE> mock_cmd.assert_called_once_with(... | Test if it set static DNS configuration on a Windows NIC. | 625941e8187af65679ca55a6 |
@cli_app.command("create-admin") <NEW_LINE> @click.option("--app", default="app", help="Your application init directory (package)") <NEW_LINE> @click.option("--appbuilder", default="appbuilder", help="your AppBuilder object") <NEW_LINE> @click.option("--username", default="admin", prompt="Username") <NEW_LINE> @click.o... | Creates an admin user | 625941e81f5feb6acb0c4fd0 |
def enumerateTautomers(mol): <NEW_LINE> <INDENT> smiles = Chem.MolToSmiles(mol,isomericSmiles=True) <NEW_LINE> tauts = enumerate_tautomers_smiles(smiles) <NEW_LINE> return [Chem.MolFromSmiles(x) for x in tauts] | Get all of the Tautomers of a given molecule
:param mol: the input molecule
:return: a list of Tautomers | 625941e80fa83653e465743e |
def is_open(self): <NEW_LINE> <INDENT> if self.cups_conn: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Checks whether the CUPS connection is open.
| 625941e8283ffb24f3c55d83 |
@contextlib.contextmanager <NEW_LINE> def make_dir_writable(directory): <NEW_LINE> <INDENT> uid = os.getuid() <NEW_LINE> try: <NEW_LINE> <INDENT> sb = directory.stat() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if sb.st_uid != uid or sb.st_mode & 0o700 == ... | Context-manager that sets write permission on a directory.
This assumes that the directory belongs to you. If the u+w permission
wasn't set, it gets set in the context, and restored to what it was when
leaving the context. u+x also gets set on all the directories leading to
that path. | 625941e88c0ade5d55d3ee45 |
def test_15(self): <NEW_LINE> <INDENT> m = MyModel(int_type=1).save() <NEW_LINE> d = MyDepModel(pk1=10, foreign=m).save() <NEW_LINE> self.assertTrue( hasattr( m, 'mydepmodel_set') ) <NEW_LINE> self.assertTrue( d in m.mydepmodel_set.all() ) | test *_set on foreign model | 625941e8c4546d3d9de72ebe |
def get_sunburst(self): <NEW_LINE> <INDENT> from browse.management.commands.buildsunburst import build_sunburst <NEW_LINE> self.sort_query_set() <NEW_LINE> return build_sunburst(self.query_set) | Return a taxonomy sunburst from the results. This is a dictionary taxonomy tree | 625941e87cff6e4e81117e0c |
def new_ratings(winner_elo, loser_elo): <NEW_LINE> <INDENT> winner_expected = expected_score(winner_elo, loser_elo) <NEW_LINE> loser_expected = expected_score(loser_elo, winner_elo) <NEW_LINE> winner_updated = update_rating(winner_elo, 1, winner_expected) <NEW_LINE> loser_updated = update_rating(loser_elo, 0, loser_exp... | This function is the "user" facing function, which takes the winner and loser's ratings,
assuming no ties are possible, and returns the two updated ratings. | 625941e8d99f1b3c44c67a0d |
def _convert(self, value, new_units): <NEW_LINE> <INDENT> converter = self.converters.get(type(value), None) <NEW_LINE> if converter is not None: <NEW_LINE> <INDENT> value = converter(value, new_units) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = "Unable to find converter for type %s" % type(value) <NEW_LINE> ra... | Find a converter for value and convert it to new_units.
If no converter is found for the type, raise ConversionError | 625941e8cdde0d52a9e534bd |
def test_basic(self): <NEW_LINE> <INDENT> form = TextForm() <NEW_LINE> self.assertEqual(form.fields["name"].widget.attrs, {}) <NEW_LINE> self.assertEqual(form.fields["university"].widget.attrs, {}) <NEW_LINE> form = parsley_form(TextForm()) <NEW_LINE> self.assertAttrsEqual(form.fields["name"].widget.attrs, { "data-pars... | Tests that parsleyfy will add data-parsley-required for required fields,
but not for required=False fields for CharFields | 625941e863d6d428bbe44977 |
def calc_K_l(Km1, Cm1, lm2, r, A, Am1, sanity_checks=False): <NEW_LINE> <INDENT> D = A.shape[2] <NEW_LINE> q = A.shape[0] <NEW_LINE> qm1 = Am1.shape[0] <NEW_LINE> K = sp.zeros((D, D), dtype=A.dtype) <NEW_LINE> Hl = sp.zeros_like(K) <NEW_LINE> for s in xrange(qm1): <NEW_LINE> <INDENT> Am1sh = Am1[s].conj().T <NEW_LINE> ... | Calculates the K_left using the recursive definition.
This is the "bra-vector" K_left, which means (K_left.dot(r)).trace() = <K_left|r>.
In other words, K_left ~ <K_left| and K_left.conj().T ~ |K_left>. | 625941e88e71fb1e9831dc2e |
def control_3_7_ensure_log_metric_disabling_scheduled_delete_of_kms_cmk(cloudtrails): <NEW_LINE> <INDENT> result = False <NEW_LINE> failReason = "" <NEW_LINE> offenders = [] <NEW_LINE> offenders_links = [] <NEW_LINE> control = "3.7" <NEW_LINE> description = "Ensure a log metric filter and alarm exist for disabling or s... | Summary
Returns:
TYPE: Description | 625941e89f2886367277ad10 |
def batch_parzen(x, mu, sigma, batch_sz = 20): <NEW_LINE> <INDENT> num_test = x.shape[0] <NEW_LINE> num_batches = num_test // batch_sz <NEW_LINE> lld = [] <NEW_LINE> for i in range(num_batches): <NEW_LINE> <INDENT> batch = x[i * batch_sz : (i+1)*batch_sz,:] <NEW_LINE> batch = np.transpose(a=batch[np.newaxis,:],axes=(1,... | :param x: the whole test data set instead of a single sample
:param mu: generated samples
:param sigma: bandwidth
:return: the mean log-likelihood | 625941e856ac1b37e626464d |
def clims(lim1, lim2): <NEW_LINE> <INDENT> lim = [None, None] <NEW_LINE> if lim1[0] < lim2[0]: <NEW_LINE> <INDENT> lim[0] = lim1[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lim[0] = lim2[0] <NEW_LINE> <DEDENT> if lim1[1] > lim2[1]: <NEW_LINE> <INDENT> lim[1] = lim1[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ... | takes two pairs of limits and returns one pair of common limts
:param lim1:
:param lim2:
:return:
>>> clims([0, 4], [1, 3])
[0, 4]
>>> clims([1, 4], [0, 3])
[0, 4]
>>> clims([1, 3], [0, 4])
[0, 4]
>>> clims([0, 3], [1, 4])
[0, 4]
>>> clims([0, 3], [0, 4])
[0, 4]
>>> clims([1, 4], [0, 4])
[0, 4]
>>> clims([0, 4], [0, 4... | 625941e876e4537e8c351afd |
def _get_value_from_conf_file(self, kind, converter=None): <NEW_LINE> <INDENT> file_name = self.get_conf_file_name(kind) <NEW_LINE> msg = ('Error while reading %s') <NEW_LINE> try: <NEW_LINE> <INDENT> with open(file_name, 'r') as f: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return converter(f.read()) if converter el... | A helper function to read a value from one of the state files. | 625941e8adb09d7d5db6cc13 |
def lookup_by_id(self, id, table="monster"): <NEW_LINE> <INDENT> logger.warning("lookup_by_id is deprecated. Use JSONDatabase.database") <NEW_LINE> self.lookup(id, table) | This is a legacy method from using the sqlite database. You should
do this instead by calling JSONDatabase.database["monster"][id]
:param id: The monster ID or technique ID to look up.
:type id: Integer
:rtype: List
:returns: A list of monsters or techniques | 625941e8cad5886f8bd2745f |
@app.route('/source/<id>') <NEW_LINE> def articles(id): <NEW_LINE> <INDENT> articles = get_articles(id) <NEW_LINE> title = f'{id}' <NEW_LINE> return render_template('articles.html',title = title, articles = articles) | View article page function that returns the news details page and its data | 625941e8566aa707497f49e9 |
def is_synced(self): <NEW_LINE> <INDENT> if "id" in self and self["id"]: <NEW_LINE> <INDENT> eventgroup = EventGroup(self["id"]) <NEW_LINE> if self.test_operation_equal(eventgroup): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Test if data on chain matches lookup
| 625941e899fddb7c1c9de815 |
def show_credit(story, credit): <NEW_LINE> <INDENT> if not story: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> style = None <NEW_LINE> if re.search(',', credit): <NEW_LINE> <INDENT> [credit, style] = re.split(r',\s*', credit) <NEW_LINE> <DEDENT> if credit.startswith('any:'): <NEW_LINE> <INDENT> target = credit[4:]... | For showing the credits on the search results page.
As far as I can tell Django template filters can only take
one argument, hence the icky splitting of 'credit'. Suggestions
on a better way welcome, as clearly I'm abusing the Django filter
convention here. | 625941e81f037a2d8b946684 |
def test_init(self): <NEW_LINE> <INDENT> student_map = HashMap(10, hash_function_1) <NEW_LINE> self.assertEqual(10, student_map.capacity) <NEW_LINE> self.assertEqual(0, student_map.size) <NEW_LINE> self.assertEqual(hash_function_1, student_map._hash_function) <NEW_LINE> for bucket in student_map._buckets: <NEW_LINE> <I... | Checks that the hash_table initializes correctly, if __init__ is provided, ignore | 625941e8c432627299f050d0 |
def GetDdcDivisionByNumber(id): <NEW_LINE> <INDENT> if isinstance(id, (int, long)): <NEW_LINE> <INDENT> id = "%03d" % id <NEW_LINE> <DEDENT> return _MAP_DIVISION_BY_NUMBER.get(id) | Gets the (id, description) tuple for the specified DDC id.
Args:
id: The three-digit string ID corresponding to a Dewey Decimal Division. | 625941e8b5575c28eb68e48b |
def add_peer_nodes(self, node): <NEW_LINE> <INDENT> self.__peer_nodes.add(node) <NEW_LINE> self.save_data() | Add a new node to peer node network
Arguments:
:node : The node url which should be added | 625941e80a50d4780f66731d |
def already_in_translation_file(self, root_name): <NEW_LINE> <INDENT> check_list = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for name in ('translation_file', 'translation_file_bad'): <NEW_LINE> <INDENT> self.shared_dict['translate_lock'].acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> content_translation_file = np.genfromtx... | Check, if the root_name already exists in the translation file.
root_name - root_name
Returns:
True, if root_name in translation file. | 625941e84527f215b584c8d9 |
def quarantie_affect(t, i, j): <NEW_LINE> <INDENT> assert t != P.times <NEW_LINE> if not P.police: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> P.KB.append([-literals('quarantie', t, i, j), literals('Q', t +1, i, j)]) <NEW_LINE> P.KB.append([-literals('quarantie', t, i, j), -literals('U', t +1, i, j)]) <NEW_LINE> P.K... | quarantie affects | 625941e8d6c5a102081444d5 |
def get_paths(pipe_num): <NEW_LINE> <INDENT> level = adj.getrow(pipe_num) <NEW_LINE> dists = [level.toarray().ravel()] <NEW_LINE> for j in range(adj.shape[1]): <NEW_LINE> <INDENT> dists.append(level.multiply(adj.getcol(j).transpose()).toarray().ravel()) <NEW_LINE> <DEDENT> dists = np.concatenate(dists) <NEW_LINE> zeros... | Input pipe_num (int):
Output associated_pipes (dict of pipes and distances) | 625941e8e8904600ed9f23bb |
def create(self, **options): <NEW_LINE> <INDENT> self._item_id = self._create(**options) | Creates canvas element | 625941e88da39b475bd65400 |
def entropy(data_classes, base=2): <NEW_LINE> <INDENT> if not isinstance(data_classes, pd.core.series.Series): <NEW_LINE> <INDENT> raise AttributeError('input array should be a pandas series') <NEW_LINE> <DEDENT> classes = data_classes.unique() <NEW_LINE> N = len(data_classes) <NEW_LINE> ent = 0 <NEW_LINE> for c in cla... | Computes the entropy of a set of labels (class instantiations)
:param base: logarithm base for computation
:param data_classes: Series with labels of examples in a dataset
:return: value of entropy | 625941e8ff9c53063f47c678 |
def report_header(self, set_A, set_B, method): <NEW_LINE> <INDENT> if method == 'MDC': <NEW_LINE> <INDENT> operation_str = "Determination Molecular Diagnostic Characters" <NEW_LINE> <DEDENT> elif method == "potential_MDC_only": <NEW_LINE> <INDENT> operation_str = "Determination POTENTIAL Molecular Diagnostic Characters... | Write header of the report
Parameters
----------
set_A : list of :class:`fastachar.fasta_logic.Sequence`
Sequence list A
set_B : list of :class:`fastachar.fasta_logic.Sequence`
Sequence list B
method : str
Description of operation method | 625941e8004d5f362079a7b7 |
def stdev(data, *, data_mean=None, data_is_sample: bool = False): <NEW_LINE> <INDENT> data = tuple(map(string_to_number, data)) <NEW_LINE> if data_is_sample: <NEW_LINE> <INDENT> result = statistics.stdev(data, xbar=data_mean) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = statistics.pstdev(data, mu=data_mean) <... | Return the standard deviation of the data (assuming the data represents an entire population). | 625941e8377c676e9127262e |
def getItemTotalStock(self,barcode): <NEW_LINE> <INDENT> return self.session.query(func.sum(Item.stock)).filter(Item.barcode==barcode).first()[0] | Get the total stock count of this item.
:param barcode: The barcode to look for total stock count.
:type barcode: str
:returns: int | 625941e8627d3e7fe0d692d9 |
def adapt(self, items, names, outer_i): <NEW_LINE> <INDENT> output_dim = self.cells[-1].hidden_size <NEW_LINE> for k, v in items: <NEW_LINE> <INDENT> v = self.search_space.eval_(v, **locals()) <NEW_LINE> if isinstance(v, (list, tuple)) and len(v) > 1: <NEW_LINE> <INDENT> key = f'{"_".join(names[:-1])}_{len(v)}_{k}s' <N... | Creates layers and updates embedding index given search space dimensions.
Args:
items (iterable): iterable of tuples corresponding to search space dimensions
names (list): names of search spaces up to current level
outer_i (int): outer iteration ordinal (used in recursion, `None` on depth `0`)
Returns: | 625941e891af0d3eaac9bea4 |
@contextlib.contextmanager <NEW_LINE> def pid_context(pid_filename=None): <NEW_LINE> <INDENT> pid_filename = pid_filename or DEFAULT_PID_FILENAME <NEW_LINE> if os.path.exists(pid_filename): <NEW_LINE> <INDENT> contents = open(pid_filename).read(16) <NEW_LINE> log.warning('pid_filename %s already exists with contents %s... | For the duration of this context manager, put the PID for this process into
`pid_filename`, and then remove the file at the end. | 625941e871ff763f4b549b1b |
def get_description(self,name_f): <NEW_LINE> <INDENT> return str(self.morphisms[name_f]) | Gets a string description of a given morphism.
Parameters
----------
name_f: a string representing the name of the morphism
Returns
-------
A string representing the corresponding morphism | 625941e85fcc89381b1e1b49 |
def write_inventory_to_lines(self, inv): <NEW_LINE> <INDENT> raise NotImplementedError(self.write_inventory_to_lines) | Produce a simple lines representation of an inventory.
Note: this is a *whole inventory* operation, and should only be used
sparingly, as it does not scale well with large trees.
The requirement for the contents of the string is that it can be passed
to read_inventory_from_lines and the result is an identical invento... | 625941e8046cf37aa974d1ca |
def get_logger_name(name): <NEW_LINE> <INDENT> LOG_NAME = "%s.%s" % (LOGGER_ROOT, name) <NEW_LINE> return LOG_NAME | get logger name | 625941e8cb5e8a47e48b7f2a |
def create_serialized_scalar_operation_from_proto(proto, one_arg_optimization=False, one_result_optimization=False): <NEW_LINE> <INDENT> import cloudpickle <NEW_LINE> scalar_operation = create_scalar_operation_from_proto( bytes(b % 256 for b in proto), one_arg_optimization, one_result_optimization) <NEW_LINE> return cl... | The CPython extension included in proto does not support initialization multiple times, so we
choose the only interpreter process to be responsible for initialization and proto parsing. The
only interpreter parses the proto and serializes function operations with cloudpickle. | 625941e850485f2cf553d223 |
def process_exception(self, request, exception, spider): <NEW_LINE> <INDENT> request_proxy_index = request.meta["proxy_index"] <NEW_LINE> if isinstance(exception, self.DONT_RETRY_ERRORS): <NEW_LINE> <INDENT> if request_proxy_index > self.fixed_proxy - 1 and self.invalid_proxy_flag: <NEW_LINE> <INDENT> if self.proxyes[r... | 处理由于使用代理导致的连接异常 | 625941e829b78933be1e5b2d |
def getPieceTableValue(self): <NEW_LINE> <INDENT> return self.piece_table[self.position] | Returns the piece's square table value based on the position of the piece. | 625941e8eab8aa0e5d26dfe1 |
@metrics.route("/magen/v2/counters/<uuid>/", methods=["PUT"]) <NEW_LINE> def update_one_counter(metric_uuid): <NEW_LINE> <INDENT> pass | Update one counter
:param metric_uuid: string uuid of counter
:return: JSON response
:rtype: RestServerApis obj | 625941e8e76e3b2f99f3ac8b |
def _show_article(bot: TeleBot, message: Message, botan_key: str) -> None: <NEW_LINE> <INDENT> sent = bot.send_message(message.chat.id, "Введите артикул интересующего товара:") <NEW_LINE> bot.register_next_step_handler(sent, _find_articles) <NEW_LINE> for id in chats_with_searching_articles: <NEW_LINE> <INDENT> if id =... | Entry point for article stores. | 625941e83317a56b8693a0d4 |
def __getitem__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.getArray().__getitem__(*args, **kwargs) | Calls the ``__getitem``__ method of the ``numpy`` array. | 625941e8fb3f5b602dac3b1f |
def get_regions(self): <NEW_LINE> <INDENT> regions = map(mkt.regions.REGIONS_CHOICES_ID_DICT.get, self.get_region_ids(worldwide=True)) <NEW_LINE> return sorted(regions, key=lambda x: x.slug) | Return regions, e.g.:
[<class 'mkt.constants.regions.BR'>,
<class 'mkt.constants.regions.CA'>,
<class 'mkt.constants.regions.UK'>,
<class 'mkt.constants.regions.US'>,
<class 'mkt.constants.regions.WORLDWIDE'>] | 625941e8ad47b63b2c50a406 |
def connectSignals(self): <NEW_LINE> <INDENT> self.connect(self, SIGNAL("currentIdChanged(int)"), self.pageChanged) | Connects the signals with the related slots. | 625941e8b57a9660fec33d12 |
def logging_debug(*args): <NEW_LINE> <INDENT> if LOGGING_DEBUG: <NEW_LINE> <INDENT> logging.debug(*args) | wrapper to log to debug a vector | 625941e8de87d2750b86021f |
def _getConvertFileNum(self): <NEW_LINE> <INDENT> result = commands.getoutput('adb shell ls /sdcard/Sharing/| wc -l') <NEW_LINE> return result | Get convert file number | 625941e82c8b7c6e89b35c45 |
def get_team_by_id(self, team_id): <NEW_LINE> <INDENT> url = config.get("base_url") + "/cxrestapi/auth/Teams/{id}".format(id=team_id) <NEW_LINE> r = requests.get( url=url, headers=authHeaders.auth_headers, verify=config.get("verify") ) <NEW_LINE> if r.status_code == OK: <NEW_LINE> <INDENT> item = r.json() <NEW_LINE> te... | Args:
team_id(int):
Returns:
Team | 625941e815fb5d323cde0f9e |
def _serialize_unindentation(self, chars, norm_indent_len_diff): <NEW_LINE> <INDENT> s = '' <NEW_LINE> i = 0 <NEW_LINE> for j, c in enumerate(chars): <NEW_LINE> <INDENT> if c == ' ': <NEW_LINE> <INDENT> s += '<' <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> elif c == '\t': <NEW_LINE> <INDENT> in_tab_pos = i % self.TAB_SIZE ... | Serializes an unindentation string into an HTML representation.
This will show every space as "<", and every tab as "|<------".
In the case of tabs, we display as much of it as possible (anchoring
to the left-hand side) given the space we have within the tab
boundary. | 625941e85fcc89381b1e1b4a |
def dup_cancel(f, g, K, include=True): <NEW_LINE> <INDENT> return dmp_cancel(f, g, 0, K, include=include) | Cancel common factors in a rational function `f/g`.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.euclidtools import dup_cancel
>>> f = ZZ.map([2, 0, -2])
>>> g = ZZ.map([1, -2, 1])
>>> dup_cancel(f, g, ZZ)
([2, 2], [1, -1]) | 625941e8baa26c4b54cb15a2 |
def download_file(url, handle_unknown_callback): <NEW_LINE> <INDENT> def unknown(): <NEW_LINE> <INDENT> handle_unknown_callback(url) <NEW_LINE> <DEDENT> def callback(data): <NEW_LINE> <INDENT> _amazon_callback(data, unknown) <NEW_LINE> <DEDENT> if url.startswith('file://'): <NEW_LINE> <INDENT> path = url[7:] <NEW_LINE>... | Deals with turning an .amz file into some real downloads. | 625941e83317a56b8693a0d5 |
def _random_function(self, random_state): <NEW_LINE> <INDENT> return random_state.rand | private function that generates a random function. This function is
usually added on the loss function in order to pertubate sampling.
Parameters
----------
random_state: numpy.random.RandomState
Returns
-------
random_func: random_state.rand | 625941e8dd821e528d63b62d |
def is_my_own(self, instance): <NEW_LINE> <INDENT> return instance.get('from') == self.username and instance.get('bridge') is None | Returns true if the update is from this client, taking bridging into account | 625941e87c178a314d6ef8ee |
def shouldSave(self, plug, result): <NEW_LINE> <INDENT> if plug in [self.falloff, self.maxDistanceUScale, self.maxDistanceVScale]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return OpenMayaMPx.MPxNode.shouldSave(self, plug, result) | https://pazrot3d.blogspot.com/2018/10/maya-api-ramp-attribute-bug.html | 625941e8ff9c53063f47c679 |
def main(args): <NEW_LINE> <INDENT> P, S, M = read_inlinksgraph(args.fname) <NEW_LINE> N = len(P) <NEW_LINE> d = 0.85 <NEW_LINE> PR = {} <NEW_LINE> eps = 1e-3 <NEW_LINE> iter = 1 <NEW_LINE> prev_ppl = None <NEW_LINE> all_ppl = [] <NEW_LINE> for p in P: <NEW_LINE> <INDENT> PR[p] = 1/N <NEW_LINE> <DEDENT> while True: <NE... | // P is the set of all pages; |P| = N
// S is the set of sink nodes, i.e., pages that have no out links
// M(p) is the set of pages that link to page p
// L(q) is the number of out-links from page q
// d is the PageRank damping/teleportation factor; use d = 0.85 as is typical | 625941e8d53ae8145f87a6ef |
def img_to_array(img, data_format=None): <NEW_LINE> <INDENT> if not isinstance(img, Image.Image): <NEW_LINE> <INDENT> return img <NEW_LINE> <DEDENT> if data_format is None: <NEW_LINE> <INDENT> data_format = DATA_FORMAT <NEW_LINE> <DEDENT> if data_format not in {'channels_first', 'channels_last'}: <NEW_LINE> <INDENT> ra... | Converts a PIL Image instance to a Numpy array.
!!Copy from Keras!!
Assure the array's ndim is 3 | 625941e8cdde0d52a9e534be |
def wrap_in_middleware( app, global_conf, **local_conf ): <NEW_LINE> <INDENT> conf = global_conf.copy() <NEW_LINE> conf.update(local_conf) <NEW_LINE> debug = asbool( conf.get( 'debug', False ) ) <NEW_LINE> app = httpexceptions.make_middleware( app, conf ) <NEW_LINE> log.debug( "Enabling 'httpexceptions' middleware" ) <... | Based on the configuration wrap `app` in a set of common and useful middleware. | 625941e8596a897236089f42 |
def exit_dfu(address = 0x08000000): <NEW_LINE> <INDENT> set_address(address) <NEW_LINE> __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, None, __TIMEOUT) <NEW_LINE> try: <NEW_LINE> <INDENT> if get_status() != __DFU_STATE_DFU_MANIFEST: <NEW_LINE> <INDENT> print("Failed to reset device") <NEW_LINE> <DEDENT> us... | Exit DFU mode, and start running the program. | 625941e8a219f33f34628deb |
def to_bool(value): <NEW_LINE> <INDENT> cases = { '0': False, 'false': False, 'no': False, '1': True, 'true': True, 'yes': True, } <NEW_LINE> value = value.lower() if isinstance(value, basestring) else value <NEW_LINE> return cases.get(value, bool(value)) | Converts human boolean-like values to Python boolean.
Falls back to :class:`bool` when ``value`` is not recognized.
:param value: the value to convert
:returns: ``True`` if value is truthy, ``False`` otherwise
:rtype: bool | 625941e8a934411ee3751b1c |
def update_position(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.last_pos = self.getTime() <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> pass | Update the player position, when possible | 625941e8e8904600ed9f23bc |
def __init__(self): <NEW_LINE> <INDENT> super(RiceOutputs, self).__init__() <NEW_LINE> self.out_msed = pd.Series(name="out_msed", dtype="object") <NEW_LINE> self.out_vw = pd.Series(name="out_vw", dtype="object") <NEW_LINE> self.out_mass_area = pd.Series(name="out_mass_area", dtype="object") <NEW_LINE> self.out_cw = pd.... | Class representing the outputs for Rice | 625941e8aad79263cf390ed0 |
def sigcont_handler(*a): <NEW_LINE> <INDENT> md = gconf.log_metadata <NEW_LINE> logging.shutdown() <NEW_LINE> lcls = logging.getLoggerClass() <NEW_LINE> lcls.setup(label=md.get('saved_label'), **md) <NEW_LINE> pid = os.getpid() <NEW_LINE> os.kill(-pid, signal.SIGUSR1) | Re-init logging and send group kill signal | 625941e8fbf16365ca6f6655 |
def count_project_samples(self,project_igf_id,only_active=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results_data = self.fetch_project_samples( project_igf_id=project_igf_id, only_active=only_active, output_mode='dataframe') <NEW_LINE> count = len(results_data.index) <NEW_LINE> return count <NEW_... | A method for counting total number of samples for a project
:param project_igf_id: A project id
:param only_active: Toggle for including only active projects, default is True
:returns: A int sample count | 625941e85e10d32532c5f3ad |
def generateOutputDataSlotGetFunction(self, slot, time=''): <NEW_LINE> <INDENT> return slot.getCodeRepresentation() | :param DataSlot.DataSlot slot:
:param str time:
:rtype: str | 625941e8b5575c28eb68e48c |
def previous(self): <NEW_LINE> <INDENT> if self.span == 'seconds': <NEW_LINE> <INDENT> start = self.start - datetime.timedelta(seconds=1) <NEW_LINE> end = self.end - datetime.timedelta(seconds=1) <NEW_LINE> <DEDENT> elif self.span == 'minutes': <NEW_LINE> <INDENT> start = self.start - datetime.timedelta(minutes=1) <NEW... | Return a new TimePeriod representing the period
immediately prior to this one. | 625941e85510c4643540f860 |
def acos(space, x): <NEW_LINE> <INDENT> return math1(space, math.acos, x) | acos(x)
Return the arc cosine (measured in radians) of x. | 625941e855399d3f05588b3f |
def setRuntimeParameters(self, method, precomputed_query): <NEW_LINE> <INDENT> actual_runtime_parameters = self.main_all_doc_methods[method].get("runtime_parameters") <NEW_LINE> if isinstance(actual_runtime_parameters, list): <NEW_LINE> <INDENT> return {x: 1 for x in self.main_all_doc_methods[method]["runtime_parameter... | Sets the runtime parameters to use depending on the method and query | 625941e8fff4ab517eb2f8c7 |
def test_redeploy_explicit_api(): <NEW_LINE> <INDENT> manifest = { 'Transform': 'AWS::Serverless-2016-10-31', 'Resources': { 'ExplicitApi': { 'Type': "AWS::Serverless::Api", "Properties": { "StageName": "prod", "DefinitionUri": "s3://mybucket/swagger.json?versionId=123" } } } } <NEW_LINE> original_deployment_ids = tran... | Test to verify that we will redeploy an API when Swagger document changes
:return: | 625941e8287bf620b61d3ee9 |
def modify(self, table, row): <NEW_LINE> <INDENT> pass | Modify an existing row.
Return 2-tuple consisting of a Result object and a new
Context object.
Arguments:
table -- the table name.
row -- a dictionary with every column name and their corresponding
(possibly) modified values. | 625941e8d8ef3951e32439c6 |
@patch('foremast.consts.validate_key_values') <NEW_LINE> def test_parse_security_group(values): <NEW_LINE> <INDENT> values.return_value = 'g1' <NEW_LINE> assert {'': ['g1']} == _generate_security_groups('default_ec2_securitygroups') <NEW_LINE> values.return_value = 'g1,g2' <NEW_LINE> assert {'': ['g1', 'g2']} == _gener... | Parse out security group entries | 625941e8e64d504609d74cc8 |
def _sample_initial_state(self): <NEW_LINE> <INDENT> self.initial_state = dict() <NEW_LINE> for k in self._all_initial_state_distribs[self.region].keys(): <NEW_LINE> <INDENT> self.initial_state[k] = self._all_initial_state_distribs[self.region][k].sample() <NEW_LINE> <DEDENT> self.initial_state['A0'] = self.initial_sta... | Samples an initial model state from its distribution (Dirac distributions if self.stochastic is False). | 625941e88a349b6b435e85fb |
def ChannelActivityList(state, candidates, airtime_threshold_ms): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> for group in candidates: <NEW_LINE> <INDENT> for primary_freq in group: <NEW_LINE> <INDENT> count_20 = count_40 = count_80 = 0 <NEW_LINE> busy_20 = busy_40 = busy_80 = 0.0 <NEW_LINE> for bss in state.seen_... | For each candidate, yields information about activity/overlap.
Args:
state: a wgdata.State representing the AP's view of the world.
candidates: the output of LegalCombos().
airtime_threshold_ms: the minimum time a channel must have been observed
before it can have nonzero activity.
Yields:
A ChannelActivi... | 625941e81d351010ab855fa3 |
def normalize_matrix(matrix): <NEW_LINE> <INDENT> normalized = tf.keras.utils.normalize(matrix) <NEW_LINE> return normalized | For given matrix (or dataset of matrices), returns matrix
(or dataset of matrices) with normalized values (float in range 0-1)
Args:
matrix - matrix (or dataset of matrices)
Returns:
normalized matrix | 625941e89c8ee82313fbbbff |
def dir_changed(self): <NEW_LINE> <INDENT> self.folder = self.folderEdit.text() | modify the saving folder | 625941e80fa83653e4657440 |
def test_group_rooms_existing_group_right(self): <NEW_LINE> <INDENT> mapobj = Map('Map') <NEW_LINE> r1 = mapobj.add_room_at(1, 1, 'Room 1') <NEW_LINE> r2 = mapobj.add_room_at(2, 2, 'Room 2') <NEW_LINE> r3 = mapobj.add_room_at(3, 3, 'Room 3') <NEW_LINE> mapobj.group_rooms(r2, r3) <NEW_LINE> self.assertEqual(len(mapobj.g... | Test adding a room to a group when the righthand room is already
in a group but the other side isn't | 625941e81f5feb6acb0c4fd1 |
def test_digest_pieced(self): <NEW_LINE> <INDENT> msg = "" <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> msg += "Line%d test test test\n" % i <NEW_LINE> <DEDENT> expected = b"" <NEW_LINE> for i in [20, 21, 22, 60, 61, 62]: <NEW_LINE> <INDENT> expected += ("Line%dtesttesttest" % i).encode("utf8") <NEW_LINE> <DEDEN... | Test pieced messages (lines > 4) in the digest process | 625941e87d43ff24873a312c |
def loadImage(self, ImageFilePath, MaskFilePath): <NEW_LINE> <INDENT> normalize = self.settings.get('normalize', False) <NEW_LINE> interpolator = self.settings.get('interpolator') <NEW_LINE> resampledPixelSpacing = self.settings.get('resampledPixelSpacing') <NEW_LINE> preCrop = self.settings.get('preCrop', False) <NEW_... | Preprocess the image and labelmap.
If ImageFilePath is a string, it is loaded as SimpleITK Image and assigned to image,
if it already is a SimpleITK Image, it is just assigned to image.
All other cases are ignored (nothing calculated).
Equal approach is used for assignment of mask using MaskFilePath.
If normalizing is... | 625941e8f8510a7c17cf9b88 |
def update_password(self, user: UserMixin, password_hash: str) -> bool: <NEW_LINE> <INDENT> return self._password_updater(user, password_hash) | Updates the password of the given user.
Arguments:
user (UserMixin): The user whose password is to be updated.
password_hash (str): The new password hash of the user.
Returns:
`True` if the password has been updated successfully, `False` otherwise. | 625941e8283ffb24f3c55d85 |
def _create_dataframe(self): <NEW_LINE> <INDENT> return pandas.read_csv( self.source_csv, names=['ticker', 'description'] ) | Retrieves tickers and descriptions from WIKI-datasets-codes.csv | 625941e80383005118ecfa69 |
def make_adder(n): <NEW_LINE> <INDENT> def adder(k): <NEW_LINE> <INDENT> return k + n <NEW_LINE> <DEDENT> return adder | Return a function that takes one argument k and return k + n.
>>> add_three = make_adder(3)
>>> add_three(4)
7 | 625941e867a9b606de4a833f |
def pasteImage(img, bigim, posn, whiteBackground = False, color = None): <NEW_LINE> <INDENT> pixdata = img.load() <NEW_LINE> width, height = img.size <NEW_LINE> bw,bh = bigim.size <NEW_LINE> mainpixdata = bigim.load() <NEW_LINE> for y in xrange(height): <NEW_LINE> <INDENT> for x in xrange(width): <NEW_LINE> <INDENT> if... | Pastes a small image onto a bigger image at the coordinates specified by posn. | 625941e8236d856c2ad44c69 |
@match_args_return <NEW_LINE> def pt_from_CT(SA, CT): <NEW_LINE> <INDENT> return _gsw_ufuncs.pt_from_ct(SA, CT) | Calculates potential temperature (with a reference sea pressure of
zero dbar) from Conservative Temperature. This function uses 1.5
iterations through a modified Newton-Raphson (N-R) iterative solution
procedure, starting from a rational-function-based initial condition
for both pt and dCT_dpt.
Parameters
----------
... | 625941e824f1403a92600feb |
def search(self, query, page=1, limit=10, department_opts=None, group_opts=None, role_opts=None, with_custom_data=False): <NEW_LINE> <INDENT> if department_opts: <NEW_LINE> <INDENT> if not isinstance(department_opts, list): <NEW_LINE> <INDENT> raise AuthingWrongArgumentException('department_opts must be a list') <NEW_L... | 搜索用户
Args:
query (str): 查询语句
page (int): 页码数,从 1 开始,默认为 1 。
limit (int): 每页个数,默认为 10 。
department_opts (list): 限制条件,用户所在的部门
group_opts (list): 限制条件,用户所在的分组
role_opts (list): 限制条件,用户所在的角色
with_custom_data (bool, optional): 是否获取自定义数据,默认为 false;如果设置为 true,将会在 customData 字段返回用户的所有自定义数据。 | 625941e815baa723493c4401 |
def get_severity(self): <NEW_LINE> <INDENT> return INFORMATION | :return: severity.INFORMATION , all information objects have the same
level of severity. | 625941e8c4546d3d9de72ec0 |
def get_user_details(self): <NEW_LINE> <INDENT> user = {} <NEW_LINE> try: <NEW_LINE> <INDENT> user_div = self._soup.find("div", {"class":"user-summary"}).contents <NEW_LINE> for content in user_div: <NEW_LINE> <INDENT> if content.name=="a" and content.attrs["class"][1] == "user-avatar": <NEW_LINE> <INDENT> user["name"]... | Get the user and his/her instagram url from the page
:return: A dictionary of user_name and user_url | 625941e897e22403b379d424 |
def _make_commit_if_dirty(repo, repo_dir): <NEW_LINE> <INDENT> if repo.is_dirty(): <NEW_LINE> <INDENT> git_cli = repo.git <NEW_LINE> git_cli.add('-A') <NEW_LINE> added_files = ADDED_FILE_REGEX.findall(git_cli.status()) <NEW_LINE> if added_files: <NEW_LINE> <INDENT> sparse_checkout_path = os.path.join(repo_dir, '.git', ... | Makes a commit with message 'WIP' if there are changes. | 625941e8d58c6744b42580e6 |
def gcd(a: int, b: int) -> int: <NEW_LINE> <INDENT> while b != 0: <NEW_LINE> <INDENT> remainder = a % b <NEW_LINE> a = b <NEW_LINE> b = remainder <NEW_LINE> <DEDENT> return a | Return the greatest common divisor between two numbers. | 625941e8d58c6744b42580e7 |
def build_config(): <NEW_LINE> <INDENT> custom = False <NEW_LINE> config = { "branch": "stable", "branches": conf.BRANCHES, "cache_dir": os.environ.get("XDG_CACHE_DIR"), "config_file": conf.CONFIG_FILE, "country_pool": [], "custom_file": conf.CUSTOM_FILE, "method": "rank", "work_dir": conf.WORK_DIR, "mirror_file": conf... | Get config informations
:returns: config, custom
:rtype: tuple | 625941e826068e7796caf16f |
def test_ruby_project(self): <NEW_LINE> <INDENT> clean_failed_app(self, self.params.get('openshift_python_PROJECT')) <NEW_LINE> new_project(self, self.params.get('openshift_WC_PORT'), self.params.get('openshift_USERNAME'), self.params.get('openshift_PASSWORD'), self.params.get('openshift_ruby_PROJECT'), self.params.get... | Runs sanity on openshift s2i ruby source
1. login
2. new project create
3. App deploy using the registry from config file
4. Validation for successful deployment
5. Routing
6. Pod status
7. project delete
8. logout
Args:
self (object): Object of the current method
openshift_URL (... | 625941e8d486a94d0b98e5cf |
@cached_function <NEW_LINE> def steiner_quadruple_system(n, check = False): <NEW_LINE> <INDENT> n = int(n) <NEW_LINE> if not ((n%6) in [2, 4]): <NEW_LINE> <INDENT> raise ValueError("n mod 12 must be equal to 2 or 4") <NEW_LINE> <DEDENT> elif n == 4: <NEW_LINE> <INDENT> return ((0,1,2,3),) <NEW_LINE> <DEDENT> elif n == ... | Returns a Steiner Quadruple System on `n` points.
INPUT:
- ``n`` -- an integer such that `n\equiv 2,4[12]`
- ``check`` (boolean) -- whether to check that the system is a Steiner
Quadruple System before returning it (`False` by default)
EXAMPLES::
sage: designs.steiner_quadruple_system(4)
((0, 1, 2, 3),)
... | 625941e8851cf427c661a993 |
def store_digits(n): <NEW_LINE> <INDENT> rest = Link(n%10) <NEW_LINE> n = n // 10 <NEW_LINE> while n > 0: <NEW_LINE> <INDENT> rest = Link(n%10, rest) <NEW_LINE> n = n // 10 <NEW_LINE> <DEDENT> return rest | Stores the digits of a positive number n in a linked list.
>>> s = store_digits(1)
>>> s
Link(1)
>>> store_digits(2345)
Link(2, Link(3, Link(4, Link(5))))
>>> store_digits(876)
Link(8, Link(7, Link(6)))
>>> # a check for restricted functions
>>> import inspect, re
>>> cleaned = re.sub(r"#.*\n", '', re.sub(r'"{3}[\s\S]... | 625941e8adb09d7d5db6cc15 |
def permute(self, nums): <NEW_LINE> <INDENT> return [list(elem) for elem in permutations(nums)] | :type nums: List[int]
:rtype: List[List[int]] | 625941e807f4c71912b1190d |
def enter(self, enter_time=None): <NEW_LINE> <INDENT> enter_time = enter_time if enter_time else datetime.datetime.utcnow() <NEW_LINE> self.entered = enter_time | Set the contract stage's enter time
Arguments:
enter_time: A datetime for this stage's enter attribute.
Defaults to utcnow. | 625941e8c432627299f050d2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.