content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def reg_all_chinese(data): """ 匹配所有的汉字 :param data: :return: 汉字list """ patt = re.compile(u'[\u4e00-\u9fa5]+?') ret = patt.findall(data) return ret
30a0e0bab9042f1ab039fe86707170470e645fc5
660,058
def smart_multiply(var, factor): """Elementwise multiplication if tuple, normal if float or integer; else: do nothing. Can be used in a apply_map on a whole dataframe.""" if isinstance(var,tuple): var = tuple(factor*x for x in var) elif isinstance(var,float): var = factor * var elif isin...
82d8c3368f2106f56b7f785d51f0982c573b22f7
660,059
import argparse def input_args(): """ This function use python's argparse module and takes 9 comanand line can be used by the user in the terminal, all arguments have default input can be used to run the program. Command Line Arguments: 1. Image folder as --data_dir with default value 'flowers'. 2...
e1de28d63080ded0cb42b7dc0b1cffe9a90ff6bc
660,060
import os import codecs def file_get_contents(filename): """Reads an entire file into a string.""" assert os.path.exists(filename) and os.path.isfile(filename), 'invalid filename: ' + filename return codecs.open(filename, 'r', 'utf-8').read()
f472d45c89fc0e1d751d450016c6506f8ec43b34
660,061
import re def getIDfromComment(line): """ Get id from comment Returns 1510862771508 from <!-- 1510862771508 --> """ idPattern = re.compile("\d{13,}") return idPattern.findall(line)[0]
501650935c53a4e1019434bff09d29e2cac6c2bb
660,062
def _sample_distribution_over_matrix(rng): """Samples the config for a distribution over a matrix. Args: rng: np.random.RandomState Returns: A distribution over matrix config (containing a tuple with the name and extra args needed to create the distribution). """ # At this point, the choices her...
20c39319f217e62bd33e06f4f556030f133baff7
660,063
from datetime import datetime def get_todays_date_obj(obj): """Get the date of the daily post and return the date in %d-%B-%Y format""" title = obj.title daily_title = title.split(' ') todays_date = '{}-{}-{}'.format(daily_title[4].rstrip(','), daily_title[3], d...
f5163ac7278357b841b1332ffa670fd4bb1101e4
660,064
def _dec_to_base(num, nbits, base): """ Creates a binary vector of length nbits from a number. """ new_num = num bin = [] for j in range(nbits): current_bin_mark = base**(nbits-1-j) if (new_num >= current_bin_mark): bin.append(1) new_num = new_num - curren...
41274c0388d29c61a18825412b80c43b168529b8
660,065
def _duration_to_nb_windows( duration, analysis_window, round_fn=round, epsilon=0 ): """ Converts a given duration into a positive integer of analysis windows. if `duration / analysis_window` is not an integer, the result will be rounded to the closest bigger integer. If `duration == 0`, returns `0`...
c6e90549a3c7f7ad42f2bf6c11fa537cc94a112a
660,066
from typing import List import re def replace_block(lines: List[str], block_name: str, block_pattern: str, new_value: List[str], check=True) -> List[str]: """ Replace the blocks in a list of lines with new values """ in_block = Fa...
d44fc996d1642ce457a0951c4383ab56a201235c
660,067
def dt64_epoch(dt64): """ Convert a panda or xarray date/time value represented as a datetime64 object (nanoseconds since 1970) to a float, representing an epoch time stamp (seconds since 1970-01-01). :param dt64: panda or xarray datatime64 object :return epts: epoch time as seconds since 1970-01-0...
fcddeb30780187d85c5a99d9cb4d341b9c57c976
660,068
from typing import Any def python_to_json(value: Any) -> Any: """Filter. Return the value as it needs to be displayed in JSON Used to display a string literals more explicitly for default and const values. """ if value is None: return "null" if value is True: return "true" if ...
ddc6aac8845903e04d79e26b9dcfb4a947c5eea0
660,069
import random def names_func(a_list, size): """ This func should take a list and size, break the list into lists of the size and return a list of lists. """ # Shuffle the names random.shuffle(a_list) # Init the groups list (expected to be a list of lists) groups = list() while ...
0c745448157f600ce92d062b70b42bb317ecba29
660,070
def outer(a, b=None): """ Compute outer product between a and b (or a and a if b is not specified). """ if b is None: b = a size_a = tuple(a.size()) + (b.size()[-1],) size_b = tuple(b.size()) + (a.size()[-1],) a = a.unsqueeze(dim=-1).expand(*size_a) b = b.unsqueeze(dim=-2).expand(*size_b) ret...
82bca0035a5cdb35c6edb07a004c805f4e5e0000
660,071
def viss(t, d): """Viscosity of vapour as a function of temperature (deg C) and density (kg / m3).""" V1 = 0.407 * t + 80.4 if t <= 350.0: return 1.0e-7 * (V1 - d * (1858.0 - 5.9 * t) * 1.0e-3) else: return 1.0e-7 * (V1 + d * (0.353 + d * (676.5e-6 + d * 102.1e-9)))
5ad2b5bad9bd679409bdee914cce504c15fe5980
660,072
def get_aggregated_metrics_from_dict(input_metric_dict): """Get a dictionary of the mean metric values (to log) from a dictionary of metric values""" metric_dict = {} for metric_name, metric_value in input_metric_dict.items(): metric_dim = len(metric_value.shape) if metric_dim == 0: metric_dict[metric_name] =...
7570ed93878ac899a9d89f22a070ea70eab12f98
660,073
def to_float(v): """Convert a string into a better type. >>> to_float('foo') 'foo' >>> to_float('1.23') 1.23 >>> to_float('45') 45 """ try: if '.' in v: return float(v) else: return int(v) except: return v
56ada02c7d0e31a186f9ac6b3afc4f6c04a993f8
660,074
def load_region_bounds_dict(): """ Load dictionary containing region short names (keys) and bounds (values). The bounds are in the order [longitude tuple, latitude tuple]. """ region_bounds_dict = {'ESEAs': [(94, 161), (-10, 65)], # modified emissions regions 'EAs': [(100,...
4c146900c63ed7d66999020aba433ee9ed996d1e
660,075
def get_public_instances(game): """ Return the instance ids of public instances for the specified game. Args: game: The parent Game database model to query for instances. Returns: An empty list if game is None. Else, returns a list of the instance ids of all joinable public instances with game as ...
035a25a1b41c5889191da600b7791c9c89637e11
660,076
import time def Main(): """The main function.""" for j in range(10): for i in range(10000): print(str(j) + 'The quick brown fox jumped over the lazy dog.' + str(i)) time.sleep(60) return 0
b207eff4700365fa33c517248ca9b6240f3d15aa
660,077
def lift_calc(PPV, PRE): """ Calculate lift score. :param PPV: precision or positive predictive value :type PPV : float :param PRE: Prevalence :type PRE : float :return: lift score as float """ try: return PPV / PRE except Exception: return "None"
8e43458ad9bdceacf5613597c3b1bb00f8dd69ec
660,079
def change_exclusion_header_format(header): """ Method to modify the exclusion header format. ex: content-type to Content-Type""" if type(header) is list: tmp_list = list() for head in header: tmp = head.split("-") val = str() for t in tmp: ...
498a66b68f7bbef26f6cb07c3292ffc7a20ad8d5
660,080
def is_negate(trial_value): """ Example: !EGFR => (True, EGFR) :param trial_value: :return: """ negate = True if trial_value.__class__ is str and trial_value and trial_value[0] == '!' else False trial_value = trial_value[1::] if negate else trial_value return trial_value, negate
a0bf43fb0e45140d4b848b1fe265c42279e7b127
660,081
def transit_func(s, a): """ Make next state by adding action str to state. ex: (s = 'state', a = 'up') => 'state_up' (s = 'state_up', a = 'down') => 'state_up_down' """ actions = s.split("_")[1:] LIMIT_GAME_COUNT = 5 HAPPY_END_BORDER = 4 MOVE_PROB = 0.9 def next_state(state...
5f12686ea70eb187e97456e1e23dc73eb31b660e
660,082
import glob import os def get_files(src_dir): """ Gets all files from source directory """ files = glob.glob(os.path.join(src_dir, '*.*')) return files
c9cd2ec751b195f89c3e527f0ffe7476fa3670ee
660,083
import argparse def get_predict_arguments(): """ Fetches all necessary inputs from the user :returns: namespace object containing all key-value pairs for user input arguments """ parser = argparse.ArgumentParser(description='Uses a pre-trained model to make a prediction on an image') parser...
664786e38fb410052361332424e1eb8957983041
660,084
def df2html(self, class_table=None, class_td=None, class_tr=None, class_th=None): """ Converts the table into a :epkg:`html` string. :param self: dataframe (to be added as a class method) :param class_table: adds a class to the tag ``table`` (None for none) :param class_td: adds a class...
27e8ec61c07acd947d02bec789288e025b8508ce
660,085
def compare_subnets(li1, li2): """ This function compares two lists and returns the difference. """ return (list(set(li1) - set(li2)))
df0455c11d0a578f0400dab3c37f9963be69f051
660,086
def tap_type_to_target_type(csv_type): """Data type mapping from S3 csv to Bigquery""" return { 'integer': 'INT64', 'number': 'NUMERIC', 'string': 'STRING', 'boolean': 'STRING', # The guess sometimes can be wrong, we'll use string for now. 'date': 'STRING', # The guess...
58b5a6cef39619b9272fe335e61b5e54b05f082c
660,087
import requests def language_check(pypi_url: str) -> str: """ 6. Are the tests running with the latest Language version? """ response = requests.get(pypi_url).json() classifiers = response.get("info").get("classifiers") languages = [s.replace("Programming Language :: Python :: ", "Python ") fo...
cb66fcc4552fa2c35ceb6ede3069947476a113a1
660,088
import numpy def produce_datearray(datetimelist): """Produce a list of date arrays from a list of datetime objects """ datearrays = [ numpy.array([d.year, d.month, d.day, d.hour, d.minute, d.second]).astype( "float64" ) for d in datetimelist ] return datearrays
c6773a5e9ed5e1dcc510d8bdd34edf6f338a156a
660,089
def encode_payer(user): """ Кодирование пользователя-инициатора платежа """ return str(user.id)
922728e28b4def4a01b696eb45081d6d51db5315
660,090
def update_mean(new_data, old_mean, num_data): """Compute a new mean recursively using the old mean and new measurement From the arithmetic mean computed using the n-1 measurements (M_n-1), we compute the new mean (M_n) adding a new measurement (X_n) with the formula: M_n = M_n-1 + (X_n - M_n-1)/n ...
8daf0d5acf369fa059e81caa4a2f95a1102780c2
660,091
import re def read_locations(year: int) -> list: """ Takes path to a file with locations, returns a list of all films from the given 6500, that match the year, entered by user, and are available for geocoding. """ locations = [] with open('locations.list', 'r', encoding='ISO-8859-1') as file: ...
5c9ba5f58421f9e5eb7486a20658716e17a63af3
660,092
def quantize(source, steps=32767): """ Quantize signal so that there are N steps in the unit interval. """ i_steps = 1.0 / steps return [round(sample * steps) * i_steps for sample in source]
3d879a4b35a384ef9fcaabdadb07f9b7b4e721f8
660,093
import re def snake_case(input_str: str, camel_case=False) -> str: """ Turn camel case into snake case. :param input_str: String of variable. :return: Snake case string of input_str. """ if camel_case: regex = r"([A-Z])" substitution = r'_\1' else: regex = r"([\s]...
7266fccc89c87cff144621d01e0f1dc08c7ea574
660,094
def InitReport(inp_d): """ Args: inp_d: (dict) fastq_fp: (str) nOff: (dict) ints (18-23) mapping to number of times (int) this distance occured between preseq and postseq within the reads codes: (dict) barcode (str)...
77cab7906466cd5d9c63a3c49dee06fc24ea3ace
660,096
import sys from io import StringIO def run_model(prob): """ Call `run_model` on problem and capture output. Parameters ---------- prob : Problem an instance of Problem Returns ------- string output from calling `run_model` on the Problem, captured from stdout """ ...
a628170b8b1c538d374fb4f61dd1eee5b91df031
660,097
def fibonacci(n: int) -> int: """Compute the N-th fibonacci number.""" if n in (0, 1): return 1 return fibonacci(n - 1) + fibonacci(n - 2)
cbefe9914fa5aa2a1eb445eb00a5c932ee04d0e6
660,098
def transaction(transaction_type = "required"): """ Decorator for the "transactional" data logic. This decorator should provide the "best" way to create a new transaction environment in a target function. The type of transaction to be created may be set with the optional parameter, but this is ...
6e156ea5f96887bb4944235bb167bde98f999504
660,100
def test_pp_model(text, pp_tokenizer, pp_model): """Get some paraphrases for a bit of text""" print("ORIGINAL\n",text) num_beams = 10 num_return_sequences = 10 batch = pp_tokenizer([text], return_tensors='pt', max_length=60, truncation=True) translated = pp_model.generate(**batch, num_beams=num_...
10394e7fe39e568f67c0347e09024ae21ca30d96
660,101
def none_formatter(error): """ Formatter that does nothing, no escaping HTML, nothin' """ return error
a08468a71060cf6f629c6f8b9b9e0c1dabc5f60d
660,102
def point_inside_polygon(polygon, p, thresh_val=0): """ Returns true if the point p lies inside the polygon (ndarray) Checks if point lies in a thresholded area :param polygon: ndarray that represents the thresholded image contour that we want to circle pack :param p: ndarray 1x2 representing a poi...
3faa905a7ddf3ce5e6a176f301222e0c993a0f1e
660,103
def dict_compare_keys(dictionary1, dictionary2, key_path=''): """ Compare two dicts recursively and see if dict1 has any keys that dict2 does not Returns: list of key paths """ res = [] if not dictionary1: return res if not isinstance(dictionary1, dict): return res for k ...
5dc4e7fee731242171534e9e9625f4fd1741c45d
660,104
import random def seed_wildcard_hierarchy(glycan_list, label_list, wildcard_list, wildcard_name, r = 0.1): """adds dataframe rows in which glycan parts have been replaced with the appropriate wildcards df_in -- dataframe in which the glycan column is called "target" and is the first column wildcard_list -- list...
5d2a04c4b6e68f7bae9dd08eea70a25635e60bbc
660,105
import subprocess def _get_all_notebooks_in_repo(skip=[]): """Get all files .ipynb included in the git repository""" git_files = ( subprocess.check_output( "git ls-tree --full-tree --name-only -r HEAD", shell=True ) .decode("utf-8") .splitlines() ) return [...
a0ee56d435537ddf63a2cd2181a46fd212f7ed04
660,106
def np_get_index(ndim,axis,slice_number): """ Construct an index for used in slicing numpy array by specifying the axis and the slice in the axis. Parameters: ----------- 1. axis: the axis of the array. 2. slice_number: the 0-based slice number in the axis. 3. ndim: the ndim of the ...
211cf4d29b730a72e481296ddb244f99d14df224
660,107
def leftjust_lines(lines): # 2007 May 25 """Left justify lines of text. Lines is a Python list of strings *without* new-line terminators. The result is a Python list of strings *without* new-Line terminators. """ result = [line.strip() for line in lines] return result
b7e5de88bd3f5e8234ca9a7363302fa608ab967e
660,108
import os.path def exists(path, **kwargs): """Check if file or directory exists""" return os.path.exists(path, **kwargs)
a31fbc37154751de201a62568f307d5d6d57bfcd
660,109
def final_metric(low_corr: float, high_corr: float) -> float: """Metric as defined on the page https://signate.jp/competitions/423#evaluation Args: low_corr (float): low model spearman high_corr (float): high model spearman Returns: float: final evaluation metric as defi...
ff1f1283f5e12917cc72a1c3a72bd2292690ea2a
660,110
def PyBuffer_IsContiguous(space, view, fortran): """Return 1 if the memory defined by the view is C-style (fortran is 'C') or Fortran-style (fortran is 'F') contiguous or either one (fortran is 'A'). Return 0 otherwise.""" # PyPy only supports contiguous Py_buffers for now. return space.wrap(1)
02eb662b969f37092a3cc71d9a9a80f00e0e4f48
660,111
import json def _parse_json_file(data): """Parse the data from a json file. Args: data (filepointer): File-like object containing a Json document, to be parsed into json. Returns: dict: The file successfully parsed into a dict. Raises: ValueError: If there was an...
b7cfafd6c8985e36bc8b8399c69ed27e6c613129
660,112
def quality_check(data): """ Expects string, returns tuple with valid data or False when data was invalid """ if data != False: if "RAWMONITOR" in data: data = data.replace("RAWMONITOR","") data = data.split("_") frequency = 2 * 8000000 - int(data[0]) ...
881821924aee33eb4a0c8ab55d700534c55991b6
660,113
def ntbk_dir_fixture(filesystem): """Return ntbk base Path for testing""" return filesystem.get_notebook_base_path()
f57038d612b6c148ca2c060ba830267f0c053ae7
660,114
def get_default_overlaps(n_s_row_max, n_s_col_max): """ comfortable for not defining new overlaps every time :param n_s_row_max: max number of rows in cut images :param n_s_col_max: max number of cols in cut images :return: our defined default overlaps """ return [(n_s_row_max // 2), (n_s_co...
87995a2894bd436561f7710a70b7916ba7a8bf20
660,115
def flex_wrap(keyword): """``flex-wrap`` property validation.""" return keyword in ('nowrap', 'wrap', 'wrap-reverse')
8b6753ba699f8e3ce16affd52292bdf9900a3fa9
660,116
def dict_string_to_nums(dictionary): """ turns all strings that are numbers into numbers inside a dict :param dictionary: dict :return: dict """ for i, j in dictionary.items(): if isinstance(j, str) and j.replace(".", "", 1).isnumeric(): num = float(j) if num.is_...
3f72959bfffbf8fd379646f615b0a8c3cfdc599b
660,117
import numpy import math def unit_vector(data, axis=None, out=None): """Return ndarray normalized by length, i.e. Euclidean norm, along axis. >>> v0 = numpy.random.random(3) >>> v1 = unit_vector(v0) >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) True >>> v0 = numpy.random.rand(5, 4, 3) ...
5ebf0021bff1b66acab2dbca0ce31db0af470a18
660,118
from typing import Tuple def parse_description(description: str) -> Tuple[int, str]: """Parse task description into amount and currency.""" raw_amount, currency = description.split(' ') raw_amount = raw_amount.replace('k', '000') return int(raw_amount), currency
181f0f0fb57acae68b6bcbc7315387fdb63e8056
660,119
from typing import Mapping def update(to_update, update_with): """ Recursively update a dictionary with another. :param dict to_update: Dictionary to update. :param dict update_with: Dictionary to update with. :return: The first dictionary recursively updated by the second. :rtype: dict ...
95082bcc6884bf4728801f058be576b5121e4bcb
660,120
def _splitter(value, separator): """ Return a list of values from a `value` string using `separator` as list delimiters. Empty values are NOT returned. """ if not value: return [] return [v.strip() for v in value.split(separator) if v.strip()]
8a2cd3faec1e56b02c6cd4c4ed508193957d9013
660,121
def rprpet_point(pet, snowmelt, avh2o_3, precip): """Calculate the ratio of precipitation to ref evapotranspiration. The ratio of precipitation or snowmelt to reference evapotranspiration influences agdefac and bgdefac, the above- and belowground decomposition factors. Parameters: pet (flo...
94473f9dc1dab4dffaf8a7556ed4109a3a7497a1
660,122
def keyword(_): """Matches keywords.""" return None
56a0f882cbd7461110398d6e9cabf55865bdb1db
660,124
def adiabatic_wall_temperature(T_c, M, gamma, r=0.9, Pr=None): """Adiabatic wall temperature: the driving temperature for boundary layer convection. Reference: Huzel and Huang, equation 4-10-a Arguments: T_c (scalar): Stagnation temperature of the fluid external to the boundary layer [u...
bbd3457dcee50eda6be0c225381ed83fa3c7edb5
660,125
def get_last_uploaded_byte(request): """Return last uploade byte..""" return int(request.headers['Range'].split('-')[-1])
7624909d3ad0f855c30865ac4d489cbb93aaceea
660,126
import argparse def get_args(): """ Python argument parser. """ parser = argparse.ArgumentParser() parser.add_argument("--id", help="The job id of travis build.") parser.add_argument("--stage", help="Travis build stage name.") parser.add_argument("--token", help="Travis build auth token.") ar...
576611163d104d4dff50ea810d633ff22cb48f83
660,127
import os import json def get_user_location(parent_dir): """ Function: get_user_location\n Parameter: parent_dir -> path of current dir\n Returns: Returns list of x and y coordinates of ground users\n """ dir_name = 'input_files' file_name = 'user_input.json' user_input = {} with o...
3ebc7ac2641765b18b94a9476a54f4434c35bc8f
660,128
import os def uname(): """ Return username from the env. """ return os.environ["USER"]
bbc91fabcfff04ecf8800927519a457d56d1d5c0
660,130
def get_arguments(frame): """Return call arguments in the given frame""" # When called, all arguments are local variables local_variables = frame.f_locals.copy() arguments = [(var, frame.f_locals[var]) for var in local_variables] arguments.reverse() # Want same order as call re...
24f21e7e303570654c1f580f254dbe30a177ec4d
660,131
def form2audio(cldf, mimetype='audio/mpeg'): """ Read a media table augmented with a formReference column. :return: `dict` mapping form ID to audio file. """ res = {} for r in cldf.iter_rows('media.csv', 'id', 'formReference'): if r['mimetype'] == mimetype: res[r['formRefere...
460f3b73f407a4c0c8bf0157c4b141f418aa6bcf
660,132
def get_value_of_bills(denomination, number_of_bills): """ The total value of bills you now have. :param denomination: int - the value of a bill. :param number_of_bills: int - amount of bills you received. :return: int - total value of bills you now have """ return denomination * number_of...
39c243588fafc32c5e5c962cacf11c0154411a22
660,133
def request_city_name(): """Function requests the city the user lives in and assigns the result. Args: NONE Returns: city: User's city Raises: ValueError: If User's input is not character. """ while True: try: if (city := input("\nEnter the city name where yo...
b8af9a2f9a90299661b71f526c04e79850d3e482
660,134
def strip_script(environ): """ Strips the script portion of a url path so the middleware works even when mounted under a path other than root. """ path = environ['PATH_INFO'] if path.startswith('/') and 'SCRIPT_NAME' in environ: prefix = environ.get('SCRIPT_NAME') if prefix.endsw...
3ec4a8da3289ea8fd281328bbc74b8fab525a366
660,136
def truncateWord32(value): """ Truncate an unsigned integer to 32 bits. """ return value & 0xFFFFFFFF
67ea12cf212590c2a7cb2f09879ca499364b5ce6
660,137
def add_to_image(image, inset, uv, verbose=False): """Add an image to another image at a specified position. The inset image may be of any size and may only overlap partly on the overall image depending on the location specified. In such a case, the inset image is cropped accordingly. :param np.array ...
6181082fac13999a6853f60a44530f69a6c328e1
660,138
def _strip_comments_from_pex_json_lockfile(lockfile_bytes: bytes) -> bytes: """Pex does not like the header Pants adds to lockfiles, as it violates JSON. Note that we only strip lines starting with `//`, which is all that Pants will ever add. If users add their own comments, things will fail. """ r...
2ccba30bd4ecdbb41432496e9d34c1975934f621
660,139
def extract_domain_idx(domain_vect, word): """ :param domain_vect: :param word: :return: a list of word index pairs in each domain: word_idx, length of vocab in the domain """ uniq_domains = domain_vect.uniq_domains uniq_domains.append('general') count = 0 domain_word_idx = [] ...
e9b803d9e78f7d6e3eb4c76c4afca1eec1ff4d15
660,141
def subcloud_db_model_to_dict(subcloud): """Convert subcloud db model to dictionary.""" result = {"id": subcloud.id, "name": subcloud.name, "description": subcloud.description, "location": subcloud.location, "software-version": subcloud.software_version, ...
f1a4d1ec6f838522b5dcf8d5109aa52a95c7d5d8
660,142
def rotate_90(rectangle): """Rotates a rectangle (2x2 coordinates) by 90""" return [(-y, x) for x, y in rectangle]
464c77f23cdce078fca0d432f9d9ce5a98c9cad3
660,143
def find_diameter(root): """ returns (max branch length, max diameter) """ if not root: return 0, 0 # traverse left and right subtrees left, right = find_diameter(root.left), find_diameter(root.right) # return the max branch from the left and right subtrees plus the current node # and ...
1c061eb868e0474370f7da98cadf6e25b01d6dea
660,144
def remove_non_printable_chars(s): """ removes 'ZERO WIDTH SPACE' (U+200B) 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) """ return s.replace(u'\ufeff', '').replace(u'\u200f', '')
670dce3bf9d77816d64d1311270e898d2801b6dd
660,146
from pathlib import Path import os def _is_writable_dir(p): """ Checks to see if a directory is writable. """ # Worried about multiple threads creating the directory at the same time. try: Path(p).mkdir(parents=True, exist_ok=True) except FileExistsError: # raised if there's an existi...
7f464c596fbd525ad8f2c71547283b5bd25169ef
660,147
def getChargeProfileSection(protein, verbose=False, options=None): """ returns the protein-folding-profile section """ str = "Protein charge of folded and unfolded state as a function of pH\n" profile = protein.getChargeProfile(grid=[0., 14., 1.], options=options) if profile == None: str...
ffa191702e712730a1d640c3b990e52eeaa4b9aa
660,148
from functools import reduce def need_broadcast(main_data_shape, main_logical_shape, with_shape): """return False if main_data needn't to do broadcast""" if not with_shape: return False if not main_logical_shape: return False with_data_num = reduce(lambda x, y: x * y, with_shape) ...
ad724bbd59ed349e7d0e68a4ca489b1df0b8a386
660,149
def diffmean(xl, yl): """Return the difference between the means of 2 lists.""" return abs(sum(xl) / len(xl) - sum(yl) / len(yl))
36a449f68311f6ec8b23698c9c9797501eb73240
660,150
import sys import subprocess import os import time def env_info(): """ Collects information about the environment, for reproducibility """ info = {} info['python_version'] = sys.version info['command'] = subprocess.list2cmdline(sys.argv) with open(os.devnull, 'w') as devnull: info['pip_mod...
01e39d923f43b770c65fad6a870fb33f0f6adbbc
660,151
def _multihex (blob): """Prepare a hex dump of binary data, given in any common form including [[str]], [[list]], [[bytes]], or [[bytearray]].""" return ' '.join(['%02X' % b for b in bytearray(blob)])
b5f7698275e9e71b6e1c70bf728277a27c78c30e
660,152
def is_disabled(field): """ Returns True if fields is disabled, readonly or not marked as editable, False otherwise """ if not getattr(field.field, 'editable', True): return True if getattr(field.field.widget.attrs, 'readonly', False): return True if getattr(field.field.widget.at...
e1b7064d0a1cb54fa7539f84460893b886202d53
660,154
def escape_chars(s): """ Performs character escaping of comma, pipe and equals characters """ return "".join(['\\' + ch if ch in '=|,' else ch for ch in s])
a28d3a991e34e480291c7c51ee7b4a5d367c5588
660,156
def return_column_from_table(table_name, column, conn,c): """ Return everything in a selected column """ cmd = "SELECT %s FROM %s"%(column, table_name) c.execute(cmd) result = c.fetchall() return result
a49515e10b23666db680636dd57c60dbe1fe2f09
660,157
def update_parameter(parameter, grads, learning_rate = 0.0075): """ :param parameter: -- a dictionary contains each layer's parameter ,i.e."W1", "b1", "W2", "b2",... :param grads: -- a dictionary contains each layer's gradient respect to cost ,i.e. "dW1","db1",... :return: parameter -- updated para...
2acae9262642ccedaf65f3271576b4538a122dc6
660,158
def kernel_func(x): """ arbitrary function goes here """ return x**4 - 2*x**2 - x - 3
3b4e052d789e5ca56a65712b99b2b2ffaf81c6bf
660,159
def unordered_types_overall(x_name_type_unord): """Create dummies capturing if particular types of unordered vars exit. Parameters ---------- x_name_type_unord : list of 0,1,2 Returns ------- type_0, type_1, type_2 : Boolean. Type exist """ type_2 = bool(2 in x_name_type_unord) ...
6cabf76a62875960e920179db79f0d7eb4a210e5
660,160
def convert_decimal(string): """ Takes a string and converts is into a decimal :param str string: :return float: """ try: return float(string) except: return ""
81dfe170d5371f7c5ae9990385a1226a9ac786ec
660,161
def Qcopy(q): """ Qcopy """ return (q[0], q[1], q[2], q[3])
0a171b22c0011ee484d459ca65a0280c7fb61f24
660,162
import subprocess import sys def _exec(command, check): """ execute the `command`. If `check` is True, the execution end if git root not found. Otherwise `None` is returned. """ complete = subprocess.run(command, stdout=subprocess.PIPE, encoding="utf-8") if complete.returncode == 0: ...
3fbb17eddd35634b2ca89a488d9b4bebca779d97
660,163
import functools def factors(n): """ Copied from - https://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python """ return set( functools.reduce( list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) i...
30492c8f2054ef5442ec1ad689c83e68951a6f4e
660,165
def slugify(str_): """Remove single quotes, brackets, and newline characters from a string.""" bad_chars = ["'", '[', ']', '\n', '<', '>' , '\\'] for ch in bad_chars: str_ = str_.replace(ch, '') return str_
e170ee44bea9d96eefbad2c7f2f4fa81efc18a42
660,167
def flip_pose(pose): """Flip pose. The flipping is based on SMPL parameters. """ flippedParts = [0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11, 15, 16, 17, 12, 13, 14, 18, 19, 20, 24, 25, 26, 21, 22, 23, 27, 28, 29, 33, 34, 35, 30, 31, 32, 36, 37, 38, 42, 43, 44, 39, 40, 4...
368cad6952bf3022cd2f310043f6fa914aff4510
660,168
import os def get_logs_version(path_logs): """Get last version of logs folder to save model inside Args: path_logs (str): path of the logs/experiments folder """ try: version = str(max([int(fold.split("_")[1]) for fold in os.listdir(path_logs)])) except: version = None ...
9aa435ca8b1819027991172f0962bd9df54756a6
660,169