content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def string_empty(string):
"""Return True if the input string is None or whitespace."""
return (string is None) or not (string and string.strip()) | fddb1e639a57b29674ce6d0a101e875272731d77 | 698,628 |
def memoize(user_function):
"""Memoization decorator for user function of 1+ parameters"""
class Memodict(dict):
"""Memoization performs user function call on dict miss"""
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
... | e8f59f5e4460e332ff88bb235a6d8beb31065de2 | 698,629 |
def Dic_Test_Empty_Dic(indic):
"""
check if indic is a (nested) empty dictionary.
"""
if indic.keys()!=[]:
for key,keydata in indic.items():
if isinstance(keydata,dict):
if keydata=={}:
pass
else:
return Dic_Test... | 360e9190fd6ab23fb1d8b4d948647baed494f417 | 698,630 |
import imghdr
def detect_image_type(filename):
"""
获取图像文件类型
:param filename:
:return: jpge|png|gif|tiff等。失败返回None
"""
return imghdr.what(filename) | a4701aa60927e730899ed8036d6f2d875aa0524a | 698,631 |
import json
def to_formatted_json(output):
"""Output is a single record"""
return f"{json.dumps(output, indent=4)}\n" | e437c8b34e510f6a72cc27ccb7b2a14c3f60e09d | 698,632 |
def _permutation_worker(k: int, items: list) -> list:
"""The kth Johnson-Trotter permutation of all items."""
n = len(items)
if n <= 1:
return items
else:
group = k // n
item = k % n
position = n - item - 1 if group % 2 == 0 else item
dummy = _permutation_worker(g... | c997721d2682a9bf54b42596b093956bc17cf94b | 698,633 |
from typing import Dict
def _results_data_row(row: Dict[str, str]):
"""
Transform the keys of each CSV row. If the CSV headers change,
this will make a single place to fix it.
"""
return {
"k": row["Key"],
"v": row["Content"],
} | 97dc7f9842d7e6a564cbe66fd93e3dbaeca08517 | 698,635 |
import os
def dpath(path):
"""
get path to a data file (relative to the directory this test lives in)
"""
return os.path.join(os.path.dirname(__file__), path) | 000bb169050820243181b88f221b522c24267361 | 698,636 |
def is_odd(self, allow_rescaling_flag=True):
"""
Returns true iff after rescaling by some appropriate factor, the
form represents some odd integers. For more details, see parity().
Requires that Q is defined over `ZZ`.
EXAMPLES::
sage: Q = QuadraticForm(ZZ, 2, [1, 0, 1])
sage: Q.... | 3e9465a19c2ad91a024b8358d27693573c620d8d | 698,637 |
def _construct_url(resource, action, params=None):
"""
Constructs rest of API url based on resource, action and parameters.
Multiple parameters must be a list.
Single parameters must be a single string
Internal usage
"""
final_url = '{}/{}'.format(resource, action)
if type(params) == ... | 38b85a4400e362887f965c0035b3a2b10e7ecce4 | 698,638 |
from typing import List
def _split_inputs(inputs: str, named_groups: dict) -> List[str]:
"""
Identify and split inputs for torch operations.
This assumes that no quotes, apostrophes, or braces show up in the operation string.
Currently, items in lists that are not within functions will be broken up in... | 5edc3c53fb9b7a19557504335eb04eb15dd3c932 | 698,639 |
def get_analysis_file(filename: str) -> str:
"""
:param filename: The name of the file containing the source code.
:return: The expected name of the file containing the analysis.
"""
return filename.rsplit('.', 1)[0] + '.ll.cm' | 6a147b5bf69078dde81fdc72585907ece6c2f461 | 698,640 |
from typing import Tuple
from pathlib import Path
from typing import Optional
import argparse
def parse_arguments() -> Tuple[str, Path, Optional[int]]:
"""Parse command line arguments
Returns:
Tuple[str, Path, Path]: (identifier, path to save log, path to VLC)
"""
parser = argparse.ArgumentPa... | cf3e7528177510fbfdcdd3b615010f4ffc2e59b9 | 698,642 |
def _viewer_urls(spectra, zoom=13, layer='ls-dr9'):
"""Return legacysurvey.org viewer URLs for all spectra.
Note: `layer` does not apply to the JPEG cutout service.
"""
u = "https://www.legacysurvey.org/viewer/jpeg-cutout?ra={0:f}&dec={1:f}&zoom={2:d}"
v = "https://www.legacysurvey.org/viewer/?ra={... | 6fe781b92f929f9265d464935929490b67a6e9a7 | 698,643 |
def jsdate(d):
"""formats a python date into a js Date() constructor.
"""
try:
return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
except AttributeError:
return 'undefined' | 0c8331f928cf26e4cac7663dd6619c62cfff0fae | 698,644 |
import typing
import asyncio
import functools
def run_sync(
target: typing.Callable[..., typing.Any],
*args,
timeout: int = 10,
new_loop: bool = False,
**keywords,
) -> typing.Any:
"""Run async tasks synchronously with a timeout
:param target:
:param args:
:param timeout:
:par... | 6c3af5a29e79d2e5fcd2b4422895a5a761e7295a | 698,645 |
import random
def mutate(chromosome):
"""
Pick a random bit to mutate by XOR and shifting the selected bit. This
ensures diversity in the population.
"""
altered_bit_position = random.randint(0, 31)
mutation = chromosome ^ (1 << altered_bit_position)
return mutation | ff93fb19d7d83c558172d005fbd140284e2b16c2 | 698,646 |
def mileage_format(value):
""" Custom formatting for mileage. """
return "{:,} miles".format(value) | 056f5fbf5d291ac892bd8f2c16cda16937f758da | 698,648 |
def _list(key: str, vals: dict) -> list:
"""Get a key from a dictionary of values and ensure it is a list."""
result = vals.get(key, [])
if not isinstance(result, list):
result = [result]
return result | cf8a5da580dc4d95f83f18a92f82f646be5c4cb3 | 698,649 |
def structureSvInstance(stackedLine, tabSpace, alignCol, alignCom):
"""
This function restructures an input "stacked line" module declaration
from a .sv file. Expecting a module declaration on one line in the form
of:
blockName#(param1,param2,param3,...)(port1,port2,port3,...)
or:
blockNam... | 8939cb6cbd2115b8b6bae3866bd4be78d32e1954 | 698,650 |
def contrast_color(hex_color):
"""
Util function to know if it's best to use a white or a black color on the foreground given in parameter
:param str hex_color: the foreground color to analyse
:return: A black or a white color
"""
r1 = int(hex_color[1:3], 16)
g1 = int(hex_color[3:5], 16)
... | 470f713af48673d7b9fb8aa3bb30f7e1498da9b5 | 698,651 |
def get_ips(filename: str) -> list:
""" Reads ips from a list of files """
ips = []
with open(filename, 'r') as f:
ips = f.read().splitlines()
return ips | 6dfd326dc57df8a8297cd27a0d3d01fbe11db3f4 | 698,652 |
import sys
def check_source_target(db_source_atoms, res_target_atoms, dbatoms):
"""
several checks if the atoms in the dsr command line are consistent
:param db_source_atoms: ['C1', 'O1', 'C2', ...]
:param res_target_atoms: ['C1', 'Q2', 'C3_2', ...]
:param dbatoms: [['C1', 1, '-0.0014... | db592ad544a20f536b425409ef1a0d8ddbfb1c42 | 698,653 |
def all_packages(request, verbose=False):
"""List all packages"""
if verbose:
packages = request.db.summary()
else:
packages = request.db.distinct()
i = 0
while i < len(packages):
package = packages[i]
name = package if isinstance(package, str) else package["name"]
... | 76103ea29f787b7cd28ff8bc9aca37daea603432 | 698,654 |
import itertools
def get_common_base(files):
"""Find the common parent base path for a list of files.
For example, ``["/usr/src/app", "/usr/src/tests", "/usr/src/app2"]``
would return ``"/usr/src"``.
:param files: files to scan.
:type files: ``iterable``
:return: Common parent path.
:rty... | bb6c7fde6a9e2f9c620febf52047b547cf24e602 | 698,655 |
def magic_dir(tmp_path_factory):
"""Provides a temporary directory for testing copy/working directory behavior."""
magic = tmp_path_factory.mktemp('build_magic')
return magic | c891b0e7e8dbf2d23d380ce316fb80b6d78d1ec7 | 698,656 |
def comment(src_line: str) -> list:
"""Returns an empty list."""
return [] | c7e584811b899ae4a17ba4c9fd0debbc97e0a5cc | 698,657 |
import numpy as np
def mask_ccf_near_RV(rv,ccf,RVp,hw):
"""
This mask a region in the ccf near a the velocity RVp, typically for the
purpose of masking velocities that are close to the expected velocity of the planet
(hence RVp). RVp should be a list or array-like object with the same number of elemen... | d074183960dc6d665f905b592cb820a3eabf349c | 698,658 |
def is_regex_url(url, regexp):
""" Wrapper method to search URL for different properties based on regex
:param url: URL
:type url: `str`
:param regexp: Regular expression for the property
:type url: `str`
:return: True/False
:rtype: `bool`
"""
return len(regexp.findall(url)) > 0 | 8e5de88e8201805b95d91001067a7756749be048 | 698,659 |
def hidden_loc(obj, name):
"""
Generate the location of a hidden attribute.
Importantly deals with attributes beginning with an underscore.
"""
return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__") | 5a8c3d066cb96cf282c1b8814ac1302bd68111c0 | 698,660 |
import json
def _load_cluster_config(input_file_path):
"""
Load queues_info and add information used to render templates.
:return: queues_info containing id for first queue, head_node_hostname and queue_name
"""
with open(input_file_path) as input_file:
return json.load(input_file) | b86f163da96be1f831da7997872825e852439f84 | 698,661 |
def find_neighbors_hexagonal_grid(map_coordinates: list, current_position: tuple) -> list:
"""Finds the set of adjacent positions of coordinates 'current_position' in a hexagonal grid.
Args:
map_coordinates (list): List of map coordinates.
current_position (tuple): Current position of the hexag... | 2a6071d59a69b828eb252504508fa3f706969e1b | 698,662 |
from pathlib import Path
def openW2wFile(path, mode):
"""
Helper function to read/write all files with same encoding and line endings
:param str|Path path: full path to file
:param str mode: open mode: 'r' - read, 'w' - write, 'a' - append
:return TextIO:
"""
if isinstance(path, Path):
... | 6e42a26d2262ed10d15e19292e7b32fffd14aeb8 | 698,663 |
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be ... | 69c92c8eea98b6d8d869f0725c49d6b164d24480 | 698,664 |
from typing import Iterable
def make_conda_description(summary: str, conda_channels: Iterable[str] = ()) -> str:
"""
Create a description for the Conda package from its summary and a list of channels required to install it.
The description will look like::
This is my fancy Conda package. Hope you like it 😉.
... | b275e3bfcb67da33a4c7a34d7801a0cb4144527a | 698,665 |
import hashlib
def sha1(text):
"""
Calculate the SHA1 fingerprint of text.
:param text: The text to fingerprint (a string).
:returns: The fingerprint of the text (a string).
"""
context = hashlib.sha1()
context.update(text.encode('utf-8'))
return context.hexdigest() | 43473e9cc22b6cbe072170244b56b831f0cc88ee | 698,666 |
def ifirst_is_not(l, v):
"""
Return index of first item in list which is not the specified value.
If the list is empty or if all items are the specified value, raise
a ValueError exception.
Parameters
----------
l : sequence
The list of elements to be inspected.
v : object
... | fef5ae1a512772cf4df75a294057330280047f88 | 698,668 |
def get_calls(mock_observer_func):
"""Given a mock IPluginObserver method, returns the plugins that caused its
methods to be called, so basically a list of plugins that
loaded/unloaded"""
return [call_tuple[0][0].name for call_tuple in mock_observer_func.calls] | 41360429df5e71da47946f75f8207f985959528f | 698,669 |
def format_date_ihme(date_in):
"""
Formats "m/d/yyy" to "yyyymmdd"
"""
try:
month, day, year = date_in.split('/')
return '%s%02i%02i' % (year, int(month), int(day))
except:
return date_in.replace('-', '') | 166739b2245833c6dddf35fcde87433648697277 | 698,670 |
def reverse_map(dict_of_sets):
"""Reverse a map of one-to-many.
So the map::
{
'A': {'B', 'C'},
'B': {'C'},
}
becomes
{
'B': {'A'},
'C': {'A', 'B'},
}
Args:
dict_of_sets (dict[set]): A dictionary of sets, mapping
one value ... | 87b0679a0ebd00c3dbdcafc89fd2644b21ecbc85 | 698,671 |
from datetime import datetime
import sys
def write_xml(xml, agent_name, data_dir="/var/spool/pandora/data_in/"):
"""Creates a agent .data file in the specified data_dir folder\n
Args:
- xml (str): XML string to be written in the file.
- agent_name (str): agent name for the xml and file name.
- dat... | dbe5714bfdd97f94673c3a09b02671e3ee3991dc | 698,672 |
def get_iemocap_emotion(session_file_name, turn_name):
"""gets the assigned evaluated iemocap emotion for a given turn name in a given session dialogue"""
r = open(session_file_name, 'r')
lines = r.readlines()
for e, l in enumerate(lines):
emo_info = l.split('\t')
if len(emo_info) == 4 ... | e82576633632e0f3cffd8d4187607e955dade594 | 698,673 |
import functools
def expand_args(function):
"""Expand arguments passed inside the CallContext object.
Converts internal method signature 'method(ctx)' to whatever
is appropriate to the client code.
Args:
function: Async function expecting CallContext as a last argument.
Returns:
A... | 72e7de46684b2c02d958fad7f9ded71e653bb811 | 698,674 |
def derivative_of_binary_cross_entropy_loss_function(y_predicted, y_true):
"""
Use the derivative of the binary cross entropy (BCE) loss function.
Parameters
----------
y_predicted : ndarray
The predicted output of the model.
y_true : ndarray
The actual output value.
Return... | 7803c852f794ab9eae165c639bfb7a04cd0c1028 | 698,675 |
def AUC(answers, scores):
"""
Compute the `AUC <https://en.wikipedia.org/wiki/Area_under_the_curve_(pharmacokinetics)>`_.
@param answers expected answers 0 (false), 1 (true)
@param scores score obtained for class 1
@return number
"""
ab = list(zip(answers,... | 477cdf2a7b51352dd728465c883dae9cb4ab6e9a | 698,676 |
def factorial(number: int) -> int:
"""
Calculating factorial of a number using
prime decomposition method
"""
prime: list = [True] * (number + 1)
result: int = 1
for i in range (2, number + 1):
if prime[i]:
j: int = 2 * i
while j <= number:
p... | 2d6a85daa1b324fe419c3e5aecfbfc8373cffdcf | 698,677 |
import os
def filestructure_snapshot(path):
"""
Create a filestructure snapshot by returning the paths of all files inside a path.
"""
paths = []
for dirpath, _dirnames, filenames in os.walk(path):
paths.append(dirpath)
for filename in filenames:
paths.append(os.path.jo... | 36a0e5ee6f05c74e75bdeca7609702735127411e | 698,678 |
def api_failed(response, endpoint, exit_on_error=True):
"""
Check if api request failed
Can raise exception
"""
if 200 <= response.status_code < 300:
return False
if exit_on_error:
raise Exception("Status code {0} calling {1}".format(
response.status_code, endpoint... | 6a9d803444c4be09806eb6c5b588e1e04062c431 | 698,680 |
def select_field(X, cols=None, single_dimension=False):
"""
Select columns from a pandas DataFrame
Args:
X (pandas DataFrame): input data
cols (array-like): list of columns to select
single_dimension (bool): reduce data to
one dimension if only one column
i... | 4f80af3621af5e0c622f2c880e88d95a6e93034e | 698,681 |
def get_pathless_file_size(data_file):
"""
Takes an open file-like object, gets its end location (in bytes),
and returns it as a measure of the file size.
Traditionally, one would use a systems-call to get the size
of a file (using the `os` module). But `TemporaryFileWrapper`s
do not feature a ... | df1edfa6cb7b97c6abbdb2252b7dd8d505931768 | 698,682 |
import collections
def _make_repolist(c, path):
"""turn the repo log into a history
input: pathname to the repository
output: dictionary containing the history
"""
## logging.info('processing {}'.format(item))
with c.cd(path):
result = c.run('hg log -v', hide=True)
data = resu... | 5c3d27bcfd52f8b0656d5bf770ce83b0fcbdf5d0 | 698,683 |
def fizz_buzz_one( start, end ):
""" Note: This method returns a long string not a list. """
fizzbuzz = ''
# range is NOT inclusive of the 2nd number, so add 1 to include it.
# range(1,4) > 1,2,3. range(1, 4 + 1) > 1,2,3,4.
for i in range(start,end+1):
if i%3 == 0:
fizzbuzz += "f... | 9000ed93629bff15a74171565f562eee29814dd0 | 698,684 |
from functools import reduce
import operator
def factorial(n):
"""Calculate n factorial"""
return reduce(operator.mul, range(2, n+1), 1) | a58e0aad4e3a8baf06bbd1a6929a3aab2ab4e66e | 698,685 |
import argparse
import time
def parse_input():
""" Sets up the required input arguments and parses them """
parser = argparse.ArgumentParser()
parser.add_argument('log_file', help='CSV file of log data')
parser.add_argument('-e, --n_epochs', dest='n_epochs',
help='number of tr... | 3d701c6a91312ee597d8d25149ffdf2f6a0ea8cc | 698,686 |
from typing import Optional
from typing import Tuple
from typing import Match
import re
def is_conversion_err(error: Exception) -> Optional[Tuple[str, int]]:
"""Check if error is caused by generic conversion error.
Return a tuple of the converter type and parameter name if True,
otherwise return None.
... | 2e53420bb8a5715c75ee30a549453f40202d4ff7 | 698,687 |
def txt_file_to_list(genomes_txt):
"""
Read ids from a one column file to a list
Args:
genomes_txt:str: Path to file with the ids.
"""
with open(genomes_txt, 'r') as fin:
genomes_list = [line.strip() for line in fin]
return genomes_list | f79874dfbcb6a2a71be87b180e80513d480fcc8e | 698,688 |
def oxfordcomma(listed, condition):
"""Format a list into a sentance"""
listed = [f"'{str(entry)}'" for entry in listed]
if len(listed) == 0:
return ""
if len(listed) == 1:
return listed[0]
if len(listed) == 2:
return f"{listed[0]} {condition} {listed[1]}"
return f"{', '.... | c64ec05df35ccb6169363bf276fb874e61525c85 | 698,689 |
def get_all_user_attributes(client):
"""
This command gets all users, chooses the first
then, run a second get command that returns all the users attributes
"""
user_id = ""
attributes = []
all_users = client.get_all_users()
users_list = all_users.get("searchRecords")
if isinstance(... | d92ccab35a61bec96e34d3ca4a4035d7688001a0 | 698,690 |
def setup_loading():
"""Establish how recordings are loaded."""
# Indicates if all information on a recording is loaded in bulk, or as needed
load_all = True
# If load_all is True, indicates what is loaded in bulk
# Should be a subset of ["signals", "spatial", "units"]
to_load = ["signals"]
... | 8855e02ba57a79c72861796de3d0c3178232c2a8 | 698,691 |
def dense_rank(x, na_option = "keep"):
"""Return the dense rank.
This method of ranking returns values ranging from 1 to the number of unique entries.
Ties are all given the same ranking.
Example:
>>> dense_rank(pd.Series([1,3,3,5]))
0 1.0
1 2.0
2 2.0
... | 53bd64e112741f20c0e62f44ba7f5bcf8cdb2f83 | 698,692 |
def erbb2_context():
"""Create test fixture for ERBB2 Gene Context."""
return {
"id": "normalize.gene:ERBB2",
"type": "GeneDescriptor",
"label": "ERBB2",
"gene": {
"gene_id": "hgnc:3430",
"type": "Gene"
},
"xrefs": [
"ncbigene:2... | 0a4ef3bf47d8ac622d6c2778bd33199f5da2a747 | 698,693 |
import codecs
def decode_rot13(cipher: str):
"""Used to decode rot13"""
return codecs.decode(cipher, 'rot_13') | 3c20989614c6691c74294a93268745bbaccecf42 | 698,694 |
from unittest.mock import Mock
def mock_channel_file(
offered_by, channel_id, playlist_id, create_user_list=False, user_list_title=None
):
"""Mock video channel github file"""
content = f"""---
offered_by: {offered_by}
channel_id: {channel_id}
playlists:
- id: {playlist_id}
{"create_user_list: true... | 3042a7fc6f0fb622db8bf035a408672ddd6408ab | 698,695 |
from functools import wraps
def run_only_once(resolve_func):
"""
Make sure middleware is run only once,
this is done by setting a flag in the `context` of `ResolverInfo`
Example:
class AuthenticationMiddleware:
@run_only_once
def resolve(self, next, root, info, *args, *... | 9742318ca44ec92d7826d561968c87cea62db1bf | 698,696 |
def ldapmask2filemask(ldm):
"""Takes the access mask of a DS ACE and transform them in a File ACE mask.
"""
RIGHT_DS_CREATE_CHILD = 0x00000001
RIGHT_DS_DELETE_CHILD = 0x00000002
RIGHT_DS_LIST_CONTENTS = 0x00000004
ACTRL_DS_SELF = 0x00000008
RIGHT_DS_READ_PROPERTY = ... | a461fd5bdc6498df345491f38885a63b0dcbefc2 | 698,697 |
import re
def get_input_size(filename):
"""Gets input size and # of channels."""
with open(filename) as input_file:
for line in input_file:
match = re.match(r'^input.*\(None, (\d*), (\d*), (\d*)\)', line)
if match is not None:
x = int(match.group(1))
... | 3e753e5ac74babcbe4f48830cfde7a3002f7cc37 | 698,698 |
import os
from pathlib import Path
def get_generated_keys():
"""
get_generated_keys function gets the .key & .pub files in the project directory.
:return: private and public key file name
"""
priv_keys = []
pub_keys = []
for file in os.listdir("."):
if file.endswith(".key"):
... | f287a38964c1ce6b63180c861a106095cb49d5f3 | 698,699 |
def indexOfSmallestInt(listOfInts):
"""
return index of smallest element of non-empty list of ints, or False otherwise
That is, return False if parameter is an empty list, or not a list
parameter is not a list consisting only of ints
By "smallest", we mean a value that is no larger than any other
... | 63afb453b13ad4da75c83e9a7f6b409f58739d7e | 698,700 |
def field_with_classes(field, *classes):
"""
Adds the specified classes to the HTML element produced for the field.
"""
return field.as_widget(attrs = { 'class': ' '.join(classes) }) | 2b9929b2629fafaafbe1d2537afc0a9a601eed53 | 698,701 |
import tkinter as Tkinter
import tkinter.filedialog as tkFileDialog
def directory_from_gui(
initialdir='.',
title='Choose directory'): # pragma: no cover
"""
Opens dialog to one select directory
Parameters
----------
initialdir : str, optional
Initial directory, in which ... | e0b43a044c0e05815023de2275cc0ff1ffb01d8e | 698,702 |
def _test_path_to_file_url(path):
"""
Convert a test Path to a "file://" URL.
Args:
path: a tests.lib.path.Path object.
"""
return 'file://' + path.resolve().replace('\\', '/') | b13025da535fe43e074f79411ab4be55c766a572 | 698,703 |
def instantiate(repo, name=None, filename=None):
"""
Instantiate the generator and filename specification
"""
default_transformers = repo.options.get('transformer', {})
# If a name is specified, then lookup the options from dgit.json
# if specfied. Otherwise it is initialized to an empty list ... | 6a280b91598d9e0dd41d99165d0474b3dcdde7f3 | 698,704 |
def create_model_name(src):
"""Generate a name for a source object given its spatial/spectral
properties.
Parameters
----------
src : `~fermipy.roi_model.Source`
A source object.
Returns
-------
name : str
A source name.
"""
o = ''
spatial_type = src['S... | d305dd26bc6017f3fce5db2a5267fa6e74df3bc6 | 698,705 |
def csv_to_list(value):
"""
Converts the given value to a list of strings, spliting by ',' and removing empty strings.
:param str value: the value to split to strings.
:return: a list of strings.
:rtype: List[str]
"""
return list(filter(None, [x.strip() for x in value.split(',')])) | dbfb90dccf8d48a46f528ca02e958306e8dcc266 | 698,707 |
from pathlib import Path
import os
def collect_leaf_paths(root_paths):
"""Collects all paths to leaf folders."""
leaf_paths = [p for p in Path(root_paths).glob('**') if not os.walk(p).__next__()[1]]
return leaf_paths | 0c75bb94211710b156460702a8135448543f938d | 698,708 |
import os
def store_uploaded_file(title, uploaded_file):
""" Stores a temporary uploaded file on disk """
upload_dir_path = '%s/static/taskManager/uploads' % (
os.path.dirname(os.path.realpath(__file__)))
if not os.path.exists(upload_dir_path):
os.makedirs(upload_dir_path)
# A1: Injec... | 5c6234a3259ea5ed682046ffb0cd3e00d1e839cd | 698,709 |
def Main():
"""
:return:
"""
a = 1
b = 2
c = a + b
return c | 6482b416105d1ba23f564d6a47a52b7cba9c38bc | 698,710 |
def trim_walkers(res, threshold=-1e4):
"""Remove walkers with probability below some threshold. Useful for
removing stuck walkers
"""
good = res['lnprobability'][:, -1] > threshold
trimmed = {}
trimmed['chain'] = res['chain'][good, :, :]
trimmed['lnprobability'] = res['lnprobability'][good,... | ba8e3ebbb2c6948be06d4d1bbd3871011763d71c | 698,711 |
def _str_eval_true(eval, act, ctxt) :
"""Returns false."""
return [False] | eb0fd9b576b55133319752f86750159c9684ba0c | 698,712 |
import os
def get_cred_from_file(key):
"""Read credential information from a file."""
filepath = os.path.join(os.path.expanduser('~'), '.%s' % key)
with open(filepath) as f:
return f.read().rstrip() | b19d2bd27d336a939dab51d9781768cee30bdbd3 | 698,713 |
def swapaxes(dat, ax1, ax2):
"""Swap axes of a Data object.
This method swaps two axes of a Data object by swapping the
appropriate ``.data``, ``.names``, ``.units``, and ``.axes``.
Parameters
----------
dat : Data
ax1, ax2 : int
the indices of the axes to swap
Returns
---... | 576ec10826c3ab92465052edcadf38cf04952c02 | 698,714 |
def update_weight(y, unsupervised_weight, next_weight):
"""update weight of the unsupervised part of loss"""
y[:, -1] = next_weight
unsupervised_weight[:] = next_weight
return y, unsupervised_weight | c961714c248ba4c0f752be568115e444e1d963e2 | 698,715 |
import re
def is_url(value):
"""Return whether or not given value is a valid URL."""
regex = re.compile(
r"^"
# startchar <
r"<?"
# protocol identifier
r"(?:(?:https?|ftp)://)"
r"(?:"
r"(localhost)"
r"|"
# host name
r"(?:(?:[a-z\... | 3a50e541a9e62156a89693d15d248080abb3718f | 698,716 |
def ysum_ysq_count(ysum, ysq, counts):
""" calculate mean and error given accumulated sum of val and sq
Args:
ysum (np.array): accumulated sum of values, (nentry,)
ysq (np.array): accumulated sum of squares, (nentry,)
counts (np.array): number of hits for each entry, (nentry,)
Return:
(np.array, ... | ecdb04c291b28bb2ad8385be3b09a45a32a72c05 | 698,717 |
def remote_call(method):
"""Decorator to set a method as callable remotely (remote call)."""
method.remote_call = True
return method | ab276cbdb190185c7e46c5205df25f022a56a097 | 698,719 |
from pathlib import Path
def node(ph5, path, class_name):
"""
Get the node handle of a given path and class name
:param ph5: an open ph5 object
:type ph5: ph5 object
:param path: path to node
:type path: string
:param class_name: name of class to get
:type class_name: st... | 2a8090952fdec3dda7490844990f41c8e154c3af | 698,721 |
import os
def individuals_all():
"""Return path to .ttl-file containing _all_ triples."""
path = os.path.normpath(
os.path.join(
os.path.dirname(__file__), "data", "individuals_with_reasoning.ttl"
)
)
return path | d51c5cf49acc4eab107429964518ecd52dbe916f | 698,722 |
def indian_word_currency(value):
"""
Converts a large integer number into a friendly text representation.
Denominations used are: Hundred, Thousand, Lakh, Crore
Examples:
1000 becomes 1 Thousand
15000 becomes 15 Thousands
15600 becomes 15.60 Thousands
100000 becomes 1 Lak... | d162725f588d96a7dc3ead80b5278d71187bf4c1 | 698,723 |
import os
def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
ma... | 8b47709f09453060739215a1b2ac275a4dfc7f11 | 698,724 |
def txfDate(date):
"""Returns a date string in the TXF format, which is MM/DD/YYYY."""
return date.strftime('%m/%d/%Y') | fd1f19b4080447379ec3ec57be0f2af047099673 | 698,726 |
import datetime
def sobject_to_dict(obj, key_to_lower=False, json_serialize=False):
"""
Converts a suds object to a dict. Includes advanced features.
:param json_serialize: If set, changes date and time types to iso string.
:param key_to_lower: If set, changes index key name to lower case.
:param ... | 5915fdd52bee26a0f4bfac67fc1140ab3d6a49a3 | 698,727 |
def allInstances(cls):
"""Return cls instances for each of this class's set"""
items = [
(choice.value, cls(name=choice.name))
for choice in cls.set.values()
]
items.sort()
items = [v[1] for v in items]
return items | 702a77b9c247ec7976201cd0829a728c6c5fdd1f | 698,728 |
from typing import Union
def get_json_url(year: Union[str, int], kind: str = "photos") -> str:
"""Returns url for the json data from news-navigator for given `year` and `kind`"""
return f"https://news-navigator.labs.loc.gov/prepackaged/{year}_{kind}.json" | 0c7650f667cb1fceebbd73e7a6eaf00145061d38 | 698,729 |
def move_right(l: list) -> list:
"""リストの各要素を1つ右に移動させる"""
return [l[len(l) - 1]] + l[:len(l) - 1] | c645595532fa2bc89b58cc38eb79feaeb43cf9b2 | 698,730 |
import torch
def kl_energy(potential_fn, rates_fn, passive_rates_fn):
""" Calculates the mean log-likelihood ell of a trajectory.
Compares Feynman-Kac measure with parametrized measure.
Normalizes mean log-likelihood by dividing by total time and number of sites.
"""
def validate_fn(traj, dts, tr... | 0d081d08e379c7cb5021f565e949dc7e7a48a7d5 | 698,731 |
def id_for_dst(value):
"""generate a test id for dest"""
return f"dst->{value.comment}" | 8db759514d720fd15f437a45ad320edaf3b51c93 | 698,732 |
def does_not_contain(token, value):
"""
Validate that `token` is not a substring of `value`
:param: token: string e.g. : | .
:param: value: dictionary, list, or str
"""
if isinstance(value, str):
if token in value:
raise ValueError(f"{value} cannot contain {token}")
if ... | 06acdf6643a84f2991180c54cb116d5450bf0a9c | 698,733 |
def get_dummy_metadata():
"""
Incase of a temporal gap, the following metadata is used
"""
return dict({"product_file": "None"}) | 71a8a053579a153b9f78fffefe935ed4e9e40d01 | 698,734 |
def get_callback_result(callback, res_str):
"""
根据callback后的jsonp语句
:param callback:
:param res_str:
:return:
"""
if callback is None:
return res_str
else:
return '%s(%s)' % (callback.encode("utf-8"), res_str) | c78d7ff07b9fa07499f9dad41805c67308aa8646 | 698,735 |
def vdecomp(v, m=None, minlen=None, maxlen=None):
"""
Decompose a vector into components. an nD stack of m-element vectors will return a tuple with up to m elements,
each of which will be an nD stack of scalars
:param v: nD stack of m-element vectors, a numpy (n+1)D array with shape
(n_stack0,n... | cbc846be6a07082711e5c9faa191181c8cdc75f8 | 698,736 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.