content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import six def setupTranslationMap(): """prepare translation map to remove all control characters except tab, new-line and carriage-return""" ctrls = trans = "" for n in range(0, 32): char = six.unichr(n) ctrls += char if char in "\t\n\r": trans += char else...
b59a5808e9a8bd2edb10f1cbd55254ed047f3737
3,598,200
def init_spacy_document( lattice, token_key="token", ): """ Given List of word-level dicts, initializes Spacy Doc using WhitespaceTokenizer :param: lattice: List[Dict]; inner dicts contain token-level information for each token in input text :param: token_key: key in Dicts containing...
5d0f5a4d331b70dbcbd414969acc1fb7008fc0af
3,598,201
import os def _get_pic_map(pic_files): """ pic_files: [pic_path, ] return: {pic_id : [file_path,]} """ file_dict = {} for f in pic_files: pic_basename = os.path.basename(f) file_dict[pic_basename] = f return file_dict
6baf2101518161788217d9b6e5fc835676947c48
3,598,202
def get_rev_by_cat(date_start, date_end): """ Return the total revenue for each category within the time range. """ sql = f""" select productcategory.name, sum(sales.total) from sales, product, productcategory where salesdate between to_date('{date_start}', 'YYYY-MM-DD') and to_date('{date_e...
0e5204ea7fd86f5918e6d3504ccd42eae5e793b4
3,598,203
def get_metaschema(): """ Patches and returns the JSON Schema Draft 4 metaschema. """ return json_merge_patch.merge(json_load('metaschema/json-schema-draft-4.json'), json_load('metaschema/meta-schema-patch.json'))
64ecf14cd8cf996896600a800b70048f984b1564
3,598,204
import re def is_url(filePath): """ Checks wether or not the file path is a valid url. :param str filePath: file path :return: returns true if path matches pattern starting with http:// or https:// :rtype: boolean """ regex = re.compile(r'^https?:\/\/', re.IGNORECASE) return re...
8d86e07c8585f30bb8927ba9cfa7f1a8d128b598
3,598,205
def reportAPIError(response, exception, sendEmail, extraErrorMessage=""): """ reportAPIError reports an APIError offering configuration options in the reporting :param response: the response from the http request :param exception: the python exception that was thrown :param sendEmail: bool, whether ...
3f95aff537c6ff3136c4e82b17ed9fcdf6507f29
3,598,206
def dump_identifier(value): """dump identifier""" if value is True: return "y" return "n"
45d5fded4a5a6f12488385c35321eb94e10a06e1
3,598,207
def get_productions_simple(**kwargs): """Load a DataFrame of productions with the most typical query Parameters ---------- **kwargs Optional arguments that are passed to get_credentials() Returns ------- prods_df : pandas DataFrame DataFrame of all productions """ q...
8e8d617aaa71a669b816d6e24481399280d758b6
3,598,208
def directpose_resnet_lpf_fpn(cfg): """ Create a ResNetFPNDirectPose instance from config. Returns: ResNetFPNDirectPose: a :class:`ResNetFPNDirectPose` instance. """ depth = cfg.CONFIG.MODEL.RESNETS.DEPTH out_features = cfg.CONFIG.MODEL.RESNETS.OUT_FEATURES num_blocks_per_stage = {5...
6581e5f5cfcfddbab70a03a8e71a4f7f4ffb4685
3,598,209
def select_results(results, selector_strings): """select the results by the specified selectors. Paramters --------- results : array-like, shape(n,) The results after scanning the directory for documents with valid headers. selector_strings : array-like, shape(m,) The list ...
e919115fdc6878ba3ca0946415c8fc43d3fbb6a7
3,598,210
def DistanceFromMatrix(matrix): """Returns function(i,j) that looks up matrix[i][j]. Useful for maintaining flexibility about whether a function is computed or looked up. Matrix can be a 2D dict (arbitrary keys) or list (integer keys). """ def result(i, j): return matrix[i][j] retu...
f3cb95aace0cfe70bfeef9d8778947df16cdd4b1
3,598,211
def job_response(request,**args): """ Job application/ job response """ if request.method=="get" or request.method== "GET": # get job response form and send back to client form=forms.JobresponseForm() return form if request.method=="post" or request.meth...
eb5bc02eb12e15983a66e680d9f41c7144ae1dae
3,598,212
def _are_orders_renormed(exposures_data, input_key): """ :param exposures_data: :param input_key: :return: """ exposures_all = list(exposures_data.keys()) n_renorm = 0 for exp_id in exposures_all: orders_all = _valid_orders_from_keys(exposures_data[exp_id].keys()) n_orde...
668802f8d9c7ec2ed4ca9be16522802411217d70
3,598,213
def preprocess_captions(data, word2vec, emoji2vec): """ Preprocess the captions: remove non-english or punctuation characters, remove captions shorter than the minimum, lowercase captions """ lengths = [] for row, caption in enumerate(data['Caption']): if type(caption) != str or len(caption...
bc836958e5e20794957ac47c1908b15550d57de9
3,598,214
def get_bprop_bias_add(self): """Grad definition for `BiasAdd` operation.""" bias_grad = SG.BiasAddGrad(self.data_format) def bprop(x, w, out, dout): return dout, bias_grad(dout) return bprop
cb75d0bda0df246ec28c56fea352d7de75abc6b7
3,598,215
from pathlib import Path def homedir() -> str: """Return the user's home directory.""" return str(Path.home())
dbd65e7db4cdbf2bd06c1ab42ed1ea3503e14ac2
3,598,216
from typing import Optional def get_raster_with_trajectories_as_rgb( pixel_size: float, raster: Raster, target_trajectory: Optional[Trajectory] = None, predicted_trajectory: Optional[Trajectory] = None, background_color: Color = Color.BACKGROUND, roadmap_color: Color = ...
64b0a01f4af292be0f21f8ffddc7b21184fb6d2c
3,598,217
import os def append_str_to_filename(path_or_file_name, str_to_append): """ Appends a given string to the given filename. **Parameters**: path_or_file_name : str The path or filename to append to. str_to_append: str The str to append. **Returns**: `str...
fed41face6e8aa66650d2ff8edc2aed395b5b8eb
3,598,218
import re def natural_keys(text): """ alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside """ ...
d3a017c9f0426175bfa8fe53ab779a501a3ec24c
3,598,219
def contributor_or_delegate_required(view_func): """ Decorator for views that checks that the user is logged in, has edit rights for at least one course or is a delegate for such a person or is a contributor. """ def check_user(user): return user.is_contributor_or_delegate return use...
e8475e30fb3f02dbff3e230bfe4cbc81f13f55c3
3,598,220
def read_label(fig, label, whitelist=LABEL_WHITELIST): """ Reads a label paragraph objects using ocr :param numpy.ndarray img: Input unprocessedimage :param Label label: Label object containing appropriate bounding box :rtype List[List[str]] """ size = 5 img = convert_greyscale(fig.img) ...
e026186e2e6cd76c09777333a1896e3b78e06a24
3,598,221
def remove_accented_chars(text): """remove accented characters from text, e.g. café""" text = unidecode.unidecode(text) return text
05afba1091a8bba2e7d6381a04e22addf022dca3
3,598,222
import itertools def _optimal_path(input_sets, output_set, idx_dict, memory_limit): """Copied from _optimal_path in numpy/core/einsumfunc.py Computes all possible pair contractions, sieves the results based on ``memory_limit`` and returns the lowest cost path. This algorithm scales factorial with res...
ba2735b208f50d117349ea12148138a1857b66b7
3,598,223
from pathlib import Path def inside_container() -> bool: """ The developer's machine is not sandboxed and should not run any testing snippets, at the risk of being damaged. So, it is important to make sure that the code execution only happens inside a container. See: * https://stackoverflow.c...
fb5377cb2cef8da20bcc18a01087b2dca7b5d2ac
3,598,224
import warnings def _check_psd_eigenvalues(lambdas, enable_warnings=False): """Check the eigenvalues of a positive semidefinite (PSD) matrix. Checks the provided array of PSD matrix eigenvalues for numerical or conditioning issues and returns a fixed validated version. This method should typically be...
be5fd1dd800e3a709462bbdfe5c627ba0bdcac2f
3,598,225
def test_function_with_no_args(): """This cannot be called because meta is always passed.""" return "look, no args!"
a6f83e1e5265f39a3037a764803a8abc6d358744
3,598,226
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up RainMachine as config entry.""" session = aiohttp_client.async_get_clientsession(hass) client = Client( entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session ) async def async_get_picku...
bc13196f150172c10fdbc15e80d1ad96d60441cd
3,598,227
def test_query_device_do_bypass(monkeypatch): """Test setting the bypass status on devices matched by a query.""" _was_called = False def _bypass(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == {"action_type": "BYPAS...
0e0b1c07da2c932afac843592d5b3bf8776462c1
3,598,228
def KK_RC19(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
b0c492edd63c6c5e9a07b9d7206f08e2cea8d594
3,598,229
def cdf_from_pdf_file(data_file): """ Computes CDF from PDF values stored in a file Creates a Cumulative Distribution Function from Probability Density Function data file. Each line must be a pair of numbers x y=pdf(x). It returns the CDF as two lists; first on is the list of x-values, second o...
ef1251357b602141a1899ea957c3240b0adb1fb4
3,598,230
def image_to_numpy(image, background_color): """Sets background of 4d image to the specified color.""" image = np.asarray(image) assert(image.shape[-1] == 4) background = image[..., 3] == 0 image = image[..., :3].copy() image[background] = background_color return image
927c9935c052c656b1970b06a520709a4c6f4bb3
3,598,231
import numpy def li_kernel(view_zenith, solar_zenith, relative_azimuth): """Calculate Li Kernel - Li X. and Strahler A. H., (1986) - Geometric-Optical Bidirectional Reflectance Modeling of a Conifer Forest Canopy. Args: view_zenith (numpy array): view zenith. solar_zenith (numpy array): solar...
0c7eef7d9fb1ec56566e77df67267fb6dc14bdd1
3,598,232
import re def parse_sphinx_substitutions(): """ Parse the file containing definitions in Sphinx format into a dict. Example: .. |short_name| replace:: A detailled definition becomes "short_name: A detailled definition" """ file_name = "../sheepdog/docs/api_reference/subst...
e0f1afcd812bb04af5a73de77f0226d55279fdc8
3,598,233
def get_invalid_parameter(value): """ Read everything up to the next ';'. This is outside the formal grammar. The InvalidParameter TokenList that is returned acts like a Parameter, but the data attributes are None. """ invalid_parameter = InvalidParameter() while value and value[0] != ';': ...
6c0af359e269606796139a55049b03816433af69
3,598,234
def idfreader1( fname, # type: str iddfile, # type: str theidf, # type: IDF conv=True, # type: Optional[bool] commdct=None, # type: List[List[Dict[str, Any]]] block=None, # type: Optional[List] ): # type: (...) -> Tuple[Dict[str, Any], Optional[List[Any]], Any, List[List[Dict[str, Any]...
d56bb795b9a2a33cb147c4c0d1ad32c2a4c8d6f3
3,598,235
def create_account(ac_name,us_name,ac_pswd): """ Function to create a new account """ new_account= Credential(ac_name,us_name,ac_pswd) return new_account
78bc04b2c973da57ed693da142dec7f5d1fca93d
3,598,236
from typing import OrderedDict def _q_calc(fatigue_life, h, v0, sn, method='brentq'): """ Calculate Weibull scale parameter (q) that gives specified fatigue life using closed form expression in DNV-RP-C03 (2016) eq. F.12-1. Parameters ---------- fatigue_life: float Fatigue life [years...
0aa35d4359dafaf1c5ea83fc75f4d02661cebe85
3,598,237
def make_attention_mask_3d(source_block, target_block): """ Returns a 3-dimensional (3-D) attention mask :param source_block: 1-D array :param target_block: 1-D array """ mask = (target_block[:, None, :] >= 1) * (source_block[:, :, None] >= 1) # (batch, source_length, target_length) # ma...
d06e44da4dfdcf2312583d4601642a34094399db
3,598,238
import itertools def get_mask_list_reg(raster_shape, reg_dimensions): """Generate a list of raster masks by regularly sampling the landscape. Takes the shape of the raster to be sampled and the dimensions of the "building block grid" as arguments. Returns a list of masks consisting of regularly sampl...
7667340e6a52f2ca49678ecf55e9f0053bd511ab
3,598,239
from typing import Dict def schema_as_dict(schema: SchemaDefinition) -> Dict: """ Translates a SchemaDefinition object into a python dictionary, removing redundant elements This is a wrapper to standard runtime dumper methods, but will produce a more compact schema, in particular: * prefix maps are ...
faa88349ba797ca81fe67c3963b4d66c9c09a533
3,598,240
def build_window_mixture_model(model, initial_states, cells, inputs, batch_size, window_components, character_inputs, char_seq_len): """ Append window mixture model to model """ assert len(cells) == 3, "Expectin...
57db2c632b16628e189e000799c9370417074a70
3,598,241
def addDropShadowSimple(image: Image.Image, offset: list[int]) -> Image.Image: """Add a simple drop shadow. Args: image (Image.Image): Base image to give a drop shadow offset (list[int, int]): Offset of the shadow as [x,y] Returns: Image.Image: A PIL Image """ border = max(abs(x) for x in offset) return a...
b9d691f8c950e487481656b6ec828dcffc341353
3,598,242
def hello_world(): """Welcome route""" return jsonify({"message": "Welcome to Dukaan Rating API"})
12a63e5e8f9eae8ce034c60d4d70cf72d8926889
3,598,243
def frame_width(camera, target, fov = 30): """ Get frame width from camera, target positions and field of view **ARGUMENTS** camera : array Camera position. A 1D array target : array Target position. A 1D array fov : float Field of view (degrees) of the camera...
c490d6d4c52f74e646fca609362513625b164815
3,598,244
def length(v): """Length of vector""" return sqrt(v.dot(v))
32c43a425c9fc10faa5790271fde2068eb391a4f
3,598,245
def filter_endpoints(end_points): """ Keep only conv layers and reshape into [Nl x Ml] matrixes """ d = {} for k, v in end_points.items(): if 'conv' in k: el = tf.squeeze(v) n_f = el.shape[-1] el = tf.reshape(el, (-1, n_f)) el = tf.transp...
1e0088d489dfebfb2d0b60f6324954017d1a2771
3,598,246
from legacyhalos.coadds import _mosaic_width from legacypipe.survey import LegacySurveyData from legacyhalos.qa import sample_trends from astrometry.util.multiproc import multiproc import os def make_plots(sample, datadir=None, htmldir=None, survey=None, refband='r', bands=('g', 'r', 'z'), pixscale=0.2...
0554ba91bd0b1d96cd40dde91c1b42fbad98cc37
3,598,247
def validate(X, Y): """ 校验X和Y的格式是否正常,如果不正常,返回False;否则返回True :param X: :param Y: :return: """ m1, n1 = np.shape(X) m2, n2 = np.shape(Y) if m1 != m2: return False else: if n2 != 1: return False else: return True
44de6cb937b6e0db810fb569b654b91dcea7a361
3,598,248
def quote_aware_split(string, delim=',', quote='"'): """ Split outside of quotes (i.e. ignore delimiters within quotes.""" out = [] s = '' open_quote=False for c in string: if c == quote: open_quote = not open_quote if c == delim and not open_quote: out += [s...
0ef5f7040eee2a041fa1b6e6d8bf3a773a80f5f9
3,598,249
def NormalizarSerie(SR): """ Descripción: ----------- Normaliza una serie basandose en maximo y minimo Haciendo que la misma se encuentre entre 0 y 1 Un ejemplo de uso seria normalizar el DPO y operar en 0.2 para la compra y 0.5 para la venta (estrategia comprado) Parametros ...
6e7a9f0b2dd9be0fd82712ab5c9176e245e34549
3,598,250
def is_const(array, *, is_const=_speedups and _speedups.is_const): """Returns if the given array is constant""" if is_const: res = is_const(array) if res is not None: return res if array.size == 0: return True else: return (array == array[0]).all()
d5a5ceb519b3f0a7433ea6ff7860a9650a4b6d8f
3,598,251
def entropy(x): """ calculate shanno ent of x """ x_value_list = set([x[i] for i in range(x.shape[0])]) ent = 0.0 for x_value in x_value_list: p = float(x[x == x_value].shape[0]) / x.shape[0] logp = np.log2(p) ent -= p * logp return ent
86e3e999501a38e3143c244c736a51855dfcc431
3,598,252
def MinMaxScaler(x, min_value=0, max_value=1): """ :brief: Normalizes data using the min max scaling. :param x: are the data :param min_value: is the minimum value :param max_value: is the maximum value :return: scaled data """ data_size = len(x) dimensions = len(x[0]...
88e11f79cb84800cef56950f8e120eaa6de6ee3f
3,598,253
def _define_rt_plan(ds: Dataset) -> Dataset: """Return an RT PLAN directory record from `ds`.""" _check_dataset(ds, ["InstanceNumber", "RTPlanLabel"]) record = Dataset() record.InstanceNumber = ds.InstanceNumber record.RTPlanLabel = ds.RTPlanLabel record.RTPlanDate = ds.get("RTPlanDate") re...
aad48d9b4317151fd973b41f0a2331377d42adaa
3,598,254
from typing import Optional def get_global_cache_info( tag: Optional[str] = None, add_banner: bool = False ) -> str: """ Report information on global cache. """ if _TRACE_FUNCS: _LOG.debug("") txt = [] if add_banner: txt.append(hprint.frame("get_global_cache_info()", char1=...
97acbda32802357e561f47286e404c7f0f49a17a
3,598,255
def NcbiTaxonomyFromFiles(nodes_file, names_file, strict=False): """Returns new NcbiTaxonomy fron nodes and names files.""" taxa = NcbiTaxonLookup(NcbiTaxonParser(nodes_file)) names = NcbiNameLookup(NcbiNameParser(names_file)) return NcbiTaxonomy(taxa, names, strict)
a4ff1dc311b9c3aa0505304585bdc2e3354da591
3,598,256
def minutes_for_days_in_range(start, end, days_in_range_hook, minutes_for_day_hook): """ Get all execution minutes for the days between start and end, inclusive. """ start_date = normalize_date(start) end_date = normalize_date(end) all_minutes = [] for day ...
514c7a1dfc28579cbb0c4203599eb80d7480df61
3,598,257
def new_action(parent, text, slot=None, shortcut=None, icon=None, tip=None, enabled=True): """actionの設定と取得""" # アクション取得 a = QAction(text, parent) # icon設定 iconsフォルダから取得 if icon is not None: a.setIcon(QIcon('icons/'+icon)) # ショートカット作成 if shortcut is not None: if isinstance(sho...
a02051154fec7d69ddca8a01073e9367e3e695ba
3,598,258
def _millis(when): """Convert a zone-aware datetime to integer milliseconds. :type when: :class:`datetime.datetime` :param when: the datetime to convert :rtype: int :returns: milliseconds since epoch for ``when`` """ micros = _microseconds_from_datetime(when) return micros // 1000
4eed9d17bf127d9b0794a539e58f4118dca415bd
3,598,259
import re import code def clean_python_code(python_code, isort=True, black=True, autoflake=True): """Clean Python code.""" # Temporarily comment out IPython %magic to avoid Black errors. python_code = re.sub("^%", "##%##", python_code, flags=re.M) # Run source code string through autoflake, isort, an...
5c9e875c5de8b688331467392c8011633d69adee
3,598,260
from re import T def check_opt_isinstance(item: T, classinfo: _ClassInfo) -> T: """ Checks something is ether None or an instance of a given class. Raises a TypeError otherwise """ if item and not isinstance(item, classinfo): raise TypeError( "Expected instance of type {!r} bu...
d6d4a439ded2aedd3a243e48b8c2e101be18f5bd
3,598,261
def getcwd(): """Return a string representing the current working directory. :rtype: string """ return ''
31ba3c781dad707ef5feaa15a841d8d528ded3e3
3,598,262
def getRenamingCommands(): """ Get all available L{renamer.irenamer.IRenamingCommand}s. """ return getPlugins(IRenamingCommand, plugins)
60b9a11d04ccab30d2dbadeb6103932115950b64
3,598,263
def _tess_ffi_file(file_name): """ TESS FFI File """ # tess2018229142941-s0001-4-3-0120-s_ffic.fits # yyyyddd sssss ccc # s0001/2018/229/4-3 # 18-23 4-8 8-11 24-27 sector = file_name[18:23] year = file_name[4:8] day_number = file_name[8:11] camera_chip = file_name[24:27] ...
8a0381c1c6566ecd518e8e7c0033453a1a9e66fe
3,598,264
import logging import os def read_in_results( path_result, seasons, model_yeardays_daytype ): """Read and post calculate results from txt files and store into container Arguments --------- path_result : str Paths seasons : dict seasons model_yea...
73a9d38e1593aa58a411a4d54ff39cb4dac07742
3,598,265
def pairwise_distance(feature, squared=False): """Computes the pairwise distance matrix with numerical stability. output[i, j] = || feature[i, :] - feature[j, :] ||_2 Args: feature: 2-D Tensor of size [number of data, feature dimension]. squared: Boolean, whether or not to square the pairwise ...
eb53830e8e11309c17ea2b3e5e0bae5d87aeafee
3,598,266
def path_specific_constraints(prefix, constraints, var_mapping): """Creates duplicate constraints with all variables replaced with path specific copies""" new_constraints = [] for cs in constraints: new_cs = [path_specific_expr(prefix, c, var_mapping) for c in cs] new_constraints.append...
0a0344f7e811dd1bdfa04fe251359bea23b74472
3,598,267
import torch def get_style_grams(style_im, cfg): """ Computes the style grams for the vgg activations of the given style image. Args: --style_im: <tensor> The pre-processed style image. Should have shape (ch, h, w) --cfg: <dict> The training config dictionary Returns: <list> The ...
c2f9e30cd42d99b548875860fb6ff6c3373c81bc
3,598,268
import torch def fft_shift(input: torch.Tensor) -> torch.Tensor: """ PyTorch version of np.fftshift Args - input: (Bx)CxHxWx2 Return - ret: (Bx)CxHxWx2 """ dims = [i for i in range(1 if input.dim() == 4 else 2, input.dim() - 1)] # H, W shift = [input.size(dim) // 2 for dim in dim...
9a08c3e33516378b80a7a53cf17915d9baa5d290
3,598,269
from typing import Callable def fcn_from_str(name: str) -> Callable: """ Get the matching function. This method is a workaround / utility tool to intended to work with optuna. Since we can not pass functions directly, we pass a sting. :param name: name of the function :return: the function ""...
abcf93d1c13e484d375d55550e3e0e599cdbdeba
3,598,270
from typing import Mapping from typing import Any import json def get_config(config_path: str = "secrets/config_oauth.json") -> Mapping[str, Any]: """ Get the config from /test_input """ with open(config_path, "r") as f: return json.loads(f.read())
9ad1726bc5b1017f47872ce422d1c7a6fbf5d59c
3,598,271
def flop(x): """ Flops each 1/2 byte with the adjacent 1/2 byte. Flop is its own inverse. """ left = x & FLOP_MASK right = x & ~FLOP_MASK return ((right << 4) | (left >> 4)) & ID_MASK
8b0208c11cbab8a92671de2ccdc94f7c030bce9a
3,598,272
def get_view_proxy_registration_name(proxy): """Assuming the given proxy is registered in the group 'views', lookup the proxy's registration name with the servermanager""" return servermanager.ProxyManager().GetProxyName("views", proxy)
a85cd2dfbc83e2d94a14413a9174ce0f288e7529
3,598,273
def LMpM_total_size(ell_min, ell_max): """Total array size of Wigner D matrix Assuming an array (e.g., Wigner D matrices) in the order [[ell,mp,m] for ell in range(ell_min, ell_max+1) for mp in range(-ell,ell+1) for m in range(-ell,ell+1)] this function returns the tot...
7a6175640236ec3bc905d3b458f99eedbc792e09
3,598,274
def get_signature_locals(f, loc): """Filters locals to only include keys in original method signature""" return {k: v for k, v in loc.items() if k in signature(f).parameters}
d157623fc0af02e2de6518697b2f2c8a59a72f96
3,598,275
def filter_factory(global_conf, **local_conf): """ paste.deploy app factory for creating WSGI proxy apps. """ conf = global_conf.copy() conf.update(local_conf) if config_true_value(conf.get('read_only')): register_swift_info('read_only') def read_only_filter(app): return Re...
d6ea8e82d61b38f37f8400f0534a063452bc28fc
3,598,276
def map_obs_subfields(epochs_selec, obs_fieldID, obs_subfield, mapdic): """Return boolean array corresponding to observed subfields. Parameters ---------- epochs_selec : numpy.array(bool) Actual observations selection. obs_fieldID : bool Id of pre selected observed fields. obs_s...
a27b1c37ec827b4a2f1dee0a6cc930c253676739
3,598,277
def value_at_depht_in_BT(tree, depth): """ O(n) time O(n) space """ if depth == 0: return [tree.value] if tree.left and tree.right: return []+value_at_depht_in_BT(tree.left, depth-1)+value_at_depht_in_BT(tree.right, depth-1) if tree.left: return []+value_at_depht_in_BT(tree.left, depth-1) if tree.right:...
dc4bcc8398fe1357d0fb8a903b26828cd20c093d
3,598,278
def load_base_library(): """Load style library defined in this package.""" library = read_style_directory(BASE_LIBRARY_PATH) return library
b027dfcbc8a622a37689470ecb3a1d3a83edffd7
3,598,279
def hdbx_keymap(): """ HDBX配列 デフォルトレイヤーをこの配列にしたい場合は、AdjustレイヤーでK (Lower + Raise + K) ,----------------------------------. ,----------------------------------. | Q | W | E | , | . | | Y | D | P | F | : | |------+------+------+------+------| ...
3cd38fc34ffc4a76398d04163478a8db4791f873
3,598,280
def get_fcurve_data_path_property(fcurve): """ Gets fcurve's data path property Example fcurve's data_path: 'sequence_editor.sequences_all["Transform"].scale_start_x' For that example path this function will return 'scale_start_x' :param fcurve: Fcurve instance to get data path from :return: The la...
0a7ce5fecdaa5cb1fe0024a18f6b6f057b5fe6cb
3,598,281
import torch import tqdm def train(config_path, model_path, model_type, src_filename, trg_filename): """ flags: saveto: str reload: store_true config_path: str pretrain_path: str, default="" model_name: str log_path: str """ # ==========================...
c1d085c9cd458543c6978bb919c806ccc816560e
3,598,282
import subprocess def _ReadFileTailInShell(file_path, line): """Tails the file in the last several lines.""" return subprocess.check_output(['tail', '-%d' % line, file_path])
614e55daf67c9e3ec996ce730df608fc40e25aef
3,598,283
import ctypes import numpy def ctypes2numpy(cptr, length, dtype): """convert a ctypes pointer array to numpy array """ assert isinstance(cptr, ctypes.POINTER(ctypes.c_float)) res = numpy.zeros(length, dtype=dtype) assert ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]) return res
d4f85de74946e5477f2f29bfa5cce119d3fe66a3
3,598,284
def align(offset, alignment): """ Return the offset aligned to the nearest greater given alignment Arguments: - `offset`: An integer - `alignment`: An integer """ if offset % alignment == 0: return offset return offset + (alignment - (offset % alignment))
1f9d8fd4d4ac7798e14ee92d83510bb4b0ba09aa
3,598,285
def update_path(alpha, beta, gradE, delta, T=100, k=5): """ Update the path along the direction -gradE :param alpha: numpy ndarray of shape (2,M) of M samples :param beta: numpy ndarray of shape (2,M) of M samples :param gradE: numpy ndarray of shape (2,M) of M samples :param delta: gradient pa...
b570d447dbc1eabc5b58e3be8fe68577b0c572fb
3,598,286
def convert_str_length_to_int(length): """ Convert a position in char to integer """ if type(length) is int: return length if length in "0123456789": return int(length) elif length <= "Z" and length >= "A": return ord(length) - ord("A") + 10 elif length == "z": return...
d89a56bbf542f8c76cee219b1759a054c6894119
3,598,287
from typing import Tuple def angles(a: float, e: float, r: float) -> Tuple[float, float]: """ theta = arccos((a * (1 - e * e) - r) / (e * r)) :param a: semi-major axis :type a: float :param e: eccentricity :type e: float :param r: radius vector :type r: float :return: the two thet...
8a6796dbcef6f9044d4f51811462087ad0b59e76
3,598,288
def parse_property_string(prop_str): """ Generate valid property string for extended xyz files. (ref. https://libatoms.github.io/QUIP/io.html#extendedxyz) Args: prop_str (str): Valid property string, or appendix of property string Returns: valid property string """ if prop_...
24a865dcf2cba5b5f840e3e682fd58486b658355
3,598,289
def getPacketKey(opCode): """ Gets the packet key for a given instruction Input: - opCode: The opcode of instruction for which the packet key has to be generated Output: - The packet keys initialized in packetDict function for the given opcode """ if opCode in ["00000", "00001", "0001...
c7730a444a4e8dacc20ae83038ddfc04ca5ba721
3,598,290
import torch def stack_sample(sample): """Stack a sample from multiple sensors""" # If there is only one sensor don't do anything if len(sample) == 1: return sample[0] # Otherwise, stack sample stacked_sample = {} for key in sample[0]: # Global keys (do not stack) if k...
1b17f43b048a86759409ee5b6cdbc506c36a588b
3,598,291
def map_to_legacy_object_map(m): """Converts a Soy map to a Soy legacy_object_map. legacy_object_maps must have string keys, but maps do not have this restriction. Args: m: Map to convert. Returns: An equivalent legacy_object_map, with keys coerced to strings. """ return {str(key): m[key] for k...
17423488a85011c7be5429af58a5baf26ab8e30a
3,598,292
def getLastRecords(desde, hasta): """ Esta tabla retorna una lista de tuplas de la forma (id_segment, data, timestamp) con los ultimos registros agregados a la tabla "historical" """ # realizando una consulta # desde = datetime.datetime.strptime(desde, '%Y-%m-%dT%H:%M:%S-03:00') # hasta = da...
eaa41ea6ba981701dfe21c3108723b2240e940bf
3,598,293
def Terrahawk(): # A.K.A. the Dillon Mayhew Matroid """ Return the Terrahawk matroid. The Terrahawk is a binary matroid that is a sporadic exception in a chain theorem for internally 4-connected binary matroids. See [CMO2011]_. EXAMPLES:: sage: M = matroids.named_matroids.Terrahawk() ...
c48dfda7e7ac4132aa274f2e83f61a9ccf83baca
3,598,294
def session_mm_secondary_master_tcp_master_publish_pull(): """ Returns an unused localhost port """ return get_unused_localhost_port()
a01d291f9ba18cd87e7d2a6ffc292bc004386b16
3,598,295
def MikotaPair(n): """Build a pair of full diagonal matrices for the generalized eigenvalue problem. The Mikota pair acts as a nice test since the eigenvalues are the squares of the integers n, n=1,2,... """ x = np.arange(1, n+1) B = diag(1./x) y = np.arange(n-1, 0, -1) z = np.arange(2*n...
3091f54c44a910a787748d204bb692d425f62a6c
3,598,296
def as_composite(identifier: str) -> str: """ Translate the identifier of a mapry composite to a composite name in C++. :param identifier: mapry identifier of a composite :return: translated to a C++ identifier of a composite >>> as_composite(identifier='Some_URL_class') 'SomeURLClass' ""...
9a702dbd2f9b4dfb65102a18f4924be432a85282
3,598,297
def create_rsa_public_and_private_from_pem(pem, passphrase=None): """ <Purpose> Generate public and private RSA keys from an optionally encrypted PEM. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ... ---...
1c11fa3d8e761992fdc4212e90f373465a103907
3,598,298
import signal import subprocess def end_process(proc): """ Makes absolutely sure that a process is definitely well and truly dead. Args: proc (subprocess.Popen): Popen object for the process """ expected_return = 0 if proc.poll() is None: # I'm not dead! expected_retur...
db821cca944b0899404ea710d8b34dcafb75a4c2
3,598,299