content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def mtl_to_json(mtl_text): """ Convert Landsat MTL file to dictionary of metadata values """ mtl = {} for line in mtl_text.split('\n'): meta = line.replace('\"', "").strip().split('=') if len(meta) > 1: key = meta[0].strip() item = meta[1].strip() if key !...
310be04e9fbf756e9cf5ead60e53aae974d2ed50
3,640,000
def endian_swap(word): """Given any string, swap bits and return the result. :rtype: str """ return "".join([word[i:i+2] for i in [6, 4, 2, 0]])
dfca46a012602150957a0830cf30cc6b6790df80
3,640,001
import logging def get_grundsteuer(request_id: str): """ Route for retrieving job status of a grundsteuer tax declaration validation from the queue. :param request_id: the id of the job. """ try: raise NotImplementedError() except NotImplementedError: logging.getLogger().info("...
d92431ff1e09652d78b7beeaeabdeb2d502d0829
3,640,002
def str_to_col_grid_lists(s): """ Convert a string to selected columns and selected grid ranges. Parameters: s: (str) a string representing one solution. For instance, *3**9 means 2 out of 5 dimensions are selected; the second and the last columns are selected, and their co...
4f5c67afa0dc97070b08223acbe6764010fd213a
3,640,003
from typing import Union import uuid from typing import List def get_installation_indices_by_installation_id( db_session: Session, installation_id: Union[str, uuid.UUID] ) -> List[SlackIndexConfiguration]: """ Gets all the indices set up in an installation given on the ID of that installation. """ ...
0025599259a8f23e1da462d465448f3ed9a1701f
3,640,004
def convert_hdf(proj_dir, dir_list, hdf_filepath_list, hdf_filename_list): """Converts downloaded HDF file into geotiff file format.""" global src_xres global src_yres geotiff_list = [] """Converts MODIS HDF files to a geotiff format.""" print "Converting MODIS HDF files to geotiff format..." ...
f74b3e89b957746aaec9c04b4615bc5a3f7388e7
3,640,005
def _join_type_and_checksum(type_list, checksum_list): """ Join checksum and their correlated type together to the following format: "checksums": [{"type":"md5", "checksum":"abcdefg}, {"type":"sha256", "checksum":"abcd12345"}] """ checksums = [ { "type": c_type, "chec...
7f09ee72c6f51ad87d75a9b5e74ad8ef4776323f
3,640,006
def _local_groupby(df_rows, axis=0): """Apply a groupby on this partition for the blocks sent to it. Args: df_rows ([pd.DataFrame]): A list of dataframes for this partition. Goes through the Ray object store. Returns: A DataFrameGroupBy object from the resulting groupby. ""...
d78cd88bac7b03136bbe8401d207ee10c2d031f9
3,640,007
def colors_terrain() -> dict: """ Age of Empires II terrain colors for minimap. Credit for a list of Age of Empires II terrain and player colors goes to: https://github.com/goto-bus-stop/recanalyst. This function has great potential for contributions from designers and other specialists. ...
8e8f00d689ce00203127a9d810b6017ee5a04e18
3,640,008
import argparse def handle_kv_string(val): """This method is used as type field in --filter argument in ``buildtest buildspec find``. This method returns a dict of key,value pair where input is in format key1=val1,key2=val2,key3=val3 Args: val (str): Input string in ``key1=value1,key2=value2``...
ccc51c26fe881660606c49a1b84a67a796f4083a
3,640,009
def _load_dataset(dataset_config, *args, num_batches=None, **kwargs): """ Loads a dataset from configuration file If num_batches is None, this function will return a generator that iterates over the entire dataset. """ dataset_module = import_module(dataset_config["module"]) dataset_fn = ge...
5a35be1cac9bf405206ebc29b24aa0c08c27a18f
3,640,010
import codecs import os def file_consolidate(filename): """ Consolidates duplicates and sorts by frequency for speedy lookup. """ # TODO: Really big files should not be loaded fully into memory to sort them. # TODO: Make it more robust, actually checking for errors, etc. sorting_hat = [] in_file ...
0ebce1dca6700b19110fe045b1d9ae458ae1a9bb
3,640,011
def mock_checks_health(mocker: MockFixture): """Fixture for mocking checks.health.""" return mocker.patch("website_checker.checks.health")
aa6dff915bc1559838e46cc3e486d916a2c9f117
3,640,012
from typing import Dict from typing import Any def decode_jwt( jwt_string: str ) -> Dict[Any, Any]: """ Decodes the given JWT string without performing any verification. Args: jwt_string (str): A string of the JWT to decode. Returns: dict: A dictionary of the body of the JWT. ""...
39b3e14a3eb63723b2a8df21d5252ea937b0a41b
3,640,013
import collections def _resolve_references(navigation, version, language): """ Iterates through an object (could be a dict, list, str, int, float, unicode, etc.) and if it finds a dict with `$ref`, resolves the reference by loading it from the respective JSON file. """ if isinstance(navigation...
cb955d74844a86afc4982199ec81b18899466b0e
3,640,014
from typing import Optional from typing import Union from typing import Sequence def phq(data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None) -> pd.DataFrame: """Compute the **Patient Health Questionnaire (Depression) – 9 items (PHQ-9)**. The PHQ-9 is a measure for depression. ....
73b925b29a51b7f0575b3449b015d41d3287ca35
3,640,015
def mbc_choose_any_program(table_path): """ randomly select one item of MBCRadioProgramTable :param table_path: :return: """ table = playlist.MBCRadioProgramTable(table_path=table_path) programs = list(filter(lambda x: x.playlist_slug, table.programs)) random_id = randint(0, len(programs...
397c56f4a4d79bf3cd2ede5eba13414fcb1836ae
3,640,016
def logout_view(request): """Logout a user.""" logout(request) return redirect('users:login')
e14292c1fc78d8fb6f395129a1b77f141ce93627
3,640,017
import os def get_file_without_path(file_name, with_extension=False): """ get the name of a file without its path """ base = os.path.basename(file_name) if not with_extension: base = os.path.splitext(base)[0] return base
f6cf8c8003fe24a2b5ed265c3497bc866d201fb2
3,640,018
def _cast(vtype, value): """ Cast a table type into a python native type :param vtype: table type :type vtype: string :param value: value to cast :type value: string """ if not vtype: return None if isinstance(value, str): return_value = value.strip() ...
27ffdb0dac7d7e5f092a798630e6b874626a27b2
3,640,019
def L2Norm(inputs, axis=0, num_axes=-1, eps=1e-5, mode='SUM', **kwargs): """L2 Normalization, introduced by `[Liu et.al, 2015] <https://arxiv.org/abs/1506.04579>`_. Parameters ---------- inputs : Tensor The input tensor. axis : int The start axis of stats region. num_axes : int ...
20c0a1677874adfbd6c24cb6f662d1c0dc6c93f1
3,640,020
from typing import Union from typing import Sequence import inspect def has_option(obj, keywords: Union[str, Sequence[str]]) -> bool: """ Return a boolean indicating whether the given callable `obj` has the `keywords` in its signature. """ if not callable(obj): return False sig = inspect.s...
de2c6d4d458a8db6f0ff555d04570897e3440c10
3,640,021
import mmh3 import struct def create_element_rand(element_id): """ This function simply returns a 32 bit hash of the element id. The result value should be used a random priority. :param element_id: The element unique identifier :return: an random integer """ if isinstance(element_id, int...
095ced835235bec4b042a8a8b5eb3c44e967390e
3,640,022
def _ul_add_action(actions, opt, res_type, stderr): """Create new and append it to the actions list""" r = _UL_RES[opt] if r[0] is None: _ul_unsupported_opt(opt, stderr) return False # we always assume the 'show' action to be requested and eventually change it later actions.append( ...
098492f8bd875c611650fa773fd308d1097bcd18
3,640,023
from typing import List from typing import Any import time def _pack(cmd_id: int, payload: List[Any], privkey: datatypes.PrivateKey) -> bytes: """Create and sign a UDP message to be sent to a remote node. See https://github.com/ethereum/devp2p/blob/master/rlpx.md#node-discovery for information on how UDP...
11ade65dc4ceceab509d13456845d37671b8abfb
3,640,024
def clip_boxes(boxes, shape): """ :param boxes: (...)x4, float :param shape: h, w """ orig_shape = boxes.shape boxes = boxes.reshape([-1, 4]) h, w = shape boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0) boxes[:, 2] = np.minimum(boxes[:, 2], w) boxes[:, 3] = np.minimum(boxes[:...
60dbdb4d3aee5a4a0f7dc076ad6d8415ddc82ba0
3,640,025
def loss_fn( models, backdoored_x, target_label, l2_factor=settings.BACKDOOR_L2_FACTOR, ): """loss function of backdoor model loss_student = softmax_with_logits(teacher(backdoor(X)), target) + softmax_with_logits(student(backdoor(X)), target) + L2_norm(mask_matrix) Args: models(Python dict): teacher...
d13fa05f4f5ac7adbebb62a48774cfc552c3d42e
3,640,026
from .models import OneTimePassword, compute_expires_at def create_otp(slug, related_objects=None, data=None, key_generator=None, expiration=None, deactivate_old=False): """ Create new one time password. One time password must be identified with slug. Args: slug: string for OTP identification. ...
20cbfd88b676ff0357fa5a37a51a3ffa24b4f76b
3,640,027
def get_pod_from_dn(dn): """ This parses the pod from a dn designator. They look like this: topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min """ pod = POD_REGEX.search(dn) if pod: return pod.group(1) else: return None
23b790bf7b216239916ba86829bb5bee0e346a4a
3,640,028
import trace def extend_table(rows, table): """ appends the results of the array to the existing table by an objectid """ try: dtypes = np.dtype( [ ('_ID', np.int), ('DOM_DATE', '|S48'), ('DOM_DATE_CNT', np.int32), ('D...
fc34b897d7e23e8833a63b0fd7ce72cd090f35ab
3,640,029
def drawblock(arr, num_class=10, fixed=False, flip=False, split=False): """ draw images in block :param arr: array of images. format='NHWC'. sequence=[cls1,cls2,cls3,...,clsN,cls1,cls2,...clsN] :param num_class: number of class. default as number of images across height. Use flip=True to set number of w...
221dc90d8a674963221abe11720d23ac92af6225
3,640,030
def with_key(output_key_matcher): """Check does it have a key.""" return output_key_matcher
5bcb64550ce202f66ac43325fe8876249b45c52d
3,640,031
def generatePersistenceManager(inputArgument, namespace = None): """Generates a persistence manager base on an input argument. A persistence manager is a utility object that aids in storing persistent data that must be saved after the interpreter shuts down. This function will interpret the input argum...
a1042764974d1b8030c6b6dd2add444bea9e521c
3,640,032
def get_app(): """ Creates a Sanic application whose routes are documented using the `api` module. The routes and their documentation must be kept in sync with the application created by `get_benchmark_app()`, so that application can serve as a benchmark in test cases. """ app = Sanic("test_api...
1f8a11ee404082dcca0c1df91910157e5c169854
3,640,033
import base64 def predict(request): """View to predict output for selected prediction model Args: request (json): prediction model input (and parameters) Returns: json: prediction output """ projects = [{"name":"Erschließung Ob den Häusern Stadt Tengen", "id":101227}, ...
364db414d2c5811df0fe36e516868e0db76f896b
3,640,034
def is_dict(etype) -> bool: """ Determine whether etype is a Dict """ return type(etype) is GenericMeta and etype.__extra__ is dict
fb0e422e08abd3b20611a8817300334d32638b49
3,640,035
import torch from typing import List def hidden_state_embedding(hidden_states: torch.Tensor, layers: List[int], use_cls: bool, reduce_mean: bool = True) -> torch.Tensor: """ Extract embeddings from hidden attention state layers. Parameters ---------- hidden_states ...
f732e834f9c3437a4a7278aa6b9bfc54589b093b
3,640,036
from datetime import datetime def is_new_user(day: datetime.datetime, first_day: datetime.datetime): """ Check if user has contributed results to this project before """ if day == first_day: return 1 else: return 0
8da8039d1c8deb5bb4414565d3c9dc19ce15adb6
3,640,037
def to_ndarray(X): """ Convert to numpy ndarray if not already. Right now, this only converts from sparse arrays. """ if isinstance(X, np.ndarray): return X elif sps.issparse(X): print('Converting from sparse type: {}'.format(type(X))) return X.toarray() else: ...
337a78066316f32cf3a4f541d38c78de18750264
3,640,038
def _2d_gauss(x, y, sigma=2.5 / 60.0): """A Gaussian beam""" return np.exp(-(x ** 2 + y ** 2) / (2 * sigma ** 2))
c010989499682e4847376a162852c9f758907385
3,640,039
def attach_task_custom_attributes(queryset, as_field="task_custom_attributes_attr"): """Attach a json task custom attributes representation to each object of the queryset. :param queryset: A Django projects queryset object. :param as_field: Attach the task custom attributes as an attribute with this name. ...
584d2f918ae1844beb5cab71318691094de6d56d
3,640,040
import torch def softmax_like(env, *, trajectory_model, agent_model, log=False): """softmax_like :param env: OpenAI Gym environment :param trajectory_model: trajectory probabilistic program :param agent_model: agent's probabilistic program :param log: boolean; if True, print log info """ ...
7b51e0336399914e357b4dbed0490e93fb22f70a
3,640,041
def bulk_add(packages, user): """ Support bulk add by processing entries like: repo [org] """ added = 0 i = 0 packages = packages.split('\n') num = len(packages) org = None results = str() db.set(config.REDIS_KEY_USER_SLOTNUM_PACKAGE % user, num) results += "Add...
7b027b45e6e3385fc3bc3da8916b8322dde7cfda
3,640,042
def laser_heater_to_energy_spread(energy_uJ): """ Returns rms energy spread in induced in keV. Based on fits to measurement in SLAC-PUB-14338 """ return 7.15*sqrt(energy_uJ)
59feb872f0c652e0ef28b0958d2b25c174a79152
3,640,043
def apparent_attenuation(og, fg): """Apparent attenuation """ return 100.0 * (float(og) - float(fg)) / float(og)
e22ce07229baa4eacb7388280630d6097e21f364
3,640,044
def most_similar(W, vocab, id2word, word, n=15): """ Find the `n` words most similar to the given `word`. The provided `W` must have unit vector rows, and must have merged main- and context-word vectors (i.e., `len(W) == len(word2id)`). Returns a list of word strings. """ assert len(W) == ...
3e13a1e24935c7eacea9973c9af315d0a2a0fca4
3,640,045
import os import json def getRecordsFromDb(): """Return all records found in the database associated with :func:`dbFilePath()`. List of records are cached using an application configuration entry identified by ``_CACHED_RECORDS`` key. See also :func:`openDb`. """ try: records = flask...
881ad1b813019f796fe70c1795c3ad4a4d8ef303
3,640,046
def build_cell(num_units, num_layers, cell_fn, initial_state=None, copy_state=True, batch_size=None, output_dropout_rate=0., input_shape=None, attention_mechanism_fn=None, memory=None, ...
85d284ba314bea94ba015f7a85d0ba6685103292
3,640,047
def setup(hass: HomeAssistant, config: ConfigType) -> bool: """Use config values to set up a function enabling status retrieval.""" conf = config[DOMAIN] host = conf[CONF_HOST] port = conf[CONF_PORT] apcups_data = APCUPSdData(host, port) hass.data[DOMAIN] = apcups_data # It doesn't really ...
ccb2061fe8c36b799e5179f113c380d379ebec9d
3,640,048
import signal def _lagged_coherence_1freq(x, f, Fs, N_cycles=3, f_step=1): """Calculate lagged coherence of x at frequency f using the hanning-taper FFT method""" # Determine number of samples to be used in each window to compute lagged coherence Nsamp = int(np.ceil(N_cycles * Fs / f)) # For each N-...
8a1cefe6fa2ef87dbc71f3f4449afc4406fa2c5f
3,640,049
def program_hash(p:Program)->Hash: """ Calculate the hashe of a program """ string=";".join([f'{nm}({str(args)})' for nm,args in p.ops if nm[0]!='_']) return md5(string.encode('utf-8')).hexdigest()
f12ed910bc94070f64fe673ddd81925a704c700a
3,640,050
async def get_events(user_creds, client_creds, list_args, filter_func=None): """List events from all calendars according to the parameters given. The supplied credentials dict may be updated if tokens are refreshed. :param user_creds: User credentials from `obtain_user_permission`. :param client_creds...
00a99194c993c5155a03b985ba46fec84fd82ad7
3,640,051
import logging import pickle def process_file(input_file, input_type, index, is_parallel): """ Process an individual SAM/BAM file. How we want to process the file depends on the input type and whether we are operating in parallel. If in parallel the index must be loaded for each input file. If th...
a10c6b520fb586f4320f538b91adf7e7add4ace3
3,640,052
def add_dictionaries(coefficients, representatives, p): """ Computes a dictionary that is the linear combination of `coefficients` on `representatives` Parameters ---------- coefficients : :obj:`Numpy Array` 1D array with the same number of elements as `representatives`. Each entry ...
ffdb894b11509a72bc6baadc4c8c0d0d15f98110
3,640,053
def dropsRowsWithMatchClassAndDeptRemainderIsZero(df, Col, RemainderInt, classToShrink): """ Takes as input a dataframe, a column, a remainder integer, and a class within the column. Returns the dataframe minus the rows that match the ClassToShrink in the Col and have a depth from the DEPT col with a remain...
f88ec5e8293d753defe0a6d31f083e52218011ba
3,640,054
import sys from meerschaum.config._paths import ( PLUGINS_RESOURCES_PATH, PLUGINS_ARCHIVES_RESOURCES_PATH, PLUGINS_INIT_PATH ) from meerschaum.utils.warnings import error, warn as _warn import plugins from meerschaum.utils.packages import attempt_import def import_plugins( plugins_to_import: Union...
10e434c64c9f32a857cf074bef2e8bce821f00d0
3,640,055
import re from datetime import datetime def _opendata_to_section_meeting(data, term_year): """Converts OpenData class section info to a SectionMeeting instance. Args: data: An object from the `classes` field returned by OpenData. term_year: The year this term is in. """ date = data['d...
bdbd2160d61732e3d33357f3f65489ae004fd1aa
3,640,056
import requests import json def get_token(): """ returns a session token from te internal API. """ auth_url = '%s/sessions' % local_config['INTERNAL_API_BASE_URL'] auth_credentials = {'eppn': 'worker@pebbles', 'password': local_config['SECRET_KEY']} try: r = request...
da875c11dd887a895fe6c133cba3d30e3b73082c
3,640,057
def setlist(L): """ list[alpha] -> set[alpha] """ # E : set[alpha] E = set() # e : alpha for e in L: E.add(e) return E
7607d3d47ea5634773298afaea12d03759c0f1d4
3,640,058
from typing import List import re def ek_8_fix(alts: List[str]) -> List[str]: """ Replace ek, 8 patterns in text. This is google ASR specifc. Google gets confused between 1 and 8. Therefore if alternatives only contain 8 and 1, we change everything to 8 pm. TODO: Another really structurally...
a1cbfda0db1d049fac703ecf771d6d7b0ae008d6
3,640,059
def _pixel_at(x, y): """ Returns (r, g, b) color code for a pixel with given coordinates (each value is in 0..256 limits) """ screen = QtGui.QGuiApplication.primaryScreen() color = screen.grabWindow(0, x, y, 1, 1).toImage().pixel(0, 0) return ((color >> 16) & 0xFF), ((color >> 8) & 0xFF), ...
62341d5d7edc3529b5184babddf475bc35f407bf
3,640,060
from datetime import datetime import time def parse_tibia_time(tibia_time: str) -> datetime: """Gets a time object from a time string from tibia.com""" tibia_time = tibia_time.replace(",","").replace("&#160;", " ") # Getting local time and GMT t = time.localtime() u = time.gmtime(time.mktime(t)) ...
da9e8f4a9b8a94161d215ff1119d8510de57b434
3,640,061
def a3v(V: Vector3) -> np.ndarray: """Converts vector3 to numpy array. Arguments: V {Vector3} -- Vector3 class containing x, y, and z. Returns: np.ndarray -- Numpy array with the same contents as the vector3. """ return np.array([V.x, V.y, V.z])
f32476c613a8032bf7119d5b99a89e72c56628d2
3,640,062
def _p_value_color_format(pval): """Auxiliary function to set p-value color -- green or red.""" color = "green" if pval < 0.05 else "red" return "color: %s" % color
ae58986dd586a1e6cd6b6281ff444f18175d1d32
3,640,063
def rms(da, dim=None, dask='parallelized', keep_attrs=True): """ Reduces a dataarray by calculating the root mean square along the dimension dim. """ # TODO If dim is None then take the root mean square along all dimensions? if dim is None: raise ValueError('Must supply a dimension alon...
c34575469fffb3ad1099a05b66acb31320e8f7c4
3,640,064
def generator(seed): """ build the generator network. """ weights_initializer = tf.truncated_normal_initializer(stddev=0.02) # fully connected layer to upscale the seed for the input of # convolutional net. target = tf.contrib.layers.fully_connected( inputs=seed, num_outputs...
93258f49ba0fc7d7d03507bdc7dc413b2a9e23d5
3,640,065
from typing import Callable import logging def solve_fxdocc_root(iws, e_onsite, concentration, hilbert_trafo: Callable[[complex], complex], beta: float, occ: float = None, self_cpa_iw0=None, mu0: float = 0, weights=1, n_fit=0, restricted=True, **root_kwds) -> RootFxdocc: ...
e0550d50d7d1b69e26982b42f44a540bf408881f
3,640,066
def getn_hidden_area(*args): """getn_hidden_area(int n) -> hidden_area_t""" return _idaapi.getn_hidden_area(*args)
3265d4258ce6717e8ca23bd10754e1b1648d4217
3,640,067
def cdist(X: DNDarray, Y: DNDarray = None, quadratic_expansion: bool = False) -> DNDarray: """ Calculate Euclidian distance between two DNDarrays: .. math:: d(x,y) = \\sqrt{(|x-y|^2)} Returns 2D DNDarray of size :math: `m \\times n` Parameters ---------- X : DNDarray 2D array of s...
14a2368ff0717ff04e0477699ff13d20f359ba0d
3,640,068
def popcount_u8(x: np.ndarray): """Return the total bit count of a uint8 array""" if x.dtype != np.uint8: raise ValueError("input dtype must be uint8") count = 0 # for each item look-up the number of bits in the LUT for elem in x.flat: count += u8_count_lut[elem] return count
e85c07b3df7dcd993c0f1cc7f9dbecd97e8be317
3,640,069
from scipy import stats def split_errorRC(tr, t1, t2, q, Emat, maxdt, ddt, dphi): """ Calculates error bars based on a F-test and a given confidence interval q. Note ---- This version uses a Fisher transformation for correlation-type misfit. Parameters ---------- tr : :clas...
3155031382c881a15a8a300d6656cae1fc0fee64
3,640,070
import copy def filter_parts(settings): """ Remove grouped components and glyphs that have been deleted or split. """ parts = [] temp = copy.copy(settings['glyphs']) for glyph in settings['glyphs']: name = glyph['class_name'] if name.startswith("_split") or name.startswith("_gr...
f8d6a59eeeb314619fd4c332e2594dee3543ee9c
3,640,071
def kernel_zz(Y, X, Z): """ Kernel zz for second derivative of the potential generated by a sphere """ radius = np.sqrt(Y ** 2 + X ** 2 + Z ** 2) r2 = radius*radius r5 = r2*r2*radius kernel = (3*Z**2 - r2)/r5 return kernel
14f36fe23531994cd40c74d26b91477d266ca21c
3,640,072
def getAccentedVocal(vocal, acc_type="g"): """ It returns given vocal with grave or acute accent """ vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'}, 'e': {'g': u'\xe8', 'a': u'\xe9'}, 'i': {'g': u'\xec', 'a': u'\xed'}, 'o': {'g': u'\xf2', 'a': u'\xf3'}, ...
cfec276dac32e6ff092eee4f1fc84b412c5c915c
3,640,073
def env_initialize(env, train_mode=True, brain_idx=0, idx=0, verbose=False): """ Setup environment and return info """ # get the default brain brain_name = env.brain_names[brain_idx] brain = env.brains[brain_name] # reset the environment env_info = env.reset(train_mode=train_mode)[brain_na...
3c951a77009cca8c876c36965ec33781dd2c08dd
3,640,074
def lorentzianfit(x, y, parent=None, name=None): """Compute Lorentzian fit Returns (yfit, params), where yfit is the fitted curve and params are the fitting parameters""" dx = np.max(x) - np.min(x) dy = np.max(y) - np.min(y) sigma = dx * 0.1 amp = fit.LorentzianModel.get_amp_from_amplitude(...
cd221c3483ee7f54ac49baaeaf617ef8ec2b7fa7
3,640,075
def tf_quat(T): """ Return quaternion from 4x4 homogeneous transform """ assert T.shape == (4, 4) return rot2quat(tf_rot(T))
7fb2a7b136201ec0e6a92faf2cc030830df46fa5
3,640,076
def solve2(lines): """Solve the problem.""" result = 0 for group in parse_answers2(lines): result += len(group) return result
5990b61e713733ba855937b8191b8a8a4f503873
3,640,077
def get_contract_type(timestamp: int, due_timestamp: int) -> str: """Get the contract_type Input the timestamp and due_timestamp. Return which contract_type is. Args: timestamp: The target timestamp, you want to know. due_timestamp: The due timestamp of the contract. Returns: ...
3b3a084f786c82a5fc1b2a7a051e9005b3df5f0a
3,640,078
from typing import Any from typing import Optional from typing import Union from typing import Type from typing import Tuple from typing import Sequence from typing import cast def is_sequence_of(obj: Any, types: Optional[Union[Type[object], Tuple[Type[objec...
3762454785563c7787451efad143547f97ae8994
3,640,079
import os def anonymize_dicom(dicom_file,patient_name='anonymous', fields_to_anonymize=ANONYMIZATION_FIELDS, fields_to_return=None,path_to_save='.', new_dicom_name='anonymous.dcm'): """ Given a dicom file, alter the given fields, anonymizing the pati...
74b743a49fdde11befe8e5bf43da4d824cd70dba
3,640,080
def _parse_tree_height(sent): """ Gets the height of the parse tree for a sentence. """ children = list(sent._.children) if not children: return 0 else: return max(_parse_tree_height(child) for child in children) + 1
d6de5c1078701eeeb370c917478d93e7653d7f4f
3,640,081
def pandas_loss_p_g_i_t(c_m, lgd, ead, new): """ Distribution of losses at time t. long format (N_MC, G, K, T).""" mat_4D = loss_g_i_t(c_m, lgd, ead, new) names = ['paths', 'group_ID', 'credit_rating_rank', 'time_steps'] index = pds.MultiIndex.from_product([range(s)for s in mat_4D.shape], names=...
65e9db48eab0a40596b205a7304bd225eb5c93d0
3,640,082
import glob import os import sys def get_file_if_unique(location, ext): """Find file if unique for the provided extension.""" files = glob(os.path.join(location, ext)) if len(files) == 1: return files[0] else: print("Multiple/No " + ext[1:] + " files found in the working ...
38689006199fdedcc5a9d3a2c69fff716d5345a2
3,640,083
def find_available_pacs(pacs, pac_to_unstuck=None, pac_to_super=None, pac_to_normal=None): """ Finds the available pacs that are not assigned """ available_pacs = pacs['mine'] if pac_to_unstuck is not None: available_pacs = [x for x in available_pacs if x['id'] not in pac_to_unstuck.keys()...
4b6674fd87db2127d5fffa781431ccc9a9ff775a
3,640,084
async def login_for_access_token( form_data: OAuth2PasswordRequestForm = Depends(), ): """ Log in to your account using oauth2 authorization. In response we get an jwt authorization token which is used for granting access to data """ is_auth, scope = await authenticate_authority( for...
441326317f0f13275ad33e369efe419a605ac4eb
3,640,085
def get_plain_expressions(s): """Return a list of plain, non-nested shell expressions found in the shell string s. These are shell expressions that do not further contain a nested expression and can therefore be resolved indenpendently. For example:: >>> get_plain_expressions("${_pyname%${_pyname#?...
a3b0f6812ffe361e291b28c4273ca7cc975eb1e7
3,640,086
def create_indices(dims): """Create lists of indices""" return [range(1,dim+1) for dim in dims]
1a83b59eb1ca2b24b9db3c9eec05db7335938cae
3,640,087
def observed_property(property_name, default, cast=None): """Default must be immutable.""" hidden_property_name = "_" + property_name if cast is None: if cast is False: cast = lambda x: x else: cast = type(default) def getter(self): try: return...
7358557b221b5d4fa18fbd29cd02b47823cfdfe0
3,640,088
from typing import Callable from io import StringIO def query_helper( source: S3Ref, query: str, dest: S3Ref = None, transform: Callable = None ) -> StringIO: """ query_helper runs the given s3_select query on the given object. - The results are saved in a in memory file (StringIO) and returned. ...
3670734c76f615fe6deb3dfed8305cfc1740b124
3,640,089
def indicator_selector(row, indicator, begin, end): """Return Tons of biomass loss.""" dasy = {} if indicator == 4: return row[2]['value'] for i in range(len(row)): if row[i]['indicator_id'] == indicator and row[i]['year'] >= int(begin) and row[i]['year'] <= int(end): dasy[s...
329411837633f4e28bea4b2b261b6f4149b92fb1
3,640,090
import math def xy_from_range_bearing(range: float, bearing: float) -> map_funcs.Point: """Given a range in metres and a bearing from the camera this returns the x, y position in metres relative to the runway start.""" theta_deg = bearing - google_earth.RUNWAY_HEADING_DEG x = CAMERA_POSITION_XY.x + ra...
a2575437b52003660d83b241da13f10687fa4241
3,640,091
def flask_get_modules(): """Return the list of all modules --- tags: - Modules responses: 200: description: A list of modules """ db_list = db.session.query(Module).all() return jsonify(db_list)
21352458773143f785658488e34f9e486c7f818d
3,640,092
def create_user(username, password): """Registra um novo usuario caso nao esteja cadastrado""" if User.query.filter_by(username=username).first(): raise RuntimeError(f'{username} ja esta cadastrado') user = User(username=username, password=generate_password_hash(password)) db.session.add(user) ...
1a50d31b764cce10d0db78141041deafc15f7c40
3,640,093
import numpy def _get_mesh_colour_scheme(): """Returns colour scheme for MESH (maximum estimated size of hail). :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`. :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`. """ colour_list = [ [152,...
4301822297d069a6cc289e72b5bf388ffae01cf4
3,640,094
def index(): """ Serve index page. """ try: data = get_latest_covid_stats() except FailedRequestError as err: # Log error response to logger logger.debug( f"Request to Public Health England COVID-19 API failed: {err}.") flash("An error occurred obtaining l...
bca737abaeb6891072f64b5a6caa6cf739da4ee2
3,640,095
import os from functools import reduce def get_files(directory, include_hidden, include_empty): """Returns all FILES in the directory which apply to the filter rules.""" return (os.path.join(dir_path, filename) for dir_path, _, file_names in os.walk(directory) for filename in file_name...
439e74215f284492bd0505af3b49fd285a94e5f0
3,640,096
def _manually_create_user(username, pw): """ Create an *active* user, its server directory, and return its userdata dictionary. :param username: str :param pw: str :return: dict """ enc_pass = server._encrypt_password(pw) # Create user directory with default structure (use the server fun...
21d523ae29121697e63460302d8027499b4d896d
3,640,097
def update_geoscale(df, to_scale): """ Updates df['Location'] based on specified to_scale :param df: df, requires Location column :param to_scale: str, target geoscale :return: df, with 5 digit fips """ # code for when the "Location" is a FIPS based system if to_scale == 'state': ...
e62083f176cd749a88b2e73774e70140c6c5b9ac
3,640,098
import json def translate(text, from_lang="auto", to_lang="zh-CN"): """translate text, return the result as json""" url = 'https://translate.googleapis.com/translate_a/single?' params = [] params.append('client=gtx') params.append('sl=' + from_lang) params.append('tl=' + to_lang) params.a...
944a5a90f60d8e54c402100e512bbce2bbb407c5
3,640,099