content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert_datetime_to_timestamp(dt):
"""Convert pandas datetime to unix timestamp"""
return int(dt.timestamp()) | f9cf6223bfabfa54c00835b56bdce2d5b268afe7 | 702,533 |
def get_indicator_type_value_pair(field):
"""
Extracts the type/value pair from a generic field. This is generally used on
fields that can become indicators such as objects or email fields.
The type/value pairs are used in indicator relationships
since indicators are uniquely identified via their ty... | 1750558782b91017061176176dda94c83c3dee6a | 702,534 |
def doc_arg(name, brief):
"""argument of doc_string"""
return " :param {0}: {1}".format(name, brief) | 8a341c7ef0b437ba9ec035001e71952e3793eea8 | 702,535 |
def example_project(tmp_path):
""" a minimal project
"""
my_module = tmp_path / "my_module"
starter_content = my_module / "starter_content"
starter_content.mkdir(parents=True)
(tmp_path / "README.md").write_text("# My Module\n")
(my_module / "__init__.py").write_text("__version__ = '0.0.0\n... | 9063c3f317abc66116bd79656c4fd16e96095e4f | 702,536 |
def foo():
"""
example function documentation
an example doctest is included below
returns: None
>>> x = foo()
>>> x
'foo'
"""
return "foo" | 81300580771ac0fa31b8c701d322a48997683c9c | 702,537 |
def string_date(mnthDay, year):
"""Return a string date as 'mm/dd/yyyy'.
Argument format:
'mm/dd' string
'yyyy'"""
return(mnthDay + '/' + str(year)) | e85bf9f0e72735be04009c6b685f2788a5c46d47 | 702,538 |
def check_who_queued(user):
"""
Returns a function that checks if the song was requested by user
"""
def pred(song):
if song.requested_by and song.requested_by.id == user.id:
return True
return False
return pred | e53a1434077ec7b97e237d1ff8bcc8c2454c4015 | 702,539 |
def _get_lines(filename):
"""Returns a list of lines from 'filename', joining any line ending in \\
with the following line."""
with open(filename, "r") as f:
lines = []
accum = ""
for line in f:
if line.endswith("\\\n"):
accum += line[:-2]
els... | 83b2184eedfb21d27f310f9f2229d05d69ac8b92 | 702,540 |
import re
def replace_punctuation_and_whitespace(text):
"""Replace occurrences of punctuation (other than . - _) and any consecutive white space with ."""
rx = re.compile(r"[^\w\s\-.]|\s+")
return rx.sub(".", text) | b539ec796c1b69176e0da132ee88f9695b745fb2 | 702,541 |
import re
def remove_symbols(text):
""" Removes all symbols and keep alphanumerics """
whitelist = []
return [re.sub(r'([^a-zA-Z0-9\s]+?)',' ',word) for word in text if word not in whitelist] | 54e3706a275f5c5ff58a924a04249066d014f393 | 702,542 |
def filter_out_length_of_one(word):
"""
Filters out all words of length 1
:param word: Input word
:return: None if word is of length 1, else the original word
"""
if len(word) > 1:
return True
return False | c89fda6b560811a178a5a2d2c242d54fba27d071 | 702,543 |
def bmesh_join(list_of_bmeshes, list_of_matrices, *, normal_update=False, bmesh):
"""takes as input a list of bm references and outputs a single merged bmesh
allows an additional 'normal_update=True' to force _normal_ calculations.
"""
bm = bmesh.new()
add_vert = bm.verts.new
add_face = bm.face... | 07d7f3401d170ed4afc3f6a795258710fe263aba | 702,544 |
import json
def read_json(jsonfile):
"""Read a json file into a dictionary
Args:
jsonfile: the name of the json file to read
Returns:
the contents of the JSON file as a dictionary
>>> from click.testing import CliRunner
>>> test = dict(a=1)
>>> with CliRunner().isolated_filesyst... | da5b7bddc42b14a6547071fe528a1c051d35356c | 702,545 |
def zero_float(string):
"""Try to make a string into a floating point number and make it zero if
it cannot be cast. This function is useful because python will throw an
error if you try to cast a string to a float and it cannot be.
"""
try:
return float(string)
except:
return 0 | 075a49b53a0daf0f92072a5ec33f4b8240cc6885 | 702,546 |
import re
def _special_att_handling(attype, col_args): # noqa: C901
""" laundry list of special handling that sqlalchemy
does to convert between a Postgres type and a Sqlalchemy type """
kwargs = {}
if attype == 'uuid':
kwargs = {'as_uuid': True}
args = ()
elif attype == 'numeri... | e9feabb792001c66a9679a3a5931cb00c96dcf83 | 702,547 |
def checksum(data) -> int:
"""
Found on: http://www.binarytides.com/raw-socket-programming-in-python-linux/. Modified to work in python 3.
The checksum is the 16-bit ones's complement of the one's complement sum
of the ICMP message starting with the ICMP Type (RFC 792).
:param data: data to built ch... | af8ba70fa53f95514bc6e8118440ba607c17d794 | 702,548 |
def _number_convert(match):
"""
Convert number with an explicit base
to a decimal integer value:
- 0x0000 -> hexadecimal
- 16'h0000 -> hexadecimal
- 0b0000 -> binary
- 3'b000 -> binary
- otherwise -> decimal
"""
prefix, base, number = match.groups()
if prefix is not None:
... | adef8f8f80342fbcd79c461068eb04f99427f88c | 702,549 |
import requests
import sys
def get_scientific_name(taxon_id):
"""Get scientific name for input taxon_id.
:param taxon_id: NCBI taxonomy identifier
:return scientific_name: scientific name of sample that distinguishes its taxonomy
"""
# endpoint for scientific name
url = 'http://www.ebi.ac.uk/... | 5cab933a3cc6ab2602e680c3db2ed129c3f85b94 | 702,550 |
def rating_calc(item, ocurrences, last_ocurrences, total_ocurrences):
""" Calculates the rating of the target language.
"""
rating = ocurrences / total_ocurrences
if item in last_ocurrences:
rating *= 2
if last_ocurrences and item == last_ocurrences[-1]:
rating *= 4
return rating | fa93bd9c44b612231cd7dd486909fa2654e34288 | 702,551 |
import hashlib
def makeKey(password, salt):
"""make master key"""
if not hasattr(password, 'decode'):
password = password.encode('utf-8')
if not hasattr(salt, 'decode'):
salt = salt.lower()
salt = salt.encode('utf-8')
# Here we use 100,000 iterations since that is the default t... | 59819fc96f3ad5e4627c5acccf3ba2acf99ee49d | 702,552 |
def run_episode(environment, agent, is_training=False):
"""Run a single episode."""
timestep = environment.reset()
while not timestep.last():
action = agent.step(timestep, is_training)
new_timestep = environment.step(action)
if is_training:
agent.update(timestep, action, new_timestep)
ti... | dcec7609b33cf2f13ca6753c2dfd614252189b51 | 702,553 |
def pandas_df_to_temporary_csv(tmp_path):
"""Provides a function to write a pandas dataframe to a temporary csv file with function scope."""
def _pandas_df_to_temporary_csv(pandas_df, sep=",", filename="temp.csv"):
temporary_csv_path = tmp_path / filename
pandas_df.to_csv(temporary_csv_path, se... | 5ec9b3072928e3cdbe067dfcb33010b2a51a267b | 702,554 |
def df(n):
"""Gives the double factorial of *n*"""
return 1.0 if n <= 0 else 1.0 * n * df(n - 2) | 71fcc2445db94b5686d4c9b8d85e9bdc1dc2bbb4 | 702,555 |
def cli(ctx, job_id):
"""Resume a job if it is paused.
Output:
dict containing output dataset associations
.. note::
This method is only supported by Galaxy 18.09 or later.
"""
return ctx.gi.jobs.resume_job(job_id) | 956ee7cbc0b251718311fae88b2bf53482d88b23 | 702,556 |
def queue_exists(queue_id):
"""Returns true if the queue ID belongs to a valid queue."""
return True | 24bb477842cedb5443eb06217374deec49f99398 | 702,557 |
import re
def track_num_to_int(track_num_str):
""" Convert a track number tag value to an int.
This function exists because the track number may be
something like 01/12, i.e. first of 12 tracks,
so we need to strip off the / and everything after.
If the string can't be parsed as a ... | af6e878bad7c3e26c61ad2ad4a759cb8c1dc4224 | 702,558 |
def elt1(list, context):
"""return second member"""
return list[1] | 40d59eaac5b9eeb86b511ef2a4df4b68893a6248 | 702,559 |
def sort_list(player_data_list):
"""Sort list based on qualifer.
Args:
player_data_list: player data list
Returns:
player data list properly sorted
"""
return sorted(player_data_list, key=lambda x: x[-1]) | 7164d2851ca6c7557e8a9e10c45a25243254180d | 702,560 |
def is_alive(worker_dict):
""" Test if worker is alive and running | None --> Bool """
return worker_dict['worker'].is_alive() | c3979d4722d27c8a3ceefe38b141313f4cdef881 | 702,561 |
def sort(array: list[int]) -> list[int]:
"""Naive bubble sort implementation.
"""
for i in range(len(array)):
for j in range(len(array) - 1, i, -1):
if array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
return array | f3121f84b238d82ea3cc7d87bfa993c2a9339786 | 702,562 |
def box_teamnames(page):
"""
A @ H always
"""
teams = page.find_all("span", {"class": "short-name"})
destinations = page.find_all("span", {"class": "long-name"})
names = [team.text for team in teams]
cities = [destination.text for destination in destinations]
if not names or not cities:
... | f116fdb86fa347c5dcbaef40771b3f49d2b67f7a | 702,563 |
def _call_bool_filter(context, value):
"""Pass a value through the 'bool' filter.
:param context: Jinja2 Context object.
:param value: Value to pass through bool filter.
:returns: A boolean.
"""
return context.environment.call_filter("bool", value, context=context) | 181a51d7d436cf0eaf2c0fe9d2f04ab4030f010c | 702,564 |
def get_attr(attrs, key):
""" Get the attribute that corresponds to the given key"""
path = key.split('.')
d = attrs
for p in path:
if p.isdigit():
p = int(p)
# Let it raise the appropriate exception
d = d[p]
return d | eec6878b19413c54008eb930af21cd40decff2cc | 702,566 |
def get_wbo(offmol, dihedrals):
"""
Returns the specific wbo of the dihedral bonds
Parameters
----------
offmol: openforcefield molecule
dihedrals: list of atom indices in dihedral
Returns
-------
bond.fractional_bond_order: wiberg bond order calculated using openforcefield toolkit ... | 82aa84036d3078826fedaec40e599ffd783a422c | 702,567 |
import re
def _GetLogTag(filename):
"""Get the tag of a log."""
regex = re.compile(r'\d+\-\d+(:?\-(?P<tag>.+))?.h5')
match = regex.search(filename)
if match and match.group('tag'):
return match.group('tag')
elif filename.endswith('.h5'):
return filename[:-3]
else:
return '' | 4be40e744478d4f0b8c5ffc7ea866537802b1f25 | 702,568 |
import numpy
def l2_norm(x: numpy.ndarray, y: numpy.ndarray) -> numpy.ndarray:
"""Euclidean distance between two batches of points stacked across the first dimension."""
return numpy.linalg.norm(x - y, axis=1) | 248f004276d5459e7b6ce8906abc7bf950a9b1a3 | 702,569 |
def ilarisHitProb(at,vt):
"""
at: AT of attacking character
vt: VT of defending character
return: probability that attacking character will hit defending character
"""
# 47.5 is the chance without any bonus
# 47.5-((y-41)*y)/8 is the added chance per bonus
# (at>vt) is extra if at>vt bec... | 488668075154a509ed87345a17fac31b88c86d69 | 702,571 |
import string
import random
def random_string() -> str:
"""Return a random string of characters."""
letters = string.ascii_letters
return "".join(random.choice(letters) for i in range(32)) | dc828f6f89f1e20ee6cea5ebcbbecb38b0b07aa6 | 702,572 |
def bbox_structure_to_square(bbox):
"""Function to turn from bbox coco struture to square.
[x,y,width,height] -> [min_height, min_width, max_height, max_width]
"""
x,y,width,height = bbox
sq = [y,x,y+height,x+width]
return sq | ff3147c89ad6d14ad22126bdc0cf119883d82db9 | 702,573 |
from typing import Pattern
def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
"""Replace `regex` with `replacement` twice on `original`.
This is used by string normalization to perform replaces on
overlapping matches.
"""
return regex.sub(replacement, regex.sub(replacemen... | 6bada9c7b349ba3a5da840e131577dd354f0b9eb | 702,574 |
import pickle
def load_pickle(filename):
"""
Loads a serialized object
Parameters:
-----------
filename : string
"""
return pickle.load(open(filename,'rb')) | 6525b73e211947ea0b2f76ec5f071d46bb806f06 | 702,575 |
def get_properties(value):
"""
Converts the specified value into a dict containing the NVPs (name-value pairs)
:param value:
:return:
"""
rtnval = None
if isinstance(value, dict):
# value is already a Python dict, so just return it
rtnval = value
elif '=' in value:
... | 03f75e85e54a08b75b8d6e25b5d1dd65f7e987db | 702,577 |
def get_pdm_terms(site_index, n, adj_sites=4, shift=0):
"""
inputs:
site_index (int): center site index
n (int): number of sites in lattice (for enforcing periodic boundary conditions)
adj_site (int): how many adjacent sites to collect pop and coherence values from
shift (int): r... | 34d7914ddd751cb75b04e855d68edb156c1defda | 702,579 |
import ast
def ast_name_node(**props):
"""
creates a name ast node with the property names and values
as specified in `props`
"""
node = ast.Name()
for name, value in props.items():
setattr(node, name, value)
return node | 880d9527d63c7b2c97a4bc616bf245dab6583f81 | 702,581 |
def buildX(traj_file, t, X):
"""
Builds the node attribute matrix for a given time step.
Inputs:
traj_file : string indicating the location of the ground truth trajectory data
t : scalar indicating current time step
X : empty node attribute matrix in shape [n_nodes, n_features]
Outputs:
... | 3b0d3b18d9897364e1140103d7f049d5502d302a | 702,582 |
def move_left(board, row):
"""Move the given row to one position left"""
board[row] = board[row][1:] + board[row][:1]
return board | a0dc74f65abd5560db7c2fe602186d15b8fda3d2 | 702,583 |
import re
import torch
def embed_seq(sequence, tokenizer, prottrans_model, device="cpu"):
"""
Embed a single sequence from the tokenizer and prottrans model.
"""
sequences = [sequence]
sep_sequences = []
for seq in sequences:
sep_sequences.append(" ".join([x for x in seq]))
#print(... | 2c8182e67aa2fe8fa1bf0dff332d8bd8a25a5fb2 | 702,584 |
def get_quadrant(x, y):
"""
Returns the quadrant as an interger in a mathematical positive system:
1 => first quadrant
2 => second quadrant
3 => third quadrant
4 => fourth quadrant
None => either one or both coordinates are zero
Parameters
----------
x : float
x coordina... | 8650edb7a3e854eed0559f633dcf5cd0c7310db4 | 702,585 |
def days_in_month(year, month):
"""
Inputs:
year - an integer between datetime.MINYEAR and datetime.MAXYEAR
representing the year
month - an integer between 1 and 12 representing the month
Returns:
The number of days in the input month.
"""
leapyear=0
if(year%4 ... | b2988e9a6b1413ef0957413c10e5e4f5ef225d8b | 702,586 |
import requests
import json
def _get_token(user, password, host, port):
""" Gets auth token. """
token_url = "{}:{}/api/token/".format(host, port)
response = requests.post(token_url, json={
"username": user,
"password": password
})
if response.ok:
return json.loads(response... | 701bb7c1a740cfeca5c321bb6662b8f4e701cd81 | 702,587 |
import random
def random_point():
"""Returns a random point on a 100x100 grid."""
return (random.randrange(100), random.randrange(100)) | 6a2a2c3a4bc3f8347d538984354c2d9688989e14 | 702,588 |
def repeat(s, n):
""" (str, int) -> str
Return s repeated n times; if n is negative, return empty string.
>>> repeat('yes', 4)
'yesyesyesyes'
>>>repeat('no', 0)
''
"""
return (s * n) | b44b56b9e69783c7f57e99b61cc86e975c575a59 | 702,589 |
def can_translate(user):
"""Checks if a user translate a product"""
return user.permissions['perm_translate'] | c6797346d8bd61637927af808bb9355a9220a91e | 702,590 |
def read_xml_file_line_basis(xml_file, element):
"""
Read the xml file and capture only the elements we need.
"""
start_tag = f'<{element}>' # 3
end_tag = f'</{element}>' # 2
start_tag_identified = False # 3
captured_records = list() # 4
captured_line = ''
with open(xml_file) as f: #... | be45d97bd3ca051f06c775b21184c158472cd824 | 702,591 |
def xyz_string(labels, coords):
""" .xyz format string for this cartesian geometry
:param labels: optional labels for the beginnings of atom lines, by index
:type labels: dict
"""
assert len(labels) == len(coords)
dxyz = '\n'.join(
'{:s} {:s} {:s} {:s}'.format(asymb, *map(repr, xyz))
... | be2d34fe41a3468c0764bbfd9d6960dc377375cc | 702,592 |
import pandas
def Protein_translation_Amb(t, y, data, mRNAData):
"""
Defines ODE function Conversion of Amb_mRNA to protein
p1,p2,p3....: Protein concentrations for all ODEs
It will have list of all parameter values for all my ODEs, so 36 values : L, U, D for each mRNA to protein conversion equation
... | 1730cf15d57566dc9ec461f3631fe0feeddd4b49 | 702,593 |
import os
def _get_abs_path(path):
"""Return the absolute path for a given path.
:param path: ``str`` $PATH to be created
:returns: ``str``
"""
return os.path.abspath(
os.path.expanduser(
path
)
) | 3420a9624470c9a2129865356277864a6d930046 | 702,594 |
def square(num):
"""
Return the square values of the input number.
The input number must be integer.
"""
return num ** 2 | e4f88e5f00de7c469d372d9ce1a7e539941b3857 | 702,595 |
from typing import OrderedDict
def apply_address_fixups(address: OrderedDict[str, str]) -> OrderedDict[str, str]:
"""Sometimes the usaddress parser makes mistakes. It's an imperfect world.
This function applies transformations to the parsed address to correct specific
known errors.
"""
# Fixup: At... | 735f7e035b352b21b9b7998b8aa6f5ad7ac826d7 | 702,596 |
import torch
def mask_finished_scores(score, flag):
"""
If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score
and the rest -inf score.
Args:
score: A real value array with shape [batch_size * beam_size, beam_size].
flag: A bool ar... | 87d5d8fb45a44c54cd690280ce0baf0c4fe8dab5 | 702,597 |
import itertools
def args_combinations(*args, **kwargs):
"""
Given a bunch of arguments that are all a set of types, generate all
possible possible combinations of argument type
args is list of type or set of types
kwargs is a dict whose values are types or set of types
"""
def asset(v):
... | 8e90ce285322bd17a97e4bdb75e230f7015f4b2d | 702,598 |
import copy
def coordinate_tensor(dim):
"""
:param dim: list of lengths for each dimension
:return: a list of every possible coordinate within the dimension system
"""
# recurrent function
def recurrent_dim_filler(dim_current, dim_higher, coordinate_higher, coordinates):
# processing... | 8a5e2f11b5157cb2500748ea149305a21b562b77 | 702,599 |
def RGBStringToList(rgb_string):
"""Convert string "rgb(red,green,blue)" into a list of ints.
The purple air JSON returns a background color based on the air
quality as a string. We want the actual values of the components.
Args:
rgb_string: A string of the form "rgb(0-255, 0-255, 0-255)".
Returns:
... | f94650ed977b5a8d8bb85a37487faf7b665f2e76 | 702,600 |
import six
def _metric_value(value_str, metric_type):
"""
Return a Python-typed metric value from a metric value string.
"""
if metric_type in (int, float):
try:
return metric_type(value_str)
except ValueError:
raise ValueError("Invalid {} metric value: {!r}".
... | 39a3b0e5bfe2180e1897dd87872f8e08925e8847 | 702,601 |
import threading
def in_main_thread():
"""
True when the current thread is the main thread.
"""
return threading.current_thread().__class__.__name__ == '_MainThread' | 82da352928b2af3794a2ee608b2763b98b8a731e | 702,602 |
def fixUnits(object, **kwargs):
"""Convert output pint units into a proper latex string."""
string = str(object)
type = kwargs.get('type', None)
unitColor = 'darkBlue'
replacements = kwargs.get('replacements', None)
if replacements:
for old, new in replacements.items():
str... | a1922f296a7d55b989fe5455ed98eb166edeeee7 | 702,603 |
def getMDistance(plug):
"""
Gets the MDistance value from the supplied plug.
:type plug: om.MPlug
:rtype: om.MDistance
"""
return plug.asMDistance() | 43cd8dfd2c698ad1cc88771c2c69f3b5e502f202 | 702,604 |
def get_time_size(rates):
"""
Get number of time intervals
Parameters
----------
Returns
-------
out : int
Number of time intervals
See Also
--------
DataStruct
"""
wgname_keys = list(rates.keys())
mnemo_keys = list(rates[wgname_keys[0]].keys())
return... | c6c496992ef0fe557df302c3c88d9290895cd4a1 | 702,606 |
import argparse
def arg_parser():
"""
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", type=str, dest='input_file',
help="Input file with tweets summary information")
parser.add_argument("-e", "--input-entities", type=str, dest='input_ent',
... | b0079ee9990229890f510e2679344256a4d32dc2 | 702,607 |
def splitFragP(uriref, punct=0):
"""split a URI reference before the fragment
Punctuation is kept.
e.g.
>>> splitFragP("abc#def")
('abc', '#def')
>>> splitFragP("abcdef")
('abcdef', '')
"""
i = uriref.rfind("#")
if i >= 0:
return uriref[:i], uriref[i:]
else:
... | cc179fd8f064f3e87f18a9968f6f98ff0d584eb6 | 702,608 |
def sanitize_name(name):
""" Clean-up the given username."""
name = name.strip()
# clean up group
name = name.replace('- IE', ' -IE')
name = name.replace('- MA', ' -MA')
for l in [1,2,3,4,5,6,7,8,9]:
for g in "AB":
name = name.replace(f'IE{l}-{g}', f'IE-{l}{g}')
... | c0618737b0717e6e90c09ab8d2f4f969abb7d891 | 702,609 |
import os
def extensionName(path):
"""
Function responsible for returning the extension of a file.
"""
extension = os.path.splitext(path)[1][1:]
return extension | e76f47164acc5d1c189b111b018690b7d2f039b4 | 702,610 |
import yaml
import re
def create_kubeconfig_for_ssh_tunnel(kubeconfig_file, kubeconfig_target_file):
"""
Creates a kubeconfig in which the Server URL is modified to use a locally set up SSH tunnel. (using 127.0.0.1 as an address)
Returns a tuple consisting of:
- the original IP/Serve... | 39c85681486abda0008a040ad13a37032fc182b5 | 702,611 |
def sse_pack(d):
"""
Format a map with Server-Sent-Event-meaningful keys into a string for transport.
Happily borrowed from: http://taoofmac.com/space/blog/2014/11/16/1940
For reading on web usage: http://www.html5rocks.com/en/tutorials/eventsource/basics
For reading on the format: https://... | 5e3f791fc5b2451ff5538c3463674e1e89b80e12 | 702,612 |
import argparse
def parse_arguments():
"""
Create command-line interface
"""
desc = "Compute dG, stdDG for different lengths and number of trajectories"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-l", "--lagtime", type=int, default=100, help="Lagtimes to use, d... | e464504557497ebcfabdefe99fec5069aa9c03a1 | 702,613 |
def _touint64(num):
"""
This is required to convert signed json integers to unsigned.
"""
return num & 0xffffffffffffffff | 9edf75a0bd62ae2c6fb126a9ce1e1b283dfbd52c | 702,614 |
import torch
def shuffle(images, targets, global_targets):
"""
A trick for CAN training
"""
sample_num = images.shape[1]
for i in range(4):
indices = torch.randperm(sample_num).to(images.device)
images = images.index_select(1, indices)
targets = targets.index_select(1, indi... | 0079304c05293fb68e3af45be7a2e3cbd9564184 | 702,615 |
def get_lines_from_file(loc):
"""Reads the file and returns a list with every line.
Parameters:
loc (str): location of the file.
Returns:
list: list containing each of the lines of the file.
"""
f = open(loc)
result= [line.replace("\n", "") for line in f]
f.clo... | c05101b94e459346adae553e31d25d46a8475514 | 702,616 |
def GetBuildShortBaseName(target_platform):
"""Returns the build base directory.
Args:
target_platform: Target platform.
Returns:
Build base directory.
Raises:
RuntimeError: if target_platform is not supported.
"""
platform_dict = {
'Windows': 'out_win',
'Mac': 'out_mac',
'Li... | 0bbbad4de3180c2ea51f5149cc3c2417a22b63e9 | 702,618 |
def make_wildcard(title, *exts):
"""Create wildcard string from a single wildcard tuple."""
return "{0} ({1})|{1}".format(title, ";".join(exts)) | 0634c450f43cc779431f61c2a060cea7e02f6332 | 702,619 |
from pathlib import Path
def dir_files(path, pattern="*"):
"""
Returns all files in a directory
"""
if not isinstance(path, Path):
raise TypeError("path must be an instance of pathlib.Path")
return [f for f in path.glob(pattern) if f.is_file()] | 5dbeeec6fe72b70381afb52dcbbea55613a37d49 | 702,620 |
def myDownsample(y, N) :
"""
yds = myDownsample(y,N)
yds is y sampled at every Nth index, starting with yds[0]=y[0] with y[range(0,len(y),N)]. Implementing Matlab's downsample.
Ted Golfinopoulos, 7 June 2012
"""
return y[range(0,len(y),N)] | 0d39f37f4e3a5528f087921e6a4993ea6bf2981c | 702,621 |
def _norm_args(norm):
"""
Returns the proper normalization parameter values.
Possible `norm` values are "backward" (alias of None), "ortho",
"forward".
This function is used by both the builders and the interfaces.
"""
if norm == "ortho":
ortho = True
normalise_idft = Fals... | e781c894c9d333fdbdf326120b1417b44dfc5181 | 702,622 |
import torch
def all_pair_iou(boxes_a, boxes_b):
"""
Compute the IoU of all pairs.
:param boxes_a: (n, 4) minmax form boxes
:param boxes_b: (m, 4) minmax form boxes
:return: (n, m) iou of all pairs of two set
"""
N = boxes_a.size(0)
M = boxes_b.size(0)
max_xy = torch.min(boxes_a[:... | 1ca948e4a16016efa694d97c4829fcdfbc29e20d | 702,623 |
def get_empty_theme():
"""Create object that contains empty theme."""
return {
'theme': {},
'background': bytearray()
} | fc129d109ef2677b41d9a0f608fd580b63c45c8e | 702,624 |
import string
def letter_extractor(raws):
"""letter_
Frequencies of 26 English letters in a given text, case insensitive.
Known differences with Writeprints Static feature "letter frequency": None.
Args:
raws: List of documents.
Returns:
Frequencies of English letters in the do... | 54dde1c58b7f5c59af313f11294483196ba917dc | 702,626 |
def crop_frames(frames, speaker):
"""
frames: (b h w c)
"""
if speaker == "chem" or speaker == "hs":
return frames
elif speaker == "chess":
return frames[:, 270:460, 770:1130]
elif speaker == "dl" or speaker == "eh":
return frames[:, int(frames.shape[1] * 3 / 4) :, int(fr... | 1d92d7f6ea62f26a8bfead47594681602f2051c4 | 702,627 |
def builddict(fin):
"""
Build a dictionary mapping from username to country for all classes.
Takes as input an open csv.reader on the edX supplied file that lists
classname, country, and username and returns a dictionary that maps from
username to country
"""
retdict = {}
for cours... | ddf9272e0da6616abd0495b7b159807a36a83dcc | 702,628 |
def get_reverse_depends(name, capability_instances):
"""Gets the reverse dependencies of a given Capability
:param name: Name of the Capability which the instances might depend on
:type name: str
:param capability_instances: list of instances to search for having a
dependency on the given Capab... | fda11bb01d6352b18e87365f1060f48a5c07f266 | 702,630 |
import collections
def node_degree_counter(g, node, cache=True):
"""Returns a Counter object with edge_kind tuples as keys and the number
of edges with the specified edge_kind incident to the node as counts.
"""
node_data = g.node[node]
if cache and 'degree_counter' in node_data:
return no... | 08c08f240e3170f4159e72bc7e69d99b69c37408 | 702,631 |
async def get_account_id(db, name):
"""Get account id from account name."""
return await db.query_one("SELECT find_account_id( (:name)::VARCHAR, True )", name=name) | 3dd6b46abd8726eb34eb4f8e1850dc56c3632e5c | 702,632 |
def params_to_payload(params, config):
"""Converts a set of parameters into a payload for a GET or POST
request.
"""
base_payload = {config['param-api-key']: config['api-key']}
return dict(base_payload, **params) | aec633ab62cf18c0acf685115d4e291cd6198cb3 | 702,633 |
from typing import Any
def is_a_string(v: Any) -> bool:
"""Returns if v is an instance of str.
"""
return isinstance(v, str) | f729f5784434ef255ea9b2f0ca7cdfbf726e7539 | 702,634 |
def historical():
"""" Retrieve stored data from datastore. """
return {
'page': 'historical',
} | 91933b3372e2972c37aaae2d8c83696e9398c19c | 702,635 |
import os
import re
def name_from_cmakelists(cmakelists):
""" Get a project name from a CMakeLists.txt file
"""
if not os.path.exists(cmakelists):
return None
res = None
# capture first word after project(), excluding quotes if any
regexp = re.compile(r'^\s*project\s*\("?(\w+).*"?\)',... | e18b214cbc4453f96989931ec9d4501cdbd1b718 | 702,636 |
import time
import json
import requests
def catch_distribution():
"""抓取行政区域确诊分布数据"""
data = dict()
url = "https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_area_counts&callback=&_=%d" %int(time.time()*1000)
for item in json.loads(requests.get(url=url).json()["data"]):
if item["area"] not ... | 4ce28940e9a3852a7622ceec489c186429fc9745 | 702,637 |
import sys
def extract_entity_text(text: str, offset: int, length: int) -> str:
"""
Get entity value.
:param text: Full message text
:param offset: Entity offset
:param length: Entity length
:return: Returns required part of the text
"""
if sys.maxunicode == 0xFFFF:
return tex... | 773426ffbf3cc186447594c9ddd50cd461c82316 | 702,638 |
def reconstructTypeFunctionType(typeFunction, args, kwargs):
"""Reconstruct a type from the values returned by 'isTypeFunctionType'"""
#note that our 'key' objects are dict-in-tuple-form, because dicts are
#not hashable. So to keyword-call with them, we have to convert back to a dict...
return typeFunc... | e57658bb7e4b368a8caf86a72db05157b689500e | 702,639 |
def str_to_dict(
text: str,
/,
*keys: str,
sep: str = ",",
) -> dict[str, str]:
"""
Parameters
----------
text: str
The text which should be split into multiple values.
keys: str
The keys for the values.
sep: str
The separator for the values.
Returns
... | 0b34ea1b47d217929fd9df760231f4786150e661 | 702,640 |
def keyset():
"""
Creates a set of numeric keys centered around 0
Provides a comparison function based on numeric closeness of the
keys
"""
class KeySet:
extent = 10
def __init__(self):
self.key = "0"
self.all = [self.key]
for i in range(KeyS... | ebdc08f13d9b82136042dae9b02206e4c6bb30d9 | 702,641 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.