content
stringlengths
22
815k
id
int64
0
4.91M
def normalize_volume_and_number(volume, number): """ Padroniza os valores de `volume` e `number` Args: volume (None or str): volume se aplicável number (None or str): número se aplicável Notas: - se `number` é igual a `ahead`, equivale a `None` - se `00`, equivale a ...
5,305,100
def create_intersection_jo_losses(pos_3d, obj_2d_polys, joints_active, pos_3d_transform_indices, obj_2d_poly_transform_indices, independent, um, d_padding, ...
5,305,101
def multi_scale_like_flow(image, flow_ms): """ :param image: [batch, height, width, 3] :param flow_ms: list of [batch, numsrc, height/scale, width/scale, 1] :return: image_ms: list of [batch, height/scale, width/scale, 3] """ image_ms = [] for i, flow in enumerate(flow_ms): batch, nu...
5,305,102
def example1(): """Check the path name of the signal in the VCD file.""" extractor = WaveExtractor('timer.vcd', '', []) extractor.print_props()
5,305,103
def test_multiple_restrictions(): """Checks the limit allocation restriction""" df = simulated_correlated_equities_4_years_gen() calculated_allocations = restricted_fifty_fifty( df, allocation_lower_limit=0.0, allocation_upper_limit=0.25, loss_limit=0.001 ) prev_alloc = 0 prev_price =...
5,305,104
def pd_xlabels(): """Create a DataFrame which uses the column labels as x-data.""" df = pd.DataFrame({"B": np.random.randint(0, 100, size=100)}) return df
5,305,105
def rotate(X,a=0): """Rotate around the origin a 2d matrix X by angle a in degrees""" a = np.deg2rad(a) # Convert degrees to radians return np.dot(X, [[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]])
5,305,106
def __prepare_postcoder(directory: PathLike): """ Create an instance of PostCoder Parameters ---------- directory: PathLike The postalcode file directory. If the file (ken_all.zip) doesn't exist, download it. """ postcoder = PostCoder.get_instance(directory) return postc...
5,305,107
def CalculateTransitionSolventAccessibility(ProteinSequence): """ ############################################################################################### A method used for calculating Transition descriptors based on SolventAccessibility of AADs. Usage: result=CalculateTransitionSolve...
5,305,108
def sSEZtoECEF(station_ecef:AbstractArray, sez:AbstractArray, conversion:str="geodetic") -> np.ndarray: """Compute the coordinates of an object in the topocentric frame of an Earth-fixed frame Args: station_ecef (np.ndarray): Earth-fixed Cartesian station coordinates sez (np.ndarray): SEZ c...
5,305,109
def convert_max(node, **kwargs): """Map MXNet's max operator attributes to onnx's ReduceMax operator and return the created node. """ from onnx.helper import make_node name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = str(attrs.get("axis", 'None')) axes = convert_string_to_list(...
5,305,110
def pairwise_cluster_raw(mat1=([0]), mat2=([0]), mat1T=([0]), mat2T=([0]), gpu=False): # the matrices (mat1 and mat2) are used to calculate the clusters and the lsts will be used to store the members of clusters """ Takes a pair of matrices mat1 and mat2 as arguments. Both of the matrices should have the ...
5,305,111
def cache_url(url): """Load a url to a local file, or return the file path if it already exists This function will download the given URL to the current directory, with a file name of the last path element in the URL. """ import os import urlparse from IPython.display import disp...
5,305,112
def tanimoto_sml(queryism, targetism): """ Returns the Tanimoto similarity between the two molecules in SMILES format. """ # no Unicode here querymol = MolFromSmiles(str(queryism)) targetmol = MolFromSmiles(str(targetism)) if querymol and targetmol: queryfp = RDKFingerprint...
5,305,113
def style_close(style: List[Tuple[str, str]]) -> str: """ HTML tags to close a style. >>> style = [ ... ("font", 'color="red" size="32"'), ... ("b", ""), ... ("i", ""), ... ("u", ""), ... ] >>> style_close(style) '</u></i></b></font>' Tags will always be in ...
5,305,114
def testrun(args): """testrun subcommand. Runs the command with the tracer using a temporary sqlite3 database, then reads it and dumps it out. Not really useful, except for debugging. """ fd, database = Path.tempfile(prefix='reprozip_', suffix='.sqlite3') os.close(fd) try: if a...
5,305,115
def apply_fd_mapping(fd_mapping): """ Takes dict target fd -> present fd. Moves fds to match the mapping. """ def _dup_mapping(fd, new_fd): logger.debug("fd {} duped to {}".format(fd, new_fd)) for target_fd in fd_mapping.keys(): if fd_mapping[target_fd] == fd: fd_map...
5,305,116
def test_perm_contrasts(): """ Testing the perm_contrasts function """ np.random.seed(10) for I in np.arange(2): if I == 1: # 1D example dim = 5 else: # 2D example dim = (10,10) nsubj = 30 categ = np.random.multinomial(2, [...
5,305,117
def get_theta_hat_bw_imd_cm1(theta_star_bw_std): """制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(℃)(27b-1) Args: theta_star_bw_std(float): 標準条件の沸き上げ温度( Returns: float: 制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度( """ # 制御モードがファーストモードの場合 return theta_star_bw_std
5,305,118
def cli(): """Method that can be called my other modules to use the commands on this file""" pass
5,305,119
def tar_directory(root, prefix, strip_times=False, tmpfile=None): """ Walk the directory specified by root, and tar files with new path prefix """ root = os.path.abspath(root) tmpfile = tmpfile or utils.get_tmpfile() tar = tarfile.open(dest, "w:gz") for filename in utils.recursive_find(root)...
5,305,120
def crossGeneAvg(genea, geneb): """ A crossover startegy where the two genes are averaged, with no cut point 12347 => 33334 54321 33334 Parameters ---------- genea : 1D numpy array An 1D numpy array of genes. geneb : 1D numpy array An 1D numpy...
5,305,121
def _oauth_url(): """Creates the URL handling OAuth redirects.""" return url_for('oauth', _external=True)
5,305,122
def test_packaged_data_files(): """Test if all required data files are packaged(positive control for the data files path)""" data_path = pkg_resources.resource_filename("transposonmapper", "data_files/") try: verify_data_files(path=data_path) except AssertionError as err: assert False, f...
5,305,123
def join_as_guest(): """ Generates Valid Token for Guest Users """ _uuid = security.create_guest_uuid() access_token, expires = security.create_access_token( subject=_uuid, is_guest_user=True, expires_delta=timedelta(hours=settings.ACCESS_GUEST_TOKEN_EXPIRE_HOURS) ) r...
5,305,124
def test_minimax_def_col(): """ x o x | o x o | o o x x x o | x x o | x o x o | x | x Test if COMPUTER can defend with a lose case on a column of the board. """ game_board = [[PLAYERX, PLAYERO, PLAYERX], [PLAYERX, PLAYERX, PLAYERO], [EMPTY, EMPTY, PLAYERO]] b...
5,305,125
def run_experiment(param_grid, n_processes=-1): """Method for running experiments This method is used for making it easy to run experiments in parallel and use different combinations of parameters. The param_grid dictionary describes what task or tasks must be executed and what parameters and/or pa...
5,305,126
def main(): """Called when invoking the command line script.""" add_parser_arguments() parser.description('RabbitMQ consumer framework') helper.start(Controller)
5,305,127
def InitializeDatabase(dbhost, dbport, dbname): """ """ rconn = rethinkdb.connect(dbhost, dbport) rconn.repl() if dbname not in rethinkdb.db_list().run(): logger.info('create the sync database %s', dbname) rethinkdb.db_create(dbname).run() rconn.use(dbname) tables = rethi...
5,305,128
def test_RunAssembly_filtered(util, short_read_mngs_bench3_viral_outputs): """ Re-run the assembly task with a higher min_contig_length and observe that contigs are removed. """ # load the task's inputs from the end-to-end workflow test task_name = "RunAssembly" inputs, _ = util.miniwdl_inputs_o...
5,305,129
def run_etl( cls, dry_run=False, no_validate=False, extract_only=False, fiscal_year=None, quarter=None, year=None, month=None, **kwargs, ): """Internal function to run ETL on fiscal year data.""" # Loop over the PDF files finished_params = [] for f in cls.get_pdf_fil...
5,305,130
def getServosFromURDF(): """ Get servo parameters from URDF. """ try: description = rospy.get_param("robot_description") robot = xml.dom.minidom.parseString(description).getElementsByTagName('robot')[0] joints = {} # Find all non-fixed joints for child in robot.childNodes...
5,305,131
def test_invalid_days(test_input, expected): """ Tests of get_ephemerides_on_day""" # 1. We have to use pytest.approx since there is a difference on the rounding of the # very last decimal in reading in the .csv between Python and Mathematica. # 2. We have to iterate over the input/output with ...
5,305,132
def test_check_logs(monkeypatch): """ . """ log1 = Log( revision1="abc123", message="foo", status="log", utc_unix_timestamp=1611608732 ) log2 = Log( revision1="abc123", message="bar", status="success", utc_unix_timestamp=1611608732, ) db_file = ge...
5,305,133
def exit_with_mapped_status(http_status): """ Given an HTTP Status, exit with either an error status of 1 or the status mapped by what we were given. """ # get the mapping by looking up the state and getting the mapping attr mapping = click.get_current_context().ensure_object(CommandState).http_...
5,305,134
def convert_checkpoint(checkpoint_file, output_dir): """Converts a given checkpoint into a new one. The function does the following steps: 1. loads an existing checkpoint. 2. computes the new variable values from the variables in the checkpoint. 3. saves the new checkpoint in output_dir. Args: checkpo...
5,305,135
def open_query(): """Opens the Query TopLevel window""" query_window = Toplevel(root) query_window.title("Query") global entity entity = Listbox(query_window, selectmode="single", width=70) entity.grid(row=0, column=1) options = sf.query_all( ("SELECT ID, QualifiedAPIName from Entity...
5,305,136
def spacegroup_sunburst( spacegroups: Sequence[int] | pd.DataFrame, sgp_col: str = None, show_values: Literal["value", "percent", False] = False, **kwargs: Any, ) -> Figure: """Generate a sunburst plot with crystal systems as the inner ring for a list of international space group numbers. A...
5,305,137
def how_many_arrows(tcol): """Determines the number of colors that have arrows on them. Args: tcol (list): A 2D array of the labeling that contains the colors and arrows for each site. Returns: arrows (int): The number of arrows in the system. n_species (int): The number ...
5,305,138
def write_bq_schema(data, inputname, filepath=''): """ write BigQuery schema as json file """ filename = generate_output_name(inputname, filepath) with open(filename, 'w') as jsonfile: json.dump(data, jsonfile, sort_keys=True, indent=4)
5,305,139
def CreateKwargHandler(endpoints, f): """ Create methods which contains kwargs and return the remaining endpoints to handle """ index = 0 # endpoints = ["/v2/users", "/v2/users/:id"] remainEndpoints = [] while index < len(endpoints) - 1: firstMatches = re.findall("(\/v2...
5,305,140
def get_grid_cells_position(shapes, aspect_ratio=16/9., dim=None): """ Constructs a XY-grid based on the cells content shape. This function generates the coordinates of every grid cell. The width and height of every cell correspond to the largest width and the largest height respectively. The grid dime...
5,305,141
def load_ignore_lists(): """ Load the to-be-ignored commits from the files in ignore/ """ onlyfiles = [f for f in listdir("ignore/") if isfile(join("ignore/", f))] for file in onlyfiles: if "#" in file or "~" in file: continue print("load ignorelist %s" % file) with open(...
5,305,142
def sandbox_child_from_pyspawner(child_pid: int, config: SandboxConfig) -> None: """ Sandbox the child process from the pyspawner side of things. The child must wait for this to complete before it embarks upon its own sandboxing adventure. """ _write_namespace_uidgid(child_pid) if config.ne...
5,305,143
def remove_config_file(conf_file: str): """ Clean up configuration file :param conf_file: location of configuration file """ if os.path.isfile(conf_file): os.remove(conf_file)
5,305,144
def fdier(in_stream, target_regex, start_regex = None, stop_regex = None): """ ------------------------------------------------------------------------- Parameters ------------------------------------------------------------------------- in_stream : A file object In...
5,305,145
def test_serializer_nonsense(): """ test whether errors are thrown for wrong input """ with pytest.raises(ValueError): cache.make_serializer('non-sense') with pytest.raises(ValueError): cache.make_unserializer('non-sense')
5,305,146
def _detect_start_end(true_values): """From ndarray of bool values, return intervals of True values. Parameters ---------- true_values : ndarray (dtype='bool') array with bool values Returns ------- ndarray (dtype='int') N x 2 matrix with starting and ending times. """ ...
5,305,147
def parse_debug(response): """ Parse the result of Redis's DEBUG command into a Python dict :param bytearray response: :return disc: """ info = {} response = response.decode('utf8') for line in response.split(','): if line.find(':') != -1: key, value = line.split(':'...
5,305,148
def load_builtin_module(): """ load built_in module """ built_in_module = load_python_module(built_in) project_mapping["debugtalk"] = built_in_module
5,305,149
def pow_many(power, *args): """ Функция складывает любое количество цифр и возводит результат в степень power (примеры использования ниже) :param power: степень :param args: любое количество цифр :return: результат вычисления # True -> (1 + 2)**1 """ rs = 0 for v in args: rs +=...
5,305,150
def create_playlist(title: str, contributor: str, creator: str, ordered: bool, source: str, format_: str, description: str, recordings_ids: list = None, name: str = None, language: str = None, num_tracks: int = None): """ """ listitems = [] ids_mode = True if ...
5,305,151
def register(request): """Summit registration form view """ class SummitForm(ModelForm): class Meta: model = SummitRegistration SummitForm.base_fields['email'].label = 'Email address' SummitForm.base_fields['phone'].label = 'Phone number' SummitForm.base_fields['address'].l...
5,305,152
def uncordon(kube, node): """uncordon a kubernetes node""" kube.patch_node( node, { "spec": { "unschedulable": False, }, }, )
5,305,153
def _d_serialize_delper_switch_field(context, self, field, d_switch_variable, prefix): """ handle switch by calling _serialize() or _unpack(), depending on context """ # switch is handled by this function as a special case param_fields, wire_fields, params = get_serialize_params(context, self) f...
5,305,154
def generate_empty_conf_dict(): """Generates an empty dictionary according to the conference template.""" with open(str(current_path) + "/confcrawler/ressources/conference_template.json", "r") as template: return json.load(template)
5,305,155
def lighr_head_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator.""" num_anchors_list = labels['num_anchors_list'] num_feature_layers = len(num_anchors_list) shape = labels['targets'][-1] if mode != tf.estimator.ModeKeys.TRAIN: org_image = la...
5,305,156
def gaussianMI(x, y, constellation, M, dtype=tf.float64): """ Computes mutual information with Gaussian auxiliary channel assumption and constellation with uniform porbability distribution x: (1, N), N normalized complex samples at the transmitter, where N is the batchSize/sampleSize y: (1,...
5,305,157
def efun_get_jwt(mud: str, file: str) -> str: """ SYNOPSIS string get_jwt(string mudname, string filename) DESCRIPTION Returns a JSON Web Token for accessing mudlib files from the web. This efun is only allowed to be called from a player object. ...
5,305,158
def init_app(app, **kwargs): # pylint: disable=unused-argument,unused-variable """ Init teams module. """ api_v1.add_oauth_scope('teams:read', "Provide access to team details") api_v1.add_oauth_scope('teams:write', "Provide write access to team details") # Touch underlying modules from ...
5,305,159
def get_book_list(): """Store information about the books in a list""" wishlist = send_wishlist_request(f"https://www.bookdepository.com/wishlists/{WISH_LIST_CODE}") if wishlist: soup = BeautifulSoup(wishlist.content, "html.parser") if not verify_homepage(soup): raise Exception(...
5,305,160
def gunzip_merge(outfile, list_files): """ Merge gunzip files into final file :param outfile: String for output file :param list_files: List of files to merge :type outfile: string :type list_files: list """ list_files = list(list_files) list_files.sort() print ("\tMerging files into: ", outfile) #pri...
5,305,161
def parse_id(method): """ Ensures the input experiment identifier is an experiment UUID string Parameters ---------- method : function An ONE method whose second arg is an experiment ID Returns ------- function A wrapper function that parses the ID to the expected strin...
5,305,162
def shuffel_data(x, y, seed=None): """Random shuffle of the data""" if seed: np.random.seed(seed) index = np.arange(x.shape[0]) np.random.shuffle(index) return x[index], y[index]
5,305,163
def font_face(psname): """Return a Face tuple given a psname""" fam = LIBRARY.parent_fam(psname) for face in LIBRARY.list_fam(fam): if face.psname == psname: return face notfound = 'Font: no matches for Postscript name "%s"'%basis raise DeviceError(notfound)
5,305,164
def _doSysExec(command: str, errorAsOut: bool = True) -> tuple[int, str]: """Execute a command and check for errors. Args: command (str): commands as a string errorAsOut (bool, optional): redirect errors to stdout Raises: RuntimeWarning: throw a warning should there be a non exit code Returns: tuple[int,...
5,305,165
def modularity_density( graph: nx.Graph, communities: object, lmbd: float = 0.5, **kwargs: dict ) -> object: """The modularity density is one of several propositions that envisioned to palliate the resolution limit issue of modularity based measures. The idea of this metric is to include the information abo...
5,305,166
def get_media_pool_clip_list_and_clip_name_list(project): """ Parametes --------- project : Project a Project instance Returns ------- clip_return_list : list clip list clip_name_list : list clip name list Examples -------- >>> resolve, project_manag...
5,305,167
def get_instances(): """returns array of instance names, array of corresponding n""" data = np.genfromtxt('m2s_nqubits.csv', delimiter=',', skip_header=1, dtype=str) return data[:, 0], data[:, 1].astype(int)
5,305,168
def data_inference(tensor_data, frozen_graph_path, show=False, out_folder=None, threshold=.5): """ Returns results """ # NOTE Single datapoint inference at a time. Really not optimized. At all. if out_folder: os.makedirs(out_folder, exist_ok=True) outputs = [] graph = model_freezer.load_grap...
5,305,169
def stac_catalogs_item(catalogs, item_id): """Fetch catalog's single features --- tags: - Data description: |- Fetch the feature with id `featureId` in the given catalog provided. with `catalogs`. parameters: - name: catalogs in: path required: true ...
5,305,170
def get_version(): """Returns the version of Bladerunner and the python it's running on.""" return "Bladerunner {ver} on Python {pyv}. Released: {date}".format( ver=__version__, pyv="{0}.{1}.{2}".format(*sys.version_info[:3]), date=__release_date__, )
5,305,171
def _generate_zip_package(target, sources, sources_dir): """Generate a zip archive containing all of the source files. """ zip = zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) manifest = _archive_package_sources(zip.write, sources, sources_dir) zip.writestr(_PACKAGE_MANIFEST, '\n'.join(manifest) + '...
5,305,172
def match_phrases(phrases: List[str]): """ Compiles multiple phrases into a single predicate function that returns True if the input contain any of the phrases surrounded by word boundaries. """ # escape regex metacharacters and ignore repeated whitespace in multi-word phrases phrases = [re.esca...
5,305,173
def get_payment_request_with_payment_method(business_identifier: str = 'CP0001234', payment_method: str = 'CC'): """Return a payment request object.""" return { 'paymentInfo': { 'methodOfPayment': payment_method }, 'businessInfo': { 'businessIdentifier': business_...
5,305,174
def test_valid_snils(snils): """No exception raise""" assert validate_snils(snils) is None snils_model = SnilsModel(snils=snils) assert snils_model.snils == snils
5,305,175
def empty_framework_version_warning(default_version, latest_version): """ Args: default_version: latest_version: """ msgs = [EMPTY_FRAMEWORK_VERSION_WARNING.format(default_version)] if default_version != latest_version: msgs.append(LATER_FRAMEWORK_VERSION_WARNING.format(lates...
5,305,176
def AddIamPolicyBinding(content_ref, member, role): """Adds iam policy binding request.""" policy = GetIamPolicy(content_ref) iam_util.AddBindingToIamPolicy( dataplex_api.GetMessageModule().GoogleIamV1Binding, policy, member, role) return SetIamPolicy(content_ref, policy)
5,305,177
def getLevelName(lvl): """ Return the textual representation of printing level 'lvl'. If the level is one of the predefined levels (JOB, IMPORTANT, TERSE, NORMAL, VERBOSE) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associ...
5,305,178
def register_handler_cart(dp: Dispatcher): """Register cart handler.""" dp.register_callback_query_handler(handler_cart, state=BotState.cart)
5,305,179
def warning(text: str) -> None: """ Print out a warning message to the user """ time = datetime.now().strftime("%m/%d %H:%M.%S") msg = "[***] {}:".format(time) add_color_first(msg_color=msg, msg_no_color=text, new_color='yellow', new_style='bold') logging.warning("[{}]: {...
5,305,180
def CIFAR100Config(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :return: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.ht...
5,305,181
def _get_cycle_factor_traversal(factor_size, num_frames): """ Cycles through the state space in a single cycle. eg. num_indices=5, num_frames=7 returns: [0,1,3,4,3,2,1] eg. num_indices=4, num_frames=7 returns: [0,1,2,3,2,2,0] """ grid = _get_interval_factor_traversal(factor_size=factor_size, num...
5,305,182
def get_links(text): """Extract all kind of links from text. Ordanaty get arxivs, dois and urls from text. Link of type doi and arxiv will never have same link, but when extract urls, all of returned links will be checked to ensure no repeat links. Parameters ---------- text : text tha...
5,305,183
def get_fine_tune_var(exclude_variable_scope, if_freeze = True): """ if_freeze: Boolean, if True, optimizer will exclude gradient over the var under variable_scope """ train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) if (if_freeze): final_vars = [] ex...
5,305,184
def test_timeout_properties_transport(base_drivers, test_data): """ Assert sync driver properly sets transport related timeout values """ attribute, new_value = test_data original_value = getattr(base_drivers, attribute) assert getattr(base_drivers._base_transport_args, attribute) == original_v...
5,305,185
async def find_enums_by_topic( topic_id: Optional[TopicId], principal_service: PrincipalService = Depends(get_console_principal) ) -> List[Enum]: """ find enumerations by given topic """ if is_blank(topic_id): raise_400('Topic id is required.') enum_service = get_enum_service(principal_service) def action()...
5,305,186
def timing_function(some_function): """ Outputs the time a function takes to execute. """ def wrapper(): t1 = time.time() print(t1) some_function() t2 = time.time() print(t2) return "Time it took to run the function: " + str((t2 - t1)) + "\n" ret...
5,305,187
def all_close(x, y, msg, solver): """ Check to see if x and y are close """ try: v = np.linalg.norm(x-y) <= 1.0e-03 * max([1, np.linalg.norm(x), np.linalg.norm(y)]) except: print(""" check_failed ============ msg: %s x: %s y: %s """ % (msg, x, y)) return False v = v or np...
5,305,188
def save_cluster_ini( cluster_ini: ConfigParser, path: str, ) -> None: """Save cluster information dictionary. Args: cluster_ini: cluster info object to be saved on disk path: path, where object has to be saved Returns: None """ with open(Path(path) / I...
5,305,189
def log_event(string): """Log events and errors""" with open(log_file, 'a') as log: log.write('{}\t\t'.format(strftime("%Y-%m-%d\t%H:%M:%S")) + string + '\n')
5,305,190
def test_get_entity_with_entity_key_and_other_params(service): """Make sure the method update_entity handles correctly the parameter key which is EntityKey""" # pylint: disable=redefined-outer-name key = EntityKey( service.schema.entity_type('TemperatureMeasurement'), Sensor='sensor1', ...
5,305,191
def save_user_profile(sender, instance, **kwargs): """Save user profile when updating user.""" instance.profile.save()
5,305,192
def term_matches(text, forms_list, options): """ Counts the number of occurences of the words in forms_list in the text The terms in forms_list can either be tokens or full terms. The matching for tokens is contains and for full terms is equals. """ token_mode = options.get('token_mode', TM_TOKENS) ...
5,305,193
def first_rows_close_as_set(a, b, k=None, rtol=1e-6, atol=1e-6): """Checks if first K entries of two lists are close, up to permutation. Inputs to this assert are lists of items which can be compared via numpy.allclose(...) and can be sorted. Args: a: list of items which can be compared via numpy.allclose...
5,305,194
def rdt(df, *expr): """ execute R style expression on pandas DataFrame Args: df: pandas DataFrame *expr: each is a string expression such as 'region=="Europe", sales_fraction := sales / sum(sales), by="country"' which conforms to R data.table syntax data.table[WHERE, EXPR, GROU...
5,305,195
def test_output_download(client): """Only viewers of the job should be allowed to download result files.""" user1, user2 = UserFactory(), UserFactory() job = AlgorithmJobFactory(creator=user1) detection_interface = ComponentInterface( store_in_database=False, relative_path="detection_re...
5,305,196
def _coffea_fn_as_file_wrapper(tmpdir): """ Writes a wrapper script to run dilled python functions and arguments. The wrapper takes as arguments the name of three files: function, argument, and output. The files function and argument have the dilled function and argument, respectively. The file output i...
5,305,197
def get_info_file(fname): """ Construct the info file name from the project id. Read the project id from the qmcpack input file. """ if fname.endswith('.info.xml'): return fname info_fname = '' try: tree = ET.parse(fname) except IOError as e: print('Assuming xml input file, unable to...
5,305,198
def process_categories(cat_path): """ Returns the mapping between the identifier of a category in Places365 and its corresponding name Args: cat_path: Path containing the information about the Places365 categories """ result = {} with open(cat_path) as f: lines = f.re...
5,305,199