code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def chrome_default_user_data(): <NEW_LINE> <INDENT> if sys.platform.startswith('linux'): <NEW_LINE> <INDENT> root_dir = '~/.config/google-chrome/' <NEW_LINE> <DEDENT> elif sys.platform == 'darwin': <NEW_LINE> <INDENT> root_dir = '~/Library/Application Support/Google/Chrome/' <NEW_LINE> <DEDENT> elif sys.platform == 'wi... | Get the default path to the user data directory for Google Chrome.
Returns:
Path to user's data directory | 625941f6dd821e528d63b80a |
def createBlockedUsersDict(inputFile): <NEW_LINE> <INDENT> import csv <NEW_LINE> blocks = {} <NEW_LINE> with inputFile: <NEW_LINE> <INDENT> blockLogReader = csv.reader(inputFile, delimiter='\t', quotechar='"') <NEW_LINE> for [timestamp, blockedUserName, _, _, _] in blockLogReader: <NEW_LINE> <INDENT> try: <NEW_LINE> <I... | Reads a block log CSV, cleans the comment, reorders the output and writes
it to disk according to outputFile.
This method naïvely parses the date in ISO 8601 format. It refrains from
using python-dateutil. However, this has no impact on the data processing as
the time differences between block and revision timestamps d... | 625941f682261d6c526abb10 |
def resize_image_mask(image, mask2D, size_nuc_ideal=None, num_nuc_on_edge_ideal=16, size_patch=256, min_size_nuclei=8, min_rescale_factor=1, max_rescale_factor=8): <NEW_LINE> <INDENT> size_nuclei = np.sqrt(np.sum(mask2D > 0) * 1.0 / (len(np.unique(mask2D))-1)) <NEW_LINE> size_image = np.sqrt(np.prod(image.shape[:2])) <... | rescale image based on the relative size of image and nuclei,
so that len_image_edge / len_nuclei is close to r_size_img_nuc_ideal | 625941f63346ee7daa2b33d9 |
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app('testing') <NEW_LINE> self.app_context = self.app.app_context() <NEW_LINE> self.app_context.push() <NEW_LINE> self.client = self.app.test_client() | Creates a version of the Flask application for testing | 625941f6d268445f265b54d6 |
def update_subset_scorers(scorer_list, estimations, labels, tagmask): <NEW_LINE> <INDENT> for tid, scorer in enumerate(scorer_list): <NEW_LINE> <INDENT> subset_idx = torch.nonzero(tagmask[:, tid]).squeeze(dim=1) <NEW_LINE> subset_estimations = estimations[subset_idx] <NEW_LINE> subset_labels = labels[subset_idx] <NEW_L... | Add the output and label of one minibatch to the subset scorer objects.
This function is only used by tasks that need evalute results on tags,
and should be called every minibatch when task.scorer are updated.
Parameters:
scorer_list: a list of N_tag scorer object
estimations: a (bs, *) tensor, model estimatio... | 625941f644b2445a339326f8 |
def test_datetime(self): <NEW_LINE> <INDENT> from calibre.utils.date import parse_date <NEW_LINE> from calibre.db.tables import c_parse, UNDEFINED_DATE, _c_speedup <NEW_LINE> for raw in ('2013-07-22 15:18:29+05:30', ' 2013-07-22 15:18:29+00:00', '2013-07-22 15:18:29', '2003-09-21 23:30:00-06:00'): <NEW_LINE> <INDENT> ... | Test the reading of datetimes stored in the db | 625941f61f5feb6acb0c51b0 |
def sort_title_info(raw_title, raw_type, raw_sec_type) -> dict: <NEW_LINE> <INDENT> split = type_dict[raw_type]["split"] <NEW_LINE> raw_title_group = re.findall(r"\[[^\]]*\]", raw_title) <NEW_LINE> return_dict = { "raw_type": raw_type, "raw_second_type": raw_sec_type, "type": type_dict[raw_type]["cat"], "second_type": ... | the function (sort_title_info) will sort title to post_data due to clone_torrent's category
But some may wrong,Due to inappropriate search_title | 625941f6442bda511e8bea75 |
def pc_nproduced_avg(self): <NEW_LINE> <INDENT> return _analog_swig.probe_avg_mag_sqrd_c_sptr_pc_nproduced_avg(self) | pc_nproduced_avg(probe_avg_mag_sqrd_c_sptr self) -> float | 625941f6656771135c3ebedd |
def run_html_review(self, istr=''): <NEW_LINE> <INDENT> if self.html_rev_style not in g_html_review_styles: return '' <NEW_LINE> if self.html_rev_style == 'none': return '' <NEW_LINE> if self.ssr_uvars == '': return '' <NEW_LINE> needed = [ 'Xvfb' ] <NEW_LINE> missing = [] <... | run apqc_make_tcsh.py | 625941f6b545ff76a891447c |
@when(parsers.parse('my target is less than {percent:d}% of the {reference}')) <NEW_LINE> @when(parsers.parse('my target is max {percent:d}% of the {reference}')) <NEW_LINE> def modify_reference(the_data, percent, reference): <NEW_LINE> <INDENT> percent /= 100 <NEW_LINE> the_data[reference] = the_data[reference] * perc... | modify the reference rmse with a percentage vlue | 625941f68e71fb1e9831de0d |
def chk_statement(ctx, stmt, grammar, canonical=False): <NEW_LINE> <INDENT> n = len(ctx.errors) <NEW_LINE> _chk_stmts(ctx, stmt.pos, [stmt], None, grammar, canonical) <NEW_LINE> return n == len(ctx.errors) | Validate `stmt` according to `grammar`.
Marks each statement in the hierearchy with stmt.is_grammatically_valid,
which is a boolean.
Return True if stmt is valid, False otherwise. | 625941f6656771135c3ebede |
def decrypt_with_key(self, enckey): <NEW_LINE> <INDENT> cleartxt = crypto.dataDecrypt(self.cipherAlgo, self.hashAlgo, self.encrypted, enckey, self.iv, self.rounds) <NEW_LINE> self.pwdhash = cleartxt[:self.shaHashLen] <NEW_LINE> self.ntlm = cleartxt[self.shaHashLen:self.shaHashLen + self.ntHashLen].rstrip(b"\x00") <NEW_... | Decrypts this credhist entry using the given encryption key. | 625941f607f4c71912b11aec |
def _save_outputs(self, xml): <NEW_LINE> <INDENT> file_urls = get_file_urls(xml) <NEW_LINE> outputs = [] <NEW_LINE> log.info('Saving outputs to:') <NEW_LINE> for url in file_urls: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_name = re.search('fileName=([^&]+)', url).group(1) <NEW_LINE> <DEDENT> except Exception: <... | Download the output files and save them to the specified outputs directory.
:param xml: XML Response Document [String]
:return: List of local output file paths | 625941f60c0af96317bb884e |
def get_gamespec(srcdir, game_version, dont_pickle): <NEW_LINE> <INDENT> if game_version[0].game_id in ("ROR", "AOE1DE", "AOC", "HDEDITION", "AOE2DE"): <NEW_LINE> <INDENT> filepath = srcdir.joinpath(game_version[0].media_paths[MediaType.DATFILE][0]) <NEW_LINE> <DEDENT> elif game_version[0].game_id == "SWGB": <NEW_LINE>... | Reads empires.dat file. | 625941f673bcbd0ca4b2c6dc |
def compa_grade(self,x,found,cols,hyp,depcol,condition): <NEW_LINE> <INDENT> conflicts = self.get_conflicts(x,found,cols) <NEW_LINE> if conflicts != []: <NEW_LINE> <INDENT> xresolved, ysolved = self.compile_features(x,found,conflicts,hyp,depcol,condition) <NEW_LINE> return xresolved <NEW_LINE> <DEDENT> else: <NEW_LINE>... | Keep compatibility after a prediction task using positions of conflicts
to resolve dataset dependencies
:param x: input dataset
:param found: targets in production
:param cols (type(cols) == list): list of columns equal to the number.
of targets that are not relevant for prediction. Eg.: [0,3,3]
:param hyp: a string ... | 625941f67b180e01f3dc4e55 |
def get_thermostat_temperature(self, root): <NEW_LINE> <INDENT> thermostat_log_id = self.get_point_log_id(root, "thermostat") <NEW_LINE> if thermostat_log_id: <NEW_LINE> <INDENT> measurement = self.get_measurement_from_point_log(root, thermostat_log_id) <NEW_LINE> value = float(measurement) <NEW_LINE> return value <NEW... | Get the target temperature from the thermostat. | 625941f623849d37ff7b36f1 |
def init(): <NEW_LINE> <INDENT> conn = get_db() <NEW_LINE> cur = conn.cursor() <NEW_LINE> f = open('app/db/init.sql', 'r') <NEW_LINE> text = f.read() <NEW_LINE> f.close() <NEW_LINE> commands = text.split(';') <NEW_LINE> for command in commands: <NEW_LINE> <INDENT> if command != '': <NEW_LINE> <INDENT> cur.execute(comma... | Initializes the db | 625941f650812a4eaa59c981 |
def setUp(self): <NEW_LINE> <INDENT> self.store = store.Store() <NEW_LINE> self.location = objects.Thing( store=self.store, name=u"Test Location", description=u"Location for testing.", proper=True) <NEW_LINE> locContainer = objects.Container.createFor(self.location, capacity=1000) <NEW_LINE> self.world = ImaginaryWorld... | Set up a store with a location, a player and an observer. | 625941f673bcbd0ca4b2c6dd |
def mlp(self, input_shape): <NEW_LINE> <INDENT> input = Input(shape=input_shape) <NEW_LINE> x = Dense(256, activation='relu')(input) <NEW_LINE> x = Dropout(0.3)(x) <NEW_LINE> x = Dense(512, activation='relu')(x) <NEW_LINE> x = Dropout(0.3)(x) <NEW_LINE> return Model(input, x) | Build a multilayer perceptron. | 625941f6a934411ee3751cfc |
def add_commands(self, data): <NEW_LINE> <INDENT> self._q.append(data) | If this manager exists, another once can write to it
using add_commands( fn )
commands will be appended to end of queue | 625941f62ae34c7f2600d797 |
def _transform_expression(self, expression): <NEW_LINE> <INDENT> transforms = [] <NEW_LINE> transforms.append(('||', 'min(abs(L), abs(R))')) <NEW_LINE> transforms.append(('&&', 'max(abs(L), abs(R))')) <NEW_LINE> transforms.append(('>=', '((L) - (R)) - abs((L) - (R))')) <NEW_LINE> transforms.append(('>', '((L) - (R)) - ... | Transform the expression into one that evaluates to 0 when true.
For example, 'x=y' becomes '(x)-(y)'. | 625941f64f88993c3716c6c7 |
def test_animal_can_set_legs(self): <NEW_LINE> <INDENT> self.bob.set_legs(6) <NEW_LINE> self.assertEqual(self.bob.legs, 6) | tests that an animal object can set its legs | 625941f6e76e3b2f99f3ae67 |
def get_int3c_mo (mol, auxmol, mo_coeff, compact=getattr(__config__, 'df_df_DF_ao2mo_compact', True), max_memory=None): <NEW_LINE> <INDENT> nao, naux, nbas, nauxbas = mol.nao, auxmol.nao, mol.nbas, auxmol.nbas <NEW_LINE> npair = nao * (nao + 1) // 2 <NEW_LINE> if max_memory is None: max_memory = mol.max_memory <NEW_LIN... | Evaluate (P|uv) c_ui c_vj -> (P|ij)
Args:
mol: gto.Mole
auxmol: gto.Mole, contains auxbasis
mo_coeff: ndarray, list, or tuple containing MO coefficients
if two ndarrays mo_coeff = (mo0, mo1) are provided, mo0 and mo1 are
used for the two AO dimensions
Kwargs:
compact: bool
If t... | 625941f6f8510a7c17cf9d69 |
def get_column(self, col_name): <NEW_LINE> <INDENT> if col_name not in self._dataframe: <NEW_LINE> <INDENT> raise ValueError(("The column {} does not exist. " "Possible values are {}").format( col_name, self.keys())) <NEW_LINE> <DEDENT> out_frame = self._dataframe[[col_name]].dropna() <NEW_LINE> indx, ret_dict = self._... | Return the time and values where the given column is non-nan
Parameters
----------
col_name : str
The name of the column to return
Returns
-------
time : array-like
The time stamps of the non-nan values
out_vals : array-like
The values at those times | 625941f69f2886367277aeef |
def model_fn(features, labels, mode, params): <NEW_LINE> <INDENT> tf.logging.info("*** Features ***") <NEW_LINE> for name in sorted(features.keys()): <NEW_LINE> <INDENT> tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) <NEW_LINE> <DEDENT> input_ids = features["input_ids"] <NEW_LINE> input_mask ... | The `model_fn` for TPUEstimator. | 625941f6fb3f5b602dac3d02 |
def reactToAMQPMessage(message, send_back): <NEW_LINE> <INDENT> if _instanceof(message, ExportRequest): <NEW_LINE> <INDENT> tmp_folder = ltp.create_ltp_package( aleph_record=message.aleph_record, book_id=message.book_uuid, urn_nbn=message.urn_nbn, ebook_fn=message.filename, url=message.url, data=base64.b64decode(messag... | React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
:mod:`.structures`.
send_back (fn reference): Reference to function ... | 625941f66fb2d068a760f70f |
def cleanup(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> clean_path = os.path.join(self.tmpdir, "node-v%s" % self.ver) <NEW_LINE> shutil.rmtree(clean_path) <NEW_LINE> self.logfile.close() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass | Remove the build tree &
close the log file. | 625941f623e79379d52eebc2 |
def test_check_basic(self): <NEW_LINE> <INDENT> data = self.tmp / 'test_check_basic.json' <NEW_LINE> self.check_basic(True, data) | Test basic functionality of checking an existing weak password entry. | 625941f6d99f1b3c44c67be9 |
def test_that_when_deleting_an_api_method_for_a_method_that_does_not_exist_the_delete_api_method_method_returns_false(self): <NEW_LINE> <INDENT> self.conn.get_resources.return_value = api_resources_ret <NEW_LINE> self.conn.delete_method.side_effect = ClientError(error_content, 'delete_method') <NEW_LINE> result = boto_... | Tests False for '/api/users' and 'GET' | 625941f6d4950a0f3b08c9ad |
def __descriptor__(): <NEW_LINE> <INDENT> classDesc = dict() <NEW_LINE> classDesc['nameStr'] = 'grass' <NEW_LINE> classDesc['staticProperties'] = [('coord', np.int16, 2)] <NEW_LINE> classDesc['dynamicProperties'] = [('height', np.float32, 1)] <NEW_LINE> return classDesc | This desriptor defines the agent attributes that are saved in the
agent._graph an can be shared/viewed by other agents and acessed via
the global scope of the world class.
All static and dynamic attributes can be accessed by the agent by:
1) agent.get('attrLabel') / agent.set('attrLabel', value)
2) agent.attr... | 625941f630bbd722463cc431 |
def test_recorddao_get_data_for_records(self): <NEW_LINE> <INDENT> many_ids = ["spam", "spam2", "spam3"] <NEW_LINE> many_scalars = ["spam_scal", "eggs_scal", "spam_scal_2", "val_data"] <NEW_LINE> for_many = self.record_dao.get_data_for_records(id_list=many_ids, data_list=many_scalars) <NEW_LINE> six.assertCountEqual(se... | Test that we're getting data for many records correctly. | 625941f69b70327d1c4e1440 |
def generateTimeTable(className,duration): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> timeTable = readTimeTable() <NEW_LINE> import semester <NEW_LINE> courseTable = semester.readClass(className) <NEW_LINE> subjects = list() <NEW_LINE> print(courseTable) <NEW_LINE> for i in courseTable.index: <NEW_LINE> <INDENT... | class whose timetable is to be generated | 625941f6bde94217f3683452 |
@with_setup(pretest, posttest) <NEW_LINE> def test_dynamic_min_iters(): <NEW_LINE> <INDENT> with closing(StringIO()) as our_file: <NEW_LINE> <INDENT> total = 10 <NEW_LINE> t = tqdm(total=total, file=our_file, miniters=None, mininterval=0, smoothing=1) <NEW_LINE> t.update() <NEW_LINE> t.update(3) <NEW_LINE> t.update() <... | Test purely dynamic miniters (and manual updates and __del__) | 625941f629b78933be1e5d0c |
def plot_polys(polys): <NEW_LINE> <INDENT> from mpl_toolkits.mplot3d.art3d import Poly3DCollection <NEW_LINE> import matplotlib.pyplot as plt <NEW_LINE> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111, projection='3d') <NEW_LINE> fc = ["crimson" if i%2 else "gold" for i in range(len(polys))] <NEW_LINE> ax.add_co... | This function is for visualising sphere segments to aid debugging/development
| 625941f64527f215b584cab8 |
def close(self): <NEW_LINE> <INDENT> super().close() <NEW_LINE> del self.ih | Close task.
Note that this does not explicitly close the underlying source;
instead, it just deletes the reference to it. | 625941f6435de62698dfe2b4 |
@task <NEW_LINE> def dumpdata(apps_or_models=''): <NEW_LINE> <INDENT> require('PROJECT', provided_by=['stage', 'production']) <NEW_LINE> remote_file = '%s/%s-%s.json.bz2' % (env.PROJECT.tmp, env.host, timestamp()) <NEW_LINE> with cd(env.PROJECT.current): <NEW_LINE> <INDENT> with prefix('source bin/activate'): <NEW_LINE... | Connect to Dreamhost server, generate a database dump and
download it.
Usage: fab stage db.dump | 625941f6b5575c28eb68e66e |
@TestScenario <NEW_LINE> def select_with_table_on_materialized_view_privilege_granted_directly_or_via_role(self, node=None): <NEW_LINE> <INDENT> user_name = f"user_{getuid()}" <NEW_LINE> role_name = f"role_{getuid()}" <NEW_LINE> if node is None: <NEW_LINE> <INDENT> node = self.context.node <NEW_LINE> <DEDENT> with Give... | Check that user is able to SELECT from a distributed table that uses a materialized view if and only if
they have SELECT privilege on the distributed table and the materialized view it is built on. | 625941f63317a56b8693a2af |
def experiment(alpha): <NEW_LINE> <INDENT> U, j = random(), 1 <NEW_LINE> XI = uniform(0, 1) <NEW_LINE> if U < alpha: <NEW_LINE> <INDENT> F = (1 / 2) <NEW_LINE> while XI >= F: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> F += F * (1 / 2) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> F = (1 / 2) * (2 / 3) <NEW_LINE> wh... | Enunciado: Desarrollar un método para generar una variable aleatoria X cuya
distribución de probabilidad está dada por: P(X = j). Aplicamos el método
de composición, donde alpha y (1 - alpha) son 0.5. | 625941f6925a0f43d254a4e5 |
def test_chained_left_right_shift(): <NEW_LINE> <INDENT> group([ ('NAME', 'a'), ('LEFT_SHIFT', '<<'), ('NAME', 'b'), ('RIGHT_SHIFT', '>>'), ('NAME', 'c'), ], [ ('NAME', 'a'), ('LEFT_SHIFT', '<<'), ('NAME', 'b'), ('RIGHT_SHIFT', '>>'), ('NAME', 'c'), ]) | a<<b>>c | 625941f61b99ca400220b11c |
def p_condexpr(p): <NEW_LINE> <INDENT> x = None <NEW_LINE> if len(p) == 6: <NEW_LINE> <INDENT> x = objects.Condicional(p.lineno(2), p[1], p[3], p[5]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = p[1] <NEW_LINE> <DEDENT> p[0] = x | condexpr : orexpr
condexpr : orexpr INTERROGACAO expr DOISPONTOS condexpr | 625941f650812a4eaa59c982 |
def db_close(self): <NEW_LINE> <INDENT> self.con.close() | Fermeture de la connexion
| 625941f6fbf16365ca6f683a |
def not_authorized(request): <NEW_LINE> <INDENT> return HttpResponse("Unauthorized", status=401) | Django view, used for displaying unauthorized error.
Simple view, which displays html error 401 - unauthorized. It is used by
decorators 'login_required' and 'permission_required' as the redirect page
of unauthorized requests.
Keyword arguments:
request -- django request object | 625941f6097d151d1a2234bd |
def replace_mapped_chars(pattern): <NEW_LINE> <INDENT> mapped_chars = {'\'': '__sq__', '\\': '__backslash__'} <NEW_LINE> for key, value in mapped_chars.items(): <NEW_LINE> <INDENT> pattern = pattern.replace(value, key) <NEW_LINE> <DEDENT> return pattern | handles special escaped characters when coming from galaxy | 625941f64d74a7450ccd482d |
def get_table_type(self): <NEW_LINE> <INDENT> if self.is_longtable(): <NEW_LINE> <INDENT> return 'longtable' <NEW_LINE> <DEDENT> elif self.has_verbatim: <NEW_LINE> <INDENT> return 'tabular' <NEW_LINE> <DEDENT> elif self.colspec: <NEW_LINE> <INDENT> return 'tabulary' <NEW_LINE> <DEDENT> elif self.has_problematic or (sel... | Returns the LaTeX environment name for the table.
The class currently supports:
* longtable
* tabular
* tabulary | 625941f67047854f462a1a69 |
def is_2D(m): <NEW_LINE> <INDENT> return len(np.shape(m)) == 2 | judge if a matrix is 2-D or not | 625941f6956e5f7376d714d3 |
def findWords(self, board, words): <NEW_LINE> <INDENT> if not board or not board[0]: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> root = TrieNode() <NEW_LINE> for word in words: <NEW_LINE> <INDENT> node = root <NEW_LINE> for letter in word: <NEW_LINE> <INDENT> child = node.children.get(letter) <NEW_LINE> if not ch... | :type board: List[List[str]]
:type words: List[str]
:rtype: List[str] | 625941f6d10714528d600353 |
def _get_index(self, percentage): <NEW_LINE> <INDENT> self._calculate_susceptible() <NEW_LINE> self.idx_I0 = np.where(self.df[self.country] > self.N0*(percentage/100))[0][0] | Day of initially infected population
| 625941f63539df3088e2e9b3 |
def _get_export_policy(self): <NEW_LINE> <INDENT> return self.__export_policy | Getter method for export_policy, mapped from YANG variable /bgp/peer_groups/peer_group/afi_safis/afi_safi/apply_policy/config/export_policy (leafref)
YANG Description: list of policy names in sequence to be applied on
sending a routing update in the current context, e.g.,
for the current peer group, neighbor, ... | 625941f68e05c05ec3eea9e2 |
def __init__(self, state_size, action_size, seed, fc1_nodes=64, fc2_nodes=32): <NEW_LINE> <INDENT> super(QNetwork, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc1_nodes) <NEW_LINE> self.fc2 = nn.Linear(fc1_nodes, fc2_nodes) <NEW_LINE> self.fc3 = nn.Linear(... | Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed | 625941f699fddb7c1c9de9f5 |
def foreignKey(self, class_name, separate_class_name_and_id_with_underscore=1): <NEW_LINE> <INDENT> return self.foreign_key(class_name, separate_class_name_and_id_with_underscore) | Deprecated, alias of #foreign_key for backwards compatibility. | 625941f65fdd1c0f98dc089e |
def append(self, counter, offset, source): <NEW_LINE> <INDENT> logger.debug('appending source, counter %d, abs offset %d, ' 'source %r', counter, offset, source) <NEW_LINE> self._sources.append((counter, offset, source)) | @param counter: the source counter; updates for each different
data source (silence or different file path)
@type counter: int
@param offset: the absolute disc offset where this source starts | 625941f6d53ae8145f87a8ca |
@admin.route('/roles', methods=['GET', 'POST']) <NEW_LINE> @login_required <NEW_LINE> def list_roles(): <NEW_LINE> <INDENT> check_admin() <NEW_LINE> roles = Role.query.all() <NEW_LINE> return render_template('admin/roles/roles.html', roles=roles, title="Roles") | List all roles | 625941f6d99f1b3c44c67bea |
def play(self): <NEW_LINE> <INDENT> if self.game.trick: <NEW_LINE> <INDENT> return self.follow() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.lead() | Play a card to start or add to a trick. (card.Card) | 625941f6f7d966606f6aa674 |
def save_account(self): <NEW_LINE> <INDENT> User.save_account(self) | Function to save account | 625941f671ff763f4b549d00 |
def __init__(self, children=None, entry=None): <NEW_LINE> <INDENT> self.children = {} if children is None else children <NEW_LINE> self.entry = entry | Make a new IndexNode with the given children and entry (defaulting to empty). | 625941f6a8370b7717052f05 |
@pytest.mark.parametrize('name', [ ('enpass'), ('libxss1'), ('lsof'), ]) <NEW_LINE> def test_packages(host, name): <NEW_LINE> <INDENT> assert host.package(name).is_installed | Test packages installed | 625941f6d8ef3951e3243ba6 |
@view_config(route_name='server-login', request_method=['GET', 'POST']) <NEW_LINE> def lazy_login(request): <NEW_LINE> <INDENT> capture_requesting_service(request) <NEW_LINE> user_id = authenticated_userid(request) <NEW_LINE> if user_id is not None: <NEW_LINE> <INDENT> raise _login(request, user_id) <NEW_LINE> <DEDENT>... | Provide a login interface for those services not wanting to do
the login logic in their application interface. It's important to
direct traffic to this route because it captures necessary information
that would otherwise be acquired via other api pieces. | 625941f663b5f9789fde774e |
def __init__(self, nums): <NEW_LINE> <INDENT> for i in range(1, len(nums)): <NEW_LINE> <INDENT> nums[i] += nums[i-1] <NEW_LINE> <DEDENT> self.nums = nums | initialize your data structure here.
:type nums: List[int] | 625941f644b2445a339326f9 |
def _get_group(self): <NEW_LINE> <INDENT> return 'aws-{}'.format(self.config.aws_account_name) | Get the event group.
Returns:
str: Formatted as 'aws-$AWS_ACCOUNT_NAME'. Ex: 'aws-supercoolco'. | 625941f6f8510a7c17cf9d6a |
def __init__(self, var, name, type_, id_, tm, access='ro', encoding='ascii', desc='', value=None, urn=''): <NEW_LINE> <INDENT> self.id_ = id_ <NEW_LINE> self.tm = tm <NEW_LINE> self.realname = var <NEW_LINE> self.name = name <NEW_LINE> self.type_ = type_ <NEW_LINE> self.encoding = encoding <NEW_LINE> self.desc = desc <... | Constructor | 625941f6e5267d203edce2fd |
def labelRotation(self): <NEW_LINE> <INDENT> return self.__data.labelRotation | :return: the label rotation
.. seealso::
:py:meth:`setLabelRotation()`, :py:meth:`labelAlignment()` | 625941f6be7bc26dc91cdc5c |
@app_views.route('/status') <NEW_LINE> def response_code(): <NEW_LINE> <INDENT> return jsonify({"status": "OK"}) | function returns a status response | 625941f62c8b7c6e89b35e23 |
def test_can_get_correct_usage_info(self): <NEW_LINE> <INDENT> self._add_user_partitions(count=2) <NEW_LINE> self._create_content_experiment(cid=0, name_suffix='0') <NEW_LINE> self._create_content_experiment(name_suffix='1') <NEW_LINE> actual = GroupConfiguration.add_usage_info(self.course, self.store) <NEW_LINE> expec... | Test if group configurations json updated successfully with usage information. | 625941f6bd1bec0571d90c98 |
def test_forking_basic(self): <NEW_LINE> <INDENT> number_blocks = 10 <NEW_LINE> with MockedBlockchain.create(number_blocks) as mock_blockchain: <NEW_LINE> <INDENT> block_9 = mock_blockchain.dftnode.get_block_from_index(9) <NEW_LINE> block_10 = mock_blockchain.dftnode.get_block_last() <NEW_LINE> block_10b = mock_blockch... | TODO: Cyyber review
- Create a blockchain of 10 blocks
- Add a new block 10b (linking to 9)
- Check that it did not switch | 625941f667a9b606de4a851e |
def setup(self): <NEW_LINE> <INDENT> GPIO.setmode(GPIO.BCM) <NEW_LINE> if self.normally_open: <NEW_LINE> <INDENT> mode = GPIO.PUD_UP <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode = GPIO.PUD_DOWN <NEW_LINE> <DEDENT> GPIO.setup(self.pin, GPIO.IN, pull_up_down=mode) <NEW_LINE> logging.debug('Reed Switch {} configured... | Setup GPIO pin to read input value.
:return: None | 625941f6b5575c28eb68e66f |
def BatchRegisterTargets(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("BatchRegisterTargets", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.BatchRegisterTarget... | 批量绑定虚拟主机或弹性网卡,支持跨域绑定,支持四层、七层(TCP、UDP、HTTP、HTTPS)协议绑定。
:param request: Request instance for BatchRegisterTargets.
:type request: :class:`tencentcloud.clb.v20180317.models.BatchRegisterTargetsRequest`
:rtype: :class:`tencentcloud.clb.v20180317.models.BatchRegisterTargetsResponse` | 625941f685dfad0860c3b4c6 |
def _create_param_fields(self): <NEW_LINE> <INDENT> for idx, (lbl, p_type, p_allow, p_init, p_help) in enumerate( self.plugin_instance.parameters, ): <NEW_LINE> <INDENT> if p_allow: <NEW_LINE> <INDENT> new_field = forms.ChoiceField( choices=[(cval, cval) for cval in p_allow], required=False, label=lbl, help_text=p_help... | Create the fields to capture the parameters. | 625941f62eb69b55b151cf21 |
@step("the destination peer must receive the command") <NEW_LINE> def step_impl(context): <NEW_LINE> <INDENT> ok_(context.receiver.message['schemaRef'] == 'ref://bpm.message.bpm.process.start') | :type context behave.runner.Context | 625941f6cc0a2c11143dd4fa |
def hash_password(value: str) -> str: <NEW_LINE> <INDENT> return hashpw(value.encode("utf-8"), SECRET_KEY.encode("utf-8")).decode("utf-8") | Hash user password to store hash in a database. | 625941f610dbd63aa1bd320a |
def set_month(event): <NEW_LINE> <INDENT> dropdown = event.target <NEW_LINE> main_instance.month = dropdown.selectedIndex + 1 <NEW_LINE> event.stopPropagation() | Sets specific Month.
Day might change to compensate for length difference between months.
:param event: event object, passed by brython. | 625941f61f037a2d8b946864 |
def get_dset(self, dset): <NEW_LINE> <INDENT> return [Candidate(cand) for cand in dset] | Turns list of dictionaries into list of
'Candidate' objects | 625941f6091ae356686675bb |
def update_zone(apiclient, state, zone_id): <NEW_LINE> <INDENT> zone_status = Zone.update( apiclient, id=zone_id, allocationstate=state ) <NEW_LINE> return zone_status.allocationstate | Function to Enable/Disable zone | 625941f623e79379d52eebc3 |
def postinit(self, args, body, decorators=None, returns=None, type_comment_returns=None, type_comment_args=None): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.body = body <NEW_LINE> self.decorators = decorators <NEW_LINE> self.returns = returns <NEW_LINE> self.type_comment_returns = type_comment_returns <NEW_LI... | Do some setup after initialisation.
:param args: The arguments that the function takes.
:type args: Arguments or list
:param body: The contents of the function body.
:type body: list(NodeNG)
:param decorators: The decorators that are applied to this
method or function.
:type decorators: Decorators or None
:param... | 625941f64f88993c3716c6c8 |
def test_ages_and_data(self): <NEW_LINE> <INDENT> N_exam = ones(self.N) * 10000 <NEW_LINE> A, pos, age_distribution = ages_and_data(N_exam, self.f_samp, self.correction_factor_array, self.age_lims) <NEW_LINE> empirical_age_distributions = [] <NEW_LINE> for j in xrange(self.N): <NEW_LINE> <INDENT> A_ind = A[j]-self.age_... | Makes sure that the ages drawn by ages_and_data match the age distributions. | 625941f6a8ecb033257d3733 |
def remove_delay(self): <NEW_LINE> <INDENT> if self.proc is not None and self.proc.is_alive(): <NEW_LINE> <INDENT> self.proc.terminate() <NEW_LINE> <DEDENT> return True | Remove network delay, return with the call's result. | 625941f666656f66f7cbc815 |
def _collect_updates( self, old_dict: Dict[str, Any], new_dict: Dict[str, Any] ) -> Dict[str, Any]: <NEW_LINE> <INDENT> updates = {} <NEW_LINE> for field_name, field_value in new_dict.items(): <NEW_LINE> <INDENT> if field_value != old_dict.get(field_name): <NEW_LINE> <INDENT> if not self.state_management_replace_object... | Compares old_dict with new_dict and returns field paths that have been updated
Args:
old_dict: dict1
new_dict: dict2
Returns: dictionary with updates | 625941f6596a89723608a120 |
def test_relu_9(): <NEW_LINE> <INDENT> op = Net() <NEW_LINE> op.eval() <NEW_LINE> obj = APIOnnx(op, 'relu', [9]) <NEW_LINE> obj.set_input_data( "input_data", paddle.to_tensor( randtool("float", -1, 1, [3, 3, 3]).astype('float32'))) <NEW_LINE> obj.run() | api: paddle.relu
op version: 9 | 625941f6711fe17d825429c5 |
def get_text(params): <NEW_LINE> <INDENT> event_text = params.get('text') <NEW_LINE> if not event_text: <NEW_LINE> <INDENT> event_text = 'help' <NEW_LINE> <DEDENT> elif isinstance(event_text, list): <NEW_LINE> <INDENT> event_text = event_text[0] <NEW_LINE> <DEDENT> elif isinstance(event_text, str): <NEW_LINE> <INDENT> ... | Return event_text from parse_qs event.get('body'). | 625941f6cdde0d52a9e536a2 |
def get_cli_header(name, char="#"): <NEW_LINE> <INDENT> term_length = get_terminal_size((80, 24))[0] or 80 <NEW_LINE> sep = get_cli_separator(char) <NEW_LINE> sub_sep = "%s" % (int((term_length - (len(name) + 2)) / 2) * char) <NEW_LINE> mid = "%s %s %s" % (sub_sep, name, sub_sep) <NEW_LINE> while True: <NEW_LINE> <INDE... | Get a "decorated header".
Get a "decorated header" to display at the beginning of the CLI execution (or whenever it is
needed).
Parameters
----------
name : str
The application name or a "title" to display as a "header".
char : str, optional
The "decorator" character.
Returns
-------
str
The actual "head... | 625941f6e64d504609d74ea8 |
def reboot(self, timeout=None): <NEW_LINE> <INDENT> ready = ADBDevice.reboot(self, timeout=timeout) <NEW_LINE> self._check_adb_root(timeout=timeout) <NEW_LINE> return ready | Reboots the device.
:param timeout: optional integer specifying the maximum time in
seconds for any spawned adb process to complete before
throwing an ADBTimeoutError.
This timeout is per adb call. The total time spent
may exceed this value. If it is not specified, the value
set in the ADB construc... | 625941f68c0ade5d55d3f029 |
def calculate_cpu_times_percent(cpu_times_older, cpu_times_younger, percpu=False): <NEW_LINE> <INDENT> WINDOWS = os.name == 'nt' <NEW_LINE> def calculate(t1, t2): <NEW_LINE> <INDENT> global _ptime_cpu_perc_nt <NEW_LINE> nums = [] <NEW_LINE> all_delta = sum(t2) - sum(t1) <NEW_LINE> for field in t1._fields: <NEW_LINE> <I... | Same as cpu_percent() but provides utilization percentages
for each specific CPU time as is returned by cpu_times().
For instance, on Linux we'll get:
>>> cpu_times_percent()
cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
... | 625941f6fb3f5b602dac3d03 |
def _create_part(name, elements, elename, eletype, nodes, transform=[[0.,0.,0]], ignore=False): <NEW_LINE> <INDENT> new_part = part(name, elename, eletype, transform, ignore) <NEW_LINE> for e in elements: <NEW_LINE> <INDENT> pts = [nodes[n] for n in e[1:]] <NEW_LINE> exec('ele = ' + eletype + '(int(e[0]), pts, e[1:])')... | Creates part class from input data | 625941f6a219f33f34628fc9 |
def received_message(self, m): <NEW_LINE> <INDENT> response = json.loads(str(m)) <NEW_LINE> if response['status'] == 0: <NEW_LINE> <INDENT> if 'result' in response: <NEW_LINE> <INDENT> trans = response['result']['hypotheses'][0]['transcript'] <NEW_LINE> if response['result']['final']: <NEW_LINE> <INDENT> print("Final t... | Parse a transcript result. | 625941f6dd821e528d63b80c |
def largestNumber(self, nums): <NEW_LINE> <INDENT> comp = lambda a, b : 1 if a + b > b + a else -1 if a + b < b + a else 0 <NEW_LINE> nums = map(str,nums) <NEW_LINE> nums.sort(cmp = comp, reverse = True) <NEW_LINE> return str(int("".join(nums))) | :type nums: List[int]
:rtype: str | 625941f682261d6c526abb12 |
def get(self, url, instance, service_check_tags, run_check=False): <NEW_LINE> <INDENT> self.log.debug('Fetching CouchDB stats at url: %s' % url) <NEW_LINE> auth = None <NEW_LINE> if 'user' in instance and 'password' in instance: <NEW_LINE> <INDENT> auth = (instance['user'], instance['password']) <NEW_LINE> <DEDENT> req... | Hit a given URL and return the parsed json | 625941f64e696a04525c9ab7 |
def get_full_name(self): <NEW_LINE> <INDENT> return self.name | "Used to get users' full name | 625941f6462c4b4f79d1dd38 |
def test_track_same_state_simple_no_trigger(self): <NEW_LINE> <INDENT> callback_runs = [] <NEW_LINE> period = timedelta(minutes=1) <NEW_LINE> @ha.callback <NEW_LINE> def callback_run_callback(): <NEW_LINE> <INDENT> callback_runs.append(1) <NEW_LINE> <DEDENT> track_same_state( self.hass, 'on', period, callback_run_callb... | Test track_same_change with no trigger. | 625941f644b2445a339326fa |
def geojson_esriGeometryPoint(self): <NEW_LINE> <INDENT> return "Point" | docstring for fname | 625941f6236d856c2ad44e4d |
def AdminSalesPrint(self, date=''): <NEW_LINE> <INDENT> self.builder.get_object('AdminCol1').get_buffer().set_text( u"\nID\n") <NEW_LINE> self.builder.get_object('AdminCol2').get_buffer().set_text( u"\nName\n") <NEW_LINE> self.builder.get_object('AdminCol3').get_buffer().set_text( u"Guest\nprice\n") <NEW_LINE> self.bui... | This prints the header of the sales overview | 625941f6b545ff76a891447e |
def snail(): <NEW_LINE> <INDENT> h = int(input('Enter the height: ')) <NEW_LINE> a = int(input('Enter the day feets: ')) <NEW_LINE> b = int(input('Enter the night feets: ')) <NEW_LINE> i = a <NEW_LINE> n = 1 <NEW_LINE> while i < h: <NEW_LINE> <INDENT> i -= b <NEW_LINE> n += 1 <NEW_LINE> i += a <NEW_LINE> <DEDENT> retur... | Snail creeps up the vertical pole of height H feets. Per day it goes A feets up,
and per night it goes B feets down. In which day the snail will reach the top of the pole? | 625941f6293b9510aa2c38f8 |
def memory_stream_pump(memory_send_stream, memory_receive_stream, *, max_bytes=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = memory_send_stream.get_data_nowait(max_bytes) <NEW_LINE> <DEDENT> except _core.WouldBlock: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if not data: ... | Take data out of the given :class:`MemorySendStream`'s internal buffer,
and put it into the given :class:`MemoryReceiveStream`'s internal buffer.
Args:
memory_send_stream (MemorySendStream): The stream to get data from.
memory_receive_stream (MemoryReceiveStream): The stream to put data into.
max_bytes (int or N... | 625941f68e7ae83300e4b638 |
def test_informative_address_message(self): <NEW_LINE> <INDENT> status_type, code_match, address_match = get_status_type("5890 :: 110 :: 9813 :: Hello.") <NEW_LINE> self.assertEqual( "5890 :: Code `110` :: Addressing: Drone #9813 :: Hello.", build_status_message(status_type, code_match, address_match) ) | returns an informative address by ID status message when a 110 code references a drone by ID with additional information. | 625941f67d847024c06be92a |
def format(self, record): <NEW_LINE> <INDENT> record.message = record.getMessage() <NEW_LINE> if self.usesTime(): <NEW_LINE> <INDENT> record.asctime = self.formatTime(record, self.datefmt) <NEW_LINE> <DEDENT> if '\n' in record.message: <NEW_LINE> <INDENT> splitted = record.message.splitlines() <NEW_LINE> output = self.... | This is mostly the same as logging.Formatter.format except for the splitlines() thing.
This is done so (copied the code) to not make logging a bottleneck. It's not lots of code
after all, and it's pretty straightforward. | 625941f626238365f5f0f4e0 |
def set_ConsumerSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ConsumerSecret', value) | Set the value of the ConsumerSecret input for this Choreo. ((optional, string) The OAuth Consumer Secret provided by Khan Academy.) | 625941f6ad47b63b2c50a5e9 |
def _config_file_path(args): <NEW_LINE> <INDENT> path = os.path.abspath(os.path.expanduser(args.file)) <NEW_LINE> if os.path.isfile(path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> default_path = os.path.join( os.path.split(sys.modules[__name__].__file__)[0], "flitter.json") <NEW_LINE> if os.path.isfile(defau... | Return the absolute path to the config file to use.
This first uses the config file given with the -f/--f command-line
argument (which defaults to ~/.flitter.json if not given).
If that file doesn't exist it falls back on the default flitter.json file
that ships with Flitter in the same directory as this Python module... | 625941f6cc40096d61595fb6 |
def invert(r: int, g: int, b: int) -> _rgb: <NEW_LINE> <INDENT> return (0xFF - r, 0xFF - g, 0xFF - b) | Inverts the given colour. | 625941f61b99ca400220b11d |
def mixed_kmeans(data, morphology_features, expression_features): <NEW_LINE> <INDENT> kmeans_morphology = KMeans(n_clusters=3) <NEW_LINE> morphology_labels = kmeans_morphology.fit_predict(data[morphology_features]) <NEW_LINE> kmeans_expression= KMeans(n_clusters=3) <NEW_LINE> expression_labels = kmeans_expression.fit_p... | Clusters FCS events using mixed k-means model
Model fits two k-means models with k=3, one using morphology features and
another using expression features. Final cluster labels are created by
combining the cluster labels from these two models.
Function assumes that any transformations (such as log, logicle, etc.) have... | 625941f671ff763f4b549d01 |
def make_error(error, status=400): <NEW_LINE> <INDENT> return { 'success': False, 'error': error }, status | Assemble an error response tuple | 625941f6a934411ee3751cfe |
def n_spaced(L=0, B=0, R=10, T=10, min_space=1, num=10, verbose=True): <NEW_LINE> <INDENT> def _pnts(L, B, R, T, num): <NEW_LINE> <INDENT> xs = (R-L) * np.random.random_sample(size=num) + L <NEW_LINE> ys = (T-B) * np.random.random_sample(size=num) + B <NEW_LINE> return np.array(list(zip(xs, ys))) <NEW_LINE> <DEDENT> de... | Produce num points within the bounds specified by the extent (L,B,R,T)
Parameters:
---------
L(eft), B, R, T(op) : numbers
extent coordinates
min_space : number
minimum spacing between points.
num : number
number of points... this value may not be reached if the extent
is too small and the spacing is large re... | 625941f6f8510a7c17cf9d6b |
def calc_feature_correlation_matrix(df, weights=None): <NEW_LINE> <INDENT> values = numpy.array(df) <NEW_LINE> weights = check_sample_weight(df, sample_weight=weights) <NEW_LINE> means = numpy.average(values, weights=weights, axis=0) <NEW_LINE> values -= means <NEW_LINE> covariation = values.T.dot(values * weights[:, N... | Calculate correlation matrix
:param pandas.DataFrame df: data of shape [n_samples, n_features]
:param weights: weights of shape [n_samples] (optional)
:return: correlation matrix for dataFrame of shape [n_features, n_features]
:rtype: numpy.ndarray | 625941f6e64d504609d74ea9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.