content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def weighted_score(raw_earned, raw_possible, weight): """ Returns a tuple that represents the weighted (earned, possible) score. If weight is None or raw_possible is 0, returns the original values. When weight is used, it defines the weighted_possible. This allows course authors to specify the exa...
98ec27ebe606586811945650c18772801edd80a0
45,100
def get_coderef_from(vw, va): """ return first code `tova` whose origin is the specified va return None if no code reference is found """ xrefs = vw.getXrefsFrom(va, REF_CODE) if len(xrefs) > 0: return xrefs[0][XR_TO] else: return None
c3042b1fee0f2aef7952f08e58c7610c96a9e9ae
45,101
def search(word: str) -> str: """查询es中朗文4的example """ if not USE_ES or not CONNECTED_ES: return "" dsl = { "query": { "match": { "han": word } } } res = esClt.search(index=INDEX, body=dsl) html = """<span>朗文4相关例句</span><link re...
a8c380879691a77a797554b835c6529337fef7d1
45,102
def tempDiffRestrict(primerInfo, maxTempDiff=MAX_TEMP_DIFF): """Checks the differnce in annealing temperatures between two primers. Difference should not be greater than 5 degrees.""" for key in primerInfo.copy(): if abs(primerInfo[key][0][1] - primerInfo[key][1][1]) > maxTempDiff: de...
6bb5453e02a60e8cee9039c27ae4240025a9ae0d
45,103
def get_compiler_dir(compiler_name): """ Try to figure out the compiler directory based on the input compiler name. This is fragile and really should be done at the distutils level inside the compiler. I think it is only useful on windows at the moment. """ compiler_type = choose_c...
2cbadc250658a60ea00b698c709ca28b7df99d26
45,104
def PairOHLCSchema(pair): """helper function to embed OHLC data frame parsing into a field with any name... returns a new instance of the class, creating the class if needed """ def build_model(self, data, **kwargs): assert len(data.get('error', [])) == 0 # Errors should have raised except...
b3ccbfb40fb50753f7a63c4b7d319a606e881c74
45,105
def sum_GaussLorentz(x, centers, amplitudes, widths, shapes, baselevels): """add mixed Gauss-Lorentzian curves together Parameters ---------- x : list-like centers, amplitudes, widths, shapes : list-like, 1-dimensional parameters for the individual curves. Lists have lenght n for n curves. ...
3f855f173566bf33375f400e82575ddc4480038e
45,106
def randn(*size, **kwarg): """Returns an array of standard normal random values. Each element of the array is normally distributed with zero mean and unit variance. All elements are identically and independently distributed (i.i.d.). Args: size (ints): The shape of the array. dtype...
5c05e64fd974709cdc4f29d010ef52943233a3fa
45,107
def is_registered(subject, license_uri, metadata): """ Checks for work registration assertions """ # shorthand accessor triples = metadata['triples'] # first check for a has_owner assertion if subject not in metadata['subjects'] or \ not triples[subject].has_key(SIOC('has_owner')): ...
6895a0454339f952e0b04a982519826ff6727cf9
45,108
import os def list_images(): """Obtain a list of available version of OneFS nodes that can be created :Returns: List """ images = os.listdir(const.VLAB_ONEFS_IMAGES_DIR) images = [convert_name(x, to_version=True) for x in images] return images
9cfbafb379a67e52b41c8a76cf0533200c1643b4
45,109
import pandas import traceback def stddev_from_average(timeseries): """ A timeseries is anomalous if the absolute value of the average of the latest three datapoint minus the moving average is greater than three standard deviations of the average. This does not exponentially weight the MA and so i...
a755ffa60301435895ad8e1f509864e9e9e3ee65
45,110
def call_base_class_method_with_same_name(obj): """ Run base class method. :param obj: class object which methods will be decorated. :return: class object with decorated methods """ if hasattr(obj, "__dict__"): if obj.__dict__.items(): for attributeName in dir(obj): ...
c53d646f4a9aaeb7f8dd7db74eb43414fd2459ae
45,111
def find_matches(descriptors, filter_matches=True): """Match descriptors to themselves Parameters ---------- descriptors: array_like, shape=[n_keypoints, n_features] The array of descriptors Returns ------- matches: list of cv2.Match The found matches """ print(f"Nu...
c0026679c186d46fd977553a871e1c86985b25e4
45,112
def grade_generic(grader_data, numeric_features, textual_features): """ Grades a set of numeric and textual features using a generic model grader_data -- dictionary containing: { 'algorithm' - Type of algorithm to use to score } numeric_features - list of numeric features to predict on ...
a56b4937f73a220449f418677bc689d85f3fcb69
45,113
from core.rule import Rule from conf.rules import getTypeObject from utils.wiki import create_wikirule def add_rule(**kwargs): """ Create a Rule Object from information passed by user, and return a TypeObject who contain the new rule Object. Keyword Args: type (list of one str): rule's type (...
26a22bd6b4a9274b3ab0ec3c782edf41636f1869
45,114
def polygon_from_xywh(xywh): """Construct polygon coordinates in numeric list representation from numeric dict representing a bounding box.""" return polygon_from_bbox(*bbox_from_xywh(xywh))
59fe9fd9bbe3d59075ccfb840c3aa3ceaf570490
45,115
def cargar_datos(): """ Funcion para cargar los datos de la base de datos """ # Cargar datos de la base de datos path_archivos = "./Data/" data_CF = pd.read_csv(path_archivos + "mmm.csv") return data_CF
f4e466c0201256690d3da7c62b5eccc84de6f678
45,116
def bestIndividual(hof, X, y): """ Get the best individual """ _individual = None minAccurcy = 2.0 for individual in hof: # if (individual.fitness.values > maxAccurcy): if individual.fitness.values[0] < minAccurcy: minAccurcy = individual.fitness.values[0] ...
37ced7bf5404243ab5173acb7866eb4aeceaee9a
45,117
def clean_phone(phone_number, drop_invalid=False, area_code='406'): """Standardizes phone number formatting for American numbers""" # Removes non-digit characters clean_number = digit_only(phone_number) # Removes US country code if present if len(clean_number) == 11 and clean_number[0] == '1':...
da3a14d4708ee60e5ade09a42396684419e4943c
45,118
def create_person(person_dto): """ Create a new user from provided data transfer object. :param person_dto: Data transfer object to convert from. :type person_dto: PersonDto :returns: (PersonDto, id) """ # TODO: implement duplicate check -- need another unique identifier for people pr...
edb3ff2eb89a817e2a5ec645d76635a2cf6346f3
45,119
def show_user_status(): """Return True if the application is configured to use the user_status block""" return _django_status_enabled() or _ceda_status_enabled()
769b9903a31084e46b9fc3f40410ffebce6be6e1
45,120
def split_dataset(df, train_proportion, valid_proportion): """Split a dataframe into a train, validation, and test set. The size of the test set will be 1.0 minus the given train and valid proportion. Parameters df - pandas.core.frame.DataFrame The dataframe to split train_propo...
84562dceeaacfa23b1bd50e55b87b0b2f80ed911
45,121
def get_crawl_rate(): """Get the rate used to crawl Parameters ---------- None Returns ------- float The current web crawling rate """ return GLContainer.get_crawl_rate()
93dee16eb0aef93068e6fa618cc81eb56ca38052
45,122
def and_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_...
4541531cd46e7a5d1ce726b6f25232b016132ce9
45,123
def config_get_state_power_on(config): """Get command/result on.""" return config[CONF_STATE][STATE_ON]
d32a024ee1832d0788704b70d73c48c816321774
45,124
def addr_entry(key): """querries the user for address data, cleans it""" # getting the input rawline = input( 'please enter ' + key + ': ' ) # get rid of trailing whitespace line = rawline.strip() # replace tabs line = line.replace('\t', ' ') # remove forbidden strings ...
3edf6a39a276f9abb63ee5930a907b75ba3c623a
45,125
from typing import Union from typing import Type def process_validate_module(event_obj: Event, step_execution_id: Union[int, Type[int]]) -> bool: """ Process validate_cryton_module :param event_obj: Event object :param step_execution_id: Step execution ID :return: True or False, depending on valid...
a6a1431e84ccf4244491033c62b8225b63c6e601
45,126
import torch def extract_neighborhood_sets( o1: torch.Tensor, o2: torch.Tensor, s1: torch.Tensor, s2: torch.Tensor, dist1: torch.Tensor, im1seeds: torch.Tensor, im2seeds: torch.Tensor, k1: torch.Tensor, k2: torch.Tensor, R1: float, R2: float, fnn12: torch.Tensor, ORIENTATION_THR: float...
485c505a350f1f1ef027088d8c44fea6fe53f8e3
45,127
import argparse def parse_arguments(): """ Read in the config file specifying all of the parameters """ parser = argparse.ArgumentParser(description="Learn subgraph embeddings") parser.add_argument("-config_path", type=str, default=None, help="Load config file") args = parser.parse_args() ...
f3f443f4df33718903132b721869eb276dbe855b
45,128
def calculate_l2r_matrix(left_extrinsics: np.ndarray, right_extrinsics: np.ndarray) -> np.ndarray: """ Return the left to right transformation matrix: l2r = R * L^-1 """ l2r = np.matmul(right_extrinsics, np.linalg.inv(left_extrinsics)) return l2r
330f58362f47e7ebd29ee800da6a89bd8ea46a15
45,129
def load_data(messages_filepath, categories_filepath): """ Load messages and categories from dataset Args: message_filepath(string): the file path of messages.csv categories_filepath(string): the file path of categories.csv Return: df(Dataframe): merged dataframe of message...
c72ee4f9b41cc5f31751551b4a48fa76dd05cdc1
45,130
def total_units_given(type_, value, start, end): """ Find total units given for a dose """ if type_ in [DoseType.bolus, DoseType.suspend]: return value return value * hours(end, start)
2caa0dc55c04c38697936b68f3bc5ceb7c32dc9c
45,131
def process_season_matches(season_matches_df): """Processes raw season match data into parsable match and table data. :param season_matches_df: Dataframe as returned by get_season_matches function :return: 3 dataframes: expanded_df with match info, table_df with match outcome info, and grouped_table_df ...
6bbbf1bc76870b75e429bdb8719e0af6d6fa888c
45,132
import base64 def decode_argument_value(name, value): """ Decodes the value of an argument. The value is assumed to be Base64 encoded :param name: The name of the argument that is being decoded :param value: The encoded value of the argument. It is assumed to be Base64 encoded :return: The decod...
b21687a6c41f5080ca0557a0d89479fce13497a0
45,133
def _lr(k, x, size): """Helper function to fit one gene""" ashr = rpy2.robjects.packages.importr('ashr') lam = x / size if np.isclose(lam.min(), lam.max()): return k, 0 else: res0 = scmodes.ebpm.ebpm_unimodal(x, size) res1 = scmodes.ebpm.ebpm_npmle(x, size) return k, np.array(res1.rx2('loglik'...
d0712478585cc573e1fa63b4330e2b4ba9074e30
45,134
def get_text_from_image(input_file: str, lang: str = "eng", tessdata_prefix: str = "") -> str: """ Get text from image using Tesseract OCR. Parameters ---------- input_file : str lang : str | Language which will Tesseract use for OCR. Avai...
ccfef30c90bad95a749fe97c031d9612211ccbf3
45,135
def create_msms_dataframe(df): """ create a dataframe organized into spectra from a raw dataframe of points """ #removed polarity and hdf5_file if 'precursor_MZ' in df.columns: grouped = df.groupby(['precursor_MZ','rt','precursor_intensity','collision_energy']).aggregate(lambda x: tuple(x)) ...
30b777dbac946d4e65f09ef80b160ee0b935dad2
45,136
def penn_to_wn(tag): """ Convert PENN to WordNet Format Args: tag (str): PENN Tag Returns: str: Wordent Representation """ try: if tag.startswith('J'): return wn.ADJ elif tag.startswith('N'): return wn.NOUN elif tag.startswith('...
4946a7e7491d0b7c27e32ec81d17cb091f92f91b
45,137
def add_landingpage_on_nav_page(sender, request=None, **kwargs): """ Receive the 'nav_organizer' signal which triggers when controlling an organization.\n If this signal occurs, the 'Landing Page' tab will be added to the menu bar on the left side.\n With the added tab you'll have access to the Landi...
f33cad80d9018df3d3b3e7017bb7c0a57b79b489
45,138
def process_code_blocks(filestr, code_style, format): """Process a filestr with code blocks Loop through a file and process the code it contains. :param str filestr: text string :param str code_style: optional typesetting of code blocks :param str format: output formatting, one of ['html', 'latex',...
4629df4da2acc4fcb8ca6d2bdf4b3a74a081aad8
45,139
def vgg_net(): """ https://arxiv.org/pdf/1409.1556.pdf """ _log.info('Building the model') model = Sequential() _mult_conv_max(model, nb_conv=2, nb_filter=64) _mult_conv_max(model, nb_conv=2, nb_filter=128) _mult_conv_max(model, nb_conv=3, nb_filter=256) _mult_conv_max(model, nb_conv...
c4f9374d10cfa8ed25a1dbbc0428a65d2ec4cadd
45,140
def grayscale(im, amount=1): """Converts image to grayscale. A grayscale operation is equivalent to the following matrix operation: | R' | |0.2126+0.7874g 0.7152-0.7152g 0.0722-0.0722g 0 0 | | R | | G' | |0.2126-0.2126g 0.7152+0.2848g 0.0722-0.0722g 0 0 | | G | | B' | = |0.2126...
1a84c62d535739e8f5a4a0f679a9c12575cc8094
45,141
def bar_chart(**kwargs): """ An example of a bar chart Args **kwargs lets you pass arguments into this function """ years = [str(year) for year in range(2010, 2021)] visitors = [1241, 50927, 162242, 222093, 665004, 2071987, 2460407, 3799215, 5399000,...
b251669ae32e08b0bdf083d1360e29eb1593e598
45,142
def splitname(name, strict_mode=True): """ Break a name into its constituent parts: First, von, Last, and Jr. :param string name: a string containing a single name :param Boolean strict_mode: whether to use strict mode :returns: dictionary of constituent parts :raises `customization.InvalidName...
29a24a26e7b644548f33de79f0e1dc07c4d4fc7c
45,143
def _gen_image(num_per_item, _list, is_covers=True, _min=None, images_list=None): """ Generate n image for each item in _list or random between _min and num_per_item, because url images are unique, it accepts list of image object (return from SQLAlchemy query) to avoid duplicate with existed images ...
5ba68dcf5471cf10460e56f0cc2c31c29709c17f
45,144
import re import sys def parse_line(line, create_organizations=False, broker=None, using='default'): """ Parse an (organization, account, amount) triplet. """ unit = None amount = 0 look = re.match(r'\s+(?P<tags>\w(\w|:)+)(\s+(?P<amount>.+))?', line) if look: organization_slug = br...
de11a8ab16199e026b094dca53840d95e2f2399f
45,145
def arikan_gen(n): """ The n-th kronecker product of [[1, 1], [0, 1]], commonly referred to as Arikan's kernel. Parameters ---------- n: int log2(N), where N is the block length Returns ---------- ndarray<int> polar code generator matrix """ F = np.array([[1, ...
f1f78d84b08da81bef942178fd37df9636fc595c
45,146
import math def check_user_answer(user_answer, calculated_answer): """ This method checks the user's answer with the calculated answer. Args: user_answer (Union[str, int, float, List[Union[int, float]]]): The user's answer. calculated_answer (Union[str, int, float, List[Union[in...
42d9c7b8ea5f5ce6cfc2bf67edb548ad809d44e9
45,147
import os import shutil def remove_dir(dir_path): """remove dir""" if os.path.exists(dir_path) and os.path.isdir(dir_path): # 如果文件夹存在 shutil.rmtree(dir_path) logger.info("delete file {}".format(dir_path)) return True else: return False
b8894e81d97f176cb50c09003ba0084b403c03c9
45,148
def segment_sentence(bestprecodetree,roottree,bestsuffcodetree,bestpostcodetree,bestendcodetree,bestvocab, sentence,marker1,marker2,mode=0,generateroots=False,optmode=1,extramode=0,nentnums=[],nentsegs=[],verbose=False): """ Segment line of words (whitespace-tokenized string) with PRP encoding ...
9e9ccb76292dd79b41cf2813bcddadb92e8fbc87
45,149
def feat_upsampling_nearest_neighbor(input_feat, up_shape, name='feat_upsampling'): """ nearest neighborhood upsampling Args: up_shape (list of length 2): upsampled shape """ with tf.name_scope(name): up_feat = tf.image.resize_nearest_neighbor( input_feat, (up_shape...
57ec83970382e47b4ef5cb895e387930c0721233
45,150
from io import StringIO def open_url(url: str) -> StringIO: """Fetches a given URL synchronously. The download of binary files is not supported. To download binary files use :func:`pyodide.http.pyfetch` which is asynchronous. Parameters ---------- url : str URL to fetch Returns ...
03babf9a465ae3c29de0352aae328953837107e6
45,151
import logging def snapshot(topmost_frame, stack_method="direct"): """ Snapshots the frame stack starting from the frame provided. Parameters ---------- topmost_frame : FrameObject Topmost frame. stack_method : {None, "direct", "predict"} Method to use for the stack: ...
0825488d8efba7c5395668ca14dd29a73a94e939
45,152
def get_replaced_all_jokers_hands(hand): """ Заменяем обоих джокеров и возвращаем общий список замен :param hand: исходная рука :return: """ replaced_joker_hands = [] replaced_black_joker_hands = get_replaced_joker_hands( hand, LIST_BLACK_CARD, '?B' ) for replaced_black_joke...
31911c6accc1ab16009eb699f490946cd053e546
45,153
def step(t, n, initial, after, seed=1, dt=0.05): """Simulates for n generators for t ms. Step at t/2.""" nest.ResetKernel() nest.SetStatus([0], [{"resolution": dt}]) nest.SetStatus([0], [{"grng_seed": 256 * seed + 1}]) nest.SetStatus([0], [{"rng_seeds": [256 * seed + 2]}]) g = nest.Create('sin...
5ab1084f4d07e457f9b69d8a9b232d0fce6dc7e2
45,154
def harmonic_epmi_score(pdict, wlist1, wlist2): """ Calculate harmonic mean of exponentiated PMI over all word pairs in two word lists, given pre-computed PMI dictionary - If harmonic ePMI is undefined, return -inf """ total_recip_epmi = None # Number of pairs for which PMI exists N...
5aec36df72e22fecbb1dfdcbc6ec840944a40d8d
45,155
def datafiles(request, tmpdir): """ pytest fixture to define a 'tmpdir' containing files or directories specified with a 'datafiles' mark. """ entry_list = [] options = { 'keep_top_dir': False, 'on_duplicate': 'exception', # ignore, overwrite } for mark in request.no...
456f13fde72609f7f65e5b50be38166ba16267e9
45,156
def get_paramvals_percentile(mcmc_table, pctl, chi2, randints_df=None): """ Isolates 68th percentile lowest chi^2 values and takes random 100 sample Parameters ---------- mcmc_table: pandas.DataFrame Mcmc chain dataframe pctl: int Percentile to use chi2: array Arra...
f29a00a68208987edefa62623e4b39ac6dcf6e88
45,157
def parse_origin(url): """ Return the origin of a URL or None if empty or invalid. Per https://tools.ietf.org/html/rfc6454#section-7 : Return ``<scheme> + '://' + <host> + <port>`` for a URL. :param url: URL string :rtype: str or None """ if url is None: return None pa...
c0efb2cc1c3910f56f634ad87a83a8fe1bab8a3f
45,158
def optional_apply(f, value): """ If `value` is not None, return `f(value)`, otherwise return None. >>> optional_apply(int, None) is None True >>> optional_apply(int, '123') 123 Args: f: The function to apply on `value`. value: The value, maybe None. """ if value is...
dfa5b6793d7226370a27d6a638c0a5bc975f78d4
45,159
from .plot_methods import multi_scatter_plot from .bokeh_plots import bokeh_multi_scatter def scatter(xdata, ydata, backend=None, data=None, **kwargs): """ Plot the provided data as a scatter plot. Varying size and color are possible. Multiple data sets are possible :param xdata: data for the x-axis ...
6f3bfca1e11b2b07e3bac361b27209fb3d08bd65
45,160
def repl_func(m): """process regular expression match groups for word upper-casing problem""" return m.group(1) + m.group(2).upper()
72ae8d2cdcec98ce4ae661dbe020dc244d47c8af
45,161
import json def build(data): """Build a binary tree using the leetcode data format. TODO Add description for leetcode data format. :param str|list data: :return: root node of the binary tree. """ values = json.loads(data) if isinstance(data, str) else data if not values: return N...
8da0c47b195c155954ad53c47937d8177efd29ab
45,162
def make_email(to, cc=None, bcc=None, subject=None, body=None): """\ Encodes either a simple e-mail address or a complete message with (blind) carbon copies and a subject and a body. :param to: The email address (recipient). Multiple values are allowed. :type to: str or iterable of strings :par...
9387bdba6968eb1cc3b948ba260a918af8554124
45,163
def invoke_gate(a, b): """Function modelling one input (a) invoking a second input (b). If the invoking is at either -1,0,1 the output is also at that value. The second input can only modify the output between those values. Args: a (float): invoking input b (float): second input ...
82be9c62cd6bc0897641ff25fb30a7e0fa8e8d7b
45,164
def cosine_similarity( X, Y=None, dense_output=True, use_float=False, approx_size=1.0, compression_rate=1.0, blas="default", ): """Compute cosine similarity between samples in X and Y. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of X...
1b8d8e780aa59bbf36c156ca0fb1cb88f5dba511
45,165
def cdlhikkakemod(opn, high, low, close): """Modified Hikkake Pattern: The modified hikkake pattern is a less frequent variant of the basic hikkake pattern and is viewed as a reversal pattern. The concept of the modified version is similar to the basic version, except that a "context bar" is used prior...
fda33ad68affabb8d18481c8c4658eb2200ca998
45,166
import os def create_c2pc_data(fovs, pixel_consensus_path, cell_table_path, pixel_cluster_col='pixel_meta_cluster_rename'): """Create a matrix with each fov-cell label pair and their SOM pixel/meta cluster counts Args: fovs (list): The list of fovs to subset on ...
2a5fab53a6e40a8dd03a7854f51d8d73f10fdebb
45,167
def coffee(): """About page.""" return render_template('public/coffee.html')
03ce072cfc917f9a16894fd6da2015fc5a44e278
45,168
def after_request(response): """log details on the request and its served response""" __log__.info('%s - "%s %s %s" %s -', request.remote_addr, request.method, request.full_path, request.environ.get('SERVER_PROTOCOL'), response.status_code) return response
d26e3b6a9606da9f1684e320447c9bfb75683002
45,169
def average_infid_set(U_dict: dict, index, dims, eval, proj=True): """ Mean average fidelity over all gates in U_dict. Parameters ---------- U_dict : dict Contains unitary representations of the gates, identified by a key. index : int Index of the qubit(s) in the Hilbert space t...
9cc07fcdd0989f1d7f3edf35043720d227c041af
45,170
async def read(id: int, auth_data: dict = Depends(get_auth_data)): """ 读取组织数据详情 :param id: 组织id :return: 组织详情结构 """ resp = OrgRespDetailSchema() resp.detail = OrgService(auth_data).read(id) return resp
84bf2d3306548e09207d9bfa1318fc4ce8f5c33f
45,171
def RAND(*args) -> Function: """ Returns a random number between 0 inclusive and 1 exclusive. Learn more: https//support.google.com/docs/answer/3093438 """ return Function("RAND", args)
3759d35ef8233a18223d3f9d65d32c65fd694142
45,172
import json def get_channel_status_bulk(request): """ Create the channel node """ data = json.loads(request.body) try: statuses = {cid: get_status(cid) for cid in data['channel_ids']} return HttpResponse(json.dumps({ "success": True, 'statuses': statuses, }...
6082cac06b4ef8d96da12c8c8ed1b226b44705fb
45,173
def GetChainAloneResidueTypesStatus(FileIndex, ChainID): """Get status of residue types for chain alone object.""" Status = OptionsInfo["InfilesInfo"]["SpecifiedChainsAndLigandsInfo"][FileIndex]["ResidueTypesChain"][ChainID] return Status
4e26ef6556fc0fcd8466c0c8ab53095ea83578ef
45,174
def run_3gpp_tests( setup, key_filename=DEFAULT_KEY_FILENAME, test_files=NG40_TEST_FILES ): """ Run teravm s6a and gxgy test cases. Usage: 'fab run_3gpp_tests:' for default key filename and default test files. key_filename: path to where the private key is for authorized-key based ssh. The ...
aab8faf5dd4701f2c294c4da59a03f969dba05d2
45,175
def gameOver(currentBoard,typeCurrentPlayer): """ Function that checks if the game is over in the current board Parameters : -currentBoard : the current board -typeCurrentPlayer : type of the current player Returns : - [True, game over message] if the game is over - [Fals...
a7b27235d31c348d260873cd7b57e16db02828b7
45,176
def task_table(request): """ ProductionTask table :return: table page or data for it """ last_task_submit_time = ProductionTask.objects.order_by('-submit_time')[0].submit_time return TemplateResponse(request, 'prodtask/_task_table.html', { 'title': 'Production Tasks Table', ...
1388c14763e553aec77caa070dde0c26e04c28c3
45,177
import requests import json def user_files(): """ This route renders a file-upload page for users. Not logged-in users (anonymous): > request that they login logged-in users (anonymous): > list files they own > show file-upload box The file-up...
c78b5891b1776feeb3c39678051efa9f45ac8ddc
45,178
def update_meta_sheet_feeders(self, puzzle_id) -> None: """ Updates the input meta puzzle's spreadsheet with the latest feeder puzzle info """ meta_puzzle = Puzzle.objects.get(pk=puzzle_id) if not meta_puzzle.is_meta or not meta_puzzle.sheet: return logger.info( "Starting up...
3b174c8c3662020a52b3d31651b7ffd3435472f5
45,179
def prod(F, E): """Check that the factorization of P-1 is correct. F is the list of factors of P-1, E lists the number of occurrences of each factor.""" x = 1 for y, z in zip(F, E): x *= y**z return x
401a5596b42b1299a07b3f621c996226474735f5
45,180
def _parse_common(raw_object: RawObject) -> TiledObject: """Create an Object containing all the attributes common to all types of objects. Args: raw_object: Raw object to get common attributes from Returns: Object: The attributes in common of all types of objects """ common = Tile...
7795a5bf462d03e46bf270276bcb8dd3cdaf6c5c
45,181
def load_file(fname, force_reload=False, **kwargs): """Load a file Parameters: fnames (list): single file name, or list of files that are part of the same time series. Glob patterns and slices are accepted, see :doc:`/tips_and_tricks` for more info. fname (str): a file n...
d274c0b4406f0c41f8fb239c3086ab64414a6170
45,182
def sort_data(data, cols): """Sort `data` rows and order columns""" return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)
33acbfd9be36d187120564f1792147b644b6c394
45,183
def calc_2d_ellipse_properties(cov,nstd=2): """Calculate the properties for 2d ellipse given the covariance matrix.""" def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1] return vals[order], vecs[:,order] vals, vecs = eigsorted(cov) width, height = ...
6875e7f92287fe9a5c1ff772988e3be09a57388b
45,184
from typing import Dict from typing import Callable from typing import Tuple def _augment_grid( policy: np.ndarray, value: np.ndarray, expected_value: np.ndarray, min_wealth_grid: float, params: pd.DataFrame, options: Dict[str, int], compute_utility: Callable, ) -> Tuple[np.ndarray, np.nda...
5d1fe3bb18c841952546735bd32c825530c74258
45,185
import argparse import os def parse_args(): """ Parse optional benchmarking arguments. """ parser = argparse.ArgumentParser(description='Inscriptis benchmarking ' 'suite') parser.add_argument('converter', type=str, nargs='*', help='The l...
ad203cc549575808b89948ffd98827ea55da7427
45,186
import torch def argval_subsample_idx(values, n, polarity="MAX"): """values is a list, n an int, polarity is MAX or MIN""" assert n > 0 descending = {"MAX": True, "MIN": False}[polarity] _, idxs = torch.sort(torch.Tensor(values), descending=descending) return idxs.tolist()[:n]
dbf15c72554be1bc750b12ca47c98b0e654a3c2e
45,187
def shortest_path_matrix(G): """ Return a matrix of pairwise shortest path lengths between nodes. Parameters ---------- G (nx.Graph): the graph in question Returns ------- pmat (np.ndarray): a matrix of shortest paths between nodes in G """ N = G.number_of_nodes() pmat = ...
32c478efd2123041feff6d62a798dcc861dfecfc
45,188
from typing import Any def build_put201_creating_failed200_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: """Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the la...
fec506a6704aeb55a2e71d2375351520f31fe099
45,189
def safe_convert_list_to_sql_tuple(filter_list): """ Safe version of convert_list_to_sql_tuple(), by first flattening the input list and then casting all its elements to strings, before proceeding with the conversion. """ return convert_list_to_sql_tuple(cast_elements_to_string(flatten_list(filter_lis...
39559b581752a1699c54935ba7adff6e09241cfc
45,190
def depthAvgFlow(U, V, dz, depthRange=500): """ Depth averaged flow for flow from bottom up to depthrange. """ steps = int(np.ceil(depthRange/dz)) Umeans = np.empty(0) Vmeans = np.empty(0) for Ui, Vi in zip(U.T, V.T): mask = np.where(np.isfinite(Ui))[0] mask = mask[-1:np.max...
e69622eba490903937c9a5ab6936e8b89f0eaba7
45,191
import numpy def get_array4d(json_data, microplate_names): """Return well values as numpy' 4d array. (iteration x spreadsheet x microplate x well) """ if len(json_data[u'iterations']) > 0: pad_missing_spreadsheets(json_data) iterations = [] for iteration in json_data[u'i...
93db6d54fcf8c40ed9348ee1385cac3629b87c0d
45,192
import logging def sanitise_graphite_url(current_skyline_app, graphite_url): """ Transform any targets in the URL that need modifications like double encoded forward slash and return whether the URL was sanitised and the url. :param current_skyline_app: the Skyline app calling the function :param...
8151a83861a3ff275694946f623f6beb42fc6bbd
45,193
def convention(predictions, length): """ Function for implementimg the convention of Indian plates """ cls = np.argmax(predictions, axis = 1) for i in [0,1]: # first 2 district code must represent letters if cls[i]==0: cls[i]= 24 # else: # print(np.argmax(pred...
ba08164b998554e740ec47e2f4d5ca7df708396d
45,194
def is_connected_dominating_set(G, nodes): """Return whether or not *nodes* is a connected dominating set of *G*. A set *D* is a *connected dominating set* of *G* is *D* is a dominating set in *G* and the subgraph of *G* induced by *D* is a connected graph. Parameters ---------- G : Networ...
20081f33de032c515bc78dbd0b2ecab212278df6
45,195
import os def aws_resource_names(): """ Get names for various aws resources the manager relies on. For example: vpcname, securitygroupname, keyname, etc. Regular users are instructed to hardcode many of these to firesim. Other users may have special settings pre-determined for them (e.g. tutoria...
c30ec1ce1a0041a75bf387607060022f52234753
45,196
import functools import time def _retry_on_deadlock(f): """Decorator to retry a DB API call if Deadlock was received.""" @functools.wraps(f) def wrapped(*args, **kwargs): while True: try: return f(*args, **kwargs) except db_exc.DBDeadlock: LO...
edc7e15826ad1d32569a1d9c8a514aa5020430a8
45,197
def command(server, cmd): """ Simple ssh remote command. Args: server (collection): Collection with server data cmd (string): Command to run on remote server Returns: string: STDOUT for the remote command """ with setup_server_connection(server) as connection: result = connection.run(cmd, ...
b73d17a68c1e4c37de315aea2aa72e7fe30a375b
45,198
def _union_all(iterables): """Return a set representing the union of all the contents of an iterable of iterables. """ out = set() for iterable in iterables: out.update(iterable) return out
673bc7493007c6cf781d84490023cea7139f1e93
45,199