content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def RemoveIamPolicyBinding(lake_ref, member, role): """Remove iam policy binding request.""" policy = GetIamPolicy(lake_ref) iam_util.RemoveBindingFromIamPolicy(policy, member, role) return SetIamPolicy(lake_ref, policy)
00b1c9bd593b280d34ff4ba01d63363f231933ad
3,606,500
import copy def getXYZRGB(ds:LyftDataset, pc, sample:dict, pointsensor): """ Implements the extraction of RGB values for each LiDAR point inputs: - ds: dataset class (LyftDataset) - pc: pointcloud (LiDAR/RADAR) - sample: sample (dict) ...
a077edd016b45be4af426d087bf0a630db513278
3,606,501
def find_tee(code): """ Find the use of tee in the code Documentation: """ tee_token = (Token.Name, '^tee$') tee_idiom = PythonIdiom('tee') for line_found in _findOneToken(tee_token, code): tee_idiom.addNew(line_found) log("tee found in lines {0}".format(tee_idiom.getLines())) ...
438bf3084a97fdab245b3c8bb810ada017c14b2f
3,606,502
import os def GetAbsPathInModule(*paths): """This function prepends the path to the module to a path given in the input""" return os.path.join(GetModulePath(), *paths)
b3e7d13ca9113aee34fdf0483ff1cc86bc74ab32
3,606,503
from typing import Counter def check_author_count(counter: Counter) -> bool: """ Takes a set of documents and counts the number of authors. If less than 2, returns False otherwise True. :param counter: a Counter object for author counts. :return: a boolean indicating whether or not the document se...
31b697cc0e5a395ebb0702c40e86f5b21760021d
3,606,504
def needleman_wunsch_score(s1, s2, match=2, mismatch=-1, gap=-0.5, score_table=None): """ Neeldman Wunsch score """ utils.check_for_none(s1, s2) utils.check_for_type(str, s1, s2) score_table = score_table if isinstance(score_table, dict) else {} # s1 = utils.unicode_normalize(s1) # s2 ...
41228ee3d5e775bc5e9f49db1b63fc3e12bcdef0
3,606,505
def extract_rows(uri: str, *, variables: t.Optional[t.List[str]] = None, area: t.Optional[t.List[int]] = None, import_time: str = DEFAULT_IMPORT_TIME) -> t.Iterator[t.Dict]: """Reads named netcdf then yields each of its rows as a dict mapping column names to values...
dd8073d045ce114a1797eca1b02ef52ef46f7931
3,606,506
def CalculateCompositionCharge(ProteinSequence): """ ############################################################################################### A method used for calculating composition descriptors based on Charge of AADs. Usage: result=CalculateCompositionCharge(protein) Input:protein is a pure p...
1b01f83c7f67841c54658e24ada583c6e6954b91
3,606,507
import os import sys def scripter(fn,spot=None): """ Decorator which calls a script interactively and discards the function. """ # the calling module should send along the file so we know where to look # for the script which we will be calling interactively # dev: automatically detect the file from the origin...
b75214ea313230a21221c2d5a8c3909fa2d5078f
3,606,508
def create_model_cousera(input_shape, class_num=command.NUM_CLASSES): """ Function creating the model's graph in Keras. Argument: input_shape -- shape of the model's input data (using Keras conventions) Returns: model -- Keras model instance """ x_input = Input(name='the_input', shape...
b868ea7266514512e6233e60ab13531e99360ee0
3,606,509
import matplotlib.pyplot as plt def get_plt(): """import matplotlib.pyplot raise import error if matplotlib is not installed """ try: return plt except (ImportError, RuntimeError): # pragma: no cover msg = "Could not import matplotlib\n" msg += "matplotlib required for plo...
8876d3b6b2cbae6988503170dcca0d829ea93c57
3,606,510
from datetime import datetime def create_portfolio() -> pd.DataFrame: """ Create data frame of current allocation. """ previous_business_day = (datetime.date.today() - BDay(1)).date() portfolio = list(Depot.objects.get_portfolio_at_date(previous_business_day)\ .annotate( symbol...
783d3f62c1c05714962d14eb03583506781253cf
3,606,511
def read(source, target=None): """Saves the contents of 'source' to 'target' Returns the name of the resulting file.""" if target is None: target = source logger.debug("Reading %s as %s" % (source, target)) container = _init() obj = container.get_object(source) obj.save_to_filen...
f6165dd74253aeb070bda8b2b526eafabcbdff21
3,606,512
def get_testscraper(line): """Get scraper from test output line.""" classname = line.split('::')[1][4:] for scraperclass in get_scraperclasses(): if scraperclass.__name__ == classname: return scraperclass raise ValueError("Scraper %r not found" % classname)
c41f307a0e2f1bb7f9a34c37b855637ecb840f48
3,606,513
def memory_capacity_reservoir(conn, input_nodes, output_nodes, readout_modules=None, readout_nodes=None, resname='EchoStateNetwork', alphas=None, input_gain=1.0, tau_max=20, plot_res=False, plot_title=None, **kwargs): """ ...
df45c1dc0cdeb0fa4dfa895d2922a3b8b5e9b8f2
3,606,514
import os def create_operation(operation_spec, base_result_dir = None): """ Creates the operation for the given operation spec Simple wrapper to the *create* function of the operation, getting the operation result dir from the configuration file. """ if base_result_dir is None: base_resul...
8c1fe10270c609cc8411611f89c1252db154a1e5
3,606,515
def default_destinations(iata_code_original_destination): """Get three default destinations different from original destination of query.""" # Paris, London, Rome, New York defaults = ['CDG', 'LHR', 'FCO', 'JFK'] if iata_code_original_destination in defaults: defaults.remove(iata_code_original_...
904ebb69bdb3bb893580b201bbc50060a194ed7b
3,606,516
from typing import Dict def load_processed_h5(data_file_path: str) -> Dict: """ Load processed dataset containing the train, validation and test subsets with corresponding samples and labels. :param data_file_path: Path to the .h5 file. :return: Dictionary containing train, validation and test su...
91643c16c8a13f6dc893fd3be5308c82ae6ecdc3
3,606,517
import copy def clean_up(room_list): """ Cleans up the room list provided so that if there's numbers that are isolated, they are changed to the surrounding number. I.e. [[0, 0, 0, 1] [0, 0, 1, 0] [0, 0, 0, 0] [1, 1, 1, 0], [1, 0, 1, 1,]] Gets turned to [[0, 0, 0, 0] [0...
b11b19a3ce3d7c4a67fe8b8664b6198ebc7fb65c
3,606,518
def to_dict_batch(o3d_geometry_list): """Convert sequence of identical (legacy) Open3D geometry types to attribute-tensor dictionary. The geometry seequence forms a batch of data. Custom attributes are not supported. TODO: This involves a data copy. Add support for List[Open3D geometry] directly to...
9786325d7feb2db3f88caba18cf01e5854e391fc
3,606,519
def get_valid_time_levels(): """Checks files defined in Common and decides what time levels to return """ if isinstance(loaders.get_parameter("DaySlices"), pd.DataFrame): levels = [s.upper() for s in constant.TIME_SLICES] elif isinstance(loaders.get_parameter("DayTypes"), pd.DataFrame): ...
1c407857f6787918240859e5dd44cf755bbafc9e
3,606,520
import random def move_network_to_new_agent(network_id, old_agent_id, agents): """Move network from one DHCP agent to another one If adding to new agent will success then network will be also removed from old agent. :param network_id: id of network to move :param old_agent_id: id of existing age...
8ec3051627f361412439a32735483f7f4a815c5b
3,606,521
import calendar def download_month(variable, yyyy, mm): """ Function to attempt to retrieve data for a specific month. Args: variable: string of variable name used by API (e.g. 'rainfall') yyyy: string containing year (e.g. '2017') mm: string containing month (e.g. '05') Outp...
5f33a6c7be67a7f1cf0cb8d74e551284681f3e98
3,606,522
def is_dir_tracked(path, p4=None): """ Return True if the given directory is currently tracked in perforce """ if p4 is None: p4 = get_p4_from_path(path) try: info = p4.run_dirs(path) except P4.P4Exception: return False else: if len(p4.errors): return Fals...
038966012700f24df6d901f0edb70ed27860e103
3,606,523
import re def getStructuralDistance( target_structure, Cseq, path, RNAfold, verbose, LP, BP, RNAfold_pattern, IUPAC_compatibles, degreeOfSequenceInducement, pseudoknots, strategy, ): """ Calculator for Structural Distance """ # fold the current solution'...
028e4707468aba3fa961a26b8dc0ac570e1718aa
3,606,524
def compose(first: VIDEOGRAIN.ConversionFunc, intermediate: CogFrameFormat, second: VIDEOGRAIN.ConversionFunc) -> VIDEOGRAIN.ConversionFunc: """Compose two conversion functions together""" def _inner(grain_in: VIDEOGRAIN, grain_out: VIDEOGRAIN): grain_intermediate = grain_in._sim...
fcc80a078510b30157795e6851701eab5efc4b3c
3,606,525
import ast def ast_argspec(node): """ Get the argspec equivalent from ast.Call and ast.FunctionDef. Both: def func(arg1, arg2, *args, **kwargs): pass func(arg1, arg2, *args, **kwargs) will return the same argspec. Note: The defaults will ast.Node since we don't know the values...
1eab3568a848a221136bd9995f9be1db2bb743e1
3,606,526
def _ToCamelCase(name): """Converts hyphen-case name to CamelCase.""" parts = name.split('-') return ''.join(x.title() for x in parts)
c164572c386e16c9fdf193eac24f350ee8218cfc
3,606,527
def tree_intersection(tree_one,tree_two): """[given two binarytrees as parameters returns the itersection of the trees values] Args: tree_one ([binarytree]): [description] tree_two ([binarytree]): [description] Returns: [list]: [intersection of trees] """ intersection = [] ...
b2277a8121ce24446ef6ff1957d46c0e0853e79e
3,606,528
def generate_tech_options(): """ Generate technology strategy options. """ output = [] scenarios = ['low_20_20_20', 'baseline_20_20_20', 'high_20_20_20', 'low_10_10_10', 'baseline_10_10_10', 'high_10_10_10', 'low_5_5_5', 'baseline_5_5_5', 'high_5_5_5', ...
ab0ae37c6c9ddbdbcf8126f7f37bd4c54804d1cb
3,606,529
def has_strange(pdgid: PDGID_TYPE) -> bool: """Does this particle contain a strange quark?""" return _has_quark_q(pdgid, 3)
4d279588819d769fc4f5a672c2f92bdf6ecb8480
3,606,530
import json import io def boxes(): """ Draws bounding boxes around detected objects. See the Swagger UI for an example request. :return: The image with bounding boxes otherwise json with error message """ if request.content_length > 4194304: return Response(json.dumps({'error': 'Exceed...
b8073f50d6d9e49b6afc7434337ed15bfa4a6925
3,606,531
def name_records_summary(self): """ Count records for every name record. Args: mod_name (str): Return: None """ counts = {} for mod, records in self.records.items(): for rec in records: if rec['id'] not in counts: counts[rec['id']] = {...
4c23d37bb8aac839afcb2a2cb724d352db8e5d8c
3,606,532
def getVectorMultipolygon(polygonfile): """ Read the given vector file and return a ogr.Geometry object of a single multipolygon of the whole layer, projected into lat/long (EPSG:4326). """ ds = ogr.Open(polygonfile) lyr = ds.GetLayer() feat = lyr.GetNextFeature() wholeGeom = N...
93698b91782d4de987abae7b092274d2e82267c5
3,606,533
import hashlib def same_files(fname, fname2): """ Two files are the same if they have the same hash. :param fname String: The first filename. :param fname2 String: The second filename. """ try: hash1 = hashlib.sha512() with open(fname, 'rb') as fin: hash1.update(fi...
502b7b6942d8766edad78d7aa0c7de9ddd85a7cb
3,606,534
def encode_msg(msg: dict, enc: str) -> str: """ Encode the given message using the serialization specified :param msg: message to encode :param enc: serialization to encode :return: encoded message """ enc = enc.lower() msg = general.default_encode(msg) if enc not in serializations....
617398a21aca632107826d32db2d5f26a2479cdb
3,606,535
import time def opening_web(web,path,wait_time): """ Open a webpage using selenium ChromeDriver We'll be using this function to open webpages that we want to collect data from Args: web (str): An url adress. This is the web page will be opening path (str): The path to the chromedriver us...
fd64b72168298064598562d636411a67f3e354db
3,606,536
def get_callbacks(model_name, checkpoint_dir = "/content/checkpoint.h5", decoder = False): """ Returns a list of callbacks. Args: checkpoint_dir (str, path): make sure to have the actually .h5 file in the path decoder (boolean): whether or not your model uses the decoder Returns: ...
e5475e7524d86e5416f59a4971c17201116a9ab0
3,606,537
def make_pdf_table(df: pd.DataFrame) -> platypus.Table: """Формирует и форматирует pdf-таблицу доходности портфеля и индекса.""" list_of_lists_table = make_list_of_lists_table(df) style = platypus.TableStyle( [ ("LINEBEFORE", *_SECOND_COLUMN, LINE_WIDTH, LINE_COLOR), ("LINEAB...
22009deaa454213a3047401fbf057a04aeb3dcfb
3,606,538
import time def get_all_cscs(): """Get fiscal year IDs and return their SbFiscalYear objects as a list. Using the legal CSCs, get their fiscal years, tracking their corresponding CSCs, and return the SbFiscalYear objects for them as a list that was created in create_fy_objs(). Returns: R...
5c06a6bdea2b1c86bba0ef314e7ee3928d5a8f16
3,606,539
import csv def get_total_reward() -> float: """ to check the calculated rewards, sum up all results in the output file :return: sum of all rewards """ s = 0 with open(output_file, newline='') as output: reader = csv.reader(output) for row in reader: s += float(row[...
90c61284102ecc9863261825eda226f7561604d4
3,606,540
def get_key(key, starting_dict=None, update_chained=True, chained=None, chained_status=None): """ Given a dictionary, return an element by ``key``. By default, ``chained`` will have ``.update()`` called on it with ``starting_dict`` as the only argument. Set ``extend_chained`` to False to ignore ``s...
95cf54eae15475745c7a8ff46c7c8c26a47e6142
3,606,541
import numpy from numpy import newaxis, zeros, resize, transpose, floor, arange, array def bshow(f1, f2=None, f3=None, factor=17): """ y = bshow(f1, f2=None, f3=None, factor=17) Generate a graphical representation of overlaid binary images. Does **not** actually display the image anywhere! Gener...
88f435b2d9f6b38cb29ff59daf1b509d27702464
3,606,542
import os import glob import itertools import re def get_machine_id_list_for_test(target_dir, dir_name="test", ext="wav"): """ target_dir : str base directory path of "dev_data" or "eval_data" test_dir_name : str (default="test") ...
8b3964886ad3b2dbda86d508985898f3875a3f7f
3,606,543
def microservice_api_grpc_feedback(prediction_request: prediction_pb2.SeldonMessage = None, prediction_response: prediction_pb2.SeldonMessage = None, reward: float = 0, microservice_endpoint: str = None, grpc_max_se...
0c2eab4b50d10791612bfe22fc32b1812a9e6827
3,606,544
def constraint_currents(sim, return_magnitudes=False, constraint_ids=None): """ Calculate the time series of current for each constraint in the ChargingNetwork for a simulation. Args: sim (Simulator): A Simulator object which has been run. return_magnitudes (bool): If true, return constraint cu...
33032659d134576435fe7feb41812d7b2b7e1936
3,606,545
def num_minima(x): """ Count occurrences of maximum value of the series :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: float """ if not isinstance(x, (np.ndarray, pd.Series)): x = np.asarray(x) mi...
4eb65b8ad09c4ce1e913860acf427f3cd00807f7
3,606,546
from typing import Tuple def _create_ast_functional_form(terminal_expr, atomic_expr, fields, d_fields, constants, nderiv, dim, mapping, d_mapping, is_rational_mapping, space, mapping_space, mask, tag, num_threads, **kwargs): """ This function creates the assembly function of a ...
c4b4c240d9ea0bd529075695a58a7a5d23937e49
3,606,547
def simulate_dataset( model_dict, params, n_obs, control_means=None, control_sds=None, policies=None ): """Simulate datasets generated by a latent factor model. Args: model_dict (dict): The model specification. See: :ref:`model_specs` params (pandas.DataFrame): DataFrame with model paramet...
58409330e3d44496dc46c27cce1ba777930671c6
3,606,548
def line_animation(line, idx, limit=10, step=1): """ Animate long string """ line = line+' | ' line_start = 0 line_end = len(line) short_line_start = line_start+idx short_line_end = limit+idx short_line = line[short_line_start:short_line_end] add_line_end = abs(len(short_line)-limit) ...
85f84c524c45ea81b2b83d14bff743791d126137
3,606,549
def compute_chunksize(df, num_splits, default_block_size=32, axis=None): """Computes the number of rows and/or columns to include in each partition. Args: df: The DataFrame to split. num_splits: The maximum number of splits to separate the DataFrame into. default_block_size: Minimum num...
4fe0b363e82a51c67f6a5fd69dbc9188bddd3803
3,606,550
def format_date(value): """Return value as string.""" return_value = None if value: return_value = str(value) return return_value
76887bb3be2c858102f1b37e0a1ed8ba42235353
3,606,551
def bbox2points(bbox): """ From bounding box yolo format to corner points cv2 rectangle """ x, y, w, h = bbox xmin = int(round(x - (w / 2))) xmax = int(round(x + (w / 2))) ymin = int(round(y - (h / 2))) ymax = int(round(y + (h / 2))) return xmin, ymin, xmax, ymax
e6c3de2477e16a74c4c4c6d00d97eca473073f1d
3,606,552
def plot_phantom( phantom, axis=None, labels=None, c_props=[], c_map=None, i=-1, z=0.0, t=0.0001 ): """Plot a :class:`.Phantom` to the given axis. Parameters ---------- phantom : :class:`.Phantom` A phantom to be plotted. axis : :class:`matplotlib.axis.Axis` ...
0ae8b99de5ed6d06a531aeba767bbc43df1b2519
3,606,553
def makeBondList(size, xperiodic): """ create bond list in the square lattice Parameters -------------- size : (int, int) linear size of the square lattice xperiodic : boolean indicates PBC along x """ # bondlist format # (0,1,2) -> (x,y,'r'/'d') # 3 -> bond numb...
8500d58195e3d375837cf73a9b8b33b9c7920640
3,606,554
def level_to_rgb(level, background): """ Converts internal consept of level to a gray color for text in RGB :param level: range from 1 to 15 :return: tuple referring to (R, G, B) """ #Level goes from 1 to 15, starting from level1:(30,30,30), and getting darker with 1 point if level not in ra...
5183e72f4422031f2aed9881be1cce869c8b2606
3,606,555
def dmp_sub_term(f, c, i, u, K): """Subtract `c(x_2..x_u)*x_0**i` from `f` in `K[X]`. """ if not u: return dup_add_term(f, -c, i, K) v = u-1 if dmp_zero_p(c, v): return f n = len(f) m = n-i-1 if i == n-1: return dmp_strip([dmp_sub(f[0], c, v, K)] + f[1:], u) e...
8d9aabbf3dac02e450f3af5c83dd44943b5ed1fb
3,606,556
def sendRawTxs(config, objRpcB, xTxBlocks, strAddrMiner): """ sends raw transactions and creates blocks. All txs will have at least 6 confirmations. :param objRpcB: :param spendBlocks: lists of "blocks" that are lists of transactions. Txs in each "block" is assumed to fit in a single bitcoin block :...
4682b91430fae637c88d8dd6f4b8fa84d6d373b3
3,606,557
import os def extension(path: str) -> str: """ finds extension """ base_name = os.path.basename(path) name = os.path.splitext(base_name) extension = name[1] return extension
16771d82f62815531ffd0394902fd84647ded58c
3,606,558
def run_copy( src_path: str, dst_path: StrOrPath = ".", data: AnyByStrDict = None, **kwargs, ) -> Worker: """Copy a template to a destination, from zero. This is a shortcut for [run_copy][copier.main.Worker.run_copy]. See [Worker][copier.main.Worker] fields to understand this function's ar...
6ff63984a6d2bb1c1c725a472e465ede4de284a2
3,606,559
def get_message_relay(celery_app): """ Function that return a celery task list. """ return celery_app.tasks['eduid_msg.tasks.send_message']
d024b6c95013d8fbd854d833e74dbedf0220a7df
3,606,560
def validate_premium_registry(cmd, registry_name, resource_group_name=None, message=None): """Raise CLIError if the registry in not in Premium SKU. :param str registry_name: The name of container registry :param str resource_group_name: The name of resource group """ registry, resource_group_name = ...
8fe021d6b1a13b57ed16dd18f4f845ed6d58cb29
3,606,561
def weapon_list(fn): """ Decorator to set up weapon list .. versionadded:: 0.8 """ def weapon_setup(*args, **kwargs): """ Setup weapon list """ context = args[0] if not hasattr(context, 'weapon_list'): context.weapon_list = {} context...
a54baf7a292898da62da6fb3ff06454ce8e7719a
3,606,562
def serialize(cluster, nodes, ignore_customized=False): """Serialize cluster for provisioning.""" objects.NodeCollection.prepare_for_provisioning(nodes) return ProvisioningSerializer.serialize( cluster, nodes, ignore_customized=ignore_customized)
c6d68c3cb200ac6ee91212a892120e94ac0d4d33
3,606,563
def get_ontology(*args, **kwargs): """Returns a new Ontology from `base_iri`. This is a convenient function for calling World.get_ontology().""" return World().get_ontology(*args, **kwargs)
8af18e65efadccf885f45327a55e08151db499c8
3,606,564
from typing import Optional def can_use_local_differ(repo: Optional[git.Repo]): """On some non-master branch""" return repo is not None and repo.head.ref.name != 'master'
8a8f62609e79048dadda221659ff3a520b4ecfac
3,606,565
def edit_tag(tag_id): """ PUT endpoint that edits an existing club tag. """ new_tag_name = g.clean_json['name'] old_tag = Tag.objects(id=tag_id).first() if old_tag is None: raise JsonError(status='error', reason='Old tag does not exist!') new_tag = Tag.objects(name=new_tag_name).f...
652aadd6c4d4b9a0a3839ee67a3d97b30f48c4f4
3,606,566
def stochastic_lindbladian(Q, sparse=False): """ Construct the Lindbladian corresponding to stochastic Q-errors. Mathematically, for a d-dimensional matrix Q, this routine constructs the d^2-dimension Lindbladian matrix L whose action is given by L(rho) = Q*rho*Q^dag where rho is a density matr...
2d0c6a4e39405804d10694fc7c7a331f6bf1bc23
3,606,567
import json def get_boxnote_text(filepath): """Convert a boxnote to plain text. Parameters: filepath (str): the path to the boxfile Returns: the text of the boxfile as a string """ f = open(filepath, encoding="utf8") text = json.loads(f.read())["atext"]["text"] f.close() return ...
ba41e36d534931b9e2d1a401d7317ee4f8956f13
3,606,568
def define_ising_helper_functions(): """Functions for plugging into solvers for +/-1 Ising model with fields h_i and couplings J_ij. Returns ------- function calc_e function calc_observables function mch_approximation """ @njit(cache=True) def fast_sum(J...
3d034fab74665d2260ba59280610894286bf5a22
3,606,569
def create_obs_vectors_singular(raw_obs, which_unit): """Creates a singular observation vector from the persepctive of which_unit See the link below for a list of available features and corresponding indices https://github.com/jjlee0802cu/pylol/blob/main/pylol/lib/features.py ""...
b032a96152446e21c067a7dc881b96b5a762f1c0
3,606,570
def discriminator_xz(x_inp, z_inp, is_training=False, getter=None, reuse=False, do_spectral_norm=True): """ Discriminator architecture in tensorflow Discriminates between pairs (E(x), x) and (z, G(z)) Args: x_inp (tensor): input data for the discriminator. z_inp (tenso...
ea90fb0ef4a1beb9ddbc9bfe93b11fb06f37fabb
3,606,571
def func_args_realizer(args): """ Using an ast.FunctionDef node, create a items list node that will give us the passed in args by name. def whee(bob, frank=1): pass whee(1, 3) => [('bob', 1), ('frank', 3)] whee(1) => [('bob', 1), ('frank', 1)] """ items = map("('{0}', {0})".for...
d8f4bc8b7a79796e9512b6c6c2ad884e79389ebc
3,606,572
def flatten_list_bytes(list_of_data): """Concatenate a sequence of bytes-like objects.""" if not PY34: # On Python 3.3 and older, bytes.join() doesn't handle # memoryview. list_of_data = ( bytes(data) if isinstance(data, memoryview) else data for data in list_of_d...
567f29f808adf80e400098d457d6c5d08cc0059f
3,606,573
import os def _process_submodules(opts, work_dir): """ process submodules for an extracted repository After extracting a repository to a working tree, this call can be used to extract any tracked submodules configured on the repository. The ``.gitmodules`` file is parsed for submodules and caches...
3e21bb0c25a86c5424ed7b4f89ad4252de5f36e1
3,606,574
from tqdm import tqdm from tqdm import tqdm import functools import collections import logging def generate_rerouters_process(parameters): """ Compute the rerouters for the given parking areas.""" sumo_net = sumolib.net.readNet(parameters['net_file']) ret_rerouters = dict() @functools.lru_cache(maxs...
1a19d6534eb37470937c6784b9d5817b9f9d8155
3,606,575
import io def load_ffme_returns(cols: list = None): """ Load the Fama-French Dataset for the returns of the Top and Bottom Deciles by MarketCap """ with resources.open_binary("tests.data", Params.DATA_FFME_FILE) as file: file = file.read() file = io.BytesIO(file) df = pd.read_csv(f...
cdb769df3a91368735b7e932be8d7bf35ca0f3ca
3,606,576
def verify_stereo(zz_stereo, zz_mono, disparity_x, disparity_y): """Verify disparities based on coefficient of variation, maximum y difference and z difference wrt monoloco""" # COV_MIN = 0.1 y_max_difference = (80 / zz_mono) z_max_difference = 1 * zz_mono cov = float(np.nanstd(disparity_x) / np.a...
f51c6c1099393333e68870b5b06160d569b3be44
3,606,577
def W_true_insurance(): """Returns the ground true DAG for Insurance data.""" # The output s are ig.graph object of ground truth dag of insurance dataset # and grouth truth dag of the insurance dataset in adjacency matrix format. vertex_label = [ 'PropCost', 'GoodStudent', 'Age', 'SocioEcon', 'RiskAvers...
57bd5f649f41fe9a7648aa586a74c1718734a275
3,606,578
def return_numbers_names_colors(): """ Return lists of numbers, names, and colors representing anatomical brain regions derived from FreeSurfer's FreeSurferColorLUT.txt lookup file. Returns ------- numbers : list of integers numbers representing anatomical labels from FreeSurferColorLUT...
ed9d9282fd5ef729b57b8e6cb42704e1827caf07
3,606,579
import math async def cos(regular_message: Message.Message, event:Event.MessageEvent, *, bot) -> Message.Message: """ 三角函数cos。 格式:cos x x: 要求的数 """ x = float(regular_message[1].data['text']) ans = math.cos(x) return Message.Message.init_with_segments( Message....
fb22f05876f8c32dde0c9a1c76786c4f20d09530
3,606,580
def _GetBrowserDumpEvents(track): """Get the browser memory dump events from a tracing track. Args: track: The tracing_track.TracingTrack. Returns: List of memory dump events. """ assert sandwich_runner.MEMORY_DUMP_CATEGORY in track.Categories() browser_pid = _GetBrowserPID(track) browser_dumps_...
1471f749f16afe6d932e589962df5f85c612bd49
3,606,581
import base64 def _compile_source(source: str) -> bytes: """Compile and return teal binary code.""" compile_response = _algod_client().compile(source) return base64.b64decode(compile_response["result"])
d5c1d8196bdb125b1590eb74da99a6694d1b50fe
3,606,582
def get_client_username(request, credentials: dict = None) -> str: """ Resolve client username from the given request or credentials if supplied. The order of preference for fetching the username is as follows: 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, credentials`` as ar...
f0cbabdd1e25b784adcb9fa12a1ae72f9414415a
3,606,583
def roman_to_int(input): """ Convert a roman numeral to an integer. >>> r = range(1, 4000) >>> nums = [int_to_roman(i) for i in r] >>> ints = [roman_to_int(n) for n in nums] >>> print r == ints 1 >>> roman_to_int('VVVIV') Traceback (most recent call last): ... ValueError: ...
329cefa78c2429de931fa89c4605b023e68f6a13
3,606,584
def blur_bg(img, mask, kernel_size=(5, 5)): """ blur the background of image (black region of mask). Args: img (np.uint8): image to blur mask (np.uint8): mask to use as reference kernel_size (tuple, optional): kernel size to use for blur. Defaults to (5, 5). Returns: img_bl...
e6bb783a898ae39ce6c34e0a173e4e20d437eb3c
3,606,585
def convert_to_canonical(P=[]): """Convertion function to convert from shapely object to canonical form. Args: P: Shapely object representing a polygon. Returns: poly: A polygon represented in canonical form. [] otherwise. """ if type(P) is not Polygon: logger.warn("Polygon conversion requested but wrong ...
ffb08362e73e9ab467db0e4f12b9b574b6e48e6f
3,606,586
def categorical_log_prob(self, logits): """ torch RelaxedOneHotCategorical log_prob is weird (uses that of TransformedDistribution) need to use log_prob from base_dist instead """ return self.base_dist.log_prob(logits)
50b9124ddbdd04696b4b152d55cb0ec4ffd86b05
3,606,587
def showCategory(category_name, category_id): # Add SQLAlchemy statements """Takes in a specified category_name and returns the the items associated with it. Renders a web page showing all the categories on one side and the items on the other side of the page. """ # NOTE IMPORTA...
b803de6214674404fa3c91117444926fb4187717
3,606,588
from typing import Dict def filter_val_not_none(d: Dict) -> Dict: """ Return a new dictionary composed of all key-value pairs (k, v) in d where v is not None. :param d: original dictionary :return: d, without key-value pairs where value is None >>> filter_val_not_none({"a": 5, "b": 10, "c": None}...
21aaf90a4407a690ce76d09dfb54d93c1293c953
3,606,589
def get_card_ids(db) -> list: """ Gets a list of all card IDs in the datase. :return: List of card IDs. """ return db['cards'].distinct('_id')
48e6e1880253603233ccdc55fb38269f75375f8f
3,606,590
from typing import List def filter_rows( df_filter:pd.DataFrame, df_to_keep:pd.DataFrame, filter_on:List[str], to_keep_on:List[str], drop_duplicates:bool=True) -> pd.DataFrame: """ Filter rows from `df_to_keep` which have matches in `df_filter` **N.B.** The order o...
08d75fa426f46e9d4affcb60256ea9f059f3d15f
3,606,591
def factorial(n): """ Computes n! Parameters ---------- n : int A positive integer Returns ------- f : int n! Raises ------ TypeError If `n` is not a number. ValueError If `n` is not non-negative integer. """ if not is_number(n):...
e58a5ac0195c0d49d04f9888cba9b45b353992d7
3,606,592
import curses def create(): """Create zti instance. """ if Zti._zti: return Zti._zti try: Zti._stdscr = curses.initscr() except curses.error: _logger.exception("initscr error") return None try: curses.cbreak() except curses.error: _logger.e...
52b3356eda0ff537a10c1231e29edd05ce0e5bda
3,606,593
import os import shutil def upload_bids_dir(fw, bids_hierarchy, group_id, rootdir, hierarchy_type, local_properties, assume_yes): """ fw: Flywheel client bids_hierarchy: BIDS hierarchy, dict rootdir: path to files, string hierarchy_type: either 'Flywheel' or 'BIDS' ...
1f3e97248947587007d1a01481155df8a8722832
3,606,594
def format_system_date(date=None): """Formats a system date. (Format: YYYY-MM-DD) """ return u'%d-%02d-%02d' % (date.year, date.month, date.day)
f34db708b467d07827de7efed8242b821b38020a
3,606,595
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.registry.registerUtility(link_attrs, interfaces.ILinkAttrs) config.include('clldmpg') config.include('clld_glottologfamily_plugin') config.registry.r...
72c1abc8382416224e18a3f26b81aeeadd55e46c
3,606,596
def lofarHBAAntPositions(ants, lofarStation, elem): """Update the antenna positions using the HBADeltas file ants: [nants, 3] array, antenna positions in XYZ lofarStation: instance, see lofarConfig.py elem: hex/base-16 string of tile element IDs returns: updated [N, 3] antenna position array ""...
770665fb58ba116dc5ba5d63535f67bd00a999cf
3,606,597
import time def datetime_to_integer(datetime): """Convert datetime object to integer value. 'datetime' is the datetime object""" return time.mktime(datetime.timetuple())
8d4d94fac947c3dd9e82ee3d60a1a57a6440457d
3,606,598
def _django_test_command(settings_module): """Get the manage.py test command for Django""" manage_script = conf.SITE_ROOT / 'manage.py' if not manage_script.exists(): print yellow("Django script manage.py doesn't exist in %s" % conf.SITE_ROOT) return None return '{MANAGE_PY} test --sett...
907e503b8fdd8f1a1188a24ddc928896f204eb27
3,606,599