content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Iterable from typing import Any from functools import reduce def concat(*it: Iterable[Any]) -> Any: """ Concatenation of iterable objects Args: it: Iterable object Examples: >>> fpsm.concat([1, 2, 3], [4, 5, 6]) [1, 2, 3, 4, 5, 6] """ return reduce(...
e2b9d1604630198486fa0649d62784078547031a
59,995
import math def to_4326(coord_size: int, point: mi.Point) -> mi.Point: """Convert a point in maps.me-mercator CS to WGS-84 (EPSG:4326).""" merc_bounds = (-180.0, -180.0, 180.0, 180.0) # Xmin, Ymin, Xmax, Ymax x = point.x * (merc_bounds[2] - merc_bounds[0]) / coord_size + merc_bounds[0] y = point.y * ...
82762aeddfe1ae292453e198d316ff2efe357b0b
59,996
def plot(domain, solution=None, solution_exact=None, **kwargs): """Plots a solution (and optionally a reference solution) onto the given DiscreteDomain instance. **kwargs are the same as the ones in the DiscreteDomain's visualize() method. Parameters ---------- domain : DiscreteDomain ...
003f55c54a19145e847b3baf97266f301b09ddaf
59,997
import platform import functools def Linux(func=None): """ is Linux expression and decorator Args: func: Returns: """ if func is None: return platform.system() == "Linux" @functools.wraps(func) def wrapper(*args, **kwargs): if platform.system() == "Linux": ...
22d8668edd639c94c8a96b5c8ea62af7d4e09fae
59,999
def create_batch(klass, size, **kwargs): """Create a factory for the given class, and create a batch of instances.""" return make_factory(klass, **kwargs).create_batch(size)
e87a8659067938e6a48a1d514eef410ede4bc9a7
60,000
def compute_x(g, h, p, e, n): """Compute intermediate x such as h=g^x in the group <g> (cf. Pohlig-Hellman algorithm).""" mod = pow(p, e) ghat = pow(g, pow(p, e-1), n) ginv = gmpy2.invert(g, n) x = 0 tmp = 1 for i in range(e): exp_hhat = pow(p, e-1-i) hhat = pow(h*tmp, exp_hh...
5b74fd08e44fac1c7647e93763d106bd74f10fcc
60,001
def fib_recursion(n): """ Assum n is an integer n > 0 """ if n == 1: return 0 if n == 2: return 1 return fib_recursion(n-1) + fib_recursion(n-2)
1a59e9df4f8ae0150234ab5401021b298493e1c9
60,002
def linearize(path, n_points=360): """Interpolate between all points on a path.""" points = [] for segment in path._segments: if type(segment).__name__ == 'Line': n_points = 0 linearized = linearize_segment(segment, n_points) points.extend(linearized[:-1]) points.appe...
0e664ea07bec07b911c3061598869e43b8052084
60,003
def del_records(bibcode_list): """ :param bibcode_list: :return: """ try: with current_app.session_scope() as session: count = 0 for bibcode in bibcode_list: count += session.query(DataLinks).filter(DataLinks.bibcode == bibcode).delete(synchronize_ses...
54dbed2eeff2215276fb249121cb21b326f38551
60,004
import logging def setup_logger(name, use_colors=True, verbose_count=0): """ 初始化日志~ :param name: 日志名 :type name: str :param use_colors: :type use_colors: bool :param verbose_count: :type verbose_count: int :return: """ fmt = '[%(levelname).8s %(asctime)s %(name)s:%(lineno)d...
d2a8a294b013ff862487637befc50cc89c87e826
60,005
import tarfile def fetch_tgz(dataname, urlname, data_home=None): """Fetch zipped dataset. Fetch a tgz file from a given url, unzips and stores it in a given directory. Parameters ---------- dataname: string Dataset name. urlname: string Dataset url. data_ho...
9d81d8a246ecc372599cec2a170d1fdadec54913
60,006
from typing import Callable def find_best_transform( sorted_x: np.ndarray, y: np.ndarray, w: np.ndarray, pct_to_clip: float = 0.005, identity_bias: float = 1e-6) -> Callable[[np.ndarray], np.ndarray]: """Finds the best transformation to use for PWLCurve fitting. Chooses between identity, log,...
3e5d0af4c096cb92e2db8c8e4b12ae3cad7ebeaa
60,007
def convert_url_to_path(url: str) -> str: """ >>> convert_url_to_path('file:///var/tmp/libreoffice') '/var/tmp/libreoffice' """ return pyuno.fileUrlToSystemPath(url)
14235857901fe35e6fba77d6f5466c9fa095188a
60,009
def get_query_matching_table(df_base, df_query, class_column='category', n_closest_matches=5, df_true_label="true_class", df_pred_label="pred_class_", df_query_label="category", df_query_id="id"): """ Yields a pandas dataframe in which each row contains the n_closest_matches as a result...
c702deefdb3f7330fb41055b51d3d3157cb236e6
60,011
def get_x(): """ Get current X keyboard setting CLI Example: .. code-block:: bash salt '*' keyboard.get_x """ cmd = "setxkbmap -query | grep layout" out = __salt__["cmd.run"](cmd, python_shell=True).split(":") return out[1].strip()
6fe8299273de514ef628a823ae70daf832b25667
60,012
def _called_with_cfg(*args, **kwargs): """ Returns: bool: whether the arguments contain CfgNode and should be considered forwarded to from_config. """ if len(args) and isinstance(args[0], _CfgNode): return True if isinstance(kwargs.pop("cfg", None), _CfgNode): re...
7626750f99504828330921ecae3613d0d03d0fc9
60,013
def are_content_experiments_enabled(course): """ Returns True if content experiments have been enabled for the course. """ return ( 'split_test' in ADVANCED_COMPONENT_TYPES and 'split_test' in course.advanced_modules )
04c0e13fd4456b3dda3b59c36568403ed448d42e
60,014
def experiment_fn(output_dir): """Creates an experiment using cnn for MNIST dataset classification task.""" plx.datasets.mnist.prepare('../data/mnist') config = './yaml_configs/conv_highway_mnist.yml' # or config = './json_configs/conv_highway_mnist.json' experiment_config = plx.configs.Experim...
1a4b811f37bc525da063bf96e496fd9117fa81b3
60,015
import scipy def normalize_graph(graph, normalized = True, add_self_loops = True): """Normalized the graph's adjacency matrix in the scipy sparse matrix format. Args: graph: A scipy sparse adjacency matrix of the input graph. normalized: If True, uses the norma...
82ac6df91e2f2247cdc941e34a84aa5619de0c7c
60,016
def create_block_static(page_type, node): """ Create a static block :param page_type: where this block will be rendered :param node: what this block will contain :return: the page layout element """ block, created = ContentBlock.objects.get_or_create(name='static-%s' % node.title, type='static',...
40d02eaebf729216fa5d04af559cef5f2669f22b
60,018
def constructObject(data): """Constructing an object""" whitelist = ["message"] if data[""] not in whitelist: return None try: classBase = getattr(getattr(messagetypes, data[""]), data[""].title()) except (NameError, AttributeError): logger.error("Don't know how to handle mes...
9133df35fc700bf052fa05aa108524e24f83499c
60,019
def valid_replay(info, ping): """Make sure the replay isn't corrupt, and is worth looking at.""" if (info.HasField("error") or info.base_build != ping.base_build or # different game version info.game_duration_loops < 1000 or len(info.player_info) != 2): # Probably corrupt, or just not interes...
e8fb8834c024f888abea50f8cf0123769a99e706
60,021
def mod(x, y): """Compute value of one parameter modulo another, element-wise. Args: x (:mod:`~taichi.types.primitive_types`, :class:`~taichi.Matrix`): The first input. y (:mod:`~taichi.types.primitive_types`, :class:`~taichi.Matrix`): The second input. Returns: the value of `x` mo...
11c97773a5c8be5363f10e3740dee51a5c773d8f
60,023
def view_tutorialvideoslist(request): """View function showing all the tutorial videos available available""" tutorialvideos = TutorialVideo.objects.all() context = { "tutorialvideos": tutorialvideos, } return render(request=request, context=context, template_name="dashboard/tutorialvideol...
6bf3cda5e62f2dd08e00515ee7a73aab7352b7b2
60,024
import scipy.optimize from padertorch.utils import to_numpy from pb_bss.permutation_alignment import _mapping_from_score_matrix def pit_loss_from_loss_matrix( pair_wise_loss_matrix, *, reduction='mean', algorithm: ['optimal', 'greedy'] = 'optimal', return_permutation=False, ): ...
f4f2353cfc31941c005ba6b194a97c2e4b88d21f
60,025
def series(request: HttpRequest, slug: str) -> JsonResponse: """ View that serves a single series as a JSON object. :param request: The original request. :param slug: The slug of the series. :return: A JSON-formatted response with the series. """ try: _series = Series.objects.get(s...
f299065f70d21241e0d56680457d31f201ebc67d
60,027
def create_choropleth(data, column, columns, key_on): """ Create Choropleth (see: https://python-visualization.github.io/folium/quickstart.html#Choropleth-maps) for passed dataset. Basically an overlay map displaying numerical values over geographic areas """ # potential quantiles to include ...
82326c209d6aad6096ec88a290a870009321e64c
60,029
def _align_mem_hla(fastq_file, pair_file, ref_file, out_file, names, rg_info, data): """Perform bwa-mem alignment on supported read lengths with HLA alignments """ with postalign.tobam_cl(data, out_file, pair_file != "") as (tobam_cl, tx_out_file): cmd = ("unset JAVA_HOME && " "%s | %s" ...
02faa832666c80472644c1315da586d1263df9c8
60,031
import operator def process_music(music): """Process a music and return the processed music.""" # Raise ValueError if no track is found if not music.tracks: raise ValueError("No track is found.") # Adjust resolution to 24 time steps per quarter note music.adjust_resolution(24) # Coll...
ec980dc4a008b904fa954d3e2d1ed3053ed1a741
60,032
def lpAddRestrictions2(problem: LpProblem, lhs, rhs, name, op='='): """ Add vector or matrix of restrictions to the problem :param problem: instance of LpProblem :param lhs: 1D array (left hand side) :param rhs: 1D or 2D array (right hand side) :param name: name of the restriction :param...
3f4a343800b1eb67b9fbd98c1703c46aab2c0a89
60,033
def get_batch(datasets, phase, reset): """Read batches from multiple datasets based on the training phase. The test dataset is reset at the beginning of every test phase. The training dataset is repeated infinitely and doesn't need a reset. Args: datasets: Dictionary of datasets with training phases as ...
09715fe850f3bfd5172931c45149649339f72e5c
60,034
def init_api(): """Initializes the twitter api.""" #REMEMBER TO REMOVE THESE BEFORE PUBLISHING! consumer_key = '9837qrKedgU22V9Xz9mHgw' consumer_secret = 'vsGk8T1J9UZwPsBkfgcMRWXSmw44a4mW9MmCPWXVzyc' access_token_key = '16007524-OyqJQMw2RHi8y1L8URIErrCKHfSYFZGdc5vImrZpf' access_token_secret = 'Y...
a3d3ca7675e5f5e627d1da48ba5bb93c7a8147f0
60,035
from typing import List import urllib import json def get_latest_versions( repo: str, number: int = 5, check_assets: bool = False ) -> List[dict]: """Get latest versions from a repository releases""" # build url url = f"https://api.github.com/repos/{repo}/releases" # download data data = urlli...
63dff91f06beee168755114961f86e6b735f55b3
60,036
def get_decoder_self_attention_bias(length): """ Calculate bias for decoder that maintains model's autoregressive property. Creates a tensor that masks out locations that correspond to illegal connections, so prediction at position i cannot draw information from future positions. :param length: length of se...
9d0288b6682d4774b56e3403ce23d0e64c7dae03
60,037
def lie_smoother(PopFrenetPath, Model): """ LieSmoother Smoothing by local averaging based on the geodesic distance in SO(p), i.e. we compute local Karcher mean. It can use the information on the curvature and torsion defined in Model for a better estimation. ... """ if isinstance(PopFrenet...
bfc754287b910a4c8abf14c728dd1ebed13ca1ef
60,038
def connect_sequential(graph: Graph): """ Connect sequential nodes to sequential graph. Args: graph (Graph) : """ # # Get node keys # node_keys_input, node_keys_hidden, node_keys_output = split_node_keys( graph.node_keys, ) # # Connect all input nodes to hi...
293eb23fc2282597301d7e935e6cea3425379643
60,039
def backward_energy(img): """ Simple gradient magnitude energy map. """ img = img.astype(np.float64) kernel_x = np.array([ [1.0, 0.0, -1.0], [2.0, 0.0, -2.0], [1.0, 0.0, -1.0], ]) kernel_y = np.array([ [1.0, 2.0, 1.0], [0.0, 0.0, 0.0], ...
082d010ad3afd6fc6f27eee523745e071ddda48b
60,041
import requests import logging def create_or_update(cluster, token_name, token_fields, admin_mode, action, fields_from_args_only, output): """Creates (or updates) the given token on the given cluster""" cluster_name = cluster['name'] cluster_url = cluster['url'] existing_token_data, existing_token_et...
fa3b2e9bd7f58a523475732fc716e1aebc8c5a2f
60,045
def _parse_due_date(part): """ Parse a part of text as a date, in either DD/MM/YYYY or YYYY/MM/DD format. """ # Strict DMY m = _DUE_DATE_DMY.match(part) if m: return reversed(m.groups()) # Partial (Y)MD m = _DUE_DATE_YMD.match(part) if m: return m.groups()
0e81a3df1949abaa9b1be100f0596ae2b71e5799
60,046
from typing import Tuple from typing import Iterable import types from typing import Optional import six def _make_dataset_feature_stats_proto( lifts: Tuple[_SlicedFeatureKey, Iterable[_LiftSeries]], y_path: types.FeaturePath, y_boundaries: Optional[np.ndarray], weighted_examples: bool, output_custom_stat...
b365dfafbc5e966fdae61bc15cb5e600852740fd
60,047
def get_from_url(url): """ Retrieve URL and return content """ try: return urllib2.urlopen(url).read() except: return None
3f0c883709856b7a292c846c5191f2c8aa2de4ae
60,048
def _shortcut(identity, residual, is_nin=False): """ 合并单位分支和残差分支的shortcut :param identity: shortcut的单位量分支 :param residual: shortcut的残差量分支 :param is_nin: 是否对单位量实施NIN操作 :return: 合并结果tensor """ identity_shape = keras.backend.int_shape(identity) residual_shape = keras.backend.int_shape(r...
f84d63c1d90d4b048230ba6a5a0342b90c011967
60,050
import math import collections def histogram_dist_column_to_pds(df, column, global_xmin_xmax, bar_width_fraction, column_properties=None, plot_individual=False, bin_width=1, individual_p...
6cd7ed3c56c9f6b0e80a06d65f8f938cd448c57f
60,051
def create_stats_filename(subject_line, email_time, ext='.xls'): """ Create a .xls filename from iScore email subject line. Returns None if filename already exists. :param str subject_line: subject line from iScore email :param str email_time: time string representing time in inbox :param str ...
74158b2f2e954b498330d5b3badbc4fa40722778
60,052
import typing def histc(labels: np.ndarray, bins: np.ndarray = None, return_bins: bool = False) -> typing.Tuple[np.ndarray, np.ndarray]: """MATLAB `histc` equivalent.""" labels = np.array(labels, dtype=int) if bins is None: bins = np.unique(labels) bins = np.array(bins, dty...
323adfe88b69e875fe4157acc0a353153543a478
60,054
def repl_escapechar(s): """xmlの制御文字をエスケープする。 s: エスケープ処理を行う文字列。 """ seq = (("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ('"', "&quot;"), ("'", "&apos;")) for old, new in seq: s = s.replace(old, new) return s
d4c8a13ba295e9f1ebee7627dc810d5626cff957
60,055
def _sharecard(slug): """ Flatfile sharecards, one per liveblog post. """ context = get_liveblog_context() for post in context['posts']: if slug == post['slug']: post_context = post post_context['PARENT_LIVEBLOG_URL'] = context['PARENT_LIVEBLOG_URL'] post_...
3d5348c7aa53be6fa5339c287d13f17191e098cc
60,056
def pl_detect(state_file): """ Assume there is a log.txt recording the audio packets receiving state at the decoder. Frame received marked as 1, and frame lost marked as 0. And the log.txt was named after the audio file name. """ with open(state_file, encoding='utf-8') as f: pl_state...
b87c2dc9d2a792d3b02685c65446ae653d28e2e5
60,057
def RDP_pureDP(params,alpha): """ This function generically converts pure DP to Renyi DP. It implements Lemma 1.4 of Bun et al.'s CDP paper. With an additional cap at eps. :param params: pure DP parameter :param alpha: The order of the Renyi Divergence :return:Evaluation of the RDP's epsilo...
d2d6f50f5e213dfafded036b9780d60d33fbb53f
60,058
def bins(*args, **kwargs): """Create binned data, i.e., a variable with elements that are bins. The elements of the returned variable are "bins", defined as views into `data`. The returned variable keeps and manages a copy of `data` internally. The variables `begin` and `end` must have the same di...
0a0661017c617c696f88c9807fd38cac6ca854f8
60,060
def class_extension(f): """ Transform a function into a class extension. This is the same as a type extension, however, it adds the function as a class method rather than an instance method. """ return extension(f, class_method=True)
7f0d922c0205c5f95fe6e4c8391b77947489aa45
60,061
def _from_soap(in_envelope_xml, xmlids=None, **kwargs): """Parses the xml string into the header and payload. """ ns_soap = kwargs.pop('ns', ns.soap11_env) if xmlids: resolve_hrefs(in_envelope_xml, xmlids) if in_envelope_xml.tag != '{%s}Envelope' % ns_soap: raise Fault('Client.Soap...
efa5a227cf9cabc6f8041aed610c5df4019bcdb8
60,062
from .algebra.onnx_operator_mixin import OnnxOperatorMixin from .algebra.type_helper import guess_initial_types def to_onnx(model, X=None, name=None, initial_types=None, target_opset=None, options=None, white_op=None, black_op=None, final_types=None, dtype=None, naming=None, verbos...
293281f10faa47db6cd22e16d933c4a3742bc13f
60,063
from typing import Dict from typing import Any def get_aws_account_information(app_id: str, api_key: str) -> Dict[str, Any]: """Retrieve aws account information from PythonDeploy.""" typer.echo("Requesting aws account information") return api_request(app_id, api_key, "aws_account")
ffc9e987d1a6aa8baf4fe24de5bcbdb54d52d12a
60,064
def isUSBLOG(filename): """ Checks whether a file is ASCII USB-Logger format. Supports temperture and humidity logger Extend that code for CO logger as well """ try: temp = open( filename, "r", newline='', encoding='utf-8', errors='ignore' ).readline() except: return False ...
38023ab4caf7cecd18f0f03ca89399acf64a90d6
60,065
from typing import Union def _dec(v: Union[LayerFieldsContainer, LayerField]) -> int: """parse the layer field as a decimal""" assert not isinstance(v, LayerFieldsContainer) or len(v.fields) == 1 return int(v.get_default_value())
5cc7a08b3471710bc12c8fc44e5f0663e128f18b
60,066
def calculate_bitmap_size_parameters(s): """ This function will calculate the parameters to be used for bitmap allocation, if we know what is the size we need to allocate, height=1, cBitsPerPel=8 @param s: size of the bitmap we need @return: (width, height, cBitsPerPel) tuple """ p = platform.platform() if p == ...
0fba2e7ab59975215274ce5ee7fddb5d43ae0cdf
60,070
from ..simplify import simplify def simplify_logic(expr, form=None, deep=True): """ This function simplifies a boolean function to its simplified version in SOP or POS form. The return type is an Or or And object in Diofant. Parameters ========== expr : string or boolean expression form ...
c0403bc79e44ba448a4019cec21fc24eef1c1550
60,071
def w_Create(net): """ Creates random weight vector of NN and defines sets needed for derivative calculation Args: net: neural network Returns: net: neural network """ M = net['M'] #number of layers layers = net['layers'] #NN structure delay = net['delay'] #time delays in Network Connections inputs = ...
b03e02bf168348ee1ce2dd613502aae178707600
60,072
def parse_drawing_level(drawing_level: t.DrawingLevelArg) -> str: """Parse drawing level into legal ANSI drawing level Sequence.""" if isinstance(drawing_level, int): try: drawing_level = list(ColorDrawingLevel)[drawing_level] except IndexError: raise KeyError( ...
48e9cb292c32e555f8c666be9c117fe73ded920c
60,073
import typing def require_plan( valid_plan_ids: typing.Iterable[str], subscription_retriever: typing.Callable[[Request], Subscription], ): """ Decorator to be used on view functions / methods that require a specific plan. Will result in 403 if resource requested is not part of an organisation tha...
bdbe0c98182ee13d0f00b0d35a95e1214c315560
60,074
def translate(dna, table=CODON_TABLE): """Translates DNA (with gaps) into amino-acids""" aa = [] assert len(dna) % 3 == 0, "dna sequence length is not a multiple of 3" for i in xrange(0, len(dna), 3): codon = dna[i:i+3].upper() if "N" in codon: aa.append("X") # unkown ...
f60c4d319714ecaecbae5eed24e27606dfa0d139
60,075
def apply_method(state, step): """Apply a method to the state. Here data is a dictionary containing all necessary information. """ method = get_method(step['method_name']) goal_id = ItemID(step['goal_id']) fact_ids = [ItemID(fact_id) for fact_id in step['fact_ids']] \ if 'fact_ids' in s...
a4770075c9cfca952e58f294ec24f1f2f3bcdfa7
60,077
def train_deep_sentiment(checkpoints_dir, train_dir, num_steps, model_name=None): """Fine tune the inception model, retraining the last layer. Parameters: dataset_dir: The directory containing the data. checkpoints_dir: The directory contained the pre-trained model. train_dir: The directory to save the trained...
5fdac7293e14b940a775a3366b5e8727021a31ef
60,078
def schedule_depthwise_conv2d_nhwc(outs): """Schedule for depthwise_conv2d_nhwc Parameters ---------- outs: Array of Tensor The computation graph description of depthwise_conv2d_nhwc in the format of an array of tensors. Returns ------- sch: Schedule The computat...
f9cebf7481cd2185875e987e79e5b8737a8eb66d
60,079
def run_from_graph_def( graph_def, input_name, output_name, input_tensor, dtype, batch_size=None, parallel_iterations=None, ): """Runs the GraphDef with `input_tensor` mapped to `input_name` and returns the tensor matching `output_name`. Args: graph_def: A GraphDef proto...
ccd3612a5cd55a4dd3d5c265a37457f5643bf54f
60,080
def get_text(root_node, tag_name): """ get the text from a node's children """ values = [] nodes = root_node.getElementsByTagName(tag_name) while len(nodes): node = nodes.pop(0) if node.nodeType == node.TEXT_NODE: values.append(node.data.strip()) elif node.has...
dc8a3d88d01308ca6df81a493742549c1298bec0
60,082
import torch import tqdm def eval_net(net, loader, device): """Evaluation without the densecrf with the dice coefficient""" net.eval() mask_type = torch.float32 if net.n_classes == 1 else torch.long n_val = len(loader) # the number of batch tot = 0 tot_precision = 0 tot_recall = 0 cou...
0bc47c6d27a07782730560f081a87ec4156535dd
60,083
def get_model_dirs(data_topdirs): """ Args: datadirs (list): top-level list of directories to search for model directories Returns (list): list of directories containing saved_models dir, file train_history.json, and possibly file test.json """ all_subdirs = [] for d...
f7a4bd160de763980c0097052e0c25cc490bb7f0
60,084
def build_vgg16_unet(input_shape): """ Input """ inputs = Input(input_shape) """ Pre-trained VGG16 Model """ vgg16 = VGG16(include_top=False, weights="imagenet", input_tensor=inputs) """ Encoder """ s1 = vgg16.get_layer("block1_conv2").output ## (512 x 512) s2 = vgg16.get_layer("bl...
616772894b9638c94551c9756d9c68aa0643307e
60,085
def check_set_object_type(type_str_list, **kwargs): """ Check if each string in type_str_list are corresponding to an actual object's name/alias, create [objects] ordered lists for: [[Function],[Data],[State],[Transition],[FunctionalElement],[Attribute], [FuncitonalInterface],[PhysicalElement],[Phys...
5c79a96a7fef1c84f6be30ac18518a1abfa10acb
60,088
import time def slow_down(func): """Sleep 1 second before calling the function""" @wraps(func) def wrapper_slow_down(*args, **kwargs): time.sleep(1) return func(*args, **kwargs) return wrapper_slow_down
089e68dd223440f67dd2a09b939759d9f0f10a28
60,089
import hmac import hashlib def calc_sig(payload, key=SECRET_KEY): """Calculate the signature of the payload.""" return 'sha1=' + hmac.new(key, payload, hashlib.sha1).hexdigest()
df85f87398597dc9b8141d03cf216ac4f2c5337a
60,090
def load_nearest_neighbour_data(filename): """ Read a nearest neighbour dataset of the format ID, Word :param filename: path to the csv file :returns: df with the above columns """ column_list = ['ID', 'Word'] data = pd.read_csv(filename, header=[0]) cols = sorted(list(...
3c3f20c9b36b74787bfd0a4a917eb296e2f7df6d
60,091
def connect(args): """ :param args: :return: :rtype pymongo.collection.Collection """ conn = MongoClient(host=args.host, port=args.port) return conn.get_database(args.database).get_collection(args.collection)
1e01974db7951b2501e15213755a070e737781d8
60,093
def phased_check(fam, v, gt_bases): """ take cases where only 1 parent is HET """ gt_type = fam['gt_type'] # need at least 1 het kid if 0 == ((gt_type[2] == 1) + (gt_type[3] == 1)): return 0 used = 0 for parent, (p1, p2) in [("dad", (0, 1)), ("mom", (1, 0))]: if gt_type[...
256f62b8fa0a648dc6f66a2a652594a4d4d69c3d
60,094
def load_latest_eog_model(): """ Load latest EOG model from disk. :return latest EOG model """ return _load_latest_model(EOG_MODEL_DIR)
d10545cb96a9c7f9ca90dedfa3b13da0e8ef34e5
60,095
import requests import json def graphql_multipart_request(body, headers, endpoint=GQL_DEFAULT_ENDPOINT): """Execute a multipart graphQL query with `body` provided on the `endpoint`. Parameters ---------- body : str payloads of graphQL query. headers : dict, optional headers added ...
a4e4311b916c2ca954e144f9a6a39f2af21dcf49
60,097
def _now(request, registry, settings): """Get the current time as :term:`UTC`. :py:func:`websauna.utils.time.now` function. Example: .. code-block: html+jinja <footer class="footer"> <div class="container-fluid"> <p class="copyright pull-right"> &copy; {{ now().ye...
d7dcce1b6eee0c8e8861773a5b3fc3c209a75d00
60,099
def prompt_aergo_keystore(): """Prompt user to input a new aergo private key. Returns: - name of the key - address of the key - path to keystore """ while 1: questions = [ { 'type': 'input', 'name': 'account_name', ...
4a30f53549b6faffa7097333dfcff92c28f9333d
60,100
def display_test_plot(): """ Display a test plot. Returns ------- plot_meta : plot_playground.common.d3_helper.PlotMeta An object that stores the metadata of the plot. """ df = pd.DataFrame(data=[{ 'date': '2017-11-03', 'apple': 100, 'orange': 140, }, { ...
60392d7be3470654c3b42a7876da8188df1f5b91
60,101
from typing import Optional import re def evaluate(value: str, env: Optional[dict] = None) -> any: """Parse a string containing one or multiple ``${{ }}`` blocks and ``eval`` the expressions. Simple strings are left unchanged: .. code-block:: python >>> from gada_compose import parser ...
58645568212a6ef815f47b8b52005e489ae86685
60,102
def extract_tables(sql): """Extract the table names from an SQL statment. Returns a list of (schema, table, alias) tuples """ parsed = sqlparse.parse(sql) if not parsed: return [] # INSERT statements must stop looking for tables at the sign of first # Punctuation. eg: INSERT INTO ...
61c94e037b93feb13355ee1feb79fdcd092214a2
60,103
from typing import Tuple def euler_angles_RX(theta: float) -> Tuple[float, float, float]: """ A tuple of angles which corresponds to a ZXZXZ-decomposed ``RX`` gate. :param theta: The angle parameter for the ``RX`` gate. :return: The corresponding Euler angles for that gate. """ return (np.pi ...
7a01b853c4296abc8649e3681d86775035c979f5
60,105
def lftx(yr): """ Function reads in NCEP Reanalysis Lifted Index Surface data Parameters ---------- yr : year as integer Returns ---------- lftx : array of lifted indices latitudel : array of latitudes longitudel : array of longitudes """ directory = '/volu...
dff8f245d4c9ff7ca61a823d0f8d536546920a04
60,106
import shutil def check_java() -> bool: """ Check if Java is installed on the system.""" return shutil.which('java') is not None
44c19db5c9b72c6904e01b09797009cd8f2079b0
60,107
def data_ref_type_str(dref_enum): """ Translate an ``enum DataRefTypes`` value into a string representation. """ if dref_enum == 0x9000: return 'unknown' elif dref_enum == 0x9001: return 'integer' elif dref_enum == 0x9002: return 'fp' else: return 'INVALID'
28f3c493c1f927e8286be5d00b695ecb399210c5
60,108
def stop_stream_json(): """Define a successful response to POST /api/v1/web/equipment/stop_stream.""" return {"code": 0, "msg": "Succeed."}
0d0cb028a343ea9ac19dc8c39f75e6cfff383e06
60,109
def four_point_transform_2D(image, src_pts, tgt_pts): """Apply 4 point transformation determined by `src_pts` and `tgt_pts` on 2-D image `image`. Args: image: 2-D tensor of shape [height, width], or 3-D tensor of shape [height, width, channels] src_pts: 2-D tensor of shape [4, 2] tg...
7b82c44b46d029cc6a8803dff720ac46d2de4946
60,110
import string def mcalpine_eflaw_index(text): """ A readability score defined by Rachel McAlpine See https://strainindex.wordpress.com/2009/04/30/mcalpine-eflaw-readability-score/ EFLAW index = (#tokens + #miniwords) / #sentences :param text: A string text without punctuation :return: McAlpi...
f645d8baa7156347d0fe7edfd09d792b6b39be34
60,111
from typing import Union def _get_latest_folder( gcs_folder: str, gcp: Box, credentials: Credentials = None ) -> Union[str, None]: """Returns the latest subfolder from a "folder" in GCP[^folders]. This function assumes the folders are named with `project-id/cbs/[v3|v4]/dataset-id/YYYYMMDD`, and that ...
f074155682219d48addcac2ceca7e6274c4841f2
60,112
def is_nonCW_in_extension(G): """ Returns True if G is 'non-CW in extension', otherwise it returns False. G: directed graph of type 'networkx.DiGraph' EXAMPLE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> G=nx.DiGraph() e_list = [(1,2),(0,1),(0,3),(3,1),(4,2),(4,0)] G.add_edges_fr...
eb5367ec271df6339c0efaf5ed972e650163326e
60,113
def six_word_trie_with_some_overlap(): """A trie with six words that will have some overlap.""" new_trie = TrieTree() new_trie.insert('cake') new_trie.insert('car') new_trie.insert('carpet') new_trie.insert('rats') new_trie.insert('ratchet') new_trie.insert('knife') return new_trie
c18c881dcc4a7fc7e4a2e4a1e46cbdf50371eb6b
60,114
def share_group_snapshot_create(context, values): """Create a share group snapshot from the values dictionary.""" return IMPL.share_group_snapshot_create(context, values)
3345a8442db619422618c9c9e63758faf720d17d
60,115
def int_beta(Beta, radial_step=1, threshold=0.1, regions=None): """Integrate beta over a range of Newton spheres. Parameters ---------- Beta : numpy array Newton spheres radial_step : int number of pixels per Newton sphere (default 1) threshold : float threshold for norm...
3fbf32719fdadd1dc7e18bb59e633ffbf47041f3
60,116
def runOCcmd_yaml(cmd, base_cmd='oc'): """ log commands through ocutil """ logger.info(base_cmd + " " + cmd) return ocutil.run_user_cmd_yaml(cmd, base_cmd=base_cmd, )
9690769c21f7e7933418244df112079d7fcb5180
60,118
def retry_if_buffer_error_or_retriable(exception): """Return True if BufferError or retriable KafkaError, False otherwise""" return ( isinstance(exception, KafkaException) and exception.args[0].retriable() or isinstance(exception, BufferError) )
8b016936cd6f03d432c006b01eed043d21fc07b5
60,119
def takewhile(pred, *args): """Produce a sequence with the same elements as the input sequence until pred returns false for some element; that element and all those following are discarded. The filter predicate is passed an element of the input sequence plus extra arguments, if provided. """ de...
74503e290b31d263964e532851a90a74d09f3568
60,120
def so3_to_quaternion(so3): """Converts an SO3 rotation matrix to a quaternion Args: so3: 3x3 rotation matrix Returns: numpy.ndarray: quaternion [w, x, y, z] Raises: ValueError: if so3 is not 3x3 """ if so3.shape != (3, 3): raise ValueError("SO3 matrix must be ...
d728e589f7996f2feadae907229226878491b43e
60,121
def geocode(ctx, where): """ Geocode an address. """ location = None user_data = yield ctx.bot.defer_from_thread(UserData.lookup_default, ctx.client, where) location = user_data.get("location") if where is None and location is None: return [] elif location is not None: ...
964002ff763b0f48f7e0679f850c88857e53d18b
60,122