code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _create_key(path, length): <NEW_LINE> <INDENT> import string <NEW_LINE> from django.utils.crypto import get_random_string <NEW_LINE> key = get_random_string( length, string.ascii_letters + string.digits + '!@#$%^&*(-_=+)' ) <NEW_LINE> with open(path, 'w') as _f: <NEW_LINE> <INDENT> _f.write(key) <NEW_LINE> <DEDENT>... | Creates project "secret key" in settings folder. | 625941cc0c0af96317bb82c9 |
def __secondary_ai_nonaggressive_comparison(self, potential, desired): <NEW_LINE> <INDENT> if potential[1].get_attack() > desired[1].get_money(): <NEW_LINE> <INDENT> self.desired_card_index = self.potential_card_index <NEW_LINE> self.logger_compare_cards("money", "is", potential[1].money, desired[1].money) <NEW_LINE> s... | This routine is used if the computer is set to aggressive
This function relies on two key global variables:
self.desired_card_index
self.potential_card_index
Expected format of desired, potential:
( val, Card() )
where val = integer or "S" | 625941cc3c8af77a43ae3881 |
def associatedWords(word,relations): <NEW_LINE> <INDENT> l=[] <NEW_LINE> for r in relations: <NEW_LINE> <INDENT> l.extend(associatedWordsRelation(word,r)) <NEW_LINE> <DEDENT> return set(l) | Return words related to the given word by one of the given relations. | 625941cceab8aa0e5d26dc39 |
def getPopulationData(country): <NEW_LINE> <INDENT> pop = pd.read_csv("https://raw.githubusercontent.com/technosap/technosap.github.io/master/population.csv") <NEW_LINE> pop = pop[pop["Country Name"]==country] <NEW_LINE> return int(pop[pop["Year"]==pop["Year"].max()].Value) | return dtype(int)
Function to Get Data from WorldBank Population Dataset hosted on GitHub
url://https://github.com/technosap/technosap.github.io/blob/master/population.csv
country: str; Country Name in World Bank Database (see above) | 625941cc01c39578d7e74f1c |
def self_test(): <NEW_LINE> <INDENT> with tf.Session() as sess: <NEW_LINE> <INDENT> print("Self-test for neural translation model.") <NEW_LINE> model = seq2seq_model.Seq2SeqModel(2, [(3, 3)], 10, 2, 5.0, 5, 0.5, 0.99) <NEW_LINE> print("model created") <NEW_LINE> sess.run(tf.initialize_all_variables()) <NEW_LINE> print(... | Test the translation model. | 625941cc925a0f43d2549f58 |
def __len__(self): <NEW_LINE> <INDENT> return int(np.floor(len(self.in_files) / self.batch_size)) | Number of batches per training epoch | 625941cc5166f23b2e1a523a |
def DescribeSmsSignList(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeSmsSignList", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribeSmsSignListRe... | 获取普通短信签名信息
:param request: Request instance for DescribeSmsSignList.
:type request: :class:`tencentcloud.zj.v20190121.models.DescribeSmsSignListRequest`
:rtype: :class:`tencentcloud.zj.v20190121.models.DescribeSmsSignListResponse` | 625941cc7c178a314d6ef541 |
def print_formatted_feature_table(self): <NEW_LINE> <INDENT> fnames = feature_names <NEW_LINE> fvals, fstrings = self.feature_vals(True) <NEW_LINE> print('%-18s %-24s %-2s'%('Feature', 'Meaning','#')) <NEW_LINE> print('%-18s %-24s %-2s' % ('-', '-', '-')) <NEW_LINE> for i in range(len(fnames)): <NEW_LINE> <INDE... | Return all feature values as a string table. | 625941cca17c0f6771cbe131 |
def get( self, resource_provider_namespace, feature_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}' <NEW_LINE> path_format_arguments = { 'resourceProviderNames... | Gets the preview feature with the specified name.
:param resource_provider_namespace: The resource provider namespace
for the feature.
:type resource_provider_namespace: str
:param feature_name: The name of the feature to get.
:type feature_name: str
:param dict custom_headers: headers that will be added to the reque... | 625941cc5fc7496912cc3a5f |
def __init__(self, phrases: List[str], daemon_if_matched=None, case_sensitive=False): <NEW_LINE> <INDENT> self.phrases = phrases <NEW_LINE> if daemon_if_matched: <NEW_LINE> <INDENT> self.daemon_if_matched_fn = daemon_if_matched <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.daemon_if_matched_fn = None <NEW_LINE> <D... | :param phrases:
:param daemon_if_matched: callable to be called if match occured | 625941cc4527f215b584c538 |
def get_side_set_names(self): <NEW_LINE> <INDENT> return self.__ex_get_names('EX_SIDE_SET') | get a list of all side set names ordered by side set *INDEX*;
(see `exodus.get_ids` for explanation of the
difference between side set *ID* and side set *INDEX*)
>>> side_set_names = exo.get_side_set_names()
Returns
-------
<list<string>> side_set_names | 625941ccd4950a0f3b08c430 |
def getspeed(self) -> float: <NEW_LINE> <INDENT> return self.__speed__ | Returns the current speed | 625941cc15baa723493c4056 |
def add_user(self, login, password, role): <NEW_LINE> <INDENT> logger.debug('usersmanager - add user with login=%s' % login) <NEW_LINE> u = self.search_user(login=login) <NEW_LINE> if u is not None: <NEW_LINE> <INDENT> error_str = "login (%s) already exists" % login <NEW_LINE> logger.error('usersmanager - %s' % error_s... | add user | 625941cc009cb60464c63493 |
@pytest.mark.parametrize( "engine, module, input_name, extensions", [ (gromacs, "gromacs/5.1.4", "md.tpr", ["tpr"]), (namd, "namd/2.12", "md.namd", ["namd", "pdb", "psf"]), ], ) <NEW_LINE> @pytest.mark.parametrize("gpu,job_name", ((True, "gpu_job"), (False, None))) <NEW_LINE> def test_write_benchmark(engine, gpu, job_n... | Test that the write_benchmark works as expected. | 625941ccd268445f265b4f4f |
def _repr_defn(self): <NEW_LINE> <INDENT> D = self.domain() <NEW_LINE> ig = self.im_gens() <NEW_LINE> return '\n'.join(['%s |--> %s'%(D.gen(i), ig[i]) for i in range(D.ngens())]) | Return a string describing the images of the generators under this map.
EXAMPLE::
sage: K.<a, b> = NumberField( [x^3 + 2, x^2 + x + 1] )
sage: K.hom(a, K)._repr_defn()
'a |--> a\nb |--> b' | 625941ccd8ef3951e324361f |
@pytest.fixture(scope='module') <NEW_LINE> def testdata(createdb): <NEW_LINE> <INDENT> createdb.connect() <NEW_LINE> ids = [] <NEW_LINE> emails = ('9f1c@4dd6.b647', '90e1@47e7.aff7') <NEW_LINE> for email in emails: <NEW_LINE> <INDENT> dmodel = DummyModel(email=email) <NEW_LINE> createdb.add(dmodel) <NEW_LINE> createdb.... | Create the necessary test data for this module.
:param models.db createdb: pytest fixture for database module
:return list(int): List of ids for DummyModel created. | 625941cc4a966d76dd5510f0 |
def looper(f, delimiter=''): <NEW_LINE> <INDENT> return lambda iterable: delimiter.join([str(f(i)) for i in iterable]) | Returns a function that applies function f to every element of an iterable. | 625941cc23849d37ff7b3171 |
def remove_file(path): <NEW_LINE> <INDENT> if os.path.exists(path) and os.path.isfile(path): <NEW_LINE> <INDENT> os.remove(path) | Remove a path only if it exists and is a file!
| 625941cc50812a4eaa59c403 |
def test_splitting(self): <NEW_LINE> <INDENT> correct_outcome = self.msg['msg']['result']['outcome'] <NEW_LINE> other_outcome = swap_outcome(correct_outcome) <NEW_LINE> outcome = correct_outcome + ',' + other_outcome <NEW_LINE> self.assertTrue(taskotron.taskotron_task_outcome( self.config, self.msg, outcome)) <NEW_LINE... | Multiple values can be specified delimited by a comma | 625941cccb5e8a47e48b7b8c |
def get_atk_dmg(self, weapon, target, pierce=False): <NEW_LINE> <INDENT> if self.hidden: <NEW_LINE> <INDENT> w_dmg = weapon.get_dmg(will_crit=True) <NEW_LINE> dmg = math.floor(w_dmg * self.attack_power / 100) <NEW_LINE> if not pierce: <NEW_LINE> <INDENT> dmg = math.floor(dmg * (100-target.toughness) / 100) <NEW_LINE> <... | Return damage value depending on entities stats and weapon
Damage cannot be 0, minimum damage set to 1
A piercing attack ignores target's toughness.
If attacker is hiding, attack will crit. | 625941cc8a43f66fc4b54147 |
def addView(self, view): <NEW_LINE> <INDENT> if view not in self.views: <NEW_LINE> <INDENT> self.views.append(weakref.ref(view)) | Add a view for the model to keep track of. | 625941cc379a373c97cfac26 |
def cToF(degC): <NEW_LINE> <INDENT> return (degC * 9.0) / 5.0 + 32.0 | Convert temperature from °C to °F
>>> cToF(100)
212.0
>>> cToF(0)
32.0 | 625941cc4a966d76dd5510f1 |
def compute_da_dz(a): <NEW_LINE> <INDENT> list_1 = [float(a[i]*(1-a[j])) if i == j else float(-a[i]*a[j]) for i in range(len(a)) for j in range(len(a))] <NEW_LINE> da_dz = np.asmatrix(list_1).reshape((a.shape[0],a.shape[0])) <NEW_LINE> return da_dz | Compute local gradient of the softmax activations a w.r.t. the logits z.
Input:
a: the activation values of softmax function, a numpy float vector of shape c by 1. Here c is the number of classes.
Output:
da_dz: the local gradient of the activations a w.r.t. the logits z, a float numpy matrix of shape (c by c).... | 625941ccaad79263cf390b22 |
def __init__(self, channel, user_id, banned_rights): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.result = None <NEW_LINE> self.content_related = True <NEW_LINE> self.channel = channel <NEW_LINE> self.user_id = user_id <NEW_LINE> self.banned_rights = banned_rights | :param InputChannel channel:
:param InputUser user_id:
:param ChannelBannedRights banned_rights:
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage. | 625941cc0a366e3fb873e8fb |
def _training_subset_evaluator(self, row): <NEW_LINE> <INDENT> cur_layer = self.tree <NEW_LINE> while cur_layer.get('cutoff'): <NEW_LINE> <INDENT> diff = abs(row[cur_layer['index_col']] - cur_layer['cutoff']) / cur_layer['cutoff'] <NEW_LINE> if row[cur_layer['index_col']] < cur_layer['cutoff'] and diff < self.delta: <N... | Determine if training instance is near the corners of hyperrectangular edges. The reason is because we're only
recording training instances when all their components are near the decision boundary.
:param: row: Single instaance from a training set.
:return: row: if near decision boundary. Otherwise, return None. | 625941ccbf627c535bc132b0 |
def set_accessory(self, accessory_df): <NEW_LINE> <INDENT> cols = ['me_name', 'ae_name', 'ae_weight', 'sets', 'reps'] <NEW_LINE> for col in cols: <NEW_LINE> <INDENT> assert col in accessory_df.columns, f'{col} is missing from df' <NEW_LINE> <DEDENT> assert accessory_df.shape == (16, 5), 'df is not the correct shape' <N... | Loads entries to accessory table
Parameters
----------
accessory_df: obj, pandas df
Raises
------
AssertionError: if accessory_df is not the correct dimensions
and does not have the correct column names | 625941cce5267d203edcdd7f |
def test_defaults(): <NEW_LINE> <INDENT> args = _parse_args(["--input=in", "--output=out"]) <NEW_LINE> assert "in" == args.input <NEW_LINE> assert "out" == args.output <NEW_LINE> assert not args.anonymize_passwords <NEW_LINE> assert not args.anonymize_ips <NEW_LINE> assert args.dump_ip_map is None <NEW_LINE> assert "IN... | Test default parameters. | 625941cc15fb5d323cde0bf1 |
def parse_glassdoor_file(glassdoor_filename): <NEW_LINE> <INDENT> with open(glassdoor_filename, 'r') as f: <NEW_LINE> <INDENT> scrape_dict = json.load(f) <NEW_LINE> <DEDENT> page = re.sub(r'<br ?/>', '', scrape_dict['body']) <NEW_LINE> tree = html.fromstring(page) <NEW_LINE> helpful = tree.xpath('//span[text()="Helpful... | Function to parse the file containing the scrape information into a pandas DataFrame. | 625941cc283ffb24f3c559e3 |
def fit(self, X, y): <NEW_LINE> <INDENT> self.__init_weights(X, y) <NEW_LINE> batch_iters = int(X.shape[0] / self.batch_size) <NEW_LINE> batch_rem = X.shape[0] - self.batch_size * batch_iters <NEW_LINE> for i in range(self.epochs): <NEW_LINE> <INDENT> for j in range(batch_iters): <NEW_LINE> <INDENT> x_batch = X[j * sel... | :param X: input. shape = (number_of_examples, features).
:param y: output. shape = (number_of_examples, classes). | 625941cc9c8ee82313fbb857 |
def dropout(A, dropout_rate): <NEW_LINE> <INDENT> dropout_mask = np.random.binomial([np.ones_like(A)], 1.0 - dropout_rate)[0] <NEW_LINE> A *= dropout_mask / (1.0 - dropout_rate) <NEW_LINE> return A, dropout_mask | Dropout forward propagation with dropout mask returned. | 625941cc711fe17d8254244e |
def crier_ordres(self, personnage): <NEW_LINE> <INDENT> adverse = self.adverse <NEW_LINE> msg = "{} s'écrie : un boulet sur {} !".format( personnage.distinction_audible, adverse.desc_survol) <NEW_LINE> self.navire.envoyer(msg) | On fait crier l'ordre au personnage. | 625941ccd99f1b3c44c67670 |
def printodes(self, out, otype): <NEW_LINE> <INDENT> p, r, s, v= self.parameters, self.reactions, self.species, self.variables <NEW_LINE> if otype == 'python': <NEW_LINE> <INDENT> deliml= '[' <NEW_LINE> delimr= ']' <NEW_LINE> stp= '' <NEW_LINE> inc= 0 <NEW_LINE> <DEDENT> elif otype == 'matlab': <NEW_LINE> <INDENT> deli... | Prints an ordinary differential equation version of the model to be called by a simulation routine.
Arguments
--
out: destination for the output
otype: either 'python' or 'matlab' or 'julia' | 625941cc090684286d50edc7 |
def post(self, post_id): <NEW_LINE> <INDENT> if self.user: <NEW_LINE> <INDENT> content = self.request.get("content") <NEW_LINE> username = self.user.name <NEW_LINE> if content: <NEW_LINE> <INDENT> comment = Comments(content=content, username=username, post_id=int(post_id)) <NEW_LINE> comment.put() <NEW_LINE> self.redir... | Attempts to add a comment to a given post | 625941cce5267d203edcdd80 |
def __init__(self, parent_comm, parent_rank=None, child_comm=None, num_epochs=1, data=None, algo=None, model_builder=None, num_sync_workers=1, verbose=False, monitor=False, custom_objects={}, early_stopping=None, target_metric=None, threaded_validation=False, checkpoint=None, checkpoint_interval=5): <NEW_LINE> <INDENT>... | Parameters:
child_comm: MPI communicator used to contact children | 625941cc1d351010ab855bfd |
def _initialize_variables(self): <NEW_LINE> <INDENT> self.plt_line = None <NEW_LINE> self.der_line = None <NEW_LINE> self.plt_y = None <NEW_LINE> self.plt_x = None <NEW_LINE> self.der_y_orig = None <NEW_LINE> self.der_y = None <NEW_LINE> self.plt_fit_line = None <NEW_LINE> self.der_fit_line = None <NEW_LINE> self.plt_f... | Initializes the variables related to plotting and fitting. | 625941cc26238365f5f0ef4f |
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None, encoding=None): <NEW_LINE> <INDENT> if to: <NEW_LINE> <INDENT> if isinstance(to, str): <NEW_LINE> <INDENT> raise TypeError('"to" argument must be a list or tuple') <NEW_LI... | Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings
(or UTF-8 bytestrings). The SafeMIMEText class will handle any
necessary encoding conversions. | 625941ccbaa26c4b54cb1202 |
def test_comments(self): <NEW_LINE> <INDENT> results = request_saltiness('topcomments') <NEW_LINE> self.assertEqual(len(results), 100) <NEW_LINE> self.assertEqual(type(results), list) <NEW_LINE> self.assertEqual(type(results[0]), dict) <NEW_LINE> return | Testing /topcomments route | 625941ccbde94217f3682ed3 |
def flatten(self, root: TreeNode) -> None: <NEW_LINE> <INDENT> arr = [] <NEW_LINE> if not root: <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> def preorder(node): <NEW_LINE> <INDENT> nonlocal arr <NEW_LINE> if not node: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> arr.append(node.val) <NEW_LINE> preorder(node.le... | Do not return anything, modify root in-place instead. | 625941cccdde0d52a9e53115 |
def test_Count(self): <NEW_LINE> <INDENT> self.assertEqual(self.NumericUnique.Count, 5) <NEW_LINE> self.assertEqual(self.NumericDuplicated.Count, 4) <NEW_LINE> self.assertEqual(self.Empty.Count, 0) <NEW_LINE> self.assertEqual(self.PosNeg.Count, 4) <NEW_LINE> self.assertEqual(self.Constant.Count, 5) | NumberFreqs counts should match hand-calculated values | 625941ccdd821e528d63b28b |
def parse_search(keyword, default_answer_select=2, timeout=2): <NEW_LINE> <INDENT> params = { "lm": "0", "rn": "10", "pn": "0", "fr": "search", "ie": "gbk", "word": keyword.encode("gbk") } <NEW_LINE> url = "https://zhidao.baidu.com/search" <NEW_LINE> resp = requests.get(url, params=params, timeout=timeout) <NEW_LINE> i... | Parse BaiDu zhidao search
only return the first `default_answer_select`
:param keyword:
:param default_answer_select:
:return: | 625941ccbf627c535bc132b1 |
def funcoes_para_treino(self): <NEW_LINE> <INDENT> funcoes = {1: ['funcao_e', self.sequencial_binario_para_funcao_e()], 2: ['funcao_ou', self.sequencial_binario_para_funcao_OU()]} <NEW_LINE> return funcoes | dicionário com o nome da função para treino,
e a sunção que contem a 'tabela verdade', ou valor em binário que representará o valor a ser obtido | 625941ccec188e330fd5a881 |
def run_test(self): <NEW_LINE> <INDENT> self.log.info("Compare responses from getinfo RPC and `dongri-cli getinfo`") <NEW_LINE> cli_get_info = self.nodes[0].cli.getinfo() <NEW_LINE> rpc_get_info = self.nodes[0].getinfo() <NEW_LINE> assert_equal(cli_get_info, rpc_get_info) | Main test logic | 625941cc8c3a87329515849c |
def __new__(cls, vo, vo_info, se, srm_dict, existing_access_protocols=None): <NEW_LINE> <INDENT> if not srm_dict: <NEW_LINE> <INDENT> gLogger.warn("No SRM info for SE %s." % se) <NEW_LINE> raise SkipAccessProtocolError() <NEW_LINE> <DEDENT> version = srm_dict.get('GlueServiceVersion', '') <NEW_LINE> if not version.star... | Constructor. | 625941cc6fece00bbac2d820 |
def createTableDb(self,DatabaseName,column_names): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = self.dataBaseConnection(DatabaseName) <NEW_LINE> c=conn.cursor() <NEW_LINE> c.execute("SELECT count(name) FROM sqlite_master WHERE type = 'table'AND name = 'Good_Raw_Data'") <NEW_LINE> if c.fetchone()[0] ==1: <NEW_LI... | Method Name: createTableDb
Description: This method creates a table in the given database which will be used to insert the Good data after raw data validation.
Output: None
On Failure: Raise Exception | 625941ccc432627299f04d28 |
def get_console_id(self): <NEW_LINE> <INDENT> con_data = self.client.call('console.list') <NEW_LINE> if b'error_message' in con_data: <NEW_LINE> <INDENT> err = con_data[b'error_message'] <NEW_LINE> raise ValueError(err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for c in con_data[b'consoles']: <NEW_LINE> <INDENT> re... | Grabs the first available console ID.
This method is not async because we need to run it at class instantiation.
Additionally, you can't use the Console object until this is done so it's
already a blocking task. This is the only function that raises an error on
failure due to its necessity of completion.
Returns:
... | 625941cc6fb2d068a760f17f |
@plugin_function("logs.setErrorLogVerbosity") <NEW_LINE> def set_error_log_verbosity(value=3, persist=False, session=None): <NEW_LINE> <INDENT> import mysqlsh <NEW_LINE> shell = mysqlsh.globals.shell <NEW_LINE> if session is None: <NEW_LINE> <INDENT> session = shell.get_session() <NEW_LINE> if session is None: <NEW_LIN... | Set the values of Error Log Verbosity.
Args:
value (integer): The optional value of the verbosity (1=ERROR, 2=ERROR, WARNING, 3=ERROR, WARNING, INFORMATION).
The default is to set it to 3.
persist (bool): Persist the change. Default: false.
session (object): The optional session object... | 625941cc73bcbd0ca4b2c158 |
def webmention_endpoint_cache_key(url): <NEW_LINE> <INDENT> domain = util.domain_from_link(url) <NEW_LINE> scheme = urllib.parse.urlparse(url).scheme <NEW_LINE> parts = ['W', scheme, domain] <NEW_LINE> if urllib.parse.urlparse(url).path in ('', '/'): <NEW_LINE> <INDENT> parts.append('/') <NEW_LINE> <DEDENT> return ' '.... | Returns cache key for a cached webmention endpoint for a given URL.
Example: 'W https snarfed.org /'
If the URL is the home page, ie path is / , the key includes a / at the end,
so that we cache webmention endpoints for home pages separate from other pages.
https://github.com/snarfed/bridgy/issues/701 | 625941cc097d151d1a222f3c |
def get_all_transaction_amounts(): <NEW_LINE> <INDENT> db.execute("SELECT cc.state, cc.transaction_amt FROM committee_contributions AS cc WHERE cc.transaction_amt > 0::numeric;") <NEW_LINE> results = db.fetchall() <NEW_LINE> return [{'state': row[0], 'amount': row[1]} for row in results] | Return all transaction amounts with the state that the contribution came from.
For all committee contributions with a transaction_amt greater than zero,
return every transaction amount with the state that the contribution came form.
:return: List of dictionaries with 'state' and 'amount' keys | 625941cc21a7993f00bc7dd1 |
def encrypt_packet(self, seq: int, header: bytes, packet: bytes) -> Tuple[bytes, bytes]: <NEW_LINE> <INDENT> packet = header + self._cipher.encrypt(packet) <NEW_LINE> return packet, self._mac.sign(seq, packet) | Encrypt and sign an SSH packet | 625941ccbe383301e01b5568 |
def function_name(func): <NEW_LINE> <INDENT> return log(level="info", message=_function_name(func)) | Gives the name of the function
Args:
func(func): The function to pass through.
Return:
The function as string. | 625941ccd18da76e235325b8 |
def main(): <NEW_LINE> <INDENT> secuencia = [] <NEW_LINE> secuencia_pares = False <NEW_LINE> while serie: <NEW_LINE> <INDENT> numero = serie.pop(0) <NEW_LINE> if espar(numero): <NEW_LINE> <INDENT> if secuencia_pares: <NEW_LINE> <INDENT> secuencia.append(numero) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(secue... | Función principal. | 625941cc1d351010ab855bfe |
def train( self, files: Union[str, List[str]], vocab_size: int = 30000, min_frequency: int = 2, show_progress: bool = True, special_tokens: List[str] = [], ): <NEW_LINE> <INDENT> trainer = trainers.BpeTrainer( special_tokens=special_tokens, min_frequency=min_frequency, show_progress=show_progress ) <NEW_LINE> if isinst... | Train the model using the given files | 625941cc16aa5153ce36255a |
def capture_samples(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> try: <NEW_LINE> <INDENT> txframe_aligned, tx_ts, tx_median, rxframe_aligned, rx_ts, rx_median = self.capture.get_samples() <NEW_LINE> result['status'] = "ok" <NEW_LINE> result['length'] = len(txframe_aligned) <NEW_LINE> result['tx_median'] = float(tx... | Captures samples and store them in the accumulated samples,
returns a dict with some info | 625941ccac7a0e7691ed41af |
def write_pkey(self, keypath=None): <NEW_LINE> <INDENT> if not keypath: <NEW_LINE> <INDENT> keypath = self.keypath <NEW_LINE> <DEDENT> utils.safe_rename(keypath) <NEW_LINE> temp_fd, temp_name = tempfile.mkstemp(dir=self.output_dir) <NEW_LINE> os.close(temp_fd) <NEW_LINE> os.chmod(temp_name, 0o600) <NEW_LINE> self.keypa... | Write the instance's private key to keypath, backing up keypath to keypath.old if necessary | 625941cc30bbd722463cbea8 |
def get_tree(repo, tree_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if tree_name == index_name: <NEW_LINE> <INDENT> tree = repo.write_tree() <NEW_LINE> <DEDENT> elif tree_name in wc_names: <NEW_LINE> <INDENT> tree = write_wc(repo, wc_names[tree_name]['force'], wc_names[tree_name]['untracked']) <NEW_LINE> <DEDEN... | Get/create a tree-ish to be used for exporting and diffing. Accepts
special keywords for git index and working copies. | 625941cc5fdd1c0f98dc0315 |
def __init__(self, spectrum, voff=0.0, webquery=True, **kwargs): <NEW_LINE> <INDENT> self.Spectrum = spectrum <NEW_LINE> self.minfreq_GHz = self.Spectrum.xarr.umin(units='GHz')*(1+voff/units.speedoflight_kms) <NEW_LINE> self.maxfreq_GHz = self.Spectrum.xarr.umax(units='GHz')*(1+voff/units.speedoflight_kms) <NEW_LINE> s... | Initialize the radio lines class
Requires a spectrum object | 625941cc85dfad0860c3af3d |
def _provision_resource(self, context, weighted_host, request_spec, reservations, kwargs): <NEW_LINE> <INDENT> instance = self.create_instance_db_entry(context, request_spec, reservations) <NEW_LINE> payload = dict(request_spec=request_spec, weighted_host=weighted_host.to_dict(), instance_id=instance['uuid']) <NEW_LINE... | Create the requested resource in this Zone. | 625941cca219f33f34628a4c |
def _compute_avg_and_save(self, buy_num=0, sale_num=0): <NEW_LINE> <INDENT> share_info = DbUtil.query_share_info_by_code(self.menu_qt.share_code_input.text()) <NEW_LINE> record = DbUtil.query_last_business_record(share_info.id) <NEW_LINE> buy_price = float(self.menu_qt.buy_price_input.text()) <NEW_LINE> sale_price = fl... | 计算买入平均价 | 625941cc5fc7496912cc3a60 |
def test_not_found_binary_search(self): <NEW_LINE> <INDENT> pos = binary_search(self.my_list, -1) <NEW_LINE> self.assertTrue(pos == None) | Test that target is NOT found by binary search. | 625941cc2ae34c7f2600d214 |
def test_read_record_from_non_pk_data(self): <NEW_LINE> <INDENT> self.get_valid_record().create(self.db) <NEW_LINE> record = self.get_blank_record() <NEW_LINE> self.assertTrue(record.read({'text1':'ABC'})) <NEW_LINE> self.assertEqual(record.get('id'), 0) <NEW_LINE> self.assertEqual(record.get('text1'), 'ABC') <NEW_LINE... | Test that an record can be read using non primary key data | 625941cc21bff66bcd684a36 |
def get_correction(self, artist, track): <NEW_LINE> <INDENT> return self._call('GET', 'getCorrection', auth=False, artist=artist, track=track) | Use the last.fm corrections data to check whether the supplied track
has a correction to a canonical track
Authorization not required.
http://www.last.fm/api/show/track.getCorrection
:param artist: required
(Required) : The artist name to correct.
:param track: required
(Required) : The track name to correct... | 625941cc462c4b4f79d1d7b3 |
def display_output(self, image): <NEW_LINE> <INDENT> res = self.sess.run(self.output, feed_dict={ self.input_ph: np.expand_dims(image, 0) }) <NEW_LINE> _display_image(image) <NEW_LINE> if self.model_type == "autoencoder": <NEW_LINE> <INDENT> _display_image(res) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(res) <... | Runs an image and shows comparison if autoencoder | 625941cc1f5feb6acb0c4c33 |
def take_step(self): <NEW_LINE> <INDENT> self.logger.debug('Take a step') <NEW_LINE> self.walker.take_step() | Take a step by invoke `walker.take_step()`
Will be called automatically from community's task manager.
Returns: None | 625941cc9b70327d1c4e0eb7 |
def update_text_value(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.SMALL_TIMEOUT, retry=False): <NEW_LINE> <INDENT> if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: <NEW_LINE> <INDENT> timeout = self._get_new_timeout(timeout) <NEW_LINE> <DEDENT> element = self.wait_for_element_visibl... | This method updates an element's text value with a new value.
@Params
selector - the selector with the value to update
new_value - the new value for setting the text field
by - the type of selector to search by (Default: CSS)
timeout - how long to wait for the selector to be visible
retry - if True, use jquery if the s... | 625941cc8c0ade5d55d3ea9d |
def trainIters(input_data, encoder, decoder, encoder_optimizer, decoder_optimizer, n_iters=20, print_every=10): <NEW_LINE> <INDENT> if encoder != None: <NEW_LINE> <INDENT> encoder.train() <NEW_LINE> <DEDENT> decoder.train() <NEW_LINE> start = time.time() <NEW_LINE> print_loss_total = 0 <NEW_LINE> criterion = nn.NLLLoss... | Applies training loop to train models on data | 625941cc5510c4643540f4c7 |
def _enter_halt(self): <NEW_LINE> <INDENT> self.halt = 1 <NEW_LINE> self._dec_pc(1) | enter halt mode | 625941cccc0a2c11143dcf73 |
def __init__(self, minitel, disjoint = False): <NEW_LINE> <INDENT> assert isinstance(minitel, Minitel) <NEW_LINE> assert isinstance(disjoint, bool) <NEW_LINE> self.minitel = minitel <NEW_LINE> self.sequences = [] <NEW_LINE> self.largeur = 0 <NEW_LINE> self.hauteur = 0 <NEW_LINE> self.disjoint = disjoint | Constructeur
:param minitel:
L’objet auquel envoyer les commandes
:type minitel:
un objet Minitel
:param disjoint:
Active le mode disjoint pour les images.
:type disjoint:
un booléen | 625941ccc4546d3d9de72b17 |
def compute_ground_truth(target_path, physical_db_name, vacuum=False, query_filename=None, query_list=None): <NEW_LINE> <INDENT> db_connection = DBConnection(db=physical_db_name) <NEW_LINE> if query_list is not None: <NEW_LINE> <INDENT> queries = query_list <NEW_LINE> <DEDENT> elif query_filename is not None: <NEW_LINE... | Queries database for each query and stores result rows in dictionary.
:param query_filename: where to take queries from
:param target_path: where to store dictionary
:param physical_db_name: name of the database
:return: | 625941cc15fb5d323cde0bf2 |
def _initialize_worker(log_queue, seed): <NEW_LINE> <INDENT> global __is_worker <NEW_LINE> __is_worker = True <NEW_LINE> faulthandler.enable() <NEW_LINE> if seed is not None: <NEW_LINE> <INDENT> init_rng(seed) <NEW_LINE> <DEDENT> if log_queue is not None: <NEW_LINE> <INDENT> h = logging.handlers.QueueHandler(log_queue)... | Initialize a worker process. | 625941cc377c676e9127228b |
def test_ckpt_converter_with_rmsprop(self): <NEW_LINE> <INDENT> self._test_ckpt_converter_with_an_optimizer('RMSProp') | Tests checkpoint converter with RMSProp. | 625941cc627d3e7fe0d68f32 |
def psd(self, frequencies): <NEW_LINE> <INDENT> first_c = 7.05e-48 <NEW_LINE> second_c = 4.8e-51 <NEW_LINE> third_c = 5.33e-52 <NEW_LINE> first = first_c * (1 + (frequencies / self.fp)**2) <NEW_LINE> second = second_c * frequencies.value**-4 / (1+(frequencies/self.fp)**2) <NEW_LINE> third = third_c * frequencies.value... | The power spectrum density of the detector, taken from equation 5 of arxiv:1101.3940. | 625941cc498bea3a759b9b92 |
def corriolisforce(self, q, v, mass_matrix=None): <NEW_LINE> <INDENT> with torch.enable_grad(): <NEW_LINE> <INDENT> if mass_matrix is None: <NEW_LINE> <INDENT> mass_matrix = self.mass_matrix(q) <NEW_LINE> <DEDENT> Mv = mass_matrix @ v.unsqueeze(2) <NEW_LINE> KE = 0.5 * v.unsqueeze(1) @ Mv <NEW_LINE> Cv_KE = torch.autog... | Computes the corriolis matrix times v
| 625941cc6fece00bbac2d821 |
def __init__(self, env, true_mean_list, epsilon, m, hyperpara, fixed_samples, est_H_flag, budget): <NEW_LINE> <INDENT> super().__init__(env, true_mean_list, epsilon, m, hyperpara, fixed_samples, est_H_flag = False) <NEW_LINE> self.budget = budget <NEW_LINE> if self.est_H_flag == False: <NEW_LINE> <INDENT> self.prob_co... | Parameters
----------------------------------------------------------
budget: int
number of total round/budget. | 625941cc4f6381625f114b1d |
def __gen_log_name( self, level ): <NEW_LINE> <INDENT> parent_dir = os.path.dirname( os.path.dirname( os.path.abspath( __file__ ) ) ) <NEW_LINE> name = "log-{}.".format( level.lower( ) ) + time.strftime( '%Y-%m-%d', time.localtime( ) ) + '.log' <NEW_LINE> log_name = os.path.join( os.path.abspath( parent_dir ), "log" ) ... | log文件的绝对路径,log文件以年月日格式命名,如log-error.2017-03-09.log。建立一个父级目录的同级目录log。
:param level:根据日志等级命名不同日志
:return: | 625941cc66656f66f7cbc28e |
def decode(self, text): <NEW_LINE> <INDENT> text = ''.join([ c for c in text if not c in "\x20\r\n\t\x0c\x00" ]) <NEW_LINE> eod = text.find('~>') <NEW_LINE> if eod != -1: <NEW_LINE> <INDENT> test=text[:eod] <NEW_LINE> <DEDENT> l = len(text) <NEW_LINE> out = [] <NEW_LINE> for i in range(0, len(text), 5): <NEW_LINE> <IND... | decode base85-encoded text | 625941cc92d797404e30426d |
def start_learning(self, input_vector, target_vector): <NEW_LINE> <INDENT> output_by_layers = self.feedforward(input_vector) <NEW_LINE> self.synaptic_weights = self.backpropagate(input_vector, output_by_layers, target_vector) | Learning process of input data and model.
Multiplayer perceptron is adopted in this algorithm. | 625941cc76e4537e8c351755 |
def cria(self, mapa=""): <NEW_LINE> <INDENT> Fab = nt("Fab", "objeto imagem") <NEW_LINE> fabrica = { "&": Fab(self.maloc, f"{IMGUR}dZQ8liT.jpg"), "^": Fab(self.indio, f"{IMGUR}UCWGCKR.png"), ".": Fab(self.vazio, f"{IMGUR}npb9Oej.png"), "_": Fab(self.coisa, f"{IMGUR}sGoKfvs.jpg"), "#": Fab(self.tora, f"{IMGUR}0jSB27g.pn... | Fábrica de componentes.
:param mapa: Um texto representando o mapa do desafio. | 625941cc57b8e32f5248357e |
def std_dev(X): <NEW_LINE> <INDENT> return variance(X)**0.5 | Assumes that X is a list of numbers.
Returns the standard deviation of X | 625941ccd10714528d5ffdc6 |
def __init__(self, temboo_session): <NEW_LINE> <INDENT> super(ZipFolder, self).__init__(temboo_session, '/Library/Box/Folders/ZipFolder') | Create a new instance of the ZipFolder Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 625941cc01c39578d7e74f1e |
def delete_remote_stroke(self, stroke): <NEW_LINE> <INDENT> if self.backbuffer: <NEW_LINE> <INDENT> self.backbuffer_valid = False <NEW_LINE> if self.get_window(): <NEW_LINE> <INDENT> self.get_window().invalidate_rect(None, False) | Rerender the part of the widget, where a stroke was deleted
Meant do be called by networking code, when a remote user deleted a stroke.
Positional arguments:
stroke -- The Stroke object, which was deleted. | 625941cc5166f23b2e1a523c |
def InfectiousStop(state): <NEW_LINE> <INDENT> if (np.sum(state==1)==0): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | When all infectious are remove, then we can stop the | 625941cc73bcbd0ca4b2c159 |
def profile(request): <NEW_LINE> <INDENT> print(request.user.username) <NEW_LINE> return render(request, 'toy/profile.html', {'user': request.user}) | Show profile data | 625941cc9c8ee82313fbb858 |
def save(self, filename, header=""): <NEW_LINE> <INDENT> with open(filename, "w") as f: <NEW_LINE> <INDENT> if header: <NEW_LINE> <INDENT> f.write("# " + header + "\n") <NEW_LINE> <DEDENT> f.write(str(len(self.players)) + "\n") <NEW_LINE> for mv in self.history: <NEW_LINE> <INDENT> if type(mv) is tuple: <NEW_LINE> <IND... | Save history of moves to a file.
| 625941ccbe7bc26dc91cd6e3 |
def cross(self, vec): <NEW_LINE> <INDENT> return Vec3(self.y * vec.z - self.z * vec.y, self.z * vec.x - self.x * vec.z, self.x * vec.y - self.y * vec.x) | Return the crossproduct between self and vec. | 625941ccde87d2750b85fe76 |
def load_from_pickle_file(self, f_pop_archive): <NEW_LINE> <INDENT> assert type(f_pop_archive)==str <NEW_LINE> with open(f_pop_archive, 'rb') as my_file: <NEW_LINE> <INDENT> self.__dict__.update(pickle.load(my_file)) <NEW_LINE> <DEDENT> assert self.check_integrity() | Loads a population from a pickle file.
:param f_pop_archive: filename of the pickle file
:type f_pop_archive: str | 625941cc91af0d3eaac9bafc |
def Generate(self, passphrase: str = "") -> bytes: <NEW_LINE> <INDENT> salt = StringUtils.NormalizeNfkd(Bip39SeedGeneratorConst.SEED_SALT_MOD + passphrase) <NEW_LINE> key = CryptoUtils.Pbkdf2HmacSha512(self.m_mnemonic.ToStr(), salt, Bip39SeedGeneratorConst.SEED_PBKDF2_ROUNDS) <NEW_LINE> return key[:Bip39SeedGeneratorCo... | Generate the seed using the specified passphrase.
Args:
passphrase (str, optional): Passphrase, empty if not specified
Returns:
bytes: Generated seed | 625941cc5fc7496912cc3a61 |
def save_config(network, filename): <NEW_LINE> <INDENT> json_model = network.to_json() <NEW_LINE> with open(filename, 'w') as f: <NEW_LINE> <INDENT> f.write(json_model) <NEW_LINE> <DEDENT> return None | Saves a model’s configuration
Args:
- network is the model whose configuration should be saved
- filename is the path of the file that the configuration should be
saved to
Returns: None | 625941cc796e427e537b06a9 |
def train(self, *args): <NEW_LINE> <INDENT> return _cmaxent.MaxentModel_train(self, *args) | train(self, iter=15, method="lbfgs", sigma2=0.0, tol=1E-05)
Train a ME model using selected training method.
Parameters:
iter Specify how many iterations are ... | 625941cc30dc7b7665901a4a |
def print_email_list(): <NEW_LINE> <INDENT> for email in get_unique_emails('duplicate_emails'): <NEW_LINE> <INDENT> print(email) | Print list of emails | 625941ccd4950a0f3b08c432 |
def convrec(r, m): <NEW_LINE> <INDENT> v = [] <NEW_LINE> for keys in [x.split(":") for x in m.keys()]: <NEW_LINE> <INDENT> _v = r.get(keys[0]) <NEW_LINE> for k in keys[1:]: <NEW_LINE> <INDENT> _v = _v.get(k) <NEW_LINE> <DEDENT> v.append(_v) <NEW_LINE> <DEDENT> return v | convrec - convert OANDA candle record.
return array of values, dynamically constructed, corresponding with config in mapping m. | 625941cca4f1c619b28b011d |
def create_bi_sequence_embedding_initialise(inputs_cond, seq_lengths_cond, repr_dim, rnn_scope_cond, last_state_fw, last_state_bw, embedding_matrix, reuse_scope=False, _FLOAT_TYPE=tf.float64): <NEW_LINE> <INDENT> embedded_inputs_cond = tf.nn.embedding_lookup(embedding_matrix, inputs_cond) <NEW_LINE> with tf.variable_sc... | Bidirectional conditional encoding
:param repr_dim: dimension of embeddings
:param vocab_size: number of symbols
:param emb_name: name of embedding matrix
:param rnn_scope: name of RNN scope
:param reuse_scope: reuse the RNN scope or not
:return: return [batch_size, repr_dim] tensor representation of symbols. | 625941cc31939e2706e4cf4e |
def get(self, group): <NEW_LINE> <INDENT> return self._get("/shared_ip_groups/%s" % base.getid(group), "sharedIpGroup") | Get an IP group.
:param group: ID of the image to get.
:rtype: :class:`IPGroup` | 625941cc627d3e7fe0d68f33 |
def get_plane_anchors(self, anchor_scales: np.ndarray): <NEW_LINE> <INDENT> base_anchor = np.array([[0, 0, self.base_size - 1, self.base_size - 1]]) <NEW_LINE> off = self.base_size // 2 - 8 <NEW_LINE> w, h, x_ctr, y_ctr = self._whctrs(base_anchor) <NEW_LINE> size = w * h <NEW_LINE> size_ratios = size / self.anchor_rati... | get anchors per location on feature map.
The anchor number is anchor_scales x anchor_ratios | 625941ccadb09d7d5db6c873 |
def test_is_valid(self): <NEW_LINE> <INDENT> lbs = self._lbs(self._make_bl_ts((1, 1, 0), (0, 1, 1), (1, 1, 0))) <NEW_LINE> self.assertFalse(lbs.is_valid()) <NEW_LINE> self.assertFalse(hasattr(lbs, 'fetch')) <NEW_LINE> lbs = self._lbs(self._make_bl_ts((0, 1, 1), (1, 0, 1), (1, 0, 1)), rsrckey='SM') <NEW_LINE> self.asser... | Whether is_valid. | 625941ccdd821e528d63b28c |
def set_property(node_uri, property_name, property_value, ossos_base=True): <NEW_LINE> <INDENT> property_uri = tag_uri(property_name) if ossos_base else property_name <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> node = client.get_node(node_uri) <NEW_LINE> break <NEW_LINE> <DEDENT> except exceptio... | Sets the value of a property on a node in VOSpace. If the property
already has a value then it is first cleared and then set.
@param node_uri:
@param property_name:
@param property_value:
@param ossos_base:
@return: | 625941cccb5e8a47e48b7b8e |
def make_dirs(dirpath: str) -> None: <NEW_LINE> <INDENT> if not os.path.exists(dirpath): <NEW_LINE> <INDENT> os.makedirs(dirpath) | Make directories for output if necessary | 625941cccc40096d61595a34 |
def install_base_os(self, chroot): <NEW_LINE> <INDENT> LOG.info('*** Preparing image space ***') <NEW_LINE> for image in self.driver.image_scheme.images: <NEW_LINE> <INDENT> LOG.debug('Creating temporary sparsed file for the ' 'image: %s', image.uri) <NEW_LINE> img_tmp_file = bu.create_sparse_tmp_file( dir=CONF.image_b... | Bootstrap a basic Linux system
:param chroot directory where the installed OS can be found
For now only Ubuntu is supported.
Note: the data gets written to a different location (a set of
ext4 images located in the image_build_dir directory)
Includes the following steps
1) create temporary sparse files for all images ... | 625941cce1aae11d1e749d9a |
def sending_handler(instance): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> gevent.sleep(0) <NEW_LINE> try: <NEW_LINE> <INDENT> pdu = instance.outgoing_pdu_queue.get(block=False) <NEW_LINE> pdu_filename = 'entity{0}_tx{1}_{2}.pdu'.format(pdu.header.destination_entity_id, pdu.header.transaction_id, instance.pdu_c... | Handler to take PDUs from the outgoing queue and send. Currently writes PDUs to file.
| 625941cc4c3428357757c40b |
def symbolic_max_plus_identity(d, nvar, ch=None): <NEW_LINE> <INDENT> d = int(d) <NEW_LINE> nvar = int(nvar) <NEW_LINE> V = FreeModule(ZZ, nvar) <NEW_LINE> e = () <NEW_LINE> zero = (V([0]*nvar),) <NEW_LINE> data = [[zero if i == j else e for j in range(d)] for i in range(d)] <NEW_LINE> return SymbolicMaxPlusMatrix(d, n... | Return the ``d x d`` identity matrices on ``nvar`` variables.
EXAMPLES::
sage: from max_plus import *
sage: m = symbolic_max_plus_identity(2, 4)
sage: print(m)
[ 0 -oo ]
[ -oo 0 ]
sage: m.num_vars()
4 | 625941ccbe7bc26dc91cd6e4 |
@app.route("/") <NEW_LINE> def home(): <NEW_LINE> <INDENT> if authenticate(): <NEW_LINE> <INDENT> apps = db.table('appointments').count() <NEW_LINE> deps = db.table('departments').count() <NEW_LINE> pats = db.table('patients').count() <NEW_LINE> docs = db.table('doctors').count() <NEW_LINE> return render_template('inde... | Renders home page with count of each table records
| 625941cc4e4d5625662d44bb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.