content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _get_qualifiers(graph, source_node: int, target_node: int): """ Retrieve the qualifiers list (empty list if nonexistent) """ if "qualifiers" in graph.es[0].attributes(): qualifiers_list = graph.es.select(_source=source_node, _target=target_node)["qualifiers"] qualifiers_list = [x if x is not...
a64c2fa74048d27aa1f0e3acc2e985ef0b245389
643,671
def create_asset(arch): """Create an asset using Archivist Connection. Args: arch: archivist connection. Returns: newasset: a new asset created. """ attrs = { "arc_display_name": "display_name", # Asset's display name in the user interface "arc_description": "displ...
63bd76bd83de86590e7b33d84e65328eeaafafd2
643,672
def question_is_nonarray(questions, question_id): """ Return whether the question exists and has no subquestions. """ if question_id not in questions: return False question = questions[question_id] if question[1] is not None or question[2] is not None: return False return Tru...
15a602366a8c14bbeb272594b36c01ca48261075
643,673
import os def numfiles(subdr): """ Count number of files in a sub- dir""" # initialize variable numf = 0 for root, dirs, files in os.walk(subdr): numf += len(files) return numf print("Number of files in {}: {}".format(subdr, numf))
42548ff7f3fed2ddd76ebe06b6f11625a21543f3
643,674
def MK_FP(seg, off): """ Return value of expression: ((seg<<4) + off) """ return (seg << 4) + off
bbc7cf5051e66d0731a449d06a83d044f431b26e
643,675
import random def extract_text(para): """Returns a sufficiently-large random text from a tokenized paragraph, if such text exists. Otherwise, returns None.""" for _ in range(10): text = random.choice(para) if text and 60 < len(text) < 210: return text return None
2a8f736ce87a94ea9c02d8037e9ce44e21f86674
643,678
import subprocess def run_piped(pipe_from,pipe_to): """ Run processes in a pipe. Raises exception if something went wrong. Input: command from pipe, command to pipe Output: stdout,stderror tulip """ run_from = subprocess.Popen(pipe_from,stdout=subprocess.PIPE) run_to = subprocess.Popen...
74f7495e5c7dfeec974648f177e43b28104a1537
643,680
def get_missing_frameworks(descriptor, environment, yml_file): """ Returns a list of missing frameworks from a given environment based on the list of dependencies returned by a bundle descriptor. :param descriptor: The bundle for which missing dependencies will be searched. :param environment: The ...
93cf391cb08dc402bbfd22a43abcaa52862f5c65
643,681
import os def getAllGenrePaths(music_dir): """return a list of all music genres, e.g., 'audiobook', and their complete path""" dirs = os.listdir(music_dir) allAudioGenrePaths = [] allAudioGenres = [] for cur_dir in dirs: if not cur_dir.startswith('.') and not cur_dir.endswith('pickle') : ...
2a2f386b848e8a8152a4db32b66a87adfa5ee604
643,682
import os def extension_from_base(base): """ Returns the extension of a file from the given file base. """ extension = '' try: _, extension = os.path.splitext(base) except: extension = 'An error occured while getting the file base' return extension
ce9ba64f61cb3de13f8c34fe4bb51e63393bebfd
643,683
def inject_none_for_missing_fields(cls, values): """Given a BaseModel class and a dictionary to populate its fields, inject None for missing fields.""" for field_name, field_info in cls.__fields__.items(): if field_name not in values and field_info.alias not in values: values[field_name] = N...
809895e9df296d8765f9c5df0640b9c8df77c136
643,684
def is_a_valid_username(string: str) -> bool: """ Verifica se a string recebida está na margem válida para um nome. :param string: nome :return: bool """ return True if 2 <= len(string) <= 15 else False
17f0e349153abf471a43a44adf7ab9b0bb657319
643,685
def entries_4(): """Input data with 4 entries""" return [ {"id": 5, "name": "Asparagus", "colour": "green", "count": 9, "herb": False}, {"id": 20, "name": "Kale", "colour": "green", "count": 4, "herb": False}, {"id": 44, "name": "Sweet Potato", "colour": "orange", "count": 12, "herb": Fa...
b59e59ddf5916c7dd50bbb279efe910617e465e8
643,686
import pickle import os def _pickle_load(model_type, file_name): """ load pickled data model file function :param model_type: :param file_name: :return: """ return pickle.load( open(os.path.abspath(os.path.join(os.path.dirname(__file__), model_type, file_name)), 'rb') )
55951c2bd792205cca6150283e42550c383f7a54
643,687
import os def genome_root(data_dir): """Returns the path of test genome.""" return os.path.join(data_dir, 'genomes')
66904f827da0fa23cf7232f644c32fdcad286f75
643,688
def combine_hash(lhash: int, rhash: int) -> int: """ As boost::hash_combine """ lhash ^= rhash + 0x9e3779b9 + (lhash << 6) + (rhash >> 2) return lhash
e300b9d1b97cebe202f1a58d2e1c24efa3ace424
643,689
def efficiency_cost(s_coeffs, d_coeffs, duration): """ Cost of slow average speed trajectories.""" return 0
eae375b629cea9d7b49dee0378223220a87eb2e4
643,690
def _get_filter_name(project_filter_dict, file_name): """ Helper function to get a correct project filter """ if file_name.endswith('wscript') or file_name.endswith('.waf_files'): return '_WAF_' # Special case for wscript files if not file_name in project_filter_dict: return 'FILE_NOT_FOUND...
fb00919bb765cb78c7ca1e0fdd149056e67cc6e6
643,691
def find_constant_features(data): """ Get a list of the constant features in a dataframe. """ const_features = [] for column in list(data.columns): if data[column].unique().size < 2: const_features.append(column) return const_features
58fb8f98e6da9026b26437fb93230258312714d6
643,692
def prepare_constraint(constraint: str, formalization: int = 1): """ Switches a constraint from one formalization to another. Args: constraint (str): The constraint to be modified. formalization (int, optional): The model formalization. Defaults to 1. """ common_names = ["basicAllo...
b8705672e6c77ada07c5f2469ba895d8f2ac9794
643,693
def get_most_freq_genotype(maf, no_none=False): """ Get highest frequent genotype. :param maf: :param bool no_none: do not return none :return: """ freq = maf['maf'] allele = maf['maf_allele'] if freq and allele: freq = float(freq) if allele == 'ref': ref...
de43ec9941cbf00dde3aed1ea7056fc06b776bc2
643,694
def remove_unspecified_items(attrs): """Remove the items that don't have any values.""" for key, value in list(attrs.items()): if value is None: del attrs[key] return attrs
10a495d8189cde6ba345dfc4bcb5bcb483769ea0
643,695
import tempfile def tmpfile(prefix, direc): """Returns the path to a newly created temporary file.""" return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
3c9a1f88804dc9626b6c8f03846eb6323cff848b
643,696
def accept_peak(time, data, event_inx, index, min_inx, threshold): """ Accept each detected peak/trough and return its index (or time) and its data value. Args: freqs (array): frequencies of the power spectrum data (array): the power spectrum event_inx: index of the current peak/tro...
f8308a5f32955a3ca1a86631fea9b1276851d362
643,697
def group_degree_centrality(G, S): """Compute the group degree centrality for a group of nodes. Group degree centrality of a group of nodes $S$ is the fraction of non-group members connected to group members. Parameters ---------- G : graph A NetworkX graph. S : list or set ...
6a63218d39790d6c8ddb76a39bc585df73822211
643,698
import random def mutate_trace(solver, t, mutation_chance=None): """ Mutates a single value in the trace to a random value :param solver: Solver used to start the optimisation :param t: Trace object :param mutation_chance: Mutation chance :return: Trace o...
c0636c89b12c003d51cc6f1566d071cf4264aeca
643,699
from typing import Iterable from pathlib import Path from typing import Optional def resolve_simple_project_path(project_folders: Iterable[Path], file_path: Path) -> Optional[Path]: """ The inverse of `simple_project_path()`. """ parts = file_path.parts folder_name = parts[0] for folder in pro...
4441538a3da4c81b0b7a18b1bf863863f659a8fd
643,700
import bisect def clip_around_detections(detections, time_interval): """Return the narrowest sublist of detections (a list of Detections) containing time_interval. """ times = [d.timestamp for d in detections] lo = bisect.bisect(times, time_interval[0]) - 1 hi = bisect.bisect_left(times, time...
bd20c5caa3f1c9737980febb584d0f131c185c33
643,701
def areAxesIdentical(ax1, ax2, is_subset=False, check_id=True): """ Takes 2 axis (coord) objects returning True if they are essentially the same and False if not. If is_subset == True then return True if ax1 is same as ax2 except that it is only defined on a subset of regularly spaced values wit...
b0c4daadd74633d7fa1327c58f2ffb090471cc3c
643,702
def split_num(num, splits): """Returns the number 'num' divided into a list of numbers of size 'splits' """ splits = [int(num/splits)+1]*(num%splits) + [int(num/splits)]*(splits-num%splits) assert sum(splits) == num return splits
131633da494d27b2d967ca5f40ecd41d28f52db9
643,704
def get_rank_hit_metrics(y_id, pred_ids): """ :type y_id: int :type pred_ids:list, k possible ids order by score desc """ ranking = pred_ids.index(y_id) + 1 _matrics = { 'MRR': 1.0 / ranking, 'MR': float(ranking), 'HITS@1': 1.0 if ranking <= 1 else 0.0, 'HITS@3': ...
1fbeeef08837e6a77fc664d789d76b5f1608d389
643,705
import requests def pr_info(branch: str): """Get PR title and link from github api""" _, _, pr_nr = branch.partition("-") try: response = requests.get( f"https://api.github.com/repos/glotaran/pyglotaran/pulls/{pr_nr}", ).json() return response["title"], response["html_u...
053074b695f323b312755a8d34a1f763c29e1943
643,706
def token_depth(token): """ determines the "depth" of a regex prefix tree. Used for guaranteeing unique node labels. """ if token[0] == 'singleton': return 1 else: depth = 0 for operand in token[1][1:]: if token_depth(operand) > depth: dep...
26e000633e76160afb1c01c427bbe4b16fa8c06b
643,707
import os import re def get_version(): """Get version information from __init__.py file""" pwd = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(pwd, 'multiword_tokenization/__init__.py') re_version = re.compile(r"__version__ = '([0-9a-z\.]+)'") with open(file_path, 'r') as fp...
189cf1cb30a6688c09701ad7bda89364173c1884
643,708
def is_string_arg(parameter): """Whether the parameter's type is string or bytes.""" return parameter["grpc_type"] in ["string", "bytes"]
d0f7a3016bdf20edae9dc8bbcf2736da38b259ce
643,710
def _is_leap(y): """True if y is a leap year.""" return (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0))
d5c93930280419b07094c0256b5ac90759b453ff
643,712
import random def random_case(message: str) -> str: """Convert the string to RanDoM CasE. Parameters ---------- message : str The string to be converted Returns ------- str The string in RandOm caSe """ characters = [] for character in message: conver...
2ac0f0b5cf0dad052754cfe319994e64d15bf858
643,714
def filter_attr(attr, coll): """ Acts like ifilter(attrgetter(attr), coll). >>> list(filter_attr('imag', [1+0j, 1+1j, 42+0j])) [(1+1j)] """ return (elem for elem in coll if getattr(elem, attr))
41b71cc01e7b03194251bac2f0f23a710db2dce7
643,715
def center_of_effect(cloud, duration): """ The center of effect condenses musical information in the spiral array by a single point. Parameters ---------- cloud : 3D array Array containing the coordinates in the spiral array of the notes in the cloud. duration : array ...
bd3037a3c9521b02db2bd9313e476daa56b426b7
643,716
def limpiar_1(texto:str): """ Se hace una primera limpieza de los datos. Eliminando saltos de línea, y espacios innecesarios. """ texto = texto.replace('\n', '') return texto
4c58f03db2a5b7e8d60623aa56c75db1e7dede2f
643,717
import argparse import sys import os def parse_cmdline_args(arg_parser: argparse.ArgumentParser) -> dict: """ parse_cmdline_args(arg_parser : argparse.ArgumentParser) -> dict: Parses command line arguments provided by the user using the given argparse.ArgumentParser object Parameters: ...
12d70867e2ac44ee851eab6e719ecdd96fe5a161
643,718
def hex_to_rgb(hexstring): """ Converts a hexadecimal string to RGB tuple Parameters ---------- hexstring : str Hexadecimal string such as '#FFFFFF' Returns ------- tuple RGB tuple such as (256,256,256) """ #From http://stackoverflow.com/a/214657 hexstri...
598e33aa0d14fee0aaf5ba84f2b6fd4c253d991a
643,719
import math def sinFunc(x): """f(x) = sin(x)""" return math.sin(x)
7e4a04e98b33528248ca8ca9cb9a7987ac863e34
643,720
def _mut_replace_terminal_is_applied(original, mutated): """ Checks if mutation was caused by `gama.ea.mutation.mut_replace_terminal`. :param original: the pre-mutation individual :param mutated: the post-mutation individual :return: (bool, str). If mutation was caused by function, True. False otherwi...
1353c0f98ea7295017522aef05a7b657111d985c
643,721
def is_valid_minimizer(object): """ Checks if the minimzer object has the following attributes/methods: * minimize """ has_minimize = hasattr(object, "minimize") return has_minimize
b822b9ba41f68a877c345ac676b7b0186cab49eb
643,722
from typing import Callable from typing import Union from typing import List import re def create_pattern(pattern: str) -> Callable[[str], Union[List[str], None]]: """ Creates Pattern based on flags :param pattern: String with regex pattern :return: Pattern matcher """ def match(string_to_spl...
5b244e4c46769cb07a7d848a6f09b881168cc69f
643,723
def hb_energy_times_to_power(es, ee, ts, te): """Compute power from start and end energy and times. Return: power values """ return (ee - es) / ((te - ts) / 1000.0)
43dc0807ed8632ccaa2f6983b9947e30354533ee
643,724
def C2F(C): """Convert Celcius to Fahrenheit""" return 1.8 * C + 32
e09f7415a2c509d8cb2d07d4c0d8e667f94e3c7d
643,725
def isPrime(x: int) -> bool: """ returns if a number is prime or not """ if x < 2: return False elif x == 2: return True for n in range(2, x): if x % n ==0: return False return True
dca2337578ed2a527ea533f9d21200d3660f802b
643,726
def ampmtonumber(time: str) -> tuple: """ Convert time in AM/PM format to hh:mm. """ hour, minute, period = time.split(':') if period == 'AM': if hour == '12': hour = 0 else: hour = int(hour) else: if hour == '12': hour = 12 els...
7482f021a8357e565484de948d20d65d5a8ab371
643,727
def PyUnicode_Splitlines(space, w_str, keepend): """Split a Unicode string at line breaks, returning a list of Unicode strings. CRLF is considered to be one line break. If keepend is 0, the Line break characters are not included in the resulting strings.""" return space.call_method(w_str, "splitli...
f29eca6a4d31bf18e9a409a686ba0977e88d3636
643,729
def _GetDataFilesForTestSuite(test_suite_basename): """Returns a list of data files/dirs needed by the test suite. Args: test_suite_basename: The test suite basename for which to return file paths. Returns: A list of test file and directory paths. """ test_files = [] if test_suite_basename in ['Ch...
0f4ff42ef0ed050cf6a48ea35ac77fda8b249f75
643,730
def estimarPGC(h, a, n, sexo): """Estimación del PGC utilizando la fórmula del item M. Args: h (float): Altura en centímetros a (float): Circunferencia abdominal en centímetros n (float): Circunferencia del cuello en centímetros sexo (string): 'M': Masculino ; 'F': Femenino ...
1bbba867b27e55d65726877e7b59c21e5ebd108d
643,731
def loop(self, n=None, duracion=None): """ Returns a clip that plays the current clip in an infinite loop. Ideal for clips coming from gifs. Parameters ------------ n Number of times the clip should be played. If `None` the the clip will loop indefinitely (i.e. with no set durac...
e3fafd8046b291563b6c77143148726c8a2b7b03
643,732
def default_dataset_1(data_env_1): """Fixture with pre-existing dataset in first node.""" return data_env_1.datasets[0]
265f6cea91ae1fd7dca008dfc057d59d6d450a3d
643,733
def normalized_in_degree(in_degree_dict): """ dict -> dict Takes a dictionary of nodes with their indegree value, and returns a normalized dictionary whose values sum up to 1. """ normalized = {} for key in in_degree_dict: normalized[key] = float(in_degree_dict[key]) / len(in_degree_dic...
30462b2f730239ae1f9ae3cba29961a597053449
643,734
import requests from bs4 import BeautifulSoup def _root(url): """Get root BeautifulSoup element from ``url``.""" page = requests.get(url) return BeautifulSoup(page.content, "html.parser")
25e2d99c61bee51c1f93cf7ce4ef7aee79c5ff0c
643,735
import glob import os def get_dist_info(wheel_dir: str) -> str: """"Returns the relative path to the dist-info directory if it exists. Args: wheel_dir: The root of the extracted wheel directory. Returns: Relative path to the dist-info directory if it exists, else, None. """ dist...
716bc5888f93ca21307c63ea280d14e232582ff8
643,736
import hashlib import re def tag_hash(string, str_enc="utf-8", hash_len=7): """ Generates short English tags for MTL from any kind of string. """ if len(string) < 1: return '' d = hashlib.sha1(string.encode(str_enc)).digest() s = '' n_chars = 26 + 10 for i in range(0, hash_len): x ...
b625c76a3eaa8ba46fbf8c5ed5e436ae4ba8d316
643,737
def machine_precision(): """ calculates the machine precision, 2*eps""" x = 1.0 eps = 1.0 while (not x + eps == x): eps = eps/2.0 return 2.0*eps
7845372e7d42df9882b82c7882f0de6961dc4de3
643,738
def generate_M(data_set): """Generate the M matrix from data_set, in order to calculate the MSE.""" try: data_set_pure = None # Task: from the data_set, you should join all numpy row vectors into a matrix data_set_pure (pure means we do not save the actual value here) return data_se...
4f993a70c5119794bd85d6c805de27cb34dd7d55
643,739
def countMotHitCmp(motDistr1, motDistr2): """Helper function for comparing two motif distributions. Compares based on number of central hits.""" return motDistr2.getNcentralHits() - motDistr1.getNcentralHits()
81a7cfc5268eb6cf124e555fa1bc1fbeaf4c2d96
643,741
def _is_list_like(x): """Helper which returns `True` if input is `list`-like.""" return isinstance(x, (tuple, list))
1af7652bac0189bd1629c4d8064b63c96c6964b2
643,742
import re import string def replace_numbers(text): """Transform every number of the string into space.""" return re.sub('[%s]' % string.digits, ' ', text)
70272349a0ebfca3a1d52e02f98674dbad5d3f69
643,743
import argparse def buildArgs(): """ Helper function to build our args :return: Args ready to be parsed! :rtype: argparser """ usage = "CLI for managing and maintaining tokens and key/certs." argparser = argparse.ArgumentParser(usage=usage) argparser.add_argument( "-add", ...
a6f0b4b09b7dfb6a816a9d4e17927583305f9da8
643,744
def status(): """Simple API response to see if API is alive.""" return "OK"
82931819c18fbf8380eaaff2cfaf59362facf839
643,745
def convert(color): """Get (0-1, 0-1, 0-1) color code and converts it to (0-255, 0-255, 0-255). Parameters ---------- color : tuple RGB code in format (0-1, 0-1, 0-1) Returns ------- list a list representing RBG color code in format (0-255, 0-255, 0-255) """ return ...
4e57b4c575ad9a8c6fe9cda077d07dc67e41df3b
643,746
def offset_bed(df, genome_offset): """Returns bed positions that have been corrected for the length of the sequence of trailing 'N' characters""" for chrom in genome_offset: per_chrom = df[df['chrom'] == chrom] df.ix[per_chrom.index, 'end'] += genome_offset[chrom] df.ix[per_chrom.in...
895de1ca74e5a9ba0efeb6f696693dcedc0c413d
643,747
import requests def random_doi(): """ Returns a random DOI. """ r = requests.get("https://api.crossref.org/works?sample=1") return r.json()["message"]["items"][0]["DOI"]
b27700633a4f12d5aeaed9c1c5d2a6c65ca4af20
643,748
def set_accuracy_95(num: float) -> float: """Reduce floating point accuracy to 9.5 (xxxx.xxxxx). Used by Hedron and Dihedron classes writing PIC and SCAD files. :param float num: input number :returns: float with specified accuracy """ # return round(num, 5) # much slower return float(f"{n...
2f4c942b66972cfcf47121a9d7d674a854161df5
643,749
import gzip import os def _get_vote_page_html(): """ テスト用の投票ページのHTMLを取得する。 :return: 投票ページのHTML :rtype: str """ # テスト用の投票ページのHTMLを返却する with gzip.open(os.path.join(os.path.dirname(__file__), 'vote_page.html.gz'), 'rb') as f: return f.read()
877c78597cf8b935463a5e594bb86e861e0bc80f
643,750
def gold_client(application_gold, api_client): """ returns api client for silver application """ return api_client(application_gold)
5766f7d96bfe65351ca9fee6dea3e00e8cead0be
643,751
def ClusterKey(cluster, key_type): """Return a cluster-generated public encryption key if there is one. Args: cluster: Cluster to check for an encryption key. key_type: Dataproc clusters publishes both RSA and ECIES public keys. Returns: The public key for the cluster if there is one, otherwise None...
073ce9fb790b8fcdaabded2c8f9a4ec649f10850
643,752
import codecs def serialize_file(path): """Return a serialised blob of the contents of a given file path. Parameters ---------- path : str Filename. Returns ------- serial_data """ with open(path, "rb") as f: serial_data = codecs.encode(f.read(), "base64").decode...
8972974c462ca78e37ce27c55e19d8570dfa3d37
643,753
import itertools def _inference_tip_cached(func, instance, args, kwargs, _cache={}): """Cache decorator used for inference tips""" node = args[0] try: return iter(_cache[func, node]) except KeyError: result = func(*args, **kwargs) # Need to keep an iterator around origi...
c6dc7804c02e1ae69bab47f330538158ae829502
643,754
def divide_by_2( any_integer ): """ This function will return the integer inputted divided by 2. """ return any_integer / 2
274b2798da3ae2e989a2a48626340bfad5610221
643,755
def latex(df): """Converte DataFrame em tabela para LaTeX. Parameters ---------- df : Pandas DataFrame DataFrame de início. Returns ------- type None Comando print para apresentar tabela em LaTeX que pode ser copiada. """ return print(df.to_latex())
0b0c0353503bd2418dc9d4c9ac477b0cb32fd684
643,756
def is_alone(author): """Checks if the user is alone in a voice channel""" if not author.guild.me.voice or not author.voice: return False num_voice = sum(1 for m in author.voice.channel.members if not ( m.voice.deaf or m.bot or m.voice.self_deaf)) if num_voice == 1 and author.guild.me.vo...
25c61893b070624f98068d38d5127b617b43f348
643,757
def _GetProcJiffies(timer_list): """Parse '/proc/timer_list' output and returns the first jiffies attribute. Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be essentially the same. Return the first one.""" if isinstance(timer_list, str): timer_list = timer_list.splitlines() fo...
63ece49d4950a1654afcbe704cf19fdfe911ed2e
643,758
from typing import Counter def intersects(count1, count2): """slide count2 from left to right until it aligns best with count1""" min1, max1 = min(count1.keys()), max(count1.keys()) min2, max2 = min(count2.keys()), max(count2.keys()) for offset in range(min1 - max2, max1 - min2 + 1): off_count...
3627e4d7583f843f7bde19fef0ded079944416a6
643,759
def figure_asthetics(ax): """Change the asthetics of the given figure (operators in place). Parameters ---------- ax : matplotlib ax object """ ax.yaxis.grid() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.xaxi...
b5a2c1b5a1274ba738117564292237e1abf42d76
643,760
def pairs_quality(cand_rec_id_pair_list, true_match_set): """Pairs quality measures the efficiency of a blocking technique. Pairs quality is calculated as the number of true matches included in the candidate record pairs divided by the number of candidate record pairs generated by blocking. Para...
d40f088e3ad2ae68ba32274f87ad1f188ccfbc67
643,761
def is_power_of_two(n): """Check whether `n` is an exponent of two >>> is_power_of_two(0) False >>> is_power_of_two(1) True >>> is_power_of_two(2) True >>> is_power_of_two(3) False >>> if_power_of_two(16) True """ return n != 0 and ((n & (n - 1)) == 0)
b5fdbabb959f224018b57c2244bbfe93780ece1c
643,762
import re def is_markdown_file(filename): """ Judge if the filename is a markdown filename i: filename o: filename without '.md' or '.markdown' """ match = re.search('.md$|.markdown$', filename) if not match: return False elif len(match.group()) is len('.md'): return filen...
ad15547e01e39666706f72c22229ef4305cbb450
643,763
def WaitForOpMaybe(operations_client, op, asyncronous=False, message=None): """Waits for an operation if asyncronous flag is on. Args: operations_client: api_lib.ml_engine.operations.OperationsClient, the client via which to poll op: Cloud ML Engine operation, the operation to poll asyncronous: b...
98221aaa1115c49c256824df072ef6f11b40e183
643,764
def is_func_bound(method, instance=None): """ check function is bound in class instance. >>> is_func_bound(lambda :None) False >>> is_func_bound(dict().get) True >>> x = dict(a=1) >>> is_func_bound(x.get, x) True >>> y = dict(a=1) >>> is_func_bound(x.get, y) False :param...
20f3fb11b4f90cfab526a0221e490598e7c7834c
643,765
import warnings def build(app, path): """Build and return documents without known warnings""" with warnings.catch_warnings(): # Ignore warnings emitted by docutils internals. warnings.filterwarnings( "ignore", "'U' mode is deprecated", DeprecationWarning) ...
66a9e00b3bd5297ce825ea8479f511001190a5e3
643,766
def toBin3(v): """Return a string (little-endian) from a numeric value.""" return '%s%s%s' % (chr(v & 255), chr((v >> 8) & 255), chr((v >> 16) & 255))
93f2ca4c39419ece5ea41dd07608cce8287c1366
643,767
from datetime import datetime import pytz def ts_2_dt_utc(ts_2_epoch): """Feb 2, 2017 UTC as timezone-aware datetime.""" return datetime.fromtimestamp(ts_2_epoch / 1000, tz=pytz.utc)
5c1e3ffd16640fc796027608bc3d72a92835b67c
643,768
def is_present(value: str) -> str: """ Ensure that a string is present :param value: the string to validate :return: a valid string """ if value == "": raise ValueError("must be present") return value
9ca041c7e344e56a7572f82b68e5c6e0cfa0af82
643,769
def clean_email_column(df): """Cleans email column so there is only 1 valid email per row. 1. Makes the contents of the "email" column lowercase. 2. If rows in the "email" column contain a comma it splits it at the first column and moves everything after the first column to the "second_...
6a440f674d86cb7816300038ccd479ed7250e54c
643,771
import inspect def steal_docs(target, ignore_missing=False, name=None): """ decorator to steal __doc__ off of a target class or function Specifically when the target is a class, it will look for a member matching the functors names from target, and clones those docs to that functor; otherwise, it...
9aeadfcaef38f9f3d140bf096693879f2cef40bf
643,772
def no_acl(*args, **kwargs): """ Stub function that always returns true This function is set by settings.py by the variable ACL_MODULE When you'd like to integrate a custom RBAC module, the ACL_MODULE should be repointed from this function to the function that will perform the ACL checks. """ ...
978bbecb71aa0e7f65f001a3dafc1da706c2f88e
643,773
from pathlib import Path from typing import Dict from typing import List from typing import Tuple import json from typing import Any def load_annotations(path: Path) -> Dict[str, List[List[Tuple[int, int]]]]: """Load in the annotations made by VGG.""" with open(path, "r") as f: annotations = json.load...
1b69d437a7a78e71c12b5caae7bf5db3e1e409d6
643,774
import click def param_options(f): """Options to supply parameter files for training and parameter search.""" f = click.option('--params_file', type=click.Path(exists=True), help='JSON file from which to load train parameters.')(f) return f
1a20c0142519f94d17ebdc3d9661cd877b91dcf0
643,775
from typing import Iterable def iterable(val): """입력값 val 가 iterable이면 True, 아니면 False""" return isinstance(val, Iterable)
c99476a69d6a7d3152a0b5318a68a83a59944f85
643,776
import argparse def parse_args(): """ Simple argument parser """ parser = argparse.ArgumentParser( description='basic tests for tsheets production api service') parser.add_argument('-a', '--auth', type=str, help='auth token to access the production api service') r = parser.parse_ar...
b1252e30786b4b0df058928376021f5f80634d7d
643,777
import re def rmURLs(text): """membuang url :return: clean string from url :rtype: string """ return re.sub(r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))'...
37312a66d21e7841caa085eab71ad9a77ddbdd34
643,778
import argparse def parse_args(args): """ Parse command line arguments using the argument parser. """ parser = argparse.ArgumentParser() parser.add_argument("--dataset", type=str, default="LJSPeech") parser.add_argument("--compseq", type=str, default="LJSpeech_syllables_left_awb_collated_u...
bdbbf610656269d7f00d0410c5076c5892974a6d
643,779
import re def synch_post_urls (post): """Извлекает url из поста""" post_urls = post.xpath('.//div[@class="body" or @class="body media-body"]') # Меняем <br> на символы новой строки: for br in post.xpath("*//br"): br.tail = "\n" + br.tail if br.tail else "\n" post_urls = post_urls[0].text_c...
9a35e862da7a0b31f85f6631affec3ff1ecb48ca
643,782