content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import tkinter def _colorvar_patch_destroy(fn): """Internal function.\n Deletes the traces if any when widget is destroy.""" def _patch(self): """Interanl function.""" if self._tclCommands is not None: # Deletes the widget from the _all_traces_colorvar # and delete...
d38380316932d8ff2fee8bed8b931b5567588774
3,654,800
import os def distros_for_filename(filename, metadata=None): """Yield possible egg or source distribution objects based on a filename""" return distros_for_location( normalize_path(filename), os.path.basename(filename), metadata )
154fa2158dc6e980c57c8b8bcea339fcadca772e
3,654,801
def pres_from_hybrid(psfc, hya, hyb, p0=100000.): """Return pressure field on hybrid-sigma coordinates, assuming formula is p = a(k)*p0 + b(k)*ps. """ return hya*p0 + hyb*psfc
4ebd90fb807ab9ea4c2b45d27da6f8b420c107f7
3,654,802
import urllib def url_exist(file_url): """ Check if an url exist Parameters ---------- file_url : string url of www location Returns ------- verdict : dtype=boolean verdict if present """ try: urllib.request.urlopen(file_url).code == 200 retu...
717ee7073ab56e8611eb46f042ab7c18f2db0f33
3,654,803
from scipy import stats def chi_square(observed, expected): """ Compute the chi square test """ # glen cowan pp61 temp = [] for (n, nu) in zip(observed, expected): if nu != 0: temp += [((n - nu) ** 2) / nu] # compute p value mychi = sum(temp) p = stats.chi2.sf(...
4b0577ec4e4b4dc6b99b00a54e78f1014b9cf93a
3,654,804
def fix_deform_for_children(pmx: pmxstruct.Pmx, me: int, already_visited=None) -> int: """ Recursively ensure everything that inherits from the specified bone will deform after it. Only cares about parent and partial-inherit, doesnt try to understand IK groups. Return the number of bones that were changed. :param ...
1757e8f4c39c2ac93f9ef63397b194412342fbae
3,654,805
def theta_8(p, q, h, phi, a, b): """Lower limit of integration for the case rho > a, rho > b.""" result = np.arctan(r_8(p, q, phi, a, b)/h) return(result)
913ceb462885fba93cbdb6bddaa5523c119821bc
3,654,806
def collect_genewise(fst_file, file_name, gene_names, gene_to_fst): """take in the file name, opens it. populates a dictionary to [gene] = fst file_name = defaultdict(str) FBgn0031208 500000 16 0.002 21.0 1:2=0.05752690 """ file_name = file_name.split("_gene")[0] f_in = open(fst_file, "r") ...
ea62da67a7084103859244bf7f192c2f4433124c
3,654,807
import torch def bbox_overlaps_batch(anchors, gt_boxes): """ :param anchors: (N, 4) ndarray of float :param gt_boxes: (b, K, 5) ndarray of float :return: (N, K) ndarray of overlap between boxes and query_boxes """ batch_size = gt_boxes.size(0) if anchors.dim() == 2: N = anchors...
cc5a88e6a1d5cd42b1827091cbee311e4f33bbb6
3,654,808
from typing import Tuple from typing import Callable from typing import Any import re def extract_curve_and_test(curve_names: str, name: str) -> Tuple[str, Callable[[Any], bool]]: """Return a curve and a test to apply for which of it's components to twist.""" twist_match = re.match(rf"(?P<curve>[{curve_names...
e4849ff7145bae0c2c900d0aa747ec7a14fb96ac
3,654,809
import numpy def psf_gaussian(psf_shape, psf_waist, psf_physical_size=1, psf_nphoton=2): """Return 3D gaussian approximation of PSF.""" def f(index): s = psf_shape[index] // 2 * psf_physical_size c = numpy.linspace(-s, s, psf_shape[index]) c *= c c *= -2.0 / (psf_waist[index] ...
77ccab6aaa141564751a0eafd13398f904673006
3,654,810
def get_employee_record(id_num): """Gets an employee's details if record exists. Arguments: id_num -- ID of employee record to fetch """ if not id_num in names or not id_num in cities: return 'Error viewing record' return f'{id_num} {names[id_num]} {cities[id_num]}'
108b6e3482022e8e65e09bda1dd8a78ca7850cfe
3,654,811
def list_aliases(): """ Gets the list of aliases for the current account. An account has at most one alias. :return: The list of aliases for the account. """ try: response = iam.meta.client.list_account_aliases() aliases = response['AccountAliases'] if len(aliases) > 0: ...
13fa5d4ded6811bbcbd6062cf7f690b08c41354e
3,654,812
def MapToSingleIncrease(val): """ Need 30 minute values to be sequential for some of the tools(i.e. 1,2,3,4) so using a format like 5,10,15,20 won't work. """ return val/5
fe89d7ccb8bef511e2ad90a07ad0346c58ba894d
3,654,813
def get_columns_for_table(instance, db, table): """ Get a list of columns in a table Args: instance - a hostAddr object db - a string which contains a name of a db table - the name of the table to fetch columns Returns A list of columns """ conn = connect_mysql(instance) cursor...
567a7e3e6ebbf33cee3cb088e1725bd2b11edcef
3,654,814
def registra_aluno(nome, ano_entrada, ano_nascimento, **misc): """Cria a entrada do registro de um aluno.""" registro = {'nome': nome, 'ano_entrada': ano_entrada, 'ano_nascimento': ano_nascimento} for key in misc: registro[key] = misc[key] return registro
e56da99ec90de9ebca204ccc3c3f3555b9bbbc64
3,654,815
def define_output_ports(docstring, short_description_word_count=4): """ Turn the 'Returns' fields into VisTrails output ports Parameters ---------- docstring : NumpyDocString #List of strings? The scraped docstring from the function being autowrapped into vistrails Returns ...
c02737fd1eb29cc1570e47df32ecdb34e1467cea
3,654,816
import signal import errno import os def kill(pidfile, logger, signum=signal.SIGTERM): """Sends `signum` to the pid specified by `pidfile`. Logs messages to `logger`. Returns True if the process is not running, or signal was sent successfully. Returns False if the process for the pidfile was runnin...
a2dd0ea54bb6e23dd0446646f41f3e34240d713e
3,654,817
def create_small_table(small_dict): """ Create a small table using the keys of small_dict as headers. This is only suitable for small dictionaries. Args: small_dict (dict): a result dictionary of only a few items. Returns: str: the table as a string. """ keys, values = tuple...
08da78580fbf4cee8c30acb21ce7fa928a9c17b1
3,654,818
def get_normalized_list_for_every_month(variable_r, list_of_ranges_r, tags_r): """ :param variable_r: big list with all the data [sizes][months] :param list_of_ranges_r: sorted list of range (sizes...Enormous, etc.) :return: normalized list for each month (numbers are percentage respect to the total by...
4a3b837e6bf254dbd3255a8ca0a5d103d34bd2a9
3,654,819
def mark_as_possible_cluster_member(g, possible_cluster_member, cluster, confidence, system, uri_ref=None): """ Mark an entity or event as a possible member of a cluster. :param rdflib.graph.Graph g: The underlying RDF model :param rdflib.term.URIRef possible_cluster_member: The entity or event to mark...
851da7d12781723c7c2fb4bc13ac14172c890daf
3,654,820
def twodcontourplot(tadata_nm, tadata_timedelay, tadata_z_corr): """ make contour plot Args: tadata_nm: wavelength array tadata_timedelay: time delay array tadata_z_corr: matrix of z values """ timedelayi, nmi = np.meshgrid(tadata_timedelay, tadata_nm) # find the maxi...
2e8850e1c8153c9c307ff785ddd1d1d127163190
3,654,821
def make_example_dags(module_path): """Loads DAGs from a module for test.""" dagbag = DagBag(module_path) return dagbag.dags
ffc2fd47bbee7d2124da199d6b5101103500fbf2
3,654,822
def count_good_deals(df): """ 7. Считает число прибыльных сделок :param df: - датафрейм с колонкой '<DEAL_RESULT>' :return: - число прибыльных сделок """ # http://stackoverflow.com/questions/27140860/count-occurrences-of-number-by-column-in-pandas-data-frame?rq=1 return (df['<DEAL_RESULT...
1f3ef9b9e0f7924d45d5ce84a77938f19386b6bc
3,654,823
import time import itertools import sh def match_lines_by_hausdorff(target_features, match_features, distance_tolerance, azimuth_tolerance=None, length_tolerance=0, match_features_sindex=None, match_fields=False, match_stats=False, field_suffixes=('', '_match'), match_strings=None, constrain_target_features...
d9c08e8e156a525495a03e5e9d6881c33ecdf0a2
3,654,824
import os from typing import Callable import stat import shutil def git_rmtree(path: os.PathLike) -> None: """Remove the given recursively. :note: we use shutil rmtree but adjust its behaviour to see whether files that couldn't be deleted are read-only. Windows will not remove them in that case""" ...
25471f9f791ef091106915cec2f5e16bf91b067c
3,654,825
def get_num_streams(): """Force an offset so high that the payload is small and quick. In it, there will be a total number to base our reverse search from""" result = get_streams() logger.debug(result) if "error" in result: raise Exception("error in request: " + str(result)) total = int...
bae59352d4962b0916e8cf09215ea108fb3e8948
3,654,826
import os def compute_corr_active(params): """ Compute correlation only for active positions, i.e. where at least one of the two signal tracks is non-zero :param params: :return: """ with pd.HDFStore(params['inputfilea'], 'r') as hdf: load_group = os.path.join(params['inputgroupa'], pa...
4d26eaab548aa02521c2cb0341e93803315e46bf
3,654,827
def create_anchors_3d_stride(grid_size, voxel_size=[0.16, 0.16, 0.5], coordinates_offsets=[0, -19.84, -2.5], dtype=np.float32): """ Args: feature_size: list [D, H, W](zyx) sizes: [N, 3] list of list or array,...
129e54a855bbacb2026eb08b5741ab70dd0374f4
3,654,828
def combined_roidb(imdb_names): """ Combine multiple roidbs """ def get_roidb(imdb_name): imdb = get_imdb(imdb_name) print('Loaded dataset `{:s}` for training'.format(imdb.name)) imdb.set_proposal_method("gt") print('Set proposal method: {:s}'.format("gt")) roidb...
4660a6ffff11511c449629c9fdb7f5d566a886f9
3,654,829
from re import A def render_locations_profile(list_id, item_id, resource, rfields, record): """ Custom dataList item renderer for Locations on the Profile Page - UNUSED @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3R...
dbec0b41b16fa48996a735372bfb001b386c7300
3,654,830
import larch import sys def enable_plugins(): """add all available Larch plugin paths """ if 'larch_plugins' not in sys.modules: sys.modules['larch_plugins'] = larch return sys.modules['larch_plugins']
a58100359d749d876976e8bb13b6766edf6ea8b3
3,654,831
def exception_log_and_respond(exception, logger, message, status_code): """Log an error and send jsonified respond.""" logger.error(message, exc_info=True) return make_response( message, status_code, dict(exception_type=type(exception).__name__, exception_message=str(exception)), ...
c784efd4b8adbbc463ff1d2a499ffd598253349d
3,654,832
import re def parse_cdhit_clusters(cluster_file): """ Parses cdhit output into three collections in a named tuple: clusters: list of lists of gene ids. reps: list of representative gene for each cluster lookup: dict mapping from gene names to cluster index In this setup, cluster ids are...
fe0634c1991f0bd687f8be675ff15cb3290c919c
3,654,833
import torch def evaluate(model: nn.Module, dataloader: DataLoader) -> Scores: """ Evaluate a model without gradient calculation :param model: instance of a model :param dataloader: dataloader to evaluate the model on :return: tuple of (accuracy, loss) values """ score = 0 loss = 0 ...
f23fbd72a24122b3a665f29918c52bbd5515d204
3,654,834
from operator import and_ def remote_judge_get_problem_info(problem_id: str, contest_id: int = -1, contest_problem_id: int = -1): """ { "code":0, "data":{ "isContest":"是否在比赛中", "problemData":{ "title":"题目名", "content":"题目内容", ...
aa7f8100bc7516659cf535e0fa7222b6f7b1a065
3,654,835
def can_write(obj, user): """ Takes article or related to article model. Check if user can write article. """ return obj.can_write(user)
9cb7cc046b63fb82670c4667abe169d6a1a279e4
3,654,836
def create_external_question(url: str, height: int) -> str: """Create XML for an MTurk ExternalQuestion.""" return unparse({ 'ExternalQuestion': { '@xmlns': 'http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd', 'ExternalURL': url, ...
d249e82225ab2c1546bd871c166e9b683622a15d
3,654,837
def credentials_batch_account_key_secret_id(config): # type: (dict) -> str """Get Batch account key KeyVault Secret Id :param dict config: configuration object :rtype: str :return: keyvault secret id """ try: secid = config[ 'credentials']['batch']['account_key_keyvault_s...
4e7cfb100c2d50ef13d47295ff0b5bb0e3351986
3,654,838
import re def is_C2D(lname): """ """ pattns = ['Conv2D'] return any([bool(re.match(t,lname)) for t in pattns])
a12bfd9857543e568148659f782615b3f2de4b83
3,654,839
def encounter_media(instance, filename): """Return an upload file path for an encounter media attachment.""" if not instance.encounter.id: instance.encounter.save() return 'encounter/{0}/{1}'.format(instance.encounter.source_id, filename)
79e4d8fae1d41edf362e99e6da11442a71565aa0
3,654,840
def findFonts(pattern, lazy=True): """Answers a list of Font instances where the pattern fits the font path. If pattern is a list, all parts should have a match. # TODO: make case insensitive """ """ >>> findFonts('Roboto-Thi') [<Font Roboto-Thin>, <Font Roboto-ThinItalic>] >>> # Selec...
dd5d0a9818292c1dadfc77f8b834b348e55ae777
3,654,841
from datetime import datetime def time_range_cutter_at_time(local,time_range,time_cut=(0,0,0)): """ Given a range, return a list of DateTimes that match the time_cut between start and end. :param local: if False [default] use UTC datetime. If True use localtz :param time_range: the TimeRa...
57e851fb5b6ae8873dde5719dec668c25561f687
3,654,842
def _darknet_conv( x: np.ndarray, filters: int, size: int, strides: int = 1, batch_norm: bool = True ) -> tf.Tensor: """create 1 layer with [padding], conv2d, [bn and relu]""" if strides == 1: padding = "same" else: x = ZeroPadding2D(((1, 0), (1, 0)))(x) # top left half-padding ...
f58153aa0c8af8df93289b872309f1c907941848
3,654,843
def _build_topic_to_consumer_topic_state_map(watermarks): """Builds a topic_to_consumer_topic_state_map from a kafka get_topics_watermarks response""" return { topic: ConsumerTopicState({ partition: int((marks.highmark + marks.lowmark) / 2) for partition, marks in watermarks_...
78ef0710e4823031ad079313484dba0eacc37135
3,654,844
from typing import Optional def elgamal_keypair_from_secret(a: ElementModQ) -> Optional[ElGamalKeyPair]: """ Given an ElGamal secret key (typically, a random number in [2,Q)), returns an ElGamal keypair, consisting of the given secret key a and public key g^a. """ secret_key_int = a if secret_...
35de350b6bb434e1bb3d2c52d90f9a96be72dc1f
3,654,845
def current_default_thread_limiter(): """Get the default `~trio.CapacityLimiter` used by `trio.to_thread.run_sync`. The most common reason to call this would be if you want to modify its :attr:`~trio.CapacityLimiter.total_tokens` attribute. """ try: limiter = _limiter_local.get() e...
7abec5d74b9cfdaa663fd432587ea19440b7132f
3,654,846
import copy def _mask_board(board): """ A function that copies the inputted board replaces all ships with empty coordinates to mask them. :param board: a 2D numpy array containing a string representation of the board. All ships should be visible. :return: a 2D numpy array containing a string represent...
c6832c90ac96d61563e37482773abf627d92a05a
3,654,847
from sys import stdout def query_yes_no(question, default="no", color=_constants.COLORS.RESET): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" ...
eee02b61b3ba9ffdded0ba8c50c6bdd8e52d3c00
3,654,848
def remove_head_id(ref, hyp): """Assumes that the ID is the begin token of the string which is common in Kaldi but not in Sphinx.""" ref_id = ref[0] hyp_id = hyp[0] if ref_id != hyp_id: print('Reference and hypothesis IDs do not match! ' 'ref="{}" hyp="{}"\n' 'Fil...
210798e8a02f555f70a1d9f2de9ce098dd0669fb
3,654,849
def convert_image_np(inp): """Convert a Tensor to numpy image.""" inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean inp = np.clip(inp, 0, 1) return inp
446feda40cc6698b5cbc80c3b14fa3212ef2800b
3,654,850
def get_miner_day_list(): """ 存储提供者每天的miner数据 :return: """ miner_no = request.form.get("miner_no") date = request.form.get("date") data = MinerService.get_miner_day_list(miner_no, date) return response_json(data)
4fd523e8855ba498a1d694e532d27c863e7f9407
3,654,851
def get_notebook_logs(experiment_id, operator_id): """ Get logs from a Experiment notebook. Parameters ---------- experiment_id : str operator_id : str Returns ------- dict or None Operator's notebook logs. Or None when the notebook file is not found. """ notebook =...
d98865cdbca25839bb6010ab5e726fd35d162ada
3,654,852
from typing import Callable def modify_env2( function: Callable[[_UpdatedType], _SecondType], ) -> Kinded[Callable[ [Kind2[_Reader2Kind, _FirstType, _SecondType]], Kind2[_Reader2Kind, _FirstType, _UpdatedType], ]]: """ Modifies the second type argument of a ``ReaderBased2``. In other words, i...
5ed2c5deaaa376e4884f31e3ba08d3b2839cc1a5
3,654,853
def model_trees(z, quantiles, normed=False, dbhfile='c:\\projects\\MLM_Hyde\\Data\\hyde_runkolukusarjat.txt', plot=False, biomass_function='marklund'): """ reads runkolukusarjat from Hyde and creates lad-profiles for pine, spruce and decid. Args: z - g...
ba3c1ea345031a8b5434e1dd4f005b1c2c1e74ce
3,654,854
def inject_general_timeline(): """This function injects the function object 'Tweet.get_general_timeline' into the application context so that 'get_general_timeline' can be accessed in Jinja2 templates. """ return dict(get_general_timeline=Tweet.get_general_timeline)
56b395da0facda561061c8f63eb3eb26c07f3605
3,654,855
def is_a(file_name): """ Tests whether a given file_name corresponds to a Cosmo Skymed file. Returns a reader instance, if so. Parameters ---------- file_name : str the file_name to check Returns ------- CSKReader|None `CSKReader` instance if Cosmo Skymed file, `None` o...
f1292033411236f1e445e36458571e5025996a2b
3,654,856
def get_vaccinated_model(model, area=None): """Get all states that can be vaccinated or recovered (by area). Parameters ---------- model : amici.model Amici model which should be evaluated. areas : list List of area names as strings. Returns ------- states : list ...
c03a9d048abb08561463b1975ffec663f24267b3
3,654,857
from datetime import datetime def MicrosecondsToDatetime(microseconds): """Returns a datetime given the number of microseconds, or None.""" if microseconds: return datetime.utcfromtimestamp(float(microseconds) / 1000000) return None
69fd3dc3b8d1a97e7a64037cabe988365b2c6e63
3,654,858
import subprocess def update() -> bool: """ Pull down the latest Docker image build and prune old image versions. """ current_image = DEFAULT_IMAGE latest_image = latest_build_image(current_image) if latest_image == current_image: print(colored("bold", "Updating Docker image %s…" % c...
1a5b8b4cf6cadccc8d95c4d9d8f5ca016199bd6e
3,654,859
def get_default_accept_image_formats(): """With default bentoML config, this returns: ['.jpg', '.png', '.jpeg', '.tiff', '.webp', '.bmp'] """ return [ extension.strip() for extension in config("apiserver") .get("default_image_handler_accept_file_extensions") .split(",...
9f2e8514ed1dcc4d533be0e3f2e501a9a9784abb
3,654,860
import sys import glob def findports(): """Returns an array of the serial ports that have a command interpreter.""" if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(255)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes...
38b16c56059c5f045b7c627cf1065c0754f7db28
3,654,861
import copy def cells_handler(results, cl): """ Changes result cell attributes based on object instance and field name """ suit_cell_attributes = getattr(cl.model_admin, 'suit_cell_attributes', None) if not suit_cell_attributes: return results class_pattern = 'class="' td_pattern ...
c49bdb89597e191d0c6b65df1b58a80ac6bd5f9e
3,654,862
def dynamic_import(import_string): """ Dynamically import a module or object. """ # Use rfind rather than rsplit for Python 2.3 compatibility. lastdot = import_string.rfind('.') if lastdot == -1: return __import__(import_string, {}, {}, []) module_name, attr = import_string[:lastdot]...
f6418ff17f3d480b22abac1146d946a5f990cb3c
3,654,863
from typing import Union from typing import List def _split_on_parenthesis(text_in: Union[str, list[str]]) -> List[str]: """Splits text up into a list of strings based on parenthesis locations.""" if isinstance(text_in, list): if None in text_in: return text_in text_list = text_in ...
7c7994590838c0293869786841eb7f97c60b16e8
3,654,864
from typing import Callable import functools import sys def shell_command_error2exit_decorator(func: Callable): """Decorator to convert given ShellCommandException to an exit message This avoids displaying nasty stack traces to end-users """ @functools.wraps(func) def func_wrapper(*args, **kwarg...
db2a51401c6616a8cf54928fc709923de3057a73
3,654,865
import requests def getExternalIP(): """ Returns external ip of system """ ip = requests.get("http://ipv4.myexternalip.com/raw").text.strip() if ip == None or ip == "": ip = requests.get("http://ipv4.icanhazip.com").text.strip() return ip
77847063a2da7c6484dd6e569786a012b3a0a62f
3,654,866
def intersection_indices(a, b): """ :param list a, b: two lists of variables from different factors. returns a tuple of (indices in a of the variables that are in both a and b, indices of those same variables within the list b) For example, intersection_indices([1,2,5,4,6],[3,5,1,2...
55264faaa4fd5e6dc5365b675ebd3b7f6a1e1280
3,654,867
def test_extract_requested_slot_from_entity_with_intent(): """Test extraction of a slot value from entity with the different name and certain intent """ # noinspection PyAbstractClass class CustomFormAction(FormAction): def slot_mappings(self): return {"some_slot": self.from_...
0b457700781183f275a8512e16bac53aa058d762
3,654,868
def graph_cases(selenium, host): """ Factory method that allows to draw preconfigured graphs and manipulate them with a series of helpful methods. :type selenium: selenium.webdriver.remote.webdriver.WebDriver :type host: qmxgraph.server.Host :rtype: GraphCaseFactory :return: Factory able to...
2df048d35a337e8d335844b7a1bb98db77816e5d
3,654,869
def figure_8(): """ Notes ----- Colors from Bang Wong's color-blind friendly colormap. Available at: https://www.nature.com/articles/nmeth.1618 Wong's map acquired from David Nichols page. Available at: https://davidmathlogic.com/colorblind/. """ # choosing test sample and network...
2a72f24673b96b577fc4f4a23a1869740e90c3ec
3,654,870
import re def check_threats(message): """Return list of threats found in message""" threats = [] for threat_check in get_threat_checks(): for expression in threat_check["expressions"]: if re.search(expression, message, re.I | re.U): del threat_check["expressions"] ...
091d370e4a2e6cbdf674d6dde73bf616b994498b
3,654,871
def data_processing_max(data, column): """Compute the max of a column.""" return costly_compute_cached(data, column).max()
299075ea3e1953abe0ffbd71afb42525c6270c49
3,654,872
from typing import Sequence def type_of_target(y): """Determine the type of data indicated by the target. Note that this type is the most specific type that can be inferred. For example: * ``binary`` is more specific but compatible with ``multiclass``. * ``multiclass`` of integers is mor...
2c721ab04cdba3209794a21b2b25fe10485be106
3,654,873
from typing import List def extract_data_from_csv_stream(client: Client, alert_id: str, attachment_id: str, delimiter: bytes = b'\r\n') -> List[dict]: """ Call the attachment download API and parse required fields. Args: client (Client): Cyberint API client. ...
992679004ae94da2731b04eaf41918a755d8306a
3,654,874
import re def validate_password(password, password_repeat=None): """ Validate user password. :param password: password as string :param password_repeat: repeat password :return: False - valid password """ if password_repeat: if password != password_repeat: return "Passw...
2987a1bec151e173156ab6a72345864c84dcb61c
3,654,875
def get_large_circuit(backend: IBMBackend) -> QuantumCircuit: """Return a slightly larger circuit that would run a bit longer. Args: backend: Backend on which the circuit will run. Returns: A larger circuit. """ n_qubits = min(backend.configuration().n_qubits, 20) circuit = Qua...
a35a9ee67d6268911f49936095a703b4fd227a56
3,654,876
import os import time def loadUserProject(): """ Loads a project that contains only the contents of user.dev. This project will not be cached, so every call will reload it.""" userFilePath = os.path.join(os.path.expanduser(devon.userPath), userFileName) project = DevonProject("", time.time()) ...
56edecff5feba9062770f164a33e281cf8232144
3,654,877
import torch def top_k(loc_pred, loc_true, topk): """ count the hit numbers of loc_true in topK of loc_pred, used to calculate Precision, Recall and F1-score, calculate the reciprocal rank, used to calcualte MRR, calculate the sum of DCG@K of the batch, used to calculate NDCG Args: loc_pr...
8796312e1fa4d43fb992c0dd7903070a9e061e1b
3,654,878
def enviar_contacto(request): """ Enviar email con el formulario de contacto a soporte tecnico """ formulario = ContactoForm() if request.method == 'POST': formulario = ContactoForm(request.POST) if formulario.is_valid(): mail = EmailMessage(subject='HPC Contacto', ...
2f17e0cd0fbd5c5df345484c5fe08a420272785a
3,654,879
def dict_depth(d): """ 递归地获取一个dict的深度 d = {'a':1, 'b': {'c':{}}} --> depth(d) == 3 """ if isinstance(d, dict): return 1 + (max(map(dict_depth, d.values())) if d else 0) return 0
16f4164fdea08af9d5846a5866428c81848726b9
3,654,880
def apercorr(psf,image,objects,psfobj,verbose=False): """ Calculate aperture correction. Parameters ---------- psf : PSF object The best-fitting PSF model. image : string or CCDData object The input image to fit. This can be the filename or CCDData object. objects : table ...
bc4bb936801fe06a55648ed9a11545eacb24fd7d
3,654,881
from typing import Dict from typing import Tuple def product_loading_factor_single_discount(skus: str, product_list: Dict[str, object], product: Dict[str, int], product_name: str, rules: list) -> Tuple[int, str]: """ Single product loading factor for calculating discounts with one rule Parameters ---...
44e12d02be7c8b54d1ea64ef2dc3cbec29a870bc
3,654,882
import re def clean_text(page): """Return the clean-ish running text parts of a page.""" return re.sub(_UNWANTED, "", _unescape_entities(page))
8042cc5049b2d8b6646c10655b84c5552e315274
3,654,883
def calculate_recall(tp, n): """ :param tp: int Number of True Positives :param n: int Number of total instances :return: float Recall """ if n == 0: return 0 return tp / n
b8a36488af59e036acdb50821716ae34287e6b8f
3,654,884
def authenticate_user_password(password : 'bytes', encryption_dict : 'dict', id_array : 'list'): """ Authenticate the user password. Parameters ---------- password : bytes The password to be authenticated as user password. encryption_dict : dict The dictionary containing all...
b608a921fb02cedf9da9d8ea8e0d8f8139a6a9bd
3,654,885
def date_to_num(date): """Convert datetime to days since 1901""" num = (date.year - 1901) * 365.25 num += [ 0, 31, 59.25, 90.25, 120.25, 151.25, 181.25, 212.25, 243.25, 273.25, 304.25, 334.25 ][date.month - 1] num += date.day return int(num)
88e342e0fc80a5998df8e5f1ab0002e0f7fe808e
3,654,886
from typing import Tuple def load_world(filename: str, size: Tuple[int, int], resolution: int) -> np.array: """Load a preconstructred track to initialize world. Args: filename: Full path to the track file (png). size: Width and height of the map resolution: Res...
8ccf97efb83b3c365fb95a2732d0737100d5f254
3,654,887
import torch def generate_image(model, img_size, n_flow, n_block, n_sample, temp=0.7, ctx=None, label=None): """Generate a single image from a Glow model.""" # Determine sizes of each layer z_sample = [] z_shapes = calc_z_shapes(3, img_size, n_flow, n_block) for z in z_shapes: z_new = tor...
bee9c45cbbd028351e580729da51092604f87288
3,654,888
def quote_spaces(arg): """Generic function for putting double quotes around any string that has white space in it.""" if ' ' in arg or '\t' in arg: return '"%s"' % arg else: return str(arg)
e0171c3b0eee18c7fcc44cbdfe007949feabba9a
3,654,889
def slice_map(center, radius, m): """ :func:`slice_map` for slicing Map object based on center and radius. :param center: x, y tuple of center of sliced map :param radius: - :class:`int` center of sliced map :param m: - :class:`Map` Map object that want to be sliced return :class:`Map` """ ...
fe30795d2330a1a2572361438a79e1e8fa9bc3cf
3,654,890
from pathlib import Path import requests import shutil def download_file(url) -> Path: """Better download""" name = Path(urlparse(unquote(url)).path).name with mktempdir() as tmpdir: @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_time=30) def get(): ...
5ff6c05e5e1eb3379918c65d945d57af7e8d56be
3,654,891
def creategui(handlerfunctions): """Initializes and returns the gui.""" gui = GUI(handlerfunctions) # root.title('DBF Utility') return gui
17be3bae6eb105aca770327898a01027271e6f9c
3,654,892
import torch def rank_src_trgs(enc_dec_gen, src_list, trg_list): """ """ batch_size = len(trg_list) x, y = enc_dec_gen.encode_inputs(src_list, trg_list, add_bos=True, add_eos=True) ...
f5472889489676e21a7bec032e13ef99c850f2da
3,654,893
def plugin_poll(handle): """ Extracts data from the sensor and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a sensor reading in a JSON document, as a Python dict, if it is av...
c3d7b32b6816c81d244f689ce4185d1dcd9a16fe
3,654,894
def top_average_pathways(document, file, max_sets, get_all=False): """ Read the pathways file and get the top average pathways """ # read in the samples and get the data with out the stratification by bug samples, pathways, data = document.read_table(file) pathway_names = utilities.pathway_names(pa...
4d4ed4fa9156ac98466197090afc52ded517af95
3,654,895
import torch def ltria2skew(L): """ assume L has already passed the assertion check :param L: lower triangle matrix, shape [N, 3] :return: skew sym A [N, 3, 3] """ if len(L.shape) == 2: N = L.shape[0] # construct the skew-sym matrix A = torch.zeros(N, 3, 3).cuda() # [N...
6e74c181fc8efcdc28ba35578f31fb6f2a7fa1bb
3,654,896
def gamma_contrast(data_sample, num_patches=324, num_channel=2, shape_data=None, gamma_range=(0.5, 1.7), invert_image=False, per_channel=False, retain_stats=False): """Performs gamma contrast transformation""" epsilon = 1e-7 data_sample_patch = [] gamma_range_tenso...
373f3f7e602de69c1cbce328ec3ff1322a44d013
3,654,897
def _converge(helper, rcs, group): """ Function to be passed to :func:`_oob_disable_then` as the ``then`` parameter that triggers convergence. """ return group.trigger_convergence(rcs)
8aab701dc7e29d83d6c8ab8b71c37837feb72847
3,654,898
def HybridClientFactory(jid, password): """ Client factory for XMPP 1.0. This is similar to L{client.XMPPClientFactory} but also tries non-SASL autentication. """ a = HybridAuthenticator(jid, password) return xmlstream.XmlStreamFactory(a)
283d9182c0e7bce254bc9f04cd42c15b9e3aed46
3,654,899