content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import random def valid_bytes(): """ Fixture that yields valid collections of bytes to write to a transport. """ return os.urandom(random.randint(1, 1024))
51a74a497595ccc701bbd9f9fc000596c84adb86
625,567
def dropIdColumn(train, test): """Detaches Id column from both datasets Parameters: train (pd.Dataset): Training set test (pd.Dataset): Testing set Returns: train (pd.Dataset): Training set without Id test (pd.Dataset): Testing set without Id trainId (pd.Dataset) : Training Id fields ...
7566c130dc3edc66601fb7ade185026de55dea3a
625,568
def rbg_to_hex(c): """Convert an rgb-formatted color to hex, ignoring alpha values.""" return f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}"
4b8061dee948e0bbbfe4e58c42b37f4b66ab29cf
625,569
def DetectEncoding(data, default_encoding='UTF-8'): """Detects the encoding used by |data| from the Byte-Order-Mark if present. Args: data: string whose encoding needs to be detected default_encoding: encoding returned if no BOM is found. Returns: The encoding determined from the BOM if present or |...
43670fd234453a703dd18521b6dc655507448664
625,570
def get_valid_file(possible_files): """This function checks that the file is from a list of possible files.""" filename = None while filename not in possible_files: filename = str(input("Please enter the name of one of the files from the list above: ")) if filename in possible_files: ...
51acc92e6405e4d2d4de1e0756a4b3efa7b90960
625,571
def append_pkcs7_padding(s): """ Function to return s padded to a multiple of 16-bytes by PKCS7 padding. :param s: string to apply padding to :return: padded string """ # numpads = 16 - (len(s) % 16) return s + numpads * chr(numpads)
c2b9dd0a473ea599b963cdab1bc612a8d8b63bb9
625,572
import re def atomwise_tokenizer(smi, exclusive_tokens = None): """ Tokenize a SMILES molecule at atom-level: (1) 'Br' and 'Cl' are two-character tokens (2) Symbols with bracket are considered as tokens exclusive_tokens: A list of specifical symbols with bracket you want to keep. e.g., ['...
245aa4b98329f55d2acffc562b922846f1d9f785
625,573
def square(x): """Calcula o quadrado do número informado. Args: x ([int], [float]): valor dado pelo usuário. Returns: [[int], [float]]: quadrado do numero informado pelo usuário. # Testes >>> square(5) 25 >>> square(4.5) 20.25 """ return x ** 2
2dbfefbc9fad5a65fe255455937e80989bc7ef33
625,574
import time def _LazyFile_reopen(method): """Decorator to perform the housekeeping of opening/closing of fds""" def wrapper(self, *args, **kwargs): if self._realFd is not None: # Object is already open # Mark it as being used self._timestamp = time.time() ...
708dd5a1645cd42e04e50f8f11811d97be304fcb
625,575
def reverse_loop(value): """Reverse string using a loop.""" result = "" for char in value: result = char + result return result
609447b4b0c7dd449f5cbeb2d9e7e0bbca675574
625,576
def compute_force_drawinglocation(form, force): """Compute an appropriate location for the force diagram. Parameters ---------- form: :class:`compas_ags.rhino.FormObject` force: :class:`compas_ags.rhino.ForceObject` Returns ------- :class:`compas.geometry.Point` """ point = for...
2caa3c6ae119cb5bf43a6d4799d51cd8120f4ff7
625,577
from PIL import Image def resize_img_square(pil_img, edge_size, background_color=(0, 0, 0)): """ 一辺がedge_sizeの正方形にリサイズする """ longer_edge = max(pil_img.size) shorter_edge = min(pil_img.size) if longer_edge == shorter_edge: return pil_img.resize((edge_size, edge_size)) else: ...
db6bbe9654675fe72cb5742fc090b28d5d3f733b
625,579
def personal_setting(head, body): """ personal user setting function :param head: title in the post :param body: content in the post return head, body """ def code_line(text): """ preprocess the code blocks :param text: content in the post retu...
9ec8b6fb0aadb17724fb8d80c1b27c7859239a39
625,580
from typing import List from typing import Tuple from typing import Optional from functools import reduce def print_prefixed_lines(lines: List[Tuple[str, Optional[str]]]) -> str: """Print lines specified like this: ["prefix", "string"]""" existing_lines = [line for line in lines if line[1] is not None] pa...
7afdfafd4d48e38c7341a229cc7abcfe6b50063b
625,581
def downsample_image(image, n): """Downsample 2D input image n x n. Parameters ---------- image : ndarray 2D input image. n : int Downsampling factor, applied to both image dimensions. Returns ------- result : ndarray Resampled image with shape = image.shape//n. ...
c85ccde52f0502cf8b097111865fc04b5c735448
625,582
def text_to_int(text): """ Converts text into an integer for use in encryption. input: text - a plaintext message output: integer - an integer encoding text """ integer = 0 for char in text: if integer > 0: integer = integer*256 integer = integer + ord(char) r...
f22d2ba29c36c6a803294a3c284ef8a9cc068ea3
625,583
from unittest.mock import call def line_count(fname): """Count number of lines in specified file""" return int(call(['wc', '-l', fname]).strip().split()[0])
bcb2a12c5b6eca0e927e44fff01c86bdd06e786c
625,585
def process_sequences(sequences, end_token=0, pad_val=0, is_shorten=True, remain_end_id=False): """Set all tokens(ids) after END token to the padding value, and then shorten (option) it to the maximum sequence length in this batch. Args: sequences: `numpy array` or `list of list` with token IDs. ...
1072b2e295b0a9df3b9704f627cd528927071f91
625,586
def underscore_to_dash(name: str) -> str: """Convert underscore to dash and drop final dash if present.""" converted = name.replace('_', '-') return converted if converted[-1] != '-' else converted[:-1]
de84984deb58a3f6e815f43bea8fcee667d2bc47
625,587
import requests import json def update_network(platform, key, client, net_id, new_name): """ Updates the name of a network via the API. :param platform: URL of the RiskSense Platform to be queried. :type platform: str :param key: API Key. :type key: str :param c...
a84a8dc10ff48dba6a9083bfddb4eccf3af44457
625,588
import torch def create_the_slices(image, label, slices: int = 5, dim: int = 0): """ Splitting raw input image into slices Args: image (torch.tensor): Input image label (torch.tensor): Target label slices (int, optional): Split size. Defaults to 5. dim (int, optional): Dimensi...
17257aef2dd7eded4943a3e3c462d9ba2c65dad4
625,589
import os import pickle def load_model(save_folder, filename): """ Loads and returns a classifier at the given folder with the given name """ _path = os.path.join(save_folder, filename) if not os.path.isfile(_path): return None with open(_path, 'rb') as handle: print(handle) ...
e41ceaca6c78edb964bd72dd660d3f93b70e2208
625,590
def get_page_and_limits(params): """default of 10 items per page""" page = 1 limit = 10 if 'page' in params: page = params['page'] if 'limit' in params: limit = params['limit'] start_index = (page - 1) * limit end_index = (page * limit) # because python list slice ends at th...
750c9c979a8e64ffee43613b85d62de0cd5f2858
625,591
import copy def modifiedSequence(sequence, modifications, aminoacid, ion_type): """modifies string of the sequence Modifies the string of a given sequence that it contains the modifications of a given aminoacid in brackets Parameters ---------- sequence : str sequence of the peptide ...
001af058a3da104c01c807acf22dbe28609e1e03
625,592
import optparse import sys def _parse_args(): """ Parse the command line for options """ usage = """AlignmentFilter.py -x [bowtie2index] -f [FqFile] -s <390> -F <20> -T [TargetPoolFile] -o <output> """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = o...
1c763b1b096c1954130d75390ce60ea85961d090
625,593
def make_python_name(name): """ Convert Transmission RPC name to python compatible name. """ return name.replace('-', '_')
e5a97eab62507f21b70da8367240b773c4107ea3
625,594
def from_tensor(tensor_item): """ Transform from tensor to a single numerical value. :param tensor_item: tensor with a single value :return: a single numerical value extracted from the tensor """ value = tensor_item.item() if value == -1: return None return value
9981215be4eb6d40838a50d147af2368ca854cd8
625,595
from typing import List import re def excluded_pattern(root: str, excludes: List[str]) -> bool: """ Check if the given path or filename matches any of the provided exclude patterns. """ for pattern in excludes: if re.search(pattern, root): return True return False
c511ac66426ace4432ba74f660b3dcb16ee4335e
625,596
def _endswith(value): """ Maps to `string.endswith`. """ return lambda v: v.endswith(value)
1cf3fda2e87f0dfa507d18c88552e6d3d463b688
625,598
import os def netcdf_ext(basepath): """ Give filename with consistent netcdf output file extention Args: basepath: path with or without netcdf extension Returns: str: the basepath with the netcdf extension """ if os.path.splitext(basepath)[-1] == ".nc": return os.path....
760d85d822944ab895668bc234bf8c1759acb3eb
625,599
def lstm_mask_layer(proj, mask): """ Removes any spurious output from the LSTM that's not covered by a label or doesn't correspond to any real input. :param proj: Output of the LSTM layer :param mask: 1 if the position is valid, 0 otherwise :return: The masked values """ return proj * m...
4b8d50f9362a9b870ac2f55365747cfc5f89d675
625,600
def user_info_query(user_id: str) -> dict: """ Build User information query. :param user_id: User id :return: Query """ return { "operationName": "ProfileGet", "query": """query ProfileGet($user_id: ID!) { userprofile { get(user_id: $user_id) { ...
da79d9f2f81c7583115f27d6ca86e98008969372
625,602
def add_delete_hook(): """ catch all """ return {"error": "API Request not Valid!"}
990233e7c995ab25ee97b16b855f8b35bbba972e
625,604
import string import random def generateRandomString(length): """Generate a random string of a specified length. To be used in rpc information. Args: length (int): Length of string to be generated. Returns: String: String that was generated. """ choice = string.ascii_...
856eacce58521a30806ebc752e30622457b68a43
625,605
def convert_response(response): """ json -> dict """ try: return response.json() except: return None
8a77e7184ca512a9a4dfbb5aada8baddcfe976d3
625,606
def lemmatize_docsents(doc_sents, stem): """ lemmatize the document sentences :param doc_sents: :param stem: :return: """ doc_sents_lemma = [] for idx, docl in enumerate(doc_sents): doc_sent = doc_sents[idx] docsent_lemma = [] for senttoks in doc_sent: ...
9c093267b8437546f5831c402b76d38d5fb75dcc
625,607
import torch def batched_block_diag(m1, m2): """ Args: m1, m2: 3-d tensors """ bs, l1, _ = m1.size() _bs, l2, _ = m2.size() assert bs == _bs res = torch.zeros([bs, l1 + l2, l1 + l2]).to(m1.device) res[:, :l1, :l1] = m1 res[:, l1:, l1:] = m2 return res
fa2aea9e4f47fe20562da978c4d5c44ce8be96b2
625,608
import argparse def parse_args(): """Parse arguments from command line call""" parser = argparse.ArgumentParser( description=__doc__, add_help=False, # Use individual setting below instead formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "...
bf62bc50f758583660d49c3fb62d83558b4175f9
625,609
import math def Bjorklund(k, n): """Using Bjorklund's algorithm as described in [The Distance Geometry of Music](https://arxiv.org/abs/0705.4085v1), return a list of 1's and 0's representing a "Euclidean Rhythm" of k beats and n-k rests.""" if not type(k) == type(n) == int: raise TypeError("Arguments ...
f6f09097c67dae669210d7ed238ae1c4aef02a8b
625,610
def knot2ms(ws_knot): """ Convert unit of wind speed from knots to meter per seconds. Examples --------- >>> ws_ms = kkpy.util.knot2ms(ws_knot) Parameters ---------- ws_knot : array_like Array containing wind speed in **knots**. Returns --------- ws...
7333b5bfdb78ee6fee0adb3cc79c64cd5c3caffd
625,611
def temp_distance(primary_color_layers, alpha_layers, rgb_layers): """  共分散行列をeye(3)とみなして簡単にしたもの.  3次元空間でのprimary_colorへのユークリッド距離を  ピクセルごとに算出し,alpha_layersで重み付けし,  最後にsum  primary_color_layers, rgb_layers: (bn, ln, 3, h, w) """ diff = (primary_color_layers - rgb_layers) distance = (...
1088ea81bdd0e613f600818dc95f5bf361019036
625,612
def parse_ens(ens_str): """Build the members strings for the ensemble answer""" components = ens_str.split(',') out = [] for c in components: if 'member:' in c: numbers = c.lstrip('member:') if '-' in numbers: start, end = numbers.split('-') ...
af521db766b15b7bda1534cc3eb7aad48ef7aa04
625,614
import struct def encode_varint(number): """ Write a VarInt to a string. :param number: Number to encode as a VarInt. :return: The encoded VarInt. """ # Python ints are variable length, which means there's no fixed size. # Typical programming language implementation exploits the sign bit moving # when doing...
a12efcaf2c636058297ae3b23c0f8ca2c49ee66a
625,616
import hashlib def str_md5(_str): """ 字符串MD5 :param _str:字符串 :return:字符串的MD5值 """ m = hashlib.md5() m.update(_str.encode()) return m.hexdigest()
e5f69c78215bde2292193eb1b2ec961829336fc7
625,617
def _polygon_area(x, y): """ Function to compute the area of a polygon by giving its coordinates in counter-clockwise order. """ area = 0 j = len(x)-1; for i in range (0, len(x)): area += (x[j]+x[i]) * (y[i]-y[j]); j = i return area/2;
88f7127f412bc3b332951730ddbbcf64355b3f31
625,618
import torch def top_k_ranking(embeddings, labels, prototypes, prototype_labels, top_k=3): """Compute top-k accuracy based on embeddings and prototypes affinity. Args: embeddings: An N-D float tensor with last dimension as `num_c...
f443b137c39737927cfe3af404ef32dcfb789a8d
625,619
from typing import Any def fmt_value(obj, **_: Any) -> str: """Format a value expression or operation. [`repr`][repr] the object if we don't have a specific formatting rule. """ return repr(obj)
67cc116b7943b6d4608790a6a04671f310227756
625,620
def get_response_frame_data(): """ This function simple creates the response data frame for response """ response_frame = { "result": 0, "payload": "" } return response_frame
84dd29619f04b4dd69b7f0dac029e7fe4db3de3c
625,621
def make_empty_table(row_count, column_count): """ Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell ...
7fdda33e73475df7051a4117dd2aaffe5193f9a0
625,622
def _try_convert_str_to_float(value, label): """ Try to convert input value to float value. """ try: return float(value) except Exception: msg = 'Invalid parameter: {} cannot cast string to float.'.format(label) raise ValueError(msg)
484738b1b76545c10031905a71a9534de3f4f646
625,623
def _validate_arg(value, expected): """Returns whether or not ``value`` is the ``expected`` type. """ if type(value) == expected: return True return False
e296ebdc51a4e441494074f5a8f5bb1e066c16e5
625,624
def get_term_uri(term_id, extension="html", include_ext=False): """:return: the URI of a term, given the retrieved ID""" if "http://" in term_id: return term_id term_uri = "http://vocab.getty.edu/aat/" + term_id if include_ext: return term_uri + "." + extension return term_uri
fd0c5fc3fadbdaabaea1224076863bf007544ede
625,625
import os def paths_to_abspaths_in_line(line): """Replace all relative paths to absolute paths in a string. For example, a line: script.py in/file1.txt out/file1.txt -v is transformed into: /home/user/proj/script.py /home/user/proj/in/file1.txt /home/user/proj/out/file1.txt -v """ if not isin...
4dbb1236205c824f9109be8f4be26154c5ce2ae8
625,626
def smellPghRootUrl(): """Return the root url for SmellPGH production""" return "http://api.smellpittsburgh.org/"
3b49185e16a2c12749b89b8312b23f8a2c080fb1
625,627
import os def detect_files(directory, keyword): """ detect files in specified directory with specified keyword input ----- directory : string dir to search keyword : string keyword to look for output ----- sorted list of file names test ----- (1)...
7473665537cb4c2aa479e2a8616cee9175f765e3
625,630
def toUserProfileBitmap(l, bp): """ l - [bid1, bid2, ...] bp - bp - {bid: bitmap, ...} """ bitmap_res = bp[l[0]] for i in range(1, len(l)): bitmap_i = bp[l[i]] bitmap_res = bitmap_res.unionTwo(bitmap_i) bitmap_res.countAndSetCountOne() return bitmap_res
ed695bdab5e2d044e4b86832ad44e58fe7798f41
625,631
def parse_requirements(path): """ Return the contents of a requirements file as a string separated by spaces. """ with open(path, 'r') as fp: return ' '.join(line.strip() for line in fp)
c220effeddfc819a1d584b575dbba997caab6e6d
625,632
import argparse def create_parse(): """ set up parser options """ parser = argparse.ArgumentParser(description="file hashing utility") parser.add_argument("target", help="one or more files to be hashed", nargs="+") return parser
73b8b597ea07110d457b005d72d9102ebc9edf1f
625,633
def enum_names_aslist(c, lower=True): """Get an Enum class as a list of enum names. Args: c (:class:`Enum`): Enum class. lower (bool): True to get names as lower case; defaults to True for easier comparison with other strings. Returns: List: List of enum names. """...
8ff40185b07dc6e4c0d1fe0ee469b9b470bcff0a
625,634
def shift_bits_left(value, bits_number): """:yaql:shiftBitsLeft Shifts the bits of value left by the number of bits bitsNumber. :signature: shiftBitsLeft(value, bitsNumber) :arg value: given value :argType value: integer :arg bitsNumber: number of bits :argType right: integer :returnTy...
5329597f5a0a9a456b2f141f906af10fb3c6d834
625,635
def create_attend(conn, face_attend): """ Create a new record into the students table :param conn: :param face_attend: :return: table id """ sql = ''' INSERT INTO attendance(attendance_id,report_id,student_number,confidence, date_attended) VALUES(?,?,?,...
6d691afc46adc6fb46ea55815284851d660c149f
625,636
def tolerance_anib_hi(): """Tolerance for ANIb concordance comparisons. This tolerance is for comparisons between "high identity" comparisons, i.e. genomes having identity greater than threshold_anib_lo_hi in homologous regions. These "within-species" level comparisons need to be more accurate """...
7539addae609d2004d985f0bcd05f789212bb664
625,638
import requests def download_file_from_google_drive(id, destination): """ This code is partially borrowed from https://gist.github.com/charlesreid1/4f3d676b33b95fce83af08e4ec261822 """ def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswi...
2c6eec74014e3178806501c0b1e6b08bad61b336
625,639
def min_length(word, thresh): """ Predicate for the length of a word """ return len(word) >= thresh
5f6eff3e06726294a64ef7705e3797ab188202f3
625,640
def preload_at(at_lat): """Load the elements onto an 'elems' object's attributes by type so that groups of elements of the same type (class) can be more easily accessed, e.g. 'elems.dipole' will return a list of all the dipoles in the lattice. As a special case 'elems.all' will return all the elements i...
016b609af4be4882b56b5b425a131c75afc4c1bf
625,642
def create_vector_net_from_module(specific_class, model_module_name, labels): """ ???+ warning "Deprecated into a trivial invocation of VectorNet's class method." """ return specific_class.from_module(model_module_name, labels)
46ace899a969d9d2ddfc0f9473a36f9f55271e46
625,643
def _key_from_query(query, qualifier=None): """ Given a Query, create a cache key. """ stmt = query.with_labels().statement compiled = stmt.compile() params = compiled.params return " ".join( [str(compiled)] + [str(params[k]) for k in sorted(params)]...
7710c9a7fbe14265e814df361b46fb8353dfdb32
625,645
def build_lstm_vocab(tokens): """ Builds vocab from list of sequences :param sentences: list of sequences, each a list of tokens :return: tuple of (dictionary: word --> unique index, pad_token_idx) """ all_tokens = list(set(tokens)) vocab = {token: i for i, token in enumerate(all_tokens)...
f35a2bcc65a46e2c224886ed93b62e47bec90aa5
625,646
def _parse_gcs_path(path: str): """Parses the provided GCS path into bucket name and blob name Args: path (str): Path to the GCS object Returns: bucket_name, blob_name: Strings denoting the bucket name and blob name """ header, rest = path.strip().split('//') if header != '...
ab77a7bbe41b7e6da4e1bd75e44fe006706a7a93
625,647
from typing import List from typing import Optional from typing import Dict def url_join(paths: List[str], params: Optional[Dict[str, str]] = None) -> str: """Construct URL with REST syntax.""" url = '' # ensure joins with '/' but ignore final '/' for path in paths: url += path if path[-1] ==...
9eee2ace40839fe1909449c056a3285bf381c0a0
625,648
import os def _read_template(template_type='index'): """ Which template to read from pre-defined set of templates. :param template_type: One of ``index``, ``hall_of_fame`` or ``ranking``. """ assert template_type in ('index', 'hall_of_fame', 'ranking') tmpl_path = os.path.dirname(os.pat...
a1b5564c7d9191d5d3308fd7ad6e9517ff33644a
625,649
def object_sort_key(obj): """ Define a predictable sort ordering for Kubernetes objects. This should be the same ordering that Kubernetes itself imposes. """ return ( # Not all objects have a namespace. getattr(obj.metadata, "namespace", None), obj.metadata.name, )
49ed089de8b8b8442fd39faf9f6d97f15186d220
625,650
def lookup(data, label, name): """根据指定的label和name来获取数据""" return data[label].get(name)
f6c9b2a8e70cece9b1b85145cfec27c69564a2e5
625,651
def is_punct(text): """ returns true if the text consists solely of non alpha-numeric characters """ for letter in text.lower(): if letter in set('abcdefghijklmnopqrstuvwxyz1234567890'): return False return True
c882d11f5004b23aea19c16fb599432fc142d3d6
625,653
def flat(data): """flat the data like zip """ sentences = data['sentence'] uuids = data['uuid'] valueses = data['values'] return [{'sentence': sentece, 'values': values, "uuid": uuid} for sentece, values, uuid in zip(sentences, valueses, uuids)]
13799cfdfb27f2c54eb2347d6d6ba18fa94176d3
625,654
def _JsonChecks(input_api, output_api): """Run checks on any modified json files.""" failing_files = [] for affected_file in input_api.AffectedFiles(None): affected_file_path = affected_file.LocalPath() is_json = affected_file_path.endswith('.json') is_metadata = (affected_file_path.startswith('site/'...
af172d8a1ac2812078b1f33c12524f10999a4473
625,655
def is_terminated(lines): """Determine if assert is terminated, from .cpp/.h source lines as text.""" code_block = " ".join(lines) return ';' in code_block or code_block.count('(') - code_block.count(')') <= 0
64cb16569b2c9ec71260306509fb51ab68209437
625,656
def is_zh(ch): """return True if ch is Chinese character. full-width puncts/latins are not counted in. """ x = ord(ch) # CJK Radicals Supplement and Kangxi radicals if 0x2e80 <= x <= 0x2fef: return True # CJK Unified Ideographs Extension A elif 0x3400 <= x <= 0x4dbf: retu...
5aceaefad2d11d854f83c8dbb43d9e34a5ab5323
625,657
def _merge_lists(a, b, append=False): """ Merge two lists. """ merged = b.copy() if append: temp_list = a temp_list.extend(x for x in b if x not in temp_list) merged = temp_list return merged
c483188b94c46c2abff32d856feb6e32e8f528c4
625,659
def get_mean_pore_size(img, nx): """ Finds the mean pore diameter of the domain Parameters: ---------- :param np.ndarray img: binary image array of domain :param int nx: number of pixels in x direction of fluid domain Returns ------- :return: Model domain mean pore ...
0ec3b3d6d103b22d769423c1c8ec9fa1af983e2d
625,660
def parsed_data(provides, data): """ Function that parse data. :param provides: action name :param data: response data :return: parsed response """ boolean_dict = {"True": "Yes", "False": "No"} if provides == "list patches": for item in data: try: item["...
4c689b4fa24ca49ffb785084719b0262576c3f9f
625,661
def format_data(df): """ Set proportions using population counts. """ # total population as integer df['pop_count'] = int(df['pop_count']) # convert count to proportion of population for k, v in df.items(): if '_age_' in k or '_sex_' in k: df[k] = df[k] / df['pop_count'] ...
0a960a0f153036b7094855fd73a28571ed342da1
625,662
def combine_data(df_cases, df_postcodes): """Join cases dataframe to postcode dataframe to get geo co-ords. Total cases by postcode.""" df_cases_with_geo = df_cases.merge(df_postcodes, on="postcode", how="left") df_cases_with_geo["cases"] = 1 cases_total_by_postcode = ( df_cases_with_geo.gro...
6fbf06863b32308d29e0c3863b93976a626d83a0
625,663
import os import sys def get_file_list(path): """ Helper function for getting all the files at the given path :param path: :return:files """ if not os.path.isdir(path): print("Path does not exist " + path) sys.exit(1) files = next(os.walk(path))[2] return files
86c523022c51f3c20b5bc229ed33c9c2608488be
625,664
def fibonacci(number): """Числа фибоначи""" a, b = 0, 1 for i in range(number): a, b = b, a + b return a
ba13a117d2d8e298250cf6903df402981ef2f4d7
625,665
def isimage(filename): """true if the filename's extension is in the content-type lookup""" ext2conttype = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "gif": "image/gif"} filename = filename.lower() return filename[filename.rfind(".")+1...
cc1a3b47c3f15bafdc01df25a8dfd99b4239bd5a
625,666
def inclusion_no_params(): """Expected inclusion_no_params __doc__""" return {"result": "inclusion_no_params - Expected result"}
e6c12687bcc50298fff18511548d66d89f601fa0
625,667
import math def diff(a, b): """Returns the difference between two values.""" return int(math.fabs(a - b))
b87a817acf274563ceb0c7d7d6df17f1f42b405d
625,668
def validate_boolean_value(boolean_value_input): """ The purpose of this function is to validate that a boolean value input is valid. """ # Type check. If it is not a boolean value, attempt to change it # into one. if not isinstance(boolean_value_input, bool): try: boo...
b813a6156fe1f2b9d4acfa1fe1a2299e3916428e
625,669
def normalizeShape(shape): """ Method used to convert shape to tuple Arguments: -shape: int, tuple, list, or anything convertible to tuple Raises: -TypeError: If conversion to tuple failed Returns: A tuple representing the shape """ if isins...
533040ca50e720301aaef602a37b104501aea1c8
625,670
def _PrettyPrintSize(x): """Pretty print sizes in bytes, e.g. 123456 -> 123.45kB. Args: x: (int) size Returns: (str) Pretty printed version, 2 decimal places. """ if x < 1e3: return '%dB' % x elif 1e3 <= x < 1e6: return '%.2fkB' % (x / 1e3) elif 1e6 <= x < 1e9: return '%.2fMB' % (x /...
439adf65e31a8bdb171d91cfc3d19dfba45cf502
625,671
import re def default_get_arg_names_from_class_name(class_name): """Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name,...
0641f1763bf8ac1c7f0906e94d817ef1e615bb37
625,673
def _tid_to_slice_ix(tid, train_ids, stop=False): """Convert a train ID to an integer index for slicing the dataset Throws ValueError if the slice won't overlap the trains in the data. The *stop* parameter tells it which end of the slice it is making. """ if tid is None: return None tr...
8a8512783c10b34ef9128a23961b9b756600f79b
625,674
import subprocess def check_git_status(input_dir): """ A convienience function to see if the input directory is a git repo. Returns 0 if input is not inside a repo. """ cmd = ['git', 'status'] p = subprocess.Popen(cmd, cwd=input_dir) p.wait() return p.returncode == 0
6a5370af0fbc8d5e46c2e7e8893deccfec1ae0be
625,675
def wordtonum(row_to_add): """ :param row_to_add: Contains the rows from the input file. :return: int type values, converted words to numbers. """ word_dict = { 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'ze...
8f0da6f3b0276a91eea75e80a03e8b015941da4c
625,676
def complement( intervals, first = None, last = None): """complement a list of intervals with intervals not in list. """ if len(intervals) == 0: if first != None and last != None: return [(first,last)] else: return [] new_intervals = [] inte...
47354203ec464e283cc04fb29655b1599a568248
625,677
def _load_spinoff_revenue(df): """_load_spinoff_revenue Args: df (pd.DataFrame): Intellectual property revenue table from HESA (table-4). Returns: df (pd.DataFrame): IP revenue from all sources. """ df = df[df['Metric'] == 'Estimated current turnover of all active firms (£ thousands...
6a5ca9c75294700bf08ab6d5a7e2f111a6eecd00
625,678
import imghdr def filter_local_img_type(ignore_type='gif', *img_path): """ 过滤指定类型本地图片 :param ignore_type: :param img_path: :return: """ result = [] for i in img_path: img_type = imghdr.what(i) # print(img_type, i) if img_type == ignore_type: continue...
99ed85b90d9ac5b36bc68d1962bc2d984479a21b
625,679
def hex_to_rgb(string): """ convert hex to rgb """ if len(string) >= 2: if string[0] == "#" or string[0:2] == "0x": if string[0] == "#": string = string[1:] else: string = string[2:] for char in string: if char not in ("0","1","2","3","4","5","6","7","8","9", "a", "b", "c", "d", "e", "f"): ...
8cac55bc36e0d9d3fda118118a8e7b8135270de3
625,680
def _sub_complete_column(column, df): # noqa: F811 """ Args: column : list df: Pandas DataFrame Returns: Pandas DataFrame """ column = df.loc[:, column] if column.duplicated().any(axis=None): return column.drop_duplicates() return column
664803f4839c14d35475fc40ddac29e3e34573fe
625,681