content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def _get_test_folder():
"""Get path of the main test folder.
Path is assumed to be located somewhere above this file. This computation
is cached as the absolute directory of the cache isn't expected to change.
Returns:
path to test folder (root for tests)
Raises:
FileN... | 8d319baf2ed19368a6fad4b6e7fdbf850497cbbd | 628,984 |
def find_max_overlap(x,y,max_shift=10):
"""Finds the value for a shift of y for which the mean squared error becomes minimal."""
assert max_shift<len(x), "max_shift too large."
assert len(x) == len(y), "works only for equal-size arrays"
_len = len(x)
rv = 0
rv_error = 1000000000
for i in ran... | 4b4550faf62fe5b64c0864c6ca72de13d369ac36 | 628,985 |
def binary_search(lo, hi, condition):
"""Binary search."""
# time complexity: O(log N)
# space complexity: O(1)
# dep: condition()
# keep looping as long as the substring exists
while lo <= hi:
mid = (lo + hi) // 2 # the int division
result = condition(mid)
if ... | 18e7b9b3ad63f2c5cdc345b2277d06b17fae791d | 628,986 |
import uuid
import os
def tempfile(prefix=None, suffix=None, temp_dir='/tmp'):
"""
Generate a temporary file path within the container.
"""
name = str(uuid.uuid4())
if suffix:
name = name + suffix
if prefix:
name = prefix + name
return os.path.join(temp_dir, name) | ec7001f9123188d1bfabf20149090d0bf58348e4 | 628,988 |
def aggregate_scores_weighted_mean(scores: list):
"""
Aggregate the given scores using a weighted arithmetic mean algorithm
"""
if not scores:
return "N/A"
weights, weight_sum = {}, 0
for i, score in enumerate(scores):
try:
score = float(score)
except ValueEr... | 8201dc1aec242829e0409f4592142f64377a8f15 | 628,989 |
import os
def report_compound_files(comp_path, comp, BBTs):
"""report_compound_files create a smi file for each BBT and put in the file all compounds in compound
assigned to that BBT_index. Warning: this function does not clea files used in previous script runs
comp_path : str (folder where compounds file... | bc3c035ab37587dc905969f94c7df2e8d2b8bd85 | 628,990 |
from typing import Counter
def split_hand(hand):
""" 88833 -> [(8, 3), (3, 2)]"""
counts = Counter(c.value for c in hand)
split = [(value, count) for value, count in counts.items()]
return sorted(split, key=lambda x: 100*x[1]+x[0], reverse=True) | ae525602861e8f06e6b5c9be128cec4dac300b19 | 628,991 |
import torch
def count_gate_batch_dims(gate: torch.Tensor):
"""Compute the number of batch dimensions for a given gate batch.
Args:
gate: Tensor with size (*batch_dims, 2^k, 2^k) where k is
the number of qubits on which the gate acts.
"""
out = gate.dim() - 2
if out < 0:
... | d5d781da8d0b2e703fc58f9c977c41d1c5c067a4 | 628,992 |
def info_qry(tickers, flds) -> str:
"""
Logging info for given tickers and fields
Args:
tickers: tickers
flds: fields
Returns:
str
Examples:
>>> print(info_qry(
... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name']
... ))
ticker... | 9f7e447a83dcef9496fa6272316a3b366a9a0d60 | 628,993 |
from typing import List
def count_window_increases(input_ints: List[int]) -> int:
"""Get rolling windows"""
prev_sum = 0
increases = -1
for i in range(3, len(input_ints)+1):
rolling_sum = sum(input_ints[i-3:i])
if rolling_sum > prev_sum:
increases += 1
prev_sum = rolling_sum
return increas... | 5f5afc38f4127e330260fda8241735b568a32cb5 | 628,994 |
import re
def escape(text):
"""Use XML character references to escape characters.
Use XML character references for unprintable or non-ASCII
characters, double quotes and ampersands in a string
"""
def fixup(m):
ch = m.group(0)
return '&#' + str(ord(ch)) + ';'
text = re.sub('[... | cd6fa1b49ccdbda1a2b10cccfde54a024eea956f | 628,995 |
def waveform_time_to_spec_time(t, spectrogram_len, spectrogram_generator):
"""Converts time in waveform space to time in spectrogram space given parameters of STFT"""
hop_length, window_length = spectrogram_generator.hop_length, spectrogram_generator.win_length
for hop in range(spectrogram_len):
if... | 3c5cbb9c00184a1d097093bf3a6ce7fac2a8c2c9 | 628,996 |
def int_or(x, y):
"""
used for getting or-values in binary classification
"""
return 1 - (1-x) * (1-y) | 96a8fe956938992cce3ddfdfd006e86cbbd15548 | 628,997 |
def tokenize_rulekey_line(line):
"""
Tokenizes a line of the form: '<type>(<value>):<type>(<value>):...<type>(<value>):'
Tokens are returned in reverse order, because the serialization was also reversed.
"""
# Since ':' can appear within a token value, we cheat and delimit tokens by '):'.
delimi... | 843d708d3400bc978a5f79396fa9586d34d5249a | 628,998 |
def _diff_target(node1, node2, gens):
"""
Calc fitness based on the fact that two nodes should not share same target.
"""
shared_tg = None
for src in gens:
if shared_tg is None and src in [node1, node2]:
shared_tg = gens[src]
elif shared_tg is not None and gens[src] == sh... | a113a2e485107e5124a201b155d45d1578d5c4d8 | 629,001 |
def proc_angle(angle):
""" proc_angle(angle)
0 -> '000', 90 -> '+90', -90 -> '-90', 180 -> '180'
"""
st = '%+03d' % (angle)
st = st.replace('+180', '180')
st = st.replace('-180', '180')
st = st.replace('+00', '000')
return st | bb09a5aa76e6a3a49f8d4fda03252138d153f9c4 | 629,002 |
def change_input_str_to_member_list(input_name_str):
"""根据命令行输入的内容创建要下载的成员名单"""
member_list = input_name_str.split(',')
return member_list | bda25cdcb52de1532dc26bb7eb7a6c96839ab367 | 629,003 |
def getting_students_sum(marks):
"""Getting sums of students marks"""
return [(i, j[0][2]) for i, j in zip([sum([task[0] for task in tasks])
for tasks in marks], marks)] | 9e26f176d86c009fb06cdf10f506e2ba583b05d6 | 629,005 |
def add(num1, num2):
""" add two num """
return num1 + num2 | 477c99680137d9ebc4719a20b310d5bbf7332af8 | 629,006 |
def generate_nav_urls(host, query, results):
"""Generate links to previous and next pages for navigation."""
cur_page = results.current_page()
if cur_page > 1:
url_prev_page = 'http://' + host + '/search?q=' + query \
+ '&page=' + str(cur_page - 1)
else:
url_prev_... | 82d47cd6c3fb192d3900b11336f45bbc08fa29d3 | 629,007 |
from typing import Tuple
def calculate_vwap(
first_stock_values: dict,
pv: float,
sum_volume: float,
actual_pv: float,
actual_vol: float
) -> Tuple[float, float, float]:
"""
Function to calculate the VWAP.
Volume-weighted average price(VWAP)
"""
if not ... | fafe5d8ee6ed85a8f726b737c9826bb34be05cf9 | 629,008 |
def filtered_selectors(args, api):
"""Returns the selectors for the user-given resource types to ensure that
only those resources will be deleted.
"""
resource_selectors = [
("project", args.project_tag, api.list_projects, None),
("execution", args.execution_tag, api.list_executions... | 485c3c67a5b4f60389c23a0df9b761d0918b336a | 629,009 |
def _worker_fn(example, transform):
"""Function for processing data in worker process."""
feature = transform(example)
return feature | 17efa5bf9431dc57cb9ddf4c9d195877967f0618 | 629,010 |
def GetMatchingDepsEntries(depsentry_dict, dir_path):
"""Gets all deps entries matching the provided path.
This list may contain more than one DepsEntry object.
Example: dir_path='src/testing' would give results containing both
'src/testing/gtest' and 'src/testing/gmock' deps entries for Chromium's DEPS.
Exa... | 7ebf54add4785cadb5561ee2ecd75bbdd020474f | 629,011 |
def _ensure_is_list(obj):
"""
Return an object in a list if not already wrapped. Useful when you
want to treat an object as a collection,even when the user passes a string
"""
if obj:
if not isinstance(obj, list):
return [obj]
else:
return obj
else:
... | d2025a28e6143941a828452ef3134de49544ca76 | 629,012 |
def calcTf(nAllTermsInDoc, nTermInDoc):
"""
# to unstable (most values are near to each other for all docs)
return math.log10(
(float(nTermInDoc) / float(nAllTermsInDoc))
+ 1
)
"""
return float(nTermInDoc) / float(nAllTermsInDoc) | 5b1276b6d51b0add6f37bcb6826ed43d7d0ae91e | 629,013 |
def binary_search_lo(a,d,lo,hi):
"""
Created for leetcode prob 34
"""
if d!=a[hi]:
raise Exception("d should be a[hi]")
while hi>lo:
mid=(lo+hi)//2
if a[mid]==d:
hi=mid
else:
lo=mid+1
if a[lo]==d:
return lo
else:
return ... | ac096d9c29eb7cdc09d5b88c40cb2f03e1f088e6 | 629,015 |
from typing import Sequence
def check_duplicates(obj_list: Sequence) -> list:
"""checks for and eliminates source duplicates in a list of sources
### Args:
- obj_list (list): list with source objects
### Returns:
- list: obj_list with duplicates removed
"""
obj_list_new = []
for src ... | bea88691b639fee8c6a4b7e609d854460fd76367 | 629,016 |
def sum_multiples(n):
"""
return number
>>> sum_multiples(10)
23
>>> sum_multiples(100)
2318
>>> sum_multiples(1000)
233168
"""
multiple = [num for num in range(n) if num % 3 == 0 or num % 5 == 0]
return sum(multiple) | d9ec67403d879e12e3ec869cd9ea4df6d762f398 | 629,017 |
from typing import Dict
from typing import Any
from typing import Iterable
def build_resources(
translation_cache: Dict[str, Dict[str, Any]], components: Iterable[str]
) -> Dict[str, Dict[str, Any]]:
"""Build the resources response for the given components."""
# Build response
resources: Dict[str, Dic... | b08602f687f295c827717575d7842167b3a78096 | 629,019 |
from typing import Optional
def convert_negative_none(value: int) -> Optional[int]:
"""Convert an negative int value from the ToonAPI to a NoneType."""
return None if value < 0 else value | 3cfbb00e47a9edbb4a8826779abd1b143829ceef | 629,020 |
import re
def short_expression(original: str, level: int = 0) -> str:
"""Abbreviate the expression, keeping it human-readable.
If `level` is 0, just remove parts that are implicit from context,
such as a leading ``PSA_KEY_TYPE_``.
For larger values of `level`, also abbreviate some names in an
una... | d19610031945ad38151e8ce85e8a4ba1f93e5d5c | 629,021 |
def frame_center(array, verbose=False):
"""
Return the coordinates y,x of the frame(s) center.
Parameters
----------
array : 2d/3d/4d array_like
Frame or cube.
verbose : bool optional
If True the center coordinates are printed out.
Returns
-------
cy, cx : float
... | 27a3089afcb36f77627c19ab431e1866ef33e773 | 629,022 |
from typing import Dict
from typing import Any
def check_arg(key: str, args: Dict[str, Any]) -> Any:
"""
Check Arg Service
:type key: ``str``
:param key: Check arg in dict
:type args: ``dict``
:param args: Args dict (e.g {key: value})
:return: Depends on the key ... | bd84247add060fdad5a379d26dd537fd702836da | 629,024 |
def maybe_result(parts):
"""
return if the argument looks like a c++ result
Returns
-------
bool
"""
return 'const' not in parts and ('*' in parts or '&' in parts) | 22f9d9c1c6153170454a3670782a8d0647b544e7 | 629,026 |
import subprocess
import re
def get_current_mac(interface):
"""Get current MAC address."""
ifconfig_result = subprocess.check_output(["ifconfig", interface])
ifconfig_result = ifconfig_result.decode(
"utf-8") # change bytecode object to string
mac_address_result = re.search(
r"\w\w:\w... | 7c054bb53389d42cd02896e0f7c00e86c2e4d979 | 629,028 |
def create_mock_attrs(to_merge):
"""
Creats an attribute set for creating a resource from,
includes the basic created, modified and id keys. Merges
that with to_merge
"""
attrs = {
"created_at": "2012-04-18T17:53:12Z",
"id": "1",
"merchant_id": "amerchantid"
}
att... | f2af8245fa6b608c63eecd83130ed67a3cc216a3 | 629,029 |
import re
def _sanitize_to_identifer(name):
""" Changes a string with various characters into an identifier that is
valid for python. i.e. 'minimum RR-interval' -> 'minimum_RR_interval'
"""
n = name.strip()
n = re.sub('/', ' ', n)
n = re.sub('-', ' ', n)
n = re.sub(' +', '_', n)
... | 625237efbddddaf0cb5414ded626f4dc46dd04ae | 629,030 |
def parse_equal(line):
"""Parse super-sequence statements"""
seq_names = line.split()[1:]
return seq_names | c64de5500e2cb7a0dd7f949445e2feb5b11349b0 | 629,031 |
def test(model, x, y_true, idx, evaluator, emb=None, layer=0):
"""
Testing module for DNN trained on ogbn-arxiv
Arguments:
model : DNN
Model trained on ogbn-arxiv
x : torch.tensor of shape (num_nodes, num_node_features)
Nod... | 1b7c078b80372c978e555feade094361355e2c25 | 629,032 |
def create_instance_metrics(config_params: dict, module, *args, **kwargs):
"""
run function or module
finds a function handle with the name given as 'module' in config_params, and returns the
instance create_instanced with corresponding keyword args given as 'args'.
parameter
config_params ->... | 7ea65b44e810751e3abece011ed86dab4d88a520 | 629,034 |
import os
def get_maya_file_path(fbx_file_path):
"""! Convenience function for creating a maya file path based on an existing FBX path.
@param fbx_file_path Path to the existing FBX file
@return str - File path
"""
return os.path.splitext(fbx_file_path)[0] + '.ma' | e8b304a1d2a445b622cefbdd6ce5b7b944850fee | 629,035 |
def safeForKids(haveKids, kidFriendly):
"""Determines if the user is travelling with kids or not, as if the country is kid friendly, anyone can go, but
if it is no kid friendly, then only people travelling without kids can go there
Parameters:
haveKids: The user's input as to if they have kids or ... | c4ee49dda977dad18e506eacc6d15b7432f01f9e | 629,036 |
def base_convert(n, base):
"""
convert 10 base number to any base number
"""
result = ""
while True:
tup = divmod(n, base)
result += str(tup[1])
if tup[0] == 0:
return result[::-1]
else:
n = tup[0] | 335f8e700d675ec179afdee316fd78f479561339 | 629,037 |
def check_sanity(tags):
"""
Check sanity of input parameters
"""
stop = False
if 'unit_cell' not in tags:
print(' No unit_cell defined')
stop = True
elif 'base' not in tags:
print(' No base defined')
stop = True
elif 'elements' not in tags:
print(' No ... | 989cbcf5bdc0caa47c465ab7912107bf2cf7ba38 | 629,038 |
def phpversion(interp, ext=None):
""" Gets the current PHP version"""
if ext:
return interp.space.w_False
return interp.config.get_ini_w('php_version') | b19b885cf92478d263628065d5f418ce8a3008ca | 629,039 |
def time_switch(x):
"""
Convenience codes to convert for time text to pandas time codes.
"""
return {
'min': 'Min',
'mins': 'Min',
'minute': 'Min',
'minutes': 'Min',
'hour': 'H',
'hours': 'H',
'day': 'D',
'days': 'D',
'week': 'W',
... | f9b83a7252958525a0fa081f4f8e9833fa92a0bc | 629,040 |
def invalid_deprecated_status_raw_content():
"""
Returns a base64 encoded string with a JSON::
{
"monthly": {},
"hourly": {
"master1/hourly/mysql/mysql-2018-03-28_04_11_16.xbstream.gz": {
"backup_finished": 1522210295,
"bin... | 2df43a89092ea22181d11fb853470b9f35d59719 | 629,041 |
async def get_sensor(client, sensor_name):
"""Get last sensor value (in encoded form), or None if no value."""
reply, informs = await client.request('sensor-value', sensor_name)
assert reply == [b'1']
status = informs[0].arguments[3]
value = informs[0].arguments[4]
if status in {b'nominal', b'wa... | 18e300422457b27d30be09fda703977ec1e98070 | 629,042 |
import math
import builtins
def line_signed_coverage(canvas, line):
"""Trace line on a canvas rendering signed coverage
Implementation details:
Line must be specified in the canvas coordinate system (that is one
unit of length is equal to one pixel). Line is always traversed with
scan line along ... | 9cc20f4c670b041643e91243998ebe546c9dde26 | 629,043 |
def non_empty(value, question, keep=None):
"""Ask value while it is empty"""
if value != "<ask>":
if value:
return value
if keep is not None:
return keep
elif keep is None:
return value
while True:
value = input("=> " + question + "\n")
che... | 2328671ea207fcd0eb697798bac5d18187db172f | 629,044 |
from itertools import islice, tee
def sliding_window(iterable, length=2):
"""
Return a sliding window over iterable.
"""
its = (
islice(it, i, None)
for i, it in enumerate(tee(iterable, length))
)
return zip(*its) | 1d4ac431446477c2b4934cb1dfa9676679463140 | 629,045 |
from typing import List
def get_package_nvrs(built_packages: List[dict]) -> List[str]:
"""
Construct package NVRs for built packages except the SRPM.
Returns:
list of nvrs
"""
packages = []
for package in built_packages:
if package["arch"] == "src":
continue
... | a560d3dbf89fbb934fb100fdb73491df972a06de | 629,046 |
def get_auth_results(reportee, dkim_result, spf_result, **kw):
"""Return "auth_results" part. This can be no or more raw DKIM results and
one or more SPF results. For now we always return either no or one DKIM and
one SPF result, based on the passed `dkim_result` and `spf_result` and use
only the `reportee` dom... | afe3e91a2edfaf2e29e5383bbf553c49b4e4810e | 629,047 |
def _compare_dacls(dacl1, dacl2):
"""
This method compare the two given DACLs to check if they are identical.
Identical means here that they contains the same set of ACEs in the same order.
"""
return ([dacl1.GetAce(index) for index in range(dacl1.GetAceCount())] ==
[dacl2.GetAce(index) ... | 9396f2d48fbb7a809fdd02403eb57af6d98d2ad4 | 629,048 |
def cat_dist(x, y):
"""
A dummy implementation of a binary distance metric.
"""
return int(x['x'] != y['x']) + int(x['xx'] != y['xx']) | 4c3a64bef59faf814bffc448d07812113cd7152d | 629,049 |
import requests
import json
def twitter_status() -> list:
"""
This function is using twittertrendAPI to retrieve data with a given hashtag.
:return info : information from the given hashtag
"""
BASE = "https://twittetrandapi.herokuapp.com/"
response = requests.get(BASE + "Bitcoin")
d = js... | e6934017ddb57fc2074796788aa5b1505fc57b2d | 629,050 |
def makelower(indict):
"""return a copy of a string->string dict such that all keys and values are lowercase."""
return {k.lower(): v for k, v in indict.items()} | 1c2b7c9bf010e91143160d482860628be2261c8e | 629,051 |
def group_by_intent(data):
"""
Split a bundle into multiple bundles using intent.
**Inputs**
data (refldata[]) : data files with intent marked
**Returns**
specular (refldata[]) : specular measurements
backp {Background+} (refldata[]) : positive offset background measurements
backm ... | f0e5abe4ac91de25eed0e8cfefb60fd25b9abc81 | 629,052 |
import os
def verify_path(path: str) -> bool:
"""
Validate file path. Raise an error if file path is invalid
:param path:
:return:
"""
if not path:
raise Exception('Invalid arguments')
if not os.path.exists(path):
raise OSError('File not found: ', path)
return os.pat... | 53479e81d36a2c433a3c9280e85ed367d7237b86 | 629,053 |
import random
def make_humane_gibberish(length):
"""Generate a meaningless but human-friendly string.
Characters are chosen so that no two characters are alike.
Easily confused characters, such as '1' and 'l' are also excluded.
"""
result = ''
for i in range(length):
result += random.choice('ACEFHJKNPQRTVXY... | 65410b354a676b00801fb137755529ee09bfc45c | 629,054 |
def _str_eval_char(eval, act, ctxt, n) :
"""Runs python chr on the argument as an integer."""
n = n[0]
return [chr(int(n))] | 8b6326808fb98801e8bcac215772d503a12614c0 | 629,055 |
def as_tuple(*values):
"""
Convert sequence of values in one big tuple.
Parameters
----------
*values
Values that needs to be combined in one big tuple.
Returns
-------
tuple
All input values combined in one tuple
Examples
--------
>>> as_tuple(None, (1, 2,... | 1c5e97236c1b5c9dd2da6666b794b85c385ac885 | 629,056 |
from datetime import datetime
def _datetime_obj_from_string(date_string, date_only=False):
"""Return a datetime object from a given string to aid in the
assignment of consistent and reliable test dates.
"""
str_format = "%Y-%m-%d %H:%M:%S"
if date_only is True:
str_format = "%Y-%m-%d"
... | 92578ae072ebebcb55232f79f85484aff5e40c19 | 629,057 |
def _process_edge_df(subgraph):
"""
Returns an edge DataFrame with the names of the genes instead of their IDs.
"""
return subgraph.get_edge_dataframe().merge(
subgraph.get_vertex_dataframe().reset_index(),
left_on='source',
right_on='vertex ID',
).merge(
subgraph.get... | a8fee40fa5af2668c8419fe79371c3948dbc5d6c | 629,058 |
def active(config):
"""
Verifies that the signature of a configuration has not timed out.
:param config:
:return: True/False
"""
return True | 79ec58ef868858809b72773cac99953cafd10768 | 629,059 |
def get_data_year_location_age(year, location, age, data_structure):
"""
Retrieve the data for a given year, location, and age.
:param year: a defined year for which corresponding data will be returned
:param location: a defined location for which corresponding data will be returned
:param age: a d... | 5db474b7033d0e392df03159d1df6507699bf881 | 629,060 |
def getChange(current, previous):
"""Get the Percentage Change.
Parameters:
current (int): Current value
previous (int): Previous value
Returns:
int: Percentage Change
"""
if current == previous:
return 0
try:
return ((current - previous) / previous) * 100.0
e... | a99e3e5820bfafe4ba7e2281b48f42349a079d9e | 629,061 |
from datetime import datetime
import re
import pytz
def str_to_datetime(input_str: str) -> datetime:
"""Parse a string `input_str` and return a corresponding `datetime` object."""
microseconds = 0
if '.' in input_str:
seconds_decimal_component_match = re.match(r"[^.]*\d+[^.]*(.\d+)", input_str)
... | b66c8c83d2b17c397c29dc80c85eded5fa1152e8 | 629,062 |
import os
def getExpandedPath(path):
"""Returns an expanded, normalized, absolute path.
Args:
path: path (possibly relative, possibly containing environment variables,
etc.) to be expanded, normalized and made absolute
Returns:
absolute path, after expanding any environment variables and "~", th... | 505851808aa63a3bc8c6c2a30b6a6330df30383a | 629,063 |
def logical_xor(a, b, unsafe=False):
"""logical xor without the bloat of numpy.logical_xor
could be substituted with numpy.logical_xor
!important: if unsafe is set to True, a and b are not checked. This improves speed but is risky.
expects integers [0,1] or bools
"""
if not unsafe:
... | bc1981e81412f29fd91b1f5d57405a3d92ac4fa3 | 629,064 |
import pandas
def pandas_unique_by_column(df):
"""
Parameters
----------
df : pandas.DataFrame
Data frame.
Returns
-------
pandas.Series
Mapping from each column label to ordered list of unique values in
corresponding column in data frame.
"""
return panda... | 1d6a2a78d139c3d72b3d4273008416a017d956dd | 629,065 |
def _peek(iterator, eof=None):
"""
Return an iterator
Yield current value and\
next value in each iteration
:private:
"""
iterator = iter(iterator)
try:
prev = next(iterator)
except StopIteration:
return iterator
for elm in iterator:
yield prev, elm
... | 49a2c7b00f799865a42d42329fdffd005e8c952f | 629,066 |
import torch
def compute_output_gradient_times_vec_intermediate(relu_network, x, z0):
"""
Compute z and Wz defined in output_gradient_times_vector() function.
Notice that when the relu network input is 0, we use only the right
derivative.
Return:
z, Wz: Refer to output_gradient_times_vector... | 4088ea9c3f9735258dfe3475e01a51873608a44c | 629,067 |
def dump_to_file(filename, data):
""" Funtion to dump out the data to a CSV file """
data.to_csv(filename, index=True)
print ('*' * 100)
print('Save all data in to file: ' + filename)
print ('\n')
return(True) | 14a1eec7a3db9aa6420f6c62e5a470b41226feab | 629,068 |
def input_index_by_name(model, input_name):
"""
:param model: the keras model
:param output_name: the string name for a specific output
:returns: <int> specifying the index of the requested output
"""
name_to_index = {name:i for i,name in enumerate(model.input_names)}
return name_to_index[i... | faa707e177dbd76c75d55c3afc82e230588db6df | 629,069 |
from typing import List
def sector_to_subreddit_list(sector: str) -> List:
"""Returns list of subreddit for respective sector
Parameters
----------
sector : str
sector of ticker
Returns
-------
List
List of subreddits
"""
sector_subreddit_map = {
"Basic Ma... | eb9da27db1b83f9291fff9812c3b7d716864e0e4 | 629,070 |
import argparse
def get_args():
"""get command arguments"""
parser = argparse.ArgumentParser()
parser.add_argument("role", help="is leader or follower")
parser.add_argument("task_id", help="unique index for fl task")
parser.add_argument("app_id", help="tag for fl task")
parser.add_argument("wo... | c9c8b490be85352c55be84db2d07a66a1f34ce43 | 629,071 |
def v_relative(v, met):
""" Estimates the relative air velocity which combines the average air velocity of
the space plus the relative air velocity caused by the body movement.
Parameters
----------
v : float
air velocity measured by the sensor, [m/s]
met : float
metabolic rate,... | b226578ce844dc60d208670614b4c06d604c7d3a | 629,072 |
def list_duplicates(cells):
"""Find duplicates in list for detailed reporting
"""
# reference https://stackoverflow.com/questions/9835762
seen = set()
# save add function to avoid repeated lookups
seen_add = seen.add
# list comprehension below chosen for computational efficiency
# adds a... | 15ff3405d33d7e9b0a47021f164c5f53a316cbf6 | 629,073 |
def array_coords(array, grid, r_norm, z_norm):
"""Sets the attributes of an array based on whether it returns with grid=True"""
if grid:
return array.rename({"dim_0": "Z", "dim_1": "R"}).assign_coords(
R=r_norm, Z=z_norm
)
else:
return array.rename({"dim_0": "points"}) | 4f00832e549e55816f7b740da432cbb08a57c2c9 | 629,074 |
def convert_range(p):
"""Convert a float from 0-1 range to integer 0-255 range."""
return max(0, min(255, round(255 * p))) | 5afb82261d8f02fd3363ac30196e6cc544a94573 | 629,075 |
def GetRunKeyName(name):
"""Returns a str used to uniquely identify a run."""
return 'Run_%s' % name | 113933373ae1a38408912453a1e84586ba78dca7 | 629,076 |
def binary_search(my_list: list, item: int) -> int:
"""
二分法排序
:param my_list: 查找列表
:param item: 所需要查找的元素
:return: 索引位置, 没有找到返回 -1
"""
low_index = 0
hight_index = len(my_list) - 1
while low_index <= hight_index:
mid = (low_index + hight_index) // 2
guess = my_list[mid]... | e866cc752099d8e17810991e1b7e63b58cc9817b | 629,077 |
import functools
import warnings
def deprecated(obj=None, suffix=""):
"""
Decorator to mark a function or a class as deprecated
"""
def decorator_deprecation_warning(obj):
@functools.wraps(obj)
def wrapped(*args, **kwargs):
if isinstance(obj, type):
msg = (... | 019813143c185c4d322d0a057210631481d9843b | 629,078 |
def mock_get_json(url, timeout, params, auth=None, verify=True, cert=None):
"""Mock method that returns params generated for use in _get_json_batch"""
return params | 79a2ea920e27935caaf5d41b123888512b3e67c3 | 629,079 |
import uuid
def generate_username_id(name):
"""
Generate an Username ID.
:param name: The name of the user.
:type UserName: :class:`cripts.usernames.username.UserName`
:returns: `uuid.uuid4()`
"""
return uuid.uuid4() | 957d095d6c1f0db16af9adec06eb4cd44ec5d69f | 629,080 |
def parse_data(dataframe):
"""
Dataframe looks like:
label1 label2 label3 ...
trial1 0.4 0.4 ...
trial2 0.6 0.1 ...
. . .
. . .
returns:
[ [0.4, 0.6, ...] , [0.4, 0.1, ...] ]
"""
labels = dataframe.co... | 0bcca55d7d175236c19fd6ae7ea74dd2adff0c7f | 629,081 |
def check_envelope(new, old):
"""expand old envelope to max extents of new envelope
"""
if len(new) == len(old) and len(new) == 4:
# update envelope if polygon extends beyond bounds
if new[0] < old[0]:
old[0] = new[0]
if new[1] > old[1]:
old[1] = new[1]
... | bd57c6e20e8bfc139c532d3df7702f9afa578001 | 629,082 |
def normalize_position(image, box):
""" Takes in an image which will be provided and then computes the normalized bouding box information.
Args:
image (3D np.array): (rows, columns, channels)
rows (int): width of image
columns (int): height of image
channels (int): n... | f84c91e986362cb44a113ec312b7d7d80d1c4ad7 | 629,083 |
import json
def get_conf():
"""Reads the config file and deserialises it"""
return json.loads(open("conf.json", 'r').read()) | f748ad147c5cdb5783a6195b41cc95163c11390b | 629,084 |
import base64
def encode_buf(buf):
""" Encoded the provided buffer into base64"""
if buf:
bbuf = base64.b64encode(buf)
return bbuf
return buf | 07d766ee3eb87e7c3ae529ab2025ff5a472b6e5e | 629,085 |
import re
def get_node_class(data):
"""
Return node class from parsed data
Returns:
Class str
"""
match = re.search("^(?P<node_class>.*) {", data)
if match:
return match.group("node_class") | 95455696a78364bd34b2b56c57630739faffd79a | 629,086 |
def _is_all_zeros(data: bytes) -> bool:
"""Returns True if data is None, empty, or consists of all zeros."""
if data is None:
return True
for i in data:
if i != 0:
return False
return True | f222a47f2b5747f7fa6a155073d686190427efc4 | 629,088 |
def chanaverage(xds, width=1):
"""
Average data across the channel axis
Parameters
----------
xds : xarray.core.dataset.Dataset
input Visibility Dataset
width : int
number of adjacent channels to average. Default=1 (no change)
Returns
-------
xarray.core.dataset.Dat... | 21d8d2f1f62cb931cb7fb4d2dd82a4a47f00163e | 629,090 |
def _fcn_extrap(x, f, bounds):
"""
Extrapolates a flat value before and after bounds
x: array to be filtered
f: function to be applied between bounds (cf. fcn_cosine below)
bounds: 2 elements list or np.array
"""
y = f(x)
y[x < bounds[0]] = f(bounds[0])
y[x > bounds[1]] = f(bounds[1]... | fa7b381fcde91dceab7fb91e88efa1220065b917 | 629,092 |
def get_left_child(iIndex):
"""
Given an index it returns it's left child's index.
"""
return 2 * iIndex + 1 | 998665b926e97e30934215228ea893bc6b119a58 | 629,093 |
def unbox_enum(typ, obj, c):
"""
Convert an enum member's value to its native value.
"""
valobj = c.pyapi.object_getattr_string(obj, "value")
return c.unbox(typ.dtype, valobj) | db6644a9e67db3a629882b4e053068ef7fd552d5 | 629,094 |
def get_params():
""" All of xgboost parameters for training. """
params = {
'learning_rate': 0.01,
'n_estimators': 1000,
'verbose': 1,
'max_depth': 6,
'min_child_weight': 4,
'gamma': 0.6,
'subsample': 0.8,
'colsample_bytree': 0.8,
'reg_alp... | 399a4dffc2a00fb2692f870fc0be84c0a7856c01 | 629,095 |
def unsigned_int(value):
"""Convert from signed to unsigned int
(Channel Access does not support unsigend int)"""
if type(value) == int and value < 0: value = value+0x100000000
return value | ff93ffaa7b1bee45d3c89372aba116a86b3032e6 | 629,096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.