content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def abbreviate(s): """ Given a sentence replace middle of long words with a char count of the omitted :param s: String :return: String """ r = s for word in split_words(s): r = r.replace(word, abbreviate_word(word)) return r
3e0c94d4cf593dbc717a5140f45eb9f3b4e6ebf6
63,100
import json def block_hash(PARAMETER=None): """ Returns the block hash at a specific height. [PARAMETER] is optional, should be a block hash or height. [DEFAULT] equals to last block. """ if not PARAMETER: d = urllib2.urlopen(blockexplorer('block')) return json.loads(d.read()) else: d = urllib2.urlopen(...
271922dec0a1f62fc0dc705f5e047b8d2a7ba211
63,101
def get_mate_unmate_factor(n_cycles: float) -> float: """Retrieve the mating/unmating factor (piK). :param n_cycles: the average number of mate/unmate cycles expected per hour of operation. :return: _pi_k; the mate_unmate_factor. :rtype: float """ if n_cycles <= 0.05: return PI_...
e5229dd3a89846e633837d1bfe8c100e6c1a1322
63,102
import json import math def compute_melt_viscosity_GRD08(): """ This function calculates the parameters of the non-Arrheanian VFT equation using the model of Giordano et al. 2008: log viscosity(Pa.s) = A + B / (T(K) - C), where A is a constant independent of composition and B and C are adjustable p...
0e7fada77ea143c514713f1747e3eb349ba44e1a
63,103
import io def xml_marshal_bucket_constraint(region): """ Marshal's bucket constraint based on *region*. :param region: Region name of a given bucket. :return: Marshalled XML data. """ root = s3_xml.Element('CreateBucketConfiguration', {'xmlns': _S3_NAMESPACE}) location_constraint = s3_xml...
3fead9ea92ed8062ae43390e5aa25b2295b3aec6
63,104
def create_user( email, **fields ): """ Create a user: * must be given user_cert_bin as a keyword, which must be an ms_user_cert * the cert must be signed by the admin it identifies * the user must not exist * an existing admin must have signed the user cert * said admin has to have been the one t...
9766d053e0c5fe885a0253476a3a19e641f24b31
63,105
def drop_field(expr, field, *fields): """Drop a field or fields from a tabular expression. Parameters ---------- expr : Expr A tabular expression to drop columns from. *fields The names of the fields to drop. Returns ------- dropped : Expr The new tabular expressi...
3007a46d3a0a44f47e10ead1eb0ab3a0ff5be44c
63,106
def async_get_pickup_type_names( entry: ConfigEntry, pickup_types: list[PickupType] ) -> list[str]: """Return proper pickup type names from their associated objects.""" return [ t.friendly_name if entry.options.get(CONF_FRIENDLY_NAME) and t.friendly_name else t.name for t in ...
94f804dd3507612a1632bd300ebb3deada0109ff
63,107
from typing import Sequence from typing import Any def parse_beta(elems: Sequence[Any]) -> dist.Beta: """ Parse a list definition as a beta distribution. Examples: >>> u = parse_beta([2.31, 0.627]) >>> u.a FloatConst(2.31) >>> u.b FloatConst(0.627) >>> parse_beta(["one", 2]) Tr...
81fb83d0d52db9aaa29780b57207979069b32926
63,108
def BRepApprox_SurfaceTool_Value(*args): """ :param S: :type S: BRepAdaptor_Surface & :param u: :type u: float :param v: :type v: float :rtype: gp_Pnt """ return _BRepApprox.BRepApprox_SurfaceTool_Value(*args)
0a965be94ff7b789a7dc0c35f1debb95bae92b02
63,109
def CommitInfo(repository_url, git_hash): """Fetches information about a commit. Args: repository_url: The url of the git repository. git_hash: The git hash of the commit. Returns: A dictionary containing the author, message, time, file changes, and other information. See gitiles_service_test.py...
1f6c40f8a8cda73ac9e65fce490289e9748a7d79
63,110
from typing import Counter def calc_mode(nums): """Calculate the number of number list.""" c = Counter(nums) nums_freq = c.most_common() max_count = nums_freq[0][1] modes = [] for num in nums_freq: if num[1] == max_count: modes.append(num[0]) return modes
dc35c0b792473f00f5e3eb841409959a0bf4ed18
63,111
def get_random_abstract(random_button_n_clicks): """ Get a random abstract for the random button. Args: random_button_n_clicks (int): The number of clicks of the random button. Returns: (str): The text of a random abstract. """ return el.get_random_abstract(random_button_n_clic...
04cbd05c690bf61630606cc43392c45e93b7503d
63,112
def wikilink_simple_url_formatter(text): """ A wikilink function that uses the simple URL formatter. :param str text: the text to format. """ return wikilink(text, simple_url_formatter)
c9a0f1b8f1920bca14ac26170b7084b5849c1b90
63,113
def getProperties(Id,propertyName): """ Get the properties for the associated group/contract combination """ property_parameters = { "contractId":Id['contract'], "groupId":Id['group'] } property_result = getResult('/papi/v0/properties', property_parameters) property_items = property_result['properties']['items'] ...
c538ac876c88da02c0f4bdc8fa61d8e884f3a85c
63,114
import argparse def create_parser(): """ Creates the argparse parser with all the arguments. """ parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) # Add subcommands subparsers = parser.add_subparsers(title="subcommands", dest="cmd") pa...
b61f4d7d146b33b01ecca0d1b8af150233510e01
63,115
def chains_tot_proxy1_rule(M, w, t, k, i, j): """ Coordinate shift and tour type day shift variables. :param M: Model :param w: week :param t: tour type :param k: shift length :param i: window :param j: day :return: Constraint rule """ return M.Shift[i, j, w, k, t] == M.Tou...
ab80506304e2fc9a5b48ebde9a155e4a0028c830
63,116
def __pickle_method__(m): """ Pickling override for using pickle with instance methods. """ if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: return getattr, (m.im_self, m.im_func.func_name)
89e8da97d0c0c8efaef05a4531903ed43c66f62a
63,117
def keepCanvas() : """Keep the current canvas >>> with keepCanvas() : ... do something here """ return KeepCanvas()
702c719d9c25ba8df3cbb5747b76070076630b57
63,118
def conv_temperature_unit(value, unit): """ """ if type(value) is str and value.upper() in ["C", "F"]: raise TypeError("the type of paramter unit must be string.") if unit.upper() == "C": pass elif unit.upper() == "F": value = value * 1.8 + 32 else: raise ValueError("not supported temperatu...
af81cc1da519c76fab7679cec3e6f81dbb7e4beb
63,119
def colorize_label_map(label): """Colorizes a label map. Args: label: A 2D array with integer type, storing the segmentation label. Returns: result: A 2D array with floating type. The element of the array is the color indexed by the corresponding element in the input label to the color map. ...
420addaaf514c65532acbcb1e2b54eecfaa4b881
63,120
import argparse def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Script for split CUB hybrid experiment.") parser.add_argument("--cross-validate-mode", action="store_true", ...
bc5f8d1c2663e5140861a56c945772447be04203
63,121
def get_table1(data_cwhsa, data_cwhsb): """ Create Table 1 of the paper. Parameters ---------- data_cwhsa : pd.DataFrame CWHS data until 1978. data_cwhsb : pd.DataFrame CWHS data from 1978 on. Returns ------- table_1 : dictionairy The dict holds the keys "wh...
bd3556a5736486e81e08a677b6a0d05d4e653b7f
63,122
import torch def collate_fn_lm(samples): """ Creates a batch out of samples """ x = torch.LongTensor(samples) return x[:, :-1], x[:, 1:].contiguous(), None
fbaa043dca5898f2df5a9f7367b654c1eedd6c0f
63,123
def AdvRebaseStream(filehandle): """Class for iteration over entries in a Rebase bairoch format file""" return EntryStream(filehandle, 'TY', 'ER')
6b487c23c05c2af62002d707f57e5b627934f45c
63,124
import os def export_array(array, output_path, metadata): """Exports a numpy array to a GeoTiff. Parameters ---------- array : numpy array Numpy array to be exported to GeoTiff. output_path : str Path to the output file (includeing filename). metadata : dict Dictiona...
e6c6ba04fa767230c60efc50b8ca31489976a057
63,125
def deletions_number(s): """ :type s: str :rtype: int """ char_list = list(s) c, del_count = char_list[0], 0 for next_c in char_list[1:]: if next_c == c: del_count += 1 else: c = next_c return del_count
b63b304510e58ad2191829138c5050e0e661adc5
63,126
def get_omero_dataset_id(conn, openbis_project_id, openbis_sample_id): """ Prints all IDs of the data objects(Projects, Datasets, Images) associated with the logged in user on the OMERO server Args: conn: Established Connection to the OMERO Server via a BlitzGateway ...
ce96afe5c7a6825b2c1b258b9335e0edb145e491
63,127
import glob import torch def model_pos_preparation(args, device): # def model_pos_preparation(args, device): """ return a posenet Model: with Bx16x2 --> posenet --> Bx16x3 """ # Create model num_joints = 16 # num_joints = 16 print('create model: {}'.format(args.posenet_name)) if args....
73b0e4f94d5c37bec7765178db51a68df21a34e7
63,128
from typing import Any from typing import Type def get_object_type_as_json_exportable(object: Any) -> Type: """Get object type to be json exportable. It appends to_json method to an object type dynamically. """ object_type = object if isinstance(object, type) else type(object) if not getattr(obje...
41af74797b19fa76cef58ebbfa00487e359b6e69
63,129
def _construct_tensor_list(types, shapes, batch_expand_num=1): """ Construct list of tensors with types and shapes, used to initialize the network. Args: types: List or Tuple. The output types of element in dataset. shapes: List or Tuple. The output shapes of element in dataset. bat...
d37d8e2aa188e223aa4c90526f2e8c28a7f0c21d
63,130
def _process_exp(data_dir, exp_accession, metadata, assembly, criteria): """Process one experiment from the metadata table. Parameters ---------- data_dir : str path to the directory with bedfiles exp_accession : str ENCODE Experiment Accession ID from the metadata table metadat...
6b0bcae187f217cfdbda30cc18fe73fc8a2b3eed
63,131
def rem_member_from_db(member_id): """Remove member from database. Used for removing members from database in certain cases (Ignoring in shipping and etc.) **Noteworthy:** This makes sense until the bot reboots. In future there are plans for adding ignore list for shipping and other commands ...
c6757ce28fd9a87af5d18b5b64ba5bc5119ee379
63,132
from typing import List def all_grams_from_tokens(tokens: List[Token]) -> List[NGram]: """make all the 1, 2, 3, and skip-3 grams from some tokens""" return (ngrams(1, tokens) + ngrams(2, tokens) + ngrams(3, tokens) + ngrams(3, tokens, skip=True))
dfaf9abe27c8d2a5773c239a3b018061d065958b
63,133
def linear_interpolation_spherical(y_initial, y_final, n, pins=None): """ This function returns a (n, len(y_initial)) array, where every row is an interpolation of the coordinates in y_initial to y_final. The interpolation is made in spherical coordinates ARGUMENTS: y_initial, y_final ::...
75dbf5804397d388d0f561e8df95c6b7cfad3435
63,134
def calc_depreciation(scenario, lights, avg_photoperiod, years): """Calculate Depreciation Function to Compute Total Farm Depreciation each Year Typically accounts for 21 production costs Args: scenario (object): The farm scenario lights (object): The lights used on the farm avg_ph...
ee4d8c4c5612d6cd95bdd2da257351c994984405
63,135
import os def get_stats_parent_dir(stats_base_dir): """ @return a directory to store build stats, relative to the given base directory. Path components are based on build type, Jenkins job name, etc. """ return os.path.join(stats_base_dir, yb_dist_tests.global_conf....
a045375b5e9962b11bcd529da2151f82ab4c91b8
63,136
def diff_dictionaries(old_dict, new_dict): """Calculate the diff two single dimension dictionaries. Args: old_dict(Dict[Any, Any]): Old dictionary. new_dict(Dict[Any, Any]): New dictionary. Returns: Tuple[int, List[:class:`DictValue`]]: Number of changed records and the :cl...
e7d9156bf82bdf27f2692417c3a054b31726aa21
63,137
def is_anagram(word1, word2): """Checks whether two words are anagrams word1: string or list word2: string or list returns: boolean """ return sorted(word1) == sorted(word2)
7a7184f3e9cbe5d1232f0c2750eebde2b9679dc7
63,138
import struct def collect_usb_packet(usb_daq): """ return the packet index and the measurements of a single packet. Measurements have been converted out of array of bytes into array of unsigned ints. Data is unscaled. """ # analog data in the usb packet is formatted as: # 1 contiguous...
f89a9e1169a96e968a196e1732e26d391ef371f8
63,139
from typing import Optional def sql(code: str, *, class_: Optional[str] = None, **kwargs: PropertyValue) -> pre: """ Highlighter method for SQL code. Keyword arguments not listed in the arguments section are turned into element attributes on the created `pre` element. Arguments: code: Th...
27c79def1dde2aa170719d48b380a8f2518f9518
63,140
def aggregate_mean_std_matrix(mu, sigma, n): """Given a matrix of mu, sigma, n return the aggregated array mu, sigma, n (remove the first matrix axis) """ mu = np.array(mu) sigma = np.array(sigma) n = np.array(n) nrow, ncol = mu.shape mu_agg_all = [] sigma_agg_all = [] n_...
810e189d1e93054d011a9cb2af763c6cb10ffa15
63,141
import six from six import StringIO def config_from_str(input_str): """Return a ConfigObj from a string. Values will be in Unicode.""" # This is a bit of a hack. We want to return a ConfigObj with unicode values. Under Python 2, # ConfigObj v5 requires a unicode input string, but earlier versions require ...
52c82e6ff42fc910695afd249f3d5f618ffc2882
63,142
def PyTuple_GetSlice(space, w_obj, low, high): """Take a slice of the tuple pointed to by p from low to high and return it as a new tuple. """ return space.getslice(w_obj, space.newint(low), space.newint(high))
d42ffc16a55deaa858648f2c23b7be14694402ce
63,143
def build_url_dict(sports=SPORTS): """ returns dictionary of { sport (str) : url (str) } """ urls = {} for sport in sports: urls[sport] = [BOV_URL + sport + suffix for suffix in SUFFIXES] return urls
792301e9d556257a457c30310497b51cf856f351
63,144
def check_index_in_list(name_list, index): """ Returns whether or not given index exists in a list of names For example: name_list: ['a', 'b'] 0 exists, 'a', so we return True 1 exists, 'b', so we return True -1 exists, 'b', so we return True 2 does not exists, we ...
efedd7511377e29cc28ea4212271a4b6b59cb3b2
63,145
def electron_distribution_width_old(gamma, **params): """ Calculate the energy-dependent width of the electron distribution Parameters ---------- gamma: array-like gamma values params: dict dict with parameters Returns ------- Width of electron distribution as a fu...
e9892a7151e5333c0b0dae589d68fe45983f1e10
63,146
def pade6(vec, h): """ 6th Order compact finite difference scheme (non-periodic BC). Lele, S. K. - Compact finite difference schemes with spectral-like resolution. Journal of Computational Physics 103 (1992) 16-42 """ n = len(vec) rhs = np.zeros(n) a = 14.0 / 18.0 b = 1.0 / 36.0 ...
0eed51b808370e453598019965da8596fda887dd
63,147
def tile_pil_image( image: Image.Image, tile_factor: int = 0, shade: bool = True ) -> Image.Image: """ Tile PIL Image. :param image: PIL Image object :param tile_factor: number of tiles, if tile_factor=0, this function returns a copy of the input image :param shade: make non-central til...
936ea55aaf70a66d74c79e1d55189aa47cb0a707
63,148
def get_cell_area_ha(raster_file): """Get grid cell area (ha) of raster file, without loading it into memory""" units = get_prj_units(raster_file) if units == 'm': x_res, y_res = get_xy_res(raster_file) area_ha = x_res * y_res * 1e-4 return area_ha else: print('Error: CRS units are {} (must be meters).'.for...
214fafa7f211c6b0a9eb8600c8e407d3e56d8bda
63,149
def _normalize_sexpr(text): """ Normalize s-expr by making sure each toplevel expr is on a new line, and sub-expressions are always indented. Starts of block comments are also alwats indented. As a result, the text can now be split on "\n(" to get all expressions. """ # You probably dont wa...
4e3b35f5021ad7cdb857ac8516876b88bf7281c3
63,150
import os def write_data(data, destination): """Write (overwrite) 'data' to 'destination' file semi-atomically. Returns 0 on success. """ tmpfile = destination + ".tmp" try: with open(tmpfile, "w") as fout: fout.write(data) fout.flush() os.fsync(fout.f...
02fdaf4efbf612b1a36e57b7bbc37091bda2904e
63,151
from typing import Dict def parse_teams(elem, known_teams: Dict[str, Team]) -> Dict[str, Team]: """Returns the teams involved in the match""" cell = elem.select('tr')[1:2][0] away_name: str = cell.contents[1].select('font')[0].contents[0].contents[0].strip() try: away: Team = known_teams[away_...
f17f7b1aa9e57e1600a73a95972c346013fc9df7
63,152
def delconj(lam, ur, ur_inv, dups): """ Delete one eigenvalue/eigenvector from of each pair of complex conjugates. Parameters ---------- lam : 1d ndarray The vector of complex eigenvalues ur : 2d ndarray Normalized complex right eigenvectors ur_inv : 2d ndarray I...
7adc71774a30a640c2baddd64f726ab4b3456e48
63,153
import random import json def generate_random_password(field, **kwargs): """ Generate a random string password or a random encryption method. Args: field: The field object. Keyword Arguments: only_required: The argument to generate only required fields. fulldate: A boolen to d...
16424ed90753508bdc2824d49b859c098756e3d3
63,154
def put_something(): """ Put something --- responses: 200: description: Success """ return "I put something", 200
e5464c86acc852d68c8a78bde3558b0673656636
63,155
from typing import Optional from typing import Sequence def cell_co_occurrence( data: AnnData, groupby: Optional[Array] = None, agg: str = "sum", selected_types: Optional[Sequence] = None, use: str = "dot", # dot, heatmap key: Optional[str] = None, **kwargs, ): """Visualization for ce...
37a999fde747ea39c472bfd03f5026b1c97d959c
63,156
def is_link_array(value): """Checks if value is an array of links. :param value: any object. :return: Boolean :rtype: bool Usage: >>> is_link_array('foo') False >>> is_link_array([1, 2, 3]) False >>> is_link([{'sys': {'type': 'Link', 'id': 'foobar'}}]) ...
00140bd454c0c10578664da7ae3ba507386a4fe7
63,157
def robust_topological_sort(graph): """ First identify strongly connected components, then perform a topological sort on these components. @param graph graph to be ordered """ components = strongly_connected_components(graph) node_component = { } for component in components: f...
64791a530f70d31dbb2df878aa4d2f8d7652a098
63,158
import os def add_pid_to_csv_filename(name): """ :param name: takes name :return: abs_file_name, exist_csv """ assert '.csv' in name, f"{name} is not .csv" # where to look requested_folder = os.path.split(name)[0] # what to look for file_name = os.path.split(name)[-1].replace('.cs...
e4bc6c4533ee5a290f6343b54b3ec9b00aa6445e
63,159
import shlex def execute(cmd, args): """ Just a simple wrapper for executing commands. args is expected to be a sequence or a basestring, a basestring will be executed with shell=True. """ if isinstance(args, basestring): args = smart_str(args) args = shlex.split(args) else: ...
8cf7e54c88c41ce6e7a27dfe3465078e79070d5e
63,160
def sql_get_columns_for_table(table_schema: str, table_name: str) -> list: """Generate an SQL command that returns the list of column of a specific table. Compatible with MySQL/ MariaDB/ Postgres and Snowflake table_schema and table_name can be lowercase and uppercase strings. It's using the IN clause ...
8c5fb78a6a1ff242b333d750cb659b67eb15c52d
63,161
from Bio import pairwise2 def align_query_vs_reference( qry_seq, ref_seq, aln_gap_open = -10, aln_gap_extend = -0.5 ): """ Globally align two input sequences using NW-algorithm, return highest-scoring alignment. ARGS: qry_seq, ref_seq, two different orthologous CDS (exon-only) DNA ...
dd2509600dd889062257d001e7f87f1ebaabe532
63,162
from typing import Tuple from typing import List def override_module_args(args: Namespace) -> Tuple[List[str], List[str]]: """use the field in args to overrides those in cfg""" overrides = [] deletes = [] if args is not None: assert ( hasattr(args, "task") and hasattr(...
9501338b4649cf020f4b99f70649e92bbb31fc1f
63,163
import enum def pascal_case(value): """Convert strings or enums to PascalCase""" if isinstance(value, enum.Enum): value = value.name return value.title().replace('_', '')
6e994650755968a3f73b345e1f3e040f0f211aa9
63,164
import math def computeSNQ(DW2,N): """ Takes the exponent for the Debye Waller factor `DW2` = 2W, and an integer N indicating a term in the phonon expansion and returns the intensity of the N-phonon incoherent scattering S_N(Q) Parameters ---------- N:integer a term in the phonon e...
6f48baaffb647a97f9662b44f0916443f3338003
63,165
def format_timedelta(td): """ Format a timedelta object with the format {hours}h {minutes}m. """ if td is None: return '0h 0m' seconds = td.total_seconds() hours, seconds = divmod(seconds, 3600) minutes = seconds / 60 return f'{int(hours)}h {int(minutes)}m'
e0b30250eef25db9b905e9e6d6c82a41b742112b
63,166
def get_file_mode_for_reading(context_tar): """Get file mode for reading from tar['format']. This should return r:*, r:gz, r:bz2 or r:xz. If user specified something wacky in tar.Format, that's their business. In theory r:* will auto-deduce the correct format. """ format = context_tar.get('for...
05908234027070c1479e5159fc16eda267228042
63,167
def apply_broadening(ipres, x_seg, y_seg, type="gauss", sme=None): """ Broaden a spectrum by instrument resolution, with a given broadening type Parameters ---------- ipres : float instrument resolution x_seg : array (npoints,) x values (wavelength) of the spectrum to broaden ...
3b3d09ef0c995efb87c75a6e79b00a1969dea57d
63,168
def iterate_ranges(range_tuples, nums): """ Yields all points of N-dimensional regular rectangular grid. :param range_tuples: List of :math:`(a_i, b_i)` tuples, where :math`i` is the number of grid dimensions. :param nums: List of number of points for grid's :math:`i`-th dimens...
4d2d3affaa286f56926cdba815b1376d24effe48
63,169
def touch_files(path): """ This function creates all necessary files for to be used with Arbiter or FFTB. """ touch = ['parse', 'edge', 'run', 'analysis', 'decision', 'fold', 'item-phenomenon', 'item-set', ...
5a6fe27eecfeee834aa0de8977c3f1acb1558623
63,170
def GaussBeam(w0, Fin, n=0, m=0, xshift=0, yshift=0, tx=0, ty=0, doughnut=False, LG=False): """ Fout=GaussBeam(w0, Fin, n=0, m=0, xshift=0, yshift=0, tx=0, ty=0, doughnut=False, LG=False): Creates a Gaussian beam in its waist. Args:: required: w0: size of the Gauss waist ...
125ca4f0edc71f6badfac46fc7fd9696cf2c34dc
63,171
def checkKey(key): """Return True if key is valid. Otherwise return False.""" keyList = list(key) lettersList = list(LETTERS) keyList.sort() lettersList.sort() if keyList != lettersList: print('There is an error in the key or symbol set.') return False return True
c3a58eb2716dad8415b78123eaeee1e3a39abd7b
63,172
def _to_seq_array(x): """ Converts a list of sequences from a generator to a DataFrame of sequences """ seq_series = pd.Series({s.metadata['id']: str(s) for s in x}) return seq_series.apply(lambda x: pd.Series(list(x)))
ab04c36fefd7775c9a62e0850a8b6d77e5c2fa41
63,173
def update(isamAppliance, name, uuid, aclEventsAllocation, ipsEventsAllocation, sysEventsAllocation, objType='logdb', comment='', check_mode=False, force=False): """ Update a specific logdb object """ if force is True or ( _exists(isamAppliance, uuid) is True and _check(isamApplia...
3d9624041c69af4cfb1872c2e76081c7bf9e243e
63,174
def handle_429(e): """捕获abort(429)频率限制错误""" rsp = { 'msg': 'Too Many Requests', 'err': 30 } err_info = { 'msg': 'Too many requests', 'ip': request.remote_addr, 'url': request.url, 'method': request.method, } logger.api_logger.error(err_info) re...
3716438b2c81e78da4138a3dabea81677eec6f69
63,175
def default_smooth_aperpar_bkg(newx_lst, ypara, fitmask, group_lst, npoints): """Smooth *bkg* of the four 2D profile parameters (*A*, *k*, *c*, *bkg*) of the fiber flat-fielding. Args: newx_lst (:class:`numpy.ndarray`): Sampling pixels of the 2D profile. ypara (:class:`numpy.ndarray`): Arra...
48a737d4e3f4e10f6ec88c236687902dece87736
63,176
from typing import Union from typing import Optional from typing import List def format_helper( df: Union[pd.DataFrame, Styler], int_cols: Optional[List[str]] = None, pct_cols: Optional[List[str]] = None, delta_cols: Optional[List[str]] = None, monospace: bool = True, hide_index: bool = True, ...
8f41410b7e735fa7c618718cefc7790a6be39cb3
63,177
def buildFeatureTableSubstitutionRecord(featureIndex, lookupListIndices): """Build a FeatureTableSubstitutionRecord.""" ftsr = ot.FeatureTableSubstitutionRecord() ftsr.FeatureIndex = featureIndex ftsr.Feature = ot.Feature() ftsr.Feature.LookupListIndex = lookupListIndices return ftsr
22a64da7f9192b3117ec002bff997f4e6c3976db
63,178
from typing import Union from typing import List from typing import Tuple def get_go_interface_instance(background: Union[List[int], List[Tuple[int, float]]] = ()) -> \ GeneOntologyInterface: """ Generates a Matrix_Knowledge_DB interface for the use in the spawner. If :return: a GO_interface obje...
107036f160d5e9c5e885bc205a883a8eb80e44b5
63,179
import re def StripComments(line): """Strips comments from a line and return None if the line is empty or else the contents of line with leading and trailing spaces removed and all other whitespace collapsed""" commentIndex = line.find('//') if commentIndex is -1: commentIndex = len(line) line = re....
06a01a01889d7f6c169acb3090eadf2c6e07d219
63,180
import itertools def final_vowel_substitution_transducer(add_meta_arc=True): """Substitute final vowels (optionally).""" t = pt.Transducer() for l in pt.abc.ALL_SYMS: t.add_arc(0, 0, l, l) t.add_arc(0, 1, l, l) max_node = 1 for s_ar, s_sw, subst_cost in pt.abc.AR_SW_FINAL_VOWELS: prev_node = 0 ...
a19e1ffc306e77788b0df7dfc4e60af2654d2727
63,181
def _mad(x, axis=None): """Calculate median absolute deviations from the median (MAD) for an array. Parameters ---------- x : np.ndarray A 1-D or 2-D numeric array to summarize. axis : {int, tuple of int, None}, optional Axis along which MADs should be calculated. If ``None``, the M...
c712a17d1fbec07f1622e25a54cbb62bcd54cd60
63,182
def ode_plotter(name, t, ny, svars, log = False, labels = None, xlim = None, ylim = None, plim = None, labels_strict = False): """ Plots the ODE trajectories. Args: name (str): Name of the outputfile including extension (e.g. *.pdf) t (list[flt]) : time units plotted on the x-axis. ny...
a049b03f36e64e66a6d954e6b9c4d4b377f5c85a
63,183
def Proxy(f): """A helper to create a proxy method in a class.""" def Wrapped(self, *args): return getattr(self, f)(*args) return Wrapped
48ce69670db02691bf20b7d277af5086c76d012d
63,184
def french_to_english(french_text): """french to English translation""" translation= language_translator.translate(text=french_text, model_id="fr-en").get_result() english_text=translation['translations'][0]['translation'] return english_text
75420074fe15360c789d76a887dc6574a37fdf95
63,185
import pandas from typing import Union from typing import List def calculate_metric_scores( r: pandas.Series, metrics_to_calculate: Union[str, list] = "all", ) -> List[Result]: """Calculates the metric score(s) between two images and returns a list of the results. Args: r (pandas.Series): Row con...
6c7a306e2c7eee42bbd2f8fcc9e5a99ddb9d7b89
63,186
def parse_results(results): """Break up multiline output from ls into a list of (name, size) tuples.""" return [(line.split()[8], int(line.split()[4])) for line in results.splitlines() if line.strip()] #return [(line.split()[1], int(line.split()[0])) for line in results.splitlines() if line.strip()]
dd4eea6fc57133225e74df1d61af69b44329b636
63,187
def use_for_variety(variety, *, read=True, write=True): """ A class wrapper to associate a specific variety with the class. Defaults to registering for both read and write widgets. Parameters ---------- variety : str The variety (e.g., 'command') read : bool, optional Use ...
568e440b62336f8e88b594c6e94ae94f0897b2c9
63,188
import requests def getListings(): """ :param ticker: str Returns: """ return requests.get(URL_LISTINGS, headers=headers).text
fd16f0ca34fdc0bf34b141c5d6c2a0bfc7bb8589
63,189
def STALTA_picker(st, nphase=2, nsta=1e-3, nlta=4e-2, fc=50, nc=2, noise_mag=1e-25, SNR_window=5e-3): """The STA/LTA picker provides a first order good estimate of the arrival times for both the P- and S- wave. The STA/LTA picker uses :py:class:`obspy.signal.trigger.recursive_sta_lta `. :param st: ...
17b1e0a0c69aa9c6c9daac003747782cd8c10ff6
63,190
def underscore_to_camel(match): """ Cast sample_data to sampleData. """ group = match.group() if len(group) == 3: return group[0] + group[2].upper() else: return group[1].upper()
4a4dafd233f420ba2066d53260e0cd8c508b2bc9
63,191
def select_tapered_estimator(debiased, direct): """Select the tapered estimator of the structure factor. Args: debiased (bool): Trigger the use of a debiased tapered estimator. direct (bool): If ``debiased`` is True, trigger the use of the direct/undirect debiased tapered estimator. Return...
b092e17597ba471acc7cbe318727b24ee72a25e7
63,192
import torch def test_ae(model, dataloader, gpu, criterion): """ Computes the loss of the model, either the loss of the layer-wise AE or all the AEs in a big graph one time. :param model: the network (subclass of nn.Module) :param dataloader: a DataLoader wrapping a dataset :param gpu: (bool) if ...
ffc55268dac0e884e7ef9594d270fb59d9fc19ec
63,193
def moments(input_t, axes=None, keepdims=False): """ Returns (mean, variance) of input_t input_t Tensor axes(None) int Iterable of ints. None - all axes keepdims(False) keep reduced axes """ mean = reduce_mean(input_t, a...
1f30a3cb85fa21b2a7abf9e2d92cb89d1141b615
63,194
def get_obj_info(oID): #TODO: what about not mesh objects? """ get object data to figure out how far away the hand needs to be to make its approach """ obj_data = p.getCollisionShapeData(oID, -1)[0] geometry_type = obj_data[2] #print("geometry type: " + str(geometry_type)) dimensions = obj_d...
eca5fde2a81d75c4895e53e56bcfecda32ea32d0
63,195
def sin(): """ Returns class instance of `Sin`. For more details, please have a look at the implementations inside `Sin`. Returns ------- Sin : Class instance implementing all 'sin' processes. """ return Sin()
9d90b5e40ae285d79bbf25498730a4728c2ed437
63,196
def parse_format(frm): """ Determine a struct format from a CPHD format string. Parameters ---------- frm : str Returns ------- Tuple[str, ...] """ return tuple(_map_part(el) for el in frm.strip().split(';') if len(el.strip()) > 0)
90503a2d6eedb9324f4668106a0f9477cb6c8f43
63,197
import boto def needs_aws(test_item): """ Use as a decorator before test classes or methods to only run them if AWS usable. """ test_item = _mark_test('aws', test_item) try: # noinspection PyUnresolvedReferences except ImportError: return unittest.skip("Skipping test. " ...
664b21ee8ac88640a6ebfcce75c4697e7b828f51
63,198
import os import imp def load_app_from_path(modulepath, factory_name='create_app'): """Load the module containg the application and create it.""" modulepath = os.path.abspath(modulepath) filename = os.path.basename(modulepath) modulename = os.path.splitext(filename)[0] dirpath = os.path.dirname(m...
01d02adb5fd21efdd1a4db2b2243f4306e6e2674
63,199