content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def replace_all_blank(value):
"""
去除value中的所有非字母内容,包括标点符号、空格、换行、下划线等
:param value: 需要处理的内容
:return: 返回处理后的内容
"""
# \W 表示匹配非数字字母下划线
result = re.sub('\W+', '', value).replace("_", '')
return result | 25913693258a06bf4787eabc6ac83fc1277ccd3d | 586,532 |
import re
def find_clades_by_name(tree, terminal=True, contains=[], contains_all=False,
pattern=None):
"""Find clades by their name and whether or not they are terminal clades.
Parameters
----------
terminal : bool
If True, only the terminal nodes of the `tree` are sea... | 66cf7e92502eaa6ba21d49a1741cc1759a5536a7 | 586,534 |
def count_bytes_in_file(filepath):
"""Count the number of bytes in a file
To do so: open the file in read and binary mode, read the content in memory
and return the length of the resulting bytes string.
Note that there are more efficient ways to do this but this is just to
illustrate that you can ... | a9fc21582c7f616868324e65851b0eb3c70a0cb8 | 586,539 |
import time
def run_with_backoff(func, runtime=60, min_backoff=1, max_backoff=10,
expontential_backoff=True, stop_on_success=False, **kwargs):
"""Long-running function to process multiple windows.
Does not catch errors.
Args:
func: The callable to run. Any null response indicates that t... | ca405ba2f0ad1cb55d7cd71ef0a51ace03b05231 | 586,543 |
from typing import Union
from pathlib import Path
import hashlib
def md5sum(file: Union[str, Path]) -> str:
"""
Compute the md5sum of a string, a text file, or a binary file.
"""
if isinstance(file, str):
return hashlib.md5(file.encode()).hexdigest()
try:
with open(file) as f:
... | 4d951d9c61a65fd5ffec307e8a6586fa97a92117 | 586,546 |
def format_query_output(item):
"""Converts an item of a puppet query to tuple(hostname, query_value)."""
return item['certname'].split('.')[0], item.get('value') | 02f437fd8769eb3301a1fc99fff61f467f455e82 | 586,553 |
import math
def Log(t):
"""Computes the log of a sequence."""
return [math.log(x) for x in t] | 8afa7594a90ac5e8a2c7107dd96e7c558b8d24c9 | 586,555 |
import inspect
def _is_internal(obj):
"""Check if the module of the object is a falcon module."""
module = inspect.getmodule(obj)
if module:
return module.__name__.startswith('falcon.')
return False | e1e44b632282cedc89ae5202d7c0342c1994130a | 586,556 |
import torch
def center_to_corners_format(x):
"""
Converts a PyTorch tensor of bounding boxes of center format (center_x, center_y, width, height) to corners format
(x_0, y_0, x_1, y_1).
"""
x_c, y_c, w, h = x.unbind(-1)
b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
... | 61fd89bd14ad3759a65624c8c52b88a066185d2c | 586,560 |
def _options_choose_characters(player):
"""Return the options for choosing a character.
The first options must be the characters name (5 are allowed
by player). The other nodes must be reached through letters:
C to create, D to delete.
"""
options = list()
characters = player.db._playable... | d72c08bf9a2cb7ebfc7d4e6d13a94e1189d0d2f9 | 586,561 |
def parse_concepts(api_concepts):
"""Parse the API concepts data."""
return {concept['name']: round(100.0*concept['value'], 2)
for concept in api_concepts} | b56713f54dd276bbbf08422027a0c1126b1b5f35 | 586,563 |
import pickle
def load_object(filename):
"""Load object from file."""
with open(filename, 'rb') as input:
obj = pickle.load(input)
return obj | dc855a703d8f5bdebe2f3dbf6dda52e428e4f858 | 586,565 |
def parser_tuple(string):
"""
Returns a pair of string from a string of comma separate elements.
:param string: str
:return: pair
"""
string = string.replace("(", "")
string = string.replace(")", "")
strings = string.split(",")
return int(strings[0]), int(strings[1]) | 39e68ebe9dbccbe35cc1a0221c35122e38b10819 | 586,566 |
import traceback
def commit_changes(session, raise_exception=False):
"""
Attempts to commit changes to DB
- if it fails, error is logged and DB is rolled back
Args:
session (sqlalchemy.Session): session connected to DB
Kargs:
raise_exception (bool): if False, returns False instead of
... | e08384019143e8bc9e1312f120c1470596b81873 | 586,568 |
def get_parameters(current, puzzle_input, opcode):
"""extracts the parameters from the input and updates the current location
"""
if opcode == '03' or opcode == '04':
params = [puzzle_input[current]]
current += 1
elif opcode == '05' or opcode == '06':
params = [puzzle_input[curre... | 3c3a7da5e93d10608b09ef29ad6622118a8f0ff5 | 586,569 |
def _get_node_colors(nodes, path, colors):
"""For each node, assign color based on membership in path."""
node_colors = []
for x in nodes:
if x in path:
node_colors.append(colors['active'])
else:
node_colors.append(colors['inactive_node'])
return node_colors | 5747a869ef1259deb1fcc480619943e9694109c8 | 586,570 |
import warnings
def esmf_apply_weights(weights, indata, shape_in, shape_out):
"""
Apply regridding weights to data.
Parameters
----------
A : scipy sparse COO matrix
indata : numpy array of shape ``(..., n_lat, n_lon)`` or ``(..., n_y, n_x)``.
Should be C-ordered. Will be then tranpose... | 7a64830a04481b4c384bc6fd5edc8c5fdc441bc7 | 586,571 |
def topological_sort(graph):
"""Topological sort algorithm to return a list of keys to a dictionary
of lists of dependencies. The returned keys define an order so
that all dependent items are in front of the originating item.
"""
def recurse(node, path):
if node not in path:
ed... | 1343fac9667097fe16669b3acb2d4673b05ab80d | 586,572 |
def extension(filename):
""" returns the extension when given a filename
will return None if there is no extension
>>> extension('foo.bar')
'bar'
>>> extension('foo')
None
"""
s = filename.split('.')
if len(s) > 1:
return s[-1]
else:
return None | 5634effc420299a66dd71985eb49cbbf98714622 | 586,575 |
def valid_uris(uris: set, uri_type: str = 'track') -> bool:
"""Checks if given uris are valid. In this case, valid means
each uri is of the form: f"spotify:{uri_type}:{id_string}".
Args:
uris (set): Set of uris that the user would like to check
for validity.
uri_type (str): ... | d7d738dc7940ce2e14071a03d07b46582ef970cd | 586,577 |
def buildUpdateFields(params):
"""Join fields and values for SQL update statement
"""
return ",".join(['%s = "%s"' % (k, v) for k, v in list(params.items())]) | 0614f1eb017f2db58f095d9e7aea2d7a8982786e | 586,578 |
def from_pt(value, units, dpi=96):
"""
convert length from pt to given units
Arguments
---------
value : float
length in measurement units
units : str
unit type (e.g. "pt", "px", "in", "cm", "mm")
dpi : float / int
dots per inch (conversion between inches and px)
... | f46e84e751971446d5bb84cc4740a1840b1ee4e0 | 586,581 |
def as_si(x, ndp):
""" Convert humber to latex-style x10 scientific notation string"""
s = '{x:0.{ndp:d}e}'.format(x=x, ndp=ndp)
m, e = s.split('e')
return r'{m:s}\times 10^{{{e:d}}}'.format(m=m, e=int(e)) | 9caabb7102b953655f74771b0ea6f1f5d8eaac43 | 586,583 |
def get_start_end_date(df, feature, format="%Y-%m-%d %H:%M:%S"):
"""
Returns the start and end date of a time series
Args
df: DataFrame consisting of the time series
feature: Name of the time series feature. The column should be of type np.datetime64
format: String format in which ... | fee3747f2d8afad63ea98a8eb1c65f483acb9b1c | 586,589 |
from typing import Iterable
from typing import Union
from typing import List
def get_option_from_prompt(options: Iterable, default: Union[str, int] = 1,
is_index=True, allow_multiple=False) -> Union[int, List[int], None]:
"""get option from prompt and return choice
:param options: ... | 206eeb62a689a891014b8e08adb4bbefecf7ee89 | 586,590 |
def chunkify(input, chunk_size=20):
"""
A convenience function to chunk a list
"""
chunked = []
for i in range(0, len(input), chunk_size):
end = i + chunk_size if i + chunk_size < len(input) else len(input)
chunked.append(list(input[i:end]))
return chunked | c647371d9ac4e13c466be359494e28383a876833 | 586,596 |
def resize_bbox(bbox, in_size, out_size):
"""
Resizes Bounding Boxes
Arguments:
bbox :- The GT bounding boxes of the image
in_size :- A tuple with height and the width of the image before resized.
out_size :- A tuple with height and the width of the image ... | fbf117fe340ca6b740eaf20af2e2013ad9c14805 | 586,598 |
def fold_description(fold: float) -> str:
"""
Return a string for describing a fraction (including a percent representation).
"""
if fold is None:
return "None"
if fold >= 0:
value = 2 ** fold
char = "X"
else:
value = 2 ** -fold
char = "/"
return f"{... | d749d1b69ffbda89c0642874b802996828d13d32 | 586,600 |
import re
def parse_show_interface_mgmt(raw_result):
"""
Parse the 'show interface mgmt' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show interface mgmt command in a \
dictionary of the form:
::
{
... | 6944b872a6672a51237645bf58bbeaece534a756 | 586,601 |
import json
def read_systematic(infile='../data/run.17.json'):
"""Read systematic error file."""
# with open('../data/run.17.json', 'w') as fp:
# json.dump(run17, fp, indent=4, sort_keys=True)
with open(infile, 'r') as fp:
temp = dict(json.load(fp))
return {int(k):v for k, v in temp.it... | db12fa324be864fa9b5c37eeea72cab712e9cc15 | 586,602 |
def geo_to_str(latitude, longitude, distance):
"""
Return geolocation data as string of comma-separated values.
"""
has_valid_unit = distance.endswith("km") or distance.endswith("mi")
assert has_valid_unit, "Must include units as 'km' or 'mi'."
return ",".join((latitude, longitude, distance)) | 80198cdee2a7500ac1bcdc457d8e20f48b4c6370 | 586,604 |
def _valid_source_node(node: str) -> bool:
"""Check if it is valid source node in BEL.
:param node: string representing the node
:return: boolean checking whether the node is a valid target in BEL
"""
# Check that it is an abundance
if not node.startswith('a'):
return False
# check ... | d8f0e341c0f1ea4fffeea5193054cb9e9eec4b28 | 586,605 |
def pointInPolygon2(p = "const Dim<3>::Vector&",
vertices = "const std::vector<Dim<3>::Vector>&",
normal = "const Dim<3>::Vector&"):
"""3D point in polygon test -- the point and all vertices of the polygon must be coplanar.
p : point we're testing
vertices : the ve... | 863c4915217f8525045d1c0af089a121211c8b72 | 586,607 |
def is_day_of_week(date, day_of_week):
"""Check if you are on specific day of a week.
day_of_week: 0 for Monday, 6 is Sunday.
"""
return (date.weekday() == day_of_week) | 8b6503b3c284bea3dc2d3e82ba1fe0fa7926b8cf | 586,610 |
def make_range_string(start, stop=None):
"""Create a byte range specifier in accordance with RFC-2616.
Parameters
----------
start: int
The start of the byte range
stop: int, optional
The end of the byte range. If unspecified, indicates EOF.
Returns
-------
str
... | 97c2f58ca390546cd3699eae5f8ea7c2a3efe07c | 586,616 |
def csw_query(identifier):
"""
Create CSW GetRecordById query for a given identifier.
"""
return f'''
<csw:GetRecordById xmlns:csw="http://www.opengis.net/cat/csw/2.0.2" service="CSW" version="2.0.2" outputSchema="http://www.isotc211.org/2005/gmd">
<csw:Id>{identifier}</csw:Id>
<csw:ElementSetN... | 9be2bd95000daa8e328c98966a0c6aa470082110 | 586,617 |
import re
def need_analyzer(args):
""" Check the intent of the build command.
When static analyzer run against project configure step, it should be
silent and no need to run the analyzer or generate report.
To run `scan-build` against the configure step might be necessary,
when compiler wrappers... | c3dc08241c9f150f815a0c93575b19bf65adc673 | 586,619 |
def check_tie(board):
""" Checks if the board's state is tie.
"""
for element in board:
if not element:
return False
return True | 525921c13efbd89a53ad0f83910bf814a18cd220 | 586,621 |
import torch
from typing import Sequence
def _flatten(x):
"""Flattens the tree of tensors to flattened sequence of tensors"""
if isinstance(x, torch.Tensor):
return [x]
if isinstance(x, Sequence):
res = []
for xi in x:
res += _flatten(xi)
return res
return [... | 9ca6769daaf9fd3b669f366e0a7e4f46972e56cf | 586,622 |
def subtract_matrices(u, v):
"""
Subtract two n-dimensional vectors
"""
return sum([
u[i] - v[i]
for i in range(len(u))]) | 455e224852dae4541796767fe8cb91350d97abcb | 586,624 |
import requests
def github_branch_exists(project, branch, project_owner='ceph'):
"""
Query GitHub to check the existence of a project's branch
"""
url_templ = 'https://github.com/{project_owner}/{project}/tree/{branch}'
url = url_templ.format(project_owner=project_owner, project=project,
... | 82660b67c07a513c0098e48852b500bb4b4aab43 | 586,627 |
def _bordas(
esquerda,
direita,
largura=48,
espacamento_minimo=4,
favorecer_direita=True
):
"""Prepara duas strings para serem impressas alinhadas às bordas opostas da
mídia, os textos da esquerda (borda esquerda) e da direita (borda direita),
respeitando uma ... | 10abdf9e9abd5d18943f2fcb6a5e7d57e89196ae | 586,630 |
import torch
def symmetric_mse_loss(input1, input2):
"""Like F.mse_loss but sends gradients to both directions
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to both input1 and input2.
"""
assert input1.size() == in... | 64e01abd6b90f2874aa58cd6306709d22535f38c | 586,631 |
def eq_div(N, i):
"""Equally divide N examples among i buckets. For example, `eq_div(12,3) = [4,4,4]`."""
return [] if i <= 0 else [N // i + 1] * (N % i) + [N // i] * (i - N % i) | d944d1602d8af48f6dfb4016325656ce10cbc2d9 | 586,632 |
def sum_digits(n: int) -> int:
"""Returns the sum of the digits of n"""
r = 0
while n:
r, n = r + n % 10, n // 10
return r | d8ba72decd97fe1366866d87494b909859b4222c | 586,633 |
def _lower(string: str) -> str:
"""Properly lower transforms Turkish string ("İ" -> "i", "I" -> "ı")."""
return string.replace("İ", "i").replace("I", "ı").lower() | 15ac29de0599faff53894dafd70150e9c4d7efad | 586,634 |
def total_mass_and_mass_ratio_to_component_masses(mass_ratio, total_mass):
"""
Convert total mass and mass ratio of a binary to its component masses.
Parameters
----------
mass_ratio: float
Mass ratio (mass_2/mass_1) of the binary
total_mass: float
Total mass of the binary
... | 496ee7abd39d4d0b2cf534730490aa2213a66c71 | 586,641 |
def space_indentation(s):
"""The number of leading spaces in a string
Args:
s: str. The input string.
Returns:
int. The number of leading spaces.
"""
return len(s) - len(s.lstrip(' ')) | 9bc74fc261f7f53d073dfc95ca76ba1ee9db90a4 | 586,648 |
def quote_shell_arg(arg):
#===============================================================================
"""
Return an argument with quotes added as needed.
"""
sarg = str(arg)
if len(sarg) == 0 or len(sarg.split()) > 1:
return '"%s"' % sarg
return sarg | 3d2b1ef68fe882af821126e8e29d80c25bf6ec69 | 586,656 |
def markdownify(span):
"""
Given a "span" element, returns a segment of markdown text
Supports __bold__, _italic_,  and [link](url) elements.
Bold and italic elements are trimmed to avoid markdown parse errors.
"""
raw_text = span.get("text", "")
modifiers = span.get("modifiers",... | 4a50944e886c3f31b959813108100c997d158d98 | 586,660 |
from typing import List
import torch
def cat_tensor_with_nones(
tensors: List[torch.Tensor]
):
"""
Concatenate a list of tensors. If any are None, they are excluded
"""
tensors = [t for t in tensors if t is not None]
if len(tensors) == 1:
return tensors[0]
elif len(tensors) == ... | dcf3a38129e54ef33c27baebd95a228c82dacc2d | 586,665 |
def _is_displaced(ins):
"""
returns whether an instruction has been displaced already
"""
return hasattr(ins, 'displaced') and ins.displaced | 645d97259a96d43a80a9dec1a1de7191b4c724b8 | 586,666 |
def get_number_docs(index_name, es):
""" Return the number of indexed documents in ElasticSearch
:param index_name: ElasticSearch index file
:param es: ElasticSearch object
:return: int
"""
res = es.count(index=index_name)
return res['count'] | 6fb43003d33a1177e1b1ed8da26513db1124a3d3 | 586,668 |
import math
def get_distance_node_pose(node, pose):
"""
get_distance_node_pose
Returns the straight line distance between a pose and a node.
"""
return math.hypot(
(pose[0] - node.pose.position.x),
(pose[1] - node.pose.position.y)) | 51439dc28f5c4e3f625c9ebfb6c13b29a61155ce | 586,669 |
def load_cutout_list(cutoutlist):
"""Load the galaxy cutouts from a list of files.
Parameters
----------
cutoutlist : string
The filename containing the list of paths to image cutouts.
Returns
-------
fnames : list(string)
List containing the path to a cutout as each elemen... | 8c854d497edb3b41092eea114504c2ce206728ae | 586,673 |
def hex2color(h):
"""Convert the 6-digit hex string to tuple of 3 int value (RGB)"""
return (int(h[:2], 16), int(h[2:4], 16), int(h[4:], 16)) | 8ff400bb9787eec45afe157439d9f6bd6996b51d | 586,674 |
def vectorized_get(dictionary, key):
"""
Helper vectorized function to get keys
from a dictionary.
"""
return dictionary.get(key, -1) | fdc4ee16630280d8dd34ba9e94f87368c1e70072 | 586,675 |
def check_exit_status(status_file):
"""Read pipeline exit status file and return True if 0, False if anything else"""
with open(status_file, 'r') as f:
exit_status = f.readline().strip()
return exit_status == '0' | 4f194a1a156031b3df70774fb235986cca011f5e | 586,681 |
import re
def _get_pretty_name(view, form_type):
"""
Get the pretty name of a view. If defined view._pretty_name will be
used, else the name will be derived from the view name by taking the
class name and removing View from the name.
"""
if isinstance(view, type):
# Instantiate the vi... | 7cf5e3f47f31e9c805da29dcc027bffcb543ebbc | 586,685 |
import copy
from warnings import warn
def create_event_dict(start_time, nodes_list):
"""
Function to generate a dictionary of event (start/finish) nodes
from the nodes list
Parameters
----------
start_time : datetime.datetime
a datetime object of the pipeline start time
nodes_list... | 50b8c1437f5c606e0d8656edbe56f00f9a5235f8 | 586,690 |
import socket
def port_to_network_int(port: int) -> int:
"""Function to conver a port (integer) into its big endian representation
Args:
port (int): the value of the port
Returns:
int: the big endian representation of the port
"""
return socket.htons(port) | e6553ab6a9dc1437d6c4fd41fd4af65f951bafbf | 586,692 |
import torch
def ts_feature_map_loss(output, label):
"""compute smooth L1 loss"""
return torch.nn.functional.smooth_l1_loss(output, label) | 8ca0e195dc177f6a35ac9e48ac17531ab1909009 | 586,697 |
def _slugs(base):
"""
Returns list of attrs slugs attached to base
:param base: class inherited from ``AbstractEntity``
:returns: list of slugs
:rtype: list
"""
if hasattr(base, 'attrs'):
return [attr.slug for attr in base.attrs]
return [] | 42041508e8e940e5fc386686f55370102adf8c3a | 586,700 |
def extract_keypoints(frame, orb):
"""Extracts ORB keypoints and descriptors in the frame."""
kp = orb.detect(frame, None)
kp, des = orb.compute(frame, kp)
return kp, des | 253e74e74d3dc276c51245d654c6e3ae0fe5ef47 | 586,701 |
import random
def _get_random_words(filename, n_words):
"""Given a # of words, return that many random words from the file 'filename'.
If n_words > the number of words in the file, there will be duplicates in the list.
This is a utililty function for get_random_arabic_citizen_names() and
get_random_... | c2a6f42474707fd1ae5602274e715f041d5b87fb | 586,702 |
def evaluate(h,x):
"""evaluate an instance x with an hypothesis h, that is
a function X->{Yes,No}"""
for i,feature in enumerate(h):
if feature=="0":
return "No"
if feature!="?" and feature!=x[i]:
return "No"
return "Yes" | e5fb5235653b2dc096318be11ff5cbf9c096daeb | 586,705 |
def insertShiftArray(original_arr, val):
"""
Summary of insertShiftArray function: takes an input array and an input value. The input
value is inserted in the middle of the array. A new array is used to create this array.
Parameters:
original_array (array): An array of values
val (int): An int... | 2f86a68b005550ff5b649f5aa0beda027ec4cbe8 | 586,706 |
def _map_groups_to_params(params):
"""Map the group name to the ColumnDataSource friendly parameter names.
Args:
params (pd.DataFrame):
DataFrame with the parameter values and additional information such as the
"group" column and Index.
Returns:
group_to_params (dic... | 65a6cbace4a7692ff1e4a79c78e2875f9a9ef86a | 586,708 |
def get_h14_config(config):
""" ViT-H/14 configuration """
config.patch_size = 14
config.emb_dim = 1280
config.mlp_dim = 5120
config.num_heads = 16
config.num_layers = 32
config.attn_dropout_rate = 0.0
config.dropout_rate = 0.1
return config | 5a66d52c22b200b70c520c0217b7fcac77f7388b | 586,712 |
def _prepare(data: dict):
""" Remove fields `_id` and `name` and return data. """
return {k: v for k, v in data.items() if k not in ('_id', 'name')} | 75ca6db934ab68bbe1c4a29bc893ef6283097ccd | 586,713 |
import inspect
def get_kind(x):
"""
Classify x as one of five high-level kinds: module, function, descriptor, type, or object
"""
if inspect.ismodule(x):
return "module"
elif inspect.isroutine(
x): # isroutine returns true for any kind of function or method
return "fun... | 0035940c3624697de3f31f9748b734a6fe27d1f1 | 586,714 |
def extract_xml_tags(xml_tag_name, node, allow_none=True):
"""Helper to extract xml tags from xmltodict.
Parameters
----------
xml_tag_name : str
Name of the xml tag to extract from the node.
node : object
Node object returned by ``xmltodict`` from which ``xml_tag_name``
sh... | 74a031bfde55e21a5eb887aff1a4fcd247a0e660 | 586,715 |
def create_mapping(start_offsets, end_offsets, context_to_plaintext_offset):
"""Creates a mapping from context offsets to plaintext offsets.
Args:
start_offsets: List of offsets relative to a TyDi entry's `contexts`.
end_offsets: List of offsets relative to a TyDi entry's `contexts`.
context_to_plainte... | 0b7cf16b2bac1573ab22b1df1e54779da47e7a6e | 586,716 |
import re
def text_fragments_and_fields(formula):
"""Given a formula with fields enclosed in angle brackets,
return a list of text-fragment,field pairs (in order of appearance) and a final text fragment.
E.g., if formula is <County>;<Precinct>, returned are [(None,County),(';',Precinct)] and None."""
... | 9a39143435cda0cf27f1016a7357c3fdbfa66df6 | 586,717 |
from typing import List
from typing import Dict
def get_member_logins(members: List[Dict[str, str]]) -> List[str]:
""" Reduce a list of github member objects to a list of logins (usernames) """
return [member["login"] for member in members] | b9f4a0983cc482df7dedb193e5a36c0ea8f6a4c3 | 586,719 |
import math
def linearTarget(targetPos, targetVel, projectilePos, projectileSpeed):
"""Calculates how to hit a target with linear prediction.
Predicts the time and location where a projectile should be fired to hit
a target at at particular position moving with a particular velocity.
Assumes that the... | afb712467a69512adf762d14f176a7f2936a48e5 | 586,721 |
from typing import Tuple
import csv
def sniff_csv_meta(file_path: str) -> Tuple[str, bool]:
""" Determine the csv delimiter and whether it has a header """
with open(file_path, "r") as csv_file:
first_bytes = csv_file.read(2 ** 12)
sep = csv.Sniffer().sniff(first_bytes).delimiter
has_header = ... | 070b49b932ab034b627041cd730c679e22b890f0 | 586,722 |
import tqdm
def slow_tqdm(*args, **kwargs):
""" Return a tqdm progress bar with infrequent updates. """
return tqdm.tqdm(mininterval=10, *args, **kwargs) | af1480c48490359831477e8384252aa54fec5cb5 | 586,723 |
import json
def post_to_query_string(dico):
""" Transform a dict to a query string
>>> post_to_query_string({'foo': 'bar', 'where': {'foo': 'bar'}})
?foo=bar&where={"foo": "bar"}
:params dico the dico to convert
"""
querystring = "?"
for key in dico:
querystring ... | 21b2c43a948c148c37ba2649e8032b1f54f88926 | 586,726 |
def read_OUTCAR(path='OUTCAR'):
"""read time and ncores info from OUTCAR"""
time = 0
ncore = 0
for line in open(path, 'r'):
if line.rfind('running on ') > -1:
ncore = int(line.split()[2])
elif line.rfind('Elapsed time ') > -1:
time = float(line.split(':')[-1])
... | a0059fa50beb47a7981f40a7bb433cd57257943c | 586,731 |
def get_date_multiplier(date_filter):
"""
Utility for returning the multiplier for a given date filter
@param date filter : the given date filter
@return multiplier for a given filter
"""
vals = {
'day': 86400,
'hour': 3600
}
return vals[date_filter] | fce8c5e1285bfc4d1234ad87093e538ff7192e38 | 586,732 |
def drop_info(df):
"""Takes a dataframe and drop rows whitout an splitted `info`
length diferrent than four.
Parameters
----------
df :
The dataframe to search.
Returns
-------
The dataframe processed.
"""
before = df.shape
print(f'Shape before dropping: {befo... | fb18f874eaf925c6651aa912009749806fc0b1f4 | 586,733 |
from typing import Any
from typing import cast
def _is_package_entry(entry: Any) -> bool:
"""Returns True if the html entry describes a package."""
href = entry["href"]
return cast(bool, (
href.endswith("gz")
and href == entry.string
and href != "PACKAGES.gz"
)) | 03baf1161a2a2c1290a633b05b98596a37c3160b | 586,735 |
def _prepare_outputs(dict_outputs, as_dict):
"""Converts from dict outputs into the return value of Module.__call__().
Args:
dict_outputs: A dict output from applying a signature.
as_dict: A boolean indicating whether to return the outputs of the Module
as a dict or return the output named 'default.
... | 84e267c6480cf89970bd2d8a553fcbe1e1bfc434 | 586,736 |
def bittest(value, bitindex):
"""This function returns the setting of any bit from a value.
bitindex starts at 0.
"""
return (value&(1<<bitindex))>>bitindex | 47bcd114c17c7dc06e15c66927ad5912115f6584 | 586,737 |
def clean_whitespace(text):
"""Standardizes whitespaces so there is only one space separating tokens
Parameters
----------
text : str
The fixed text
Returns
-------
str
fixed text
"""
return ' '.join(str(text).split()) | 622b453242f06786ca45104b36cb716e85175a2e | 586,740 |
def _get_res_id_from_role_id(role_id):
"""Get role's ID from its given GCP ID.
Args:
role_id (str): resource ID (in inventory) of role.
Returns:
str: role ID; None if the given resource ID is incorrect.
"""
split_id = role_id.split('/')
if len(split_id) == 4:
return spl... | a412713ba12366f9092a245de1fce5134bd2ef79 | 586,743 |
def handle_index(l, index):
"""Handle index.
If the index is negative, convert it. If the index is out of range, raise
an IndexError.
"""
# convert negative indices to positive ones
if index < 0:
# len(l) has always type 'int64'
# while index can be an signed/unsigned integer
... | 8bcded8f19732379aebf0de113a037d1d9d7283f | 586,749 |
def translateValue(value: str) -> int:
"""Translates the string representation of an Item to an LED brightness
Args:
value (str): The given String block
Returns:
int: The LED brightness value for that block [0,9]
"""
if value == "P":
return 9
elif value == "B":
... | 9f10fe0e88e954a3bb1be643470e51434c833058 | 586,753 |
def get_included_models(model):
"""
get a list of all models stored within a model
(including the owning model).
Args:
model: the owning model
Returns:
a list of all models
"""
if (hasattr(model, "_tx_model_repository")):
models = list(model._tx_model_repository.all... | 510755950c2a36db3235b3f13e06f03582e1374e | 586,755 |
def track_processed(args):
"""
Track processed if there might be a delete timeout or interval specified
:param args:
:return:
"""
return args.delete or (args.interval and args.interval > 0) | 9542f227316e96b22d9cb236ebb6196bd059618d | 586,756 |
import base64
import pickle
def get_carts_from_cookies(request):
"""
获取cookie中的购物车数据
:param request: 请求对象
:return: 购物车字典 or {}
"""
carts_from_cookies = request.COOKIES.get('carts')
if carts_from_cookies: # "XdnhjgrbewghjrtebABFGNJEKb="
# 1、先base64解码
# b'\x56\x78.....'
... | 7463520fc6de3e472a7c64536b7759093e33c42b | 586,757 |
def average_rt(rt_list):
"""Calculate average rt for a set of peaks (e.g. experiment analyte rt based on replicate analyte rts).
Currently this is a simple average calculation, but is broken out as a separate function for possible future
changes to rt determination strategy
"""
return round(sum(rt... | ae4c0599374fbbcebc6cfd5969f842454edf12b1 | 586,758 |
def aggregate_run_results(collection_failures, test_results):
"""
Determines overall status of run based on all failures and results.
* 'ERROR' - At least one collection failure occurred during the run.
* 'FAIL' - Template failed at least one test
* 'PASS' - All tests executed properly and no failu... | c63597486927597e70dbd4c67216f37b9f1d18ba | 586,759 |
from operator import mod
def oddround(x):
"""Return the nearest odd integer from x."""
return x-mod(x,2)+1 | 78363fede7f7a768a395a6b1447edc7f86f5b1da | 586,760 |
def derive_source(url):
"""Derive the source of data from the URL."""
parts = url.split('/')
return '//'.join([parts[0], parts[2]]) | 7a5ebe0ab0bca751bf8bb546e62a4f7e9e9321c9 | 586,764 |
def extract_comment_attributes(dict_elem):
"""
Select the attributes of interest from the comment attribute dict.
:param dict_elem: dict with parsed XML attributes
:return: dict with selection of parsed XML attributes
"""
return {
'PostId': int(dict_elem['PostId']),
'Score': dict... | cec2efc325e4601af9bcc071e762bdbba1021794 | 586,765 |
from datetime import datetime
import time
def util_timestamp_format ( unixtime ):
"""Returns as string a human-readable time stamp from unix time in microseconds"""
# return as YYYY-MM-DD HH:MM:SS.MMMMMM
t = float(unixtime) / 1000000
t2 = datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S.%f') ... | 83e65b35c971561fdde8784ab51340a5f879a9e8 | 586,766 |
def node_to_tensor(node, index=0):
"""
Get tensor name from node name and index
Args:
node: Name of an operation in a a graph.
index: index of the tensor among the outputs of the node. Defautls to 0.
When some nodes return more than one tensors, index helps to
identif... | e32eeec707a691ae84d35376ea0276b024d14c44 | 586,768 |
def get_query_sentiment_avg(tweets):
"""
Calculates the average sentiment score in a given query set of Tweets.
:param tweets: A query set of tweet data
:return: The average sentiment score in the query set
"""
total = 0
count = len(tweets)
for tweet in tweets:
total += tweet.... | 80ae94dca7191258a6b46a1ca97ff9e1c8f0966a | 586,770 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.