content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert_to_one_hot(indices, num_classes):
"""
Args:
indices (tensor): A vector containing indices,
whose size is (batch_size,).
num_classes (tensor): The number of classes, which would be
the second dimension of the resulting one-hot matrix.
Returns:
resul... | b60caec3f3c1436c44453450a8c7a2a8c23241d6 | 624,539 |
def understand_input(input_: set[str]) -> dict[str, int]:
"""
Figures out which signal pattern corresponds to which digit
"""
digits: dict[str, int] = {}
five_segments: set[str] = set()
six_segments: set[str] = set()
one = ""
four = ""
for digit in input_:
match len(digit):
... | 421ef4aa54e7f197cafaf60fc4526e8384a34084 | 624,540 |
def sumar(n, m):
""" Operando: Sumar """
return n + m | 65041fc450f7e4688185b9f8486e94398194e834 | 624,541 |
def patch(program: list[int], noun: int, verb: int) -> list[int]:
"""Restore the gravity assist program
:param program: Intcode program
:param noun: updated noun value
:param verb: updated verb value
:return: patched Intcode program
"""
program[1] = noun
program[2] = verb
return pro... | 0822a15abb354f235e7a14ff05c255a2bc300af4 | 624,542 |
def build_json_response(status, value):
"""
Generate json format from input params
:param status: string
:param value: string
:return: json array
"""
return {
'status': status,
'message': value
} | 28785fabcf56af4e3a9b2172d6a4efc8718867cc | 624,543 |
import re
def parse_chains(chains):
"""Parses a given chains string returned from the MySQL DB
"""
## Turns "A:100:1:aa" -> "A", "100", "1", "aa"
## I.e.: chain_id = A, num_residues = 100,
## selected = 1/True, type = aa/amino acids
## NOTE:
## - aa = amino acid
## - na = nuc... | 6695eda3c8355345fa4251107fb282f11dc3ecb1 | 624,544 |
def mac_format(mac):
"""convert mac format to xxxx-xxxx-xxxx"""
if not mac:
return None
if mac.count("-") != 2:
return None
addrs = mac.split("-")
for i in range(3):
if not addrs[i] or not addrs[i].isalnum():
return None
if len(addrs[i]) < 1 or len(addr... | 7a0869e09b6cf07446a5249c6be46d1ed21e4de1 | 624,545 |
def _StoryToGtestFilter(story_name):
"""Returns a gtest_filter to run only tests generating data for |story_name|.
WebRTC perf tests story names and gtest names are different and use different
formats (e.g. snake case vs camel case). This function uses some heuristics
to create a gtest filter that will allow P... | c200aaf8d746dc41bd4fa053ec673321c4c931b9 | 624,546 |
import torch
def get_laplacian_kernel2d(kernel_size):
"""
Function that returns Gaussian filter matrix coefficients.
"""
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \
kernel_size <= 0:
raise TypeError("ksize must be an odd positive integer. Got {}"
... | 4f6747a356dd214b5e1142fe1fa18d407bd0f291 | 624,548 |
from pathlib import Path
import os
def _resolve_path(path):
"""Expand environment variables and :file:`~` in :kbd:`path` and resolve it to an absolute path.
:param path: Path of the directory/file to resolve.
:type path: :py:class:`pathlib.Path`
:return: :py:class:`pathlib.Path`
"""
path = P... | 7b67b3177f614da605f4b136c506fc6444859059 | 624,550 |
def get_short_title(title: str) -> str:
"""Get the short version of a text."""
titles = [title, title.split("\n")[0], title.split(".")[0]]
lens = [len(title) for title in titles]
short_titles = sorted(zip(lens, titles), key=lambda v: v[0])
return short_titles[0][1] | 72bb3476fcf4c97b14cc8c5f339de2675214419b | 624,551 |
def cache_name(doctype, processed):
"""returns cache key"""
suffix = ""
if processed:
suffix = ":Raw"
return "doctype:" + doctype + suffix | 2103e6dba3ebb2d8fc71b7cd71031c4ad603ea4f | 624,552 |
import os
def listmailcapfiles():
"""Return a list of all mailcap files found on the system."""
# XXX Actually, this is Unix-specific
if 'MAILCAPS' in os.environ:
str = os.environ['MAILCAPS']
mailcaps = str.split(':')
else:
if 'HOME' in os.environ:
home = os.environ... | 8c2ee601b7209083c58581bffd0c7e0e2f43ff50 | 624,553 |
def _transform_to_rc_coords(start, end, read_length):
"""Transforms the given start and end coordinates into the RC equivalents using the given read_length."""
return read_length - end - 1, read_length - start - 1 | c072a5992ba5cd11d16a30cdf9432a8c1f6bdb30 | 624,554 |
def usr_dtype(this_str):
"""usr_dtype: test for system `dtypes`"""
excluded = {'_root_', '_version_', '_text_', '_nest_path_'}
return not this_str in excluded | a5b7cc1d0158759ed6c93ffe82da64ca7d587509 | 624,555 |
def segment(*segments):
"""Select a (list of) segment(s)."""
vsegment = [t for t in segments]
return {"segment": vsegment} | 7c5e816ab721969eedad412bc9e5749af1259f2c | 624,556 |
import argparse
def create_basic_parse():
""" create the basic arg parses
:return object:
>>> parser = create_basic_parse()
>>> type(parser)
<class 'argparse.ArgumentParser'>
"""
# SEE: https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser()
parser.add_... | 7ab754ccb81c3d7e8539ca6850243f5ffa806888 | 624,557 |
def _var_names(var_names):
"""Handle var_names input across arviz.
Parameters
----------
var_names: str, list, or None
Returns
-------
var_name: list or None
"""
if var_names is None:
return None
elif isinstance(var_names, str):
return [var_names]
else:
... | f9887e46f0c6f836e84be1aabec4ead8b6f977f9 | 624,558 |
def get_partial_failure_messages(client, response):
"""Get a list of all partial failure error objects for a given response.
Shows how to retrieve partial_failure errors from a response message (in
the case of this example the message will be of type MutateAdGroupsResponse)
and how to unpack those erro... | 80da221ad810533ceb81797fcec56d12b41e552d | 624,559 |
def fast_zeta_transform(counts, size):
"""
高速ゼータ変換
ret[s]: sum of counts[t] (t ⊆ s)
https://qiita.com/Euglenese/items/260f9ddf513f772d7e42#本題
O(2^N * N); len(counts) == 2^N
:param list of int counts:
:param int size:
"""
assert (1 << size) == len(counts)
dp = list(counts)
for... | af3917b935295d1f3131af3f776eb118054a8df5 | 624,560 |
def is_full_slice(obj, l):
"""
We have a full length slice.
"""
return (
isinstance(obj, slice) and obj.start == 0 and obj.stop == l and obj.step is None
) | 775de65e50372153eaac9acf4d78b8275ff7c884 | 624,561 |
def _limit(query, hints):
"""Applies a limit to a query.
:param query: query to apply filters to
:param hints: contains the list of filters and limit details.
:returns: updated query
"""
# NOTE(henry-nash): If we were to implement pagination, then we
# we would expand this method to suppo... | b52a6476c598b54ec4b2cd34bb563ba16f91216a | 624,562 |
def get_power( df ):
"""
Creates a Pandas DataFrame containing the power of the JV curves.
:param df: DataFrame containing the JV curves.
Values are currents, index is voltage.
:returns: A Pandas DataFrame containg the power at each voltage index value.
"""
pwr = df.mul( df.index, axis ... | a45cca425971cf45dc48efc704a1019d37a578e1 | 624,563 |
from typing import Dict
def get_operating_json(json: Dict) -> Dict:
"""
Get operating in rawsec json.
Parameters
----------
json: Dict
rawsec json.
Returns
-------
Dict
operating dict.
"""
return json["operating_systems"] if "operating_systems" in json else {} | 3ff570d50305cce04b2c0b1a4eaef0511d5ffb13 | 624,564 |
def init_record(msg):
"""Initialize a TaskRecord based on a request."""
header = msg['header']
return {
'msg_id' : header['msg_id'],
'header' : header,
'content': msg['content'],
'metadata': msg['metadata'],
'buffers': msg['buffers'],
'submitted': header['date... | 1fbb3136354423acbb028d7a1c340d41faad555c | 624,566 |
import re
def template_token_subst(buf, key, val):
"""
Given a string (buf), a key (e.g. '@@MASTER_IP@@') and val, replace all
occurrences of key in buf with val. Return the new string.
"""
targetre = re.compile(re.escape(key))
return re.sub(targetre, str(val), buf) | 4ecf929203506223a66e634660bf259c441c7640 | 624,567 |
def validate_project(project):
"""Ensures the given project is valid for Cloud Pub/Sub."""
# Technically, there are more restrictions for project names than we check
# here, but the API will reject anything that doesn't match. We only check /
# in case the user is trying to manipulate the topic into posting som... | beee25a8bd7b3dc686dce9262993e45932467f1d | 624,568 |
def expand(dirs):
"""
Expands four directions per CSS convention.
`dirs` may be a four-element iterable of (top, right, bottom, left), or
a two-element iterable of (top-bottom, left-right), or a single-element
iterable or a plan value for all four directions.
@return
A `tuple` of top, ri... | eefe32892f2fee6f9b84f74ad7366868372dad25 | 624,569 |
def isint(x):
"""Test whether an object is an instance of int."""
return isinstance(x, int) | 4413f2cc4feca99914323e33afaf75401f9ac3cb | 624,571 |
import glob
def get_globfiles(fileglob, minfiles=1, maxfiles=1):
"""
Get file(s) matching ``fileglob``. If the number of matching
files is less than minfiles or more than maxfiles then an
exception is raised.
:param fileglob: Input file glob
:param minfiles: Minimum matching files (None => n... | 15318ed3c7c7c80f70295ca9a74d7fb6f5b299fd | 624,572 |
def is_at_least_one_not_none(*args):
"""
>>> is_at_least_one_not_none(1, 2, 3)
True
>>> is_at_least_one_not_none(None, 2, 3)
True
>>> is_at_least_one_not_none(1, None, 3)
True
>>> is_at_least_one_not_none(1, 2, None)
True
>>> is_at_least_one_not_none(1, None, None)
True
>... | 5239b68798b630e9a0508f85a4a5fb5678a68fda | 624,573 |
from typing import Any
from typing import Mapping
def is_mapping(obj: Any) -> bool:
"""Just a shorthand for instancecheck on :py:class:`typing.Mapping`.
"""
return isinstance(obj, Mapping) | 00d4312cf3e1bce1b663329ce880ea41926b5f24 | 624,574 |
import os
import re
def get_existing_library_album_paths(sorted_path: str, artist: str, suggested_album_title: str) -> list:
"""
Looks for possible existing albums in the library
:param sorted_path:
:param artist:
:param suggested_album_title:
:return:
"""
ret = []
artist_path = o... | de332f617a226fdc974c3d50720fe26312e3f75e | 624,575 |
def window_validator(value):
"""
Supported window values: 4, 8, 16
"""
if not value.isnumeric:
raise TypeError("Select a valid vlaue.")
elif int(value) in (4, 8, 16):
return int(value)
else:
raise TypeError("Select a valid vlaue.") | b4c2df1fe96894072310348dc048fcb5da51ae88 | 624,576 |
def _highest_error_only(errors):
"""Removes any duplicate concentrations that have lower errors.
This script take a list of errors and concentrations and returns
only the highest error for each concentration.
Parameters
----------
errors : list of lists of floats
A list containing [err... | ad2642e89b699ec400572d0f868858337fe66e25 | 624,577 |
def filterIQM(apidf, filter_list):
""" Loads the API info and filters based on user-provided
parameters. Filter parameters should be a list of strings
and string formats should be "(VAR) (Operator) (Value)".
Example: ['TR == 3.0'] or ['TR > 1.0','FD < .3']
Note: Each element in each... | bd75b1dfecc48db1cf75128183d414bf594abfa2 | 624,578 |
def remove_suffix_ness(word: str) -> str:
"""Remove suffix ness.
:param word: str of word to remove suffix from.
:return: str of word with suffix removed & spelling adjusted.
This function takes in a word and returns the base word with `ness` removed.
"""
return f"{word[:-5]}y" if word[-5] ==... | 1f869fb37aba84cffa29220ca8d898012c5103d3 | 624,579 |
def intersect(obs,pred):
"""
Return the input pair of dataframes (obs,pred) with a common index made up of the intersection of
the input indexes
"""
if hasattr(obs,'intersect'):
return obs.intersect(pred)
idx = obs.index.intersection(pred.index)
return obs.loc[idx],pred.loc[idx] | eb876be8f8a0177784a61ac262ec8298940d9208 | 624,580 |
from typing import Any
from typing import Iterable
def is_atom(entity: Any) -> bool:
"""Everything that is NOT an iterable(except strings) are considered atoms.
>>> is_atom("plain string")
True
>>> is_atom(1)
True
>>> is_atom([1, 2])
False
Added in version: 0.1.0
"""
... | 45014fdb6569fd2f273b21af7d9425638bd4746f | 624,581 |
def row_to_mapping(row, schema):
"""Convert a dictionary to a list for bigquery.Table.insert_data.
Silly. See https://github.com/GoogleCloudPlatform/google-cloud-python/issues/3396
"""
return [row.get(field.name, [] if field.mode == 'REPEATED' else None) for field in schema] | 2fc1c8470dda5a993f0862ca66d29f415f00a014 | 624,582 |
def find_name(slaves, name):
"""Function: find_name
Description: Locates and returns a slave's instance from an array of slave
instances.
Arguments:
(input) slaves -> List of slave instances.
(input) name -> Name of server being searched for.
(output) Slave instance or N... | 90be5b22b4d4fdd0a93e1df2abb6565933cdd10f | 624,583 |
def format(keyword: str, keyword_style: str) -> str:
"""Returns formatted keyword
Args:
keyword: target keyword
keyword_style: formatting style
Returns:
formatted keyword
"""
expected: str = keyword
if keyword_style == 'lower':
expected = keyword.lower()
if... | 0ec8a52be9fd62f92ba13659166b1ea06e1c2ec0 | 624,584 |
def trace2index_flat(shape, ntrace):
"""
Calculate the index of a trace assuming a flat structure
"""
# algorithm is to take quotient/remainders of sizes in reverse
q = ntrace # seed quotient with remained
index = []
for s in shape[:0:-1]: # loop from last size to 2nd size
q, r = d... | 80d9a4d6908c6963979991346bd91c6cd543f393 | 624,585 |
import socket
def get_hostname() -> str:
"""Returns the fully-qualified domain name of the server this code is
running on.
"""
return socket.getfqdn() | 8f2f65498a993c1034f26991369613d05c0bd083 | 624,587 |
import requests
import json
def get_ipaddr(url='http://httpbin.org/ip', proxy=None):
""" gets the external IP address """
if proxy:
proxy = 'http://{0}'.format(proxy)
proxies = {'http': proxy, 'https': proxy}
response = requests.get(url, proxies=proxies)
else:
response = r... | e8e6a531ad1e3de74e05f78db20d8fa71907c74c | 624,588 |
def ensure_divisible_by(feats, N):
"""Ensure that the number of frames is divisible by N.
Args:
feats (np.ndarray): Input features.
N (int): Target number of frames.
Returns:
np.ndarray: Input features with number of frames divisible by N.
"""
if N == 1:
return feat... | bb8da0adc85dcb6fec3f3dfc2aebef1a23156cf2 | 624,590 |
import json
def load_json(path: str) -> dict:
"""Get json schema to format from file.
Args:
path(str): path to json.
Returns:
(dict): db.
"""
with open(path, "r", encoding="utf-8") as file:
return json.load(file) | 32063ce9c5bf7be26d601aeeb247bc849fdfb889 | 624,591 |
import torch
def get_column(data: torch.Tensor, i):
"""get a column from a tensor.
Args:
data (torch.Tensor): a matrix
i (int): the index of column
Return:
column (torch.Tensor): a vector with a shape (:, 1).
"""
d = data.size(dim=-1)
x = data.view(-1, d)
retur... | f2019c092a5d79c807afd394e479a2544bbf7163 | 624,592 |
import requests
from bs4 import BeautifulSoup
def get_dates(season, info):
"""
returns list of dates in which matches were played in the season
"""
url = 'http://www.basketball-reference.com/leagues/NBA_{0}_games.html'.format(season.split('-')[-1])
rv = requests.get(url)
soup = BeautifulSoup(r... | 7e55ba0f80e07c3dbba0995468c07dce607036e4 | 624,593 |
def get_variables(interface):
"""Creates and returns dictionary of test variables.
:param interface: name of super-interface for the tested sub-interface
:type interface: str
:return: dictionary of test variables
:rtype: dict
"""
# basic settings
bd_name = 'bd_persist'
sub_if_id = 1... | 8051ce9e71d24fd44df4ea39c0c03b48b85c40b5 | 624,594 |
def get_table(table, expand=False):
"""
Return GRIB2 code table as a dictionary.
Parameters
----------
**`table`**: Code table number (e.g. '1.0'). NOTE: Code table '4.1' requires a 3rd value
representing the product discipline (e.g. '4.1.0').
**`expand`**: If `True`, expand output dicti... | 0b028cd5de28bcada1af86a2d1edf457f93cc05d | 624,595 |
def b(s):
"""Byte string with LSB first into an integer.
>>> b("1")
1
>>> b("01")
2
>>> b("101")
5
"""
return int(s[::-1], 2) | 3519d44ab4248d338590340bbb3d7c22e1d6619c | 624,598 |
def decode_qname(qname : bytes) -> str:
""" \x03www\x06domain\x03tld\x00 -> www.domain.tld. """
labels = []
while qname:
count = int(qname[0])
qname = qname[1:]
label = qname[0:count]
label = label
labels.append(label)
qname = qname[count:]
name = '.'.join... | 4dc3f4ba3f9091f2abe5f1aca63ac4c385eedb1f | 624,599 |
def add_points_to_skills(skills, embedding_2d):
"""Add x and y points from 2 dimensional skills embedding
to skills dataframe
Args:
skills (df): skills dataframe
embedding_2d (array): skills embedding with 2 dimensions
Returns:
df: skills dataframe with additional columns for x... | 82e699d940660164750802ebb3c8b8d98cc4be9b | 624,600 |
import math
def specify_significant_figures(float_value, num_sig_figs):
"""Round float_value to num_sig_figs significant figures."""
try:
# Find my_mult, my_exp such that float_value = my_mult*10^my_exp
# such that 1. <= my_mult < 10.
my_exp = math.floor(math.log10(abs(float_value))... | cec7b793401962cf04509c099f76c5f29389fc24 | 624,601 |
def duplicate(N, Elem):
"""
N = integer() >= 0
Elem = T
List = [T]
T = term()
Returns a list which contains N copies of the term Elem. For example:
> lists:duplicate(5, xx).
[xx,xx,xx,xx,xx]
Note: Function taken from Erlang -
http://erldocs.com/17.3/stdlib/lists.html#duplicat... | 57aa86a7e555485f61813b423389ea823327fc9c | 624,603 |
import torch
def confidence_mask(tensor: torch.Tensor, confidence: float) -> torch.Tensor:
"""
Returns the masked form of the input tensor with respect to given
confidence
Arguments:
tensor (torch.Tensor): tensor to be masked by confidence
confidence (float): confi... | 2c2117f343dbba63e0b6e29d82ed847e87b4285a | 624,604 |
import os
def delete_img(file):
"""DELETE THE DOWNLOADED MEME"""
return os.remove(file) | a1d2f8f6f5074bf412f205bfc52ace9859075646 | 624,605 |
def html_escape(s):
"""
转义特殊符号 "&", "<", ">"保证HTML安全
"""
if s:
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("(", "(")
s = s.replace(")", ")")
return s
else:
return... | 5d1bcc09c5ff225e136a2116112a2211dd9d0110 | 624,606 |
def slug_from_id(page_id: str) -> str:
"""Extract Notion page slug from the given id, e.g. lwuf-kj3r-fdw32-mnaks -> lwufkj3rfdw32mnaks."""
return page_id.replace("-", "") | 9f38ae38540666ca3b439852883390068924a2f4 | 624,607 |
def contains_memory(memoryrange, memory):
"""Returns True if the given `memory` is in `memoryrange`, False if not."""
for field, value in memoryrange.lower.ListFields():
if getattr(memory, field.name) < value:
return False
for field, value in memoryrange.upper.ListFields():
if ge... | 91133402ee4e150fde8bfa85e4c4a84363ef9c20 | 624,608 |
from random import randint
import numpy as np
def createRandomCompleteGraph(n, symmetric=False):
"""
create a complete symmetric graph with
random edge weight
"""
v = [i for i in range(1, n+1)]
e = []
M = [[0 for v1 in v] for v2 in v]
for ind1, i in enumerate(v):
ind2 = ind1+1
for j in v[ind1+1:]:
if... | d975fdfdd250585acf14dddcdebfdf0f106142b2 | 624,609 |
def add_imply_rule(config, fname, linenum):
"""Add a new 'imply' option to a Kconfig
Args:
config: config option to add an imply for (without CONFIG_ prefix)
fname: Kconfig filename to update
linenum: Line number to place the 'imply' before
Returns:
Message indicating the r... | b0d2b0fa9e64aed3d3681d94c725b1f2e5d48283 | 624,610 |
from typing import List
from typing import Optional
def distance(v1: List[int], v2: List[int]) -> Optional[int]:
"""
Determine the distance between two vectors, i.e. the number of positions in which their value differs.
:param v1: first vector
:param v2: second vector
:return: distance as describe... | 253a27d9df7edd5d281854fd9b24b0b498876cc5 | 624,611 |
def merge(a, b, *, replace=None):
""" Merges dicts and lists from the configuration structure """
if isinstance(a, dict) and isinstance(b, dict):
if not replace:
replace = set()
res = {}
for key in set(a).union(b):
if key not in a:
res[key] = b[ke... | 671b316b2567acf6f1e30437657e8c648c72729c | 624,612 |
def search_letter_in_pattern(pattern,letter):
"""
Search the letter inside in pattern if no converge return -1
"""
m = len(pattern)
count = 1
for i in range(m-1,-1,-1):
if letter==pattern[i]:
return count
count = count+1
return -1 | 1a53dc266134d81d32a6247478d8441325b8a5c1 | 624,613 |
import random
def random_image_size():
"""
Generate a random size for images
"""
return random.randint(250000, 80000000000) | 083c0d3ae42a25055e7784c66309f3fe3b86d635 | 624,615 |
def endswithoneof(inputstr, seq):
"""
Check if *inputstr* ends with one of the items in seq. If it does, return
the item that it ends with. If it doe not, return ``None``.
:param inputstr: input string
:param seq: sequences of items to check
:return: the item the the input string ends wit... | 7eef43bc6d33b973465ca2ceb07b8d08156a63a1 | 624,616 |
import yaml
def save_dict_as_yaml(input_dict, path):
"""
Save a dictionary to a YAML file.
Args:
input_dict: Dictionary which will be saved to file
path: Path to the YAML file which will be (over-) written.
"""
with open(path, 'w') as f:
return yaml.dump(input_dict, f) | 7bd52eb46d3367ac193554883ac131f60cd6ebf9 | 624,617 |
import yaml
import random
def get_random_subject(species='human'):
"""
Function to get a random data config file and subject for a given species.
Note: only human data are configured at the moment
Parameters
----------
species: str
'human', 'rodent', or 'nhp'
Returns
-------... | b5f03da80febc08339bda78e535d4a2a19bedbec | 624,618 |
def compute_fixed_point(g, x0, tol=1e-8, print_n=False):
""" Compute the fixed point of g(x). """
prev_x = x0
x = g(x0)
n = 1
while(abs(prev_x - x) > 0.5 * tol):
prev_x = x
x = g(x)
n += 1
if(print_n):
print("\tn = %d" % n)
return x | ab9c1ed68c15a692af49d34f446734a7be68c3a9 | 624,619 |
import math
def is_triangle_number(num):
"""Returns whether a number is a triangle number.
A triangle number n is one for which there exists an integer x with
n = (x^2 + x) / 2. Solving this quadratic equation gives
x = (-1 +- sqrt(1 + 8n)) / 2
which will be an integer if and only if 1 + 8n... | 3b0f10387ff3f67fd84e8d10a7fd74e12fbf2109 | 624,620 |
import argparse
def parse_args():
""" 동작에 필요한 arguments 설정 """
parser = argparse.ArgumentParser(description="Sequence prediction simple project arguments.")
parser.add_argument("--seed", default=1234, type=int, help="random seed value")
parser.add_argument("--n_epoch", default=30, type=int, help="num... | 8269754d90d6a0c057acca8bfb8a0a689cae0e94 | 624,621 |
def _user_get_full_name(user):
"""
Override regular get_full_name which returns first_name + last_name
"""
return user.profile.full_name if user.has_profile() else " ".join([user.first_name, user.last_name]).strip() | a1bd053ccd1b45ce891119f5e6804bca30e7e599 | 624,622 |
def tle_scientific_2_float(number):
"""
This method transforms a scientific suffix from the TLE format into a
string format that can be parsed into a float by Python. The format is the
following:
15254-5 = 0.15254 >>> 15254E-5
-333-3 = -0.333 >>> 333E-3
@param number String where the decim... | 9b82eb2b3832577b03433832f8b97bb85a2ae5a4 | 624,624 |
import shlex
import asyncio
import logging
async def run(cmd):
"""Fork shell and run command NOTE: Popen is non-blocking"""
cmd = shlex.split(cmd)
proc = await asyncio.create_subprocess_shell(" ".join(cmd))
await proc.communicate()
if proc.returncode != 0:
# This can happen because the NAT... | 437b0cb71432d1bd3632d9204fd25311b8774724 | 624,625 |
from datetime import datetime
def print_time(x):
""" Print the current
Description
-----------
Appends the current time into a print statement
Parameters
----------
x : String
A message to be printed
"""
ts = datetime.now().strftime("%y-%m-%d %H:%M:%S")
print(f"[{ts}]... | 11ba832fad817a91c40cee567721c1fdde37041d | 624,626 |
def _imshow_formater(arr):
"""Creates a formating function to show the values of imshow in the status
bar.
:param arr: Array to be shown
:returns: function formater(x, y) that should be set to ax.format_coord
"""
def format_coord(x, y):
col, row = int(x + .5), int(y + .5)
if (c... | 8ef4657c441a5c1ae565a2ebf1312eecd689095b | 624,627 |
import subprocess
def pipe(prev_proc, to_cmd):
"""
Pipes output of prev_proc into to_cmd.
Returns piped process
"""
stdin = None if prev_proc is None else prev_proc.stdout
process = subprocess.Popen(to_cmd,
stdout=subprocess.PIPE,
stdin=stdin)
if... | e968be473e97fb8b09d5eba9f8690b0c27662404 | 624,628 |
def matrixReshape(nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
A = [x for row in nums for x in row]
return [A[i*c:(i+1)*c] for i in range(r)] if c * r == len(A) else nums | 2589f6a37f4ebda7c1d23ce9505e9dc6c5b09e5d | 624,629 |
def _copy_dir_entry(workdir: str, user_id: int, user_group: int,
dirname: str) -> str:
"""Returns the Dockerfile entry necessary to copy a single extra subdirectory
from the current directory into a docker container during build.
"""
owner = "{}:{}".format(user_id, user_group)
return """#... | a9ae168d2bd350a8b8d6a9692e4baf661bec39ef | 624,630 |
import six
def _removeUniqueMetadata(dicomMeta, additionalMeta):
"""
Return only the common data between the two inputs.
Only work if all the data element are hashable,
this means not have any dict or list as properties
"""
return dict(
set(
(
k,
... | 5ace83e2f3de37896d893361c056e4229193d770 | 624,631 |
def list2row(worksheet, row, col, values, positions=None):
"""
Create header of the template xlsx file
:param Worksheet worksheet: Worksheet class to write info
:param int row: Row number to start writing
:param int col: Column number to start writing
:param list values: List of ... | 140dcf9c375b3bd73baa01e513b165e61862cedb | 624,632 |
def draw_boyer_moore():
"""Solution to exercise R-13.4.
Repeat the previous problem for the Boyer-Moore algorithm, not counting
the comparisons made to compute the last(c) function.
---------------------------------------------------------------------------
Solution:
--------------------------... | c6bed0496de0b2f35090b30042ec4421ee81423d | 624,633 |
import copy
def bg_job_ids(job_dict):
"""A list of job IDs"""
dict_copy = copy.deepcopy(job_dict)
return [str(dict_copy["id"])] | 684a41ac7b03081735004fbc43b7798410489094 | 624,634 |
def lambda_combine_sent(sentences):
"""
lambda function in pandas to combine sentences that are tokenized
"""
new_sentences= ''
for sentence in sentences:
new_sentences = new_sentences + sentence + ' '
return new_sentences | a62e196fb0a0647f8c89c882bda2e5b513008be7 | 624,635 |
def thumbnail(value, size):
"""
Get the thumbnail of 'size' of the corresponding url
"""
return value.replace('.jpg', '.' + size + '.jpg') | 89e8835b47a2917793c3407780fd92067d4ae67f | 624,636 |
import math
def nan_interpolate(data):
"""Remove all the NAN values
If NANs exist. If it is the first element, replace it with the value behind
If it is the middle element, replace it with the average
If it is the last value, replace it with the previous value
Args:
data (ndarray): the d... | 9de092a9fb45e80ae9d30ce7593ffdf39d478b69 | 624,638 |
import os
def make_video_from_frames(
frames_dir: str, video_path: str = "", in_fps: int = 30, out_fps: int = 30
) -> int:
"""Make video from frames in frames_dir.
Args:
frames_dir (str): Path to directory containing frames.
video_path (str): Path to output video file.
in_fps (int... | e78c4176b05f52b7948a9a199351f44ef5faaf3a | 624,639 |
def collatz_sequence_length(starting_value: int) -> int:
"""
Given solution relies on just calculating the length, which takes out the longer and more
expensive collatz calculation that requires storing the sequence. Passing the integer parameter
is cheaper than storing, appending, and passing a list da... | 6647038f06a794de9e8dbbeed7d9dca753f166f1 | 624,640 |
import re
def get_ex_poly(polyhedra_list, species_tag):
"""
:param polyhedra_list: (list of Polyhedra) list of all Polyhedra in the super cell structure
:param species_tag: (String) name of species given by a connectivity matrix; may contain the cation site number
appended to the species name
:re... | 8f53bea86b17ba6a367c81ba09823bf8138bf6bf | 624,641 |
def has_admin_privileges(user):
"""Return whether the specified user has admin privileges."""
# Finding this is the point of the challenge...
return user["position"].lower() == "admin" | b81f0c4faf69ae60ba7f5d43084c09fdf6f7c90f | 624,643 |
import csv
def load_urls(src):
"""
Load given url file csv into memory.
It assumes that only two columns are present. One is key, other is value.
"""
with open(src) as f_h:
data = csv.reader(f_h, delimiter=",")
return dict((int(row[0]), row[1]) for row in data) | 552b17cab44a2a2d0793b56f4ba39261634b0d89 | 624,644 |
def _is_num(x):
"""Return: True if x is an int or float"""
return type(x) in [int,float] | 4d1e41ccd2017e71853db3fe1eb85a7384c4e9f0 | 624,646 |
def strftime(datetime, formatstr):
"""
Uses Python's strftime with some tweaks
"""
# https://github.com/django/django/blob/54ea290e5bbd19d87bd8dba807738eeeaf01a362/django/utils/dateformat.py#L289
def t(day):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'r... | bc748022e5e85c52c70f781c2c5b3bdfdaa1ecc6 | 624,647 |
def get_heart_rate(message_fields):
""" get_heart_rate
return the heart rate as float from a message.as_dict()['fields'] object
Args:
message_fields: a message.as_dict()['fields'] object (with name 'record')
Returns:
heart rate in bpm or 50. if not found
"""
for message_field i... | e28f004e14fa0711c24f0ccdf79c83408e58cf04 | 624,649 |
import os
def parent_dir(path):
"""
:param str path: Path for which the parent directory should be
retrieved.
:return: Parent directory path. An empty string is returned if the
provided path is the root directory.
:rtype: str
"""
parent_path = os.path.abspath(os.path.join(path... | b0577976abca6eced8684f0dd6a51ad8e8207bf4 | 624,650 |
def dataset_relationship_type(dataset_object):
"""relationship_type for the related_item depending on the dataset_type"""
if dataset_object.dataset_type:
if dataset_object.dataset_type == "prev_published_datasets":
return "references"
if dataset_object.dataset_type == "datasets":
... | eeffebc0b644ca5a64eba7009d4494d650f1ac0f | 624,652 |
def product_composite_iterator(base, handle, callback, include_top=False):
"""
A function to walk through an osaka product enabling handling of
coposite childeren. Note: if not a composite product, nothing happens.
@param base: base of the product
@param handle: handler for the backend
@param ca... | aad47ebb0a68696afb090f80e33c2e2d012edc93 | 624,653 |
import json
import sys
def read_config(filename):
"""
Read in config json file
:param filename: name of the config file
:returns: a dictionary with the config
"""
try:
with open(filename, 'r') as json_config:
config = json.load(json_config)
except EnvironmentError as e:... | 19ccf9d2f7718e2be4d1b838f952ee68475b6cf0 | 624,654 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.