code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def db_for_write(self, model, **hints): <NEW_LINE> <INDENT> from django.conf import settings <NEW_LINE> if not settings.DATABASES.has_key('bank_2'): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if model._meta.app_label == 'bank_2': <NEW_LINE> <INDENT> return 'bank_2' <NEW_LINE> <DEDENT> return None
Point all operations on app1 models to 'app1'
625941df4527f215b584c7a8
def __init__(self, size=0): <NEW_LINE> <INDENT> self.__size = size
initializes data
625941df956e5f7376d711c1
def rotate(self, yaw: float) -> 'Vector3': <NEW_LINE> <INDENT> rad = math.radians(yaw) <NEW_LINE> x = - self.z * math.sin(rad) + self.x * math.cos(rad) <NEW_LINE> z = self.z * math.cos(rad) + self.x * math.sin(rad) <NEW_LINE> return Vector3(x, self.y, z)
(180) z- (90) x- x+ (270) z+ (0) >>> Vector3(1, 0, 0).rotate(90).astype(int) Vector3(x=0, y=0, z=1) >>> Vector3(0, 0, 1).rotate(90).astype(int) Vector3(x=-1, y=0, z=0) >>> Vector3(1, 0, 0).rotate(-90).astype(int) Vector3(x=0, y=0, z=-1) >>> Vector3(0, 0, -1).rotate(-90).astype(int) Vec...
625941dfd4950a0f3b08c69f
@pytest.mark.parametrize('python_datetime,expected,comment', [ (datetime(1976, 11, 23, 3, 33, 6, microsecond=123000, tzinfo=timezone.utc), '/Date(217567986123+0000)/', 'UTC'), (datetime(1976, 11, 23, 3, 33, 6, tzinfo=timezone(timedelta(hours=14))), '/Date(217567986000+0840)/', '+14 hours'), (datetime(1976, 11, 23, 3, 3...
Test Edm.DateTimeOffset trait: Python -> json
625941df23e79379d52ee8b5
@app.route('/top10/category/<string:category_url>') <NEW_LINE> def showCategory(category_url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> listCategory = session.query(Category).filter_by(url=category_url).one() <NEW_LINE> <DEDENT> except NoResultFound: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> allLists = ses...
Display category page with all top ten lists
625941dfa4f1c619b28b0386
def get_keys(self, obj, index=None): <NEW_LINE> <INDENT> if inspect.isclass(obj): <NEW_LINE> <INDENT> model = obj <NEW_LINE> obj = model() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> model = type(obj) <NEW_LINE> <DEDENT> return tuple(self._get_cache(model).get_keys(obj, index))
Returns IDs for all objects matching the query. If index is omitted, we assume result should contain all object of the model. >>> db_store.get_keys(Lport(topic='topic1'), index=Lport.get_index('topic')) ('id1', 'id2', 'id3', ...)
625941df9f2886367277abe0
def get(self): <NEW_LINE> <INDENT> user = UserManager.getUser() <NEW_LINE> self.return_json(user.toDict())
Retrieves current user (newebe owner) data at JSON format.
625941dffb3f5b602dac39ec
def set_account(self, email): <NEW_LINE> <INDENT> raise NotImplementedError
@type email: str
625941dfd486a94d0b98e49c
def query_bibcode_async(self, bibcode, wildcard=False): <NEW_LINE> <INDENT> request_payload = self._args_to_payload(bibcode, wildcard=wildcard, caller='query_bibcode_async', get_raw=True) <NEW_LINE> response = commons.send_request(self.SIMBAD_URL, request_payload, self.TIMEOUT) <NEW_LINE> return response
Serves the same function as `query_bibcode`, but only collects the reponse from the Simbad server and returns. Parameters ---------- bibcode : str the bibcode of the article wildcard : boolean, optional When it is set to `True` it implies that the object is specified with wildcards. Defaults to `False`. R...
625941dfbaa26c4b54cb1471
def list_contents(path, root): <NEW_LINE> <INDENT> cmd = "svn ls %s/%s" % (root, path) <NEW_LINE> code, out = util.execute(cmd, return_out=True) <NEW_LINE> dirs = out.strip().split('\n') <NEW_LINE> return dirs
@return list of relative paths rooted at "root"
625941df31939e2706e4d1ba
def check_two_pairs(self): <NEW_LINE> <INDENT> is_one_pair = self.check_one_pair() <NEW_LINE> list_two_pairs = [is_one_pair] <NEW_LINE> if 0 <= is_one_pair < MAX_INDEX_OF_PAIR: <NEW_LINE> <INDENT> pair_index_in_spot_3rd_or_4th = is_one_pair + MAX_INDEX_OF_PAIR <NEW_LINE> for i in range(pair_index_in_spot_3rd_or_4th, le...
:return: the indexes of the two pairs in a hand if exist
625941df5f7d997b87174df0
def serialize_summary(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'slug': self.slug, 'number': self.number, 'name': self.name, 'location': self.location, 'rating': self.rating, 'strava_id': self.strava_id, 'segment': self.segment.serialize_summary(), 'book_id': self.book_id, 'region_id': self.region_id, }
Returns an easily serializeable summary of the object.
625941dffff4ab517eb2f793
def distribute_items(self, X, Y, t, id, items): <NEW_LINE> <INDENT> if t.children_left[id] == skl_tree._tree.TREE_LEAF: <NEW_LINE> <INDENT> self.items[id] = items <NEW_LINE> self.distr[id] = Counter(Y[items].flatten()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = X[items, :] <NEW_LINE> left = items[np.where(x[:, t...
Store example ids into leaves and compute class distributions.
625941df377c676e912724fc
def is_within_size_limit(self, a_size): <NEW_LINE> <INDENT> if (len(self.payload) + a_size + 2) <= self.size: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Check if adding data will result in a payload size below size The actual size increase is given by a_size + 2 for the channel and sensor type. Args: a_size: The size of the data to be added to the payload (in bytes). Returns: True if the current size of the payload + a_size is lower than size, False othe...
625941df1b99ca400220ae07
def next_feeding(self, wh, opponents): <NEW_LINE> <INDENT> return self.interface.next_feeding(self, wh, opponents)
Asks this player's strategy interface for the feeding choice they would like to make. :param wh: The number of food tokens in the watering hole. :param opponents: list of PlayerState containing all other players. :return: A Feeding representing the player's desired feeding choice.
625941df3317a56b86939fa6
def check( self, data_dict, basename=None, fullpath=None, tolerances=None, default_tolerance=None, ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import numpy as np <NEW_LINE> <DEDENT> except ModuleNotFoundError: <NEW_LINE> <INDENT> raise ModuleNotFoundError(import_error_message("NumPy")) <NEW_LINE> <DEDENT> import fu...
Checks a dictionary of NumPy ndarrays, containing only numeric data, against a previously recorded version, or generate a new file. Example:: def test_some_data(ndarrays_regression): points, values = some_function() ndarrays_regression.check( { 'points': points, # arra...
625941df44b2445a339323e9
def run(args): <NEW_LINE> <INDENT> protein = [] <NEW_LINE> genes_file = args.output_location + "outfile.fasta" <NEW_LINE> process_gff(args.intervals_file, args.input, genes_file) <NEW_LINE> codon_aa = codons(args.aa_codons) <NEW_LINE> with open(genes_file) as f_in: <NEW_LINE> <INDENT> for line in f_in.readlines(): <NEW...
Function to process the mRNA, generate the six translation frames, translate and then save the longest proteins in the output file with the gene name. :param args :type <class 'argparse.Namespace'>
625941df9c8ee82313fbbacb
def mhg_cutoff_value(marker_exp, cutoff_ind): <NEW_LINE> <INDENT> def find_val(row): <NEW_LINE> <INDENT> gene = row['gene'] <NEW_LINE> val = marker_exp[gene].sort_values( ascending=False).iloc[row['mHG_cutoff']] <NEW_LINE> if re.compile(".*_c$").match(gene): <NEW_LINE> <INDENT> return val - FLOAT_PRECISION <NEW_LINE> <...
Finds discrete expression cutoff value, from given cutoff index. The XL-mHG test outputs the index of the cutoff of highest significance between a sample and population. This functions finds the expression value which corresponds to this index. Cells above this value we define as expressing, and cells below this val...
625941dfc432627299f04f9d
def dcLUID(self, decachunky_x, decachunky_z): <NEW_LINE> <INDENT> return self.cLUID(decachunky_x, decachunky_z)
get decachunk LUID (locally-unique id) from decachunk
625941df6e29344779a62965
def thrust_control(self, target_z, dt): <NEW_LINE> <INDENT> current_z, current_z_dot = self.vehicle_state <NEW_LINE> delta_z = target_z - current_z <NEW_LINE> target_z_dot = delta_z / dt <NEW_LINE> delta_z_dot = target_z_dot - current_z_dot <NEW_LINE> target_z_dot_dot = delta_z_dot / dt <NEW_LINE> target_f_net = target...
Returns a thrust which will be commanded to the vehicle. This thrust should cause the vehicle to be at target_z in dt seconds. The controller's internal model of the vehicle_state is also updated in this method.
625941df7b25080760e397ad
def get_openid_request(openid_url): <NEW_LINE> <INDENT> c = consumer.Consumer({}, FileOpenIDStore(settings.OPENID_STORE_DIR)) <NEW_LINE> req = c.begin(openid_url) <NEW_LINE> return req.redirectURL(get_openid_realm(), get_openid_verify_url()), c
リダイレクト先URLとconsumerオブジェクトを返す
625941dfb5575c28eb68e358
@pytest.mark.solver <NEW_LINE> @select_database("alni_tough_chempot.tdb") <NEW_LINE> def test_eq_stepsize_reduction(load_database): <NEW_LINE> <INDENT> dbf = load_database() <NEW_LINE> eq = equilibrium(dbf, ['AL', 'NI', 'VA'], list(dbf.phases.keys()), {v.P: 101325, v.T: 780, v.X('NI'): 0.625}, verbose=True) <NEW_LINE> ...
Step size reduction required for convergence.
625941df4e4d5625662d4729
def _ciphers_(ciphers): <NEW_LINE> <INDENT> ss = [] <NEW_LINE> for cipher in ciphers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ss.append(wlan.WLAN_CIPHER_SUITE_SELECTORS[cipher]) <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> ss.append('RSRV-{0}'.format(hex(int(e.__str__())))) <NEW_LINE> <DEDENT> <DE...
identifies supported ciphers :param ciphers: the cipher suite stream :returns: a list of supported ciphers
625941df009cb60464c63704
def scrape_prices(self) -> list: <NEW_LINE> <INDENT> cars = self.__cars <NEW_LINE> prices = [] <NEW_LINE> for car in cars: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> price = ( car.find("div", attrs={"class": "announcement-pricing-info"}) .text.strip() .replace(" €", "") .replace(" ", "") .split()[0] ) <NEW_LINE> <DED...
Takes cars soup instance from init method, extracts information about car's price (in euros) from every advertisement and merges the list with self.__prices init method. Parameters: * None Returns: * mileages(list): a list of prices from car adverts. The object is appended to an instance of class.
625941df30bbd722463cc11c
def format_fnames(self, step, fields): <NEW_LINE> <INDENT> return [field + '{0:010d}.dat'.format(step) for field in fields]
Returns a list of file names for a given step
625941df45492302aab5e61c
def unsubscribe(receiver): <NEW_LINE> <INDENT> pass
Unregister an IStatusReceiver. No further status messgaes will be delivered.
625941df38b623060ff0b142
def skip_after_postgres(*ver): <NEW_LINE> <INDENT> ver = ver + (0,) * (3 - len(ver)) <NEW_LINE> @decorate_all_tests <NEW_LINE> def skip_after_postgres_(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def skip_after_postgres__(self): <NEW_LINE> <INDENT> if self.conn.info.server_version >= int("%d%02d%02d" % ver): <NEW_LINE...
Skip a test on PostgreSQL after (including) a certain version.
625941df498bea3a759b9e03
def certi_success(request): <NEW_LINE> <INDENT> search_school_id = None <NEW_LINE> if request.session.get('is_login', None): <NEW_LINE> <INDENT> search_school_id = models.User.objects.get(pk=request.session['user_id']).school <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return redirect("/") <NEW_LINE> <DEDENT> search_...
验证成功页面,三秒后跳转至首页
625941df5166f23b2e1a54ae
def top_ten(subreddit): <NEW_LINE> <INDENT> headers = {"User-Agent": "Frocuts"} <NEW_LINE> url = "http://reddit.com/r/{}/hot.json?limit=10" <NEW_LINE> about = r.get(url.format(subreddit), headers=headers) <NEW_LINE> if about.status_code != 200: <NEW_LINE> <INDENT> print(None) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> abo...
queries the Reddit API and returns the number of subscribers If an invalid subreddit is given, the function should return 0.
625941dfd268445f265b51c3
def _get_service(self, volume): <NEW_LINE> <INDENT> label = utils.extract_host(volume['host'], level='pool') <NEW_LINE> LOG.info(_LI("Using service label: %s"), label) <NEW_LINE> if label in self.config['services'].keys(): <NEW_LINE> <INDENT> svc = self.config['services'][label] <NEW_LINE> if self.config['chap_enabled'...
Get the available service parameters for a given volume using its type. :param volume: dictionary volume reference
625941dfadb09d7d5db6cae2
def arrange_children(self): <NEW_LINE> <INDENT> y0 = self.h + 40 <NEW_LINE> x = 0 <NEW_LINE> for elm in self.shunt_children: <NEW_LINE> <INDENT> elm.setPos(x, y0) <NEW_LINE> x += elm.w + 10 <NEW_LINE> <DEDENT> self.terminal.process_callbacks(self.pos() + self.terminal.pos())
This function sorts the load and generators icons Returns: Nothing
625941df3617ad0b5ed6824b
@memoize <NEW_LINE> def prizes(days, cons_abs=0, late=0): <NEW_LINE> <INDENT> if cons_abs >= 3 or late > 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if days == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return ( prizes(days - 1, late=late) + prizes(days - 1, cons_abs + 1, late) + prizes(days - 1, late=...
Returns how many prize strings exist over a period of `days` days
625941df66656f66f7cbc501
def do_PUT(self): <NEW_LINE> <INDENT> length = int(self.headers.getheader('content-length')) <NEW_LINE> cal = icalendar.Calendar.from_ical(self.rfile.read(length)) <NEW_LINE> for vTodo in cal.walk(): <NEW_LINE> <INDENT> if "UID" in vTodo: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._processVTodo(vTodo) <NEW_LINE>...
Receive a todolist for updating
625941dfa79ad161976cc49b
def reply(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['reply_to'] = self.original_message.id <NEW_LINE> return self._client.send_message(self.original_message.to_id, *args, **kwargs)
Replies to the message (as a reply). Shorthand for `telethon.telegram_client.TelegramClient.send_message` with both ``entity`` and ``reply_to`` already set.
625941df8a349b6b435e84c8
def onProjectLoaded(self, projectManager): <NEW_LINE> <INDENT> if self._data_export_args: <NEW_LINE> <INDENT> self.dataExportApplet.configure_operator_with_parsed_args( self._data_export_args ) <NEW_LINE> <DEDENT> if self._headless and self._batch_input_args and self._data_export_args: <NEW_LINE> <INDENT> logger.info("...
Overridden from Workflow base class. Called by the Project Manager. If the user provided command-line arguments, use them to configure the workflow inputs and output settings.
625941dfdd821e528d63b4fc
def leastInterval(self, tasks, n): <NEW_LINE> <INDENT> counts = {} <NEW_LINE> for item in tasks: <NEW_LINE> <INDENT> if item in counts: <NEW_LINE> <INDENT> counts[item] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> counts[item] = 1 <NEW_LINE> <DEDENT> <DEDENT> keys = [k for k, v in sorted(counts.items(), key=lambd...
:type tasks: List[str] :type n: int :rtype: int
625941df4c3428357757c67b
def test_get_page_data(self): <NEW_LINE> <INDENT> feature_id = self.feature_1.key.integer_id() <NEW_LINE> with test_app.test_request_context(self.request_path): <NEW_LINE> <INDENT> page_data = self.handler.get_page_data( feature_id, self.feature_1, models.INTENT_IMPLEMENT) <NEW_LINE> <DEDENT> self.assertEqual( 'http://...
page_data has correct values.
625941df1f5feb6acb0c4ea0
def setFluidYPeriodic(self): <NEW_LINE> <INDENT> self.bc_yn[0] = 2 <NEW_LINE> self.bc_yp[0] = 2
Set the Y boundaries of the fluid domain to follow the periodic (cyclic) boundary condition. This is the default behavior for the boundary. See also :func:`setFluidYFixedPressure()` and :func:`setFluidYNoFlow()`
625941dfe76e3b2f99f3ab5c
def parse_cmdline_args( self ): <NEW_LINE> <INDENT> from optparse import OptionParser, OptionGroup <NEW_LINE> for arg in sys.argv: <NEW_LINE> <INDENT> self.cmdline = self.cmdline+arg+" " <NEW_LINE> <DEDENT> parser = OptionParser( usage="%prog [options]" ) <NEW_LINE> options = OptionGroup( parser, "Options" ) <NEW_LIN...
Parse the command line arguments for the PTCLM testing script
625941df99fddb7c1c9de6e5
def f1(A, B): <NEW_LINE> <INDENT> A = np.array(A, dtype=bool); B = np.array(B, dtype=bool) <NEW_LINE> C = (A & B).sum() <NEW_LINE> A = A.sum() <NEW_LINE> B = B.sum() <NEW_LINE> R = C / A if A != 0 else 1.0 <NEW_LINE> P = C / B if B != 0 else 1.0 <NEW_LINE> F = 2*P*R/(P+R) if (P+R) != 0 else 1.0 <NEW_LINE> return F
Compute the F1 measure on two bit vectors. >>> f1([1], [1]) 1.0 >>> f1([1], [0]) 0.0 >>> f1([1,0,1], [0,1,1]) 0.5
625941df32920d7e50b28528
def colors(enabled: Optional[bool] = None) -> Union[_Color, _NoColor]: <NEW_LINE> <INDENT> if enabled is None: <NEW_LINE> <INDENT> env = pw_cli.env.pigweed_environment() <NEW_LINE> enabled = env.PW_USE_COLOR or (sys.stdout.isatty() and sys.stderr.isatty()) <NEW_LINE> <DEDENT> if enabled and os.name == 'nt': <NEW_LINE> ...
Returns an object for colorizing strings. By default, the object only colorizes if both stderr and stdout are TTYs.
625941df435de62698dfdfa2
def fxr_dp(): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> T = [[0]*2 for _ in range(n+1)] <NEW_LINE> mx = nums[0]**2 <NEW_LINE> for i in range(1, n+1): <NEW_LINE> <INDENT> T[i][0] = nums[i-1] + max(T[i-1][0], 0) <NEW_LINE> T[i][1] = max( nums[i-1]**2 + max(T[i-1][0], 0), nums[i-1] + max(T[i-1][1], 0) ) <NEW_LINE> mx =...
Runtime: 1560 ms, faster than 18.81% of Python3 online submissions for Maximum Subarray Sum After One Operation. AC in 1! (inspired from 376. Wiggle Subsequence & 309. Best Time to Buy and Sell Stock with Cooldown) Metacognition: T[n][0 or 1] 0: till now, max subarray sum including nums[i] 1: till now one item...
625941df3eb6a72ae02ec83b
def test_station_id_not_in_dictionary(): <NEW_LINE> <INDENT> df = parse_metar_to_dataframe('METAR KLBG 261155Z AUTO 00000KT 10SM CLR 05/00 A3001 RMK ' 'AO2=') <NEW_LINE> assert df.station_id.values == 'KLBG' <NEW_LINE> assert_almost_equal(df.latitude.values, np.nan) <NEW_LINE> assert_almost_equal(df.longitude.values, n...
Test for when the METAR does not correspond to a station in the dictionary.
625941df30bbd722463cc11d
def getFileNameBase(outFlags,outFileByFlag,default): <NEW_LINE> <INDENT> if outFlags: <NEW_LINE> <INDENT> logging.debug("Output Flags: \n%r", outFlags) <NEW_LINE> logging.debug("Output Files \n%r", outFileByFlag) <NEW_LINE> best_file = None <NEW_LINE> for flag in outFlags: <NEW_LINE> <INDENT> out_file = outFileByFlag.g...
what do we name all the log files?
625941df851cf427c661a862
def main(): <NEW_LINE> <INDENT> args = get_args() <NEW_LINE> uname = args.uname <NEW_LINE> if auth.authentication(uname): <NEW_LINE> <INDENT> itf.build_itf() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Sorry! You're not authorized.")
Build the magic!
625941df6fece00bbac2da97
def count(self, arg): <NEW_LINE> <INDENT> args = shlex.split(arg) <NEW_LINE> models.storage.reload() <NEW_LINE> if len(args) < 1: <NEW_LINE> <INDENT> print(self.errors["missingClass"]) <NEW_LINE> <DEDENT> elif args[0] in self.classes: <NEW_LINE> <INDENT> instances = str(models.storage.all().keys()) <NEW_LINE> print(ins...
Prints the number of instances of a class. usage: count <class_name>
625941df1b99ca400220ae08
def examples2features(examples, max_seq_length, tokenizer): <NEW_LINE> <INDENT> def tokenize_text(text): <NEW_LINE> <INDENT> text = text[0: max_seq_length] <NEW_LINE> _tokens = [] <NEW_LINE> for word in text: <NEW_LINE> <INDENT> token = tokenizer.tokenize(word) <NEW_LINE> _tokens.extend(token) <NEW_LINE> <DEDENT> retur...
从 InputExamples 转化为 ModelFeatures
625941dfcc0a2c11143dd1e7
def update(self, words): <NEW_LINE> <INDENT> for word in words: <NEW_LINE> <INDENT> self.add(word)
add all elements in words to the trie
625941dfac7a0e7691ed441c
def GetWindowMaximum(self): <NEW_LINE> <INDENT> return _itkIntensityWindowingImageFilterPython.itkIntensityWindowingImageFilterID2IUC2_GetWindowMaximum(self)
GetWindowMaximum(self) -> double
625941df498bea3a759b9e04
def test_add_adblock_entry_without_force_with_target_having_multiple_names(tmpdir): <NEW_LINE> <INDENT> ipv4_line = '0.0.0.0 example.com' <NEW_LINE> hosts_file = tmpdir.mkdir("etc").join("hosts") <NEW_LINE> hosts_file.write(ipv4_line) <NEW_LINE> hosts_entries = Hosts(path=hosts_file.strpath) <NEW_LINE> assert hosts_ent...
Test that addition of an adblock entry does not succeed if force is not set and there is a matching name (matching names)
625941df435de62698dfdfa3
def compute_tiles_for_zoom(self, zoom, tiles): <NEW_LINE> <INDENT> pzoom = pow(2, zoom - 1) <NEW_LINE> bound = int(pow(2, zoom)) <NEW_LINE> tw = TILE_W / float(pzoom) <NEW_LINE> th = TILE_H / float(pzoom) <NEW_LINE> ret = True <NEW_LINE> pzw = pzoom / float(TILE_W) <NEW_LINE> pzh = pzoom / float(TILE_H) <NEW_LINE> minx...
Calculate and put on `tiles` all tiles needed to draw this zoom level.
625941df4527f215b584c7a9
def add_token_with_properties(self, *props_and_vals): <NEW_LINE> <INDENT> token = Token(len(self.token_map)) <NEW_LINE> for name, (level, val) in props_and_vals: <NEW_LINE> <INDENT> token.add_property(name, val, level) <NEW_LINE> <DEDENT> self.token_map[token.index] = token
Add a token that has the provided properties and values. Args: props_and_vals: (<token_property>, (<level>, <value>)) pairs.
625941df377c676e912724fd
def apply(self, f, x, x0, evaluation, options): <NEW_LINE> <INDENT> x0 = apply_N(x0, evaluation) <NEW_LINE> if not isinstance(x0, Number): <NEW_LINE> <INDENT> evaluation.message("FindRoot", "snum", x0) <NEW_LINE> return <NEW_LINE> <DEDENT> x_name = x.get_name() <NEW_LINE> if not x_name: <NEW_LINE> <INDENT> evaluation.m...
FindRoot[f_, {x_, x0_}, OptionsPattern[]]
625941df656771135c3ebbc8
def lm_train(data_dir, language, fn_LM): <NEW_LINE> <INDENT> language_model = dict() <NEW_LINE> language_model['uni'] = dict() <NEW_LINE> language_model['bi'] = dict() <NEW_LINE> for file in os.listdir(data_dir): <NEW_LINE> <INDENT> if file[-1] == language: <NEW_LINE> <INDENT> data = open(data_dir + file, 'r') <NEW_LIN...
This function reads data from data_dir, computes unigram and bigram counts, and writes the result to fn_LM INPUTS: data_dir : (string) The top-level directory continaing the data from which to train or decode. e.g., '/u/cs401/A2_SMT/data/Toy/' language : (string) either 'e' (English) or 'f' (Fre...
625941df6aa9bd52df0370fb
@pytest.mark.usefixtures("user") <NEW_LINE> def test_login_inactive(extended_app): <NEW_LINE> <INDENT> assert is_user_logged(extended_app) is False <NEW_LINE> authenticate(extended_app) <NEW_LINE> assert is_user_logged(extended_app) is True
Log in inactive user.
625941df71ff763f4b5499e7
@babel.localeselector <NEW_LINE> def get_locale(): <NEW_LINE> <INDENT> return request.accept_languages.best_match(LANGUAGES.keys())
Retrieve locale based on available languages
625941df8e7ae83300e4b323
def get_sample_rate(self): <NEW_LINE> <INDENT> return self.__sample_rate
Sample rate in samples per second.
625941df167d2b6e31218eeb
@check_auth <NEW_LINE> @insert_repo <NEW_LINE> @check_supplier <NEW_LINE> def add_brand(event, context): <NEW_LINE> <INDENT> logger.debug('event: {}'.format(event)) <NEW_LINE> try: <NEW_LINE> <INDENT> body = get_body(event) <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> return { 'statusCode': 400,...
Add a new brand
625941dffbf16365ca6f651f
def add_statement(self, statement): <NEW_LINE> <INDENT> self.statements.append(statement)
:param Statement statement: statement to be added
625941df26068e7796caf039
def prepare_empty_partition_squashfs(self, cr_workdir, oe_builddir, native_sysroot): <NEW_LINE> <INDENT> msger.warning("Creating of an empty squashfs %s partition was attempted. " "Proceeding as requested." % self.mountpoint) <NEW_LINE> fs = "%s/fs_%s.%s" % (cr_workdir, self.label, self.fstype) <NE...
Prepare an empty squashfs partition.
625941df5166f23b2e1a54af
def _method_lookup(self, method_name, dbus_interface): <NEW_LINE> <INDENT> parent_method = None <NEW_LINE> candidate_class = None <NEW_LINE> successful = False <NEW_LINE> if dbus_interface: <NEW_LINE> <INDENT> for cls in self.__class__.__mro__: <NEW_LINE> <INDENT> if not candidate_class and method_name in cls.__dict__:...
Walks the Python MRO of the given class to find the method to invoke. Returns two methods, the one to call, and the one it inherits from which defines its D-Bus interface name, signature, and attributes.
625941df8e71fb1e9831dafe
def get_cashf_concepthist_EM(bkname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> df=pd.read_pickle('output/eastmsource/bk.pkl') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> df=pd.read_csv('output/eastmsource/bk.csv',encoding='gbk') <NEW_LINE> <DEDENT> idd=df[df['name']==bkname]['id'].tolist()[0] <NEW_LINE> url='ht...
板块的历史资金流向,资金流入金额的单位均为万元 -------------------------------------- Main.I.net :今日主力净流入净额 Main.I.R :今日主力净流入净占比
625941dfa05bb46b383ecb75
def _import_source_data(self, source_file: str) -> None: <NEW_LINE> <INDENT> with open(source_file, 'r') as csv_file: <NEW_LINE> <INDENT> reader = csv.DictReader(csv_file) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> self.cell_map.append( Cell( datamap_id=None, cell_key=row['cell_key'], cell_value=None, cell_refer...
Internal implementation of csv importer.
625941df7cff6e4e81117cdb
def test_put_car_fail_invalid_ints(self, client): <NEW_LINE> <INDENT> response = client.put( '/api/car', json={ "car_id": "1", "username": "admin", "make": "Toyota", "body_type": "SUV", "colour": "Black", "no_seats": -5, "location": "32.426998,-81.754753", "cost_per_hour": -20 } ) <NEW_LINE> expected_data = b'{"message...
Testing that updating a car fails when inputting an invalid number of seats and invalid cost per hour
625941dfd164cc61757830a5
def get_mean_spike_template_amplitudes(self, cluster_id): <NEW_LINE> <INDENT> spike_ids = self._get_amplitude_spike_ids(cluster_id) <NEW_LINE> return np.mean(self.get_spike_template_amplitudes(spike_ids))
Return the average of the spike template amplitudes.
625941dfb7558d58953c5264
def list_(): <NEW_LINE> <INDENT> url = '{0}/api/slicing'.format(__opts__['pillar']['proxy']['url']) <NEW_LINE> return salt.utils.http.query( url, header_dict={'X-Api-Key': __opts__['pillar']['proxy']['apikey']}, opts=__opts__, decode=True, decode_type='json', )['dict']
List OctoPrint slicers and slicing profiles CLI Example: .. code-block:: bash salt octominion slicer.list
625941dfc4546d3d9de72d8d
def ContainsKey(self,key): <NEW_LINE> <INDENT> pass
ContainsKey(self: StringDictionary,key: str) -> bool Determines if the System.Collections.Specialized.StringDictionary contains a specific key. key: The key to locate in the System.Collections.Specialized.StringDictionary. Returns: true if the System.Collections.Specialized.StringDictionary contains an entry ...
625941df796e427e537b091e
def _draw_objects(self) -> None: <NEW_LINE> <INDENT> self._space.debug_draw(self._draw_options)
Draw the objects. :return: None
625941df8a349b6b435e84c9
def drawDebugRects(self, image): <NEW_LINE> <INDENT> if utils.is_gray(image): <NEW_LINE> <INDENT> faceColor = 255 <NEW_LINE> leftEyeColor = 255 <NEW_LINE> righEyeColor = 255 <NEW_LINE> noseColor = 255 <NEW_LINE> mouthColor = 255 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> faceColor = (255, 255, 0) <NEW_LINE> leftEyeC...
Draw rectangles around the detected objects :param image: :return:
625941dfcad5886f8bd2732f
def run(self): <NEW_LINE> <INDENT> conf_ctx = self.generator <NEW_LINE> filename = self.inputs[0].abspath() <NEW_LINE> compiled_prog_paths = get_runtime_paths(conf_ctx, filename) <NEW_LINE> conf_ctx.env.append_value("RPATH", list(compiled_prog_paths))
Discover what RPATHs are necessary for a binary compiled with our compiler
625941dfb7558d58953c5265
def get_figsuptitle(self): <NEW_LINE> <INDENT> return self.figsuptitle
:returns: the main title of the plot. :TODO: remove the method and use the direct reference.
625941dfa05bb46b383ecb76
def connect(self, device): <NEW_LINE> <INDENT> print('Connecting %s to %s' % (device.name, self.name)) <NEW_LINE> self.device = device <NEW_LINE> self.hostnames = []
This function takes the device connecting to the switch and adds it to a list of connected devices. This function also maintains a dictionary of devices and the ports to which they are connected.
625941dff9cc0f698b14094f
def create_app(config_name): <NEW_LINE> <INDENT> app = Flask(__name__) <NEW_LINE> CORS(app) <NEW_LINE> app.config['CORS_HEADERS'] = 'Content-Type' <NEW_LINE> app.config.from_object(app_config[config_name]) <NEW_LINE> from app.question.views import QUESTION_APP <NEW_LINE> from app.auth.views import AUTH_BLUEPRINT <NEW_L...
Creates the application and registers the blueprints with the application
625941df3d592f4c4ed1d3bc
def testWriteText(self): <NEW_LINE> <INDENT> test_output_writer = output_writers.StdoutOutputWriter() <NEW_LINE> test_output_writer.WriteText('Test')
Tests the WriteText function.
625941df956e5f7376d711c2
def send_command_expect(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.send_command(*args, **kwargs)
Palo Alto requires an extra delay
625941dfcc40096d61595ca6
def constructGeometryMatrix(planes, cells): <NEW_LINE> <INDENT> splittingList = [] <NEW_LINE> for cellNo, cell in enumerate(cells): <NEW_LINE> <INDENT> for planeNo, wire in enumerate(cell.wires): <NEW_LINE> <INDENT> splittingList.append(utilities.getChannelNo(planes, wire[0], planeNo)) <NEW_LINE> splittingList.append(u...
Make a matrix that associates merged wires and cells based on detector Geometry Parameters ---------- planes : list of PlaneInfo A list containing information for all the planes in the detector cells : list of Cell List of cells Reconstructed from Geometric information Returns ------- list of tuple[2] int, np...
625941dfd486a94d0b98e49d
def get_final_bin_path(env) -> pathlib.Path: <NEW_LINE> <INDENT> firmware_dir = get_override_path(BIN_DIR, env) <NEW_LINE> firmware_dir.mkdir(parents=True, exist_ok=True) <NEW_LINE> return firmware_dir / "{}.bin".format(get_variant(env))
Path to the final destination for the .bin If the parent directory does not exist, it will be created
625941df73bcbd0ca4b2c3cd
def identificador(dados): <NEW_LINE> <INDENT> dados = dados.split('#') <NEW_LINE> tipo = dados[0].strip().lower() <NEW_LINE> numero = dados[1].strip().zfill(4) <NEW_LINE> data = dados[2].strip().split('/').pop().split('-').pop() <NEW_LINE> return "{tipo}-{numero}-{data}".format(tipo=tipo, numero=numero, data=data)
Gera identificadores a partir dos primeiros campos na tabela
625941df99fddb7c1c9de6e6
def p_expr_cast_double(p): <NEW_LINE> <INDENT> pass
expr : DOUBLE_CAST expr
625941dfd99f1b3c44c678e0
def generate_steps(self, xy_list, seq_state, input_path=[]): <NEW_LINE> <INDENT> for xy in xy_list: <NEW_LINE> <INDENT> if xy in self.valid_xy[seq_state]: <NEW_LINE> <INDENT> path = input_path + [xy] <NEW_LINE> self.valid_xy[seq_state].remove(xy) <NEW_LINE> yield Step(path=path, seq_state=seq_state)
Generate steps dynamically from a static list of input coordinates, so that we do not visit the same step twice :param xy_list: list of (x,y) coordinate tuples :param seq_state: state in colour sequence to generate steps for :param input_path: current path to prepend to step xy coordinates :returns: Step object
625941df3cc13d1c6d3c76d0
def image_crawl_requests(): <NEW_LINE> <INDENT> headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.68 ' } <NEW_LINE> img_url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa2.att.hudong.com%2F74%2F24' ...
requests直接抓取图片 with持续化存储 :return: 一个jpg文件
625941dffb3f5b602dac39ed
def get_random_cell(self): <NEW_LINE> <INDENT> rand_index = np.random.randint(self.n_cells) <NEW_LINE> return self.inhabitable_coord[rand_index]
Gets indexes of a random cell that has civilization.
625941df8e05c05ec3eea6ce
def test_accumulate_D8(dans_grid1): <NEW_LINE> <INDENT> fr = FlowAccumulator(dans_grid1.mg, flow_director="D8") <NEW_LINE> fr.run_one_step() <NEW_LINE> assert_array_equal(dans_grid1.A_target, dans_grid1.mg.at_node["drainage_area"]) <NEW_LINE> assert_array_equal( dans_grid1.frcvr_target, dans_grid1.mg.at_node["flow__rec...
Test accumulation works for D8 in a simple scenario.
625941df7cff6e4e81117cdc
def get_tags_v2(): <NEW_LINE> <INDENT> tags = list() <NEW_LINE> tree = ET.ElementTree(file=RSS_FEED) <NEW_LINE> for node in tree.iter(): <NEW_LINE> <INDENT> if node.tag == 'category': <NEW_LINE> <INDENT> tags.append(node.text.replace('-', ' ')) <NEW_LINE> <DEDENT> <DEDENT> return tags
Find all tags in RSS_FEED. Replace dash with whitespace.
625941df26068e7796caf03a
@contextlib.contextmanager <NEW_LINE> def FlagReplacer(device, command_line_path, new_flags): <NEW_LINE> <INDENT> if not device: <NEW_LINE> <INDENT> yield <NEW_LINE> return <NEW_LINE> <DEDENT> changer = flag_changer.FlagChanger(device, command_line_path) <NEW_LINE> changer.ReplaceFlags(new_flags) <NEW_LINE> try: <NEW_L...
Replaces chrome flags in a context, restores them afterwards. Args: device: Device to target, from DeviceUtils. Can be None, in which case this context manager is a no-op. command_line_path: Full path to the command-line file. new_flags: Flags to replace.
625941df3eb6a72ae02ec83c
def __call__(self, bb, n): <NEW_LINE> <INDENT> bb = np.array(bb, dtype='float32') <NEW_LINE> sample = np.array([bb[0] + bb[2] / 2, bb[1] + bb[3] / 2, bb[2], bb[3]], dtype='float32') <NEW_LINE> samples = np.tile(sample[None, :], (n, 1)) <NEW_LINE> if self.aspect_f is not None: <NEW_LINE> <INDENT> ratio = np.random.rand(...
sample产生器 :param bbox: input_bbox :param n: amount :return: samples_location
625941df627d3e7fe0d691a8
def as_neuralstate(self) -> NeuralState: <NEW_LINE> <INDENT> v = self.as_matrix().flatten() <NEW_LINE> n = NeuralState(self.size, self.size, False, -1, initial_vector=v) <NEW_LINE> return n
Create a neural state with the generated vector as neural vector :return: NeuralState
625941df2c8b7c6e89b35b15
def filter(self, environment_state): <NEW_LINE> <INDENT> if self.sensing_threshold is None: <NEW_LINE> <INDENT> filtered_signal = environment_state <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = len(environment_state) <NEW_LINE> if count < self.sensing_threshold: <NEW_LINE> <INDENT> filtered_signal = [] <NEW_LIN...
Filter out uninteresting states. In this case uninteresting means states in which less then a specific number of requests could be served. Args: environment_state (list): Set of routed requests. Returns: filtered_signal (np.ndarray)
625941df7c178a314d6ef7bc
def face_coeffs(self, F): <NEW_LINE> <INDENT> return self.get("face_coeffs", F)
Returns the coefficients associated to each integration of a face. Only for approximate methods, this has no meaning for exact integration methods!
625941df656771135c3ebbc9
def hydrate(drink_string): <NEW_LINE> <INDENT> drink_total = sum(list(map(int,re.findall('[\d]+', drink_string)))) <NEW_LINE> glasses = ('glass' if drink_total == 1 else 'glasses') <NEW_LINE> return '{} {} of water'.format(drink_total, glasses)
Returns number of waters to balance alcoholic drinks found in drink string
625941df96565a6dacc8fa21
def intersect(self, nums1, nums2): <NEW_LINE> <INDENT> import collections <NEW_LINE> dic = collections.defaultdict(int) <NEW_LINE> ans = [] <NEW_LINE> for x in nums1: <NEW_LINE> <INDENT> dic[x] += 1 <NEW_LINE> <DEDENT> for x in nums2: <NEW_LINE> <INDENT> if x in dic and dic[x] > 0: <NEW_LINE> <INDENT> dic[x] -= 1 <NEW_...
:type nums1: List[int] :type nums2: List[int] :rtype: List[int]
625941df046cf37aa974d09c
def index(self, namespace=0, start=None, count=100, cached=True, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault("unicode", True) <NEW_LINE> kwargs.setdefault("throttle", self.throttle) <NEW_LINE> id = kwargs.pop("_id", "title") <NEW_LINE> while start != -1: <NEW_LINE> <INDENT> url = URL(self._url, method=GET, query={...
Returns an iterator over all article titles (for a given namespace id).
625941df009cb60464c63706
def rm_outlier_pixels(data, rows, cols, set_to_zero=False): <NEW_LINE> <INDENT> if set_to_zero: <NEW_LINE> <INDENT> data[rows, cols] = 0. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert(len(rows) == len(cols)) <NEW_LINE> for x, y in zip(rows, cols): <NEW_LINE> <INDENT> data[x,y] = np.median(data[x-1:x+1,y-1:y+1]) ...
WARNING: this function mutates the input array "data"!!!
625941dfe1aae11d1e74a011
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'socialmini.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you s...
Run administrative tasks.
625941dfe5267d203edcdff0
def create_vm(self, group_name, vm_name, vm_parameters): <NEW_LINE> <INDENT> if self.error_in_create: <NEW_LINE> <INDENT> self.error_in_create = False <NEW_LINE> raise Exception("Error creating VM") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> async_vm_creation = MagicMock() <NEW_LINE> async_vm_creation.wait.side_effe...
Create VMs returning error only first time
625941df7b25080760e397af
@app.post('/recommend', response_model=ItemsOutput, summary='Items most relevant to given user', response_description='Recommended items', ) <NEW_LINE> def recommend(user_items: Items): <NEW_LINE> <INDENT> recommended = app.reco.recommend(user_items.ids) <NEW_LINE> return {'recommended_products': recommended}
- **user_items**: IDs of user items
625941df796e427e537b091f
def allPossibleFBT_best(self, N): <NEW_LINE> <INDENT> res = [] <NEW_LINE> if not N%2: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> if N == 1: <NEW_LINE> <INDENT> return [TreeNode(0)] <NEW_LINE> <DEDENT> if N in self.memo: <NEW_LINE> <INDENT> return self.memo[N] <NEW_LINE> <DEDENT> for i in range(1,N,2): <NEW_LINE...
:type N: int :rtype: List[TreeNode]
625941df5166f23b2e1a54b0
def _AddParserForUriPath(self, api_name, api_version, subcollection, parser, path): <NEW_LINE> <INDENT> tokens = [api_name, api_version] + path.split('/') <NEW_LINE> cur_level = self.parsers_by_url <NEW_LINE> while tokens: <NEW_LINE> <INDENT> token = tokens.pop(0) <NEW_LINE> if token[0] == '{' and token[-1] == '}': <NE...
Registers parser for given path.
625941dfd10714528d60003e
@contextlib.contextmanager <NEW_LINE> def handled_exceptions(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> except exc.CommunicationError: <NEW_LINE> <INDENT> msg = _('Unable to communicate to murano-api server.') <NEW_LINE> LOG.exception(msg) <NEW_LINE> _handle_message(request, msg) <...
Handles all murano-api specific exceptions.
625941df29b78933be1e59fe
def get_next_available_id(session, table_field, id_type): <NEW_LINE> <INDENT> min_value = MAPPING_LIMITS[id_type][0] <NEW_LINE> max_value = MAPPING_LIMITS[id_type][1] <NEW_LINE> rows = session.query(table_field).order_by(table_field) <NEW_LINE> used_ids = set([row[0] for row in rows]) <NEW_LINE> all_ids = set(range(min...
Find first unused id for the specified field in IdentifierMap table. As entries are removed, find the first "hole" and return that as the next available ID. To improve performance, artificially limit the number of entries to a smaller range. Currently, these IDs are globally unique. Could enhance in the future to be u...
625941dfac7a0e7691ed441d