content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def clock_emoji(time): """ Accepts an hour (in 12 or 24 hour format) and returns the correct clock emoji. Args: time: 12 or 24 hour format time (:00 or :30) Returns: clock: corresponding clock emoji. """ hour_emojis = { "0": "🕛", "1": "🕐", "2": "🕑", ...
4ba4864d6fbdced7413e3233cba35c3a8d45a9f7
658,491
def igraph_path(g, nodes, labels=None, desc=None): """Display edge directions in path of nodes""" return " ".join( "[{node}] {arrow}".format( node=u if labels is None else (labels[u] if desc is None else desc[labels[u]]), arrow="->" if g...
5df0abc3501acbbd07f661ac55f81145feebb490
658,492
import itertools def count_alive_neighbors(alive_cells: set, coords: tuple) -> int: """return the number of alive neighbors of a given cell""" alive = 0 ranges = ((c-1, c, c+1) for c in coords) for cell in itertools.product(*ranges): if cell in alive_cells: alive += 1 if coords...
a84782f90632f433b2adffe6283ca6909332a680
658,493
import random def _assign_random_labels(seq, labels, lab_imb): """For Categorical attributes: assign the purest label of each community. Return a list of the purest labels.""" tot_lab_seq = [] for lb in labels: if lb == "auto": card_lab = [i for i in range(1, len(seq) + 1)] ...
33802d873880d32c488b2ebb67c46a8362573be9
658,494
import re def find_clades_by_name(tree, terminal=True, contains=[], pattern=None): """Faster implementation than BioPython's Phylo package find_clades search functionality. """ if pattern: pattern = re.compile(pattern) if terminal: if contains: return (clade for clade i...
aa70e62a4bfff43aca57104b61aef2e9ff50e1e2
658,495
def Password_length() : """ :return length """ while True : while True : length = input("Please enter the length of passcode you want (8~16): ") if length.isdigit() : break else : print("!!! Please enter an integer. !!!") ...
a68b1ecfafed23ac005fc21482fc669c26cbebd7
658,496
def minor(matrix: list[list], row: int, column: int) -> list[list]: """ >>> minor([[1, 2], [3, 4]], 1, 1) [[1]] """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor]
1261617518e5a1fe8cf247881796e87a29dd3c0a
658,497
import re def count_MNQmod(aaseq, char2find=r"\(de\)|\(ox\)"): """ count the number of oxidized M, N modified to D and Q modified to E e.g. aaseq = r"_AAIAAFNAQ(de)N(de)N(de)GSNFQIEEISR_" count_N2D_Q2E(aaseq) :param aaseq: String :param char2find: String :return: Tuple(Int, Int) ""...
53de802997ef8b268914670f73b82dcd47eeb44f
658,498
def _env_sh(_dict, path_append=True): """ Parameters ---------- _dict : dict Returns ------- str """ text = "" for k, v in _dict.items(): if path_append and k == "PATH": text += k + "=\"" + "$PATH:" + v + "\"\n" else: text += k + "=\"" + v...
30b497ba0bf0e2708c658386e2e4225dde473771
658,499
import argparse import os def parse_args(): """ Parse python script parameters. Returns ------- ArgumentParser Resulted args. """ parser = argparse.ArgumentParser( description="Calculate Dataset Statistics", formatter_class=argparse.ArgumentDefaultsHelpFormatter) ...
90f04b7080866c68ea86f825fe629c6b2e85f64a
658,500
def roundRobin(units, sets=None): """ Generates a schedule of "fair" pairings from a list of units """ if len(units) % 2: units.append(None) count = len(units) sets = sets or (count - 1) half = count / 2 schedule = [] for turn in range(sets): pairings = [] ...
fda7cb13a31d9363aae5ea6287c3247b376d1ec7
658,501
def flush(hand): """"Return True if all the cards have the same suit. Args: hand: list of 5 2-letter strings representing card rank and suit. """ return hand[0][1] == hand[1][1] == hand[2][1] == hand[3][1] == hand[4][1]
01236468b98531ef55c506b7eb3ba1e4907afc67
658,502
def maxpitchamp(amparray): """ Max Pitch Amplitude audio feature: High Predictability rate (86%) :param amparray: array of pitch period amplitudes (floats) :return maxamp: Max pitch period amplitude """ maxamp = 0 if len(amparray) > 0: maxamp = max(amparray) return maxamp
529d2214a1fc708a1126c65c02d87800bd7d9bba
658,503
def tally(rows): """ Return result table """ table = {} for line in rows: items = line.split(";") if items[-1] == "win": try: table[items[0]][0] += 1 table[items[0]][1] += 1 table[items[0]][4] += 3 except Ke...
acba65f84189fcb83474f09e15811c128ebfca05
658,506
import re def mem2bytes(t): """ MEM2BYTES converts memory size (from str) to bytes (to double) v = mem2byes("300 kB") """ if not isinstance(t,str): raise ValueError("t must be a string") U = "KMGTP"; f = [1<<10,1<<20,1<<30,1<<40,1<<50] # A left shift by n bits is defined as multip...
6dcec069ea8995f69e8315a038418f7e96c6b0e6
658,507
def get_overlap(a, b): """ Computes the amount of overlap between two intervals. Returns 0 if there is no overlap. The function treats the start and ends of each interval as inclusive, meaning that if a = b = [10, 20], the overlap reported would be 11, not 10. Args: a: Fi...
692892f21169b5d626fe40e6a0700385a181d513
658,508
def _GetResourceMessageClassName(singular_name): """Returns the properly capitalized resource class name.""" resource_name = singular_name.strip() if len(resource_name) > 1: return resource_name[0].upper() + resource_name[1:] return resource_name.capitalize()
19cc9802ed97398120753e36e856fc44d6a3cf6c
658,511
def analyze_data(year_member_type): """ Step 3: 数据分析 """ n_member = year_member_type[year_member_type == 'Member'].shape[0] n_casual = year_member_type[year_member_type == 'Casual'].shape[0] n_users = [n_member, n_casual] return n_users
8812d9cde05eaf1471ed78646764ff381c711615
658,512
import os def find_lib_path(): """Find Tengine dynamic library files. Returns ------- lib_path : list(string) List of all found path to the libraries. """ dll_path = [] curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) dll_path.append(curr_path) #d...
264512223e58ea1fc2d1dc67624579649f4c82e6
658,513
import sqlite3 from typing import List def _get_table_names( conn: 'sqlite3.Connection', fts4: bool = False, fts5: bool = False ) -> List[str]: """A list of string table names in this database.""" where = ["type = 'table'"] if fts4: where.append("sql like '%USING FTS4%'") if fts5: ...
749ce1f1946d10e512c8ecc6dcbed7826968e9ff
658,514
import os def error(path): """ Handle eventual internal error. You can optionally use your custom error page, just add it to 'static' folder and return it with 'app.send_static_file' method. :param path: file path """ if not(os.path.isfile(path)): return "Application error : "+pat...
e816300e12f631e6af39539f5e6cbeceb0842ccb
658,515
def n_values(obj, keys): """Extract multiple values from `obj` Parameters ---------- obj : dict A grow or data "object" keys : list A list of valid key names Must have at least one element Returns ------- tuple The values for each key in `args` Notes ...
1394b19f0978ae1b15fddc5515325d31bfa36434
658,516
def project_09_pythagorean_triplet(summation): """ Problem 9: Find the product of pythagorean triplet a, b, c, that sums to user specified total. Args: summation (int): The sum of a + b + c. """ for a in range(0,int(summation/3)+1,1): for b in range(a+1, int(summation/2)+1,1): ...
0ac7fb00feb9e24f02d49e3066e736dc17713583
658,517
def troubleDiff(old, new) -> str: """ 消えた情報には価値は無いので新規除法だけ出すように変更 """ new_set = set(new) - set(old) return "\n".join(new_set)
fd9088324dd6f919a038c6e15fdd2c4682b63528
658,518
def _inverse(self): """Inverse""" if self.cols != self.rows: print('agla: keine quadratische Matrix') return if self.det() == 0: print('agla: die Inverse existiert nicht (die Determinante ist = 0)') return return self.inv()
654a086fc686669b4982e6917ab10c5654478c32
658,519
import ast def lift_sourcecode(value, filename="<unknown>"): """Parse a string as a Python expression. Run-time part of `n[]`. Main use case is to access lexical variables with names computed at your macro definition site:: lift_sourcecode("kitty") -> Name(id='kitty') More complex expressions w...
84b0fcc18b47c846958d739f2ed9c4ba2f9df501
658,520
def make_filename(name): """Make valid file name. """ return "".join(l for l in name if (l.isalnum() or l in "._- ") and l not in "/")
32bf960953ac549f312623fa97bac605805301dc
658,521
def __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max): """ For RGB_to_HSL and RGB_to_HSV, the Hue (H) component is calculated in the same way. """ if var_max == var_min: return 0.0 elif var_max == var_R: return (60.0 * ((var_G - var_B) / (var_max - var_min)) + 360) % 360.0 ...
d4a91f31a52234c3a8b0093a8915c8bf32a56d08
658,522
def fibonacci(n): """ fibonacci function Args: n (int): the number for the n numbers of fibonacci Returns: a list of finobacci numbers """ result = [1] # fibonacci number starts from 1 t1 = 1 t2 = 1 if n > 0: for _ in range(n-1): result.append(t2)...
8c0d4089782c1114428cf5f43bf316a673e9f159
658,523
import torch def eval(model,dataloader, criteria, batch_size,gpu_f=True): """ :param model: model to be tested :param dataloader: dataloader for testing set :param criteria: loss function to be used :param batch_size: batchsize in dataloader :return: return predictions and targets as tuple ...
852cfa1a361ded3e06026623e3bdbb3ff755cb4a
658,524
import logging def log_func_decorator(func): """ Decorator to log the execution of a function: its start, end, output and exceptions """ logger = logging.getLogger() def wrapper(*args, **kwargs): logger.info( 'Executing function "{}" (args: {}, kwargs: {})'.format( ...
f812c046612fe5c24fdcc0e4b61a3ce1d9f3bec6
658,525
import struct def int2byte(i): """Encode a positive int (<= 256) into a 8-bit byte. >>> int2byte(1) b'\x01' """ return struct.pack('B', i)
78749aa3c581e7dd944260c05c49c2ae1434abb1
658,526
from typing import List import random def sample_vector(dimensions: int, seed: int) -> List[float]: """Sample normalized vector given length. Parameters: dimensions: int - space size seed: Optional[int] - random seed value Returns: List[float] - normalized random vector of given ...
c1da7b824857e63d8745e1944fc1689c92b7c786
658,527
def add_to_visited_places(x_curr: int, y_curr: int, visited_places: dict) -> dict: """ Visited placs[(x,y)] contains the number of visits that the cell (x,y). This updates the count to the current position (x_curr, y_curr) Args: x_curr: x coordinate of current position y_curr: ...
605d1941ae0f069405ed4b804cf9c25ee3381b9b
658,528
def remove_keys(dict_, seq): """Gracefully remove keys from dict.""" for key in seq: dict_.pop(key, None) return dict_
65a6b8d846081e42db25f5fc056c59723ee3be9c
658,529
import torch def bbox_drop(bbox, boundary): """Drop bounding boxes that are not entirely inside image boundary. Note that difference between bbox_drop() and bbox_clip(): clip will resize the bbox to be inside image, drop will just eliminate the outsiders. Args: bbox [N x 4]: bounding boxes bou...
67dfa26f2aedf51a009fc8f438c0495b77667cd6
658,530
import os def check_absolute_path(directory, print_error=True): """Check if a directory has an absolute path or not.""" output = False if os.path.isabs(directory): output = True elif print_error: print("ERROR: Please use an absolute path") return output
c524205c683d2659782a10e6904424bc81b5caec
658,531
def reverse_score(dataset, mask, max_val=5, invalid_response=None): """Reverse scores a set of ordinal data. Args: data: Matrix [items x observations] of measured responses mask: Boolean Vector with True indicating a reverse scored item max_val: (int) maximum value in the Likert (-like...
98df725b23f14f12106bee43a8de88fded2e42df
658,532
def flat_dataset_dicts(dataset_dicts): """ flatten the dataset dicts of detectron2 format original: list of dicts, each dict contains some image-level infos and an "annotations" field for instance-level infos of multiple instances => flat the instance level annotations flat format: ...
52a3ea4449381f83372cb9cd7fb7c2463b6dab10
658,533
def mapping_dialog_id(a_id, b_id): """计算对话 id """ assert a_id != b_id dialog_id = a_id << 32 | b_id if a_id < b_id else b_id << 32 | a_id return dialog_id
cd150ae93b85ab86191f55255e51846d9d2b15a0
658,534
import copy def v3_to_v2_package(v3_package): """Converts a v3 package to a v2 package :param v3_package: a v3 package :type v3_package: dict :return: a v2 package :rtype: dict """ package = copy.deepcopy(v3_package) package.pop('minDcosReleaseVersion', None) package['packagingVe...
37a54fba43dc6c92dd51aa50fe5e160fa4ee9fa9
658,535
def is_desktop(request): """ See if the browser is desktop """ if request.MOBILE == 0: return {'is_desktop' : True} else: return {'is_desktop' : False}
f1c206faecbf4903d1757f794a22f36d4046bb05
658,536
from typing import Tuple import requests def get_pf_parking_data() -> Tuple[int, str]: """ Returns a parking HTML document from the UQ P&F website """ page = requests.get("https://pg.pf.uq.edu.au/") return (page.status_code, page.text)
d152c842a7d78073e04382f113a90b5bc2bf9070
658,537
def _fetch_all(cursor, row_callback): """Fetch all rows and return them all at once.""" return [row_callback(r, cursor) for r in cursor.fetchall()] \ if cursor.rowcount else []
ba5049c37d6ad749092b1819f48f879037b57734
658,538
def decimal_to_binary_util(val): """ Convert 8-bit decimal number to binary representation :type val: str :rtype: str """ bits = [128, 64, 32, 16, 8, 4, 2, 1] val = int(val) binary_rep = '' for bit in bits: if val >= bit: binary_rep += str(1) val -= bi...
85dc53b4635d509f3562a458f6350aeca263ed36
658,539
def multidict_split(bundle_dict): """Split multi dict to retail dict. :param bundle_dict: a buddle of dict :type bundle_dict: a dict of list :return: retails of dict :rtype: list """ retails_list = [dict(zip(bundle_dict, i)) for i in zip(*bundle_dict.values())] return retails_list
1d3c95ef6f2d5a7065f95b4a26d430d10618cb49
658,540
def has_module(module_name, members=[]): """Returns whether or not a given module can be imported.""" try: mod = __import__(module_name, fromlist=members) except ImportError: return False for member in members: if not hasattr(mod, member): return False return Tr...
b52ab117c1555cb14775f52e9a7a092eb361658e
658,541
def rotate(text, direction, distance): """Rotate operations. rotate left/right X steps means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc. rotate based on position of letter X means that the whole string should be rotated to the right based on ...
e4bd00fc4229bccc4bccd43d191668a7c0fb2c8e
658,542
from typing import Any import zlib def compute_hash(*args: Any) -> str: """ Creates a 'version hash' to be used in envoy Discovery Responses. """ data: bytes = repr(args).encode() version_info = ( zlib.adler32(data) & 0xFFFFFFFF ) # same numeric value across all py versions & platform...
0f41694319d173bddacb633b12c72611f37e9eb6
658,543
def get_coordinates(sub_turn): """ Obtain coordinates entered by human user Attributes ---------- sub_turn: str Game's sub turn. Used to prompt user. """ print(sub_turn, 'phase') user_input = input("Please input in following format: xy ") column, row = -1, -1 # Adding this ...
ce1556bc826581c7b3536bf60f21c51dbf8b4ae8
658,544
def find_content_children(g, s): """ :type g: List[int] :type s: List[int] :rtype: int """ if not g or not s: return 0 g = sorted(g) s = sorted(s) gidx = 0 sidx = 0 count = 0 while gidx < len(g) and sidx < len(s): if g[gidx] <= s[sidx]: count...
339da6443fd86e1e57ffbae2a667bf353ddad891
658,545
def _get_default_rules(): """ A basic set of rules: - Allow access to Port 22 (SSH) - Allow IPv4 Access - Allow IPv6 Access --- This is an EXAMPLE of what should be in your PROVIDER's `cloud_config`: cloud_config = { ... 'network': { ... 'user_secu...
23eaeeab754eae439e2a37ce714f61824108e538
658,546
def calc_grade_score(grade_list): """ :param grade_list: a list of grades :return: the final grade, unweighted """ return sum(grade_list) / len(grade_list)
053ccb6e438039f7625ba801d3dcb801f4a7cde0
658,547
def flip(str_array: list[str]) -> list[str]: """ Flip a list of strings on a top-left to bottom-right diagonal :param str_array: array as a list of strings :return: array flipped """ return list(reversed(str_array.copy()))
572ca4337da74493f9f3e489e2875ea7f356f16f
658,548
import os def get_container_options(container_options): """ Get the container options from AGIS for the container execution command. For Raythena ES jobs, replace the -C with "" (otherwise IPC does not work, needed by yampl). :param container_options: container options from AGIS (string). :return...
87a65a1cf3edd6866985de9cac0ac409023cba33
658,549
import csv def read_csv_mapping( csvFile, firstColIsKey=True ): """Returns a dictionary mapping values in the first column to values in the second. That way the second column list of tuples for each row of the stored item Args: firstColIsKey (oboolean): Whether the first column in the file is to...
4c8d348e6b9870176e55ef401636c5004fd178c2
658,550
def get_query(premise: str, hypothesis:str) -> str: """Construct a query by specifying a prompt to accompany the input x.""" prompt = 'How are the Premise and Hypothesis related?' query = 'Premise: ' + premise + ' ' + 'Hypothesis: ' + hypothesis + ' ' + prompt return query
a9047fc1bdc2fdea7ff66d40bef2f9ab28471564
658,551
import requests import json def get_asset_data(token, video_id, account_id): """ returns JSON object that contains a bunch of asset-related data for a specific video, but not metadata """ url = "https://cms.api.brightcove.com/v1/accounts/{}/videos/{}/sources".format( account_id, video_id) ...
f1ec396200559fdc9225ab420955f7b1f1a933b9
658,552
def extract_parent_dir_name(value: str): """figures out what the clone directory will be called""" # "git@github.com:esmf-org/esmf-test-summary.git" return value.split("/")[-1].split(".")[0]
32464ed17e03c22aaa3f194ec5a7e4e68dfdc076
658,555
def _derived_measures(inmat): """Return a dictionary in which the keys are the derived measures and the values gives their composition """ d = {} n = len(inmat) for i in range(1,n): for j in range(i+1,n): d[inmat[i,j]] = "{} * {}".format(inmat[0,i], inmat[0,j]) return...
26800589f3bfc80275d8e590f90ba8fc0f75ddbe
658,556
def expand(data): """ Provede rozšíření z 32 bitů předané pravé strany na 48 bitů, které se dále využijí v f-funkci. Šlo by použít funci permutate, nicméně jsem chtěl odlišit, že dochází k rozšíření. :param data: Vstupní pravá strana, tedy řetězec o 32 znacích reprezentující binární číslo. """ ...
8065a414e94dcd92c1affc45f56ee9d3c8deeb6a
658,558
import torch import time def nms_no_voting(boxes, scores, std, overlap=0.5, top_k=200, sigma_t=0.02): """Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. Args: boxes: (tensor) The location preds for the img, Shape: [num_priors,4]...
348a72ea90891fa70a469767c27f7a5f90ce7cc4
658,559
import hashlib def hash_file(filepath): """ Hashes the contents of a file. SHA1 algorithm is used. :param filepath: Path to file to hash. :type filepath: ``str`` :return: Hashed value as a string :rtype: ``str`` """ HASH_BLOCKSIZE = 65536 hasher = hashlib.sha1() with open(fil...
c9a374ec7aa471c3f226431be55770d108145f41
658,560
def make_xz_ground_plane(vertices): """ Given a vertex mesh, translates the mesh such that the lowest coordinate of the mesh lies on the x-z plane. :param vertices: (N, 6890, 3) :return: """ lowest_y = vertices[:, :, 1].min(axis=-1, keepdims=True) vertices[:, :, 1] = vertices[:, :, 1] - ...
e05622420f431882a11cf60f4db28c094cbc0dca
658,561
def make_title(text): """ turn a text string of words into a title by capitalizing each word """ words = text.split() new_words = [] for word in words: new_words.append(word[0].upper()+word[1:]) return ' '.join(new_words)
a00097cc17f44c9e28f5e523d7347ff8ea091186
658,562
def load_file_as_list(file_path: str) -> list: """ Loads the file at a specificed path, returns an error otherwise :param file_path (str): The path to the file you want to load :return _file a file of the contents of the file """ _file = "" try: with open(file_path, "r") as ...
5d1c3f87c4108c9f5d6d843c7fbcdc1e127629b4
658,563
import inspect def _has_kwarg_or_kwargs(f, kwarg): """Checks if the function has the provided kwarg or **kwargs.""" # For gin wrapped functions, we need to consider the wrapped function. if hasattr(f, "__wrapped__"): f = f.__wrapped__ (args, _, kwargs, _, _, _, _) = inspect.getfullargspec(f) ...
1f1b1e3698ac9d06ee8afe8255344190c793e258
658,564
def baz(): """frobnicate the quux machine""" return 3
da66be4c8da471f47733ac2c9415a76e51d810aa
658,565
def get_tes_status(tes, buffer_low, buffer_high): """ Returns tes status: 1 - No further power input allowed 2 - Only thermal input of efficient devices (e.g. CHP, HP) allowed 3 - All devices can provide energy Parameters ---------- tes : object Thermal energy storage object of ...
7f02dc42f818095b5cebc0d1985b50ed1e1e2ccc
658,566
def extract_encoder_model(model): """ Extract the encoder from the original Sequence to Sequence Model. Returns a keras model object that has one input (body of issue) and one output (encoding of issue, which is the last hidden state). Input: ----- model: keras model object Returns: ...
f3afdff230f1d8fb795c122bbe5abb8c42b90843
658,567
def hello_world(): """ writeln("Hello, world"); """ return None
269a6a5d4ebe435f4e3c901338f97a8a5fcfe44d
658,568
import argparse def build_parser(): """Creates a parser suitable for parsing a command line invoking this program. :return: An parser. :rtype: :class:`argparse.ArgumentParser` """ parser = argparse.ArgumentParser() parser.add_argument( "input", help="Choose amongst : a file, ...
0ea5b5507ef800278ee5d067be7cae1ec733ade3
658,569
def get_frequency(text: str) -> dict: """Get word frequency from text""" freq_dict = {} for letter in text: freq_dict[letter] = freq_dict.get(letter, 0) + 1 return freq_dict
1ac3d9203c41e4d999ac9349e867724cb87cad81
658,570
def slider_command_to_str(arguments): """ Convert arguments for slider and arrowbox command into comment string for config file. :param arguments: slider arguments :return: Formatted string for config file. """ return '; '.join(arguments)
36f10271d5fb8f6c7477b71eb515fb4194b5ce4f
658,572
def factorial(n): """Computes factorial of n.""" if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result
16894444b052095b255574aa1ab355e12fa37ef4
658,573
import torch import math def log_poisson_loss(targets, log_input, compute_full_loss=False): """Computes log Poisson loss given `log_input`. FOLLOWS TF IMPLEMENTATION Gives the log-likelihood loss between the prediction and the target under the assumption that the target has a Poisson distribution. ...
aebf9b09f921feac836bba1b56d4243915a5ca18
658,574
import re import subprocess def nc_convert(filename): """ Transform a NETCDF4 file to classic-model format. Requires installation of netcdf binaries: apt-get install netcdf-bin (Ubuntu) or brew install netcdf (OSX) :param filename: :return: output filename """ output_file = re.sub('\.n...
e760cb799571a096234774537fb961df92753c65
658,575
from typing import Dict async def read_file(file_path: str) -> Dict[str, str]: """Pass file path.""" return {"file_path": file_path}
74616df579472b83746f004f9075c6dfc0c879e3
658,577
def row2dict(row): """ *** **** Make this function global in order to use it from all files :param row: :return: it converts a db row to a dictionary (key:value pairs) """ d = {} for column in row.__table__.columns: d[column.name] = str(getattr(row, column.name)) return d
db590380b26c5c5b892f26215b68bef3717414dc
658,578
import argparse def restricted_float(x): """ Takes an argparsed argument x and ensures it is a float in the range (0, 1]. Credit: https://stackoverflow.com/questions/12116685/how-can-i-require-my-python-scripts-argument-to-be-a-float-between-0-0-1-0-usin """ try: x = float(x) except Va...
11da6fb9001012790107cd160947ac1214cbff64
658,579
import fnmatch def _find_one(pattern, files): """ :type files: tuple[pathlib.Path] :rtype pathlib.Path >>> str(_find_one('*.txt', (Path('/tmp/asdf.txt'),))) '/tmp/asdf.txt' >>> _find_one('*.txt', (Path('/tmp/asdf.tif'),)) """ files = [f for f in files if fnmatch.fnmatch(f.name, pattern...
2e99368a17dcbb433f5db2de68b18629963c88e2
658,580
def receiver(signal): """ A decorator for connecting receivers to events. Example: @receiver(on_move) def signal_receiver(source_path, destination_path): ... """ def _decorator(func): signal.connect(func) return func return _decorator
478e62178a756bdc8cdfcdf050103b2ab4db3b0b
658,581
def pnpoly(point, vertices): """Python translation of the C algorithm taken from: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html """ (x, y) = point j = vertices[-1] c = False for i in vertices: if ( (i[1] > y) != (j[1] > y) ) and \ ( x < (((j[0]-i[0]) * (y-i[1]) / (j[1...
85b51e122f1ee37dc790f2acb43a6d92eca056bb
658,582
def define_options(enable=[], disable=[]): """ Define the options for the subscribed events. Valid options: - CRfile: file created - CRdir: directory created - MDfile: file modified - MDdir: directory modified - MVfile: file moved - MVdir: directory moved ...
a0b35008bebe70d3ec7b964122e24746ee89d1cc
658,583
def _solve_method_1(a): """Literally did this first and was surprised when it didn't work on any other test case, and then found out about the problem inputs.""" first_d = a[0][0] + a[1][1] + a[2][2] second_d = a[0][2] + a[1][1] + a[2][0] return abs(first_d - second_d)
a5b08b88bdb235e86db1366a4df41f479be486cb
658,584
def safeindex(v, s): """Safe index for v in s, returns -1 if v is not in s""" if v not in s: return -1 return s.index(v)
849583010a50971b68aeb2d97053e3e1c94ec5fb
658,585
import os def files_in_dir(path, extension): """Enumartes the files in path with the given extension""" ends = '.{0}'.format(extension) return (f for f in os.listdir(path) if f.endswith(ends))
f78f0cebbb58995da9e72e8b75f7fa985795683a
658,586
def rot13_decode(decvalue): """ ROT13 decode the specified value. Example Format: Uryyb Jbeyq """ return(decvalue.decode("rot13"))
dcf9625f329ee19a5138adf0b909a17f686ce41e
658,587
def inner(u, v): """inner product""" return (u * v.conjugate()).real
6969dd442b114900824f78e0c230b4fd7da064dc
658,588
def get_image_url(status): """ Get image url from tweet status Parameters ---------- status: Tweet Tweet status that mentions img2palette Returns ------ image_url: str Image url """ if "media" not in status["entities"]: raise ValueError("No phot...
86479c8f58b749439440568fbaed1a1439a0ac34
658,589
def is_full_section(section): """Is this section affected by "config.py full" and friends?""" return section.endswith('support') or section.endswith('modules')
bf11103b876432ac1d6eefc6884bf81647c8ca41
658,590
def get_parseinfo(fp): """Read parse info.""" return dict( bozo=fp.get('bozo') and str(fp.get('bozo_exception')), encoding=fp.encoding, version=fp.get('version'), namespaces=fp.get('namespaces'), # Not using HTTPStatus here because YAML must output int. status=fp....
a9d1cdf967cf24689e7504c054bcafb8a5632893
658,592
def msort(l, key): """Sort which also allows None.""" return l.order_by(key)
bc12b4ccdeea52e3de3e2c06c38e19cdb3b26d6a
658,593
from typing import List def delete_items(keys: List[str], s3_bucket): """Delete the specified keys from the provided S3 bucket and return the S3 response.""" delete_request = { 'Objects': [{'Key': key} for key in keys] } print(f'Deleting keys {keys} from bucket {s3_bucket.name}') return s...
0f4b3c1227c29acad9105514da9391fe7a6f5b77
658,594
import random def pick_random(my_list, ntopick): """Function to pick a series of random elements from a list""" ids_out = [] fps_out = [] i = 0 while i < ntopick: my_choice = random.randrange(0, len(my_list)) if my_choice in ids_out: continue ids_out.append(my_c...
db73743b5d60c36adee526254079c851a001b378
658,595
from operator import add from functools import reduce def sum_node_list(node_list): """Custom sum function in order to avoid create redundant nodes in Python sum implementation.""" return reduce(add, node_list)
3be1d07051301a245a7691102bf2bd6926a23d64
658,596
import argparse def create_arg_parser(): """ Returns an ArgumentParser instance. """ arg_parser = argparse.ArgumentParser(prog="pycoolc") # Cool program(s) source file(s) arg_parser.add_argument( "cool_program", type=str, nargs="+", help="One or more cool program sourc...
bd5fddf2885b0a6e9761e3a8accb0f7cd01ef024
658,597
def filter_gists(tbl_object, username, skip, limit, search_text): """ for tweet in Tweet.select().where(Tweet.created_date < datetime.datetime(2011, 1, 1)): print(tweet.message, tweet.created_date) """ if search_text: query= tbl_object\ .select(tbl_object.name, ...
b1648929715033ef4cfccc9397151886191fe24f
658,598
def translate_task(contest: str, contest_no: int, task: str) -> str: """ Atcoderは第N回目コンテストのNの値によって、 URLに含まれるタスク名がアルファベット(a, b, c, d)表される場合と 数字(1, 2, 3, 4)で表される場合がある 数字だった場合は、タスク名(A, B, C, D)をアルファベットの小文字に変換、 アルファベットだった場合は小文字に変換する Parameters ---------- contest : str コンテスト名. AB...
8394c3d0a26d9d698efc9d5383e74c5dd6f109f6
658,599
import struct def read_bin_fragment(struct_def, fileh, offset=0, data=None, byte_padding=None): """It reads a chunk of a binary file. You have to provide the struct, a file object, the offset (where to start reading). Also you can provide an optional dict that will be populated with the extracted...
76f060f1c1a638c5131ae5ab376edd9fbe2905e5
658,600