content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def hex_to_rgb(col_hex):
"""Convert a hex colour to an RGB tuple."""
col_hex = col_hex.lstrip('#')
return bytearray.fromhex(col_hex) | 2a38fe4fbd9231231a0ddcc595d27d71b0718ba3 | 672,267 |
import torch
def second_order_loss_with_ic(neural_network, a, b, g, ic, ic_prime, domain_lower_bound=0, domain_upper_bound=1, num_points=10):
"""Computes loss for a given NN
Parameters
----------
nerual_network : torch.nn.Module
Neural network used in trial solution
a: function
Fu... | 721e5db2eba1581603ce8f977b30518a58cc1e29 | 672,269 |
def timeit(get_ipython, fn, *args, **kwargs):
"""Invoke the IPython timeit line magic.
Determined how this worked via:
>>> import dis
>>>
>>> def capture_line_magic(fn):
... timeit_result = %timeit -o -q fn()
... return timeit_result
...
>>> dis.dis(capture_line_magic)
... | 4d8f1fa41fa50ea9a214216e1467e29980e0a7fc | 672,270 |
def encode(to_be_encoded):
"""
Run-length encodes a string
:param to_be_encoded: string to be run-length encoded
:return: run-length encoded string
"""
last_seen = None
last_seen_count = 0
to_be_encoded_as_list = list(to_be_encoded)
encoded_str_as_list = list()
for c in to_be_e... | e9f0e515848feb16d00e2c18ddcf63407d988882 | 672,271 |
def page_query_with_skip(query, skip=0, limit=100, max_count=None, lazy_count=False):
"""Query data with skip, limit and count by `QuerySet`
Args:
query(mongoengine.queryset.QuerySet): A valid `QuerySet` object.
skip(int): Skip N items.
limit(int): Maximum number of items returned.
... | 2aef61019b67f2d9262ad8f671a9991e0915ddcf | 672,272 |
import os
def create_output_dir_for_chromosome(output_dir, chr_name):
"""
Create an internal directory inside the output directory to dump choromosomal summary files
:param output_dir: Path to output directory
:param chr_name: chromosome name
:return: New directory path
"""
path_to_dir = o... | 3d78335f7588f6f60305eee2df43203428ebaabc | 672,273 |
def nvt_cv(e1, e2, kt, volume = 1.0):
"""Compute (specific) heat capacity in NVT ensemble.
C_V = 1/kT^2 . ( <E^2> - <E>^2 )
"""
cv = (1.0/(volume*kt**2))*(e2 - e1*e1)
return cv | 12d8cee877ef2a6eee1807df705ba5f193c84f52 | 672,274 |
def rectangle_to_cv_bbox(rectangle_points):
"""
Convert the CVAT rectangle points (serverside) to a OpenCV rectangle.
:param tuple rectangle_points: Tuple of form (x1,y1,x2,y2)
:return: Form (x1, y1, width, height)
"""
# Dimensions must be ints, otherwise tracking throws a exception
return (int(rectangle_points[... | 47548d4098d057625ebfd846164946481222559d | 672,275 |
def dijkstra(g, source):
"""Return distance where distance[v] is min distance from source to v.
This will return a dictionary distance.
g is a Graph object.
source is a Vertex object in g.
"""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0
whi... | aa28bb28c581fc6f3651f1a7ae704b56ac3f1525 | 672,276 |
def calc_gross_profit_margin(revenue_time_series, cogs_time_series): # Profit and Cost of Goods Sold - i.e. cost of materials and director labour costs
"""
Gross Profit Margins Formula
Notes
------------
Profit Margins = Total revenue - Cost of goods sold (COGS) / revenue
... | d7fe1352278423b048cc456adba3580647cff0f4 | 672,277 |
import subprocess
def untracked_files(hg_dir):
"""untracked files in an hg repository"""
process = subprocess.Popen(['hg', 'st'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=hg_dir)
stdout, stderr = proces... | b6dbe8b5ff07491cc45be02e2e5639da4042a713 | 672,278 |
import re
def translate_years(val):
"""Convert X ('YY-'YY) into an array"""
if val.find("-") > 0:
tokens = re.findall("[0-9]+", val)
one = int(tokens[0])
two = int(tokens[1])
one = (1900 + one) if one > 50 else (2000 + one)
two = (1900 + two) if two > 50 else (2000 + tw... | 61520d0cf40f71d80bfd7ed7b8100e3f86d0876b | 672,279 |
def np_slice(matrix, axes={}):
"""Slices a matrix along specific axes"""
ans = [slice(None)] * len(matrix.shape)
for key, value in axes.items():
ans[key] = slice(*value)
return matrix[tuple(ans)] | 299c26b494bd56bf38ece02748a7ca5a31ab1264 | 672,280 |
import itertools
def determineQATaskName(qaTaskBaseName, f, isPtHard):
""" Determine the task name based on a wide variety of possible names.
Since the task name varies depending on what input objects are included,
we need to guess the name.
Args:
qaTaskBaseName (str): Base name of the QA task wit... | 97a106e9b30552a1bd4b7380cc4ebdcccfbcd119 | 672,281 |
def sfill(x, max_chars=10, justify='>'):
"""Fill a string with empty characters"""
return '{}' \
.format('{:' + justify + str(max_chars) + '}') \
.format(x) | b1525e05095bd07384fd16832da2cda77cb845c6 | 672,282 |
import asyncio
def event_loop() -> asyncio.AbstractEventLoop:
"""Returns an event loop for the current thread"""
return asyncio.get_event_loop_policy().get_event_loop() | 19d1e4544eba04b2b8d99c7efa3427021d2d95e8 | 672,283 |
def set_discover_targets(discover: bool) -> dict:
"""Controls whether to discover available targets and notify via
`targetCreated/targetInfoChanged/targetDestroyed` events.
Parameters
----------
discover: bool
Whether to discover available targets.
"""
return {"method": "Target.... | 31de0937b68af4b6492f4c49d67d5f4c481a5c6b | 672,284 |
import subprocess
def execute_pylint(filename):
"""Execute a pylint process and collect it's output
"""
process = subprocess.Popen(
["pylint", filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
stout, sterr = process.communicate()
... | 7152fd8c9f3ac5cf969021c3be394872ece129b1 | 672,285 |
def notas(*nt, sit=False):
"""
-> Função para analisar notas e situação de vários alunos.
:param nt: recebe uma ou mais notas dos alunos.
:param sit: valor opcional, mostrando ou não a situação do aluno(True/False).
:return: dicionário com várias informações sobre a situação da turma.
"""
pr... | 4854c5941f57e5775a504fd9ad24b96886dd2bfd | 672,286 |
import os
def get_subid_sesid_mask_dti(subject_id, caps_directory, fwhm, compartment_name, threshold):
"""
This is to extract the base_directory for the DataSink including participant_id and sesion_id in CAPS directory, also the tuple_list for substitution
:param subject_id:
:return: base_directory fo... | 821dd13baf81af52ae20c251bf2ae182895f6b00 | 672,288 |
def _get_binary(value, bits):
"""
Provides the given value as a binary string, padded with zeros to the given
number of bits.
:param int value: value to be converted
:param int bits: number of bits to pad to
"""
# http://www.daniweb.com/code/snippet216539.html
return ''.join([str((value >> y) & 1) for... | 4b4312026cef9fbdca228b1db7205825c5353450 | 672,289 |
import os
def Usable(entity_type, entity_ids_arr):
"""Can run with Python files only"""
fil_nam = entity_ids_arr[0]
# But probably it is not enough and we should try to open it.
fil_ext = os.path.splitext(fil_nam)[1]
# Maybe this can be generalised to survol_python.pyExtensions
return fil_e... | c515782bf7919aa59e3667b6290ecf3c183a1297 | 672,290 |
def count_null_values_for_each_column(spark_df):
"""Creates a dictionary of the number of nulls in each column
Args:
spark_df (pyspark.sql.dataframe.DataFrame): The spark dataframe for which the nulls need to be counted
Returns:
dict: A dictionary with column name as key and null count as ... | ff27c3bad5a0578bb51b0ef6d71659360ab5b11e | 672,293 |
def __version_compare(v1, v2):
"""
Compare two Commander version versions and will return:
1 if version 1 is bigger
0 if equal
-1 if version 2 is bigger
"""
# This will split both the versions by '.'
arr1 = v1.split(".")
arr2 = v2.split(".")
n = len(arr1)
m =... | fe1a563d26a5dabdae968c8502049fc1333acdd9 | 672,294 |
import re
def get_hits(pattern: re.Pattern, body: str, context_len: int = 15):
"""Applies search, and returns a string for every match with some
additional context"""
matches = pattern.finditer(body)
res = []
for match in matches:
if match is None:
continue
start = max(... | 3d5a7a3775f0303f109b568ac6f77333b4aabb67 | 672,295 |
def create_vocab_item(vocab_class, row, row_key):
"""gets or create a vocab entry based on name and name_reverse"""
try:
name_reverse = row[row_key].split("|")[1]
name = row[row_key].split("|")[0]
except IndexError:
name_reverse = row[row_key]
name = row[row_key]
temp_ite... | 3f8fd941e02b857279f1a4961d35cfd36bf7cb5b | 672,297 |
def sentence_position(i, size):
"""different sentence positions indicate different
probability of being an important sentence"""
normalized = i*1.0 / size
if 0 < normalized <= 0.1:
return 0.17
elif 0.1 < normalized <= 0.2:
return 0.23
elif 0.2 < normalized <= 0.3:
return... | 3ead84d8910deae5b6e76b9066f9461ae1d4c677 | 672,298 |
import os
def _add_eutils_api_key(url):
"""Adds an eutils api key to the query.
Args:
url (str): The query url without the api key.
Returns:
str: The query url with the api key, if one is stored in the environment variable
``NCBI_API_KEY``, otherwise it is unaltered.
"""
... | 3ae4a256ebf0705280c35adeb289d80468fe6b80 | 672,299 |
def _restore_config_data(dct: dict, delete: dict, defaults: dict) -> dict:
"""delete nested dict keys, restore from defaults."""
for k, v in delete.items():
# restore from defaults if present, or just delete the key
if k in dct:
if k in defaults:
dct[k] = defaults[k]
... | 142b01bc0b2b67deee8d753ab323e213387f0473 | 672,300 |
import json
def _load_repo_configs(path):
"""
load repository configs from the specified json file
:param path:
:return: list of json objects
"""
with open(path) as f:
return json.loads(f.read()) | f96e2d78b2614d07b2b1b1edc71eb10a9c2709a3 | 672,301 |
def get_if_all_equal(data, default=None):
"""Get value of all are the same, else return default value.
Arguments:
data {TupleTree} -- TupleTree data.
Keyword Arguments:
default {any} -- Return if all are not equal (default: {None})
"""
if data.all_equal():
return da... | 30e7186ae835ba3ba9ac110c2f55b316346bdc1a | 672,302 |
def sdp_abs(f, u, O, K):
"""Make all coefficients positive in `K[X]`. """
return [ (monom, K.abs(coeff)) for monom, coeff in f ] | 00d3ef9984774aac40abc15ab8b95b2bf1918894 | 672,303 |
def convert_compartment_id(modelseed_id, format_type):
""" Convert a compartment ID in ModelSEED source format to another format.
No conversion is done for unknown format types.
Parameters
----------
modelseed_id : str
Compartment ID in ModelSEED source format
format_type : {'modelseed... | 8856858637b2f655ac790e026e7fe88c6e83e364 | 672,304 |
def _box_area(boxes):
"""copy from torchvision.ops.boxes.box_area(). """
return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) | 8396356125f1eeb21957b2253bbb21accb770821 | 672,305 |
import torch
def dirichlet_common_loss(alphas, y_one_hot, lam=0):
"""
Use Evidential Learning Dirichlet loss from Sensoy et al. This function follows
after the classification and multiclass specific functions that reshape the
alpha inputs and create one-hot targets.
:param alphas: Predicted para... | c6c5749e9a24b8d5d2d9df8a3567f0c1d967f84e | 672,306 |
def get_windows(y, cv):
"""Generate windows"""
train_windows = []
test_windows = []
for i, (train, test) in enumerate(cv.split(y)):
train_windows.append(train)
test_windows.append(test)
return train_windows, test_windows | 603bcae549f8936a6c8e76aff651bb4bd95096c7 | 672,307 |
def merge_dicts(base, updates):
"""
Given two dicts, merge them into a new dict as a shallow copy.
Parameters
----------
base: dict
The base dictionary.
updates: dict
Secondary dictionary whose values override the base.
"""
if not base:
base = dict()
if not u... | 8f5cfc3805cd94809648a64311239b6bdc04adea | 672,308 |
def get_hashes_from_file_manifest(file_manifest):
""" Return a string that is a concatenation of the file hashes provided in the bundle manifest entry for a file:
{sha1}{sha256}{s3_etag}{crc32c}
"""
sha1 = file_manifest.sha1
sha256 = file_manifest.sha256
s3_etag = file_manifest.s3_etag
c... | d86d979fb5266f5a5b3027ddc6cf03548d4bf3a1 | 672,309 |
from typing import List
import sqlite3
def list_quotes(*, conn) -> List[sqlite3.Row]:
"""
Retrieves a list of quotes
"""
cur = conn.cursor()
cur.execute("select id, text, source, topic from quotes order by id desc")
return cur.fetchall() | 8fb6cc68b98ec9bfe4cbc3299ec4cde03f4c6045 | 672,310 |
def lowerColumn(r, c):
"""
>>> lowerColumn(5, 4)
[(5, 4), (6, 4), (7, 4), (8, 4)]
"""
x = range(r, 9)
y = [c, ] * (9-r)
return zip(x, y) | a51dcefed097f09315be21ec1aca958799f05d6b | 672,311 |
def summarize_filetypes(dir_map):
"""
Given a directory map dataframe, this returns a simple summary of the
filetypes contained therein and whether or not those are supported or not
----------
dir_map: pandas dictionary with columns path, extension, filetype, support;
this is the ouput o... | b825402d123b48354607e8fd76319b45bc586e32 | 672,312 |
import re
def show_ansi(text):
"""Make ANSI control sequences visible."""
replacements = {
'\033[1A': '{up1}',
'\033[2A': '{up2}',
'\033[1B': '{down1}',
'\033[1L': '{ins1}',
'\033[2L': '{ins2}',
'\033[1M': '{del1}',
'\033[31m': '{red}',
'\033[32m... | b857d7daaa5369349a415009416f485c4eadb0ff | 672,314 |
def staticTunnelTemplate(user, device, ip, aaa_server, group_policy):
"""
Template for static IP tunnel configuration for a user.
This creates a unique address pool and tunnel group for a user.
:param user: username id associated with static IP
:type user: str
:param device:... | 0367205462157fe8b242095f19cf936a24b9afd8 | 672,315 |
def build_cdf_sampling_list(results, rank_field_to_sort='WEIGHTED_RANK_RND'):
"""
:param results: a list of results in dictionary template
:param rank_field_to_sort: For example ['AVERAGE_RANK_RND', 'RANK_BING', 'WEIGHTED_RANK_RND']
:return: a list containing of length sum of rank_field_to_sort * [resul... | ab9be407c756b343e2896e09013e5fcfc4407faf | 672,318 |
def merge_all_elements(*elements):
"""
Merge all the elements in to a list in a flatten structure and they are sorted by pages and y coordinate.
:param elements:
:return:
"""
element_list = []
for element in elements:
if len(element) > 0:
for obj in element:
... | 9baa3d00056d26024932840c3d73d4c68f4d4e53 | 672,319 |
from typing import Tuple
def _build_label_attribute_names(
should_include_handler: bool,
should_include_method: bool,
should_include_status: bool,
) -> Tuple[list, list]:
"""Builds up tuple with to be used label and attribute names.
Args:
should_include_handler (bool): Should the `handler... | 52b704767b69a8a75e1824489c39e3b59c994a17 | 672,320 |
def constructQuery(column_lst, case_id):
"""
Construct the query to public dataset: aketari-covid19-public.covid19.ISMIR
Args:
column_lst: list - ["*"] or ["column_name1", "column_name2" ...]
case_id: str - Optional e.g "case1"
Returns:
query object
"""
# Public dataset
... | e2107800565b10b3ee21ab15db04fadc8b167f42 | 672,321 |
import os
def find_python_sources(src_dir, modules=('sage',)):
"""
Find all currently installed files
INPUT:
- ``src_dir`` -- string. The root directory for the sources.
- ``module`` -- list/tuple/iterable of strings (default:
``('sage',)``). The top-level directory name(s) in ``src_dir``... | 9b55ffaf7f2bbafc43bc08bb7b38e5b5fbc26384 | 672,322 |
def batch_unflatten(x, shape):
"""Revert `batch_flatten`."""
return x.reshape(*shape[:-1], -1) | 0cbde13e3621336a6571d7a047eafcf20124e1b6 | 672,323 |
import sys
def get_alpha(val, verbose=False, getscale=False):
"""
Get an alpha level associated with this amount
:param val: the value
:param verbose: more output
:param getscale: get the alpha scale regardless of val
:return: the alpha level, a number between 0 and 1
"""
alphalevels ... | c7ec947c290b6f86b2832c8356e2fa2f3d93ce88 | 672,324 |
def prepend_batch_seq_axis(tensor):
"""
CNTK uses 2 dynamic axes (batch, sequence, input_shape...).
To have a single sample with length 1 you need to pass (1, 1, input_shape...)
This method reshapes a tensor to add to the batch and sequence axis equal to 1.
:param tensor: The tensor to be reshaped
... | 2433b8ddf2ed9f5854b8c527e7e39b869939360d | 672,325 |
def shorten_trace_data_paths(trace_data):
"""
Shorten the paths in trace_data to max 3 components
:param trace_data:
:return:
"""
for i, (direction, _script, method, path, db) in enumerate(trace_data):
path = "/".join(path.rsplit('/')[-3:]) # only keep max last 3 components
trac... | 153929949faec06a5b9596784cdefdb6996cb760 | 672,326 |
def dms2dd(d, m, s):
"""
Convert degrees minutes seconds to decimanl degrees
:param d: degrees
:param m: minutes
:param s: seconds
:return: decimal
"""
return d+((m+(s/60.0))/60.0) | e8285ada31a1b8316e1d9563992475a197fdb76a | 672,327 |
def transpose_dataframe(df): # pragma: no cover
"""
Check if the input is a column-wise Pandas `DataFrame`. If `True`, return a
transpose dataframe since stumpy assumes that each row represents data from a
different dimension while each column represents data from the same dimension.
If `False`, re... | 9ef8f30337467fe256042389e03c4e052feb6a12 | 672,328 |
def load_single_line_str(s):
"""validates that a string is single line"""
s = str(s)
if '\n' in s:
raise ValueError('String value "{}" contains newline character. HINT: consider using '
'yaml ">-" operator for multi-line strings'.format(s))
return s | d097a17ccf3f9cff0350555204787f094811dc02 | 672,329 |
def write_data(f, grp, name, data, type_string, options):
""" Writes a piece of data into an open HDF5 file.
Low level function to store a Python type (`data`) into the
specified Group.
.. versionchanged:: 0.2
Added return value `obj`.
Parameters
----------
f : h5py.File
Th... | 748dbc7d646ec33c31f9ef393ae998b76b317d41 | 672,330 |
import math
def get_bg(bg_reader):
"""
Asks user to enter his/her blood glucose reading. Sanitizes user input,
echos read value back to user, and returns it to caller.
If user input cannot be parsed, function return nan.
:param bg_reader: Function responsible for reading information from user inpu... | 68ed77a15e1f54c447e8d3bfe5502de4d4d08aab | 672,331 |
def find_collection(client, dbid, id):
"""Find whether or not a CosmosDB collection exists.
Args:
client (obj): A pydocumentdb client object.
dbid (str): Database ID.
id (str): Collection ID.
Returns:
bool: True if the collection exists, False otherwise.
"""
... | 96f6bb66797b40daf137ed2d7920b6cd30697aa0 | 672,332 |
import json
def load_dicefile(file):
""" Load the dicewords file from disk. """
with open(file) as f:
dicewords_dict = json.load(f)
return dicewords_dict | 42da982410dfc1ac39a1f40766ba6f7a2824d088 | 672,333 |
def get_soup_search(x, search):
"""Searches to see if search is in the soup content and returns true if it is (false o/w)."""
if len(x.contents) == 0:
return False
return x.contents[0] == search | 402a9cf0523c0022d86f8c7eb7d502acb45a9291 | 672,334 |
def EVLACalModel(Source,
CalDataType=" ", CalFile=" ", CalName=" ", CalClass=" ", CalSeq=0, CalDisk=0, \
CalNfield=0, CalCCVer=1, CalBComp=[1], CalEComp=[0], CalCmethod=" ", CalCmode=" ", CalFlux=0.0, \
CalModelFlux=0.0, CalModelSI=0.0,CalModelPos=[0.,0.], CalModelPar... | 0aa7ef72d7a379868b2edba1ffea6aa2eee8f559 | 672,335 |
def get_interface():
"""
get the interface name
"""
interface = input("Enter the interface name: ")
return interface | e875ea6eb1b11133ab4947963a252f3ab9f8daeb | 672,336 |
import torch
def smooth_l1_loss(bbox_preds, bbox_targets, bbox_inside_weights, bbox_outside_weights, sigma=3.0):
"""as caffe implementation, the bbox_preds and bbox_targets should be a 2-dim torch Var
[[x1, y1, x2, y2],
[x1, y1, x2, y2],].
"""
sigma2 = sigma ** 2
diff = bbox_preds - bbox_targ... | 3c6b752858e2e62166527f0de9c55c058630c79f | 672,337 |
def line_or_step_plotly(interval_label):
"""
For a given interval_label, forecast_type determine any kwargs for
the plot.
"""
if 'instant' in interval_label:
plot_kwargs = dict()
elif interval_label == 'beginning':
plot_kwargs = dict(line_shape='hv')
elif interval_label == 'e... | 0a25cde0892066307d8d009847369725a804850c | 672,338 |
def split(children):
"""Returns the field that is used by the node to make a decision.
"""
field = set([child.predicate.field for child in children])
if len(field) == 1:
return field.pop() | 798ae7e7e82cb62b9b71f2e7453a7ceb77c07fae | 672,340 |
def is_continuous_subset(tensor_slice, tensor_shape, row_major=True):
"""
Figure out whether a slice is a continuous subset of the tensor.
Args:
slice_shape (Sequence(slice)): the shape of the slice.
tensor_shape (Sequence(int)): the shape of the tensor.
row_major (bool): whether th... | fd990152e630323adfcb89c591f4d6e58cd83c4b | 672,341 |
def multiplyPaulis(a,b):
""""
A simple helper function for multiplying Pauli Matrices. Returns ab.
:param: a: an int in [0,1,2,3] representing [I,X,Y,Z]
:param: b: an int in [0,1,2,3] representing [I,X,Y,Z]
"""
out = [[0,1,2,3],[1,0,3,2],[2,3,0,1],[3,2,1,0]]
return out[int(a)][int(b)] | fbde4ee067fbee01b85b9edf55a4cdb7775935ab | 672,343 |
import io
def load_instructions(filename):
"""
Function to read a string in from a text file and return that string.
:param filename: The name of the text file as a string
:return: The contents of the text file as a string
"""
filepath = ".\\" + filename
try:
file = open(filepath)
... | 01f6e787df96f08929d2a0406a0a9643646a5f23 | 672,344 |
def reverseList(head):
"""
递归 反转 链表
:type head: ListNode
:rtype: ListNode
"""
if not head :
return None
if not head.next :
return head
last = reverseList(head.next)
head.next.next = head
head.next = None
return last | c6c923a2c30302cf10809086d689b7e238c42e28 | 672,345 |
def reverse_str(input_str):
"""
Reverse a string
"""
return input_str[::-1] | df53f8e4ff65731865b3c9ef86fcb3a040c98677 | 672,346 |
from sys import version
def healthz():
""" Healthcheck """
return (f'{__package__} {version}', 200) | 295ad7d3e8ea342536d882bfe212f74b22fab584 | 672,347 |
import random
def single_introduction(end):
"""Single return a single introduction day for the introduction_days parameter"""
return [random.randint(0,end)] | 4a6756aac82548b1e94d544e46771f225558e2f5 | 672,348 |
def drop_suffix_from_str(item: str, suffix: str, divider: str = '') -> str:
"""Drops 'suffix' from 'item' with 'divider' in between.
Args:
item (str): item to be modified.
suffix (str): suffix to be added to 'item'.
Returns:
str: modified str.
"""
suffix = ''.join([suf... | 68ed4d44ef30243558b482964108bfe3a1f87552 | 672,349 |
def recode(posterior, levels, data, original_data, condition):
""" This is really a replace operation on a dataframe. """
for column in levels + ['combined_condition']:
if column not in posterior.columns:
continue
if column == 'combined_condition':
original_columns = con... | 5b65ed0dd673cebeaeee7be4e5e1e0627bece911 | 672,350 |
def length_ok_input_items(items):
"""Helper for union_line_attr_list_fld()
---
Takes a list of items (grabbed from the attribute structure) and
ensures that the user input-items per markdown line are of length
1. This check is needed for Sigma, G_in, and G_out for TMs.
However... | d9a8c98cd5c49fc2bcc10f723d3df4c7435138f2 | 672,352 |
def anzahl_ziffern(integer):
"""gibt die Anzahl der Ziffern einer Zahl zurück"""
string = str(integer)
return len(string) | 5843ea1fb7947e14cc44ab17a17cb92dbef0fcee | 672,354 |
def _read_node(f, scale):
"""Read a node card.
The node card contains the following:
=== ===== === ====== === ===
1 ID IV KC
=== ===== === ====== === ===
X Y Z
ICF GTYPE NDF CONFIG CID PSP
=== ===== === ====== === ===
"""
line = f.readline()
entries = [line[i : i... | f50cf617bf02f3d23aa1d09be15b3c49ebfae803 | 672,355 |
def environmentfunction(f):
"""This decorator can be used to mark a function or method as environment
callable. This decorator works exactly like the :func:`contextfunction`
decorator just that the first argument is the active :class:`Environment`
and not context.
"""
f.environmentfunction = Tr... | 86493da32150746333f90209725ae145188c9379 | 672,356 |
def Torsor(cls):
"""
Torsor(cls)
A parametric class. Implements a set of labels equipped with a free and
transitive action of a group `cls`. This means that the only operations
available are the addition and subtraction of x∊`cls` from a given element
of a torsor.
By default, the label... | dfb770ac26002f14e513620f2d2787b21bd9f6b4 | 672,357 |
def extract_intervals(request_history):
"""
Extract the continuous (start, end) intervals during which network IO happend.
Summing the duration of those intervals gives the total API call time as perceived
by the end-user (taking into account parallel requests using concurrency features).
"""
i... | 8d82ee5bac819ebd69885e6306f2bbc128a4b323 | 672,359 |
import numpy
def _msa_i_op(
lulc_array, distance_to_infrastructure, out_pixel_size,
msa_i_primary_table, msa_i_other_table):
"""Calculate msa infrastructure.
Bin distance_to_infrastructure values according to rules defined
in msa_parameters.csv.
Parameters:
lulc_array (array)... | 545e4fb6a031319934422daa658ac1e3c69c7b53 | 672,360 |
def get_model_columns(sm,model_index):
"""Return the data columns of the galaxy model (given by index)
:param sm: Sky model in human readable format (final hopefuly)
:param model_index: The index of the galaxy model
"""
ID = sm[model_index][:,0];
RA = sm[model_index][:,1];
RA_err ... | e30e487da5647587298360c4f84f07e2ad436a9f | 672,362 |
def match3(g1, s, guesses_number):
"""
Give the guesses_number that the user has.
"""
if g1 in s:
print("You have " + str(guesses_number) + " guesses left.")
else:
guesses_number = guesses_number - 1
if guesses_number == 0:
pass
else:
# print("... | 0ebee22c50b3708070424b4111a469b5eb1709a0 | 672,364 |
def calc_time(times):
""" Takes a list of times in HHMM-HHMM format, and returns the difference
between the first and second times
"""
cumt = 0
for t in times:
t1, t2 = t.split('-')
tm = (int(t2[2:]) - int(t1[2:])) % 60
th = 60 * ((int(t2[:2]) - int(t1[:2])) % 24)
... | ad9d62231501fe99290f1fa4e110b848a6b54e50 | 672,365 |
def compute_reporting_interval(item_count):
"""
Computes for a given number of items that will be processed how often the
progress should be reported
"""
if item_count > 100000:
log_interval = item_count // 100
elif item_count > 30:
log_interval = item_count // 10
else:
... | e82a1210e235afe9da1cd368900b7ac688488353 | 672,366 |
def _preprocess_graphql_string(graphql_string):
"""Apply any necessary preprocessing to the input GraphQL string, returning the new version."""
# HACK(predrag): Workaround for graphql-core issue, to avoid needless errors:
# https://github.com/graphql-python/graphql-core/issues/98
return g... | df2ef81ef8fc5311686cbfcc644ce187dce8e02f | 672,367 |
import sys
import os
def _user_data_dir(appname="BrazilDataCube"):
"""Return full path to the user-specific data dir for this application."""
if sys.platform == "win32":
const = "CSIDL_LOCAL_APPDATA"
path = os.path.normpath(_get_win_folder(const))
path = os.path.join(path, appname)
... | 9d8407d4378d80722dc3bde2fd188e519e2e2308 | 672,368 |
import argparse
def create_parser():
"""
Command Line parser for serialize_convention
Input: metadata convention tsv file
"""
# create the argument parser
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_a... | 88aba377d42f1b9a88ca8c6fc4902f095626a599 | 672,369 |
def merge_sort(elements):
"""
Use the simple merge sort algorithm to sort the :param elements.
:param elements: a sequence in which the function __get_item__ and __len__ were implemented,
as well as the slice and add operations.
:return: the sorted elements in increasing order
"""
length = l... | db056161445ca67aa6d4ab83d25082f21a529631 | 672,370 |
import argparse
def parameter_parser():
"""
A method to parse up command line parameters. By default it gives an embedding of the Bitcoin OTC dataset.
The default hyperparameters give a good quality representation without grid search.
Representations are sorted by node ID.
"""
parser = argpar... | 2c530bab2ce21f4f0419c687c70ad77e20f36fd8 | 672,371 |
def _sign(x):
""" returns sign function (as float)
if x is complex then use numpy.sign()
"""
sgn_int = x and (1, -1)[x < 0]
return 1.0 * sgn_int | 418748602be96a66c3c2bb77c50e152827352c50 | 672,372 |
def get_yn_input(prompt):
"""
Get Yes/No prompt answer.
:param prompt: string prompt
:return: bool
"""
answer = None
while answer not in ["y", "n", ""]:
answer = (input(prompt + " (y/N): ") or "").lower() or "n"
return answer == "y" | 8957f6a77716fb7ad85063dddf5921e108827ab5 | 672,373 |
import os
def is_readable(path):
"""
Check if a given path is readable by the current user.
:param path: The path to check
:returns: True or False
"""
if os.access(path, os.F_OK) and os.access(path, os.R_OK):
# The path exists and is readable
return True
# The path does ... | a06e33ce554f5e069fe77672db5bf248530cf0db | 672,374 |
def form_clean_components(rmsynth_pixel, faraday_peak, rmclean_gain):
"""Extract a complex-valued clean component.
Args:
rmsynth_pixel (numpy array): the dirty RM data for a specific pixel.
faraday_peak (int): the index of the peak of the clean component.
rmclean_gain (float): loop gain for cle... | 2bac5a50fff2e593e5aeab26a15f5dd814b61079 | 672,375 |
from os.path import dirname, join, exists
import re
def parse_requirements(fname='requirements.txt'):
"""
Parse the package dependencies listed in a requirements file but strips
specific versioning information.
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
... | c8d3e74746129aedabbd5be5d21875f398f98387 | 672,376 |
import re
import json
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'):
"""Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings
Args:
badjson_path (str): path to input json file that doesn't properly quote
goodjson_pat... | 1339c0f900f1c6162866983f2a575dc30b4820cd | 672,377 |
import re
def xstr(s):
"""
Converts null string to 'N/A'
"""
if s is None:
return 'N/A'
try:
# UCS-4
highpoints = re.compile(u'[U00010000-U0010ffff]')
except re.error:
# UCS-2
highpoints = re.compile(u'[uD800-uDBFF][uDC00-uDFFF]')
return s.encode('utf-8') | 05ae2934ee5f5b2f6b1a3817d0991011fa85328c | 672,378 |
def get_unique_values(df, column):
"""
Get unique strings from a column.
Numeric or other types of values will error out.
"""
unique_values = list(set(list(df[[column]][column])))
return [value.lower() for value in unique_values] | 07f7412f47430b5d771c5fb2bf04dc6d5835c759 | 672,379 |
import torch
def get_device():
"""Return default cuda device if available, cpu otherwise."""
return torch.device('cuda' if torch.cuda.is_available() else 'cpu') | 89d4ea0da76362af9791959faf099909ef17df41 | 672,380 |
def get_mpaxos_result(results):
"""
Returns a Results object from the 'results' list in which the protocol was
Multi-Paxos.
"""
return list(filter(lambda r: r.is_mpaxos(), results)) | ab141110716dcad68e6f85ded14f2d0bfa6ed28e | 672,381 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.