content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def cyccalc(self, fileprefix="", fileformat="", **kwargs):
"""Calculates results from a cyclic harmonic mode-superposition analysis
APDL Command: CYCCALC
using the specifications defined by CYCSPEC.
Parameters
----------
fileprefix
Each result table (corresponding to each CYCSPEC speci... | b713d33c1984a11654e31f6ac9eadbf83978f1e7 | 676,553 |
import inspect
import os
def _file_name_to_module_name(file_name):
"""Takes a file name/path (e.g. `"blah.py"`) and returns the module
name to which it corresponds, if any. If none, just returns the
leaf file name with ".py" stripped off.
This function is used to resolve file names reported in f... | 2ce32d0e87742d729632387ede6a9531f99eba5e | 676,554 |
def mean(numbers, precision=2):
"""return mean of a list, a basic function that is bafflingly absent"""
return round(float(sum(numbers)) / max(len(numbers), 1), precision) | be816038c247aa39e82db9d0f3494f4faf033f5f | 676,555 |
def traverse_json_obj(obj, path=None, callback=None):
"""
Recursively loop through object and perform the function defined
in callback for every element. Only JSON data types are supported.
:param obj: object to traverse
:param path: current path
:param callback: callback executed on every eleme... | 5270ed47ebb5bc190f99407752932b8414b8aef1 | 676,556 |
def data_transformer(x, y, xfactor, yfactor, **kwargs):
"""Multiplies x or y data by their corresponding factor."""
return {"x": x * xfactor, "y": y * yfactor} | cfe008e2d9b316d1e12554b65077484c92267104 | 676,557 |
def length_average(length, logprobs, alpha=0.):
"""
Returns the average probability of tokens in a sequence.
"""
return logprobs / length | e7f2768447618f2b426bc65ae7ecd30b67f933c7 | 676,558 |
def is_valid_name(name, parameters, kw):
"""Checks if name is a valid script variable name. Returns the error."""
if not name.isidentifier():
return "Variable name '{}' is not a valid identifier.".format(name)
if name in kw.KEYWORDS:
return "Variable name '{}' is a keyword.".format(name)
... | 9bfe5b75f2068757c0b434664bbfe65f0d16e8ae | 676,559 |
def equal_string_modulo_digits(s1, s2):
"""Returns whether two strings without their digits are the same
"""
s1 = (c for c in s1 if not c.isdigit())
s2 = (c for c in s2 if not c.isdigit())
return all(c1 == c2 for c1, c2 in zip(s1, s2)) | b44ca57446fec957d81e44acc2f3e3b950376dca | 676,560 |
def _has_magic(instream, magic):
"""Check if a binary stream matches the given signature."""
return instream.peek(len(magic)).startswith(magic) | 125555bebaad905c4b8521d7321b171a683ef767 | 676,561 |
import numpy
def _fix_numpy_split(ys, x, indices_or_sections, axis):
"""Make the output of np.split compatible with numpy >= 1.11"""
if all(y.ndim == x.ndim for y in ys):
return ys
tmp = [len(t) for t in numpy.split(
numpy.empty(x.shape[axis], dtype=numpy.int8), indices_or_sections, 0)]
... | 35dd18f53087a6f8ae81973e32c99097e3d8ca0a | 676,562 |
def div(arg1, arg2):
"""
fucntion that divides tow arguments
"""
return arg1 / arg2 | b4382a67d257d1510b0fd46a55778a351ed8c89a | 676,563 |
def cache():
""" Shows a view of all
the initialized cache's in the pipeline
and allows for modification to them.
"""
return None | 997b582f5c1e7ea591ac45a99d220acdf2722bca | 676,564 |
def make_dic(doc_id=None, root=None, date=None,
author=None, text=None, favorite=None):
"""make dictionary form argument and return dictionary
Keyword Arguments:
doc_id {int} -- documnet ID (default: {None})
root {string} -- xml file name (default: {None})
date {string} -- ... | 1948b9e20fe03a849cc072cc16330270730ee72d | 676,565 |
def get_users(f_path):
"""
Getting user name and password hash from file
"""
out = {}
with open(f_path) as file:
for d in file:
h = d.split(':')[1]
if h != '*':
u = str(d.split(':')[0]).strip()
if len(u) > 0:
out[u]... | c82a1b2ae844f48695f58997fcebd5cf44c0e11a | 676,566 |
def _matrix2dict(matrix, etype=False):
"""Takes an adjacency matrix and returns an adjacency list."""
n = len(matrix)
adj = {k: {} for k in range(n)}
for k in range(n):
for j in range(n):
if matrix[k, j] != 0:
adj[k][j] = {} if not etype else matrix[k, j]
return ... | 3898c34707d25327743f9a939f977ecf93d0c3ea | 676,567 |
import click
def _gui_command(f):
"""Command options for GUI commands."""
f = click.option(
'--clear-cache/--no-clear-cache', default=False,
help="Clear the .phy cache in the data directory.")(f)
f = click.option(
'--clear-state/--no-clear-state', default=False,
help="Clear... | 2f4f4fc871f3e7daafc99e2c7f27e368afd45dca | 676,568 |
def filter_enter(s):
"""正文 换行替换"""
s = s.replace("\n", "<br/>")
return s.replace(" ", " ") | 44633997bd801d2fd40d8ec161b9197aed2ca1f1 | 676,569 |
import six
def is_jid(jid):
"""
Returns True if the passed in value is a job id
"""
if not isinstance(jid, six.string_types):
return False
if len(jid) != 20 and (len(jid) <= 21 or jid[20] != "_"):
return False
try:
int(jid[:20])
return True
except ValueError... | e4dfcf00c5a02205f03b1383066703ffdb517d54 | 676,570 |
import os
def get_backup_filename(filename):
"""Get the name to which a backup of the given file can be written.
This will typically the filename with ".old" inserted at an appropriate
location. We try to preserve the file extension where possible.
"""
parent = os.path.dirname(filename)
part... | 7332cc2f4dff23aa3fd0ae203de9714ad31a40f1 | 676,571 |
def format_legacy_response(response, skills, category):
"""Format responses appropriately for legacy API. # noqa: E501
Examples:
>>> skills = ["Strength", "Hitpoints", "Ranged", "Magic", "Slayer", "Farming"]
>>> category = "xp"
>>> response = [
... {
... 'skills': {
... ... | e1af2f1600c8b68d68984e2ce357a76907e240fe | 676,572 |
import re
def GetFormatCount(format_):
"""
Get format prefix count
@param format_:
format specifier
@return:
prefix count or 1 if not specified
"""
if isinstance(format_, str):
match = re.search("\s*(\d+)", format_)
if match:
return int(match.grou... | ec6aae6bbb2a60aec5f7d038e17c34d021931a4c | 676,573 |
def _registered_tasks_to_pacbio_options(registered_tasks):
"""
:type registered_tasks: dict[str,ToolContractMetaTask]
:rtype: dict[str, PacBioOption]
"""
pacbio_options_d = {}
for task in registered_tasks.values():
for pb_opt in task.option_schemas:
pacbio_options_d[pb_opt.o... | 44223f59ded3447030e2ad40caeff08cf8265b3d | 676,574 |
def generate_wrapper(name, module, original_docstring, num_threads):
"""Generate a wrapper function.
Parameters
----------
name : string
Name of the function wrapped.
module : string
Name of the module the wrapped function is part of.
original_docstring : string
Docstrin... | e139f5df140b9c3a5ac7ec70eb5d221ad1f93c2e | 676,575 |
def select_and_rename(df, survey):
"""Cleaning: rename column titles."""
df = df.rename(columns={"indegree": "article_indegree",
"outdegree": "article_outdegree",
"pagerank": "article_pagerank",
"page_lengths": "article_textleng... | 635ee8b528ae284e517789ea1921b517afa90766 | 676,576 |
def domain_level(host):
"""
>>> domain_level('')
0
>>> domain_level(' ')
0
>>> domain_level('com')
1
>>> domain_level('facebook.com')
2
>>> domain_level('indiana.facebook.com')
3
"""
if host.strip() == '':
return 0
else:
raw_parts = host.strip()... | 42b242211589f1679e15e3e20fd9391ec6786b13 | 676,577 |
def _test_if_all_vals_equal(vals1, vals2):
"""Checks if the union of two iterables is 1 and returns True if that is the case. Is used in test_num_feats to
check if two lists of values have only the same value and nothing else.
:param vals1:
:param vals2:
:return:
"""
# build union between v... | d06bd3f862fee76a08b0e211fdbc7208921efe6d | 676,578 |
def triangularNumber(n):
""" Renvoie i si n est le ième nombre triangulaire, renvoie -1 si n n'est pas triangulaire.(cf : https://fr.wikipedia.org/wiki/Nombre_triangulaire ) """
m = n
i = 0 # Compteur
while m > 0:
# On retire à chaque étape i, qui vaut : 1, puis 2, puis 3, ...
... | 4efbc75b5d414e411baf07708f8fec831a168520 | 676,579 |
import copy
def convert_chord_label(ann):
"""Replace for segment-based annotation in each chord label the string ':min' by 'm'
and convert flat chords into sharp chords using enharmonic equivalence
Notebook: C5/C5S2_ChordRec_Eval.ipynb
Args:
ann (list): Segment-based annotation with chord la... | 50077cf6121df0df764ad254be57269c9600684a | 676,580 |
import random
def partition(array, s, e, pivot_pos=None):
"""
partition过程:
1.将参考值 pivot放到最右边
2.pos记录的位置表示在pos左边的值全小于pivot_value.
3.最后将pos和参考值(最右边的元素)交换。
:param array:
:param s: 开始元素
:param e: 结束元素
:param pivot_pos: 参考元素的位置。若不传。则在[s, e]中随机选
:return:
"""
if s == e:
... | 24019ba841c2f27e83c31b5f70d692ed748e2659 | 676,581 |
def copy_file_request(drive_service, file_id, body):
"""Send copy request to gdrive"""
response = drive_service.files().copy(
fileId=file_id,
body=body,
fields='id,webViewLink,name'
).execute()
return response | de05d3adb252dc84708eba3914b08227765ce74e | 676,582 |
import base64
import json
def main(event, context):
"""
>>> import shell, uuid
>>> run = lambda *a, **kw: shell.run(*a, stream=True, **kw)
>>> path = __file__
>>> uid = str(uuid.uuid4())[-12:]
>>> _ = run(f'aws-lambda-rm -ey {path}')
>>> _ = run(f'aws-lambda-deploy {path} -y && sleep 5 #... | c0bd5df00c5cc38a39b92b2ff149fb3be414b3d3 | 676,583 |
from typing import Optional
async def get_sample_owner(db, sample_id: str) -> Optional[str]:
"""
A Shortcut function for getting the owner user id of a sample given its
``sample_id``.
:param db: the application database client
:param sample_id: the id of the sample to get the owner for
:retur... | a028f4e6097808ecfe839b82c7d8e18e8934d384 | 676,584 |
import torch
def celeba_robustness_loss(x, aggregates, concepts, relevances):
"""Computes Robustness Loss for CelebA dataset
Formulated by Alvarez-Melis & Jaakkola (2018)
[https://papers.nips.cc/paper/8003-towards-robust-interpretability-with-self-explaining-neural-networks.pdf]
The loss formulat... | 1957d5ed5b7faacbe456f42ada0b8417c53a007b | 676,585 |
def format_password(password):
"""
Formats password for printing to the terminal.
This is done so that the password is not returned as plain text.
"""
return password[0] + "*" * (len(password) - 1) | a1477472802c12a10426f31e4fb2eaf1d52448b4 | 676,586 |
import os
import pickle
def _write(path, data):
"""Write a pickle file at a specified path. If the folder does not exist
yet, create it."""
os.makedirs(os.path.dirname(path), exist_ok = True)
try:
pickle.dump(data, open(path, 'wb'))
return True
except:
return False | 4d69e4c4ca82c399863a40eee9e8c19c80811cf0 | 676,587 |
def lstsq(normalizer, X, y, pattern, coef):
"""Normalizes to minimize the least-squares-error with the given y"""
y_hat = X.dot(coef.T).ravel()
return y_hat.dot(y) / y_hat.dot(y_hat) | 1ef6e7acdeaeb75ef33a34e645e8d1cd76c0b39c | 676,588 |
def is_equivalent(a, b):
"""Checks if two strings are equivalent
This only does a == b, and will not replace anything. For testing.
"""
return a == b | 88ca6a1ac08b15c288b4361c6a5e1b1fcf71dd48 | 676,589 |
def to_string(params, indent=2):
"""format params to a string
Args:
params (EasyDict): the params.
Returns: The string to display.
"""
msg = '{\n'
for i, (k, v) in enumerate(params.items()):
if isinstance(v, dict):
v = to_string(v, indent + 4)
spaces = ' '... | a85245cb4463529cf7f3b10b252ad85f74b4824d | 676,590 |
import csv
def read_csv(read_path, delim=','):
"""Reads a generic CSV file.
Args:
- read_path - string path to read from.
- delim - delimiter to use for the CSV format.
Returns:
- rows - list of rows where each row is a string list of cell values.
"""
rows = []
with open(read_pat... | 772a03a953c1bddd77b4fd4a47a7eca3526ec32f | 676,591 |
def unzip(items):
"""The inverse of zip
Parameters
----------
items : a nested iteratable
Returns
-------
list
The unzipped items
Examples
--------
>>> from t2t.util import unzip
>>> unzip([[1, 2], ['a', 'b']])
[[1, 'a'], [2, 'b']]
"""
if items:
... | 3da11d0a7342e226654285a668d59daedc94a9f3 | 676,593 |
def dq_normalize(dq):
"""Normalize a dual quaternion"""
l = 1 / dq.real.magnitude
dq.real.normalize()
d = dq.real.dot(dq.dual)
# d = dq.real[0] * dq.dual[0] + dq.real[1] * dq.dual[1] + dq.real[2] * dq.dual[2] + dq.real[3] * dq.dual[3]
dq.dual[0] = (dq.dual[0] - dq.real[0] * d) * l
dq.du... | 4f8603005705545768f426506cf074a20478abbf | 676,594 |
def Rayleigh_KD(f, alpha):
"""
Calculate partitioning of trace element (TE) as a function of Rayleigh fractionation.
Parameters
----------
f : array-like
Fraction of Ca remaining in the biomineralisation reservoir.
alpha : array-like
Partition coefficient for extraction of TE fr... | 3848463fc04c0a2e36ed6da856f7ce6771a30bfa | 676,595 |
def find_smallest_int(arr):
"""
Given an array of integers find the smallest number.
:param arr: an array of integers.
:return: the smallest number within the array.
"""
return min(arr) | 3f19e0e6901d52daf3f68be3b12c8f0f744b3279 | 676,596 |
from typing import Union
from typing import Any
from typing import List
from typing import Tuple
def as_list(content: Union[Any, List[Any], Tuple[Any]]) -> Union[List[Any], Tuple[Any]]:
"""Ensures we always get a list"""
if isinstance(content, (list, tuple)):
return content
return [content] | 3e6c23609082e78fbf3f77436c975b53f355197c | 676,597 |
import colorsys
import random
def generate_colors(class_names):
"""Generates different colours for all classes.
Args:
class_names (list of `str`):
List containing names of all classes.
Returns:
list: List containing colours for corresponding classes.
"""
hsv_tuples = ... | 66c42367398055211618eeb9528d7ee652349822 | 676,598 |
from typing import Union
import hashlib
def calc_checksum(data: Union[str, bytes]) -> str:
"""Generate checksum for CodeNotary."""
if isinstance(data, str):
return hashlib.sha256(data.encode()).hexdigest()
return hashlib.sha256(data).hexdigest() | 92a420cf0a45c77435a4521398354617f2bcdf0e | 676,599 |
def _is_national_number_suffix_of_other(numobj1, numobj2):
"""Returns true when one national number is the suffix of the other or both
are the same.
"""
nn1 = str(numobj1.national_number)
nn2 = str(numobj2.national_number)
# Note that endswith returns True if the numbers are equal.
return nn... | ca99aa363764874794d48b5f85b57aed63827547 | 676,600 |
def format_time_filter(start, stop, field):
"""Formats a time filter for a given endpoint type.
Args:
start (str): An ISO date string, e.g. 2020-04-20.
stop (str): An ISO date string, e.g. 2021-04-20.
field (str): The time field to filter by.
"""
start_date = start.split('-')
... | 6c21bb1ff6f90002d0f7f50d2c82fd081db89213 | 676,601 |
from re import IGNORECASE
import re
from re import UNICODE
def _re_literal_pattern(pattern, rum_flags=0, binary=False):
"""Prepare literal search pattern flags."""
flags = 0
if rum_flags & IGNORECASE:
flags |= re.IGNORECASE
if not binary and rum_flags & UNICODE:
flags |= re.UNICODE
... | 8141e3ec606569a9ad011ebe2264db37e04ac655 | 676,602 |
def __get_char_hex_value(c):
"""returns 61; for 'a' truncated from 0x61"""
return hex(ord(c)).replace("0x", "") | 9b172a3175ee7626fec0baf9be14262be659d76c | 676,603 |
def alive():
"""
Just a function that can be used to verify that cookiecutter built the
project boilerplate correctly
"""
return True | 35dfd5b0d1e888b2211da27ac8126a98575a3f03 | 676,604 |
def get_hypothesis(x, theta):
"""
:param x : scalar of a given sample
:param theta : 1D array of the trainable parameters
"""
hypothesis = 0.0
for t in range(len(theta)):
# compute prediction by raising x to each power t
hypothesis += theta[t] * (x ** t)
... | be84e00c1eb7dbb6d2cbdf87eb7f84ff08d4980b | 676,605 |
from pathlib import Path
import json
def load_ambient_sensor(session_path):
"""
Load Ambient Sensor data from session.
Probably could be extracted to DatasetTypes:
_ibl_trials.temperature_C, _ibl_trials.airPressure_mb,
_ibl_trials.relativeHumidity
Returns a list of dicts one dict per trial.
... | 095bd61826b36bb930e70d4bcb8c8a37577d9058 | 676,606 |
import math
def circle_layout(n):
"""Custom node layout to have nodes positioned in an anti-clockwise circle starting from
the middle left"""
frac = 2 * math.pi / n
return {i: (-math.cos(i * frac), -math.sin(i * frac)) for i in range(n)} | 2553a997f24156b86cad3e87da765d37f5c261df | 676,608 |
def isSliceUnitSUV(dcmSlice):
"""Take a dcm slice in input and returns true if the voxels are expressed in SUV - Standardized uptake value.
Return false otherwise."""
# 00541001 corresponds to the tag index of the voxel unit in the dcm file
units = dcmSlice[0x00541001].value.lower()
unitIsSUV = "su... | b9dcdc393dade1182cb624b47a1c0a9a8878e30b | 676,609 |
def sanitize_filename(filename: str) -> str:
"""
@param filename:
@return:
"""
filename = filename.replace('/', '_').replace(' ', '_')
return filename | 76f533192b64dadf1b7a72f49688bc4a70f399cc | 676,610 |
def safezip2(seq1, seq2):
"""A zip that raises an error when the sequences have different length.
It can only handle two sequences.
"""
if len(seq1) != len(seq2):
raise ValueError(
"Lengths of iterators differ: {} != {}.".format(len(seq1), len(seq2))
)
return zip(seq1, se... | d2c34cd33de021e0fc52ecce9c5f3a394828da3e | 676,611 |
def get_primes(length: int = 26, min_prime: int = 2,
max_prime: int = 101) -> list:
"""Get list of primes.
Given a length, minimum, and maximum prime number, return a list of prime
numbers.
Args:
length (int): Number of prime numbers to return. Defaults to ``26``.
min_pr... | 2b7cff406db46da9922057633abadbf4a6dca0a4 | 676,612 |
def create_doc_list(doc_qs):
""" Helper function for person() and organization() """
doc_list = []
for doc in doc_qs:
doc_list.append({
'document_date': str(doc.date) if doc.date else 'Unknown',
'document_title': f'<a href="{doc.url}">{doc.title}</a>',
})
return d... | 04436f091b3ea1fbe555e10050638de7ce204d87 | 676,613 |
def autocomplete_configuration_path(actions, objects):
"""
Returns current configuration_path for object. Used as a callback for
`default_value`.
Args:
actions: Transition action list
objects: Django models objects
Returns:
configuration_path id
"""
configuration_pa... | 2d1a1ea5bf8fd4f3ecbee65da0024995ada07727 | 676,614 |
def monitorDocFromRequestSchema(schema):
"""
prun and convert
"""
doc = {}
doc["_id"] = schema['RequestName']
doc["workflow"] = schema['RequestName']
doc["requestor"] = schema['Requestor']
doc["campaign"] = schema['Campaign']
doc["request_type"] = schema['RequestType']
doc["prior... | 0e1e9df52dc28fdc912515627113c706dc2ddaa2 | 676,615 |
def s2(val):
"""Convert to string."""
try:
if val.mask:
return 'M'
except Exception as _exp:
pass
return "%5.1f" % (val,) | 2c52f15f0f5993f45f0a2db2abc450e9c51be1e5 | 676,616 |
import requests
def get_page(url, word):
"""
get the translation webpage
:param url:
:param word:
:return webpage:
"""
queryUrl = url + word
response = requests.get(queryUrl)
return response.content | 67511bd5ef17550c036d004e4ac9172898238f8a | 676,617 |
def eval_symb_reg(individual, points, toolbox):
""" Takes an individual, randomly generated function and compares it with
each row in the training dataset. Returns a decimal value indicating the
margin of errors (higher is worse).
"""
# Transform the tree expression in a callable function
func ... | 0243bc9d92fb07af14c02fd2eba3e31512b4dd8a | 676,618 |
def generate_knowledge_store_published_message(knowledge_store_object):
"""
Util for creating knowledge store message
:param knowledge_store_object: KnowledgeStore object
:return: str
"""
hustler_name = (
knowledge_store_object.created_by.first_name
if knowledge_store_object.crea... | 5643e97fd802609cca8660a58d0aa546bbaf0a61 | 676,619 |
import six
def split(text, strip=True):
"""Splits a comma separated text blob into its components.
Does nothing if already a list or tuple.
"""
if isinstance(text, (tuple, list)):
return text
if not isinstance(text, six.string_types):
raise TypeError("Unknown how to split '%s': %s... | 537be3a932244568f550f5cb2d90063a14c6d7f2 | 676,620 |
def predict_types(model, words):
"""Predict morphemes along with morpheme types.
return list of two-element lists: for each word list of morphemes and list of types
[
[[morpheme11, ..., morpheme1N], [type11, ..., type1N]],
...
[[morphemeK1, ..., morphemeKM], [typeK1,... | b2a379ca73691a4225277809f3b23aecfb408a3a | 676,621 |
import string
def is_segment(pattern):
"""Test if pattern begins with a segment variable."""
return (type(pattern) is list
and pattern
and len(pattern[0]) > 2
and pattern[0][0] == '?'
and pattern[0][1] == '*'
and pattern[0][2] in string.ascii_letters... | 5eb800b96389ac57c1c133637ec9500464850805 | 676,622 |
def readStrFromFile(filePath):
"""
从文件中读取字符串str
param filePath: 文件路径
return string : 文本字符串
"""
with open(filePath, "rb") as f:
string = f.read()
return string | 45160ad6f74935065a9588d1645822e61356b2dc | 676,623 |
def convert_word_index_to_sentence(word_idx, vocab):
"""Convert word indices to sentence."""
s = ""
for ind in range(len(word_idx)):
w_idx = word_idx[ind]
if w_idx> 0:
s += vocab[w_idx-1]
if ind < len(word_idx)-1:
s+= " "
return s | 85eb540bb23f9de4d12b4beebf1a6af5129d2080 | 676,624 |
def vshale_from_gr(df):
"""
Creates Clavier, Larionov old, Larionov new, Steiber VSH
"""
GR_min = df.GR.min()
GR_max = df.GR.max()
df.loc[:, 'IGR'] = (df.GR - GR_min) / (GR_max - GR_min)
df.loc[:, 'VSH_clavier'] = 1.7 - ((3.38 - (df.IGR + 0.7)**2)**0.5)
df.loc[:, 'VSH_larionovO'] = 0... | e9b9806052d6787c2742b832a2cabf67ec74cd61 | 676,625 |
import os
def filename_wo_ext(filepath):
"""
Returns the name of the given file without extension.
:param filepath: str, path of a file
:return: str, filename without extension
"""
name = os.path.splitext(os.path.basename(filepath))[0]
return name | 7bc72935fc6a1ff60b4768c0d1ba7a04383d74af | 676,626 |
def thickest_clouds(cloud_thickness_and_base_list):
"""
Given a list of tuples indicated cloud thickness and base, return the tuple
with the thickest clouds
"""
return max(cloud_thickness_and_base_list, key=lambda c: c[0]) | e52258ecab4835133e67c6295e56e019295ce3f1 | 676,627 |
def validate_run(cards):
"""
a run is 3 to 10 consecutive cards of the same suit
:param cards: list of Card objects
:return: Boolean
"""
if len(cards) < 3 or len(cards) > 10:
return False
if not all(card.suit == cards[0].suit for card in cards):
return False
ranks = sort... | 253d5f9e159c6c83243c752ea75a5c38a3888f6b | 676,628 |
from typing import Callable
def time_sort(sorting_fn: Callable[[list[int]], list[int]], arr: list[int]) -> int:
"""
time_sort takes a function and an array and returns how long it took
for that array to be sorted
Args:
sorting_fn (Callable[[list[int]], list[int]]): sorting function to use
... | afd4946299b9e44398a84652e901b3e813f23bb6 | 676,629 |
from typing import List
def nifs3_v(x: List[float], y: List[float], M: List[float], x0: float, x1: float, nn: int ) -> List[List[float]]:
"""Funkcja generująca wykres NIFS3.
Parameters
----------
x : List[float]
Wartości na osi X.
y : List[float]
Wartości na osi Y.
M : List[fl... | bf3c0110f26442ad772f82ce5ba49c041e50d87a | 676,630 |
import subprocess
def term_width():
"""
Return the width of the terminal. This function assumes stty exists and is runnable. If that is
not the case than a width of 80 characters is returned as a guess/default. This should never
happen as stty exists on ESX, Linux and OSX.
"""
try:
# G... | e1b4dcd874d0e2b2096b1923ff22d4ed3190693b | 676,631 |
def iteration(V, Vbool, iterations=10000):
"""
Function to solve Laplace equation by the FDM.
Parameters
----------
V : np.array
Matrix of V initial values.
Vbool : np.array
Matrix of U boolean values, 1 if the cell is inside an object and 0
otherwise.
iterations : f... | 2bd9443a0aa04fe1d3cf7fb29f2747e88c726861 | 676,632 |
def getEdges(G):
""" 输入图G,返回其边与端点的列表 """
v1 = [] # 出发点
v2 = [] # 对应的相邻到达点
w = [] # 顶点v1到顶点v2的边的权值
for i in range(len(G)):
for j in range(len(G[i])):
if G[i][j] != 0:
w.append(G[i][j])
v1.append(i)
v2.append(j)
retur... | afaf4ccf5236a043b01a6fb2df1a105773509309 | 676,633 |
def get_plural_string(word: str, amount: int) -> str:
"""Returns singular or plural of the word depending on the amount.
Example:
word = 'piece', amount = 0 -> '0 pieces'
word = 'piece', amount = 1 -> '1 piece'
word = 'piece', amount = 5 -> '5 pieces'"""
if amount == 1:
return f'1 {word}'
else:
return f'{... | 34c6af2e6d4c429e070f28ad184d18faa2c22060 | 676,634 |
import math
def calculateRMSDs(position):
"""
calculating rmsd for new and old position
"""
rmsd_new = 0.00
rmsd_old = 0.00
number_of_points = len(position['target'])
for key in position['target'].keys():
for i in range(3):
rmsd_new += pow( (position['new'][key][i] - position... | 49a8a4bc2800c0393866c79826a9b7e3f20b5650 | 676,636 |
from functools import reduce
from typing import Mapping
def deep_get(dictionary: dict, *keys, default=None):
"""Safely return the value of an arbitrarily nested map
Inspired by https://bit.ly/3a0hq9E
"""
return reduce(
lambda d, key: d.get(key, default) if isinstance(d, Mapping) else default, keys, dictionary
... | e39b362d9c0c94e1a0230a71037b12bd7fe2dd18 | 676,637 |
from typing import List
import struct
def unpack_long(data_length: int, msg) -> List[int]:
"""
解包短长整数
:param data_length: 原始数据长度,原始数据元素个数
:param msg: 打包的消息字符串
:return: 解包结果的元素列表
"""
origin_format = f"{data_length}l"
format = f"{data_length}l"
b = struct.unpack(format, msg)
r =... | 4fdb29458d89474dde0416d899e34f64639b7079 | 676,638 |
def word_ids_to_words(data, id_to_word):
"""Given a context (ids) in list format and the vocabulary,
Returns a list of words to represent the context.
Parameters
----------
data : a list of integer
the context in list format
id_to_word : a dictionary
mapping id to unique word.
... | 4b3c1a3e775615926a34484dd598e82ae64410ee | 676,639 |
def get_ohlc_intraday(
data, start_time, end_time, date_col=None, col_mappings=None, sort=False
):
"""
Get ohlc for a specific period in a day for all days
for all the symbols.
data
dataframe with symbol, timestamp, date, open, high, low, close columns.
The timestamp and date columns... | e8682d88ec1991bdbb95eb617bea5c2798889fbe | 676,640 |
def get_description(repo_info):
"""Return repository description"""
try:
return repo_info.find('p').text.strip()
except AttributeError:
return | 927891159d73fde57cbb8bb0456a6d08034a10ad | 676,641 |
def skipped_when(df, percentage, interval = None):
"""Number of tracks that where skipped before reaching the given percentage
of playback time"""
if not interval:
return df[df.percentagePlayed <= percentage].count().iloc[:][0]
else:
return df[(df.percentagePlayed < percentage) &\
... | c48e1492843ead6170fb06d491306315c091c3e1 | 676,642 |
def transform(reference, mapping, start=0, stop=None):
"""
Transforms a reference using a mapping object
:param reference: a string
:param mapping: a list of [{position},{"I"|"D"|"S"},{None|length_of_deletion|sequence_of_insertion}] operations
:param start: option to specify a reference start positi... | fe02bf7535804cc217e3a743de0c3bb9e84e1e34 | 676,643 |
from datetime import datetime
def _update_enhancement_zen_data(enhancement, zen_ticket, zen_user_reference):
"""Updates the base Zendesk information for an enhancement with the data from
the passed Zendesk ticket.
Parameters:
enhancement - A dictionary of enhancement data.
zen_ticket - A ... | 6d18d991311845ba9a5446ace707332d8880b4cb | 676,645 |
def _exact_compare(tree1, tree2):
"""Simultaneously compares the name, length, and support of each node from
two trees.
Parameters
----------
tree1: skbio.TreeNode
first tree to compare
tree2: skbio.TreeNode
second tree to compare
Returns
-------
bool
`True`... | 11022142306165a29afb58f2075fb9fcb9e6ce3d | 676,646 |
def readthrough_in_bedpe(record, annotation, rt_threshold):
"""
Determine if the two genes in the record are within `rt_threshold` bp of each other on the same
chromosome.
:param BEDPE record: A BEDPE line from the input file
:param dict(str, GTFRecord) annotation: see `read_fusions:gene_annotation... | e460505e948b59d42c279c83f3e081d0f4b5a253 | 676,647 |
from typing import Dict
from pathlib import Path
import os
import json
def get_constants() -> Dict[str, dict]:
""""Parses ../constants.json file
Return:
dict: constants from constants.json
"""
root_dir = Path(os.path.dirname(__file__)).parent
constants_path = os.path.join(root_dir, 'const... | b203452ec4030da4641c01ac133d660a1dc32b7a | 676,649 |
def _has_multiple_loop_exits(cfg, lpinfo):
"""Returns True if there is more than one exit in the loop.
NOTE: "common exits" refers to the situation where a loop exit has another
loop exit as its successor. In that case, we do not need to alter it.
"""
if len(lpinfo.exits) <= 1:
return False... | 724137e474df587c204d5de498133be57d29df63 | 676,650 |
import os
def getValidBNGLFiles(directory):
"""
Gets a list of bngl files that could be correctly translated in a given 'directory'
"""
onlyfiles = [ f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) ]
logFiles = [x[0:-4] for x in onlyfiles if 'log' in x]
erro... | a02a76445dd2ca214001ef672ad2e3b8c263c98a | 676,651 |
from datetime import datetime
def strf_time(value):
"""
格式化时间:2017-04-07 10:30:13
:param value:
:return:
"""
if not isinstance(value, datetime):
return ''
return value.strftime('%Y-%m-%d %H:%M:%S') | 47c2df72ce888abf76b4b8dd289869175027859e | 676,652 |
import random
def choose(char):
""" Randomly choose upper or lower case to return """
return char.upper() if random.choice([0, 1]) else char.lower() | 1795dc883f157449e3ce48f1bdba67e43c46afbb | 676,653 |
def A008588(i: int) -> int:
"""Nonnegative multiples of 6."""
return i * 6 | 862ee8538de73acae42294c398d4986545623b32 | 676,655 |
def int_(num: str) -> int:
"""
Take an integer in the form of a string, remove any commas from it,
then return it as an ``int``.
Args:
num: A string containing only numeric characters or commas.
Returns:
An integer version of the string.
"""
return int(num.replace(",", "")) | 697061556cc1553c49370b68490cdea19f540535 | 676,657 |
def median(lst):
"""
Return a list's median
:param lst: List (sorted or not) of int
:return: int
"""
lst.sort()
length = len(lst)
if length == 0:
return None
elif length % 2 == 0:
# Even number of elements
return (lst[int((length+1)/2 - 1)] + lst[i... | d134faacc2ab3e9635322ad06a307a9f93274c8b | 676,658 |
def send_help():
"""
Send help!
:return: A message containing help information.
"""
return f"""
```
BigDogg v1.0
Commands: dogg [command] [arg1, arg2, ...]
help - Send help (print this message).
hello - Say hello to BigDogg.
add - Add t... | 8275955ebd5694c389d31d1e4a4e7a9e6ef3d473 | 676,659 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.