content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def search_by_pattern(pattern, limit=20): """Perform a search for pattern.""" pattern_ = normalize_pattern(pattern) db = get_db() results = db.execute( """ SELECT json FROM places WHERE document MATCH ? ORDER BY rank DESC LIMIT ?; """, (fts_pattern...
467b85c850bb27ac1ed9a6e7fff6bb969a5f84e0
3,650,091
def gcd(a, b): """Greatest common divisor""" return _gcd_internal(abs(a), abs(b))
886d366893a0215ccf0208af56c9c45037ad9549
3,650,092
def exp_create_database(db_name, demo, lang, user_password='admin', login='admin', country_code=None, phone=None): """ Similar to exp_create but blocking.""" _logger.info('Create database `%s`.', db_name) _create_empty_database(db_name) _initialize_db(id, db_name, demo, lang, user_password, login, count...
b1d956628d864e0aa3998c00fd6a0b7cfb3ba411
3,650,093
def fix_cr(data): """Cosmic ray fixing function. Args: data (:class:`numpy.ndarray`): Input image data. Returns: :class:`numpy.dtype`: Fixed image data. """ m = data.mean(dtype=np.float64) s = data.std(dtype=np.float64) _mask = data > m + 3.*s if _mask.sum()>0: ...
40702ccc9400f4ba5f10cad1f376b83eac487876
3,650,094
def iou(box1, box2, iouType='segm'): """Compute the Intersection-Over-Union of two given boxes. or the Intersection-Over box2. Args: box1: array of 4 elements [cx, cy, width, height]. box2: same as above iouType: The kind of intersection it will compute. 'keypoints' is for intersectio...
42ef4689c977e4ccbdbb987ff3ae63b265d3c42d
3,650,095
def transform_color(color1, color2, skipR=1, skipG=1, skipB=1): """ transform_color(color1, color2, skipR=1, skipG=1, skipB=1) This function takes 2 color1 and color2 RGB color arguments, and then returns a list of colors in-between the color1 and color2 eg- tj.transform_color([0,0,0],[10,10,20]) returns a list:...
5f04daa951c59b0445387b2dc988ab7efb98aff4
3,650,096
def sandwich(func): """Write a decorator that prints UPPER_SLICE and LOWE_SLICE before and after calling the function (func) that is passed in (@wraps is to preserve the original func's docstring) """ @wraps(func) def wrapped(*args, **kwargs): print(UPPER_SLICE) fun...
167e1a753b7ba1f0d42732e12c5b37e0b0670f1b
3,650,097
def as_dict(bdb_path, compact=True): """Get the state of a minter BerkeleyDB as a dict. Only the fields used by EZID are included. """ with nog.bdb_wrapper.BdbWrapper(bdb_path, dry_run=False) as w: return w.as_dict(compact)
dab02d671c099bd726839dc40167632cab812015
3,650,098
import json def main() -> int: """ Builds/updates aircraft.json codes """ craft = {} for line in AIRCRAFT_PATH.open().readlines(): code, _, name = line.strip().split("\t") if code not in craft: craft[code] = name json.dump(craft, OUTPUT_PATH.open("w")) return 0
e35bc5b5f8be2452d60b73b891bc5756931b18aa
3,650,100
def bootstrap_mean(x, alpha=0.05, b=1000): """ Calculate bootstrap 1-alpha percentile CI of the mean from a sample x Parameters ---------- x : 1d array alpha : float Confidence interval is defined as the b : int The number of bootstrap samples Returns ------- lb...
10b240f97196c7e2922574230a675d7e7c89038e
3,650,101
def _penalize_token(log_probs, token_id, penalty=-1e7): """Penalize token probabilities.""" depth = log_probs.shape[-1] penalty = tf.one_hot([token_id], depth, on_value=tf.cast(penalty, log_probs.dtype)) return log_probs + penalty
af8bf807438ff7ae96be0c5be0ec37fdbf81a5d1
3,650,102
from typing import Iterable def minimize(function, vs, explicit=True, num_correction_pairs=10, tolerance=1e-05, x_tolerance=0, f_relative_tolerance=1e7, initial_inverse_hessian_estimate=None, max_iterations=1000, ...
22659e37afa29fde75ba344e0054207582e44fb3
3,650,104
def variation_reliability(flow, gamma=1): """ Calculates the flow variation reliability Parameters ---------- flow: numpy array flow values gamma: float, optional soft threshold Returns ------- variation reliability map (0 less reliable, 1 reliable) """ #comput...
cbdc4ab49402239e5e0fd484e5bf7bceaca383d4
3,650,105
def get_means(df: pd.DataFrame, *, matching_sides: bool, matching_roots: bool) -> pd.Series: """ Calculates mean conditional probabilities from a given co-occurrence table with filters restricting for matching sides and roots. Args: df: The co-occurrences. matching_sides: ...
e6318fe4d284b134a8b655003b074ec554abca82
3,650,108
from typing import Dict import math def main( pathname: str, sheetname: str='Sheet1', min_row: int=None, max_row: int=None, min_col: int=None, max_col: int=None, openpyxl_kwargs: Dict=None ): """ main is the main function. It accepts details about a excel sheet and returns an HTML ...
b44884bf84909b3bb76553aff247df6a961f3289
3,650,109
def get_go_module_path(package): """assumption: package name starts with <host>/org/repo""" return "/".join(package.split("/")[3:])
1443d59391a36c7b9ba1d72ade9fd51f11cc1cc3
3,650,110
def get_hports(obj, *args, **kwargs): """ get_hports(obj, ...) Get hierarchical references to ports *within* an object. Parameters ---------- obj : object, Iterable - required The object or objects associated with this query. Queries return a collection of objects associated with the ...
f4a18a43018c10ef5860e974ed1d3eaf0ab73ac3
3,650,111
def binary_cross_entropy(preds, targets, name=None): """Computes binary cross entropy given `preds`. For brevity, let `x = `, `z = targets`. The logistic loss is loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i])) Args: preds: A `Tensor` of type `float32` or `float64`. ...
b56e8bbaf16c688ebeb8be05b15a8c63745def3d
3,650,113
from typing import Optional def get_organization(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrganizationResult: """ Use this data source to retrieve basic information about a GitHub Organization. ## Example Usage ```python import ...
f534525be6bc7bc7e6e3c80be9b94543b327a8e7
3,650,114
import array def numerator_LGG(mfld_dim: int, ambient_dim: array, vol: array, epsilon: array, prob: float) -> array: # our theory """ Theoretical M * epsilon^2 / K, our formula Parameters ---------- mfld_dim K, dimen...
b8f22f269cfb5a42ebb60118e6715c812d18ef73
3,650,115
from typing import OrderedDict def group_nodes(node_list, tree_height): """ Groups a list of nodes. """ dict = OrderedDict() for node in node_list: nodelist = _make_node_list(GroupNode(node), tree_height) if nodelist.get_name() not in dict: dict[nodelist.get_name()] = n...
50dc5f0356bed740e8b88e8bc05df01057fab29d
3,650,116
def power_over_line_rule_pos_rule(m, i, j, t): """ If decision variable m.var_x[i, j, t] is set to TRUE, the positive power over the line var_power_over_line is limited by power_line_limit :param m: complete pyomo model :type m: pyomo model :param i: startnode index of set_edge :type i: int...
c4d5a70f4cc2a67a45f11b3072fcb98c9f54e4e2
3,650,117
def join_tiles(tiles): """Reconstructs the image from tiles.""" return np.concatenate(np.concatenate(tiles, 1), 1)
559b88d8bdd42662961669050d29b6583dfbc706
3,650,118
def solve2(lines, max_total): """Solve the problem for Part 2.""" points = parse_points(lines) xmin = min([p[0] for p in points]) xmax = max([p[0] for p in points]) ymin = min([p[1] for p in points]) ymax = max([p[1] for p in points]) size = 0 for x in range(xmin, xmax+1): for y ...
1e743f736f92f60df960d4946f89ae222054d4aa
3,650,120
import random import json def main(): """ 関数の実行を行う関数。 Return: """ def shuffle_dict(d): """ 辞書(のキー)の順番をランダムにする Args: d: 順番をランダムにしたい辞書。 Return: dの順番をランダムにしたもの """ keys = list(d.keys()) random.shuffle(keys) re...
eca402495d47c8d856568c2271f3de92b1ca2d4f
3,650,121
def scheme_load(*args): """Load a Scheme source file. ARGS should be of the form (SYM, ENV) or (SYM, QUIET, ENV). The file named SYM is loaded in environment ENV, with verbosity determined by QUIET (default true).""" if not (2 <= len(args) <= 3): expressions = args[:-1] raise SchemeError...
d41bb38e60d5e82022c0857629937774c6b180d5
3,650,122
import torch from typing import Optional from typing import Tuple def mask2idx( mask: torch.Tensor, max_length: Optional[int] = None, padding_value: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor]: """ E.g. input a tensor [[T T F F], [T T T F], [F F F T]] with padding value -1, ret...
b0900aadd14c9eff8af4fcf8e9043127d2a3562c
3,650,123
def generate_paths(data, path=''): """Iterate the json schema file and generate a list of all of the XPath-like expression for each primitive value. An asterisk * represents an array of items.""" paths = [] if isinstance(data, dict): if len(data) == 0: paths.append(f'{path}') ...
367f244b44c254b077907ff8b219186bd820fccd
3,650,124
def enable_heater_shaker_python_api() -> bool: """Get whether to use the Heater-Shaker python API.""" return advs.get_setting_with_env_overload("enableHeaterShakerPAPI")
f849413c072034a15f0242e4b65dd36753a8d6f1
3,650,128
def solidityKeccak(abi_types, values): """ Executes keccak256 exactly as Solidity does. Takes list of abi_types as inputs -- `[uint24, int8[], bool]` and list of corresponding values -- `[20, [-1, 5, 0], True]` """ if len(abi_types) != len(values): raise ValueError( "Length ...
2e31d05404b204a233694f14e808c78e96e67aed
3,650,129
def run_fib_recursive_mathy_cached(n): """Return Fibonacci sequence with length "n" using "fib_recursive_mathy_cached". Args: n: The length of the sequence to return. Returns: A list containing the Fibonacci sequence. """ return [fib_recursive_mathy_cached(i + 1) for i in range...
7cdd01ab747bccbd95dbb886e680c9214c2f883d
3,650,131
def binning(LLRs_per_window,info,num_of_bins): """ Genomic windows are distributed into bins. The LLRs in a genomic windows are regarded as samples of a random variable. Within each bin, we calculate the mean and population standard deviation of the mean of random variables. The boundaries of the bins ...
bc872aa9d32545a91d9854d83ba2efb238cbfc02
3,650,132
from typing import Optional from typing import List def conj(node: BaseNode, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None) -> BaseNode: """Conjugate a `node`. Args: node: A `BaseNode`. name: Optional name to give the new node. axis_names: Optional list of nam...
9baffa5ad00289b0f44ad4953dc12931eccb8ed9
3,650,133
from typing import Union import torch def f1( predictions: Union[list, np.array, torch.Tensor], labels: Union[list, np.array, torch.Tensor], ): """Calculate F1 score for binary classification.""" return f1_score(y_true=labels, y_pred=predictions)
e35fa02281351a2c2003982fc6450aa4d8e5561b
3,650,134
def length(v, squared=False, out=None, dtype=None): """Get the length of a vector. Parameters ---------- v : array_like Vector to normalize, can be Nx2, Nx3, or Nx4. If a 2D array is specified, rows are treated as separate vectors. squared : bool, optional If ``True`` the sq...
16caea4730b7dfd7cfcc71d253ee1fc7691fe05d
3,650,135
def generateUniqueId(): """ Generates a unique ID each time it is invoked. Returns ------- string uniqueId Examples -------- >>> from arch.api import session >>> session.generateUniqueId() """ return RuntimeInstance.SESSION.generateUniqueId()
f5dd066c1f9e6670b1e0949c890d5abc9931142a
3,650,136
def order_rep(dumper, data): """ YAML Dumper to represent OrderedDict """ return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items(), flow_style=False)
6b455d49cd5702324f4b1e825dabb4af90734730
3,650,137
def match_format( format_this: spec.BinaryInteger, like_this: spec.BinaryInteger, match_pad: bool = False, ) -> spec.BinaryInteger: """ will only match left pads, because pad size cannot be reliably determined """ output_format = get_binary_format(like_this) output = convert(data=forma...
0a9638cbe5e522b1c7dc9ee316e559f9238b9abe
3,650,138
def parse_nonterm_6_elems(expr_list, idx): """ Try to parse a non-terminal node from six elements of {expr_list}, starting from {idx}. Return the new expression list on success, None on error. """ (it_a, it_b, it_c, it_d, it_e, it_f) = expr_list[idx : idx + 6] # Match against and_n. if ...
1c82d6b0654cf15c5aafec2c08e92c86cb5a4543
3,650,139
def make1d(u, v, num_cols=224): """Make a 2D image index linear. """ return (u * num_cols + v).astype("int")
1f37c7ae06071ce641561eadc1d0a42a0b74508d
3,650,140
def xkcd(scale=1, length=100, randomness=2): """ Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will only have effect on things drawn after this function is called. For best results, the "Humor Sans" font should be installed: it is not included with Matplotlib. Parameters...
1ce7aed60b2b67febb1658e98f14434005f3434a
3,650,141
def team_size(data): """ Computes team size of each paper by taking the number of authors in 'authors' Input: - df: dataframe (dataset); or just the 'authors' column [pandas dataframe] Output: - team: vector of team_size for each paper of the given...
76a5aafe90cf63fb0506525e566ca7759d0e27ce
3,650,142
from datetime import datetime def header_to_date(header): """ return the initial date based on the header of an ascii file""" try: starttime = datetime.strptime(header[2], '%Y%m%d_%H%M') except ValueError: try: starttime = datetime.strptime( header[2] + '_' + he...
3e2757ae39a2a9008a5f0fb8cd8fe031770c83ad
3,650,143
def PhenylAlanineCenterNormal(residue): """ Phenylalanine """ PHE_ATOMS = ["CG", "CD1", "CD2", "CE1", "CE2", "CZ"] return RingCenterNormal(residue, PHE_ATOMS)
4d96c7fe14bd411749136cf1569f32bd1c01679d
3,650,144
def diamBiasK(diam, B, Kexcess, RshellRstar=2.5): """ diameter bias (>1) due to the presence of a shell only works for scalar diam, B and Kexcess validity: Kexcess>0 and Kexcess<0.1 and B*diam <~ 500 return 1 if Kexcess <= 0 """ global __biasData, KLUDGE d = np.abs(__biasData['Rshell/...
6754ee70c64b2028cd5b72d3331e65bb64ea53b4
3,650,148
def interpolate_poses_from_samples(time_stamped_poses, samples): """ Interpolate time stamped poses at the time stamps provided in samples. The poses are expected in the following format: [timestamp [s], x [m], y [m], z [m], qx, qy, qz, qw] We apply linear interpolation to the position and use SLERP for ...
3131fe895a53b7d6c262930c635ce8cfa1c277f2
3,650,149
def test_add_client(case, client_name, client=None, client_id=None, duplicate_client=None, check_errors=False, log_checker=None): """ UC MEMBER_47 main test method. Tries to add a new client to a security server and check logs if ssh_host is set. :param case: MainController object ...
0b15ee41c8a61c0602e89e59a6343e67c6dc712f
3,650,150
from typing import List def get_data_unit_labels(data_unit: DataUnit) -> List[Attributes]: """ Extract important information from data_unit. That is, get only bounding_boxes and associated classifications. Args: data_unit: The data unit to extract information from. Returns: list of pairs ...
36577b13713258fe1542c9bfc377a469ed5d6fd6
3,650,151
def calc_4points_bezier_path(svec, syaw, spitch, evec, eyaw, epitch, offset, n_points=100): """ Compute control points and path given start and end position. :param sx: (float) x-coordinate of the starting point :param sy: (float) y-coordinate of the starting point :param syaw: (float) yaw angle at...
455225b10c034895c32329bc14ce6dc384f5e0b3
3,650,152
import copy def permutationwithparity(n): """Returns a list of all permutation of n integers, with its first element being the parity""" if (n == 1): result = [[1,1]] return result else: result = permutationwithparity(n-1) newresult = [] for shorterpermutation in result: ...
218b728c2118a8cca98c019dff036e0ae2593974
3,650,153
from typing import List import torch import logging def _train_model(model: BertForValueExtraction, optimizer, scheduler, train_data_loader, val_data_loader) -> List[int]: """ Main method to train & evaluate model. :param model: BertForValueExtraction object :param optimizer: optimizer :param sch...
fbf5a588d9da24f72c0955c767f454297d91e74d
3,650,154
def mass_at_two_by_counting_mod_power(self, k): """ Computes the local mass at `p=2` assuming that it's stable `(mod 2^k)`. Note: This is **way** too slow to be useful, even when k=1!!! TO DO: Remove this routine, or try to compile it! INPUT: k -- an integer >= 1 OUTPUT: a r...
35f85dd32e3c81a4921c5d5a87ab4cdc13e8ae46
3,650,155
import logging def get_paginiation_data(first_pagination_url, family, cazy_home, args, session): """Parse the first paginiation page and retrieve URLs to all pagination page for the Family. :param first_pagination_url: str, URL to the fist page of the family :param family: Family class instance, represen...
89cdd6e0d333cc69f0b92c202b6f0d4257849382
3,650,156
def gravitationalPotentialEnergy(mass, gravity, y): """1 J = 1 N*m = 1 Kg*m**2/s**2 Variables: m=mass g=gravity constant y=height Usage: Energy stored by springs""" U = mass*gravity*y return U
f4fcfc9e7ddac8b246b2200e3886b79f6706936e
3,650,157
def to_list(obj): """List Converter Takes any object and converts it to a `list`. If the object is already a `list` it is just returned, If the object is None an empty `list` is returned, Else a `list` is created with the object as it's first element. Args: obj (any object): the object...
3ca373867ea3c30edcf7267bba69ef2ee3c7722e
3,650,159
from molsysmt.basic import select, extract def remove(molecular_system, selection=None, frame_indices=None, to_form=None, syntaxis='MolSysMT'): """remove(item, selection=None, frame_indices=None, syntaxis='MolSysMT') Remove atoms or frames from the molecular model. Paragraph with detailed explanation. ...
a2232e6226f76df6760eef59aab0f31edf7a75ec
3,650,160
def macd_cross_func_pd(data): """ 神一样的指标:MACD """ if (ST.VERBOSE in data.columns): print('Phase macd_cross_func', QA_util_timestamp_to_str()) MACD = QA.QA_indicator_MACD(data) MACD_CROSS = pd.DataFrame(columns=[ST.MACD_CROSS, FLD.MACD_CROSS_JX...
d7c970efc931a3f1f2c25e51cf8e55e630eb37ad
3,650,161
import json def jsonp_response(data, callback="f", status=200, serializer=None): """ Returns an HttpResponse object containing JSON serialized data, wrapped in a JSONP callback. The mime-type is set to application/x-javascript, and the charset to UTF-8. """ val = json.dumps(data, default=seri...
3ac71358043184b84b2f1f610a852b0b587d158d
3,650,162
import collections def enhance_bonds(bond_dataframe, structure_dict): """Enhance the bonds dataframe by including derived information. Args: bond_dataframe: Pandas dataframe read from train.csv or test.csv. structure_dict: Output of :func:`make_structure_dict`, after running :func:`enhance_st...
46836576b6bec8e1ca9f5685185d0f379b9e63f6
3,650,163
import numbers def _tofloat(value): """Convert a parameter to float or float array""" if isiterable(value): try: value = np.asanyarray(value, dtype=np.float) except (TypeError, ValueError): # catch arrays with strings or user errors like different # types o...
796b03699cb3b1e201436b6eb61df0636318de14
3,650,164
import time import functools def sp2mgc(sp, order=20, alpha=0.35, gamma=-0.41, miniter=2, maxiter=30, criteria=0.001, otype=0, verbose=False): """ Accepts 1D or 2D one-sided spectrum (complex or real valued). If 2D, assumes time is axis 0. Returns mel generalized cepstral coefficients. ...
01e380ddf10c56c3c4b9d09726ac98aef58715ca
3,650,165
def has_prefix(sub_s): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ for key, val in word_dic.items(): if key.startswith(sub_s): return True else: pass return False
b52937578d62d464df3131374a5dc0bdca735807
3,650,166
def _package_data(vec_f_image, vec_f_imageBscan3d, downscale_size, downscale_size_bscan, crop_size, num_octa, str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d, str_bscan_layer, dict_layer_order, dict_layer_order_bscan3d): """ Organizes the angio...
dfe9ed58bd25715948cfb09f069c76d2f844df3c
3,650,167
def apply_padding_by_last(list_of_lists): """ The same as applying pad_into_lists followed by carry_previous_over_none but takes a list of lists instead of events Args: lists_of_lists: list of lists with possibly different lengths Returns: lists of lists padded to the same length by ...
83316fedb46230665fc543d4a3961cb72692023b
3,650,168
def combine_patterns( *patterns: str, seperator: Expression = None, combine_all=False ) -> str: """ Intelligently combine following input patterns. Parameters ---------- patterns : The patterns to combine. seperator : The seperator to use. If None, the default seperator :dat...
1bcd703a183b72d88a8bfa7f1680754e0e3ee35e
3,650,169
from datetime import datetime async def utc_timediff(t1, t2): """ Calculate the absolute difference between two UTC time strings Parameters ---------- t1, t2 : str """ time1 = datetime.datetime.strptime(t1, timefmt) time2 = datetime.datetime.strptime(t2, timefmt) timedelt = time1...
ba0b406048467029f6d05d72898b534dd6309e45
3,650,170
def function(): """ >>> function() 'decorated function' """ return 'function'
46b892fb70b5672909d87efcf76ffd3f96f9cf7f
3,650,171
def load_stopwords(file_path): """ :param file_path: Stop word file path :return: Stop word list """ stopwords = [line.strip() for line in open(file_path, 'r', encoding='utf-8').readlines()] return stopwords
9cb6578b5cbc608bc72da7c4f363b4f84d0adbb7
3,650,172
def hello(): """Return a friendly HTTP greeting.""" return 'abc'
9acda65833bec5976c3e2f0ffa77df8a2a7537bf
3,650,173
def show_ip_ospf_route( enode, _shell='vtysh', _shell_args={ 'matches': None, 'newline': True, 'timeout': None, 'connection': None } ): """ Show ospf detail. This function runs the following vtysh command: :: # show ip ospf route :param dic...
0f80ef7a46211002141ea489459df6be78aeeb28
3,650,174
from typing import get_origin def attrs_classes( verb, typ, ctx, pre_hook="__json_pre_decode__", post_hook="__json_post_encode__", check="__json_check__", ): """ Handle an ``@attr.s`` or ``@dataclass`` decorated class. This rule also implements several hooks to handle complex case...
9db1f0a9ddefe1fb32d52331e158e8e2565b2697
3,650,175
import torch def delta(pricer, *, create_graph: bool = False, **kwargs) -> torch.Tensor: """Computes and returns the delta of a derivative. Args: pricer (callable): Pricing formula of a derivative. create_graph (bool): If True, graph of the derivative will be constructed, allowing...
88216117ba58afd68c88515210ad927a581eaf54
3,650,176
def formula_search(min_texts, max_texts, min_entries, max_entries): """Filter search results""" result = Cf.query.filter( Cf.n_entries >= (min_entries or MIN), Cf.n_entries <= (max_entries or MAX), Cf.unique_text >= (min_texts or MIN), Cf.unique_text <= (max_texts or MAX) )....
938cc7ea25c2fe1bcd240ad4b60e517295eebe7b
3,650,177
from datetime import datetime import uuid def versioneer(): """ Function used to generate a new version string when saving a new Service bundle. User can also override this function to get a customized version format """ date_string = datetime.now().strftime("%Y%m%d") random_hash = uuid.uuid4(...
7c5123d28e3bee45f2c9f7d519e830cf80e9fea8
3,650,178
import http def request_url(method, url): """Request the specific url and return data""" try: r = http.request(method, url) if r.status == 200: return r.data.decode('utf-8') else: raise Exception("Fail to {} data from {}".format(method, url)) except Exceptio...
9d25df49c9996364a9cb0195b90454378aefa5fd
3,650,179
def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf, labels=None): """ Rather than attempting to merge files that were modified on both branches, it marks them as unresolved. The resolve command must be used to resolve these conflicts.""" # for change/delete conflicts write out the changed versio...
4d90ff7296fa9042392c7ffe28034fbbf804614f
3,650,180
from typing import Callable def __noise_with_pdf(im_arr: np.ndarray, pdf: Callable, **kwargs) -> np.ndarray: """Apply noise to given image array using pdf function that generates random values.""" util.check_input(im_arr) im_arr = im_arr/255.0 noise = pdf(**kwargs, size=im_arr.shape) out_im = im_a...
d1b9f612f4490ac526c2a952c54ee03cbedc2139
3,650,181
def train_test_split(df, frac): """ Create a Train/Test split function for a dataframe and return both the Training and Testing sets. Frac refers to the percent of data you would like to set aside for training. """ frac = round(len(df)*frac) train = df[:frac] test = df[frac:] r...
8e233e017a261141f57f7b2bff9a527e275d2ed9
3,650,183
def load_special_config(config_filename, special_type, image_type='extent'): """Loads the google earth ("google"), science on a sphere ("sos"), or any other special type of image config. """ cfg = load_config(config_filename) # Promote the image type's keys cfg = _merge_keys(cfg, cfg[image_typ...
b3a38d4ea9e39e42685604b4f01c7dcfa8ee2cdd
3,650,184
def softmax_strategy_cim(attrs, inputs, out_type, target): """softmax cim strategy""" strategy = _op.OpStrategy() strategy.add_implementation( wrap_compute_softmax(topi.nn.softmax), wrap_topi_schedule(topi.cim.schedule_softmax), name="softmax.cim", ) return strategy
11c5e581d9ad2814068558bc9faf24f57f5acba3
3,650,185
def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2): """Get fully formed statements from a list of hashes. Parameters ---------- hash_list : list[int or str] A list of statement hashes. ev_limit : int or None Limit the amount of evidence returned per Statem...
26924f7d05b35b6655eb69989a32677edf1eedbf
3,650,186
def _is_in(val_set): """Check if a value is included in a set of values""" def inner(val, val_set): if val not in val_set: if isinstance(val_set, xrange): acceptable = "[%d-%d]" % (val_set[0], val_set[-1]) else: acceptable = "{%s}" % ", ".join(val_...
462afc33c73ae78bd62fa446f652a30492150643
3,650,187
def onebyone(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000, parallel=False, find_uncertainties=False, **args): """ **Convex optimization based on Brent's method** A strict assumption of one optimum between the parameter limits is used. The bounds are narrowed until...
86a12d7d7b738cc8ab7d8e65e3765e6b81f825b4
3,650,189
def test_data(): """Test data object for the main PlantCV module.""" return TestData()
f8b2dc49d460ddadcd74c89da1159274660ecdfb
3,650,191
def make_cmap(infile): """Call correct cmap function depending on file.""" cornames = ["coherence-cog.tif", "phsig.cor.geo.vrt", "topophase.cor.geo.vrt"] phsnames = ["unwrapped-phase-cog.tif", "filt_topophase.unw.geo.vrt"] if infile in cornames: cpt = make_coherence_cmap() elif infile in ph...
cd6408e1f8718b7073d1c5baa4e5a20ab8553720
3,650,193
def tail_correction(r, V, r_switch): """Apply a tail correction to a potential making it go to zero smoothly. Parameters ---------- r : np.ndarray, shape=(n_points,), dtype=float The radius values at which the potential is given. V : np.ndarray, shape=r.shape, dtype=float The potent...
50934031776cfd4d92ef7a05ca2e63c215518352
3,650,194
def process_input(input_string): """ >>> for i in range (0, 5): ... parent_node = Node(None) ... parent_node.random_tree(4) ... new_node = process_input(parent_node.get_test_string()) ... parent_node.compute_meta_value() - new_node.compute_meta_value() 0 0 0 0 ...
3cea94806034ebd3d95fdc7b5c8844d79698a684
3,650,195
def equiv_alpha(x,y): """check if two closed terms are equivalent module alpha conversion. for now, we assume the terms are closed """ if x == y: return True if il.is_lambda(x) and il.is_lambda(y): return x.body == il.substitute(y.body,zip(x.variables,y.variables)) return False ...
27cd246e217403320bd16580029eb1d7c0122e33
3,650,197
def delete(isamAppliance, file_id, check_mode=False, force=False): """ Clearing a common log file """ ret_obj = {'warnings': ''} try: ret_obj = get(isamAppliance, file_id, start=1, size=1) delete_required = True # Exception thrown if the file is empty # Check for Docker ...
7f27555eb33e489a59e1d9d1a7127713afd25d2f
3,650,198
def filter_imgs(df, properties = [], values = []): """Filters pandas dataframe according to properties and a range of values Input: df - Pandas dataframe properties - Array of column names to be filtered values - Array of tuples containing bounds for each filter Output: df - Filter...
cdc5c8bfef10fae60f48cee743df049581a0df04
3,650,199
def conjugate_term(term: tuple) -> tuple: """Returns the sorted hermitian conjugate of the term.""" conj_term = [conjugate_field(field) for field in term] return tuple(sorted(conj_term))
d21834ff5c2abe5ff6ec85304db962d809b07637
3,650,200
def create_notify_policy_if_not_exists(project, user, level=NotifyLevel.involved): """ Given a project and user, create notification policy for it. """ model_cls = apps.get_model("notifications", "NotifyPolicy") try: result = model_cls.objects.get_or_create(project=project, ...
3d2eec3e3a5f12a4cbba3c3c111608f38133cf94
3,650,201
def parse_table(soup, start_gen, end_gen): """ - Finds the PKMN names in the soup object and puts them into a list. - Establishes a gen range. - Gets rid of repeated entries (formes, e.g. Deoxys) using an OrderedSet. - Joins the list with commas. - Handles both Nidorans having 'unmappable' chara...
1bb1ce6135f162e532b02e2d95eabd675540878d
3,650,202
import torch def get_expert_parallel_src_rank(): """Calculate the global rank corresponding to a local rank zero in the expert parallel group.""" global_rank = torch.distributed.get_rank() local_world_size = get_expert_parallel_world_size() return (global_rank // local_world_size) * local_world_si...
0022f953707f26f9a3b3b021422ebc16e1d14213
3,650,203
from typing import Dict from typing import Any from typing import Optional def _add_extra_kwargs( kwargs: Dict[str, Any], extra_kwargs: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """ Safely add additional keyword arguments to an existing dictionary Parameters ---------- kwargs : dic...
cfc4c17f608c0b7fe1ae3046dc220d385c890caa
3,650,204
import random import math def Hiker(n,xLst,yLst,dist): """ Hiker is a function to generate lists of x and y coordinates of n steps for a random walk of n steps along with distance between the first and last point """ x0=0 y0=0 x=x0 y=y0 xLst[1] = x0 yLst[1] = y0 ...
abe341c8ecdc579de2b72f5af1ace3f07dd40dc3
3,650,205
def extractdata(csvName='US_SP_Restructured.csv'): """ Parameters ---------- :string csvName: Name of csv file. e.g. 'US_SP_Restructured.csv' """ df = pd.read_csv(csvName) df['index'] = df.index # extract alternative specific variables cost = pd.melt(df, id_vars=['quest', 'index'], value_vars=['Ca...
e0a3f405da0e31e252b6110f84f81363c692d66a
3,650,206
def has_field(entry: EntryType, field: str) -> bool: """Check if a given entry has non empty field""" return has_data(get_field(entry, field))
e13d973fde62e36764871fd3b565552ff46b359b
3,650,207
def open_file(app_id, file_name, mode): # type: (int, str, int) -> str """ Call to open_file. :param app_id: Application identifier. :param file_name: File name reference. :param mode: Open mode. :return: The real file name. """ return _COMPSs.open_file(app_id, file_name, mode)
7c38d219d4a867e72d90b873412ec7d5e5aad78a
3,650,209
def correct_repeat_line(): """ Matches repeat spec above """ return "2|1|2|3|4|5|6|7"
b9c1e48c5043a042b9f6a6253cba6ae8ce1ca32c
3,650,211