content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def SanitizeAPIName(name):
"""Sanitizes API filenames that are in subdirectories.
"""
filename = os.path.splitext(name)[0].replace(os.sep, '_')
if 'experimental' in filename:
filename = 'experimental_' + filename.replace('experimental_', '')
return filename | 780cbf4b14303de42c2ae24908a02570e21fc7e8 | 647,667 |
import yaml
def load_yaml_file(file_name):
"""Load YAML file.
Parameters
----------
file_name: str or pathlib.Path
YAML file name.
Returns
--------
dict_data: dict
YAML contents.
"""
with open(file_name, 'r') as f:
dict_data = yaml.load(f, L... | 7f2ac99700a80bc4eb99752f14ca1e67da41665c | 647,668 |
import os
def is_zero_length_file(fpath):
""" Determine if a file system path refers to an existing file that is zero length
Args:
fpath (str) : file system path to test
Returns:
bool : true if the path is an existing file that is zero length
"""
return os.path.isfile(fpath) and ... | f4a2e87b60b45317a592a89ad1d844798429295e | 647,669 |
def _parse_raw_dockerfile(lines):
"""
Author: Michal Papierski <michal@papierski.net>
https://github.com/mpapierski/dockerfile-parser
"""
result, current_line = [], []
for line in lines:
if line.startswith('#') or not line.strip():
continue
current_line.append(line)
... | 48b50caa81fc961260054431494754c6a2eb8437 | 647,670 |
import os
import uuid
def GetNodeName(output_dir):
"""Returns the cached Zircon node name, or generates one if it doesn't
already exist. The node name is used by Discover to find the prior
deployment on the LAN."""
nodename_file = os.path.join(output_dir, 'nodename')
if not os.path.exists(nodename_file):
... | 7617a6d4443fc555c6ad915f66d7ac7a27cfb3c0 | 647,671 |
def within(self, index):
"""
Like between() but takes a pandas index object.
:param pandas.Index index: pandas index
:returns self: result of between() with start/end as the ends of the index.
"""
try:
start = index.min().start_time
end = index.max().end_time
except Attribut... | d09c662b9e3d743d14535d3d99c6d4d53cd5a205 | 647,672 |
import subprocess
def proc_popen(cmd):
"""execute a command with Popen of subprocess in background
"""
subproc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, env={'PYTHONIOENCODING':'latin1'})
return subproc | ccda33b3461e13cb88bf0ec0e9b31933f42f7515 | 647,673 |
def read_transcripts(transcript_file):
"""Return a dict containing transcript data with UCSC ID as key"""
transcripts = dict()
f_in = open(transcript_file)
for line in f_in:
data = line.rstrip('\n').split()
transcript_data = { 'chrom': data[2],
'start': int(da... | cf00783e91667dc7516a68bcf700195b792f254c | 647,674 |
import torch
def batch_rotate_p4(batch, k, device=None):
"""Rotates by k*90 degrees each sample in a batch.
Args:
batch (Tensor): the batch to rotate, format is (N, C, H, W).
k (list of int): the rotations to perform for each sample k[i]*90 degrees.
device (str): the device to allocate... | e6d3365c5ba3c073cb7d63d97b1208b5584a947e | 647,675 |
def lin_sum(x, lr, y):
"""Returns linear sum."""
return x + lr * (y - x) | 6a7996e82ee7c0a8f611e8995c5537939e680564 | 647,677 |
def select_tags(tag_list, key_list):
"""
Return selected tags from a list of many tags given a tag key
"""
select_list = []
# select tags by keys in key_list
for tag in tag_list:
for key in key_list:
if key == tag['Key']:
select_list.append(tag)
# ensure o... | 66dd34b06a06c7dd26b59368522a1a33fb5fab08 | 647,678 |
import random
import string
def get_random_str(length):
"""
Returns a random string of length characters.
"""
return ''.join(random.choice(string.ascii_letters) for _ in range(length)) | 978dcb0a7a6d6cff87a1ce18a3474325e3fce941 | 647,681 |
def huber(x, y, scaling=0.1):
"""
A helper function for evaluating the smooth L1 (huber) loss
between the rendered silhouettes and colors.
"""
diff_sq = (x - y) ** 2
loss = ((1 + diff_sq / (scaling**2)).clamp(1e-4).sqrt() - 1) * float(scaling)
return loss | fe9ba23d60ddd6effbeec9c9b49634a443ba1ae9 | 647,682 |
def fill_zero(df):
"""Fill NaN with zero."""
df = df.fillna(0)
return df | 6d55c249a8c28da1fc8debe7bf47727e67ca1271 | 647,683 |
def form_template_to_dict(formtemplate):
"""
Initializes a dictionary of form data from the given list-of-dictionaries
form template, as formatted above.
Args:
formtemplate (list of dicts): Tempate for the form to be initialized.
Returns:
formdata (dict): Dictionary of initalized f... | bca5d6cbec70520df34f2d32afe1db46c1a08888 | 647,684 |
import subprocess
import re
def check_mac(host):
"""
Attempts to retrieve the MAC address of a given device using OS commands
:param host: (str) The IP address of a given device on the network
:return: (str) The name of a device or Unknown in case of any errors
"""
arp = subprocess.Popen(['arp... | dddfb1a0e51fbb7c20c93974f62bfd9a1137fde7 | 647,686 |
def delete_script(fmg, script_name, adom):
"""
This method deletes a script.
"""
datagram = {
'name': script_name,
}
url = '/dvmdb/adom/{adom}/script/{script_name}'.format(adom=adom, script_name=script_name)
response = fmg.delete(url, datagram)
return response | 95ecc7af70a50693ccf307a0a1dcd891364152f6 | 647,687 |
def get_channel(driver, team_name, channel_name):
"""
Retrieve a channel given a team and channel name.
Returns the JSON response from the Mattermost API.
"""
response = driver.channels.get_channel_by_name_and_team_name(
team_name, channel_name)
return response | d928f25d12ba931bb4b795db96412c03f2c559d8 | 647,689 |
def input_bool(question, default=None):
"""
:param str question:
:param bool default:
:rtype: bool
"""
if default is None:
question += ' [y/n]? '
elif default:
question += ' [Y/n]? '
else:
question += ' [y/N]? '
while True:
answer = input(question).lo... | cd799345108666f3840113e00d33fc043e3ea669 | 647,690 |
def make_ewma_metric(metric, alpha):
""" Format the name of an EWMA metric. """
return f"{metric}-ewma-alpha{alpha}" | 7af137592ef6d2e8d8fd871a0f96b4d9b760d1b2 | 647,691 |
def reporting_date(submission):
""" Format submission reporting date in MM/YYYY format for monthly submissions and Q#/YYYY for quarterly
Args:
submission: submission whose dates to format
Returns:
Formatted dates in the format specified above
"""
if not (submission.... | 5ef78cb819bddfa127a953b7d4a774e921a5124f | 647,692 |
def cli(ctx, name, owner, changeset_revision):
"""Return a list of dictionaries of metadata about a certain changeset revision for a single tool.
Output:
Returns a list of the following dictionaries:
#. a dictionary defining the repository
#. a dictionary defining the repository revision ... | ef5ca31a798d4425a923a3cd50953af653891607 | 647,693 |
def subreddit_idx_to_subreddit(idx):
"""
Warning: temporarily hardcoded for convenience. Beware!
:param idx:
:return:
"""
subreddits = {0: '100DaysofKeto',
1: 'AskMen',
2: 'AskMenOver30',
3: 'AskWomen',
4: 'AskWomenOver30',... | 21d398d3a30792476ff69b754511b7f7367aad8e | 647,694 |
def matrix_inverse(matrix):
"""Invert a 6-item homogenous transform matrix.
A transform matrix [a, b, c, d, e, f] is part of a 3x3 matrix:
a b 0
c d 0
e f 1
Invert it using the formula for the inverse of a 3x3 matrix from
http://mathworld.wolfram.com/MatrixInverse.html
"""... | e2a45f3ca1e082c2192e98b7e2f8344e803de703 | 647,695 |
def capitalize_first(str):
"""Capitalizes only the first letter of the given string.
:param str: string to capitalize
:return: str with only the first letter capitalized
"""
if str == "": return ""
return str[0].upper() + str[1:] | ad08e1ca5e50bf747e6166791cd6ec3c076fd29c | 647,697 |
def build_code(codes_dict):
"""
Builds a code based on a codes dictionary
:param codes_dict: A dictionary with the code and whether it's flagged or not.
:return: The full code
"""
code = 0x00000000
for value in codes_dict.values():
if value[0]:
code += value[1]
retu... | ddbfd409a2d2b2ccae445c7863ac1fef0e566e43 | 647,698 |
def count_ints(cxs):
"""
Given cxs, a list of [(name, set([id1,id2...])), ...], return the number of
possible positive pairwise interactions implied.
"""
def count_pairs(items):
n = len(items)
return int(n*(n-1)/2)
return sum([count_pairs(c[1]) for c in cxs]) | b6a8a02f73c6bed8ca6884baced2072f5fbb6ffc | 647,699 |
def intersection(a, b):
"""
Returns the intersection of sets a and b.
In plain english:
Returns all the items that are in both a and b.
"""
return a.intersection(b) | 0e3496306f103ccabb6f142203ea11942cdfc3d8 | 647,700 |
def dummy_predictor(X):
"""just predicts always no surge"""
return [False] * len(X) | 2376edfb16d81be70ad18f21cd3680b9c509e03c | 647,701 |
def parameter_value(parameter):
"""Get current parameter value.
If value attribute references a geoprocessing value object, will use this
function recursively to get the actual value.
Args:
parameter (arcpy.Parameter): Parameter to check.
Returns:
Current parameter value.
"""
... | e22991253b34a5bd984348eab3b429975833e79d | 647,702 |
def clean_date(date):
"""
Perform date format cleanup
"""
months = {'Jan': 'January',
'Feb': 'February',
'Mar': 'March',
'Apr': 'April',
'Mai': 'May',
'May': 'May',
'Jun': 'June',
'Jul': 'July',
... | 89f1b8980aa1be7a84b66fb5d28947a5beb47ea5 | 647,703 |
def generate_primes(lower_limit, upper_limit):
"""Function to generate prime numbers from a given interval
param lower_limit: int variable to store lower limit value
param upper_limit: int variable to store upper limit value
return: list of prime numbers
"""
if not isinstance(lower_limit, int)... | 60c485b471b1de3126f98784baf8b1b58e0b719b | 647,704 |
def options_as_dictionary(meta):
"""
Transforms a list of tuples to a dictionary
Args:
meta (list): A list ot option tuples
Retuns:
dict: A dictionary of options key - values
"""
module_config = {}
for seltuple in meta:
module_config.update({seltuple[0]: seltuple[1]})... | fc82aaca0bebfd22d4a17c6dd6e92f8b30d35e3d | 647,705 |
def del_char_val(inline, char):
"""
Delete all chars matching the given parameter.
Args:
inline(str): Input string.
char(char): A character value which has to be deleted.
"""
return inline.replace(char, '') | 19aac570b0ddb5507c383cf2400ea906fe0d6317 | 647,706 |
import subprocess
def dirty_rm_rf(directory_name):
""" Executes a quick and dirty `rm -rf directory_name'
Works on directories or files
Use subprocess because its easier to let bash do this than Python
:param directory_name:
:returns bool:
"""
subprocess.call(
[b'/bin/bash', b'-c'... | 266e2f19f0f7eff4a7814d71e05f41dd483711d1 | 647,707 |
def get_subregion(row):
"""
Parse subregion and month names from SUBREGION row.
"""
cell_text = [cell.text_content().strip() for cell in row]
return cell_text[0], cell_text[3:] | c73f9b012c556a080a989284bcf6ccbc4bd054af | 647,708 |
def is_str_or_list_str(s):
"""
Return boolean whether `s` is a string or list of strings.
"""
return isinstance(s, str) or \
(isinstance(s, list) and all(isinstance(x, str) for x in s)) | b8972eb2c77989acb57886c135e5753180025747 | 647,709 |
def _namespaceTag(xmlns, tagName):
"""Preface an XML tag name with the provided namespace"""
return ''.join(["{", xmlns, "}", tagName]) | 0783f95f4e2a77771fd163835b3be706a375b2f1 | 647,710 |
def format_card(note: str) -> str:
"""Formats a single org-mode note as an HTML card."""
lines = note.split('\n')
if lines[0].startswith('* '):
card_front = '<br />{}<br />'.format(lines[0][2:])
else:
print('Received an incorrectly formatted note: {}'.format(note))
return ''
... | b05c6d9e2419f3aa7c78811faf7c4ebf171d3073 | 647,711 |
import requests
def get_files_from_pr(pr_num):
"""Return a list of changed files from a GitHub Pull Request
Arguments:
pr_num {str} -- Pull Request number to get modified files from
Returns:
{list} -- List of modified filenames
"""
files = []
pr_url = f"https://api.github.com... | 6b31ee4dd71e5d472d3ded5ae237d6884d27883d | 647,712 |
def is_right(gaze):
"""Returns true if the user is looking to the right"""
if gaze.pupils_located:
return gaze.horizontal_ratio() <= 0.5 | b5adeee8e8be252a9379efc3a5531ce9b6b20aa9 | 647,713 |
def str_to_list(string, delim=',', type='float'):
""" Convert a str (that originated from a list) back
to a list of floats."""
if string[0] in ('[', '(') and string[-1] in (']', ')'):
string = string[1:-1]
if type == 'float':
lst = [float(num) for num in string.split(delim)]
elif ty... | 7edb5ac9382f2bc225bae4937b6406642b9349e3 | 647,714 |
def argsort(seq, key=None):
""" equivalent of numpy's argsort in basic python
Modified after http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python
>>> a = ['a', 'd', 'c']
>>> argsort(a)
[0, 2, 1]
>>> argsort(a, key=lambda x: {'a':2,'c':1,'d':0}[x])
[1, 2, 0... | ee35f1190f64bb7a9e8cdce12c132eb762897164 | 647,715 |
from typing import Dict
from typing import Any
def get_dict_value_recursively(dct: Dict, key: str) -> Any:
"""
Nest into the dict given a key like root.container.subcontainer
Args:
dct: Dict to get the value from.
key: Key that can describe several nesting steps at one.
Returns:
... | 1d6bcc6998c3523890845733362f41bc09d1a62c | 647,716 |
def base_agreement(hparams):
"""Adds base hparams for AgreementMultilingualNmt."""
# Encoder agreement.
hparams.add_hparam("enc_agreement_coeff", 0.0001)
hparams.add_hparam("enc_agreement_loss", "cosine")
hparams.add_hparam("enc_agreement_pool", True)
hparams.add_hparam("enc_agreement_enable_step", 100000)
... | 6d3478e0feca9ccc6e8531676a4f6ab2524f9566 | 647,717 |
def Crossing1Files(fileName, ind=None):
"""
Takes a filename of the structure used for the Crossing 1 videos - YYYMMDD_hhmmss-suffix.mkv
Retrieves the datetime of the start of the video
Input:
fileName: Name of the file
ind: Indicator of whether it is the left or right crop of the video... | 9228908b6f95dd0ef2e61e7cb2a2a2c52eb77cb4 | 647,718 |
def compute_durations(timestamp_df):
"""Compute time durations of interest from timestamps dataframe and append new cols to dataframe"""
timestamp_df['wait_for_1st_inspect'] = timestamp_df.loc[:, 'got_officer_ts'] - timestamp_df.loc[:, 'arrival_ts']
timestamp_df['1st_inspect_time'] = timestamp_df.loc[:, 'r... | bd9be8504a934b503d1b76f4e5bd6cebb95fd6d5 | 647,719 |
def split_encoded(data, encoding, max_split=None):
"""Split ID3v2 frame data according to encoding."""
remainder = data
values = []
num_split = 0
while True:
try:
if encoding in ['iso-8859-1', 'utf-8']:
head, tail = remainder.split(b'\x00', 1)
else:
if len(remainder) % 2 != 0:
remainder += b... | b7b38a8fdde1be07d84eb1161c8f6b981eee635c | 647,720 |
import inspect
def is_fitted(model):
"""Checks if model object has any attributes ending with an underscore"""
return 0 < len( [k for k,v in inspect.getmembers(model) if k.endswith('_') and not k.startswith('__')] ) | 7a7a7479d1718d0af2c3a01b9c92bf2d714ec9bf | 647,721 |
def permission_to_string(perm):
"""
Transforms a Permission instance
into a string representation.
"""
app_label = perm.content_type.app_label
codename = perm.codename
return '%s.%s' % (app_label, codename) | c65c29734792d2b56a84630a638cac275a263c4e | 647,722 |
import json
def _search(kwargs, stations):
""" search for arbitrary string"""
idx = []
for k in stations:
txt = json.dumps(stations[k])
if kwargs['search'].lower() in txt.lower():
idx.append(k)
flt = list(set(idx).intersection(stations))
return {k: stations[k] for k in... | 95c17241a71c524b9fd08275a750c6f4a16687fa | 647,723 |
from typing import Any
def reachable_states(self, s0: Any):
""" Computes all states reachable from s0.
"""
result = {s0}
stack = [s0]
domain = self._domain
while len(stack) > 0:
if not len(result) % 100:
print("Expanded {} states.".format(len(result)))
s = stack.pop... | ef3a188d38207c93d9c74f499dd0b6abd8616eda | 647,724 |
import sys
import platform
def get_version_str(algorithm_str):
"""
Common method to retrieve the version string of the running script.
:param: algorithm_str - name of algorithm to log with the version info.
:return: returns version string.
"""
# Get the Python version information
verstr = ... | 2c05d8c7ea6d53ac9bf09b311e01890dc3552bf0 | 647,725 |
def convert_language_code_to_iso639_2(lang_code):
"""
Translate OpenSubtitle language code to its iso-639-2 equivalent.
OpenSubtitles seem to support some extensions to iso-639-2, for instance
"pob" means "brazilian portuguese".
See http://www.opensubtitles.org/addons/export_languages.php.
:p... | dfd7ca6139c7c833e44e63c117638ddcf773800f | 647,726 |
import re
def _except(txt, pattern):
"""
Show only text that does not match a pattern.
"""
rgx = "^.*({pattern}).*$".format(pattern=pattern)
unmatched = [
line for line in txt.splitlines() if not re.search(rgx, line, re.I)
]
return "\n".join(unmatched) | 537e6631c09040e172f8309d171715d3c0794602 | 647,727 |
import numpy as np
def triangulate_nviews(P, ip):
"""
THIS FUNCTION WAS COPIED FROM davegreenwood's triangulation.py FILE ON 2022 JAN 17
https://gist.github.com/davegreenwood/e1d2227d08e24cc4e353d95d0c18c914
Triangulate a point visible in n camera views.
P is a list of camera projection matrices.... | 8ab9a47b02af7cf53d0462ee9a82a1350d01f7fb | 647,728 |
import subprocess
def get_changed_files(rev):
"""
Get all changed files between the working tree and `rev`
"""
changed_files = (
subprocess.check_output(
["git", "diff-index", "--diff-filter=AMU", "--name-only", rev]
)
.decode()
.split("\n")
)
return... | 18716c20589d1fec1356e05b702e4d81d684adf0 | 647,729 |
def find_largest_anysize_at_xy(grid, x, y):
"""
Finds the largest sizexsize grid with top-left location (x,y).
"""
maxsize = min(300 - x, 300 - y)
record = grid[(x,y)]
record_tuple = (x, y, 1)
prevsize = record
for size in range(2, maxsize + 1):
cand = prevsize
for i in r... | a5d70616f9988db6d0bbbf8612d7c81f37e1e3e0 | 647,730 |
def find_boundaries(x, y, ground_map):
"""
Returns two tuples for the left and right, each containing an x position and string
indicating if that position is a 'wall' or a 'drop'.
"""
initial_x = x
# Find Left boundary
left_boundary = None
while left_boundary is None:
x -= 1
... | 817bd881fa77c969fe3f4a2cbc414b2d6ada0173 | 647,731 |
import platform
def get_platform():
"""
Get platform name.
Returns:
str, platform name in lowercase.
"""
return platform.system().lower() | b0d482763792ab288ae1e91afcfca14dac73631b | 647,732 |
import pytz
def validate_timezone(zone):
"""Return an IETF timezone from the given IETF zone or common abbreviation.
If the length of the zone is 4 or less, it will be upper-cased before being
looked up; otherwise it will be title-cased. This is the expected
case-insensitivity behavior in the majorit... | 41673d0f70ead61b74a186206d198f2278ace0b7 | 647,733 |
def max2(x,y):
"""
Returns: max of x, y
Parameter x: first value
Precondition: x is a number
Parameter y: second value
Precondition: y is a number
"""
# Put the max inside of y
if x > y:
temp = x
x = y
y = temp
return y | 773d5270aee613a744fca9557fb33fbbbb14f6aa | 647,735 |
import random
def rand_scale(s):
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Gets a randomized scaling based on given s term
- Returned scaling can be less than or greater than 1
----------
"""
scale = random.uniform(1.0, s)
flip_scale = bool(random.randint(0,1)... | aebca8470d5885a3b524251e0afbad09fe1b44db | 647,736 |
def set_rdmol_positions_(mol, pos):
"""
Args:
mol: An `rdkit.Chem.rdchem.Mol` object.
pos: (N_atoms, 3)
"""
for i in range(pos.shape[0]):
mol.GetConformer(0).SetAtomPosition(i, pos[i].tolist())
return mol | 7210ccba078b627f812ebc31493d7e38d1eaf9e3 | 647,737 |
import argparse
def get_arg_parser(parser=None):
"""Parse args and do basic checks.
Args:
parser (argparse.ArgumentParser): an argument parser instance
Returns:
argparse.ArgumentParser: the argument parser instance
Notes:
if parser is None, creates a new parser instance... | 7ae8fe07038e2533c5070a5ebc6a3f44c895771d | 647,738 |
def f2(a):
"""Quy hoạch động cho bài toán tìm độ dài lớn nhất dãy con không giảm
Thuật toán có thời gian O(n^2) và không gian O(n)"""
n = len(a)
l = [1]*n #Khởi tạo mảng lưu trữ bộ đếm tăng theo công thức L[1] = 1
for i in range(n):
for j in range(i):
if a[i] >= a[j]: #nếu giá tr... | dd6b0663999b4606f58e0cb95e371bdc9ff27a1f | 647,739 |
def contrast(low, high, *channels):
"""
Эффект пониженной контрастности.
:param low: нижнаяя граница.
:param high: верхняя граница.
:param channels: RGB каналы.
:return: RGB c эффектом кпониженной контрастности.
"""
rgb = []
for channel in channels:
if channel < low:
... | 0550f2fc99f0a22411b867943ac128466e5a86a0 | 647,740 |
def f():
""" -> int """
# j : Number
j = 1.2
# i : int
i = j + 3
return i | 00955ed26545b63436126bc6212b0a9d3181f308 | 647,741 |
from typing import Dict
from typing import Any
def parse_mdp(mdp_file: str) -> Dict[str, Any]:
"""
Reads an MDP file and puts the parameters and their values into a dictionary
:param mdp_file:
:return:
"""
res = dict()
with open(mdp_file) as fp:
for line in fp.readlines():
... | dbf8a9badbc7ec4d61bfd80509c9966b0e5287b6 | 647,742 |
def good(seconds,needed_number_of_copies,x_seconds,y_seconds):
"""
This function is a little tricky
We need to make 2 copies as fast as possible. To do this, we need to use the copier that uses the minimum amount of time.
This minimum copier needs to run once to generate an extra copy
Consequentl... | b2e03d87f945c07dee1fc0fb2c39754c1ff7520c | 647,743 |
def xy(x:int, y:int) -> int:
"""Converts coordinates [x,y] in [(0-8),(0-8)] to [0-80] array location
"""
return y*9 + x | a9925c9ff1aead156b7157114638696f95765f79 | 647,744 |
def is_binary(g):
"""check if the DAG is binary
"""
for n in g.nodes():
if len(g.neighbors(n)) > 2:
return False
return True | e3729885399da61e117bedd9ba19857662af206a | 647,745 |
def divide(x, y, use_floor=False):
"""
Divides two number
:param x: dividend
:param y: divisor
:param use_floor: flag to use floor division
:return: division of two numbers
"""
if use_floor:
return x // y
return x / y | dabd0c577daf78e4193e5b04383bf09910b2441e | 647,746 |
import json
def _get_as_str(input_value):
"""
Helper method to serialize.
:param input_value:
:type input_value: str or List of str
:return: serialized string
:rtype: str
"""
result = None
if input_value:
if type(input_value) == str:
result = input_value
... | 1c921ed12e3894ec1477b063220453871c9bfd9d | 647,747 |
import pkg_resources
import sys
import os
import hashlib
def getRequirements (dist):
""" Get dependencies of a package.
Figure out packages’ dependencies based on setup/distutils, then look at
modules loaded and compute hashes of each loaded dependency.
This does not and cannot protect against malic... | f627e1ae5fff2d07e16fc3c63be3139b774ea791 | 647,748 |
import subprocess
def pdf_to_text(pdf_bytes):
""" run pdftotext from poppler """
p = subprocess.Popen(['pdftotext', '-enc', 'UTF-8', '-', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
outs, errs = p.communicate(pdf_bytes, timeout=10)
return outs... | 3106a22a0a65ac8846f59e4e211f236edaddb7f0 | 647,749 |
import os
def _get_app_absolute_dir_path(path):
"""It works only in tests dir"""
file_dir = os.getcwd()
return os.path.join(file_dir, path) | f713a14ab7ebfe20c259929b926a5b493ee8081c | 647,750 |
def same_type(s1: str, s2: str) -> bool:
"""A and a are the same type"""
return s1.lower() == s2.lower() | 07ea4adc137471ffe3aef7c075f8eeae94f3f797 | 647,751 |
def assign_rows_helper(note_fields, table_row):
"""
Builds and returns a String of notes from the fields specified in :param
note_fields and populated with the data for those fields in :param
table_row
:param note_fields: Note fields from profile the user wants included in
the match sent to the... | dce7b8a4343fb07666c92a1fbc6e810886d10808 | 647,752 |
def get_global_option(checker, option, default=None):
""" Retrieve an option defined by the given *checker* or
by all known option providers.
It will look in the list of all options providers
until the given *option* will be found.
If the option wasn't found, the *default* value will be returned.
... | 2f08d7c102471f80922aed87e161dc10614f60ff | 647,753 |
def createDependencyDictionary(ordering_matrix):
"""create dictionary of dependencies for toposort"""
dep_dict = dict()
for i in range(len(ordering_matrix)):
dep_dict.update({i: {j for j in range(len(ordering_matrix))
if ordering_matrix[i][j] > 0}})
return dep_dict | fb9f36c3e29cf7489b6f499593a43b044a465a08 | 647,754 |
import json
def read_json_file(input_data):
"""Read data source file. File is in json format"""
with open(input_data, "r") as src:
data = json.load(src)
return data | b6ba37796c5cce7605ab346f456b6e14ab9fe6cd | 647,755 |
def calc_doc_word_lengths(word_counts, wordlen_minmax):
"""Take in a word count dictionary and return a dictionary where the keys
are the length of each word and the values are the total occurance of
words with that length in the document.
"""
# Initialize word length distribution dict with keys de... | 062c811d1dd174b78585b7ac5a9ec7acaaaa0d76 | 647,756 |
def get_weight(item):
"""Get sort weight of a given viewlet"""
_, viewlet = item
try:
return int(viewlet.weight)
except (TypeError, AttributeError):
return 0 | 1e60b2731cf69384a4f55a958afff2ecc3577247 | 647,757 |
def efacet(self, num="", **kwargs):
"""Specifies the number of facets per element edge for PowerGraphics
APDL Command: /EFACET
displays.
.. warning::
This will not change element plotting within PyMapdl with
``eplot(vtk=True)``
Parameters
----------
num
Number of fac... | 9e4bc214eba1adbff08d9230453d9ef2bfcecfb6 | 647,758 |
import platform
def get_patch_os_version():
"""Returns the minor OS version."""
os_version_tuple = platform.mac_ver()[0].split('.')
return int(os_version_tuple[2]) | 988a433ab4f26509f233dcc22e1b8f3fd13a511e | 647,759 |
def nopat(operating_income, tax_rate):
"""
nopat = Net Operating Profit After Tax
"""
return operating_income * (1-(tax_rate/100)) | de002f10b5deebf22e6a53428bbef663df649783 | 647,760 |
import sys
def add_target(filename):
""" Returns the target class, using the filename (index of the dataframe). """
target = filename.split('_')[1].lower()
if target == 'covid':
return 1
elif target == 'asthma' or target == 'normal':
return 0
else:
print('Make sure the fi... | 845b96b0a65a0bbb89d91b59ba1da019a4fa45e7 | 647,761 |
def encryptxor(key, message):
"""
Takes two strings, key and message, and returns an encrypted ascii string
"""
message_ord = [ord(char) for char in message]
key_ord = [ord(key[index%len(key)]) for index in range(len(message))]
return "".join([chr(key_ord[i] ^ message_ord[i]) for i in range(len(... | 4aa7da290cf418594148d8d373b34fba04ca35ac | 647,762 |
import torch
def sqrt_PEHE(po: torch.Tensor, hat_te: torch.Tensor) -> torch.Tensor:
"""
Precision in Estimation of Heterogeneous Effect(PyTorch version).
PEHE reflects the ability to capture individual variation in treatment effects.
Args:
po: expected outcome.
hat_te: estimated outcom... | 16d600efde81f5e3a59ee0573e59cbe50b01a8d7 | 647,763 |
def get_optimal_parens(chain, mid, i, j):
""" recursive algorithm for string presentation
of optimal multiplication chain
"""
if i == j:
return '[' + str(chain[j]) + ' ' + str(chain[j + 1]) + ']'
else:
return ('(' + get_optimal_parens(chain, mid, i, mid[i][j]) +
'... | 9f7dd3bbcbb78f63f7acbfee8eec97f4b87740e7 | 647,764 |
import os
def _get_relative_path(control, fn):
"""
If relative paths are used, they should be relative to the control file
Parameters
----------
control : str
control file path and name
fn : str
file path and name
Returns
-------
str : relative path
"""
... | b401ac0494642b1930ac80900e587ca70052d145 | 647,765 |
def _is_constant_mapping(val_dict):
"""
@param val_dict:
Defines the mapping, by defining an output value for each row of
constrains. Each row is defined by a dictionary of operand names to
operand values.
@type val_dict:
[ ([ dict(opname:string -> opval:string) ], value:string) ]
The r... | 8a9f5502d2646095ac59aa3c5d7735fa210f29e3 | 647,766 |
def is_unique(digit, cell, grid):
"""
Checks if a given digit is unique across its row, column and subgrid.
Arguments:
digit {number} -- The digit to check for
cell {tuple} -- The (x, y) coordinates of the digit on the grid
grid {number matrix} -- The matrix to check the digit a... | 397d6629ad37129f4c7465c02f84046800adbc61 | 647,767 |
def _calc_bin_size(n_bins, t_start, t_stop):
"""
Calculates the stop point from given parameters.
Calculates the size of bins `bin_size` from the three parameters
`n_bins`, `t_start` and `t_stop`.
Parameters
----------
n_bins : int
Number of bins
t_start : pq.Quantity
S... | 2aed891ff22fbae567b12b47ee430f5b1127230d | 647,768 |
def getShowId(show, conn):
"""
Return the show id given its name. (Database query)
:param show:
:param conn:
:return: id_show (integer)
"""
cur = conn.cursor()
cur.execute("SELECT id_show FROM show WHERE name=?", (show,))
id_show = cur.fetchone()[0]
return id_show | ca2cb90be09d0fa745819c9300d4f45937b6e4d5 | 647,769 |
import types
def objToNestedNs(obj):
""" Convert an object into a (potentially) nested namespaces """
if isinstance(obj, dict):
nnObj = {}
for k, v in obj.items(): # pylint: disable=invalid-name
nnObj[k] = objToNestedNs(v)
nestedNs = types.SimpleNamespace(**nnObj)
el... | 7bce3184a535d6c2bd025b2dd609616293b1b90e | 647,770 |
def _explode_indexes(df, axis_type, drop_original=False):
"""
Performs an operation similar to explode, but uses the index of the cell as the differentiator.
:param df: the input dataframe of body cells
:param axis_type: either ``"row"`` or ``"column"``, determining which axis to be operating on.
:p... | ebfe8621bec25e7204a3596f817443a355eb9fc9 | 647,771 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get all logdb objects
"""
return isamAppliance.invoke_get("Get all logdb objects",
"/core/rsp_logdb_objs") | ebba65199f6ff3e118591633616bde734ab0b0d4 | 647,772 |
import subprocess
import sys
import re
def get_file_version(file_path, version_cmd):
"""
Get executable file version
"""
# Return values
err = None
version = None
# Build vastool command
cmd = []
cmd += [file_path]
cmd += [version_cmd]
# Exec file to get version
try:... | bd4e19c058d8f6873b16d5f1ccbbcff09e0baaa0 | 647,773 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.