content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _print_behind_ahead(behind, ahead):
""" Print Behind Ahead """
numcommits = ""
if behind:
numcommits += "-" + str(behind)
if behind and ahead:
numcommits += "/"
if ahead:
numcommits += "+" + str(ahead)
return numcommits | 816e761a7d31d41b13b32db4eb01e7ee8040087b | 698,845 |
def precprint(prec_type, prec_cap, p):
"""
String describing the precision mode on a p-adic ring or field.
EXAMPLES::
sage: from sage.rings.padics.misc import precprint
sage: precprint('capped-rel', 12, 2)
'with capped relative precision 12'
sage: precprint('capped-abs', 11... | b3eab5f0fd133ead8c413aded650d839a2c818b9 | 698,846 |
def zooms_string(z1, z2):
"""Prints 'zoom N' or 'zooms N-M'."""
if z2 != z1:
return "zooms {}-{}".format(min(z1, z2), max(z1, z2))
else:
return "zoom {}".format(z1) | 2e433472d721767cfc152b75a74f9976ba340f7a | 698,848 |
def collect(group, p, barrier_token):
""" Collect partitions from partd, yield dataframes """
return p.get(group) | d3824864defbdec8b1712483b7b1e41ef7941268 | 698,849 |
def ret_schema():
"""Defines dictionary of schema."""
schema = {
('path to directory', str, 'path'): ('path', str, '/apps/homefs1/.*'),
('dict of stocks', str, 'stocks'): {
('ticker', str, '[A-Z]*', '+'): {
('stock price', str, 'price'): ('price', float),
... | 83c66bc000a471ff0787eb98a1a8b4146b628911 | 698,850 |
import os
def files_and_folders(dir_path="."):
"""Return a dict containing a sorted tuple of files and a sorted
tuple of folders"""
f_and_f = os.listdir(dir_path)
folders = [f for f in f_and_f if os.path.isdir(os.path.abspath(f))]
files = set(f_and_f) - set(folders)
return {
"files": t... | 3858d603acd208de0e81667fcd8ad79a9ea590e7 | 698,851 |
def _imag_2d_func(x, y, func):
"""Return imag part of a 2d function."""
return func(x, y).imag | b95f64fb2bca54db89c85349ed3ca961d2b47b4c | 698,852 |
def save_config( bkp_config, config_file, for_restart = False ):
""" save the configuration to the file object passed as a parameter """
print("bucket =", bkp_config["bucket"], file=config_file)
print("dirs = ", ";".join(bkp_config["dirs"]), file=config_file)
print("exclude_files = ", bkp_config["exclud... | a4894cf29a44200442c6fb32b59eab9aefb5352c | 698,853 |
def index(l, val, default=-1):
"""
find the index the val in list
:param l: index list
:param val: value to find index
:param default: default value to return that value not in list
:return: value index in list
"""
try:
getattr(l, 'index')
except:
raise TypeError('ipn... | 6c953b278cb65451879bbde19dfd4392a034b36f | 698,854 |
from typing import OrderedDict
def dict_order(_dict):
"""Controls the print order of the dictionary
"""
new_dict = OrderedDict()
new_dict['name'] = _dict.get('name')
new_dict['type'] = _dict.get('type')
new_dict['conditions'] = _dict.get('conditions')
new_dict['scopes'] = _dict.get('scopes... | a4ed107403289093065ce169d549dda88b5dee5c | 698,856 |
def batch_directions(z, y, Q, path_sizes, step_vals, subtract_projection=True):
"""
This function takes an input batch of z vectors (and corresponding class label vectors y)
and applies the directions in Q to the batch of z vectors.
:param z: (N, nz) tensor of base random noise to manipulate with direc... | 4adeab5b8a9ded7b4a10affbb5427435dbd5a599 | 698,857 |
def update_tax_nodes(nodes, tax):
"""
nodes can be a list of strings: taxids or names or a list of tuples with (rank, taxid/name)
Return a dictionary mapping nodes and updated nodes (or None)
First look for id, if nothing found, lookup by unique name
"""
updated_nodes = {}
for node in nodes... | 7d292ddf43e39280e699f76765079799f61dc0dc | 698,858 |
def value_formating():
"""Format a value with the underlying format function."""
happy_value = type('HappyFormater', (object,), {
'__format__': lambda _, template: template.replace('lol', '(^_^)')})()
return "{:lol}".format(happy_value) | a637bace1337d73658eb667bc3eafc866e5cd9ba | 698,859 |
import json
def _CanParseJSON(my_json):
"""Returns True if the input can be parsed as JSON, False otherwise."""
try:
json.loads(my_json)
except ValueError:
return False
return True | c8602b9e9544a70102135bd875d19c66664bdefc | 698,860 |
import csv
def write_csv(f, items):
"""
:type items: list[OrderedDict]
"""
if len(items) == 0:
# nothing to write
return f
fieldnames = items[0].keys() # this works as expected because we use OrderedDicts
writer = csv.DictWriter(f, fieldnames)
writer.writeheader()
f... | 1cabe109bb42e892cc85b40bc6c6930987c042ee | 698,861 |
import json
def get_brawl_cookie(request):
"""
Get brawl cookie
"""
return json.loads(request.cookies.get('brawl') or '[]') | e9264476a44bebfa9a43106678d1653ba86e555d | 698,862 |
import torch
def label_smoothed_nll_loss(
lprobs: torch.Tensor, target: torch.Tensor, epsilon: float, ignore_index=None, reduction="mean", dim=-1
) -> torch.Tensor:
"""
Source: https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/label_smoothed_cross_entropy.py
:param lprobs: Log-probab... | 5c85297cda97746413c747fe10fae1ecaa16dea9 | 698,863 |
def select_latest(engine, ticker, time_x):
"""
获取离time_x最近的一个
:param engine:
:param ticker:
:param time_x:
:return:
"""
sql = 'select price,adj_factor from security_lookup_cn_wave_10 where ticker="{}" and time_x<="{}" ORDER BY time_x desc limit 1'.format(
ticker, time_x)
rs_s... | d33d817afdf58407c9e4ecb66ed9f43e9de6128a | 698,864 |
from typing import Union
import json
def prettify(data: Union[list, dict]) -> str:
"""
Return input data structure (list or dict) as a prettified JSON-formatted string.
Default is set here to stringify values like datetime values.
"""
return json.dumps(data, indent=4, sort_keys=True, default=str) | 800ef5d3f7a5765bca6fe42fc32e40da5a1cc398 | 698,865 |
def power_series(z, cs):
"""
returns cs[0] + cs[1] * z + cs[2] * z ** 2 + ... + cs[-1] * z ** (len(cs) - 1)
"""
s = cs[-1]
for c in reversed(cs[:-1]):
s *= z
s += c
return s | a9fe54d8a4bc15385f5c1da61eb1696b43a470d4 | 698,866 |
def normalize(signal):
"""Restrict the range of a signal to the closed interval [-1.0, 1.0]. """
normalized_signal = signal / max(signal.max(), signal.min(), key=abs)
return normalized_signal | d86fe058302ee133e6318f5c0a3fa24430e7e24c | 698,867 |
from pathlib import Path
import os
import hashlib
def pseudo_hash(path: Path, string: str = "") -> str:
"""Compute a pseudo hash based on :
- The file size
- The file last modification date
- A given string
(Real hash is too long to compute for big file.)
"""
string = "-".join([str(os.pat... | 10bdf79dfcb78bead4ec8f9b165496b977ce2e81 | 698,868 |
def remove_non_ascii(s):
"""
Remove non-ascii characters in a file. Needed when support for non-ASCII
is not available.
Args:
s (str): Input string
Returns:
String with all non-ascii characters removed.
"""
return "".join(i for i in s if ord(i) < 128) | 0a215ffa1841667d7dd7d9c1d9a12bbe84e2cbcd | 698,869 |
def generate_streak_matrix(weeks_data):
"""
Create the streak matrix
1 if the user committed
0 if the user hasn't committed
-1 to store null values
:param weeks_data: week-wise contribution data of the user
:return: matrix containing the values of the contribution streak
"""... | e6cc9e3c96aebb20ca8af11ae19e7f86aab96d62 | 698,870 |
def any_in_seq(search_vals, seq):
"""Check if any value in search_vals in the sequence seq"""
for v in search_vals:
if v in seq:
return True
return False | d314355aef2cba89833394ff6aeacf675daec7e6 | 698,871 |
def date2season(dt):
"""converts datetime to season like 2008/2009"""
y = dt.year
if dt.month <= 6:
return "%s/%s" % (y - 1, y)
else:
return "%s/%s" % (y, y + 1) | e8653264fb682c0c2e5ceeb0548f513e0af0eb33 | 698,872 |
def limit(self, *args, **kwargs):
"""
Calls :meth:`.Table.limit` on each table in the TableSet.
"""
return self._proxy('limit', *args, **kwargs) | 40b22ac87d582d6e245bb3ed2ba6d60766ec0870 | 698,874 |
import json
def get_json_file(path):
"""
Load a JSON file from disk.
"""
with open(path) as f:
data = json.load(f)
return data | acb099868c4baeb59ead76bb20018af477720609 | 698,875 |
def can_use_slay(user_id):
"""Return true if the user can use the command "slay"
Characters that can slay:
- All characters (to allow for fake claiming)
"""
return True | f8be6bd59c1c8bb8acb12d164c7b452c6ede1308 | 698,876 |
def get_emojis():
"""Retrieves hundreds of emoji glyphs derived from the UTF-8 character table.
Examples:
>>> moji = get_emojis()\n
>>> moji[1540:1547]\n
'🤠 🤡 🤢 🤣'
"""
emoji_list_1 = [chr(i) for i in range(127744, 127994)]
emoji_list_2 = [chr(e) for e in range(128000, 12... | 2ba1401ac5a2b326f56fc29fa91cd638e27c5426 | 698,877 |
def Floyd(G):
"""Returns the length of paths from all nodes to remaining nodes
Parameters
----------
G : graph
weighted graph
Returns
-------
result_dict : dict
the length of paths from all nodes to remaining nodes
Examples
--------
Returns the length of p... | 9fc9102225bf5273ff5a507b14ef2d8d679b2223 | 698,879 |
def format_datetime(session):
"""Convert date or datetime object into formatted string representation.
"""
if session.data is not None:
date_format = session.field.opts.date_format
if date_format == 'iso8601':
session.data = session.data.isoformat()
else:
sess... | 53a99843e47dde6b82cb48e77fd553bbf65dd646 | 698,881 |
def train_step(model, optimizer, loss_fn, conditions, true, out):
"""One training step
Args:
model: the feed-forward network
optimizer: the optimizer for the network
loss_fn: the loss function
conditions: the observing conditions used as inputs
true: the true galaxy ... | 8d9ba730582e1d7992bf2bd2f8359f4531392645 | 698,882 |
import torch
def get_concentrated_mask(class_weights, topk):
"""
Returns a logical mask indicating the categories with the top k largest
probabilities, as well as the catogories corresponding to those with the
top k largest probabilities.
Parameters
----------
class_weights : torch.Tensor... | 8663c6e4d868eb2100684132ef95c59eee9b3560 | 698,883 |
import os
import sys
import shutil
def main(loc=None, excluded=[], silent=False):
"""Sorts files into categories.
Sorts each file (excluding itself), according to its extension, into folders
created for each category. New files are moved, existing files are
overwritten.
A summary is printed ... | 8fd380b66844a7ff0a2f0dfb27464246730e3bc1 | 698,885 |
import re
def get_params(rule):
""" Returns params from the url
Args:
rule (str): the endpoint path (e.g. '/v1/data/<int:id>')
Returns:
(list): parameters from the endpoint path
Examples:
>>> rule = '/v1/random_resource/<string:path>/<status_type>'
>>> get_params(rul... | 05414d950a6a603ff79fa2efff3ff3fef1e375f2 | 698,887 |
import json
import os
def get_bait_name(input_config: str):
"""Get the bait name from case config
Args:
input_config: Path to config
Returns:
bait: string
"""
with open(input_config) as f:
load_config = json.load(f)
# Read the config file and return the bait nam... | 840c9e578f77ef18d3170d8cd5300a1e8055885b | 698,888 |
def reset_var():
"""reset vars"""
return [], [], True | 3d78de5df772f60e0331a95d9ca14f46d1d36071 | 698,889 |
def upstream_or_distgit_path(
request, upstream_and_remote, distgit_and_remote, ogr_distgit_and_remote
):
"""
Parametrize the test to upstream, downstream [currently skipped] and ogr distgit
"""
return {
"upstream": upstream_and_remote[0],
"distgit": distgit_and_remote[0],
"o... | 6f94a44e95301398c495dff56f9e470b46b5c737 | 698,890 |
def dotProduct(d1, d2):
"""
@param dict d1: a feature vector represented by a mapping from a feature (string) to a weight (float).
@param dict d2: same as d1
@return float: the dot product between d1 and d2
"""
if len(d1) < len(d2):
return dotProduct(d2, d1)
else:
return sum(... | 65892f62f3c9d1ec13a62427aaafa7831a8ee1e5 | 698,891 |
def input_data():
"""Input data (as coming from the view layer)."""
return {
"metadata": {"title": "Test", "type": {"type": "test"}},
} | 7a8bb2b82ee4754b2ee8b535c76a23ca5695c237 | 698,892 |
def bitvec_number(x):
"""Return number represented by given bitve"""
return sum(x << (32 * i) for i, x in enumerate(x.data[0:x.size])) | ad393d4f30d9fef35f089491a7c59faca3ec6610 | 698,894 |
def garfield_empty_mock(url, request) -> str:
"""
Mock HTTP empty response using HTTMock
:param url: str
:param request: Request
:return: str
"""
return """
<html>
<body></body>
</html>
""" | c2c349e40f315bfc625680fc5b0e92a7a54f5f7c | 698,895 |
def check_order(order):
"""
Checks the specified drawing order is valid and returns the corresponding
tree traversal order.
"""
if order is None:
order = "minlex"
traversal_orders = {
"minlex": "minlex_postorder",
"tree": "postorder",
}
if order not in traversal_o... | c8478bbbb59ce25beec4a4196dc183a49ecb62ba | 698,896 |
def get_total_num_women(dataframe, fil):
"""Counts total women in category
Returns:
[list] -- total number of women, total number in category
"""
total = 0
matched = 0
for index, row in dataframe.iterrows():
if fil(row):
total += 1
if row["gender"] == "F"... | 478046f1f7bb62280f36df50b50c537dba2eb063 | 698,897 |
def get_cat2id(item_metas, n_entities):
"""Extracts all categories from item metada and maps them to an id"""
categories = set([cat for it_meta in item_metas for cat in it_meta.categories])
return {cate: n_entities + i for i, cate in enumerate(categories)} | 38c7895949d3eccf9d8d4fc6c609b036700f93d8 | 698,898 |
def add_acids(EP, amino_acids):
"""
The function check that all alpha amino acids in sequence,
else add this monomers.
Parameters
----------
EP : dict
Variants of peptide sequences.
amino_acids : list
List of alpha amino acids.
Returns
-------
EP : dict
C... | 45027c8b38c97da4af677e79af0c302539d8b747 | 698,899 |
def identify_target_ligand(ligand_residues):
"""Attempts to guess the target ligand"""
# If there is only one target ligand then that must be the target
# even if there are multiple instances. That could be the case if
# the compound is peptidic for example.
if len(ligand_residues) == 1:
ret... | 50e3559b2f42aa1a60ca5270279cc2a37325f3cb | 698,900 |
def Recherche(tree, word):
"""Recherche le mot word dans l'arbre tree et indique s'il est dans l'arbre."""
return tree.contains(word) | f17d4024b0e5e7542fec0a502f853fdb63a21c95 | 698,901 |
def fix_IE_for_attach(request, response):
"""
This function will prevent Django from serving a Content-Disposition header
while expecting the browser to cache it (only when the browser is IE). This
leads to IE not allowing the client to download.
"""
useragent = request.META.get('HTTP_USER_AGENT... | b8fd12ba12a2f7df918a3e0fa7c64094c0bd016d | 698,902 |
def to_dict(arr):
"""
Convert a list to a dict with keys drawn from '0', '1', '2', ...
Examples
--------
>>> to_dict([2, 3, 4]) # doctest: +SKIP
{'0': 2, '1': 3, '2': 4}
"""
return dict(zip(map(str, range(len(arr))), arr)) | a51c0cbb477b4569a67fda3088a200194bb8bf67 | 698,903 |
def is_power_of_two(a):
"""Return whether the argument, cast to int, is a power of 2."""
a = int(a)
# Bit manipulations. A power of 2 has a bit represetenation like 0...010...0.
# For such a number subtracting 1 from it turns it into 0...001...1, so ANDing
# a-1 and a should yield 0.
return a > 0 and ((a - ... | d7b0d90df8eb4287a6f56e8256aa6c40b9b46441 | 698,904 |
from typing import Callable
from functools import reduce
def clean(text: str, *cleaners: Callable[[str], str]) -> str:
"""Cleans the given text using the provided cleaning functions.
Arguments:
text:
The text string to be cleaned.
cleaners:
The simple cleaner functions... | 67a53637bca0b19b49bd157ccc520d8dc053a12f | 698,905 |
def strip_parens(text):
""" strips parenthesis from a string (works with nested parentheses)
note that this method will leave the extra spaces behind, but this will not affect tokenization
:param text: original string
:return: text stripped of parenthetical words
"""
left_parens = []
... | 1976636150bc6705e39ab3929e1214f0b0c09644 | 698,906 |
def variable_name_to_title( variable_name, latex_flag=True ):
"""
Translates a variable name into a title suitable for inclusion in Matplotlib
title strings. Variable names are assumed to be lowercased as found in IWP
datasets and titles may include LaTeX markers for mathematical typesetting.
Unkno... | 3f9d56a13f4aacb2ec6e9cf15ad1d2ff1c4288bc | 698,907 |
import builtins
import sys
def _str_type_to_type_annotations_dict(annotations_dict: dict):
"""
When getting the annotations, they return as a string representation of the type.
However, we need the actual type.
This function will take the annotations dict with the string type and turn it to
the ty... | 346b1f12271d78aa588e5f0649e97ac819fd7351 | 698,908 |
import os
def get_editor():
"""return the editor command or raise Exception:
look in the environment for either EDITOR, GIT_EDITOR or SVN_EDITOR
if not found, raise error EDITOR needs to be set in the env
"""
found = os.environ.get('EDITOR',
os.environ.get('GIT... | 99aaba84f42c176b6f8d8b10479527f4f01931ec | 698,909 |
def fix_filter_query(filter):
"""
fix filter query from user
Args:
filter: filter from users
Returns:
dict
"""
if filter:
try:
filter = {
_.split("=")[0]: _.split("=")[1] for _ in list(
set(
str(filt... | 11dce2c8471205118277bb396ec298de7fb7bf67 | 698,910 |
def rectangle_area(length, width):
"""
Calculates the area of a rectangle.
:param length: The length of the rectangle.
:param width: The width of the rectangle.
:return: The area of the rectangle.
"""
return length * width | 0cbe453fbd4c3c6a061f520d57f303dae55fdc25 | 698,911 |
def has_level_five(line):
"""Check if we need to explode"""
count = 0
for c in line:
if c == '[':
count += 1
if count > 4:
return True
elif c == ']':
count -= 1
return False | 6d2e9d4aed708a9d71a9f01f90519f804e1fd3d9 | 698,912 |
def threshold_array(arr, threshold=2e-4):
"""
Thresholds an array, returning a binary array
Parameters
---------
arr : NumpyArray
Contains the data to threshold
Returns
---------
NumpyArray
Returns arr with binary values, depending of the threshold
"""
return (ar... | 254692de4f82dbf6c3e684b10324cb73c436ff28 | 698,913 |
def __binary_search(arr, f, g):
"""
Perform the binary search in order to find the minimum feasible value of ``c`` inside ``arr``.
:param arr: The array on which to perform the binary search.
:param f: Function to be applied to ``g`` and ``arr[mid]`` (``check_th7`` or ``feas``).
:param g: A Network... | 415528fd46a33d1efe8d736717ac8b041d34c5d7 | 698,914 |
def _current_window_for_event(event):
"""
Return the `Window` for the currently focussed Buffer.
"""
return event.app.layout.current_window | 4b9859c7bf7fc4b072362d2d5b9e896022769587 | 698,915 |
import re
def clean_xml(xml):
"""Clean the given XML string of namespace definition, namespace
prefixes and syntactical but otherwise meaningless differences.
Parameters
----------
xml : str
String representation of XML document.
Returns
-------
str
String representat... | 3f566975ab512ccc22824c45e7ef04fc861a5c03 | 698,916 |
import torch
def _make_orthogonal(A):
""" Assume that A is a tall matrix.
Compute the Q factor s.t. A = QR (A may be complex) and diag(R) is real and non-negative
"""
X, tau = torch.geqrf(A)
Q = torch.linalg.householder_product(X, tau)
# The diagonal of X is the diagonal of R (which is always ... | ad2cfaa0c041062c8628bc02faedcfdbc550f4bb | 698,917 |
def weighted_average(gini_or_entropy_left, left_cnt, gini__or_entropy_right, right_cnt):
"""
calculate weighted average for Gini index or Entropy
:param right_cnt: count of total records on the right side of node
:param left_cnt: count of total records on left side of node
:param gini_or_entropy_le... | 7914a0164427de4e9cebf7637dda670694f8df59 | 698,918 |
import torch
def concat_entities(entities):
"""
Concat multiple graphs via concatenation of their entities tensors.
Parameters
----------
entities: a list of graph tuples.
Either [(v,e,c),...] or [(v,e),...] when the graph has no global attribute.
Returns v,e,c - concatenated entities... | 06d0619836d4cb8c977028ee0cdccd9075136c72 | 698,919 |
def filter_out_installed_pkgs(event_out_pkgs, installed_pkgs):
"""Do not install those packages that are already installed."""
return {p for p in event_out_pkgs if (p.name, p.modulestream) not in installed_pkgs} | 16fb8f68372fb070869a744b15ddce0ed6591887 | 698,921 |
import os
def is_using_wayland() -> bool:
"""Check if we are running on Wayland DE.
Returns
[bool] -- {True} if probably Wayland
"""
return "WAYLAND_DISPLAY" in os.environ | 2c361ecdada0dfb55101cb0e06290d7033bcfbf1 | 698,922 |
def truedicts(all):
"""
Generates a pair of dictionairies containg all true tail and head completions.
:param all: A list of 3-tuples containing all known true triples
:return:
"""
heads, tails = {(p, o) : [] for _, p, o in all}, {(s, p) : [] for s, p, _ in all}
for s, p, o in all:
... | 03c126ff6cdc0cc14be1c64a91e8164e890c2f2d | 698,923 |
import math
def RotateXY(x, y, xc=0, yc=0, angle=0, units="DEGREES"):
"""Rotate an xy cooordinate about a specified origin
x,y xy coordinates
xc,yc center of rotation
angle angle
units "DEGREES" (default) or "RADIANS"
"""
x = x - xc
y = y - yc
# make angle clockwise (l... | 68d24bfd5b2cf436b1ea37c0d4124f6cfa357e9f | 698,924 |
def _extract_gpcrdb_residue_html(txt):
"""
Extracts the relevant lines for all residues from a GPCRdb html entry.
Parameters
----------
txt : str
Content (html) of the website with the GPCRdb entry.
Returns
-------
residue_html : list
A list in which... | 4621848f27b9cd24017ed5c49683bfc4b8a180e8 | 698,925 |
def seq2set(xs) :
"""
bijection from sequences to sets
"""
rs=[]
s = -1
for x in xs:
sx=x+1
s+=sx
rs.append(s)
return rs | b90ec731ce35539240c43d4c616889f71ca7c982 | 698,926 |
def simple_tag_without_context_parameter(arg):
"""Expected simple_tag_without_context_parameter __doc__"""
return "Expected result" | aad64452d051a587447696c6bd616b04f3f5b23e | 698,927 |
import re
def uuid(value: str):
"""
Validator for Universally unique identifier
Example Result:
[123e4567-e89b-12d3-a456-426655440000,
6a2f41a3-c54c-fce8-32d2-0324e1c32e22]
Detail: https://en.wikipedia.org/wiki/Universally_unique_identifier#Format
"""
_uuid_pat = r'[0-9a-fA-F]{... | 66f498669b52df2e3ff9ea281fb781cb6774c77c | 698,930 |
from typing import Tuple
from typing import Dict
def field_annotations(typed_dict) -> Tuple[Dict[str, type], Dict[str, type]]:
"""Return the required and optional fields in the TypedDict."""
return (typed_dict.__annotations__["required_fields"].__annotations__,
typed_dict.__annotations__["optional... | 2e88481a1668cd40caacb8bfc91a50c8746a704e | 698,931 |
import os
def get_config_log_dir():
"""
Retrieve logging directory, create it if it doesn't exist.
"""
log_dir = os.path.expanduser(os.path.join(u'~', u'.mssqlscripter'))
if (not os.path.exists(log_dir)):
os.makedirs(log_dir)
return log_dir | dd30794544f19083b74635d2a4c82621f2fd16ba | 698,932 |
import sqlite3
def get_member_data(member_id: str, conn: sqlite3.Connection) -> dict:
"""
Gets email and phone data from database based on passed member.
This function uses placeholders in query so it is injection safe.
Look up get_member_data_injection for example where it's NOT injection safe.
"... | a4ca505961352e292109e22318ff7a0188ffc454 | 698,933 |
def node_short_name(node, **kwargs):
"""
Returns short name of the given node
:param node: str
:return: str
"""
return node | 67d1d5ff172544eb2b233a925d90bbd0ea767e83 | 698,934 |
def create_notify_payload(host, nt, usn, location=None, al=None, max_age=None, extra_fields=None):
"""
Create a NOTIFY packet using the given parameters.
Returns a bytes object containing a valid NOTIFY request.
The NOTIFY request is different between IETF SSDP and UPnP SSDP.
In IETF, the 'location... | 95b6a7ad37ec96d646116451340ed7ee96495632 | 698,935 |
import math
def runs(bit_str: str):
"""Runs Test
Determine whether the number of runs of ones and zeros of various
lengths is as expected for a random sequence.
See section 2.3 in this NIST publication:
https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=906762
"""
n = len(bit_str)
... | fce124ccf0b3da512c72ae866aca70572a768692 | 698,936 |
import numbers
import math
import cmath
def atan(x):
"""
Uncertain number arctangent function
.. note::
In the complex case there are two branch cuts:
One extends from :math:`\mathrm{j}` along the imaginary axis to
:math:`\mathrm{j}\infty`, continuous from the right.
... | 470af67f67a6c5c1aa63fb28b5590c4f699c988c | 698,937 |
import os
def cpu_time(reference_cpu_time = 0.0):
"""
Returns current or elapsed value of CPU time used by the process,
including both user and system CPU time of both the process itself and
its children.
"""
return sum(os.times()[:4]) - reference_cpu_time | 9aee8973bea50d89e08dbf3d0c77ad4cfc252657 | 698,938 |
def get_present_volume(present):
"""Calculate volume of the box needed for present."""
volume = 1
for side in present:
volume *= side
return volume | e3df95638a741513307163abd90a68013aa7da3b | 698,939 |
def crop_rasters_for_sr(max_sr_factor, *hmaps):
"""Crop a list of rasters to a size such that they can be evently divided by
``max_sr_factor``. It assumes that each raster is centered identically. I.e. if one
raster has size 256x256 and another 254x254, it assumes that it is a border of size
1 that is r... | 77b45841cb82bc5475c6343df05c91b04d4e74c8 | 698,940 |
def track_score(track_path):
"""
Scoring the proposal tracklet can b associate 2 st_track possibility.
Score = weight_motion * score_motion + weight_appearance * score_appearance
:return:
"""
path_score = 0.
for each_node in track_path:
path_score += each_node.score
return path_s... | 8633bdbff8520e94e775d34b64bc448fa3b9366b | 698,941 |
def font_size_norm(x):
"""the web font size is different from the game client's - try to
approximate how it would look without having to know the actual value."""
try:
x = int(x)
except ValueError:
return "100%"
ratio = x / 24
return f"{int(ratio * 100)}%" | d70679ec385abe0cb283aa4615853e8b5e1a853e | 698,942 |
def apim_api_operation_get(client, resource_group_name, service_name, api_id, operation_id):
"""Gets the details of the API Operation specified by its identifier."""
return client.api_operation.get(resource_group_name, service_name, api_id, operation_id) | 4101a7aa2b3815856bf852a299698d407af390c0 | 698,943 |
def _uses_vulnerable_solc_version(version):
"""Detect if used compiler version is 0.4.[0|1|2|3|4]
Args:
version (solc version used)
Returns:
Bool
"""
if version in ["0.4.0", "0.4.1", "0.4.2", "0.4.3", "0.4.4"]:
return True
return False | 475dff3c6d3ed71317aab79e147f8797bde85f3a | 698,944 |
import hashlib
def get_subscriber_hash(member_email):
"""
The MD5 hash of the lowercase version
of the list member's email.
Uses as memeber_id
"""
member_email = member_email.lower()
m = hashlib.md5(member_email)
return m.hexdigest() | c2d7c7f4d0da58ec3990cccad865cb53cf2ebe15 | 698,945 |
def set_ax_info(ax, **kwargs):
"""Set Axes information
Args:
ax (Axes) : The ``Axes`` instance.
kwargs : ``key`` indicate the method which is start with ``set_``, and the method takes arguments (``val``) according to the type of ``val``
Returns:
ax (Axes) : The ``Axes`` instance... | f54d959b83464071eda6efec2a9189b47addec34 | 698,946 |
def Reverse(action):
"""Reverses the behavior of the action
Example::
# rotates the sprite 180 degrees in 2 seconds counter clockwise
action = Reverse( RotateBy( 180, 2 ) )
sprite.do( action )
"""
return action.__reversed__() | 9bde87421204300e55fff80eed0564f4b4d8e978 | 698,947 |
from datetime import datetime
def prune(iterable, start, end):
"""Discard events that fall outside the start-end interval."""
events = sorted(iterable, key=lambda event: event.created_at)
events.reverse()
# Check if we have at least one event older than the start date.
# If so, then we have a com... | d69be8ef507347049b4fc59938378eb108cc8ee4 | 698,948 |
def get_licenses(obj):
"""
Returns a list of license under which the given language resource is
available.
"""
result = []
for dist in obj.distributioninfotype_model_set.all():
for licence_info in dist.licenceInfo.all():
result.append(licence_info.licence)
return result | 09cbadcc55b15d189c0f19095351fdb2d9d526e3 | 698,949 |
def patches(internal_api_patcher):
"""
Fixture that resets session-wide patches before each test case function
"""
for mock in internal_api_patcher.patcher_mocks:
mock.reset_mock()
return internal_api_patcher | 05bacb7491e7178a324c07da4c67fad0b1fed01c | 698,950 |
def get_frame_number(frame):
"""Get frame number by calculating distance to newest frame."""
num = 0
newer = frame.newer()
while newer != None:
newer = newer.newer()
num += 1
return num | 1b653a629d9e34af2cfa1ce37bea54644a18236a | 698,951 |
import torch
def batch_l2(kernels):
"""
Args:
kernels: (num_kernels, bsize, bsize)
"""
n = kernels.shape[0]
kernels = kernels.view(n, -1) # (n, bsize*bsize)
distances = torch.cdist(kernels, kernels)
distances = distances - torch.diag(torch.diag(distances))
return - distances.m... | 0d1d9d1544cf98a0ae92e34e6ed739dadc6ef5f5 | 698,952 |
def ecs_efs_encryption_status(status):
"""
Property: EFSVolumeConfiguration.TransitEncryption
"""
valid_status = ["ENABLED", "DISABLED"]
if status not in valid_status:
raise ValueError(
'ECS EFS Encryption in transit can only be one of: "%s"'
% (", ".join(valid_statu... | 85e0d0f8b3c33331c8d877f0554126ca72c023bc | 698,953 |
def folder_contents_html(folder_path, files, folders):
"""Given files and folders generate html."""
html = "<!DOCTYPE html><html><body>{}</body></html>"
atag = '<a href="{}">{}</a>'
files_and_folders = ''
for folder in folders:
files_and_folders += '<h4>' + atag.format(folder_path + '/' + fo... | 6b6b37ca9452319d309a61c877ebf6d1fba201aa | 698,954 |
import os
def get_logdir_name(flags):
"""Generates the name of the log directory from the values of flags
Parameters
----------
flags: neural net architecture generated by get_arguments()
Outputs
-------
the name of the directory to store the training and evaluation results
"""... | 2caa6a8005bfb76b52847be3acc64ba93a0d72e0 | 698,955 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.