content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Dict
from typing import Any
def marker_smoothing_exceptions(all_exceptions: Dict[str, Any], trial_name: str, marker_name: str) -> Dict[str, Any]:
"""Given all exceptions (all_exceptions) return just the ones for the specified marker (marker_name) and trial
(trial_name)."""
trial_excepti... | d6f33bd4f038f88de1e91e0446f4ee206549fbda | 677,446 |
import os
def full_path(path, ensure_exists=True):
"""
Makes path abolute. Can ensure exists.
"""
p = os.path.expandvars(path)
p = os.path.abspath(p)
if ensure_exists:
assert os.path.exists(p), 'path does not exist: ' + p
return p | 731c87fde97f2f88e55e8126a7ac4f23e19cd1b9 | 677,447 |
def core_display_list_fields():
"""
Return list of fields displayed in all change lists
"""
return ("id", "update_time", "update_user") | f3b54b86b93294bdd663a1ec144f4712f8db3837 | 677,448 |
def cid_fetch(pkg):
"""
gathers the cid pkg files
"""
offset_start = 48
offset_end = 84
fileread = open(pkg, 'rb')
fileread.seek(offset_start)
stuff = fileread.read(offset_end - offset_start)
return stuff.decode('utf-8') | 89b7de7aa534ae5ac1318536edc24bcaca0aef49 | 677,449 |
def clip_point(xmin, ymin, xmax, ymax, x, y):
"""Clips the point (i.e., determines if the point is in the clip
rectangle).
Parameters
----------
xmin, ymin, xmax, ymax, x, y : float
Returns
-------
bool
`True`, if the point is inside the clip rectangle; otherwise,
`Fals... | 382f2354ffeba0dcc0e437f91ae9d4ff511d6f4b | 677,450 |
def get_fixed_hyperparams(parser):
""" Hyperparameters that remain fixed across all experiments """
parser.add_argument('--pred_logvar_domain', type=bool, default=True)
parser.add_argument('--use_l2_sigma_reg', type=bool, default=True)
parser.add_argument('--dataset', type=str, default='imagenet_bboxes'... | 0cb5f67508a3bf2aa88c9af917ee850e6c8c6625 | 677,451 |
import argparse
def parse_args(arguments):
"""Arguments parser."""
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--human',
help='Print output in human readable format',
action='store_true',
default=False)
benchma... | 1ce9cd4b2ea211680a642c0b5d2e2426103eba8c | 677,452 |
from typing import List
def get_lower_from_list(upper_array_items: List[str]) -> List[str]:
"""
Convert a list/tuple objects to lower case character and return it.
"""
return list(map(lambda x: x.lower(), upper_array_items)) | fc9e7ec214454226433cc948bb8e455716b87226 | 677,453 |
def format_date(date):
"""Converts date to string in d. m. Y format."""
return date.strftime('%d. %m. %Y').lower() | c2eb9e0b2c80b64e8931a7f187a7afbefac82e1d | 677,454 |
def _cmpMessage( a, b ):
"""
used when sorting the messages
"""
if a._pri < b._pri: # lower value comes first
return -1
elif a._pri > b._pri:
return 1
else:
# equal priority
# if ._expires is None then long time in future so treat as greater than any other expiry.... | 991d1cb845e3add1d6dbce9ce877a9a9da3fdc8c | 677,455 |
def epsg_string_to_epsg(epsg_string: str) -> int:
"""From a string of the form 'EPSG:${code}' return
the epsg code as a integer
Raise a ValueError if the epsg_string cannot
be decoded
"""
epsg_string = epsg_string.lower()
epsg_string = epsg_string.strip()
epsg_string = epsg_string.replac... | ea556b4c3eca389d523c4c2473a730bdeaeabd8a | 677,456 |
def sl(c, s, l):
""" This accountancy function computes straight line
depreciation for an asset purchase for cash with
a known life span and salvage value.
c = historical cost or price paid (1000)
s = the expected salvage proceeds at disposal
l = expected useful life of the fixed asset
Ex... | 84577ac8d1ddb1a84794a2f786ebd0e91e1cc5f8 | 677,458 |
from sys import prefix
def build_url(url: str) -> str:
"""Attach API address to endpoint."""
if not url.startswith('http'):
url = prefix + url
return url | 04c5978482e8045c792ef61a8212bd2117367190 | 677,459 |
def split_target(frame, target):
"""
"""
if isinstance(target, str):
f = frame.drop(columns = target)
t = frame[target]
else:
f = frame.copy()
t = target
return f, t | b34e7cc89d0a208da7024cbdbd58deac7c0677dd | 677,461 |
import re
def natural_sort(iterable):
"""Sort an iterable by https://en.wikipedia.org/wiki/Natural_sort_order."""
def _convert(text):
return int(text) if text.isdigit() else text.lower()
def _alphanum_key(key):
return [_convert(c) for c in re.split("([0-9]+)", key)]
return sorted(it... | a3f3b52f1e84188d4859ad938a6c52292144fbab | 677,462 |
def add_caracteres(string, caractere, len_elem):
"""Add the element "catactere" at the begin of a string named "string" for
return a string which have "len_elem" caracteres"""
if len(string) < len_elem:
nb_elem = len_elem - len(string)
supplement = caractere * nb_elem
return suppleme... | 010e82aee9e40247813e140cde3ff3c63bd46cdc | 677,463 |
import os
def Tmust_exist(test_func):
"""Generic for an argparse type.
:param test_func: One of :func:`os.path.isdir`, :func:`os.path.isfile` or
:func:`os.path.ismount`.
"""
def must_exist(file_name):
if file_name:
file_name = os.path.abspath(file_name)
if... | cc6c56d46eacefe4f2fc37683ac645e1321ee756 | 677,464 |
import re
def countHashtag(text):
""" Input: a text, Output: how many hastags in front of a word """
return len(re.findall(r'#([^\s]+)', text)) | 762e026db8330a9e8c0775f1935a75a9a7316deb | 677,465 |
def readable(string):
"""return a human-readable version of a variable name"""
return string.replace('_', ' ').title() | 7d540ec88c628d5d766969c139de2f2b86a9ac28 | 677,466 |
def std_ver_major_uninst_valid_known(request):
"""Return a value that is a correctly formatted representation of a known major version number."""
return request.param | ad8c13807accd2836c19b325284caa7521f504dd | 677,467 |
def minimumDeletions(s: str) -> int:
"""Return minimum number of deletions to make 's' balanced, i.e.
no 'b' comes before 'a' in string consisting of just 'a's and 'b's."""
deletions = 0
countOfBs = 0
for c in s:
if c == 'a' and countOfBs > 0:
# Only need to delete 'b' if it co... | 1429cc444c0e5b0223d887fc1d2baf05e943e0d2 | 677,468 |
import os
def analyse_device_list_from_profiler_dir(profiler_dir):
"""
Analyse device list from profiler dir.
Args:
profiler_dir (str): The profiler data dir.
Returns:
list, the device_id list.
"""
profiler_file_prefix = ["timeline_display", "output_op_compute_time"]
gpu_... | 5da296cfbaa2202556e465e9fd0ddb7728f83107 | 677,469 |
import yaml
def repr_pairs(dump, tag, sequence, flow_style=None):
"""This is the same code as BaseRepresenter.represent_sequence(),
but the value passed to dump.represent_data() in the loop is a
dictionary instead of a tuple."""
value = []
node = yaml.SequenceNode(tag, value, flow_style=flow_styl... | 6fbd8dfa8e63b3bb066af5f3afddfc16a6801441 | 677,470 |
def template_dict(this_object):
"""Dump all of the properties for an object/variable.
This is generally more useful for frontend than template_dir because we
normally don't need access to the objects method's on the frontend and
makes the dump much smaller/quicker to scan through to find what you need
... | ae2ccafdfbdb7f4891ff00c2e6c16c19ff3831d8 | 677,471 |
def Luv_uv_to_xy(uv):
"""
Returns the *xy* chromaticity coordinates from given *CIE Luv* colourspace
*u"v"* chromaticity coordinates.
Parameters
----------
uv : array_like
*CIE Luv u"v"* chromaticity coordinates.
Returns
-------
tuple
*xy* chromaticity coordinates.
... | 3c032edd099d5d7f126bbdacc91f8013435f2bbd | 677,472 |
import copy
def dc(o):
"""
Some of the testing methods modify the datastructure you pass into them.
We want to deepcopy each structure so one test doesn't break another.
"""
return copy.deepcopy(o) | d0299776280e537855b8100f3f9f9761d9461212 | 677,473 |
import re
def cleantext(text):
"""
Custom function to clean enriched text
:param text(str): Enriched ytext from Ekstep Content.
:returns: Cleaned text.
"""
replace_char = [
"[",
"]",
"u'",
"None",
"Thank you",
"-",
"(",
")",
... | 7728ab5f2d2c4603789c8d2ad1a4a2c76a48b427 | 677,474 |
def format_float(value, rounding=2):
"""default formatting operation for establishing a consistent
representation of floating point and numeric values returned by API."""
return float("{:.{}f}".format(round(float(value), rounding), rounding)) | a547de187da2fd948f082430229154295f340329 | 677,475 |
def lastMoment(name):
"""
Method to return the last moment
Parameters
---------
name : str
name of the file.
Returns
-------
The last time of the plot.
"""
f=open(name,"r")
return(f.readlines()[-1].split(" ")[0]) | bc5020173f54aa84d93973224332a3d77fccdc83 | 677,476 |
def get_after(end_cursor):
""" Get the "after" portion of the pagination query
"""
return 'after: "{}", '.format(end_cursor) if end_cursor else "" | bac11ec8b3faefed5fb29e041f825db49e3cc36c | 677,477 |
def _and(queries):
"""
Returns a query item matching the "and" of all query items.
Args:
queries (List[str]): A list of query terms to and.
Returns:
The query string.
"""
if len(queries) == 1:
return queries[0]
return f"({' '.join(queries)})" | 4a2ba5f3812055b76a75b71ccad06c1fbc492618 | 677,478 |
def multiagent_rollout(env, policy_right, policy_left, render_mode=False):
"""
play one agent vs the other in modified gym-style loop.
important: returns the score from perspective of policy_right.
"""
obs_right = env.reset()
obs_left = obs_right # same observation at the very beginning for the other agent
... | 48541de2502be07e05aa15e80e84d5ab23e089a8 | 677,480 |
def proto_check(proto):
"""Checks if protocol is TCP or UDP
Parameters
----------
proto: int
The protocol number in the FCN/CN message
Returns
-------
The protocol name if TCP/UDP else returns nothing
"""
# Check for TCP
if proto == 6:
return 'tcp'
# Ch... | 118f37249bdfa405ca09846b66c315e8866005ba | 677,481 |
def common_replacements(setting, item):
"""Maps keys to values from setting and item for replacing string
templates.
"""
return {"$name": setting.lower(),
"$setting": setting,
"$prettyname": item.py_name,
"$doc_str": item.doc_str} | 618e0f9f90822455cebdf48c5cfafd913f193214 | 677,483 |
def loadStopWords(filename) :
"""
loads a Set of stopwords from a standard file
input :
file path containing stop words (format expected is one word per line)
return :
lines : a set of words
"""
lines = []
with open(filename,"r") as fileHandle:
for line in fileHandle.readlines() :
line... | 8323557ee2be73017bdc3c853c3cf6e5ccad2055 | 677,484 |
import pkg_resources
def get_resource_bytes(path):
"""
Helper method to get the unicode contents of a resource in this repo.
Args:
path (str): The path of the resource
Returns:
unicode: The unicode contents of the resource at the given path
"""
resource_contents = pkg_resourc... | e3ccfa4e2e5d040cc06bad3e042093456e923c58 | 677,486 |
import math
def batExposure(theta, phi):
"""
Given theta,phi in radians, returns (open_coded_area_in_cm^2, cosfactor)
theta = distance from center of FOV (boresight) in radians
phi = angle around boresight in radians.
This is moderate accuracy, but does not take into account, e.g. dead detectors.... | 32607e7ef58d93fad220d914b0a3c7e7c1363043 | 677,487 |
import re
def CheckHTTPUrl(url: str) -> bool:
"""
URLのチェックをする
"""
regex = r'https?://[\w/:%#\$&\?\(\)~\.=\+\-]+'
if (re.search(regex, url)):
return True
else:
return False | 5fd49aaa4d60dc19f91e8dd917eeda0de04cca48 | 677,488 |
def first_match(predicate, list):
"""
returns the first value of predicate applied to list, which
does not return None
>>>
>>> def return_if_even(x):
... if x % 2 is 0:
... return x
... return None
>>>
>>> first_match(return_if_even, [1, 3, 4, 7])
4
... | 859ac7fde416c94cb2cddaf815b76eb59da9654f | 677,489 |
import os
def get_platform_path(lang, component, platform):
"""Get the platform translation path."""
if os.path.isdir(os.path.join("homeassistant", "components", component, platform)):
return os.path.join(
"homeassistant",
"components",
component,
platfo... | fa4a1bf693b070954de24b731aa05aa4a7c4bc21 | 677,490 |
def convert_to_seconds(input_str):
"""Converts a string describing a length of time to its length in seconds."""
hours = {"h", "hr", "hour", "hours"}
minutes = {"m", "min", "minute", "minutes"}
seconds = {"s", "sec", "second", "seconds"}
value, unit = input_str.split()
if unit[-1] == "s" and len... | 0d5772b8d68f6a7ba150a1765f66dd62abdf7512 | 677,491 |
def split_data(msg, expected_fields):
"""
Helper method. gets a string and number of expected fields in it. Splits the string
using protocol's data field delimiter (|#) and validates that there are correct number of fields.
Returns: list of fields if all ok. If some error occured, returns None
"""
count=0
List=... | 3f81c7aa6eb2ec210a64c56be325b41f5f8c51ec | 677,493 |
def load_synapses_tsv_data(tsv_path):
"""Load synapse data from tsv.
Args:
tsv_path (str): path to the tsv synapses data file
Returns:
list of dicts containing each data for one synapse
"""
synapses = []
with open(tsv_path, "r", encoding="utf-8") as f:
# first line is d... | 097c6f591b6e68e3bd99f53a41a22b89d565e612 | 677,494 |
import torch
def softplus(x):
"""Alias for torch.nn.functional.softplus"""
return torch.nn.functional.softplus(x) | 24d431b5a8965dc382dda846b474c91422b9b48c | 677,495 |
import time
def epoch(dttm):
"""Returns an epoch-type date (tuple with no timezone)"""
return (int(time.mktime(dttm.timetuple())) * 1000,) | 99babced4229ff2637e4075f7850ce32c410f098 | 677,496 |
def _index_name(self, name):
"""
Generate the name of the object in which to store index records
:param name: The name of the table
:type name: str
:return: A string representation of the full table name
:rtype: str
"""
return '_{}_{}'.format(self._name, name) | 261fb302a10a56e60a58a4a1d6749d8502e45d6c | 677,497 |
from typing import OrderedDict
import torch
def transfer_data_to_numpy(data_map: dict) -> dict:
""" Transfer tensors in data_map to numpy type.
Will recursively walk through inner list, tuple and dict values.
Args:
data_map (dict): a dictionary which contains tensors to be transferred
Return... | 772310153c8e4b84c3c5b3884dcb2d2d2ebc5666 | 677,498 |
import os
def get_xnat_catalog(data_path, subject):
"""
For a given subject, finds and returns all of the xml files as full
paths. In almost all cases, this will be a single catalog.
THIS IS BROKEN.
"""
dicoms = os.listdir(os.path.join(data_path, 'dicom'))
subjects = filter(lambda x: sub... | ac508b5e15d440e26c039ad9fa264b5b30881eb0 | 677,499 |
def _cost_enumerative(u, prm, fol):
"""Compute cost of cover `u` by enumerating it."""
if u is None:
return float('inf')
eq = prm.eq
cover = list()
params = prm.p_vars
for p in fol.pick_iter(u, params):
# equal to existing ?
r = fol.false
for w in cover:
... | 52bcc3f2bcdbb65b5bd8b640ab27f2710d017c45 | 677,500 |
from re import VERBOSE
import requests
def post_req(url, data, credentials):
"""
INPUT: an API endpoint for posting data
OUTPUT: the request object containing the posted data response for successful requests. If a request fails, False is returned.
"""
if VERBOSE:
print("POSTING: " + url)
... | e3a9094ccd131ea81ef5542f622b2067a0fda045 | 677,502 |
from typing import Dict
from typing import Any
def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float:
"""
Computes intensity of a transform that consists of temporal cropping or
padding. For these types of transforms the intensity is defined as the
percentage of video time that has ... | 4eb0f07699f8199959bf870757fe769915f0d4ae | 677,503 |
import os
import subprocess
def grab_mac_marketing_name():
"""
Returns a string telling you you the macOS marketing name of the device your running on.
Ex: "MacBook Pro (15-inch, 2018)"
"""
script_path = os.path.join(os.path.dirname(__file__), "resources", "get_market_name.sh")
return subproce... | f82cbeb08c8dfd75cf24b29584ca37977d9c00b9 | 677,504 |
def locality(values, locdef):
"""
"""
length = locdef[0]
repeat = locdef[1]
if repeat <= 1:
return values
values = [
values[i:i + length] * repeat
for i in range(0, len(values), length)
]
values = [item for sublist in values for item in sublist]
return valu... | a12ccf9418a5f28c04cf7fd4e979b0195e817342 | 677,505 |
import pickle
def load_pickle(filepath_to_load):
"""Load pickle file"""
with open(filepath_to_load, "rb") as inp:
return pickle.load(inp) | 3635b9d58919f9a43bd53bb0145e297baa831ed1 | 677,506 |
def imprint(oEditor, blanklist, toollist, KeepOriginals=False):
"""
Imprint an object onto another object.
Note: This function is undocumented in the HFSS Scripting Guide.
"""
imprintselectionsarray = [ "NAME:Selections",
"Blank Parts:=", ','.join(blanklist),
... | 4b922c67ac586523b1aad8e9721042f7aa29bcc7 | 677,507 |
import json
import torch
def get_features_from_commonsenseQA(data_path, tokenizer, max_seq_length, choices_num=5):
"""
从 commonsenseQA 中获取数据,做 choices_num 分类问题所需数据
:param tokenizer:
:param max_seq_length:
:param choices_num: 返回的每条数据中包含的选项个数,默认全选,有五条,要大于等于 1,暂未作判断
:return:
"""
features ... | 51716f3f45dacdc3ce3577cfa7f96d6c32a1767a | 677,508 |
def _flattenText(elem):
"""
Returns the text in an element and all child elements, with the tags
removed.
"""
text = ""
if elem.text is not None:
text = elem.text
for ch in elem:
text += _flattenText(ch)
if ch.tail is not None:
text += ch.tail
return t... | aa47128b2f447c8471919abff0f07b6d3c06201b | 677,509 |
import math
def distance(x1, y1, x2, y2, x0, y0):
"""Calculate distance from a point x0, y0 to a line defined by x1, y1 and x2, y2"""
num = (y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1
den = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
return float(num) / float(den) | a692033b29350d666eb251f6f7d0447bc9a94d26 | 677,510 |
def parse_copy_availability(line):
"""Parses 'Status-'line for availability.
:param line: Line string.
:type line: str
:return: Availability.
:rtype: bool
"""
if 'Entliehen' in line:
return False
elif 'Verfügbar' in line:
return True
else:
return False | c027bc6ee9f3a33c18f4eece47fa9e409354ba8d | 677,511 |
def get_label(dataset):
"""打标
领券后15天之内使用为1,否则为0,新增一列“label”表示该信息
Args:
dataset:
Return:
打标后的DataFrame
"""
data = dataset.copy()
data['label'] = list(map(lambda x, y: 1 if (x-y).total_seconds()/(60*60*24) <= 15 else 0, data['date'], data['date_received']))
return data | 9c5ddba1af979d94160a5157a84d1fe7d5fb0638 | 677,512 |
def _get_location_extension_feeds(client, customer_id):
"""Gets the location extension feeds.
Args:
client: The Google Ads API client.
customer_id: The Google Ads customer ID.
Returns:
The list of location extension feeds.
"""
googleads_service = client.get_service("GoogleAd... | 437b1aa086f5fbac532dfb1d9efb3d3593c772b0 | 677,513 |
def find_node_by_name(node_host_name, swis):
"""
This function allows you to find a node based on it's name.
"""
results = swis.query("SELECT NodeID, IPAddress, DisplayName FROM Orion.Nodes WHERE DisplayName = '" + node_host_name.strip() + "'")
return results['results'] | 1f97270ed3d2fbf5879e5f23ebada26ef95b8686 | 677,514 |
def count_key_not_in_trg_doc(trg_src_dict):
"""
统计 关键词不在其标记的所有文档中出现
"""
absent_key = []
max_len_posts = -1
key_posts_num_b10 = 0
for key, posts in trg_src_dict.items():
all_docs = " ".join(posts)
if key not in all_docs:
# print(key + '\t' + str(len(posts)))
... | 7fa655ec489588556e8d1b88882da77342248d39 | 677,515 |
def get_fastq_stats(fastq_filehandle):
"""Return some basic statistics for a fastq file."""
read_count, gc_count, total_base_count = 0, 0, 0
for i, line in enumerate(fastq_filehandle):
if i != 1: # only process the reads from the fastq
continue
read_count += 1
for base i... | b4fc34668d7d2842617e035a059798888d3d8640 | 677,517 |
def filter_rule_ids(all_keys, queries):
"""
From a set of queries (a comma separated list of queries, where a query is either a
rule id or a substring thereof), return the set of matching keys from all_keys. When
queries is the literal string "all", return all of the keys.
"""
if not queries:
... | daf5a40754c34342d0707c2334be2ad9de0444e0 | 677,518 |
import numpy
def delta(feat, N):
"""Compute delta features from a feature vector sequence.
:param feat: A numpy array of size (NUMFRAMES by number of features) containing features. Each row holds 1 feature vector.
:param N: For each frame, calculate delta features based on preceding and following N frames... | a353e91ec8c29e0cd5573621faa625c29ab7f186 | 677,519 |
def is_quoted_retweet(text):
"""
Determines if the text begins with a quoted retweet
:param text: The text to analyze (str)
:return: true | false
"""
return int(text[:2] == '"@') | 0b1f73f35cf31b369147ff8995a72214702aaefe | 677,521 |
import re
def lower_intradocument_links(rst):
"""Lowercase intra-document links
Reference names are converted to lowercase when HTML is rendered
from reST (https://bit.ly/2yXRPzL). Intra-document links must be
lowercased in order to preserve linkage.
`The Link <#Target-No.1>`__ -> `The Link <#ta... | c58e785a07b8adb4a2793f8d061146f001a690b8 | 677,522 |
def mean_average(list_of_numbers):
"""Return the mean average of a list of numbers."""
return sum(list_of_numbers) / len(list_of_numbers) | 92b587cac365cdc9c34ca9a03e28d5d0a7adf4e2 | 677,523 |
import os
def _get_log_type(log_type=None):
"""
This functions gets the New Relic logtype from env vars.
"""
if log_type:
return log_type
return os.getenv("LOG_TYPE", "") | 3108f9c4a6ffb43bb479a6efd44820617e0905a0 | 677,524 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
parser.add_argument('-sd', '--save-dir', type=str,
default='', help='where you save checkpoint')
parser.add_argument('-re', '--resume', type=str,
default='', hel... | e6823993def464591da676f59bc60223dcdb9688 | 677,525 |
import pathlib
import json
def read_lipids_topH(filenames):
"""Generate a list of lipid hydrogen topologies.
This function read a list of json files containing
the topology of a united-atom lipid for reconstructing
the missing hydrogens.
The list topologies is stored as dictionary were the key i... | 26d7214730dc8b1164af1f2bcafcb3e94104683a | 677,527 |
import pkg_resources
import warnings
def find_parser(filename):
"""Find the correct parser by iterating entry_points."""
for ep in pkg_resources.iter_entry_points(group='uniplot.parsers'):
try:
parser = ep.load()(filename)
except ImportError:
# this parser couldn't be i... | 50b85eae268ba0784774a9cfbc21c0780daab63e | 677,528 |
def perform_mask(df, dup_column, drug_word_col, treatment_word_col, replace_labels):
"""
Masks certain words to follow GAD training format.
"""
df[dup_column] = df.map(lambda x: x[dup_column].replace(drug_word_col, replace_labels[0]))
df[dup_column] = df.map(lambda x: x[dup_column].replace(treatment... | 025daf32fc97f7daf32c07e6f36097e191d06fe2 | 677,529 |
def stringify_steamids(list_of_steamids):
"""
Args:
list_of_steamids: list of steamids
Returns:
Single string with steamids separated by comma
"""
return ','.join(list(map(str, list_of_steamids))) | 280866a64db270cbec82db1301fc579dc5be631c | 677,530 |
def ascii_line(chunk):
"""Create ASCII string from bytes in chunk"""
return ''.join([
chr(d) if 32 <= d < 127 else '.'
for d in chunk]) | 96b0196e11b2ee79c0772973fe06dff705514c17 | 677,531 |
import numpy
import numbers
import six
def conv_to_fortran(val, quote_strings=True):
"""
:param val: the value to be read and converted to a Fortran-friendly string.
"""
# Note that bool should come before integer, because a boolean matches also
# isinstance(...,int)
if isinstance(val, (bool,... | 9e9b5d66a480ddb41a6a101f97eaae1ec539e96f | 677,532 |
def mul(var1, var2):
"""
Wrapper function for __mul__ and __rmul__
"""
return var1 * var2 | 257bf665db7542cfe071ecbde169bf0039e52f6a | 677,533 |
from typing import OrderedDict
def create_epoch_dict(epochs):
""" Creates an ordered dictionary of epoch keys and a list of lists,
where the first list is the average flux of the bin, and second list
the CTE loss slope.
Parameters:
epochs : list of ints/floats
Returns:
... | 7492f5b2a1a9f0752106424c837a6e363563e944 | 677,534 |
def load_list_room_items(data, room_names):
"""
Loading each room respective list of items.
Parameters:
data(dict): Nested dictionaries containing
all information of the game.
room_names(list): List containg room names.
Returns:
items_list(list): Returns list of roo... | 728c5903945cc992ed06505c60554557875aed8f | 677,536 |
import ast
def literal_eval_lc(lc_string: str) -> list:
"""Convert a string to a list comprehension.
Parameters
----------
lc_string : str
String encapsulation of list comprehension.
Returns
-------
evaluated_lc : list
The evaluated expression of the list comprehension.
... | a5854e4dad1d70409c2810b11e8504ecadbec47a | 677,537 |
def fix_shifted_columns(df_raw, how):
"""
For a few rows, somehow the readout is broken such that the values
of 8 columns are missing. Unfortunately, the missing data is not
filled with nans, but replaced with the next valid readout,
causing the table to be shifted for those broken rows. The problem... | 6137bd1abf77244748a1acc670b89123638cdc4c | 677,538 |
def convert_to_nvc(vertices, faces):
"""Convert into format expected by CUDA kernel.
Nb of triangles x 3 (vertices) x 3 (xyz-coordinate/vertex)
WARNING: Will destroy any resemblance of UVs
Args:
vertices (torch.Tensor): tensor of all vertices
faces (torch.Tensor): tensor of all tri... | 090f894259f680cf4d4f277c097896b71d677b5a | 677,539 |
def update_docstring_references(obj, ref="ref"):
"""
Updates docstring reference names to strings including the function name.
Decorator will return the same function with a modified docstring. Sphinx
likes unique names - specifically for citations, not so much for footnotes.
Parameters
-------... | 78a109838573d5dc42027da8a8998ff107b8ed2a | 677,540 |
def is_dataclass_type(cls):
"""Returns whether cls is a dataclass."""
return isinstance(cls, type) and hasattr(cls, "__dataclass_fields__") | 7a354b54198e8873cbafd184c1611f99958e69c4 | 677,541 |
import sys
import os
def find_original_file(duplicate_hash_to_names, folder_to_check):
"""Find the original file from which the others duplicates are copied."""
original_files = {}
for file_names in duplicate_hash_to_names.values():
min_mtime = sys.maxsize
file_name_min = None
for... | 8bbcfafb80e34336141e8abf12cccd082e81c0d4 | 677,542 |
def validate_options(options, option_name, option_value):
"""
This function will filter validated options
and sets flag to use in sql template if there are any
valid options
Args:
options: List of options
option_name: Option Name
option_value: Option Value
Returns:
... | 5f12f401b30fc8d0f3f727a966bdb21ffc148beb | 677,543 |
import torch
def get_p_star(samples, y, beta):
"""Get the values for the p_star distribution
Parameters:
samples: tensor of dim (batch_size x num_samples) with the samples indexes
y: tensor of dim (batch_size) with the true label for each example
beta: the strength of the feedback
Returns:
... | e48bd9fdc8369122880ed428c4fafd0fa5429238 | 677,545 |
import pickle
def _encode(o):
"""Encodes an object with cPickle"""
return pickle.dumps(o, pickle.HIGHEST_PROTOCOL) | 895a273bccd0a0aaa8715679462d958ad9238268 | 677,546 |
def geturl(sub_url):
"""Returns the suburl"""
return "" + sub_url | da219d0d1fa26e321628e04d639699dd1088edf8 | 677,547 |
import struct
import os
def oid_generated_on_client(oid):
"""Is this process's PID in this ObjectId?"""
pid_from_doc = struct.unpack(">H", oid.binary[7:9])[0]
return (os.getpid() % 0xFFFF) == pid_from_doc | 08470680c9e211fbca7a5fb913f1cbe01fd574a5 | 677,548 |
def hsi_linecolors():
"""
Define discrete colors to use for RHESSI plots.
Returns
-------
`tuple` :
A tuple of names of colours.
References
----------
`hsi_linecolors.pro <https://hesperia.gsfc.nasa.gov/ssw/hessi/idl/gen/hsi_linecolors.pro>`__
"""
return ('black', 'mag... | f76adbe6ba2453c5c0a1a98d117e2410c0346230 | 677,549 |
def get_signal_frame(l4e_data_frame, model_name):
"""
Converts a dataframe from an L4E style to a Seeq signal style
PARAMS
======
l4e_data_frame: pandas.DataFrame (Required)
A dataframe returned from lookout_equipment_utils.get_predictions_data_frame()
model_nam... | 8ee4137832886b61d2dfc71839bb4a35fdc93f11 | 677,550 |
from typing import Iterable
from typing import List
from typing import Optional
def sorted_dedup(iterable: Iterable) -> List[Optional[int]]:
"""Sorted deduplication without removing the
possibly duplicated `None` values."""
dedup: List[Optional[int]] = []
visited = set()
for item in iterable:
... | b7b5424157bccb764c3db03fadf4ca88e6c50b02 | 677,551 |
def xor(a, b):
"""Return the XOR of two byte sequences. The length of the result is the length of the shortest."""
return bytes(x ^ y for (x, y) in zip(a, b)) | a4d41e4d871244a588246f554515b9115ad60b11 | 677,553 |
import uuid
def create_api_release(
client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None):
"""Creates a new Release for the API."""
if release_id is None:
release_id = uuid.uuid4().hex
api_id1 = "/apis/" + api_id + ";rev=" + api_revi... | a9b2490ca857712b2b8e4be36e76cc7dba9fbc99 | 677,554 |
import inspect
def list_classes_from_module(module, parent_class=None):
"""
Parse user defined module to get all model service classes in it.
:param module:
:param parent_class:
:return: List of model service class definitions
"""
# Parsing the module to get all defined classes
classe... | 390c0d2371b020ab3846fac2a69513f2a89ac106 | 677,556 |
def cli_parse(parser):
"""Add method specific options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument('-M', '--M', type=int, required=False,
default=4,
h... | bbc02f2031e71b2bdf06f6c4f29994b1f9fd6c6a | 677,557 |
def readme_contents_section_exists(path: str) -> bool:
"""
Given a README.md path, checks to see if there is a Contents section
"""
try:
with open(path, 'r') as f:
return '## Contents' in f.read()
except FileNotFoundError:
return False | 7353613b5e74f3343c8214073b00919a32a692b0 | 677,558 |
import math
def is_power_of_n(num:int,n :int) ->bool:
"""
Check whether a number is a power of n.
Parameters:
num: the number to be checked
n: the number those power num is checked
Returns:
True if number is a power of n, otherwise False
"""
if num <= 0:
ra... | da60f68e1f211df052e5df2b7ee60adb61d66c5c | 677,559 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.