content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _scalarize(value):
"""Scalarize a value.
If VALUE is a list that consists of a single element, return that
element. Otherwise return VALUE."""
if type(value) == list and len(value) == 1:
return value[0]
return value | d5eb2e0a42ed91472bf83d527c85e6adf4cc9200 | 646,074 |
def MeansOpenInProject(status, config):
"""Return true if this status means that the issue is still open.
Args:
status: issue status string. E.g., 'New'.
config: the config of the current project.
Returns:
Boolean True if the status means that the issue is open.
"""
status_lower = status.lower()... | 54e6d0b6047f9cf565b43c67126ba79bb5e594f0 | 646,075 |
def choose_peers(relay, relay_count, worker_count, min_w2r, min_r2w):
"""
Given `relay`, the position of relay within the affinity set for a
given service, the number of relays in that set (`relay_count`), the number
of workers for the service (`worker_count`), the minimum number of
connections requ... | 9539394c26d093f8f6fba1165e8119ca946226aa | 646,076 |
def str_as_bool(val):
""" Interpret the string input as a boolean
"""
if val.lower() in ("false", "none", "no", "0"):
return False
return True | f38e56b174a93523eb7adcd15ba5a1263d27922d | 646,077 |
def MakeCopyList(alist):
"""Make a copy of a list"""
#newlist = the copied list
newlist = []
for x in range(len(alist)):
newlist.append(alist[x])
return newlist | d2eb3f9d9613e9dee44c1e37182d22f6b48e9a33 | 646,078 |
def merge_dicts(*dicts):
""" Merge two dictionaries
example: merge({1:'a', 2:'b'}, {1:'c'}) -> {1:['a','c'], 2:['c']}
Parameters
----------
dicts
Dictionaries to be merged
"""
temp = {}
for dict_ in dicts:
for key, value in dict_.items():
if key in temp.key... | 5061b2bcf83a893a68ba67d3fffeefb5c17eedb8 | 646,079 |
def mk_error(buf, errbnch, deltalines):
"""Make a formatted error message.
"""
lines = buf.split('\n')
res = [errbnch.errstr]
if errbnch.lineno != 0:
# Define the range of lines to be shown
startline = max(1, errbnch.lineno - deltalines)
endline = min(errbnch.lineno + deltal... | f9b6b546f03037eb1e467c6fb6232df0cceeefc9 | 646,080 |
def get_attrs():
"""Get default attrs for tan."""
default_attr_map = {
"enable_auto_inline": False,
}
return default_attr_map | 3ea65b1513da4fa56c3e35d4468dee7794a836df | 646,081 |
import re
def scraping_txt_file(filetxt):
"""This scrape the data inside text files using regular expression. """
datum = []
with open(filetxt, "r", encoding="latin1") as foo:
for line in foo: # I think a genertator is imaginable here!
pattern = re.compile(
r"(?P<Date_... | 92bb74730bdaa4805b9c2fd664b28fb830bae534 | 646,083 |
def _fit_unconstrained(inv, XTY):
"""Fit unconstrained"""
return inv @ XTY | 9248c050cfd44bc98f2f579a4dd642374b5bd735 | 646,084 |
def val_interpolate(x1, y1, x2, y2, x):
"""Perform linear interpolation for x between (x1,y1) and (x2,y2) """
d = [[x1, y1],[x2, y2]]
output = d[0][1] + (x - d[0][0]) * ((d[1][1] - d[0][1])/(d[1][0] - d[0][0]))
return(output) | a8ba1b89433a561b7a52d02031cee2f2633f7730 | 646,085 |
import subprocess
def get_site_packages_path() -> list[str]:
"""Get site packages path by using user's python binary,
this will allow virgil to check dependencies of user's
environment when it's installed globally
"""
return [
subprocess.check_output(["python3", "-c", "import site;print(si... | 4b7e18542d9f1ab06fc06704022467a06cb8da63 | 646,086 |
import glob
import subprocess
def check_for_migration():
"""If migration files are found, delete them and return true"""
half_bundle_pattern = '/tmp/nagiosbundle-*.tar'
half_bundles = glob.glob(half_bundle_pattern)
if half_bundles:
for cur_file in half_bundles:
subprocess.run(['rm'... | a5b72681a2aba27f10675a5bb2021c8545e92a93 | 646,087 |
def subtract(x, y):
""" Returns the first vector minus the second. """
n = len(x)
assert len(y) == n
return map(lambda i: x[i]-y[i], range(0, n)) | dd66579b99d01c42b9773a116b4989910a6be3be | 646,088 |
def list_of_dicts_is_homogenous(dicts_list):
"""
Returns True if dictionary values are all the same
Returns False if more than one value is different
"""
previous_item = dicts_list[0]
for item in dicts_list:
if previous_item != item:
return False
return True | 8a9213af11f1766b4b1bce1c5fae403a379744b6 | 646,089 |
import json
def json_g_check(folder_loc):
""" Checking if a thread is group chat"""
with open(folder_loc + "/message_1.json", "r", encoding='utf-8') as file:
raw_data = json.load(file)
if raw_data["thread_type"] == "Regular":
return False
elif raw_data["thread_type"] == "R... | 1c527755a1f952a07f2adc95270b61d4729fcb0a | 646,090 |
import re
def remove_non_ascii(text):
"""
Remove non ascii characters in the text
Parameters
----------
text : str
Returns
-------
text: str
"""
return re.sub(r'[^\x00-\x7F]', ' ', text) | f32fcc3de385d5c16de7e821d48085f88389b4bd | 646,091 |
def check_build_vocab(func):
"""A decorator to make sure the indexing is built before used.
"""
def _wrapper(self, *args, **kwargs):
if self.word2idx is None or self.rebuild is True:
self.build_vocab()
return func(self, *args, **kwargs)
return _wrapper | e2090241a05127f4893e56df463430a02e40ab0d | 646,092 |
def lens(lists):
"""Returns the sizes of lists in a list."""
return list(map(len, lists)) | 495ed5e2c1dc598eea8c6e5016d63c251c597f2f | 646,093 |
import pickle
def load_transform(file):
"""
Load a transform object
"""
with open(file, 'rb') as input_file:
transform = pickle.load(input_file)
return transform | 0be183a69b3eb8a833edbd4a1241c7b940e24495 | 646,094 |
import os
import argparse
def file_exists(file_name):
"""return the real path to the file if it exists, otherwise
raise an argparse ArgumentTypeError
"""
if os.path.isfile(file_name):
return os.path.realpath(file_name)
else:
raise argparse.ArgumentTypeError(
"{file_name... | ee13152125fb7616b5757af2ffa48f2975e79a66 | 646,095 |
def report_file_path(report_path, report_label, report_extension):
"""
Function to create a path for report files.
Parameters:
report_path (path): Report file path
report_label (str): Report file label
report_extension (str): Report file extension. e.g. txt, csv
Return:
r... | f4c2f12f252f1afb8a66e88c3de2d694613211bc | 646,096 |
from datetime import datetime
def get_test_case_name():
"""Generate unique name for unit test case."""
# If not unique enough, replace with an uuid
test_case_name = 'test ' + datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
return test_case_name | c6c1ce7334d906479fff02705a161368ffade38b | 646,097 |
def random_walk_step(r, p0, W, pt):
"""
r = probability of restart
p0 = initial probability vector
W = column-normalized adjacency matrix
pt = probability vector at time step t
pt = probability vector at time step t + 1
"""
#print 'r', r
#print 'W', W
#print 'pt', pt
#print '... | 047ae6ff08a1a6f0bef579ab026a46c747de5953 | 646,099 |
import math
def distance_nautical_miles(ll1,ll2):
"""
Given two (lat,lon) points ll1 and ll2, returns the distance
between them in nautical miles.
"""
lat1,lon1=ll1
lat2,lon2=ll2
rad = math.pi / 180.0
yDistance = (lat2 - lat1) #* nauticalMilePerLat
xDistance = (math.cos(lat1 * rad) + math.cos(l... | cc3b9756cbcce66aeb9c023ab206aee7d42bdf90 | 646,102 |
def slow_swap(A, B):
"""
This is a N(O^2) solution
"""
n = len(A)
sumA = sum(A)
sumB = sum(B)
for i in range(n):
for j in range(n):
change = B[j] - A[i]
sumA += change
sumB -= change
if sumA == sumB:
return True, A[i],... | e2da2b3ac32ce1875039d9d5d5cc3990de7283ed | 646,104 |
from typing import Any
def attribute_condition(filter: Any) -> str:
"""
Convert filters into a SQL syntax.
:filter (str) Array of filters
Return a SQL string
"""
if filter['value'] == '':
return f"(attributes -> {filter['key']} IS NULL OR attributes ->>\
{filter['key']} =... | ecb257e31a7b6dae5b843e486b84e943f5ca0045 | 646,105 |
import torch
def _optimal_step_size(last_step, error_ratio, safety, ifactor, dfactor, order):
"""Calculate the optimal size for the next step."""
if error_ratio == 0:
return last_step * ifactor
if error_ratio < 1:
dfactor = torch.ones((), dtype=last_step.dtype, device=last_step.device)
... | 8bb8b8c0ce7720448cbd9ec186a78270278e4d77 | 646,106 |
import math
def distXY(f_dx, f_dy):
"""
DOCUMENT ME!
"""
# return
return math.sqrt(pow(f_dx, 2) + pow(f_dy, 2)) | cf752402d85dcd0dc953e1634adc9407d09bf1bf | 646,107 |
def pairwise_diff(X, Y):
"""Compute pairwise difference of rows of X and Y.
Returns tensor of shape len(X) x len(Y) x dim."""
return X.unsqueeze(1) - Y | d7ed4e5f1ed5add306ed3e978620303b7b290946 | 646,108 |
import sympy
def grad(DN,x):
""" This method defines a gradient
Keyword arguments:
DN -- The shape function derivatives
x -- The variable to compute the gradient
"""
return sympy.simplify(DN.transpose()*x) | edbdfbcb7e7f973abf212a82782d7e7418ec6659 | 646,110 |
import sys
import argparse
def parse_args(args=sys.argv[1:]):
"""
Parse command line arguments for Grole server running as static file server
"""
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--address', help='address to listen on, default localhost',
... | 5a0a82af6ecaffe0064fd401e15a3a4cc7524b41 | 646,111 |
import re
def _tracwiki_list_separate_from_paragraph(text: str):
"""
During conversion from TracWiki to RST, ensure an empty line
between each non-list-item and the list item following it, if any.
"""
lines = text.split('\n')
newlines = []
was_list_item_or_blank = True
for l in lines... | 7559d5fab4d39e174d12948ec8c5ebc24e08d20d | 646,112 |
from pathlib import Path
import os
def get_pw_filename(fname="logins"):
""" Attempt to find the logins.csv file in this python file's directory, downloads, or desktop. Fetch the newest file created with 'logins' in the name. """
# directories to search
this_dir = Path(__file__).parent
downloads = Path... | d636df3ac70df7e589ea348342019ac9f262557a | 646,113 |
from textwrap import dedent
def one_paragraph_ragged_left():
"""A one paragraph text with a ragged left margin"""
return dedent(
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Integer condimentum, orci at auctor venenatis, dolor
orci congue felis, sit a... | b66add73574cf1c2cc96a299e232340cf60274ce | 646,114 |
def kwargs_to_flags(valid_flags, arguments):
""" Takes an iterable containing a list of valid flags and a flattened
kwargs dict containing the flag values received by the function.
The key for each dict entry should be the name of a valid flag for the
command being run, with any hypn... | d1df8c623c71faca41d8b6e88132e7984dbd1efb | 646,115 |
import typing
def check_status_of_pipelinerun(
jeez: typing.Dict[str, typing.Dict]) -> typing.List[str]:
"""Check status of a pipelinerun using kubectl, we avoid the the Running
ones since we run in finally, it will have a running ones"""
task_runs = jeez['status']['taskRuns']
failed = []
... | 24b045cadd28620c548c7a1aa3ac71e14afd050a | 646,118 |
import sys
import os
def _get_interop_filename():
"""interopXX.cs is auto-generated as part of the build.
For common windows platforms pre-generated files are included
as most windows users won't have Clang installed, which is
required to generate the file.
"""
interop_file = "interop%d%s%s.cs... | 619e363c0c27de88254d06b7a3194377d1796b64 | 646,119 |
def _is_sub_partition(sets, other_sets):
"""
Checks if all the sets in one list are subsets of one set in another list.
Used by get_ranked_trajectory_partitions
Parameters
----------
sets : list of python sets
partition to check
other_sets : list of python sets
partition to ... | b2a1d60245a8d2eca1f753f998ac1d69c8ff9d08 | 646,120 |
def InvertDict( aDict ):
"""Return an inverse mapping for the given dictionary"""
assert len( set( aDict.values() ) ) == len( aDict )
return dict( ( v, k ) for k, v in aDict.items() ) | c926ded2a1b14249d46e8433af1bb8647cb4a9a8 | 646,121 |
def scoreClickAUC(num_clicks, num_impressions, predicted_ctr):
"""
Calculates the area under the ROC curve (AUC) for click rates
Parameters
----------
num_clicks : a list containing the number of clicks
num_impressions : a list containing the number of impressions
predicted_ctr : a li... | 5c5d3a6bf6f634e6b39ccdda96cdaca2e54d168a | 646,122 |
def next_move(file_names, decision):
"""
Takes in a filepath containing constestant names and decisions,
and a final decision to make. Returns a message for the
contestants whose decisions match the final decisions.
Parameters:
file_names: Path to file containing names and decisions.
... | 06c207e1638ec1a8696b03d5dd03bcb56fd198a1 | 646,123 |
import re
def multi_replace(target: str, replacements: dict[str, str]) -> str:
"""Given a string and a replacement map, it returns the replaced string.
See https://gist.github.com/bgusach/a967e0587d6e01e889fd1d776c5f3729.
Args:
target: String to execute replacements on.
replacements: Rep... | 390047f6525f5fb2025fca818b09e8b80f231244 | 646,124 |
from typing import Union
from typing import List
def _df_convert_list(data: Union[List[str], str, None]) -> Union[List[str], None]:
"""Converts str to List[str] and raises error"""
if type(data) == list:
return data
elif data is None:
return None
elif type(data) == str:
return ... | 61ca84a994182e1f7b5096e90178ed75c747f232 | 646,125 |
def _resolve_name(name, package, level):
"""Resolve a relative module name to an absolute one."""
bits = package.rsplit('.', level - 1)
if len(bits) < level:
raise ValueError('attempted relative import beyond top-level package')
base = bits[0]
return '{}.{}'.format(base, name) if name else b... | fc2df72f07594fd0e0e9d72ccfa870bb235a4868 | 646,126 |
def _error(y_true, y_pred):
""" Simple error """
return y_true - y_pred | 75c5f29a82b89258bf47fa33b6882cbec2d6d2c9 | 646,127 |
def lower(value):
"""
returns the lowercase copy of input string.
:param str value: string to make lowercase.
:rtype: str
"""
return value.lower() | 266bd0b32bb79a62d4ecc2d0e5bdee55a1bcc05f | 646,128 |
def frange(limit1, limit2 = None, increment = 1.):
"""
Range function that accepts floats (and integers).
Usage:
frange(-2, 2, 0.1)
frange(10)
frange(10, increment = 0.5)
The returned value is a list.
"""
if limit2 is None: limit2, limit1 = limit1, 0.
else: limit1 = float(limit1)
result =... | a70512b1264a9352bc9e48e88baa41497eb53b32 | 646,129 |
import string
def letter_part(n): # takes quotient and index
"""
Function to calculate the lettered part for a given number of parts n
Eg. letter_part(1) = 'a', letter_part(26) = 'z', letter_part(27) = 'az', letter_part(702) = zz this is the max
Values for n > 702 return None
:param n:number of ... | 42af53ade009abf86219f42849de9fdf7d56bc2d | 646,130 |
def dataframe_first_value(df):
""" dataframe第一个值 """
return df.iloc[[0], [0]].values[0][0] | d6901a6f9e1a589e1d2cfbb75e1b33585ba215fb | 646,131 |
def insertion_sort(lst):
"""
A stable, in-place sorting algorithm that sorts the list in increasing
order, one element at a time.
:param lst: An unsorted list of sortable items (i.e. the items can be
compared using the 'greater-than' operator [>]).
:type lst: list
:return: The list sorted ... | d8dc0ca0c1e048ad4032b01b7288c6120b26df6b | 646,132 |
from typing import List
from typing import Dict
def get_distribution(labels: List[str]) -> Dict[str, int]:
"""
Get the distribution of the labels.
Prameters
---------
labels : List[str]
This list is non-unique.
Returns
-------
distribution : Dict[str, int]
Maps (label... | cbc42b4cbdc8924226979e1fe63e3cb0b409efba | 646,133 |
def apply_fixed_k3739(a39, pr, fixed_k3739):
"""
x=ca37/k39
y=ca37/ca39
T=s39dec_cor
T=ca39+k39
T=ca37/y+ca37/x
ca37=(T*x*y)/(x+y)
"""
x = fixed_k3739
y = 1 / pr.get('ca3937', 1)
ca37 = (a39 * x * y) / (x + y)
ca39 = pr.get('ca3937', 0) * ca37
... | 901775b8ca04f91afa30977d11bba59f4288e0b8 | 646,134 |
def fc_forward(mat_x, mat_w, vec_b):
"""Forward pass of Fully-Connected layer.
A good reference for this is: http://cs231n.github.io/linear-classify/#score
Args:
mat_x: NxD ndarray, N is number of features, D is length of feature vector
mat_w: DxC ndarray, C is number of classes.
vec_b: length C nda... | 5ab37b3a58e23a0c4b57162ea373aa4b8ad9a988 | 646,135 |
def one_semitone_up(freq, amount=1):
"""
Returns the key, one semitone up
:param freq: the frequency in hz
:param amount: the amount of semitones up
:return: the frequency one tone up in hz
"""
return freq * 2 ** (amount / 12) | c7db7202e992c4d4b9cd5e8d778bbd8854196737 | 646,136 |
def lonlat_to_latlon(coords):
"""Tranforms a list of coordinates in lon, lat to a list of coordinates in lat, lon.
Context: Leaflet had the brilliant idea of using the let/lon format instead of geojson
standard lon/lat, hence why we need to often convert shapes from one system to another.
"""
if is... | 5c060a09ac661fd786ba55c35a3ee4e40dbce4e8 | 646,137 |
def version_add(version1, version2):
"""Add two tuples elementwise."""
version = [int(first) + int(second) for first, second
in zip(version1.split("."), version2.split("."))]
return "{}.{}.{}".format(*version) | b8e904192adfabbdda677b6b662b503c78ba6ae5 | 646,138 |
def play(game):
"""
play a game
Parameters
---
Agents:
A list of agents to play the game.
mode:
Whether the deck is "infinite deck" or "finite deck", default "infinite deck".
"""
while True:
# print("agent %s's turn:" % game.current_player)
while True:
# print(' try')
action ... | c9bd1699449aba8d84666a35711dd0f8a00313d7 | 646,139 |
def srange(characters):
"""Construct a list with all characters in the string"""
return [c for c in characters] | bebae3c6ef5a056a2e97a47f722463dca6829759 | 646,140 |
import json
def deserialize(recipe):
"""Deserialise JSON strings."""
recipe["tags"] = json.loads(recipe.get("tags", []))
recipe["newTags"] = json.loads(recipe.get("newTags", {}))
return recipe | 0ba065157ba3b1c91225814c0312f305db30722e | 646,141 |
import numpy
def to_usec(timestamps):
"""Convert seconds to microseconds."""
return (1e6 * timestamps).astype(numpy.int64) | 0c19ba4762227e6f11628480523f2aa4b88f5c95 | 646,142 |
def num_there(s):
"""helper function for main()"""
return any(i.isdigit() for i in s) | 5d59dfb0ab697ac1067ba978d3a6b6ff23519d74 | 646,143 |
import toml
def configfile(tmp_path, configuration):
"""Return path to a toml formated config file.
This file contains values from the configuration fixture.
"""
base_path = tmp_path / "cfg"
base_path.mkdir()
cfg_file = base_path / "config.toml"
cfg_file.write_text(toml.dumps(configuratio... | 6fb3d621a191046729b3c346b15401751780fb11 | 646,144 |
from pathlib import Path
import sys
def get_system_license_path() -> Path:
"""Returns the default path to the Binary Ninja license.dat on the current platform
:return: Path object to the license.dat file.
:rtype: Path
"""
if sys.platform == "darwin":
return Path.home() / 'Library' / 'Application Support' / 'B... | 8018a0223afca040820d6e3bb30c1ce46708b44c | 646,145 |
import random
def choose_random_data(map_data, all_locations, n_locations):
"""
Returns n randomly chosen unique locations.( n: n_locations)
:param map_data: list of tuples as (film, location, coordinates)
:param all_locations: integer, number of all films available for given year
:param n_locati... | 44719ad35b50e94ee63a1f3d91971f37b34893be | 646,147 |
def no_operator(func):
"""
Декоратор вызова оператора по ключу. Возвращает None, если искомый
оператор не найден.
:param func: Функция извлечения WTAS или WTADB.
:return:
"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except KeyError:
... | aa8ffd5df3ef4c6ee7912a1b67f0521610cb803b | 646,148 |
def equalise_end_dates(*args):
"""
function to cut end date of set of datetime dfs to be the earliest last date within the set of dataframes passed
:param args: must all be dataframes with datetime indices with latest date at bottom
:return: dataframes with equalised end-dates, wrapped in a list
"""... | c9aef4e6d38a93fca88ef5fd042552ceb822fcfc | 646,149 |
import struct
def isNii(fname):
"""Determine if the file is a valid NIFTI file"""
# Idea from https://brainder.org/2015/04/03/the-nifti-2-file-format
# under section titled "NIFTI-1 or NIFTI-2?"
niftiType = 0 # Encode "failure" as 0, and Nifti 1/2 as 1/2
with open(fname,'rb') as infile:
... | 14da05f4cb2d5b47a63601dc76529a832719be42 | 646,150 |
def extract_used_columns_from_nba_response(nba_response, desired_column_headers):
"""
Keeps all columns specified in desired_column_headers
and returns the processed list of rows.
"""
try:
desired_column_indicies = [nba_response.headers.index(
header) for header in desired_column... | 4e2f4d0b0a160d563f0ce4a6f698c7a8a2087c44 | 646,151 |
import json
def fix_game_str(game_json):
"""Get the json string for a game"""
return json.dumps(game_json) | c41d244ac3c82084f00734a6d2a3a7af6b73e9af | 646,152 |
import pickle
def load_pickle(filename):
"""
Load saved data from pickle file
:param filename: pickle file name
:return: data from pickle file
"""
with open(filename, "rb") as f:
data = pickle.load(f)
return data | aabb0fb57fca48ef53c75129d662bf82f683d978 | 646,153 |
async def add_result(user: dict, form: dict) -> str:
"""Extract form data and update one result and corresponding start event."""
rank_identifier = f"form_rank_{form['rank']}"
new_result = {
"event_id": form["event_id"],
"race": form["race"],
"race_id": form["race_id"],
rank_... | dd9e411e813edce53064ac8308722d4ad94d58b8 | 646,154 |
def recvline(sock):
"""Sends an email behind a proxy. Receives a line."""
stop = 0
line = ''
while True:
i = sock.recv(1)
if i.decode('UTF-8') == '\n': stop = 1
line += i.decode('UTF-8')
if stop == 1:
print('Stop reached.')
break
print('Receive... | c02ebb2f93805e679442c3f3cae0641e0664f7ac | 646,155 |
def tapcodeConvert(sentence: str, tap: str = " ", sep: str = ".", outputSep: str = " ") -> str:
"""
Convert TapCode to decimal values
Args:
Sentence (String): Tapcode to convert
Tap (String): Tap string ("." by default)
Sep (String): Separator ("... | c50689a3965cee22bc5060cf8d907605cdf03359 | 646,156 |
import string
def output_ext_ascii(key: int, ext=None):
"""
given a key, returns a made up lange name from the ascii char list.
[a,b,c,d,e,f, ...,z,A,B,..]
if key ==1, ext = aa; if key ==3, ext = cc
"""
fnames_alpha = string.ascii_letters
# fnames_alpha[0] = a
fname = fnames_alpha[key ... | 0591fa8f7652337a616c4b4ed8b92061fa152158 | 646,157 |
import re
def only_numbers(string):
"""Return a string w only the numbers from the given string"""
return re.sub("\D", "", string) | 99bf3aeae8a462c5f6b2f217445d8d2fc616984e | 646,158 |
def omp_get_initial_device():
"""
The omp_get_initial_device routine returns a device number
that represents the host device.
"""
return 0 | 40c1ef9146a9fc0fe07826c5b4402f902fd8613d | 646,159 |
from typing import Union
def _get_address_from_instance_response(instance_response: dict) -> Union[str, None]:
"""
Extracts the instance's IP address (public if possible, private if not) from the boto3 response dict
:param instance_response: Boto3 response dict
:return: IP address of the instance (pub... | 08c7623ec2d1e0af8a36b3fafdf8439ae818c80f | 646,160 |
def decode(b):
"""Decodes as UTF-8"""
return b.decode('UTF-8') | f717dfe10945a25b5d9548482c8b828aa17baad3 | 646,162 |
def return_all(columns):
""" Check if all columns should be returned """
return columns is None | cebd501fa37df08063513f0ae623678a13f659bf | 646,164 |
import os
def _full_live_path(cli_config, lineagename):
"""Returns the full default live path for a lineagename"""
return os.path.join(cli_config.live_dir, lineagename) | 91ef55f0ecfc4e8a325fe6bbb9f9b6e18326673f | 646,165 |
import ast
def get_functions(_ast):
"""
Gets all function definitions immediately below an ast node
@param _ast the ast node to search for functions in
@return a tuple of function definition ast nodes
"""
return (node for node in _ast.body if isinstance(node, ast.FunctionDef)) | 8d9816b9ea6c20090e72e833644c69dbf982d436 | 646,166 |
from typing import List
def fibonacci_sequence(n) -> List[int]:
"""Generate n+1 terms of the fibonacci sequence"""
fibo_sequence = [0, 1]
a, b = fibo_sequence
for i in range(2, n+1):
a, b = b, a + b
fibo_sequence += [b]
return fibo_sequence | 861fee1758d9ac3496af1e1cd9af048846038bc1 | 646,167 |
import os
def get_mode():
""" get the runtime mode """
# set the mode based on where this is running from
if os.path.dirname(__file__).startswith("/usr"):
return 'prod'
else:
return 'dev' | 31d20d3715485ac3f9cf5af81f061586c685e67d | 646,168 |
import json
def get_message_info(parsedData):
"""
:param parsedData: data after being parsed by the en parser
:return: message info in json
"""
message_info = {}
token_info = {}
for i, token in enumerate(parsedData):
token_info['original'] = str(token.orth) + " " + str(token.orth_)... | ce95526f3fb4d4fd4cba55847ca00b5e86714cb9 | 646,169 |
def get_incoming_voice_sub_id(ad):
""" Get incoming voice subscription id
"""
if hasattr(ad, "incoming_voice_sub_id"):
return ad.incoming_voice_sub_id
else:
return ad.droid.subscriptionGetDefaultVoiceSubId() | 2c293f82dc0d506727e466d82d81733ef0f9c5ef | 646,170 |
def help_builtin():
"""help: View the doc of an object."""
# ex: help(help)
return help.__class__.__name__ | e61dd7ca1749c05e97eb3f73dfa8e62217bd43e3 | 646,171 |
import os
import pathlib
def get_build_dir():
"""Return absolute path to the directory where pack files will be written"""
return os.path.join(pathlib.Path(__file__).parent.absolute(), "build") | 44ed2dabf55a8556a2d013dd15c1f1ec9dccf3bf | 646,172 |
from typing import Sequence
from typing import Optional
def _pick_remote_uri(uris: Sequence[str]) -> Optional[int]:
"""
Return the offset of the first uri with a remote path, if any.
"""
for i, uri in enumerate(uris):
scheme, *_ = uri.split(":")
if scheme in ("https", "http", "ftp", "s... | c4ce40dda5778b57890d000131bf2ec5a6bb5170 | 646,173 |
def paged_search_computers(api, configuration, api_version, api_exception):
""" Uses a search filter to create a paged list of computers
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api client.
:param api_version: The version of the API to use.
... | deb01d742681b2c890dfcaf5c1dbfd631e2f240a | 646,174 |
def bool_converter(value):
"""Simple string to bool converter (0 = False, 1 = True)."""
return value == "1" | 06962569a732b176f0a904ab4cf186a634f01f1a | 646,175 |
def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None):
"""Checks no '\r' (CR) character is in any source files."""
cr_files = []
for f in input_api.AffectedSourceFiles(source_file_filter):
if '\r' in input_api.ReadFile(f, 'rb'):
cr_files.append(f.LocalPath())
if cr_files:
return [... | c9649f5f5e35c04f6f13d88b81823571f67cfb44 | 646,176 |
import os
import random
def data_split(path, n=None, frac=0.80, n_rot=10, shuffle=True, seed=28):
""" Train-test split the matrices data"""
training_ids = []
validation_ids = []
data_ids = sorted(
[x for x in os.listdir(path + "/density_matrices") if x.endswith(".npy")]
)
data_ids_pla... | 16a1d54968e7d9c937404d7ec60ebbee978fe4d6 | 646,178 |
import json
def get_parent_table(version='alchemy2'):
"""Returns a parent table where each parent has its own dict entry consisting of al resulting children.
Args:
version (str, optional): 'joined', 'alchemy1', 'alchemy2', 'tinyalchemy' or 'tinypixels'.
States what element and com... | 759f32d5384bc7430cc084acf2af296be4db90b4 | 646,180 |
def rescale(feature, feature_space):
"""Rescales a feature back to their original range."""
rescaled_feature = (feature + 1.) / 2.
rescaled_feature *= (feature_space.high - feature_space.low)
rescaled_feature += feature_space.low
return rescaled_feature | da2d162f5a50fb805294623a67a570074dadb1b1 | 646,182 |
from typing import List
import re
def get_list_schedule_raw_from_html(html: str) -> List:
"""Trích xuất và lấy ra list schedule thô từ html."""
schedules_raw = []
join_schedules = []
raw_sub_time = html.replace('\n','')
strings = re.findall(r'>(.*?)<', raw_sub_time)
for string in strings:
... | 5c7a9c2365d59863849bd5993ce75e11f01a466a | 646,183 |
from typing import List
def simple_clean_cells(cells: List) -> List:
"""
Removes cells that lack a bounding box or have a volume equal to 0
Args:
cells: List of spatial features
Returns:
List of spatial features
"""
return [cell for cell in cells
if len(cell.get_... | 2904b961127d0250c13e8a2647c9745dfa396981 | 646,185 |
def get_noaa_url(start, end, station):
""" Formats url with params for tides request from NOAA.
Args:
start (int or str): YYYYMMDD start date.
end (int or str): YYYYMMDD end date (max 30 days from start).
station (int or str): NOAA station ID.
Returns:
URL for NOAA tides ca... | 992af0db89bb5a61baf71beaac213d815fb9e2f6 | 646,186 |
def var_name(var):
""" Return the name of a variable """
for name,value in globals().items() :
if value is var :
return name
return None | ecc7223d77bd5f9565080d9ae90554e1cbbf1593 | 646,187 |
import torch
def is_loss(module):
"""Return whether `module` is a `torch` loss function.
Args:
module (torch.nn.Module): A PyTorch module.
Returns:
bool: Whether `module` is a loss function.
"""
return isinstance(module, torch.nn.modules.loss._Loss) | b106c327c1c1ba24b55acae588224af493dfc7f4 | 646,188 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.