content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reversedict(dct): """ Reverse the {key:val} in dct to {val:key} """ # print labelmap newmap = {} for (key, val) in dct.iteritems(): newmap[val] = key return newmap
f7a5a102546270a2e6aa7fb52d4fa6dd5e826753
3,638,900
from unfurl import yamlmanifest import os def createNewEnsemble(templateVars, project, targetPath, mono): """ If "localEnv" is in templateVars, clone that ensemble; otherwise create one from a template with templateVars """ # targetPath is relative to the project root assert not os.path.isabs...
c08400deec0099f6833cdd54c2240b10c8d2fd1e
3,638,901
from typing import Iterable from typing import Sequence from typing import Optional import logging import time import itertools def mincut_graph_tool(edges: Iterable[Sequence[np.uint64]], affs: Sequence[np.uint64], sources: Sequence[np.uint64], sinks: ...
be29b44cdeaddd5f26605d9793ebe6b2e2fe71fc
3,638,902
def mock_graph_literal(): """Creates a mock tree Metasyntactic variables: https://www.ietf.org/rfc/rfc3092.txt """ graph_dict = [ { "frame": {"name": "foo", "type": "function"}, "metrics": {"time (inc)": 130.0, "time": 0.0}, "children": [ { ...
4b65f0dfffe705963c1041fbbef65d85af306f4f
3,638,903
def parse_ADD_ins(tokens): """Attempts to parse an ADD instruction.""" failure = None assert len(tokens) > 0 if tokens[0].text.upper() != 'ADD': return failure statement = Obj() statement.type = 'STATEMENT' statement.statement_type = 'INSTRUCTION' statement.instruction = 'ADD' ...
ffc515d0079dbaf860a10de675542e798abfd4a3
3,638,904
import re def commonIntegerPredicate(field): """"return any integers""" return tuple(re.findall("\d+", field))
955dc61fa4293f21c707b538ea218b15d5a95fb2
3,638,905
def spatialft(image, cosine_window=True, rmdc=True): """Take the fourier transform of an image (or flow field). shift the quadrants around so that low spatial frequencies are in the center of the 2D fourier transformed image""" #raised cosyne window on image to avoid border artifacts (dim1,dim2) = ...
cafca20ec79dcaca6d6dfb11c18156077b172ab0
3,638,906
def _get_instrument_parameters(ufile, filemetadata): """ Return a dictionary containing instrument parameters. """ # pulse width pulse_width = filemetadata('pulse_width') pulse_width['data'] = ufile.get_pulse_widths() / _LIGHT_SPEED # m->sec # assume that the parameters in the first ray represent...
af6ee2097848a672ec18c2199faece072f3990f1
3,638,907
import os def get_deployment_mode(path): """ Work out the 'deployment mode' from the global attributes in a NetCDF file :param path: path to dataset :return: Mode as a value from `DeploymentModes` enumeration :raises ValueError: if mode cannot be determined or is invalid """ fname = os...
5f24adda063cb2efdc1853a5ce862c674dbb7afa
3,638,908
import re def split_reaction(reac): """ split a CHEMKIN reaction into reactants and products :param reac: reaction string :type reac: str :returns: reactants and products :rtype: (tuple of strings, tuple of strings) """ em_pattern = one_of_these([PAREN_PLUS_EM + STRING_END, ...
d9ccbf02bd8f037d42f9de5f30612a99a1d7d918
3,638,909
def bond_stereo_parities(sgr): """ bond parities, as a dictionary """ return mdict.by_key_by_position(bonds(sgr), bond_keys(sgr), BND_STE_PAR_POS)
7b80fdb861530e4389a83db1ef55f9552baf758d
3,638,910
def encode(text): """ Encode to base64 """ return [int(x) for x in text.encode('utf8')]
af51272d8edc25d46695ea3b35fd395ad26321b5
3,638,911
import socket def _get_ip(): """ :return: This computer's default AF_INET IP address as a string """ # find ip using answer with 75 votes # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib ip = '' sock = socket.socket(socket.AF_INET, socket.SOCK_D...
f39c961877a1ec026596a7ced01679411962fca4
3,638,912
def _get_value(cav, _type): """Get value of custom attribute item""" if _type == 'Map:Person': return cav["attribute_object"]["id"] \ if cav.get("attribute_object") else None if _type == 'Checkbox': return cav["attribute_value"] == '1' return cav["attribute_value"]
c8210579cf8b2a29dffc1f28a6e204fc9f89f274
3,638,913
def get_inference(model, vectorizer, topics, text, threshold): """ runs inference on text input paramaters ---------- model: loaded model to use to transform the input vectorizer: instance of the vectorizer e.g TfidfVectorizer(ngram_range=(2, 3)) topics: the list of topics in the model ...
e48ba018d372de317dd79fb678d69d2c83b4787b
3,638,914
def get_message_id(update: dict, status_update: str) -> int: """функция для получения номера сообщения. Описание - функция получает номер сообщения от пользователя Parameters ---------- update : dict новое сообщение от бота status_update : str состояние сообщения, изменено или ...
9b299c94e322ad9cea92fd73cb9e7a55f3364caa
3,638,915
def gmm_clustering_predict(model, X): """ X is a (N, 1) array """ X = np.clip(X, -2.5, 2.5) return model.predict(X)
9dcff9aa68fe008713dbb5142e16702bb68f65a0
3,638,916
import requests def http_request(url, method='GET', timeout=2, **kwargs): """Generic task to make an http request.""" headers = kwargs.get('headers', {}) params = kwargs.get('params', {}) data = kwargs.get('data', {}) request_kwargs = {} if headers: request_kwargs['headers'] = headers ...
f7605d5b88bb7e23a1b541b7103185d229427270
3,638,917
from typing import Type def unify_nest(args: Type[MultiNode], kwargs: Type[MultiNode], node_str, mode, axis=0, max_depth=1): """ Unify the input nested arguments, which consist of sub-arrays spread across arbitrary nodes, to unified arrays on the single target node. :param args: The nested positional...
392491382b31c566db7eb8b13a98001158d8153a
3,638,918
def ast_for_inv_exp(inv: 'Ast', ctx: 'ReferenceDict'): """ invExp ::= atomExpr (atomExpr | invTrailer)*; """ assert inv.name is UNameEnum.invExp atom_expr, *inv_trailers = inv res = ast_for_atom_expr(atom_expr, ctx) if len(inv_trailers) is 1: [each] = inv_trailers if each.n...
77de8d7c1fd5dfc4a8fefa04ee6c0a5da17a6bc1
3,638,919
def create_input_pipeline(files, batch_size, n_epochs, shape, crop_shape=None, crop_factor=1.0, n_threads=2): """Creates a pipefile from a list of image files. ...
17c26de3659cccd7e32d8297ed0e31167ef05c38
3,638,920
def confirm_email_page(): """Returns page for users that have not confirmed their email address""" if not g.loggedIn: return redirect(url_for('general.loginPage')) next = request.args.get('next') if general_db.is_activated(g.user): if next is not '': return make_auth_to...
e37c59e9f1fa1d710d2795257be1cfb8bc9aa3df
3,638,921
from bs4 import BeautifulSoup def get_movie_names(url_data): """Get all the movies from the webpage""" soup = BeautifulSoup(url_data, 'html.parser') data = soup.findAll('ul', attrs={'class' : 'ctlg-holder'}) #Get all the lines from HTML that are a part of ul with class = 'ctlg-holder' movie_list...
1cae6b0093f0e0ca9e361bdc207be9ea654e7c2b
3,638,922
def message_results(): """Shows the user their message, with the letters in sorted order.""" message = request.form.get('message') encrypted_message = sort_letters(message) return render_template('message_results.html', message=encrypted_message)
8e0868330c318c958da496a742f630583822bbd0
3,638,923
def flatten_dict(dicts, keys): """ Input is list of dicts. This operation pulls out the key in each dict and combines the values into a new list mapped to the original key. A new dictionary is formed with these key -> list mappings. """ return { key: flatten_n([d[key] for d in dicts]) fo...
ca037e47e2e6287145da693cd55f47719d463115
3,638,924
def render_url(fullpath, notebook=False): # , prefix="files"): """Converts a path relative to the notebook (i.e. kernel) to a URL that can be served by the notebook server, by prepending the notebook directory""" if fullpath.startswith('http://'): url = fullpath else: url = (radiopad...
ee401c4521cf93fe4ec95b2d3c1fb7dbe337ff52
3,638,925
def register(): """Register User route.""" email = request.form.get('email') password = request.form.get('password') new_user = User.register(email, password) if new_user: return jsonify({'message': 'Registration successful.'}), 201 return jsonify({'message': 'Invalid username or passwor...
a6148b514268e36fc28a69737718598fcc355460
3,638,926
import json def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """ record = event['Records'][0] message = json.loads( record['Sns']['Message'] ) return run_message(message)
1e7c8f774f62cddf633e51d631f74cad3fa1ec8e
3,638,927
def release_dp_mean_absolute_deviation(x, bounds, epsilon): """Release the dp mean absolute deviation. Assumes dataset size len(`x`) is public. Theorem 27: https://arxiv.org/pdf/2001.02285.pdf """ lower, upper = bounds sensitivity = (upper - lower) * 2. / len(x) x = np.clip(x, *bounds) ...
da49088e52fcd0ccf8358db072354fcd39de565e
3,638,928
import cloudpickle import pickle import os def get_configuration(spec_path): """Get mrunner experiment specification and gin-config overrides.""" try: with open(spec_path, 'rb') as f: specification = cloudpickle.load(f) except pickle.UnpicklingError: with open(spec_path) as f: ...
4e4d76b7fd9e3c27a16f9e1aeedaa21f5a97defd
3,638,929
def LoadScores(firstfile, prevfile): """Load the first and previous scores. For each peptide, compute a prize that is -log10(min p-value across all time points). Assumes the scores are p-values or equivalaent scores in (0, 1]. Do not allow null or missing scores. Return: data frame with scores a...
b6a0d9769795937a21aee195d782060db73ec494
3,638,930
import os def add_makeflags(job_core_count, cmd): """ Correct for multi-core if necessary (especially important in case coreCount=1 to limit parallel make). :param job_core_count: core count from the job definition (int). :param cmd: payload execution command (string). :return: updated payload ex...
c559b703894fed48e21c616125166b697e32c817
3,638,931
def _gen_find(subseq, generator): """Returns the first position of `subseq` in the generator or -1 if there is no such position.""" if isinstance(subseq, bytes): subseq = bytearray(subseq) subseq = list(subseq) pos = 0 saved = [] for c in generator: saved.append(c) if le...
ec89e787a61d684e2a7d0c8c2d0fb9c89cf73ada
3,638,932
def fnCalculate_Bistatic_RangeAndDoppler(pos_target,vel_target,pos_rx,pos_tx,wavelength): """ Calculate measurement vector consisting of bistatic range and Doppler shift for 3D bistatic case. pos_rx, pos_tx = position of Rx and Tx in [km]. pos_target = position of target in [km]. wavelength = wavele...
4cd5177a8ad0be0732821f6af7cf9030cadab781
3,638,933
def all_permits(target_dynamo_table): """ Simply return all data from DynamoDb Table :param target_dynamo_table: :return: """ response = target_dynamo_table.scan() data = response['Items'] while response.get('LastEvaluatedKey', False): response = target_dynamo_table.scan(Exclusi...
8efdaf4ff407d0e2ce8dd592eeac766b0ec2264b
3,638,934
def maximum_difference_sort_value(contributions): """ Auxiliary function to sort the contributions for the compare_plot. Returns the value of the maximum difference between values in contributions[0]. Parameters ---------- contributions: list list containing 2 elements: a Numpy....
cd7f66ec252199fb01b9891440d0f7da370c7b8e
3,638,935
import re import os def load_test_val_train_files(version): """Load the test, validation and train labels and images from the data folder. Also does the basic preprocessing (converting to the right datatype, clamping and rescaling etc.) return images_train, images_validation, images_test, labels_...
f85bb48840619a23c7a96ea5b5820ab8af6c9622
3,638,936
def get_primer_target_sequence(id, svStartChr, svStartPos, svEndChr, svEndPos, svType, svComment, primerTargetSize, primerOffset, blastdbcmd, genomeFile): """Get the sequences in which primers will be placed""" if svType in ["del", "inv3to3", "trans3to3", "trans3to5", "snv", "invRefA", "invAltA"]: targe...
b8b32319d6a37a2373a620b1be867ab838c54fdc
3,638,937
def human_format(num): """ :param num: A number to print in a nice readable way. :return: A string representing this number in a readable way (e.g. 1000 --> 1K). """ magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 return '%.2f%s' % (num, ['', 'K', 'M', 'G...
41e4f3823f756588c18b0fb926949a5aca9c6942
3,638,938
from typing import Optional from typing import Dict def torchserve( model_path: str, management_api: str, image: str = TORCHX_IMAGE, params: Optional[Dict[str, object]] = None, ) -> specs.AppDef: """Deploys the provided model to the given torchserve management API endpoint. >>> from torch...
b90ec26512525e3f23a54034a685be380ef0be96
3,638,939
def ExpandRange(r,s=1): """expand 1-5 to [1..5], step by 1-10/2""" if REGEX_PATTERNS['step'].search(r): [r1,s] = r.split('/') s=int(s) else: r1 = r (start,end) = r1.split('-') return [i for i in range(int(start),int(end)+1,s)]
1e8ca3b5b026c36817acfefd1666312b0bcccf23
3,638,940
def write_file_if_changed(name, data): """ Write a file if the contents have changed. Returns True if the file was written. """ if path_exists(name): old_contents = read_file(name) else: old_contents = '' if (data != old_contents): write_file(name, data) return True return False
42962e9f9159d8cab121826e223bfa10467b8d5c
3,638,941
def _get_preprocessor_loader(plugin_name): """Get a class that loads a preprocessor class. This returns a class with a single class method, ``transform``, which, when called, finds a plugin and defers to its ``transform`` class method. This is necessary because ``convert()`` is called as a decorato...
5b2c1687be92b21f31c0e9e28a3566505831c876
3,638,942
def preprocess_sample(data, word_dict): """ Args: data (dict) Returns: dict """ processed = {} processed['Abstract'] = [sentence_to_indices(sent, word_dict) for sent in data['Abstract'].split('$$$')] if 'Task 2' in data: processed['Label'] = label_to_onehot(data['Task...
0b1b50285be0afa1faf78917024b1e2cd01fb167
3,638,943
import yaml import torch def read_input_file(input_file_path): """ read inputs from input_file_path :param input_file_path: :return: """ cprint('[INFO]', bc.dgreen, "read input file: {}".format(input_file_path)) with open(input_file_path, 'r') as input_file_read: dl_inputs = yaml.l...
ade3584937997798b496690d5799e23effae1cd1
3,638,944
def task_deploy_docs() -> DoitTask: """Deploy docs to the Github `gh-pages` branch. Returns: DoitTask: doit task """ if _is_mkdocs_local(): # pragma: no cover return debug_task([ (echo, ('ERROR: Not yet configured to deploy documentation without "use_directory_urls"',)), ...
52101c7321618e9a1f98e4bd16c5e88b291b38da
3,638,945
def plugin(version: str) -> 'Plugin': """Get the application plugin.""" return XPXPlugin
8211b8b3f2aaedbbfe289184117e6964fad5cce5
3,638,946
def is_anaconda_5(): """ anaconda 5 has conda version 4.4.0 or greater... obviously :/ """ vers = conda_version() if not vers: return False ma = vers['major'] >= 4 mi = vers['minor'] >= 4 return ma and mi
cc4701bb788867a6370c53b48994c166dffa7cd4
3,638,947
def relay_array_map(c, fn, *array): """Implementation of array_map for Relay.""" assert fn.is_constant(Primitive) fn = fn.value if fn is P.switch: rfn = relay.where else: rfn = SIMPLE_MAP[fn] return rfn(*[c.ref(a) for a in array])
8d3d89ea131272f987054c198353ec7fc398e4a0
3,638,948
def get_multi_objects_dict(*args, params=None): """Convertir un array de objetos en diccionarios""" object_group = [] result = {} for data_object in args: if params is not None and params['fields']: fields = params['fields'] else: fields = [attr for attr in data_o...
2f4e2bc6e68bc77fedfae89ff4562cdab5fa91fb
3,638,949
from btu.manual_tests import ping_now def test_function_ping_now_bytes(): """ Picking the 'ping_now' function and return as bytes. """ queue_args = { "site": frappe.local.site, "user": frappe.session.user, "method": ping_now, "event": None, "job_name": "ping_now", "is_async": True, # always true; we...
0673efa3ff11aa9b55b470c4ac84a35f7878af98
3,638,950
def post_equals_form(post, json_response): """ Checks if the posts object is equal to the json object """ if post.title != json_response['title']: return False if post.deadline != json_response['deadline']: return False if post.details != json_response['details']: retu...
965a533c7ebbb70001bcdcb0e143b617708807e3
3,638,951
def get_shield(plugin: str) -> dict: """ Generate shield json for napari plugin. If the package is not a valid plugin, display 'plugin not found' instead. :param plugin: name of the plugin :return: shield json used in shields.io. """ shield_schema = { "color": "#0074B8", "la...
f1c7dadabd0b5fe6b1b0012188559b4958ca5fd0
3,638,952
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == expectedUN and password == expectedPW
e19759a1514fad47a085e3dad2180c5b8b49827c
3,638,953
def Lambda(t, y): """Original Arnett 1982 dimensionless bolometric light curve expression Calculates the bolometric light curve due to radioactive decay of 56Ni, assuming no other energy input. t: time since explosion in days y: Arnett 1982 light curve width parameter (typical 0.7 <...
85752fa09f1189ca7e24a32d821e36c58379572d
3,638,954
from datetime import datetime def get_utcnow_time(format: str = None) -> str: """ Return string with current utc time in chosen format Args: format (str): format string. if None "%y%m%d.%H%M%S" will be used. Returns: str: formatted utc time string """ if format is None: ...
994e47abde4a4b56bd0f22ccc41d7d91c7b3b8d0
3,638,955
def repair_branch(cmorph, cut, rmorph, rep, force=False): """Attempts to extend cut neurite using intact branch. Args: cmorph (treem.Morph): cut morphology. cut (treem.Node): cut node, from cmorph. rmorph (treem.Morph): repair morphology. rep (treem.Node): undamaged branch start...
1e76ec2619f1b74791c1258c65c649c25261a740
3,638,956
from datetime import datetime def parse_patient_dob(dob): """ Parse date string and sanity check. expects date string in YYYYMMDD format Parameters ---------- dob : str dob as string YYYYMMDD Returns ------- dob : datetime object """ try: dob = datetime....
a6c5f76cc2f335bc91d94dc5372542342d2ae9ae
3,638,957
def us2cycles(us): """ Converts microseconds to integer number of tProc clock cycles. :param cycles: Number of microseconds :type cycles: float :return: Number of tProc clock cycles :rtype: int """ return int(us*fs_proc)
51d405c512c146bdfda0a091470ad84593872819
3,638,958
from datetime import datetime def date_range(begin_date, end_date): """ 获取一个时间区间的list """ dates = [] dt = datetime.datetime.strptime(begin_date, "%Y-%m-%d") date = begin_date[:] while date <= end_date: dates.append(date) dt = dt + datetime.timedelta(1) date = dt...
a3373ab76752423eaf1484e5d66dc5d6334c4360
3,638,959
def scalar(name): """ Create a scalar variable with the corresponding name. The 'name' will be during code generation, so should match the variable name used in the C++ code. """ tname = name return symbols(tname)
8f1f7295d15b136be38383135729fe7717fd71b8
3,638,960
def add(number1, number2): """ This functions adds two numbers Arguments: number1 : first number to be passed number2 : second number to be passed Returns: number1*number2 the result of two numbers Examples: >>> add(0,0) 0 >>> add(1,1) 2 >>> add(1.1,2.2) ...
5db1a461f65672d5fc1201a82657fada30220743
3,638,961
def calculate_timeout(start_point, end_point, planner): """ Calucaltes the time limit between start_point and end_point considering a fixed speed of 5 km/hr. Args: start_point: initial position end_point: target_position planner: to get the shortest part between start_point and ...
cb7ae44df9b6a89d2e171046fa0bdfe3f81445c5
3,638,962
def overview(request): """Returns the overview for a daterange. GET paramaters: * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y) Returns an overview dict with a count for all action types. """ form = OverviewAPIForm(request.GET) if not form.is_valid(): return {'success': False, 'er...
41d97127833d2c873ebedb1aaff9dcdfb31ae4dd
3,638,963
def func_parallel(func, list_inputs, leave_cpu_num=1): """ :param func: func(list_inputs[i]) :param list_inputs: each element is the input of func :param leave_cpu_num: num of cpu that not use :return: [return_of_func(list_inputs[0]), return_of_func(list_inputs[1]), ...] """ cpu_cores = mp.c...
4642149db87236b444e26515747a18ccbc420e64
3,638,964
def get_mean(jsondata): """Get average of list of items using numpy.""" if len(jsondata['results']) > 1: return mean([float(price.get('price')) for price in jsondata['results'] if 'price' in price]) # key name from itunes # [a.get('a') for a in alist if 'a' in a] else: return float(...
63851f6e89bea230549975eba68391421b57f087
3,638,965
from typing import Dict import torch import time def evaluate_with_trajectory( sc_dataset: SingleCellDataset, n_samples: int, trajectory_type: str, trajectory_coef: Dict, types: DeconvolutionDatatypeParametrization, deconvolution_params: Dict, n_iters=5_000, ): """Evaluate L1_error and...
bb82164f4ec9d79bcc675be1612a61ff5b209752
3,638,966
import sys def main(argv=None): """ """ if argv == None: argv = sys.argv[1:] try: pdb_file = argv[0] data_file = argv[1] except IndexError: err = "Incorrect number of arguments!\n\n%s\n\n" % __usage__ raise PerturbPdbError(err) out = perturbPdb(pd...
2d2c175430ebd953e2b363927c34b491c71d0737
3,638,967
def plot_diffraction_1d(result, deg): """ Returns this result instance in PlotData1D representation. :param deg: if False the phase is expressed in radians, if True in degrees. """ # Distinguish between the strings "phase in deg" and "phase in rad". if deg: phase_string = "Phase in deg" ...
f316e1f02a5b5b295bfed22fc5307bcf908788c2
3,638,968
import logging def prepare_go_environ(): """Returns dict with environment variables to set to use Go toolset. Installs or updates the toolset and vendored dependencies if necessary. """ bootstrap(LAYOUT, logging.INFO) return get_go_environ(LAYOUT)
cf7d6ee594193317a1201beb127e607139fd367f
3,638,969
def get_subnets(client, name='tag:project', values=[ec2_project_name,], dry=True): """ Get VPC(s) by tag (note: create_tags not working via client api, use cidr or object_id instead ) https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_subnets """ ...
4504a37689bce171d3d62a3cf6f66365c58f56e8
3,638,970
import requests def get_object_handler(s3_client, request_context, user_request): """ Handler for the GetObject Operation :param s3_client: s3 client :param request_context: GetObject request context :param user_request: user request :return: WriteGetObjectResponse """ # Validate user...
fc98197f99e8751976245902eb4034a5b4930d3b
3,638,971
import os import posixpath def NormalizePath(path): """Returns a path normalized to how we write DEPS rules and compare paths.""" return os.path.normcase(path).replace(os.path.sep, posixpath.sep)
e6a6c7a50176f6990841a48748e5951c4f40b8af
3,638,972
import os import shutil import torch def eval_imgs_output_dets(opt, data_loader, data_type, result_f_name, out_dir, save_dir=None, show_image=True): """ :...
d156450d42da57364e7f9037c4abbe8af7a18d4c
3,638,973
def decline_agreement(supplier_code): """Decline agreement (role=supplier) --- tags: - seller edit parameters: - name: supplier_code in: path type: number required: true responses: 200: description: Agreement declined. 400: ...
fa7f2186af9f7beb2b138eab3347cd34580557f0
3,638,974
import torch def load_model(model, model_path): """ Load model from saved weights. """ if hasattr(model, "module"): model.module.load_state_dict(torch.load(model_path, map_location="cpu"), strict=False) else: model.load_state_dict(torch.load(model_path, map_location="cpu"), strict=...
0fbf34548474c4af89c25806f05d1e7d3170bbde
3,638,975
def get_file_size(filepath: str): """ Not exactly sure how os.stat or os.path.getsize work, but they seem to get the total allocated size of the file and return that while the file is still copying. What we want, is the actual file size written to disk during copying. With standard Windows file copyin...
6936a8227a96e3ebc4b1146f8363f092d232cafd
3,638,976
import json def get_aws_regions_from_file(region_file): """ Return the list of region names read from region_file. The format of region_file is as follows: { "regions": [ "cn-north-1", "cn-northwest-1" ] } """ with open(region_file) as r_file: r...
639da8c6417295f97621f9fd5321d8499652b7b2
3,638,977
def item_pack(): """ RESTful CRUD controller """ s3db.configure("supply_item_pack", listadd = False, ) return s3_rest_controller()
e6bce829b441a08c98dc81fa6ac1ea432ef67c89
3,638,978
def inv_cipher(rkey, ct, Nk=4): """AES decryption cipher.""" assert Nk in {4, 6, 8} Nr = Nk + 6 rkey = rkey.reshape(4*(Nr+1), 32) ct = ct.reshape(128) # first round state = add_round_key(ct, rkey[4*Nr:4*(Nr+1)]) for i in range(Nr-1, 0, -1): state = inv_shift_rows(state) ...
477b32450b4fef060f936952d0af3115ca4b8add
3,638,979
import os import ast def get_version(module='spyder_terminal'): """Get version.""" with open(os.path.join(HERE, module, '__init__.py'), 'r') as f: data = f.read() lines = data.split('\n') for line in lines: if line.startswith('VERSION_INFO'): version_tuple = ast.literal_eva...
085bdff77724f7962e506f735d8336b5b8ba63d8
3,638,980
def _ptrarray_to_list(ptrarray): """Converts a ptr_array structure from SimpLL into a Python list.""" result = [] for i in range(0, ptrarray.len): result.append(ptrarray.arr[i]) lib.freePointerArray(ptrarray) return result
430c26f15ee41dbf5b4bdf562dd81c0167eead18
3,638,981
import copy import random def perform_modifications(statemachine,amount=1,possible_modifications=[]): """Starting point for modifications upon interfaces. Performs modifications as specified in the peramaters. N (amount) of modifications are selected at random from possible_modiifcations and then attemp...
8cd1f21a3b7e74d3b9c3919c829e8156065e020f
3,638,982
from typing import Callable def endpoint(path: str) -> Callable[[], Endpoint]: """Decorator for creating an Arguments: path: The path to the API endpoint (relative to the API's ``base_url``). Returns: The wrapper for the endpoint method. """ def wrapper(method): retu...
1a0b9b836630f1ab4eea902861899c50303aa539
3,638,983
def from_string_to_bytes(a): """ Based on project: https://github.com/chaeplin/dashmnb. """ return a if isinstance(a, bytes) else bytes(a, 'utf-8')
e76509f1be8baf8df0bf3b7160615f9a9c04ff86
3,638,984
def split(x, divider): """Split a string. Parameters ---------- x : any A str object to be split. Anything else is returned as is. divider : str Divider string. """ if isinstance(x, str): return x.split(divider) return x
e77a162777d9bb13262e4686ba1cb9732ebab221
3,638,985
def despesa_update(despesa_id): """ Editar uma despesa. Args: despesa_id (int): ID da despesa a ser editada. Lógica matemática é chamada de utils.py: adicionar_registro() Returns: Template renderizado: despesa.html Redirecionamento: aplication.transacoes """ desp...
bd848eacc19144c40822a7389ceecdae4f5c5532
3,638,986
def _convert_format(partition): """ Converts the format of the python-louvain into a numpy array Parameters ---------- partition : dict Standard output from python-louvain package Returns ------- partition: np.array Partition as a numpy array """ return np.arra...
5afffe9745c0083829a2ce88f5842b295583e737
3,638,987
def settingsdir(): """In which directory to save to the settings file""" return module_dir()+"/settings"
ac485b7d947cfa051adc9eeed6f194b9746d8401
3,638,988
def _is_iqn_attached(sess, iqn): """ Verify if oci volume with iqn is attached to this instance. Parameters ---------- sess: OCISession The OCISession instance. iqn: str The iSCSI qualified name. Returns ------- str: the ocid """ _logger.debug('Verifying...
d0aff2d1ba1bc7f316f2cafbbca655449e63cc77
3,638,989
from typing import Dict from typing import List import copy def run_range_mcraptor( timetable: Timetable, origin_station: str, dep_secs_min: int, dep_secs_max: int, max_rounds: int, ) -> Dict[str, List[Journey]]: """ Perform the McRAPTOR algorithm for a range query """ # Get stops...
d09a85fbe5f3e1a8e3081037e195298aed6e5fc8
3,638,990
def _choose_node_type(w_operator, w_constant, w_input, t): """ Choose a random node (from operators, constants and input variables) :param w_operator: Weighting of choosing an operator :param w_constant: Weighting of choosing a constant :param w_input: Weighting of cho...
7517d347b97bce2748e4ccd45a5f25120e074e9d
3,638,991
import os def plot_prisma_diagram(save_cfg=cfg.saving_config): """Plot diagram showing the number of selected articles. TODO: - Use first two colors of colormap instead of gray - Reduce white space - Reduce arrow width """ # save_format = save_cfg['format'] if isinstance(save_cfg, dict) e...
490123552f3c6c8428e9156947241a9f7edc5f49
3,638,992
import os def get_script(software): """ Gets the path of the post install script of a software. :rtype: str """ dir_scripts = get_scripts_location() scripts = os.listdir(dir_scripts) for script in scripts: if script == software: return os.path.join(dir_scripts, script...
b6d292d15bbd26a9f26a7f1c19fddb0c94207a30
3,638,993
def _plat_idx_to_val(idx: int , edge: float = 0.5, FIO_IO_U_PLAT_BITS: int = 6, FIO_IO_U_PLAT_VAL: int = 64) -> float: """ Taken from fio's stat.c for calculating the latency value of a bin from that bin's index. idx : the value of the index into the histogram bins edge : fractiona...
f992194492e031add3d14f0e145888303a5b4f06
3,638,994
def is_blank(value): """ Returns True if ``value`` is ``None`` or an empty string. >>> is_blank("") True >>> is_blank(0) False >>> is_blank([]) False """ return value is None or value == ""
6a30f9f6726701a4b7a9df8957503111a5222558
3,638,995
def overload_check(data, min_overload_samples=3): """Check data for overload :param data: one or two (time, samples) dimensional array :param min_overload_samples: number of samples that need to be equal to max for overload :return: overload status """ if data.n...
9c59bb2e105828afd93af193949a2ad01a34a32e
3,638,996
import socket import time def send_packet_to_capture_last_one(): """ Since we read packets from stdout of tcpdump, we do not know when a packet is finished Hence you should send an additional packet after you assume all interesting packets were sent """ def send(): conf = get_netconfig() ...
984848ec685273d97630dd6a95d93c939665969e
3,638,997
from typing import Callable from pathlib import Path from typing import Iterable from typing import Optional import signal import random def diss( demos: Demos, to_concept: Identify, to_chain: MarkovChainFact, competency: CompetencyEstimator, lift_path: Callable[[Path], Path] = lambda x: x, n...
016af4c38a890426fa148af78e1349b6bacdfa79
3,638,998
def expand_gelu(expand_info): """Gelu expander""" # get op info. input_desc = expand_info['input_desc'][0] graph_builder = builder.GraphBuilder() # generate a graph. with graph_builder.graph_scope('main') as graph_scope: # create tensor input. input_x = graph_builder.tensor(inp...
1237d4899ef0411b827efd930fb7e2e0fa5fddde
3,638,999