content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def duration(start_time, end_time=None): """Get a timedelta between end_time and start_time, where end_time defaults to now(). WARNING: mixing tz-aware and naive datetimes in start_time and end_time will cause an error. """ if not start_time: return None last_time = end_time if end_...
89febebf342225525bf7543342b884f130e7b3f2
28,086
def get_commands(cfg, clargs, *, what, **kwargs): """ Delegates the creation of commands lists to appropriate functions based on `what` parameter. Parameters ---------- cfg: dict Configuration dictionary. clargs: Namespace Command line arguments. cmds: iter(tuple(str)) what: str...
360410064a24d547729722c4f5843d78af9444c8
28,087
def heappush(heap, item): """ >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13], 7) [4, 4, 8, 9, 4, 12, 9, 11, 13, 7] >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13, 7], 10) [4, 4, 8, 9, 4, 12, 9, 11, 13, 7, 10] >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13, 7, 10], 5) [4, 4, 5, 9, 4, 8, 9, 11, 13, 7, ...
99e6814828e42da8a14f4d0873e62af920a800b8
28,088
def dx(scalar_field): """ Computes first derivative of a 1D scalar field :param scalar_field: :return: """ first_derivative = np.zeros((scalar_field.size - 1)) for i_scalar in range(scalar_field.size - 1): i_next_scalar = i_scalar + 1 first_derivative[i_scalar] = scalar_fiel...
b0af862210a2a395dcdfdab2e921f2c305a536d2
28,089
def get_genetic_profiles(study_id, profile_filter=None): """Return all the genetic profiles (data sets) for a given study. Genetic profiles are different types of data for a given study. For instance the study 'cellline_ccle_broad' has profiles such as 'cellline_ccle_broad_mutations' for mutations, 'ce...
b409a1511112cafab0330a23684b3e255fa0a60c
28,091
import string def cipher(sentence, n_rotate): """ Cipher string with Caesar algorithm ( Anything else than letters stays the same. ) :param sentence: String containing sentence/sentences/word/words. :param n_rotate: number to translate letters :return: string with ciphered words """ upper ...
e0606949f254971431faf7899bd254f4792176d4
28,092
from typing import Union from typing import List def _assert_in_fc( r: RestClient, uuids: Union[str, List[str]], all_keys: bool = False ) -> StrDict: """Also return data.""" if isinstance(uuids, str): uuids = [uuids] if all_keys: data = r.request_seq('GET', '/api/files', {'all-keys': ...
908f12309a93abc472e05598abbb0e5ee29cc798
28,093
def power_law(uref, h, href, shear): """ Extrapolate wind speed (or other) according to power law. NOTE: see https://en.wikipedia.org/wiki/Wind_profile_power_law :param uref: wind speed at reference height (same units as extrapolated wind speed, u) :param h: height of extrapolated wind speed (same ...
cb5d002dfeed022af694060bfe9e516191835742
28,094
def binary_weight_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True):...
3cae56fee85ba0c7679e9de7fd2743c9ce252d1a
28,096
def dataset2Xy(dataset): """Convert a dataset (pd.DataFrame) to X, y and output_dim where X is the features, y is the labels (one-hot vectors), and output_dim is the number of labels overall. Args: dataset: A pandas dataframe that is composed of features columns and th...
ef07873db639a7a9c34b149959acd419d4a0b9d3
28,097
def pairwise_list(a_list): """ list转换为成对list "s -> (s0,s1), (s1,s2), (s2, s3), ..." :param a_list: list :return: 成对list """ if len(a_list) % 2 != 0: raise Exception("pairwise_list error!") r_list = [] for i in range(0, len(a_list) - 1, 2): r_list.append([a_list[i], a...
5142fb2e00c931ab57fc9028eb9b6df5a98c0342
28,099
import math def BaseWaveguideOFF(args,state,options)->GeomGroup: """ Offset the waveguide (jumps left or right of waveguide) Parameters ---------- args : list 1 argument: offset (in um), positive means on left of waveguide direction. state : dict Current state. options : d...
235004836ea149b02c7dd12dde400861a6739954
28,100
def read_csv_profiles(file): """Read csv file and parse dates.""" return pd.read_csv(file, parse_dates=["valid"], index_col="valid")
ce45c4200e8cc71daaec4dcb91e5bdd9199709c6
28,102
def uCSIsMathematicalAlphanumericSymbols(code): """Check whether the character is part of MathematicalAlphanumericSymbols UCS Block """ ret = libxml2mod.xmlUCSIsMathematicalAlphanumericSymbols(code) return ret
2812f04afe4d977636a1c7c41dac712f1d63e184
28,103
import time def builtin_localtime(t): """ Convert an epoch time to a [yr mon day hr min sec wd yd dst] list structure in the local timezone, or vice-versa. """ if isinstance(t, BReal): tv = [BInt(xv) for xv in time.localtime(t.value)] return BList(tv) elif isinstance(t, BList): tvv = [x.value for x in t.v...
ebc900d3b82f5223489e3fedb761302713e27fba
28,104
def avg_gate_infidelity(A, B, mxBasis): """ Returns the average gate infidelity between A and B, where B is the "target" operation.""" return _tools.average_gate_infidelity(A, B, mxBasis)
282b930fbaf1822ec52b937c854491ed8512ae89
28,105
from bs4 import BeautifulSoup def html_to_plain_text(html_str): """ Takes an HTML string and returns text with HTML tags removed and line breaks replaced with spaces. Shamelessly copied from open-discussions. Args: html_str (str): A string containing HTML tags Returns: str: Plain ...
d681ffdf2878f13673d66dadf964dcb2d0d06644
28,106
from datetime import datetime def read_hotfilm_from_lvm(filename, dt=1e-3): """Reads 2-channel hotfilm data from a Labview text file.""" times = [] ch1 = [] ch2 = [] data = [line.rstrip() for line in open(filename).readlines()] line = data[0].split(',')[1:] t = [int(float(n)) for n in line...
e0dadac656120173e5833e6eb36498943613e8f5
28,107
import string def GetCategoryWrapper(func_name): """Return a C preprocessor token to test in order to wrap code. This handles extensions. Example: GetTestWrapper("glActiveTextureARB") = "CR_multitexture" Example: GetTestWrapper("glBegin") = "" """ cat = Category(func_name) if (cat == "1.0" or cat == "1.1" or...
eba3d524b3bcebfe96d253fa9348e3927ae9c737
28,110
from typing import Dict def get_capability_text(src_capability: SourceCapability) -> str: """ Returns markdown format cell text for a capability, hyperlinked to capability feature page if known """ capability_docs_mapping: Dict[SourceCapability, str] = { SourceCapability.DELETION_DETECTION: "....
df66582caa42828b5c0099c3399612973cfaab7c
28,111
import re def camel_case_split(identifier): """CamelCase split""" matches = re.finditer( ".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier) return [m.group(0) for m in matches]
bfaf845a0fa6eae46a4a8c96f91aee8c755255f5
28,112
def init_formation_goal_msg(): """Create formation goal msg Swarm goal is represented by a green sphere and arrow. Returns: [type]: [description] """ msg = Marker() msg.header.frame_id = "world" msg.header.stamp = rospy.Time() msg.ns = "swarm" msg.id = 2 msg.type = 2 ...
359e5422908b94693968fb73c7ad5e367d715e42
28,113
def allow_pay_as_you_go(**kwargs): """Allow Pay As You Go Set pay as you go account settings to ``allow=True`` Reference: https://iexcloud.io/docs/api/#pay-as-you-go Data Weighting: ``Free`` .. warning:: This endpoint is only available using IEX Cloud. See :ref:`Migrating` for m...
f2435da3b6d8e8265bf19249fbe38c8734f06d1b
28,115
def _process_user_data_for_order(checkout: Checkout): """Fetch, process and return shipping data from checkout.""" shipping_address = checkout.shipping_address if checkout.user: store_user_address(checkout.user, shipping_address, AddressType.SHIPPING) if ( shipping_address ...
e6ab0d248469fadb9233dc45d563ec2c185da8e5
28,116
def catastrophic_energy(rpb,rho,Vi): """ Return the catastrofic energy in c.g.s. Based in Stewart and Leinhardt(2009) rpb: parental radius in km rho: mean density of the system in cgs Vi: impact velocity in km/s """ # qs, qg, fi, mi: constants of material if rho < 4.0: qs, q...
4b7472df40fa7e9dc2622854805055e28d2789f4
28,117
def hide_toolbar(notebook): """ Finds the display toolbar tag and hides it """ if 'celltoolbar' in notebook['metadata']: del(notebook['metadata']['celltoolbar']) return notebook
09d594f26f2ad8ee5af2563332ff77136713a7ef
28,118
def draft_github_comment(template, result): """ Use a template to draft a GitHub comment :template: (str) the name of the template file :result: (ContentError) the error to display in the comment """ # start with template with open(template, 'r') as f: contents = f.read() # replace variables in template wi...
42842b7af06da8a54c0647e5aac079132e82de5a
28,119
def get_domains(sequence, disorder, disorder_threshold=0.42, minimum_IDR_size=12, minimum_folded_domain=50, gap_closure=10, override_folded_domain_minsize=False): """ Parameters ------------- sequence : str ...
5d7f17e0cf2b54c2da927b4f2689dddb182dfb4a
28,120
def get_topic(topic_id): """ Endpunkt `/topic/<topic_id>`. Der Response enthält die JSON-Datei des Thema. """ try: file_path = queries.get_topic_file(topic_id) if file_path is None: err = flask.jsonify({"err_msg": "Unknown topic"}) return err, 400 r...
2fee779cb7c0937441bf11470da31759a8704c0e
28,121
def get_epaipm_file(filename, read_file_args, data_dir): """Reads in files to create dataframes. No need to use ExcelFile objects with the IPM files because each file is only a single sheet. Args: filename (str): ['single_transmission', 'joint_transmission'] read_file_args (dict): dict...
0f19187bfc926abc926a5251fe52e48c93f9863c
28,122
import requests def futures_rule(trade_date: str = "20200712") -> pd.DataFrame: """ 国泰君安期货-交易日历数据表 https://www.gtjaqh.com/pc/calendar.html :return: 交易日历数据 :rtype: pandas.DataFrame """ url = "https://www.gtjaqh.com/fn/128" params = {"base_date": f"{trade_date}"} r = requests.post(ur...
b15c538b11d73d22706786cc40fe9b480e647a63
28,123
import scipy.sparse.linalg def conjgrad_scipy(A, Y, sigma, tol=1e-4): """Solve the least-squares system using Scipy's conjugate gradient.""" Y, m, n, d, matrix_in = _format_system(A, Y) damp = m * sigma**2 calcAA = lambda x: np.dot(A.T, np.dot(A, x)) + damp * x G = scipy.sparse.linalg.LinearOpera...
d25c147223df15e1934e62c59f166d50d11c3bbe
28,124
def get_total_revenue(data: list) -> float: """ data: any list with product_id at [0] and revenue at [1] returns: total revenue for data """ revenue = get_revenue(data) total = 0 for r in revenue: total += r[1] return float(total)
0387a8aff8ff8163c284b395f1bce779ec6126c4
28,125
def plot_tttdprc(data_frame): """ Plot Change Total Travel Time % vs distance """ figtt, axtt = plot_var( data_frame=data_frame, x_var="distance", y_var="totTT %", label_var="mpr", pivot="flow", x_label="Distance [m]", y_label=r"Change in Tota...
e7fb39a208bfba0e27968d728cd9980adff7c2ba
28,126
import apyfal.host.alibaba as alibaba from apyfal.host.alibaba import AlibabaCSP import apyfal.exceptions as exc from aliyunsdkcore import client from aliyunsdkcore.acs_exception.exceptions import ServerException import json def test_alibibaclass_request(): """AlibabaHost._request""" # Mocks some variables ...
480b2408b55a3975bb317a3e0710753a6b256ed4
28,127
import pathlib def write_pdf_file( fpath: pathlib.Path, puzzle: Puzzle, key: Key, level: int, ) -> pathlib.Path: """Write a PDF file of the current puzzle to `path`. Args: fpath (pathlib.Path): Path to write the CSV to. puzzle (Puzzle): Current Word Search puzzle. key ...
8a41134437c8a8989021164e92c17fe3d64284be
28,128
import csv def get_zip_rate_areas(file_path): """ reads zips.csv file and returns the content as a dictionary Args: file_path: the path to zips.csv file Returns: a dictionary mapping each zip code into a set of rate areas """ zip_rate_areas = dict() with open(file_pat...
d8405bc466e7bbe949fded4360d4f184024653d2
28,130
def lucas_mod(n, mod): """ Compute n-th element of Fibonacci sequence modulo mod. """ P, Q = 1, -1 x, y = 0, 1 # U_n, U_{n+1}, n=0 for b in bin(n)[2:]: x, y = ((y - P * x) * x + x * y) % mod, (-Q * x * x + y * y) % mod # double if b == "1": x, y = y, (-Q * x + P * y...
319e74c13c370becc255bbab9d304aa220e69a0d
28,131
def compute_demand_balancing(demand_sector, energy_service, energy_carrier): """aggregates the demand over balancing area and balancing time """ cols = get_group_cols_for_ec(energy_carrier) return compute_demand_with_coarseness(demand_sector, energy_service, ...
e70d9f42929ca88478f09ac0e5d5423457108de7
28,132
def get_file_encoding(filename): """ Get the file encoding for the file with the given filename """ with open(filename, 'rb') as fp: # The encoding is usually specified on the second line txt = fp.read().splitlines()[1] txt = txt.decode('utf-8') if 'encoding' in txt: ...
c91a8f71429ed5f6eccd7379c66b4ee4c2d73989
28,133
def alias(name): """Make property given by name be known under a different name""" def get(self): return getattr(self,name) def set(self,value): setattr(self,name,value) return property(get,set)
37539fbb2d413a4964fec09f9c1b40fed203dc34
28,134
def is_feature_class(symbol): """Check whether the symbols imported from a module correspond to classes defining a feature. We assume that the symbol in question defines a feature if it inherits from the FeatureDefinition class. :param symbol: An imported symbol to check :type symbol: object :r...
f7556869105e3a20c05e05560baf56759d08f374
28,136
def overall_sentiment(text): """Function to calculate the overall sentiment using NLTK's vader library. param text: The input text blob being entered by user """ sid = SentimentIntensityAnalyzer() ss = sid.polarity_scores(text) for _ in sorted(ss): if ss["compound"] >= 0.15: ...
faf5ba826b6affbb9ee7f972fa55098b681a15ee
28,139
def new_category(blog_id, username, password, category_struct): """ wp.newCategory(blog_id, username, password, category) => category_id """ authenticate(username, password, 'zinnia.add_category') category_dict = {'title': category_struct['name'], 'description': category_str...
9de1684fca80b7bf1a0190be1f239e2b4cae7428
28,140
def scatt(coords, id, plot_col='w', bckg_col='k', z_dim=0, **kwargs): """ 2D scatter plot Parameters ---------- coords : np.array unit : str id : str plot_col : str, default = 'w' bckg_col : str, default = 'k' z_dim : int, default = 0 axes : AxesSubplot, optional Return...
a59d176e1032c745b9b066fe9dc306c7ecae04a9
28,141
import re def keep_text_characters(text): """ INPUT: text - Python str object - the raw text OUTPUT: text- Python str object - the text after removing all non-text characters """ filtered_tokens = [] tokens = tokenize_text(text) for token in tokens: if re.search('...
e0da2f6517c1aa2b0f34349583147323a4c17ef7
28,142
def global_access(key, val): """function test""" local = 1 MY_DICT[key] = val for i in val: if i: del MY_DICT[i] continue else: break else: return local
b48b8e86f266abe79f64d665ea73055e133f04ce
28,143
def generate_auxiliar_basis( sett: Settings, auxiliar_basis: str, quality: str) -> Settings: """Generate the `auxiliar_basis` for all the atoms in the `sett`. Use the`quality` of the auxiliar basis provided by the user. """ quality_to_number = {"low": 0, "medium": 1, "g...
178e9f5eee8d192252ad48f6df19dfab670d9f4c
28,144
import pathlib def extract_user_inputs(job: Job): """Extract the various combinations of user inputs for a job.""" # variables to be used while looping through the runs all_inputs = {} job_id = job.id results_folder = pathlib.Path('data', job_id).resolve() # loop through the runs and find all ...
a0bcd3db9ff90c30b6981c9f76c54531da0e2d49
28,145
def __process_args(args): """ Process the command-line arguments and prompt the user for any missing information :param args: the command-line arguments list :raises CLAException: if an error occurs while validating and processing the command-line arguments """ cla_util = CommandLineArgUtil(_pro...
8806a4050a1cbcfa549584da4832a1c6e7f7faa6
28,146
from typing import Any def float_converter(value: Any) -> float: """Validator that ensures value is a float.""" if isinstance(value, bool): raise ValueError() if isinstance(value, float): return value elif isinstance(value, int): return float(value) else: raise Valu...
c46832a017c0d83017e75fa58090a030bc5091c2
28,147
from operator import add def generate_row(world_x, world_rpy=[0.0, 0.0, 0.0], algae_obj_dir=None, algae_texture_dir=None): """Generate a row of algaes using the given world transform""" components = [] buoy_z = 0 rope_y = 0 rope_z = buoy_z + 2 ...
c8ee8afab4d3ca4ebf386fcd0795aad9c7768eef
28,149
def split_chunk_for_display(raw_bytes): """ Given some raw bytes, return a display string Only show the beginning and end of largish (2x CONTENT_CHUNK_SIZE) arrays. :param raw_bytes: :return: display string """ CONTENT_CHUNK_SIZE = 50 # Content repeats after chunks this big - used by echo c...
de53bf679552c52f5075aedf9156cdb3b3fc69f7
28,150
def get_cvi(nodes): """ Returns a dictionary whose keys correspond to samples, and whose values are sets of tuples, where the tuples represnts the two characters this sample caused incompatability :param nodes: A list of target nodes, where each node is in the form 'Ch1|Ch2|....|Chn' :return: A dictionary w...
aeae708f8e7cd2bc1a3863dd4e77b00be8c2fc4a
28,151
import torch def warp(x, flo): """ warp an image/tensor (im2) back to im1, according to the optical flow x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow """ B, C, H, W = x.size() # mesh grid xx = torch.arange(0, W).view(1,-1).repeat(H,1) yy = torch.arange(0, H).view(-1,1).repeat(1,W)...
9f5ab5338f18cf249962454deff996a556f7b2ea
28,153
import logging async def search(username): """ Do Maigret search on a chosen username :return: - list of telegram messages - list of dicts with found results data """ try: results = await maigret_search(username) except Exception as e: logging.er...
b0cbebdea838c0a0a422af4ece86c8c0af6a7aff
28,154
def train(frame, columns, mean_centered=True, k=None): """ Creates a PcaModel by training on the given frame Parameters ---------- :param frame: (Frame) A frame of training data. :param columns: (str or list[str]) Names of columns containing the observations for training. :param mean_cente...
057261f8a1fd7d2a02f094d35fb28a5084f5ab47
28,155
def validate_spin(value): """ Validate the value of the spin """ if not isinstance(value, int): raise ValidationError('spin must be integer') if value < -1 or value > 1: raise ValidationError('spin must be among -1, 1 or 0 (undefined)') return value
d651d8ace39e92d324c823ab88a5b0e1a6637760
28,156
def _get_basis_functions(basis, deriv): """ Returns a list of interpolation function for the interpolation definition and derivatives specified by the user. Also returns the number of dimensions as defined in the basis parameter. """ # List of basis functions bsfn_list = { 'L1': [L1,...
1116989fd5d3af74bb0c499e930f98013b3b1b9a
28,157
from typing import List import logging def get_all_loggers() -> List: """Return list of all registered loggers.""" logger_dict = logging.root.manager.loggerDict # type: ignore loggers = [logging.getLogger(name) for name in logger_dict] return loggers
97059a78925ff669a841644b186e39ccd366472d
28,158
from typing import cast def argmax(input, axis=None, dtype='int64', name=None): """Index of the maximum value along an axis. Parameters ---------- input : tensor_like Input tensor. axis : () tensor_like, default=None Axis along which to extract the maximum index. If None, ...
2c04eaafadd91b19bbd3342ece5ad0a6cefa3cc0
28,159
import string def __clean(contents): """ remove comments from the list 'contents', and remove unnecessary whitespace """ answer = [] for line in contents: cleaned = string.strip(line) if len(cleaned)>0: if cleaned[0] != "#": answer.append(cleaned) return answer
e7c6a1f6a7b065fbc4da9e32f37f9e3b152848b4
28,160
import inspect def _get_extract_params(): """ Utility function for extracting the parameters from a Prophet model. The following attributes are not considered for parameter extraction for the reasons listed: The changepoints attribute is being removed due to the fact that it is a utility NumPy array ...
00b9c6526be2cc78766426386d443f3500e8668c
28,161
from typing import Mapping def deep_update(target, source): """Update a nested dictionary with another nested dictionary.""" for key, value in source.items(): if isinstance(value, Mapping): target[key] = deep_update(target.get(key, {}), value) else: target[key] = value ...
01ca285ed907850b17490290c6eb92f931ed537a
28,162
from typing import Callable def distmat(func: Callable, x: np.ndarray, y: np.ndarray) -> np.ndarray: """distance matrix""" return jax.vmap(lambda x1: jax.vmap(lambda y1: func(x1, y1))(y))(x)
0c09289e795f9f90af1a3d0363eefb82eebe6822
28,164
def feature_length(attribute_name_var): """ Return number of a attribute values """ attribute = attrDictionary[attribute_name_var] attribute_index, attribute_values = attribute return len(attribute_values)
4aa5816d38dac02cc528d6d5ee528fcaf5e39b4a
28,165
def iso2_to_country_name(country_2_code): """Convert country code to country name. """ if country_2_code not in COUNTRY_ALPHA2_TO_COUNTRY_NAME: print(country_2_code, 'NOT FOUND in iso2 to country_name') raise KeyError return COUNTRY_ALPHA2_TO_COUNTRY_NAME[country_2_code]
4c3e5f46a8c7aac6851a1d304c89e298fcc31a71
28,166
from typing import List from typing import Dict def get_related_objects(api_key: str, obj: MISPObject, rel: str, disable_output: bool = False) -> List[Dict]: """Gets related objects from VT.""" if obj.name == "file": vt_id = obj.get_attributes_by_relation("sha256")[0].value else: print_err...
5c0c36febc2f5c79c98496b835dbb2e8e5b564e6
28,167
def _take_along_axis(arr, indices, axis): """Implements a simplified version of np.take_along_axis if numpy version < 1.15""" if np_version >= parse_version('1.15'): return np.take_along_axis(arr=arr, indices=indices, axis=axis) else: if axis is None: arr = arr.flatten() ...
b7eb8c49503e6364694af3becadf7faba5814f68
28,168
def moveeffect_022(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int: """ Move Effect Name: Increases user evasion by one stage """ if move.category == MoveCategory.STATUS: if user.boosts.get("evasion", 0) == 6: score -= 90 else: ...
bde07c2101132d44e78bb9877689d7ffc36058e7
28,169
def chan_freq(header, fine_channel, tdwidth, ref_frame): """ Args: header: fine_channel: tdwidth: ref_frame: Returns: """ fftlen = header['NAXIS1'] chan_index = fine_channel - (tdwidth-fftlen)/2 chanfreq = header['FCNTR'] + (chan_index - fftlen/2)*header['DELTA...
b7cb67d2d7b21a475fdaddee47ebbd6d112125f8
28,170
import torch from typing import Any from typing import Dict def extract_logger_info( model_a: torch.nn.Module, model_b: torch.nn.Module, model_name_to_use_for_layer_names: str, ) -> Any: """ Extracts intermediate activations from model_a and model_b. """ model_name_a, results_a = _extract...
73872f1a3083373a8767ca60668479e24b0aa240
28,171
def make_masked_msa(protein, config, replace_fraction): """Create data for BERT on raw MSA.""" # Add a random amino acid uniformly random_aa = tf.constant([0.05] * 20 + [0., 0.], dtype=tf.float32) categorical_probs = ( config.uniform_prob * random_aa + config.profile_prob * protein['hhblits_profile...
47d3f40c27c6a6722ac7a8cab21844decdd21a0f
28,172
from winguhub.settings import HTTP_SERVER_ROOT def get_httpserver_root(): """ Construct wingufile httpserver address and port. Returns: Constructed httpserver root. """ assert HTTP_SERVER_ROOT is not None, "SERVICE_URL is not set in ccnet.conf." return HTTP_SERVER_ROOT
5327f05fdbdbd062435c90d51cb8ee1667199e9f
28,173
def csys_torusv1_to_xyz_jacobian(v: np.ndarray, rho_0: float, rho_1: float, aspect: float = 1) -> np.ndarray: """ Compute Jacobian matrix of the toroidal coordinate system with respect to the Cartesian coordinate system. :param v: Toroidal coordinates (r, psi, phi) :param rho_0: Torus Radius (major) ...
e402a0fbc6f8f33ccc556ab9eeaeee323f3fde99
28,174
def normalize_answer(s): """ Lower text and remove punctuation, articles and extra whitespace. """ def remove_articles(text): return re_art.sub(' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): return re_punc.sub(' ', text) # c...
1146af739b33992aae551a0b1ab5059c0d645608
28,175
import typing def intensity(pixel: typing.Tuple[int, int, int]) -> int: """Sort by the intensity of a pixel, i.e. the sum of all the RGB values.""" return pixel[0] + pixel[1] + pixel[2]
5ba060d409a2f0df148cdc50684b80f920cf314f
28,176
def load_statistics( input_path): """Loads data statistics proto from file. Args: input_path: Data statistics file path. Returns: A DatasetFeatureStatisticsList proto. """ serialized_stats = tf.python_io.tf_record_iterator(input_path).next() result = statistics_pb2.DatasetFeatureStatisticsList...
f7c094e79e7f6c8654aa703cd75da62164f9d421
28,177
def plot_grid(data): """ Plot a grid of heatmaps showing performance for each tile pairing. """ def _draw_heatmap(*args, **kwargs): """ Draw a heatmap showing flops for (ch_vect x feat_vect). """ data = kwargs.pop('data') reshaped = pd.pivot_table( data, index='c...
834472a852b98916f9a9507bc56dde5bb71c55ec
28,178
from datetime import datetime from typing import Optional def get_national_holiday(day: datetime.date) -> Optional[Holiday]: """ For a given date, return the national holiday object if the particular date is a Czech national holiday; return None otherwise """ for holiday in Holidays(year=day.year)...
8cc2b83a16e6a07fc8e5f1c8cc95bec66bf8ffe5
28,179
def robust_topological_sort(graph): """ First identify strongly connected components, then perform a topological sort on these components. graph should be a dictionary mapping node names to lists of successor nodes. """ components = strongly_connected_components(graph) node_component ...
3ecb7dbeea4f4b9f2d205472ee2c1a59465b09ea
28,180
from typing import List def similar_consonants_to(phonet_1: UnmarkableConsonant) -> List[Phonet]: """ a list of vowels that are similar to a specified consonant. """ vocal_folds: List[VocalFolds] = similar_in_voice(phonet_1.vocal_folds) place: List[Place] = similar_in_place(phonet_1.place) manner: List[Manner] ...
168603fff454bb6ba9cb29a051ec674547720344
28,181
def error_handler(error): """Render errors as JSON""" if not all(hasattr(error, attr) for attr in ("code", "name", "description")): LOGGER.exception("An error occured: %r", error) error = InternalServerError() resp = { "code": error.code, "name": error.name, "descript...
4fd4834254e78503817e621cafc14e8d477b3bad
28,182
def get_encoded_len_value(typename, package_specs): """ Get the encoded size of a given type on the wire """ if typename in PRIMITIVE_TYPES: return PRIMITIVE_SIZES[typename] encoded_len = 0 for package in package_specs: for msg in package.definitions: if get_v4_typen...
0d11c409fb760a317b456d0397876a97cf43a593
28,183
def parsestream(stream, encoding=None): """Parses sql statements from file-like object. :param stream: A file-like object. :param encoding: The encoding of the stream contents (optional). :returns: A generator of :class:`~sqlparse.sql.Statement` instances. """ stack = engine.FilterStack() s...
90c0cb061f1cdd370b5c31b8326fc80be16f310d
28,184
import torch def apply_hardmask_with_map(input, attention, mask): """ Apply any number of attention masks over the input. input: [batch, num_objs, visual_features] = [b, o ,v] attention: [batch, num_objs, glimpses] = [b, o ,g] return: masked_input, masked_weight """ b, o, v = inpu...
3dd40399e42a02770351cd772feb89ed7b2dd16b
28,185
def _make_merge_query(increment_table_id, target_table_id): """merge incremental_load to existing target_table""" client = bigquery.Client() #try ge target table columns for merge, if not possible then it means it does not exist so just copy instead try: table = client.get_table(target_table_id)...
f42f895268e5417c904c2d2c40c7f4d75306c8d2
28,186
def delete_alert(id): """ delete an alert and associated thread from the database """ alert = Alert.query.get(id) if alert is None: return {'message': 'Alert ' + str(id) + ' does not exist'}, 404 # delete associated thread delete_thread(id) # delete alert db.session.delete(al...
414e448d9b0b256342d13baea0e316cbddf007aa
28,187
def data_file_read_calltree(filename): """ Extracts the calltree of a fuzzer from a .data file. This is for C/C++ files """ read_tree = False function_call_depths = [] tmp_function_depths = { 'depth' : -2, 'function_calls' : [] } with open(fil...
10d876a8aa585a767f1939434edc018e5c44404d
28,188
def bidirected(DAG): """Return a graph with an opposing edge added for every edge in DAG.""" return skeleton(DAG).to_directed()
8ca8d79f9d5fb6d66543b91004e83854b5b9d57e
28,189
def get_census_data(independent_var, dependent_var): """ Returns a dict containing the data for the requested variables in a table format :param census_vars: the chosen variable :return: """ # Adjust the names of the variables for querying if dependent_var == PAYPEREMP: dependent_va...
9dd13284ab28aefa93d5caa8940208211eeb5bbc
28,191
def generate_chirp_exp(dur, freq_start, freq_end, Fs=22050): """Generation chirp with exponential frequency increase Notebook: C1/C1S3_Dynamics.ipynb Args: dur (float): Length (seconds) of the signal freq_start (float): Start frequency of the chirp freq_end (float): End frequency o...
c0c9b7b374fbef62e73fab3bb97caaca11388a15
28,192
def get_geoId(row: str, geo_map: dict) -> str: """ Dataframe utility function to map DC geoId based on latitude, longitude """ loc = f"{str(row['Latitude'])},{str(row['Longitude'])}" try: return ', '.join(geo_map[loc]) except: print(f"{loc} -- does not exist in the map")
a06edaaf6b7c848f4580bdd78e5514b65c23bf16
28,193
import shutil def update_cm_working_file(source_file, target): """Copies source file to target and stages in git. Returns True on success.""" print('<<Copy {} to {}>>'.format(source_file, target)) try: shutil.copyfile(source_file, target) except OSError as ex: print('Exception copying ...
2ec65b077a9c1954071f4daf4082c4eabc245252
28,195
def farthest(pts, xlims, ylims, n): """ Find the 'n' points that lie farthest from the points given in the region bounded by 'xlims' and 'ylims'. 'pts' is an array of points. 'xlims' and 'ylims are tuples storing the maximum and minimum values to consider along the x and y axes.""" # There are a...
708d8ac66da7bc478c9df64be70f0fccc5b5f28d
28,196
def vis_ss_barplot(m, s, sample, hyperparams, stats=None, t_on=None, t_off=None, with_ss=True, with_params=True, voltage_trace=None, test_idx=None, case=None, title=None, date_today=None, counter=0, save_fig=False, legend_offset=0.0, axss=None, axmemparams=None, axsynparams=N...
ad374ff232505579f9a557d26553e9e860147d29
28,197
import torch def delta_to_binary_mask(delta, k, hop_size, sample_rate, return_indeces=False): """returns a binary mask indicating the k segments with the largest norm / magnitude """ delta_factorization = TimeFrequencyTorchFactorization(delta, frequenc...
fb8eb2234565a8247df24588a77a9c6d3fe302d2
28,199
def get_patron_pid(record): """Get patron_pid from existing users.""" user = get_user_by_legacy_id(record["id_crcBORROWER"]) if not user: # user was deleted, fallback to the AnonymousUser anonym = current_app.config["ILS_PATRON_ANONYMOUS_CLASS"]() patron_pid = str(anonym.id) else...
e2ba9102052c0ce84f7fc04fdc5be97a6050634c
28,200
import PySide.QtGui as QtGui import PyQt5.QtWidgets as QtWidgets def get_QGroupBox(): """QGroupBox getter.""" try: return QtGui.QGroupBox except ImportError: return QtWidgets.QGroupBox
9c0333c9c8a4fafd1c4f4f5739546aaa19a6e321
28,201
import collections def update_dict(orig_dict: dict, new_dict: collections.abc.Mapping) -> dict: """Updates exisitng dictionary with values from a new dictionory. This function mimics the dict.update() function. However, it works for nested dictionories as well. Ref: https://stackoverflow.com/questio...
e176f4cf293be67aece6e9811fe75de679bb1e94
28,202