content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def getDegree(relation, start, end, target_bool=True): """ Update the residual in the path given in input Parameters: relation(dict): as key the year and as a value a dict that have as a value the type of relation and as a key the list of all relatio...
12381e899ca0c503c64ab4ac5a9870b036aaea17
20,868
def adjust_returns_for_slippage(returns, turnover, slippage_bps): """Apply a slippage penalty for every dollar traded. Parameters ---------- returns : pd.Series Time series of daily returns. turnover: pd.Series Time series of daily total of buys and sells divided by portfoli...
d445bf566f5c228ffda793089d7bfe23f3897df2
20,869
import requests def get_json(url): """Fetches URL and returns JSON. """ res = requests.get(url) res.raise_for_status() return res.json()
280f3c298cb5a471abe180b29c9d465d52b7b9b8
20,870
def find_matching_resource(preview_resource, delivery_entry, search_field): """Returns matching resource for a specific field. :param preview_resource: Entry from the Preview API to match. :param delivery_entry: Entry to search from, from the Delivery API. :param search_field: Field in which to search ...
518297f18a2dcd37bb226f96bd51370d7ed3c7e3
20,872
def app_security_group(): """ 生成默认安全组模板,默认允许所有流量出去 """ return { 'type': 'tosca.groups.nfv.PortSecurityGroup', 'properties': { 'description': 'default security group', 'name': 'app-group' }, 'members': [] }
7d4314b7e6d1718ba1cbfc9c7a2fb1982456a384
20,873
def author_join(value, d=u', ', last=u', and ', two=u' and '): """ Like join but for list of names (convenient authors list) """ if len(value) == 1: return value[0] elif len(value) == 2: return value[0] + two + value[1] else: return d.join(value[:-1]) + last + value[-1]
bbd5f172c503e5122ff60670b8a1c263a1cb11e0
20,874
import re def extract_date(text): """ Given the HTML text for one day, get the date :param text: HTML text for one day :return: Date as string """ report_date = re.findall("Arrow Build Report for Job nightly-.*", text)[0] report_date = report_date.strip("Arrow Build Report for Job nightly-...
e73952c4efc421f9227dad16346e923590933bdf
20,875
def replicate_filename_counter(unique_sample_list): """Create dict of sample names to number replicates sequentially""" sample_replicate_counter = {} for sample_name in unique_sample_list: sample_replicate_counter[sample_name] = 1 return sample_replicate_counter
9cca8e612266034f3cadc48c58451cabd123fa5b
20,877
def substitute(x, method="substitute"): """Turn a cpp type ``x`` into substituted string""" obj = eval(x.__class__.__name__ + "Template()") return getattr(obj, method)(x)
9b34cbd1491570faa217116b16570d3f97876223
20,879
def __validate_scikit_params(parameters): """validate scikit-learn DBSCAN parameters Args: parameters: (dict) Returns: eps, min_samples, metric, n_jobs """ eps, min_samples, metric, n_jobs = None, None, None, None if parameters is not None: eps = parameters.get('eps') ...
9b1f9bf89f6526bb0b67d658dd1bfc6d69a8ad83
20,880
def layerwise_group(model, criterion): """Group weight and bias of a layer.""" def is_weight(p): return p.dim() > 1 def is_bias(p): return p.dim() == 1 params = list(model.parameters()) num_params = len(params) assert num_params % 2 == 0, "Number of torch parameters must be ev...
4d5347ab6990923a9ce82589a8ade406207292e6
20,882
def get_central_conic_equation_coefficient_by_focus_d(x1, y1, x2, y2, d): """ central conic include ellipse, circle, hyperbola. especially ellipse and hyperbola. when ellipse, assign two focus and add. when hyperbola, assign two focus and difference. """ dd = d * d dddd = dd * dd x1x...
2ad8594f889d3ad2923248df2d149d3ec41f5986
20,883
def _build_message(texts, gif=None): """ Internal method """ base_dict = { '$schema': 'http://adaptivecards.io/schemas/adaptive-card.json', 'type': 'MessageCard', 'version': '1.0', 'themeColor': 'FFA800', 'summary': 'Notification', 'sections': [] } for te...
c1c3e7a2b5bdefbbd9071273618f808eb48d1dd9
20,884
def config(): """Marks this field as a value that should be saved and loaded at config""" tag = "config" return tag
c5f901f0a5cd25f4579b60d41f25a6df1821b4a0
20,885
import json def load_json_key(obj, key): """Given a dict, parse JSON in `key`. Blank dict on failure.""" if not obj[key]: return {} ret = {} try: ret = json.loads(obj[key]) except Exception: return {} return ret
d695d8eb1d08933a3bacba4de77161a6587a863d
20,886
def float_to_fixed_point(x: float, precision: int) -> int: """ Converts the given floating point value to fixed point representation with the given number of fractional bits. """ multiplier = 1 << precision width = 16 if precision >= 8 else 8 max_val = (1 << (width - 1)) - 1 min_val = -...
8b80f701b610da06ac8a09e8811ce00967a1a413
20,887
def encode(s): """ Encodes a string into base64 replacing the newline at the end. Args: s (str): The string. """ return s.strip().encode('base64').replace('\n', '')
02c805b7888560596cede9c763d0cf42334d4185
20,889
def format_file_date(edition_date): """Return a string DDMMYY for use in the filename""" return edition_date.strftime('%d%m%y')
3cab0a2de4c91ae66826f4ba49d9e4fdc1b7c1d0
20,890
def classify(obj, *classes): """Multiclass classificaiton based on human-tuned boundaries. Parameters ---------- obj : skimage.measure._regionprops.RegionProperties The object to classify. classes : florin.classify.FlorinClassifiers The classes to select from. Returns -----...
ba2b2e4ad43b7b89271f8e9a168c05a5055aac49
20,892
def parse_repo_url(repo_url: str) -> str: """ Parses repo url and returns it in the form 'https://domain.com/user/repo' Args: repo_url (str): unformatted repo url Returns: str: parsed repo url """ repo = repo_url.lstrip("git+") if repo_url.startswith("git+") else repo_url r...
5f9b5d2a0bc3dc30e48006fd43baa73d996268ca
20,896
def organism_matches(organism, patterns): """Tests organism filter RegEx patterns against a given organism name.""" for pattern in patterns: if pattern.match(organism): return True return False
135b6ad0472a2b0904ececc8b8f226c77b2294e6
20,897
import os def process_file(fname): """Process complexity curve file. Inputs -- fname - filename of complexity curve file Returns -- dictionary with complexity curve points """ sample = os.path.basename(fname).replace('.complex.ccurve.txt','') data = {'complexity_curve': {}} with open(fn...
a2e288f2b7862a5240d451498de9b954a46bb035
20,899
import argparse def optionparse(): """Argument Parser.""" opts = argparse.ArgumentParser(description='XDR Hunting Script', formatter_class=argparse.RawTextHelpFormatter) opts.add_argument('-d', '--days', help='Days of logs') opts.add_argument('-H', '--hours', help='H...
95117acb15abc78f5a15419a36b40c17b90b7aca
20,901
def permissions_to_label_css(permissions): """Return Bootstrap label class qualifier corresponding to permissions. Return <this> in class="label label-<this>". """ if permissions.startswith('all_'): return 'success' elif permissions.startswith('restricted_'): return 'warning' el...
6b6f4038abe023692644e1e137cfd8a76f56a6b6
20,903
from typing import Optional from typing import Dict def type_filter(type_: Optional[str], b: Dict) -> bool: """ Check Mistune code block is of a certain type. If the field "info" is None, return False. If type_ is None, this function always return true. :param type_: the expected type of block (...
083c89f9563c9282edf1babf9fdf249f694a0117
20,906
from typing import List def elements_identical(li: List) -> bool: """Return true iff all elements of li are identical.""" if len(li) == 0: return True return li.count(li[0]) == len(li)
2cccfaf588994080033e4ddfd17c351f5c462546
20,908
def color_rgb_to_hex(r: int, g: int, b: int) -> str: """Return a RGB color from a hex color string.""" return f"{round(r):02x}{round(g):02x}{round(b):02x}"
1021b5195619f1b6a9512fec44a253430a0a43ba
20,909
def read_file(filepath): """Open and read file contents. Parameters ---------- filepath : str path to a file Returns ------- str contents of file Raises ------ IOError if file does not exist """ file_data = None with open(filepath, "r") as f...
5b4e65893c94c45bb697a41222dbe524d60d2b04
20,910
def format_date(date:str) -> str: """return YYYYmmdd as YYYY-mm-dd""" return f"{date[:4]}-{date[4:6]}-{date[6:]}"
dfcc434006df8a7f6bd89003f592792faa891f30
20,911
def _mk_content(missing, headers, section): """Check if content exists and add to table setup lists if it does. Warnings -------- This method is intended for internal use only. """ content_lists = [] columns = [] sections = [] for content, head in zip(missing, headers): if ...
9117b568c8c09f1b3831efd0cf131288eace7a87
20,912
def reversal_algorithm (ar, k): """ ar is array of ints k is and positve int value """ n = len(ar) k = k % n temp = [] final = [] temp = ar + ar return temp[n-k:n+k] """ for i in range(0, n): if i < n-k: temp.append(ar[i]) else: final.append(ar[i]) for i in range(0, len(temp)): final.append(te...
8460422c6fa9eb103083414d7eaf76e97ac2b47e
20,913
def _get_bootstrap_samples_from_indices(data, bootstrap_indices): """convert bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays containing positional indices of observations in data. ...
15dac498120db5590bc3c8c2542c0d78be999dd4
20,914
def get_module_name_parts(module_str): """Gets the name parts of a module string `module_str` in the form of module.submodule.method or module.submodule.class """ if module_str: parts = module_str.split('.') module_name = '.'.join(parts[:-1]) attr_name = parts[-1] values ...
f167fe3a1224b5d3a1909e66bb9fa5288fd23eae
20,915
from typing import List def blocks_to_squares(blocks: List[List[int]]) -> List[List[List[int]]]: """Returns a list of list of blocks of four squares at a time. E.g. .. code-block:: python blocks = [ [A, B, 1, 1], [C, D, 0, 1], ] # would return the list below ...
5bdde168ef9309ff93d478c6e6776d250c832c37
20,916
import csv def load_ground_truth(data_path): """Load ground truth files of FSD50K Args: data_path (str): Path to the ground truth file Returns: * ground_truth_dict (dict): ground truth dict of the clips in the input split * clip_ids (list): list of clip ids of the input split ...
84d1e524fc2e3a780d162b7626d459ff4f3aced8
20,917
import os def realcwd(): """!Returns the current working directory, expanding any symbolic links.""" return os.path.realpath(os.getcwd())
7036fe6301fcd1ade2572db3e06533a9b7054991
20,918
def server(app): """Return a test client to `app`.""" client = app.test_client() return client
aeef67904f95d28356989ddbde49a43378fa096f
20,920
def middle(a): """Returns a (list) without the first and last element""" return a[1:-1]
112854e009afaf6080363f3f1b3df944b4739ede
20,922
import subprocess def check_output(*args): """A wrapper for subprocess.check_output() to handle differences in python 2 and 3. Returns a string. """ result = subprocess.check_output(*args) if isinstance(result, bytes): return result.decode('utf-8') else: return result
d53b5696944545310ae1254209cee9b2c93679a7
20,923
import numpy def get_fill_value(dtype): """ Returns string fill value based on data type. :param dtype: data type for variable :type dtype: str """ if dtype == 'a25': return '' elif dtype == 'i8': return -9999 else: return numpy.NaN
b4d052829597357aa9300d7d0b168f74335b0663
20,924
def alpha_over_k_rho_func(rho, rhoV, l, lV): """Inverse function for alpha/k from J/k""" aoK = rho / (l - rho * (l - 1)) partial_rho = aoK**2 * l / rho**2 partial_l = - aoK**2 * (1 - rho) / rho aoKV = partial_rho**2 * rhoV + partial_l**2 * lV return [aoK, aoKV]
97c73db83ebc82f638663197e56c2c8ffdac5154
20,925
import unicodedata import re def ascii_uppercase_alphanum(s, decoding='utf-8'): """Convert a string to alphanumeric ASCII uppercase characters.""" if type(s) is float: return s nfkd = unicodedata.normalize('NFKD', s) only_ascii = nfkd.encode('ASCII', 'ignore') upper = only_ascii.upper() ...
3694581fae9935a332e2929364e96eb054b3e749
20,926
def build_db_query(fields_names, field_values): """ method builds query dictionary by zipping together DB field names with the field values """ if not isinstance(fields_names, (list, tuple)): fields_names = [fields_names] if not isinstance(field_values, (list, tuple)): field_values = [field_...
0d90067488aa46c7836fbb644ebb5aca47e14e50
20,927
def _add_tags(tags, additions): """ In all tags list, add tags in additions if not already present. """ for tag in additions: if tag not in tags: tags.append(tag) return tags
234e6cabd478bcfc95bb3d8f6118e0f0307fabc4
20,929
def get_cmdb_detail(cmdb_details): """ Iterate over CMDB details from response and convert them into RiskSense context. :param cmdb_details: CMDB details from response :return: List of CMDB elements which includes required fields from resp. """ return [{ 'Order': cmdb_detail.get('order'...
aa2750b3754d2a776d847cfa22ff2b84f53bb351
20,932
def increase_around(octos, x, y): """Increase all around with one""" for _x in range(x - 1, x + 2): for _y in range(y - 1, y + 2): if ( _x >= 0 and _x < len(octos[1]) and _y >= 0 and _y < len(octos) and (_x != x ...
4a9520280f54b5f401b8d3c8e171bca805af59bb
20,933
def predictRecallMode(prior, tnow): """Mode of the immediate recall probability. Same arguments as `ebisu.predictRecall`, see that docstring for details. A returned value of 0 or 1 may indicate divergence. """ # [1] Mathematica: `Solve[ D[p**((a-t)/t) * (1-p**(1/t))**(b-1), p] == 0, p]` alpha, beta, t = pr...
bcf1c7194e9b647ebe882151e9ad65b9a511a878
20,934
def sqr(num): """ Computes the square of its argument. :param num: number :return: number """ return num*num
cb16d5638afeff0061415e45467b5fd4e644951f
20,935
def cidr_to_common(cidr_mask): """Function that returns a common mask (Ex: 255.255.255.0) for a given input CIDR mask (Ex: 24)""" cidrtocommon = { 1: "128.0.0.0", 2: "192.0.0.0", 3: "224.0.0.0", 4: "240.0.0.0", 5: "248.0.0.0", 6: "252.0.0.0", 7: "25...
9357592b86c812d632edcbe376d55994c58174b6
20,936
def color_to_16(color): """Convert color into ANSI 16-color format. """ if color.r == color.g == color.b == 0: return 0 bright = sum((color.r, color.g, color.b)) >= 127 * 3 r = 1 if color.r > 63 else 0 g = 1 if color.g > 63 else 0 b = 1 if color.b > 63 else 0 return (r | (g << 1)...
977f405dda37d67ade56ac191d92a217d356d4dc
20,937
import os def parse_file_entry(entry, file_format): """parses a file entry given the format""" # smbmap example: # host:10.1.1.1, privs:READ_ONLY, isDir:f, name:dir1\dir2\file1234.txt, fileSize:1698, date:Tue Feb 14 19:43:46 2017 # host:10.1.1.1, privs:READ_ONLY, isDir:d, name:dir1\dir2\dir3, fileSize...
dead170b10135ae896a90b1a5f8940d1c81d8a02
20,938
def pluralize(n, s, ss=None): """Make a word plural (in English)""" if ss is None: ss = s + "s" if n == 1: return s else: return ss
1b24a513f1529666f8535a17482f1ce1b140d1ef
20,939
from typing import List def _get_mirror_repo(request) -> List[str]: """ Retrieves the list of all GIT repositories to be mirrored. Args: request: The pytest requests object from which to retrieve the marks. Returns: The list of GIT repositories to be mirrored. """ uris = request.conf...
bd0411ac9375ee1838b72cc103d13d0ae2e8abe8
20,940
def serialize_profile(user_profile): """ Serializes an user profile object. :param user_profile: user profile object :return: dictionary with the user profile info """ return { 'bio': user_profile.bio, 'description': user_profile.description, 'resume': user_profile.resume...
4eb1f88c197117c9dd31ab3090d541c0ae7b65bb
20,941
import os def find_repo_root(): """Find the root of the repo, which contains a .git folder """ path = os.getcwd() while ".git" not in set(os.listdir(path)) and path != "/": path = os.path.dirname(path) if path == "/": raise Exception("No repo found, stopping at /") return pa...
b389de605531be3218a49c44ac4ace36af5e4f0f
20,942
def get_model_data_by_ids(model, ids, return_data_dict): """ 通过id获取一条数据 :param model: :param ids: :param return_data_dict: 返回的data字段列表 :return: """ records = model.objects.filter(id__in=ids) if not records: return None # 查询成功 if records.count == 1: record = re...
9aa892691698bcd9f81b8db08a26df1145cddcf3
20,943
def get_points_to_next_level(current_level): """ returns the number of average points needed to advance to the next level """ if current_level == 1: return 50 elif current_level == 2: return 125 elif current_level == 3: return 225
229a681a242a7628a5f6597134480e026b77763d
20,947
def ensure_list(thing): """ Wrap ``thing`` in a list if it's a single str. Otherwise, return it unchanged. """ if isinstance(thing, str): return [thing] return thing
45ac322794627661c814b7905d6531aedd2a61b5
20,948
import time def get_cpu_usage(enode): """ This function reads /proc/stat file for enode and parses it to get cpu usage and calculate relative usage rate relative to a small time. :param topology.platforms.base.BaseNode enode: Engine node to communicate with. """ last_worktime = 0...
59d05b4a621e7c5e1f0954d31498e513bf12488d
20,949
import os def module_filename(module, filename): """ Return the full path to a specific file inside a module """ path, _ = os.path.split(module.__file__) return os.path.join(path, filename)
e49cdf8c86c762232e73dd4fd9c86a1f3793d228
20,950
def create_acc_ui_command(packer, main_on: bool, enabled: bool, stock_values): """ Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam assist status. Stock functionality is maintained by passing through unmodified signals. Frequency is 20Hz. """ values = { ...
2a0ab397b54d328e6af38701caec002ca7fa99ac
20,951
import re def cleanup_tex_line(text): """Format line of tex e.g. replace multiple spaces with one""" # replace multiple spaces with 1 space (simplifies matching) if text == r"\n": return "" text = re.sub(r" {2,}", " ", text) text = text.rstrip() return text
0304477aafa447a3aad58da116cac2590437351d
20,952
import json def humanreadable_from_report_contents(contents): """Make the selected contents pulled from a report suitable for war room output Parameters ---------- contents : dict Contents selected from an ANYRUN report for Demisto output. Returns ------- dict Contents fo...
852be1990fff7832ff73f1853b756ddf1b34ec33
20,953
from typing import Tuple def fscanf(string: str) -> Tuple[str, str]: """ Función para leer parcialmente una línea. Esta función permite hacer una equivalencia más directa con la función 'fscanf' de C y no es necesario que la reescriban. Ejemplo de uso: a, b = fscanf("hola como estas") ...
c731674951946f33185fe159e08154b8f6df455a
20,954
def get_id(mention): """ Get the ID out of a mention as a string :param mention: String of just the mention :return: Snowflake ID as an int """ return int(mention.strip("<@#&!>"))
eb7dcfd8ae5752318e646218219c8faaf6348d19
20,956
def get_cost(hours): """ Returns hourly cost of parking lot based in the hours stayed in the parking lot :param hours: :return: """ if 0 < hours < 3: return 15 if 2 < hours < 7: return 25.5 if 6 < hours < 11: return 30 if hours > 10: return 37.7
e78fdced1a7ed647128cead7abc55770cf4483b0
20,959
import math def to_deg_min_sec(DecDegrees): """ Converts from decimal (binary float) degrees to: Degrees, Minutes, Seconds """ degrees, remainder = divmod(round(abs(DecDegrees), 9), 1) minutes, remainder = divmod(round(remainder * 60, 9), 1) # float to preserve -0.0 return math.copy...
52ac22a4d504c264260a812d43b7bf850c7f1595
20,962
import re def cleanId(input_id) : """ filter id so that it's safe to use as a pyflow indentifier """ return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id)
a53b93945754dec2c79039e9fe2720f3472248cc
20,963
import torch def predict(model, dataloader, labeldict): """ Predict the labels of an unlabelled test set with a pretrained model. Args: model: The torch module which must be used to make predictions. dataloader: A DataLoader object to iterate over some dataset. labeldict: A dictio...
c2e28c9dacca715720186c2ce01735cb4a7c2e38
20,964
def solution(capacity, items): # O(M * N) """ Given the capacity of the knapsack and items specified by weights and values, return the maximum summarized value of the items that can be fit in the knapsack. Example: capacity = 5, items(value, weight) = [(...
95f14a13b873877e8596069421476657018a5b7d
20,965
def _decision_list_nodes(children_right, children_left, idx=0, elders=list()): """ recursive function to do the inner operations in decision_path_nodes """ if children_left[idx] == -1: # leaf node n = len(elders) + 1 return [[idx]*n, elders + [idx]] else: c_left = _decision_...
33da6d23687d5f43402fbbc7df9196c981dca2cb
20,966
def target_fasta(tmp_path): """A simple target FASTA""" out_file = tmp_path / "target.fasta" with open(out_file, "w+") as fasta_ref: fasta_ref.write( ">wf|target1\n" "MABCDEFGHIJKLMNOPQRSTUVWXYZKAAAAABRAAABKAAB\n" ">wf|target2\n" "MZYXWVUTSRQPONMLKJIHG...
a0aead0b8aab69d3d9b2805b26fcad94ea9e5b8d
20,967
import re def _parse_result_values_from_output(metric, text): # pragma: no cover """Attempts to parse a metric in the format RESULT <graph>: <trace>= ... Args: metric: The metric as a list of [<trace>, <value>] string pairs. text: The text to parse the metric values from. Returns: A list of float...
67e97e2d03f74de3c79949725d42bf896466719e
20,968
def simple_mutation(image, base_image, sequence, calculate_error, palette, draw): """Computes the effects of a simple mutation. :param image: The image to draw the gene on. :param base_image: The original image to compare to. :param sequence: The gene sequence. :param calculate_error: The error met...
7f39cfcf877f55b4f3072ac1762470d7d38d33e7
20,969
import time def should_refresh_time(event_time, last_refresh_time, refresh_after_mins=60): """ The clock on the PyPortal drifts, and should be refreshed from the internet periodically for accuracy. We want to refresh the local time when: - The local time isn't set - After refresh_after_mins h...
a785714b5efeafe8250f4fe841d2d0e085ba197f
20,973
def map_skip_none(fn, it): """ emulate list(map(fn, it)) but leave None as it is. """ ret = [] for x in it: if x is None: ret.append(None) else: ret.append(fn(x)) return ret
296110c3d416d1653411da7c3fbce02b280078b1
20,974
def get_exception_message(ex): """Build exception message with details. """ template = "{0}: {1!r}" return template.format(type(ex).__name__, ex.args)
5022f375353db51ddfd05e034bc9cdc37249475a
20,976
def partial(f, args): """ Arguments: - `f`: a function of a value tuple to values - `args`: a tuple of arguments for f, may contain None elements """ if None in args: return None else: return f(*args)
ca592641041fffb44c9830b8d0c5e276f0bd81ec
20,978
import random def choosing_a_new_index(num_v, tested_values, length): """ If there're still vehicles the function hasn't tried inserting our element into, the function gets a new id to give it a try. If it's not the case, the function just returns the current id. """ new_num_v = num_v ...
7ca461495c39e4b55874e2d8f8fda76f8bcda29e
20,979
def shoot_error(x_target, x): """ calculates the error of a shoot on the target at x_target. :param x_target: position of the target :param x: state array holding the complete history of the shoot :return: error. A positive sign of the error indicates that the shoot has been to far, a negative sign ...
d03e07cb4779cedbf485e4ebd55869c5f9471d29
20,981
def parse_mapholder_div(tree): """Parses the HTML for a 'mapholder' class. Parameter --------- tree: lxml.html.HtmlElement The section in the HTML page for each map. This is normally <div class="mapholder"> ... </div> Return ------ Dictionary object with the specified f...
6f211eb5341de1d59e9043d2cc9c4b0340a8bd50
20,982
import logging def get_most_frequent_response(input_statement, response_list): """ 返回频率最高的回复 :param input_statement: 输入语句 :param response_list: 回复列表 :return: 回复结果 """ matching_response = None occurrence_count = -1 logger = logging.getLogger(__name__) logger.info(u'Selecting re...
16ccc1bc59edf100e536aa6c89dc635ad9d02358
20,984
def _load_model_weights(model, path, framework): """Backend for loading the model.""" if framework.lower() == 'keras': try: model.load_weights(path) except OSError: raise FileNotFoundError("{} doesn't exist.".format(path)) elif framework.lower() in ['torch', 'pytorc...
9f2b1abeb15a8727711104230b0735134eb13d79
20,985
import os import stat def getFileSize(filepath): """ Get the size of the file in bytes. """ return os.stat(filepath)[stat.ST_SIZE]
08989dd219970c1357fb674c916ebe723d27b37b
20,986
from typing import Iterable def last_survivor(letters: str, coords: Iterable[int]) -> str: """ Removes from letters the chars at coords index. Returns the first survivor letter. """ arr = list(letters) for idx in coords: del arr[idx] return arr[0]
21d2ddb7bfb43a8df5eca390b1154a1a863ed373
20,987
def pred_sql(col, val): """ Generates SQL for equality predicate. Args: col: predicate restricts this column val: filter column using this value Returns: predicate as SQL string (escaped) """ esc_val = str(val).replace("'", r"''") return f"{col}='{esc_val}'"
16dd042820fc0cef3139320e204646c3c678bd0e
20,988
import random def block(n_subjects, n_groups, block_length, seed=None): """ Create a randomization list using block randomization. Block randomization takes blocks of group labels of length `block_length`, shuffles them and adds them to the randomization list. This is done to prevent long runs of a ...
d42601d3861f86f7eac4c7525d78e1b4dd4ef81a
20,990
def get_number_features(dict_features): """Count the total number of features based on input parameters of each feature Parameters ---------- dict_features : dict Dictionary with features settings Returns ------- int Feature vector size """ number_features = 0 f...
6f81c359cfee77896cb8e4334aa23cf977aaca5a
20,991
def save_gpf(df, output_file): """ Write a socet gpf file from a gpf-defined pandas dataframe Parameters ---------- df : pd.DataFrame Pandas DataFrame output_file : str path to the output data file Returns ------- int : success ...
fb551a8e5a3861939bd40cbfcb5a82bd6cc88161
20,993
def next_node_of_edge(node, edge): """ Return the node of the edge that is not the input node. :param node: current node :type node: Node object :param edge: current edge :type edge: Edge object :return: next node of the edge :rtype: Node object """ # If the input node ...
2fd226802ba504bfa7f950d0c69defc79a45e049
20,994
def un_human_readable(value_str): """ Takes the output of IOR's HumanReadable() and converts it back to a byte value """ args = value_str.strip().split() if len(args) == 1 and args[0].endswith("%"): return float(args[0].rstrip("%")) elif len(args) != 2: raise Exception("Inval...
a7f62aef57f621877185d431783a386b4a6f7af6
20,996
def clip_in_blacket(line, bracket='('): """ [Functions] get sentence in most outer bracket. """ if bracket == '(': return line[line.find('(') + 1: line.rfind(')')] elif bracket == '[': return line[line.find('[') + 1: line.rfind(']')] elif bracket == '{': return line[l...
0bf48f9e1ea54c417ab06ead6fd218c7274bcca3
20,997
def add_transport_costs(element, transport, quantities): """Adds the transport cost for the crop to the production cost. elements are of the form (crop, greenhouse, mapping, cost), the cost only corresponds to the production cost. Return the same format, but including the transport cost. """ crop = element...
4de3a64018a5b1e1b9402eedd970e75619ce5f00
20,999
import logging def logging_wrapper(level, path): """Producing log message :param level: Logging level. Default=3. 1-5 scale determining the logging messages to save. 5 is only CRITICAL, 1 is all message :param path: Default=logs/{scipt_name}_{unix_time}.log Path to the d...
236357f295dea3d0dcb91a0d8834e916fd952158
21,000
def collective_result(results, limit): """Combines many results in the range [0, 1] into a single value in the range [0, 1]. A limit can be specified for a value that is regarded as certain enough. If any certain results are found, the mean of all certain results is returned, otherwise the mean of a...
105e4199c8b935be9d3bbb2d796feccbec885e17
21,001
def replace(tokens): """ exec str in globals(), locals() -> exec(str, globals(), locals()) """ return tokens[0] + "exec(" + ", ".join(tokens[1:]) + ")"
895ea10b24d0b77a7a7b6e6278e03e94fb424ce7
21,003
from typing import List def consec_badpixels(bad_pixels: List[List[int]]) -> bool: """Check for consecutive bad pixels in the same nod. Consecutive in in axis=1 for the same axis=0 value. parameters ---------- bad_pixels: list of list of ints List of index locations of bad pixels [nod, p...
a14e994151c12fa04dca4ce5f6e143d652264dc7
21,004
def str_2_sec(timein): """ Convert time in days / hrs / mins etc to total seconds used) """ splitdays = timein.split('-') if len(splitdays) == 2: # Have list of days and time secs = 24*60*60*int(splitdays[0]) + str_2_sec(splitdays[1]) elif len(splitdays) == 1: # Just have...
460864d37fabcdb73862fe84b7c359a089e25496
21,006
def dfs(capacity, flow, visit, vertices, idx, sink, current_flow = 1 << 63): """ Depth First Search implementation for Ford-Fulkerson algorithm. """ # DFS function for ford_fulkerson algorithm. if idx == sink: return current_flow visit[idx] = True for nxt in range(vertices): ...
0d719fd8004704ad6780882b974688f8a9afd9e7
21,007
def format_pfrule(pfrule): """Render port forwarding option.""" format_str = '-{0.pf_type} {binding}'.format return format_str(pfrule, binding=pfrule.binding) if pfrule else ''
a8e7bec5818586aac945c48ff5553f38f5c444d6
21,008