content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import PIL def resize_img(img, size, keep_aspect_ratio=True): """resize image using pillow Args: img (PIL.Image): pillow image object size(int or tuple(in, int)): width of image or tuple of (width, height) keep_aspect_ratio(bool): maintain aspect ratio relative to width Returns: ...
b3ddc2c929fa530f2af612c3021802f7bd1ed285
3,658,260
from typing import Tuple def calculate_clip_from_vd(circuit: DiodeCircuit, v_d: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ :returns: v_in, v_out """ Rs = circuit.Rs Is = circuit.diode.Is n = circuit.diode.n Vt = circuit.diode.Vt Rp = circuit.Rp Rd = circuit.Rd Id = Is * (np.exp(v_d / (n * Vt)) - 1.0...
ec60231622c06f1a972af050c0403e8247aa75ed
3,658,261
def tex_coord(x, y, n=8): """ Return the bounding vertices of the texture square. """ m = 1.0 / n dx = x * m dy = y * m return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
0776dd61aa83b9c9d8afe7574607022c9f7c2b77
3,658,262
def uniindtemp_compute(da: xr.DataArray, thresh: str = "0.0 degC", freq: str = "YS"): """Docstring""" out = da - convert_units_to(thresh, da) out = out.resample(time=freq).mean() out.attrs["units"] = da.units return out
640a50e2a4ff61192f97e31c782be58437d301d0
3,658,263
def verify_parentheses(parentheses_string: str) -> bool: """Takes input string of only '{},[],()' and evaluates to True if valid.""" open_parentheses = [] valid_parentheses_set = {'(', ')', '[', ']', '{', '}'} parentheses_pairs = { ')' : '(', ']' : '[', '}' : '{' } if le...
2e2c07314d474b582f12af8cf53a311c0fa323c1
3,658,264
import time def _stableBaselineTrainingAndExecution(env, typeAgent, numberOptions, mode): """"Function to execute Baseline algorithms""" if typeAgent == 2: model = A2C(MlpPolicy, env, verbose=1) else: model = PPO2(MlpPolicy, env, verbose=1) print("Training model....") startTime =...
7fd91b28ab475fb43ea7e6af4ca17302863e269a
3,658,265
def string_to_hexadecimale_device_name(name: str) -> str: """Encode string device name to an appropriate hexadecimal value. Args: name: the desired name for encoding. Return: Hexadecimal representation of the name argument. """ length = len(name) if 1 < length < 33: he...
53d5c5a221a2c3dac46c5fb15d051d78592b109b
3,658,266
def createTeam( firstIndex, secondIndex, isRed, first = 'DefensiveAgent', second = 'OffensiveAgent'): """ This function should return a list of two agents that will form the team, initialized using firstIndex and secondIndex as their agent index numbers. isRed is True if the red team is being created, ...
b99e8f548b6e6166517fb35a89f5381ef6d7692b
3,658,267
def str_dice(die): """Return a string representation of die. >>> str_dice(dice(1, 6)) 'die takes on values from 1 to 6' """ return 'die takes on values from {0} to {1}'.format(smallest(die), largest(die))
29eb7f6aa43e068e103016bbc8c35699fbf4a3ea
3,658,268
def transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, make_image_summary=True): """A stack of tr...
0f56315a972acc235dba7ec48c8b83b84bd6b3f1
3,658,270
import re def compute_dict(file_path): """Computes the dict for a file whose path is file_path""" file_dict = {} with open(file_path, encoding = 'utf8') as fin: for line in fin: line = line.strip() txt = re.sub('([^a-zA-Z0-9\s]+)',' \\1 ',line) txt = re.sub('([\...
821e29181aad781279b27174be0fd7458b60481f
3,658,272
def get_scale(lat1, lon1, var, desired_distance, unit='miles'): """ Calculate the difference in either latitude or longitude that is equivalent to some desired distance at a given point on Earth. For example, at a specific point, how much does latitude need to change (assuming longitude is constant) to be equal ...
258d95b1372d1b863f121552abb2ba6047f5aaad
3,658,273
from typing import Union from pathlib import Path async def connect_unix(path: Union[str, PathLike]) -> UNIXSocketStream: """ Connect to the given UNIX socket. Not available on Windows. :param path: path to the socket :return: a socket stream object """ path = str(Path(path)) return...
825d69aa19afd593b355063639cbcd91cb23e9fa
3,658,274
def isMatch(s, p): """ Perform regular simple expression matching Given an input string s and a pattern p, run regular expression matching with support for '.' and '*'. Parameters ---------- s : str The string to match. p : str The pattern to match. Returns -------...
92cd3171afeb73c6a58bbcd3d3ea6d707401cb09
3,658,275
def cepheid_lightcurve_advanced(band, tarr, m0, period, phaseshift, shape1, shape2, shape3, shape4, datatable=None): """ Generate a Cepheid light curve. More flexibility allowed. band: one of "B", "V", "I" tarr: times at which you want the light curve evaluated m0: mean magnitude for the light curve...
7e9a94f4e59f3da31c8c21a6e35822a0ac0d8051
3,658,276
def app_list(context): """ Renders the app list for the admin dashboard widget. """ context["dashboard_app_list"] = admin_app_list(context["request"]) return context
699aa55403169f87c26fc9655d8c6dcb29aa14d2
3,658,277
def path_depth(path: str, depth: int = 1) -> str: """Returns the `path` up to a certain depth. Note that `depth` can be negative (such as `-x`) and will return all elements except for the last `x` components """ return path_join(path.split(CONFIG_SEPARATOR)[:depth])
c04899974560b2877db313fa0444203cc483a2b0
3,658,278
def read_config_file(filename, preserve_order=False): """ Read and parse a configuration file. Parameters ---------- filename : str Path of configuration file Returns ------- dict Configuration dictionary """ with open(filename) as f: return parse_config...
6a0aab4ae0da3abdddf080c98ee69eb92d2d8d04
3,658,279
def languages_list_handler(): """Get list of supported review languages (language codes from ISO 639-1). **Example Request:** .. code-block:: bash $ curl https://critiquebrainz.org/ws/1/review/languages \\ -X GET **Example Response:** .. code-block:: json { ...
5b8791ad5d71a94486d96379f62ed9ebf850ec59
3,658,280
def corpus_subdirs(path): """ pathの中のdir(txt以外)をlistにして返す """ subdirs = [] for x in listdir(path): if not x.endswith('.txt'): subdirs.append(x) return subdirs
645f198f78795dbc5c14b7cfd400fa1e94dc9244
3,658,281
def edit_string_for_tags(tags): """ Given list of ``Tag`` instances or tag strings, creates a string representation of the list suitable for editing by the user, such that submitting the given string representation back without changing it will give the same list of tags. Tag names which contai...
a05b6cb12e36304096d076e015077f1ec1cc3432
3,658,282
from typing import Optional def convert_postgres_array_as_string_to_list(array_as_string: str) -> Optional[list]: """ Postgres arrays are stored in CSVs as strings. Elasticsearch is able to handle lists of items, but needs to be passed a list instead of a string. In the case of an empty array, ret...
cc64fe8e0cc765624f80abc3900985a443f76792
3,658,283
def generate_prime_number(min_value=0, max_value=300): """Generates a random prime number within the range min_value to max_value Parameters ---------- min_value : int, optional The smallest possible prime number you want, by default 0 max_value : int, optional The largest possible...
539f74fcdba2c366b0fe13b0bc0fab6727300ec1
3,658,284
def sort_extended_practitioner(practitioner): """ sort on date latestDate Then alpha on other practitioners :param practitioner: :return: practitioner """ uniques = [] for p in practitioner: if find_uniques(p, uniques): uniques.append(p) return uniques
476d9adf9d93b88f20166b1e95715aaa54bd67f9
3,658,285
def lti13_login_params_dict(lti13_login_params): """ Return the initial LTI 1.3 authorization request as a dict """ utils = LTIUtils() args = utils.convert_request_to_dict(lti13_login_params) return args
026e65c132666816f774a05f6977dac9ab194b77
3,658,286
def calcShannonEnt(dataset): """ 计算数据集的熵 输入:数据集 输出:熵 """ numEntris = len(dataset) labelCounts = {} for featVec in dataset: currentLabel = featVec[-1] #每行数据中的最后一个数,即数据的决策结果 label if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0 l...
9b64d0ad0bb517deb77c24f3c08e004d255daa68
3,658,287
import array def get_boundaries_medians(things, lowers=[], uppers=[]): """Return the boundaries and medians of given percentage ranges. Parameters: 1. things: a list of numbers 2. lowers: lower percentage limits 3. uppers: upper percentage limits Returns: lower, median, upper ...
d83365ad2d9598dc19c279a6b20424746f53d6ce
3,658,288
def getMeanBySweep(abf, markerTime1, markerTime2): """ Return the mean value between the markers for every sweep. """ assert isinstance(abf, pyabf.ABF) pointsPerSecond = abf.dataRate sweepIndex1 = pointsPerSecond * markerTime1 sweepIndex2 = pointsPerSecond * markerTime2 means = [] ...
8051d67c832c9b331798f896b8f98c2673770a94
3,658,289
def add_prefix(key): """Dummy key_function for testing index code.""" return "id_" + key
96dda0bd57b4eb89f17c8bb69ad48e3e1675a470
3,658,291
def schedule_conv2d_nhwc_tensorcore(cfg, outs): """TOPI schedule callback""" s = te.create_schedule([x.op for x in outs]) def _callback(op): if "conv2d_nhwc_tensorcore" in op.tag: schedule_nhwc_tensorcore_cuda(cfg, s, op.output(0)) traverse_inline(s, outs[0].op, _callback) retu...
318be211f02469c1e971a9303f48f92f88af5755
3,658,292
import tqdm def simulate(config, show_progress=False): """Simulate incarceration contagion dynamics. Parameters ---------- config : Config Config object specifying simulation parameters. Returns ------- dict Dictionary specifying simulated population of agents. """ ...
b5b813c1038d6b473ff3f4fa6beccdad2615f2af
3,658,293
import cel_import def get_event_log(file_path: str = None, use_celonis=False): """ Gets the event log data structure from the event log file. Dispatches the methods to be used by file tyoe :param use_celonis: If the attribute is set to true the event log will be retrieved from celonis :param file_...
9b77a2bed9d6551cc2d0e4eb607de0d81b95c6f3
3,658,294
def find_peak(corr, method='gaussian'): """Peak detection algorithm switch After loading the correlation window an maximum finder is invoked. The correlation window is cut down to the necessary 9 points around the maximum. Afterwards the maximum is checked not to be close to the boarder of the correlat...
685eb87cefc6cd2566a9e9d40f827a1fea010b73
3,658,295
def binaryToString(binary): """ 从二进制字符串转为 UTF-8 字符串 """ index = 0 string = [] rec = lambda x, i: x[2:8] + (rec(x[8:], i - 1) if i > 1 else '') if x else '' fun = lambda x, i: x[i + 1:8] + rec(x[8:], i - 1) while index + 1 < len(binary): chartype = binary[index:].index('0') # 存放字...
2044109d573abe7c9428b64b289b5aa82ec4d624
3,658,297
import functools import logging def disable_log_warning(fun): """Temporarily set FTP server's logging level to ERROR.""" @functools.wraps(fun) def wrapper(self, *args, **kwargs): logger = logging.getLogger('pyftpdlib') level = logger.getEffectiveLevel() logger.setLevel(logging.ERRO...
6990a2a1a60ea5a24e4d3ac5c5e7fbf443825e48
3,658,298
def create_csv_step_logger(save_dir: pyrado.PathLike, file_name: str = "progress.csv") -> StepLogger: """ Create a step-based logger which only safes to a csv-file. :param save_dir: parent directory to save the results in (usually the algorithm's `save_dir`) :param file_name: name of the cvs-file (with...
355c205cf5f42b797b84005c1485c2b6cae74c2e
3,658,299
def _key_chord_transition_distribution( key_chord_distribution, key_change_prob, chord_change_prob): """Transition distribution between key-chord pairs.""" mat = np.zeros([len(_KEY_CHORDS), len(_KEY_CHORDS)]) for i, key_chord_1 in enumerate(_KEY_CHORDS): key_1, chord_1 = key_chord_1 chord_index_1 = i...
0e89b1e11494237c526170f25286c3ad098a1023
3,658,300
def level_set( current_price, standard_deviation, cloud, stop_mod, take_profit_mod, ): """ Calculates risk and reward levels. Should return a stop loss and take profit levels. For opening a new position. Returns a stop (in the format (StopType, offset)) and a take profit level. """ stop...
541a15b22bc830db530658c10515a15def196516
3,658,301
def back(deque): """ returns the last elemement in the que """ if length(deque) > 0: return deque[-1] else: return None
810d2135cf39af7959f6142be4b2b3abee8d6185
3,658,302
import json import operator def my_subs_helper(s): """Helper function to handle badly formed JSON stored in the database""" try: return {'time_created':s.time_created, 'json_obj':sorted(json.loads(s.json_data).iteritems(), key=operator.itemgetter(0)), 'plain_json_obj':json.dumps(json.loads(s.json_data...
4b649d865c3a99f89111baa694df4902e65243e6
3,658,303
def dynamic_features(data_dir, year, data_source, voronoi, radar_buffers, **kwargs): """ Load all dynamic features, including bird densities and velocities, environmental data, and derived features such as estimated accumulation of bird on the ground due to adverse weather. Missing data is interpolated...
fd5675b127d6a20f930d8ee88366e7426c5a09b9
3,658,304
def __normalize_allele_strand(snp_dfm): """ Keep all the alleles on FWD strand. If `strand` is "-", flip every base in `alleles`; otherwise do not change `alleles`. """ on_rev = (snp_dfm.loc[:, "strand"] == "-") has_alleles = (snp_dfm.loc[:, "alleles"].str.len() > 0) condition = (on_rev & h...
1ebe00294eb55de96d68fc214bd5051d40a2dfa5
3,658,305
def add_to_codetree(tword,codetree,freq=1): """ Adds one tuple-word to tree structure - one node per symbol word end in the tree characterized by node[0]>0 """ unique=0 for pos in range(len(tword)): s = tword[pos] if s not in codetree: codetree[s] = [0,{}] ...
e92a48f112e7a774bed3b125509f7f64dce0a7ec
3,658,306
def TA_ADXm(data, period=10, smooth=10, limit=18): """ Moving Average ADX ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/ Parameter...
40f41b013127b122bddf66e3dfe53f746c89b3c7
3,658,307
def remove_from_dict(obj, keys=list(), keep_keys=True): """ Prune a class or dictionary of all but keys (keep_keys=True). Prune a class or dictionary of specified keys.(keep_keys=False). """ if type(obj) == dict: items = list(obj.items()) elif isinstance(obj, dict): items = list(...
b1d9a2bd17269e079ce136cc464060fc47fe5906
3,658,308
def unify_qso_catalog_uvqs_old(qsos): """Unifies the name of columns that are relevant for the analysis""" qsos.rename_column('RA','ra') qsos.rename_column('DEC','dec') qsos.rename_column('FUV','mag_fuv') qsos.rename_column('Z','redshift') qsos.add_column(Column(name='id',data=np.arange(len(qso...
8fe561e7d6e99c93d08efe5ff16d6e37ed66ab4e
3,658,309
def get_hash_key_name(value): """Returns a valid entity key_name that's a hash of the supplied value.""" return 'hash_' + sha1_hash(value)
b2bba3031efccb5dab1781695fc39c993f735e71
3,658,310
import yaml def yaml_dumps(value, indent=2): """ YAML dumps that supports Unicode and the ``as_raw`` property of objects if available. """ return yaml.dump(value, indent=indent, allow_unicode=True, Dumper=YamlAsRawDumper)
ed368fb84967190e460c1bcf51bd573323ff4f46
3,658,311
def poi_remove(poi_id: int): """Removes POI record Args: poi_id: ID of the POI to be removed """ poi = POI.get_by_id(poi_id) if not poi: abort(404) poi.delete() db.session.commit() return redirect_return()
26c1cb2524c6a19d9382e9e0d27947a0d2b2a98c
3,658,312
def stringToTupleOfFloats(s): """ Converts s to a tuple @param s: string @return: tuple represented by s """ ans = [] for i in s.strip("()").split(","): if i.strip() != "": if i == "null": ans.append(None) else: ans.append(float...
7eec23232f884035b12c6498f1e68616e4580878
3,658,313
import json import requests def create_training(training: TrainingSchema): """ Create an training with an TrainingSchema :param training: training data as TrainingSchema :return: http response """ endpoint_url = Config.get_api_url() + "training" job_token = Config.get_job_token() heade...
c0ce20fc68cbb3d46b00e451b85bf01991579bcc
3,658,314
def respects_language(fun): """Decorator for tasks with respect to site's current language. You can use this decorator on your tasks together with default @task decorator (remember that the task decorator must be applied last). See also the with-statement alternative :func:`respect_language`. **Ex...
547629321d649a102a0c082b1eddcac32334432c
3,658,315
def zero_one_window(data, axis=(0, 1, 2), ceiling_percentile=99, floor_percentile=1, floor=0, ceiling=1, channels_axis=None): """ :param data: Numpy ndarray. :param axis: :param ceiling_percentile: Percentile value of the foreground to set to the ceiling. :param floor_percentile...
4056433a9f3984bebc1c99f30be4f8e9ddc31026
3,658,316
def get_event_stderr(e): """Return the stderr field (if any) associated with the event.""" if _API_VERSION == google_v2_versions.V2ALPHA1: return e.get('details', {}).get('stderr') elif _API_VERSION == google_v2_versions.V2BETA: for event_type in ['containerStopped']: if event_type in e: ...
89a32228d3ad0ecb92c6c0b45664903d6f4b507d
3,658,318
def xA(alpha, gamma, lsa, lsd, y, xp, nv): """Calculate position where the beam hits the analyzer crystal. :param alpha: the divergence angle of the neutron :param gamma: the tilt angle of the deflector :param lsa: the sample-analyzer distance :param lsd: the sample deflector distance :param y:...
0dfb9bd7b761fa0669893c692f3adb2a5cb079c4
3,658,319
from typing import Optional from datetime import datetime def find_recent_login(user_id: UserID) -> Optional[datetime]: """Return the time of the user's most recent login, if found.""" recent_login = db.session \ .query(DbRecentLogin) \ .filter_by(user_id=user_id) \ .one_or_none() ...
153dc509e2382e8f9eb18917d9be04d171ffdee9
3,658,320
async def async_remove_config_entry_device( hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry ) -> bool: """Remove ufp config entry from a device.""" unifi_macs = { _async_unifi_mac_from_hass(connection[1]) for connection in device_entry.connections if conn...
f8ae37a454f5c5e3314676162ff48e1e05530396
3,658,321
def batch_unsrt_segment_sum(data, segment_ids, num_segments): """ Performas the `tf.unsorted_segment_sum` operation batch-wise""" # create distinct segments per batch num_batches = tf.shape(segment_ids, out_type=tf.int64)[0] batch_indices = tf.range(num_batches) segment_ids_per_batch = segment_ids +...
299a514e926c43564960288c706c1d535620144b
3,658,322
import json def read_json(file_name): """Read json from file.""" with open(file_name) as f: return json.load(f)
2eccab7dddb1c1038de737879c465f293a00e5de
3,658,323
def get_role(request): """Look up the "role" query parameter in the URL.""" query = request.ws_resource.split('?', 1) if len(query) == 1: raise LookupError('No query string found in URL') param = parse.parse_qs(query[1]) if 'role' not in param: raise LookupError('No role parameter found in the query s...
87cc8f15a3d0aeb45a8d7ea67fb34573e41b7df7
3,658,324
def login(username: str, password: str) -> Person: """通过用户名和密码登录智学网 Args: username (str): 用户名, 可以为准考证号, 手机号 password (str): 密码 Raises: ArgError: 参数错误 UserOrPassError: 用户名或密码错误 UserNotFoundError: 未找到用户 LoginError: 登录错误 RoleError: 账号角色未知 Returns: ...
a982cddb107cc8ccf8c9d1868e91299cd6ac07f3
3,658,325
def _decode_end(_fp): """Decode the end tag, which has no data in the file, returning 0. :type _fp: A binary `file object` :rtype: int """ return 0
5e8da3585dda0b9c3c7cd428b7e1606e585e15c6
3,658,326
def make_dqn_agent(q_agent_type, arch, n_actions, lr=2.5e-4, noisy_net_sigma=None, buffer_length=10 ** 6, final_epsilon=0.01, final_exploration_frames=10 ** 6, ...
0b5974e30a12ef760a424d8d229319ccfee3119a
3,658,327
def build_consensus_from_haplotypes(haplotypes): """ # ======================================================================== BUILD CONSENSUS FROM HAPLOTYPES PURPOSE ------- Builds a consensus from a list of Haplotype objects. INPUT ----- [HAPLOTYPE LIST] [haplotypes] ...
977e59e77e45cb4ccce95875f4802a43028af060
3,658,328
from typing import List from typing import Dict from typing import Tuple def convert_data_for_rotation_averaging( wTi_list: List[Pose3], i2Ti1_dict: Dict[Tuple[int, int], Pose3] ) -> Tuple[Dict[Tuple[int, int], Rot3], List[Rot3]]: """Converts the poses to inputs and expected outputs for a rotation averaging a...
1f058ae1925f5392416ec4711b55e849e277a24c
3,658,329
def all_arrays_to_gpu(f): """Decorator to copy all the numpy arrays to the gpu before function invokation""" def inner(*args, **kwargs): args = list(args) for i in range(len(args)): if isinstance(args[i], np.ndarray): args[i] = to_gpu(args[i]) return f(*a...
25ea43a611ac8a63aa1246aaaf810cec71be4c3f
3,658,330
def create_intersect_mask(num_v, max_v): """ Creates intersect mask as needed by polygon_intersection_new in batch_poly_utils (for a single example) """ intersect_mask = np.zeros((max_v, max_v), dtype=np.float32) for i in range(num_v - 2): for j in range((i + 2) % num_v, num_v - int(i =...
32d2758e704901aa57b70e0edca2b9292df2583a
3,658,331
def gdi_abuse_tagwnd_technique_bitmap(): """ Technique to be used on Win 10 v1703 or earlier. Locate the pvscan0 address with the help of tagWND structures @return: pvscan0 address of the manager and worker bitmap and the handles """ window_address = alloc_free_windows(0) manager_bitmap_handle = create_bitmap(0x1...
e77253d082b9aaaa083c84ffdbe8a74ae0b84b0b
3,658,332
def check_stop() -> list: """Checks for entries in the stopper table in base db. Returns: list: Returns the flag, caller from the stopper table. """ with db.connection: cursor = db.connection.cursor() flag = cursor.execute("SELECT flag, caller FROM stopper").fetchone() ...
b2694938541704508d5304bae9abff25da2e0fc9
3,658,334
def get_camelcase_name_chunks(name): """ Given a name, get its parts. E.g: maxCount -> ["max", "count"] """ out = [] out_str = "" for c in name: if c.isupper(): if out_str: out.append(out_str) out_str = c.lower() else: out_s...
134a8b1d98af35f185b37c999fbf499d18bf76c5
3,658,336
def _GetBuildBotUrl(builder_host, builder_port): """Gets build bot URL for fetching build info. Bisect builder bots are hosted on tryserver.chromium.perf, though we cannot access this tryserver using host and port number directly, so we use another tryserver URL for the perf tryserver. Args: builder_hos...
551ac7ee9079009cd8b52e41aeabb2b2e4e10c21
3,658,337
def case_two_args_positional_callable_first(replace_by_foo): """ Tests the decorator with one positional argument @my_decorator(goo) """ return replace_by_foo(goo, 'hello'), goo
fa5ca0af3d5af7076aebbb8364f29fc64b4e3c28
3,658,338
def cal_sort_key( cal ): """ Sort key for the list of calendars: primary calendar first, then other selected calendars, then unselected calendars. (" " sorts before "X", and tuples are compared piecewise) """ if cal["selected"]: selected_key = " " else: selected_key = "X" ...
fd1d8b32ee904d3684decba54268d926c5fd3d82
3,658,339
from datetime import datetime def select_zip_info(sample: bytes) -> tuple: """Print a list of items contained within the ZIP file, along with their last modified times, CRC32 checksums, and file sizes. Return info on the item selected by the user as a tuple. """ t = [] w = 0 z = ZipFile(s...
aac5b04c40552c09d07bf2db0c2d4431fc168aa2
3,658,340
def unitary_ifft2(y): """ A unitary version of the ifft2. """ return np.fft.ifft2(y)*np.sqrt(ni*nj)
16dfe62cea08a72888cc3390f4d85f069aac5718
3,658,342
def orb_scf_input(sdmc): """ find the scf inputs used to generate sdmc """ myinputs = None # this is the goal sdep = 'dependencies' # string representation of the dependencies entry # step 1: find the p2q simulation id p2q_id = None for key in sdmc[sdep].keys(): if sdmc[sdep][key].result_names[0] == 'o...
c319693e9673edf540615025baf5b5199c5e27a3
3,658,343
def is_success(code): """ Returns the expected response codes for HTTP GET requests :param code: HTTP response codes :type code: int """ if (200 <= code < 300) or code in [404, 500]: return True return False
fa502b4989d80edc6e1c6c717b6fe1347f99990d
3,658,344
from typing import Optional from typing import Union async def asyncio( *, client: AuthenticatedClient, json_body: SearchEventIn, ) -> Optional[Union[ErrorResponse, SearchEventOut]]: """Search Event Dado um Trecho, uma lista de Grupos que resultam da pesquisa por esse Trecho e um price token...
6bf2a312d41cf77776e0c333ed72080c030a7170
3,658,345
def get_symmtrafo(newstruct_sub): """??? Parameters ---------- newstruct_sub : pymatgen structure pymatgen structure of the bulk material Returns ------- trafo : ??? ??? """ sg = SpacegroupAnalyzer(newstruct_sub) trr = sg.get_symmetry_dataset() trafo = [] ...
9a346b4d0761de467baae1ee5f4cb0c623929180
3,658,346
def convert_sentence_into_byte_sequence(words, tags, space_idx=32, other='O'): """ Convert a list of words and their tags into a sequence of bytes, and the corresponding tag of each byte. """ byte_list = [] tag_list = [] for word_index, (word, tag) in enumerate(zip(words, tags)): tag_ty...
2288d22e44d99ee147c9684befd3d31836a66a9d
3,658,347
def get_number_rows(ai_settings, ship_height, alien_height): """Determina o numero de linhas com alienigenas que cabem na tela.""" available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (2 * alien_height)) return ...
473f73bc5fb4d6e86acb90f01d861d4d8561d494
3,658,349
def map_ref_sites(routed: xr.Dataset, gauge_reference: xr.Dataset, gauge_sites=None, route_var='IRFroutedRunoff', fill_method='r2', min_kge=-0.41): """ Assigns segs within routed boolean 'is_gauge' "identifiers" and what each seg's upstream and downstream reference se...
a2146e532a7aa95ba0753aaddc6d6da2cc4f1c67
3,658,351
def get_error(est_track, true_track): """ """ if est_track.ndim > 1: true_track = true_track.reshape((true_track.shape[0],1)) error = np.recarray(shape=est_track.shape, dtype=[('position', float), ('orientation', float), ...
5ccdb12b844de9b454f62375358d4a1e1b91e6f7
3,658,352
from typing import Any def test_conflict(): """ Tiles that have extras that conflict with indices should produce an error. """ def tile_extras_provider(hyb: int, ch: int, z: int) -> Any: return { Indices.HYB: hyb, Indices.CH: ch, Indices.Z: z, } ...
2d2e86f5d60762d509e7c27f5a74715c868abbc4
3,658,353
import json def get_node_to_srn_mapping(match_config_filename): """ Returns the node-to-srn map from match_conf.json """ with open(match_config_filename) as config_file: config_json = json.loads(config_file.read()) if "node_to_srn_mapping" in config_json: return config_j...
37bf2f266f4e5163cc4d6e9290a8eaf17e220cd3
3,658,354
def nest_dictionary(flat_dict, separator): """ Nests a given flat dictionary. Nested keys are created by splitting given keys around the `separator`. """ nested_dict = {} for key, val in flat_dict.items(): split_key = key.split(separator) act_dict = nested_dict final_key = ...
f5b8649d916055fa5911fd1f80a8532e5dbee274
3,658,356
def write(path_, *write_): """Overwrites file with passed data. Data can be a string, number or boolean type. Returns True, None if writing operation was successful, False and reason message otherwise.""" return _writeOrAppend(False, path_, *write_)
3bd5db2d833c5ff97568489596d3dcea47c1a9f4
3,658,357
import json def prepare_saab_data(sequence): """ Processing data after anarci parsing. Preparing data for SAAB+ ------------ Parameters sequence - sequence object ( OAS database format ) ------------ Return sequence.Sequence - full (not-numbered) antibody sequence...
f88ba3f2badb951f456678e33f3371d80934754e
3,658,358
import math def _is_equidistant(array: np.ndarray) -> bool: """ Check if the given 1D array is equidistant. E.g. the distance between all elements of the array should be equal. :param array: The array that should be equidistant """ step = abs(array[1] - array[0]) for i in range(0, len(arr...
d12c12e48545697bdf337c8d20e45a27fb444beb
3,658,360
def list_a_minus_b(list1, list2): """Given two lists, A and B, returns A-B.""" return filter(lambda x: x not in list2, list1)
8fbac6452077ef7cf73e0625303822a35d0869c3
3,658,361
def is_equivalent(a, b): """Compares two strings and returns whether they are the same R code This is unable to determine if a and b are different code, however. If this returns True you may assume that they are the same, but if this returns False you must not assume that they are different. i...
c37ea6e8684c1d2fcd5d549836c9115da98c7b2f
3,658,362
def solve(lines, n): """Solve the problem.""" grid = Grid(lines) for _ in range(n): grid.step() return grid.new_infections
2db532a911e088dd58ee17bdc036ea017e979c8d
3,658,363
import requests def get_ingredient_id(): """Need to get ingredient ID in order to access all attributes""" query = request.args["text"] resp = requests.get(f"{BASE_URL_SP}/food/ingredients/search?", params={"apiKey":APP_KEY,"query":query}) res = resp.json() lst = {res['results'][i]["name"]:res['r...
8c58232f48883a4b1e2d76ca1504b3dccabdb954
3,658,364
def xticks(ticks=None, labels=None, **kwargs): """ Get or set the current tick locations and labels of the x-axis. Call signatures:: locs, labels = xticks() # Get locations and labels xticks(ticks, [labels], **kwargs) # Set locations and labels Parameters ---------- ...
a6b044ffc9efdc279495c25735745006de9d7a8c
3,658,365
def main() -> None: """ Program entry point. :return: Nothing """ try: connection = connect_to_db2() kwargs = {'year_to_schedule': 2018} start = timer() result = run(connection, **kwargs) output_results(result, connection) end = timer() print...
53727547a16c8b203ca89d54f55ddbd8b2f2645b
3,658,366
def delete(home_id): """ Delete A About --- """ try: return custom_response({"message":"deleted", "id":home_id}, 200) except Exception as error: return custom_response(str(error), 500)
408fe8db0a728b33d7a9c065944d706d6502b8b5
3,658,368
def round_to_sigfigs(x, sigfigs=1): """ >>> round_to_sigfigs(12345.6789, 7) # doctest: +ELLIPSIS 12345.68 >>> round_to_sigfigs(12345.6789, 1) # doctest: +ELLIPSIS 10000.0 >>> round_to_sigfigs(12345.6789, 0) # doctest: +ELLIPSIS 100000.0 >>> round_to_sigfigs(12345.6789, -1) # doctest:...
a5191f3c60e85d50a47a43aee38d7d1f14d3fdc6
3,658,369
import urllib import json def load_api_data (API_URL): """ Download data from API_URL return: json """ #actual download with urllib.request.urlopen(API_URL) as url: api_data = json.loads(url.read().decode()) #testing data ##with open('nrw.json', 'r') as testing_set: ## ...
61832a798ac616f3d1612ce69411d4f43ed85699
3,658,370
def test_parsing(monkeypatch, capfd, configuration, expected_record_keys): """Verifies the feed is parsed as expected""" def mock_get(*args, **kwargs): return MockResponse() test_tap: Tap = TapFeed(config=configuration) monkeypatch.setattr(test_tap.streams["feed"]._requests_session, "send", mo...
25a79966eba641e4b857c80e12fb123e8fc3477f
3,658,371
def hsl(h, s, l): """Converts an Hsl(h, s, l) triplet into a color.""" return Color.from_hsl(h, s, l)
081fb4b7e7fc730525d0d18182c951ad92fab895
3,658,372