content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def int_not_in_range(bounds, inclusive=False): """Creates property that must be an int outside bounds[0] and bounds[1]. Parameters: bounds: Subscriptable with len()==2, where bounds[0] is the lower bound and bounds[1] is the upper bound. Requires bounds[1] > bounds[0]. ...
6890cd827fb741329c958a001e48013466414d11
3,640,600
from typing import Dict from typing import List def plot_concordance_pr( pr_df: pd.DataFrame, snv: bool, colors: Dict[str, str] = None, size_prop: str = None, bins_to_label: List[int] = None, ) -> Column: """ Generates plots showing Precision/Recall curves for truth samples: Two tabs: ...
8ad9541605c8f9f274faba03de7e19766341a562
3,640,601
from enum import Enum def typehint_metavar(typehint): """Generates a metavar for some types.""" metavar = None if typehint == bool: metavar = '{true,false}' elif is_optional(typehint, bool): metavar = '{true,false,null}' elif _issubclass(typehint, Enum): enum = typehint ...
31b42c29dd970d561917420e789eea6a7bd84cfa
3,640,602
from datetime import datetime def generate_signed_url(filename): """ Generate a signed url to access publicly """ found_blob = find(filename) expiration = datetime.now() + timedelta(hours=1) return found_blob.generate_signed_url(expiration)
917f78cfa12496baf655a8ea707143b4922f99c0
3,640,603
def delete_old_layer_versions(client, table, region, package, prefix): """ Loops through all layer versions found in DynamoDB and deletes layer version if it's <maximum_days_older> than latest layer version. The latest layer version is always kept Because lambda functions are created at a maximum...
291afac422a37cad59a8c2128776567b24c5a0c1
3,640,604
def _run_simulation(sim_desc): """Since _run_simulation() is always run in a separate process, its input and output params must be pickle-friendly. Keep that in mind when making changes. This is what each worker executes. Given a SimulationDescription object, calls the sequence & binning code,...
16cacdb3eaf1fadff8769ab6316eb06e89c226eb
3,640,605
def view_filestorage_file(self, request): """ Renders the given filestorage file in the browser. """ return getattr(request.app, self.storage).getsyspath(self.path)
ad65b83b9462c8b8efec7626d4751685df3aba8b
3,640,606
def enum_choice_list(data): """ Creates the argparse choices and type kwargs for a supplied enum type or list of strings """ # transform enum types, otherwise assume list of string choices if not data: return {} try: choices = [x.value for x in data] except AttributeError: c...
4f91c76569a4b42e655ed198a5c4ec2e48d9e839
3,640,607
def chartset(request): """ Conjunto de caracteres que determian la pagina request: respuesta de la url""" print "--------------- Obteniendo charset -------------------" try: charset = request.encoding except AttributeError as error_atributo: charset = "NA" print "charset: " +...
072ec863bd555706a64bab48d147afb24142fae4
3,640,608
import uuid def generate_UUID(): """ Generate a UUID and return it """ return str(uuid.uuid4())
feab11861e366ddf60cdc74c12f77f6a6ece2fa3
3,640,609
def streaming_recall_at_thresholds(predictions, labels, thresholds, ignore_mask=None, metrics_collections=None, updates_collections=None, name=None): """Computes various recall values for different `thresholds` on `predictions`. The `streaming_r...
6cdaa7cf3b0d1c35204764fb78c4f9cefb09b577
3,640,610
def fib(n): """Returns the nth Fibonacci number.""" if n == 0: return 1 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2)
397d5714f45491dde68c13379fe2a6acafe55002
3,640,611
import os def load_saved_users(args) -> list: """ :param args: :return: list """ data_frame = pd.read_csv(os.path.join(args.data_dir, args.users_tweets_dir, args.users_file), header=No...
efb4f9bbd055f39c30693fbea23d7e9254760e27
3,640,612
import logging def remove_artifacts_from_biom_table(table_filename, fasta_filename, ref_fp, biom_table_dir, ref_db_fp, threads=1, ...
89f8be391587598db8fec97c3d6f9a46b4fdff54
3,640,613
def template_review(context, mapping): """:phabreview: Object describing the review for this changeset. Has attributes `url` and `id`. """ ctx = context.resource(mapping, b'ctx') m = _differentialrevisiondescre.search(ctx.description()) if m: return templateutil.hybriddict({ ...
f475cf717026329ecc3c1ed1ccaff89089423e50
3,640,614
def addRandomEdges(graph: nx.Graph, nEdges: int) -> tuple: """ Adds random edges to a given graph """ nodes = list(graph.nodes) n = len(nodes) edges = [] for i in range(nEdges): newEdge = False while not newEdge: i_u, i_v = np.random.randint(0, n-1), np.random.randint(0, ...
004723ac17a431a266bae27c91316a66ced507f9
3,640,615
def get_s3_buckets_for_account(account, region='us-east-1'): """ Get S3 buckets for a specific account. :param account: AWS account :param region: AWS region """ session = boto3.session.Session() # create session for Thread Safety assume = rolesession.assume_crossact_audit_role( session...
bc2a334bb6c358c43fb97336d3092c27372bd2d0
3,640,616
import os def create_uid_email(username=None, hostname=None): """Create an email address suitable for a UID on a GnuPG key. :param str username: The username portion of an email address. If None, defaults to the username of the running Python process. :...
ca8ad0204e188d850f93f94d559a5a2e04a9170c
3,640,617
def get_users(): """ Alle Benutzer aus der Datenbank laden. """ session = get_cassandra_session() future = session.execute_async("SELECT user_id, username, email FROM users") try: rows = future.result() except Exception: log.exeception() users = [] for row in rows: ...
c6f7b49447dd187e188e9094af3443fe3e4ed218
3,640,618
import signal def fastcorrelate( input1, input2, usefft=True, zeropadding=0, weighting="None", displayplots=False, debug=False, ): """Perform a fast correlation between two arrays. Parameters ---------- input1 input2 usefft zeropadding weighting displayplots debug Ret...
2cb18d598f6071806cd5cd9c6260fa5a58764cd7
3,640,619
def vgconv(xinput,yinput,fwhm, ppr=None): """convolution with a Gaussian in log lambda scale for a constant resolving power Parameters ---------- xinput: numpy float array wavelengths yinput: numpy array of floats fluxes fwhm: float FWHM of the Gaussian (km/s) ppr: float, optional ...
d4722c87881eca27bac45cd47f84269249591cd0
3,640,620
def attach_component_to_entity(entity_id, component_name): # type: (azlmbr.entity.EntityId, str) -> azlmbr.entity.EntityComponentIdPair """ Adds the component if not added already. :param entity_id: EntityId of the entity to attach the component to :param component_name: name of the component :r...
f2c29f18ede8eef7accaf19970d18b0a432801ed
3,640,621
def get_raw_samples(sampling_strategy: sample_entry.Strategy, step: int) -> np.ndarray: """ Collects raw samples from database associated with sampling strategy. If the raw samples do not exists in the database new ones will be created by calling the Sobol function """ sampling_strategy.reload() ...
d0b2b4d643767eb1afc65611a78888d2c5b57824
3,640,622
import yaml from io import StringIO def mix_to_dat(probspec,isStringIO=True): """ Reads a YAML mix file and generates all of the GMPL dat components associated with the mix inputs. Inputs: ttspec - the tour type spec object created from the mix file param_name - string name of paramte...
972c1118c8d7af6dc8f9ff87908b1ca7184c880e
3,640,623
from typing import Any def get_setting(setting_name: str, default: Any=None) -> Any: """ Convenience wrapper to get the value of a setting. """ configuration = get_configuration() if not configuration: # pragma: no cover raise Exception('get_setting() called before configuration was initi...
774ee06824a227ed66357cb46a5277c24ba11f09
3,640,624
def deceptivemultimodal(x: np.ndarray) -> float: """Infinitely many local optima, as we get closer to the optimum.""" assert len(x) >= 2 distance = np.sqrt(x[0]**2 + x[1]**2) if distance == 0.: return 0. angle = np.arctan(x[0] / x[1]) if x[1] != 0. else np.pi / 2. invdistance = int(1. / ...
c08ab425bbc9803fcea9695c46acee71c2455873
3,640,625
import os def get_basins_scores(memory_array, binarized_cluster_dict, basinscore_method="default"): """ Args: - memory_array: i.e. xi matrix, will be N x K (one memory from each cluster) - binarized_cluster_dict: {k: N x M array for k in 0 ... K-1 (i.e. cluster index)} - basinscore_met...
9b4bf91ed760767444a595fb575c81593189e486
3,640,626
from aiida.orm import Dict from aiida_quantumespresso.utils.resources import get_default_options def generate_inputs_ph(fixture_sandbox, fixture_localhost, fixture_code, generate_remote_data, generate_kpoints_mesh): """Generate default inputs for a `PhCalculation.""" def _generate_inputs_ph(): """Gen...
4ab1f46ff08094fccd4197a19ab56c31dc1ac93c
3,640,627
from urllib.parse import quote def escape_url(raw): """ Escape urls to prevent code injection craziness. (Hopefully.) """ return quote(raw, safe="/#:")
4eee23f244998d2d2f4abd892a867f2e27f502a2
3,640,628
def split_sample(labels): """ Split the 'Sample' column of a DataFrame into a list. Parameters ---------- labels: DataFrame The Dataframe should contain a 'Sample' column for splitting. Returns ------- DataFrame Updated DataFrame has 'Sample' column with a list of strin...
483f1b78e07a2156aa3e48ae6c1f5ce41f5e60fe
3,640,629
def pmi_odds(pnx, pn, nnx, nn): """ Computes the PMI with odds Args: pnx (int): number of POSITIVE news with the term x pn (int): number of POSITIVE news nnx (int): number of NEGATIVE news with the term x nn (int): number of NEGATIVE news Ret...
5d4786f477fb12051a5a56887a7a7573aeab0802
3,640,630
def berDecodeLength(m, offset=0): """ Return a tuple of (length, lengthLength). m must be atleast one byte long. """ l = ber2int(m[offset + 0:offset + 1]) ll = 1 if l & 0x80: ll = 1 + (l & 0x7F) need(m, offset + ll) l = ber2int(m[offset + 1:offset + ll], signed=0) ...
e93252966e370088274f62bd512d59062e7431b2
3,640,631
def hasAspect(obj1, obj2, aspList): """ Returns if there is an aspect between objects considering a list of possible aspect types. """ aspType = aspectType(obj1, obj2, aspList) return aspType != const.NO_ASPECT
71907043900d080f2254557fe0bd2420b9bf9ac3
3,640,632
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, \ mtype, denovo_plots_dict, basis_plots_dict, reconstruction_plot_dict, \ reconstruction=False, statistics=None, sig_version=None, custom_text=None): """ Generate the correct plot based on mtype. Parameters: ---------- denovo_name: ...
9bb65728017a3f9f2a64ae94cb1ae7e15268c93b
3,640,633
from unittest.mock import Mock def org(gh): """Creates an Org instance and adds an spy attribute to check for calls""" ret = Organization(gh, name=ORG_NAME) ret._gh = Mock(wraps=ret._gh) ret.spy = ret._gh return ret
017d044015ff60c91742ea2eb12e2cd7720328c6
3,640,634
def merge_regions( out_path: str, sample1_id: int, regions1_file: File, sample2_id: int, regions2_file: File ) -> File: """ Merge two sorted region files into one. """ def iter_points(regions): for start, end, depth in regions: yield (start, "start", depth) yield (en...
eeb4b8bf73df45ae9d6af39d0d8c9db04251da41
3,640,635
import hashlib def get_text_hexdigest(data): """returns md5 hexadecimal checksum of string/unicode data NOTE ---- The md5 sum of get_text_hexdigest can differ from get_file_hexdigest. This will occur if the line ending character differs from being read in 'rb' versus 'r' modes. """ da...
762115178406c0b49080b3076859a3d1c13ad356
3,640,636
import json def recipe(recipe_id): """ Display the recipe on-page for each recipe id that was requested """ # Update the rating if it's an AJAX call if request.method == "POST": # check if user is login in order to proceed with rating if not session: return json.dumps({...
60db178d071d1880410e4e752ec484c4b59b0f96
3,640,637
def api_program_ordering(request, program): """Returns program-wide RF-aware ordering (used after indicator deletion on program page)""" try: data = ProgramPageIndicatorUpdateSerializer.load_for_pk(program).data except Program.DoesNotExist: logger.warning('attempt to access program page orde...
d4966689b0ea65885456ad7b52cf5dfd845ac822
3,640,638
def isinteger(x): """ determine if a string can be converted to an integer """ try: a = int(x) except ValueError: return False else: return True
180cea2f61733ada26b20ff046ae26deffa5d396
3,640,639
from typing import Tuple from typing import List def unmarshal_tools_pcr_values( buf: bytes, selections: TPML_PCR_SELECTION ) -> Tuple[int, List[bytes]]: """Unmarshal PCR digests from tpm2_quote using the values format. Args: buf (bytes): content of tpm2_quote PCR output. selections (TPML...
3a5b9dd36ca787026bb9bade4b5e5cc175add9e9
3,640,640
def new_topic(request): """添加新主题""" if request.method != 'POST': #未提交数据,创建一个新表单 form = TopicForm() else: #POST提交的数据,对数据进行处理 form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit = False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponse...
8d41cb1926d809742e89ec7e79ef7bd1ed14443c
3,640,641
from typing import Union from typing import List from typing import Any from typing import Optional def address(lst: Union[List[Any], str], dim: Optional[int] = None) -> Address: """ Similar to :meth:`Address.fromList`, except the name is shorter, and the dimension is inferred if possible. Otherwise, an e...
ef9e21bb3ef98b12c8ad02c75ccf2cbf6552fd44
3,640,642
from .views.entrance_exam import remove_entrance_exam_milestone_reference from .views.entrance_exam import add_entrance_exam_milestone from sys import path import base64 import os import shutil import tarfile def import_olx(self, user_id, course_key_string, archive_path, archive_name, language): """ Import a ...
39a83c292e82e5b9c86f793195f140f6249dc57e
3,640,643
import io def create_scenario_dataframes_geco(scenario): """ Reads GECO dataset and creates a dataframe of the given scenario """ df_sc = pd.read_csv(io["scenario_geco_path"]) df_sc_europe = df_sc.loc[df_sc["Country"] == "EU28"] df_scenario = df_sc_europe.loc[df_sc_europe["Scenario"] == scenar...
8a17d452feeb506bc2c2bf61a91e8473f2097649
3,640,644
def escape_env_var(varname): """ Convert a string to a form suitable for use as an environment variable. The result will be all uppercase, and will have all invalid characters replaced by an underscore. The result will match the following regex: [a-zA-Z_][a-zA-Z0-9_]* Example: "my.pri...
c1e57ff3b9648e93a540202f00d0325f91bccde1
3,640,645
def rms(signal): """ rms(signal) Measures root mean square of a signal Parameters ---------- signal : 1D numpy array """ return np.sqrt(np.mean(np.square(signal)))
6643ad464b4048ad71c7fb115e97b42d58a84a9c
3,640,646
import os def get_template_page(page): """method used to get the a page based on the theme it will check the options.theme defined theme for the page first and if it isnt found it will fallback to options.theme_dir/cling for the template page """ templates = ['%s.html' % os.path.join(options.them...
b8e642f9513300f984b5e701b1d18d07d1ab6554
3,640,647
def get_config( config_path, trained: bool = False, runner="d2go.runner.GeneralizedRCNNRunner" ): """ Returns a config object for a model in model zoo. Args: config_path (str): config file name relative to d2go's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_F...
e6d2b57bcadd833d625bd0a291fbb8de9d333624
3,640,648
from typing import Optional def make_game( width: int = defaults.WIDTH, height: int = defaults.HEIGHT, max_rooms: int = defaults.MAX_ROOMS, seed: Optional[int] = defaults.SEED, slippery_coefficient: float = defaults.SLIPPERY_COEFFICIENT, default_reward: float = defaults.DEFAULT_REWARD, goa...
908c772cdc3af5a891bce8c169d744e335da6e61
3,640,649
def weighted_var(x, weights=None): """Unbiased weighted variance (sample variance) for the components of x. The weights are assumed to be non random (reliability weights). Parameters ---------- x : np.ndarray 1d or 2d with observations in rows weights : np.ndarray or None 1d ar...
2166b214351da22117bf395fda950f1c79ccf0d1
3,640,650
def start_detailed_result_worker_route(): """ Add detailed result worker if not exist :return: JSON """ # check if worker already exist if check_worker_result(RABBITMQ_DETAILED_RESULT_QUEUE_NAME) == env.HTML_STATUS.OK.value: return jsonify(status=env.HTML_STATUS.OK.value) if 'db_nam...
567595574a09ce99f3feb11988bed0ba403b04cd
3,640,651
def _find_next_pickup_item(not_visited_neighbors, array_of_edges_from_node): """ Args: not_visited_neighbors: array_of_edges_from_node: Returns: """ # last node in visited_nodes is where the traveling salesman is. cheapest_path = np.argmin( array_of_edges_from_node[not...
06dc80e09d5b87cbc94558bee53677c887844b4b
3,640,652
def deformable_conv(input, offset, mask, num_filters, filter_size, stride=1, padding=0, dilation=1, groups=None, deformable_groups=None, ...
0dce5c2333a0a3dcaa568a85f3a6dec1536d2cfb
3,640,653
def ieee(): """IEEE fixture.""" return t.EUI64.deserialize(b"ieeeaddr")[0]
b00b13bb16c74bc96e52ad067dc0c523f5b5a249
3,640,654
def is_in(a_list): """Returns a *function* that checks if its argument is in list. Avoids recalculation of list at every comparison.""" def check(arg): return arg in a_list return check
34afbc269c164f0e095b1cbbf4e9576bafc7a9e1
3,640,655
def get_log_record_extra_fields(record): """Taken from `common` repo logging module""" # The list contains all the attributes listed in # http://docs.python.org/library/logging.html#logrecord-attributes skip_list = ( 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'func...
95fe6a74cd169c14ac32728f0bb1d16a2aa9e874
3,640,656
def ldap_is_intromember(member): """ :param member: A CSHMember instance """ return _ldap_is_member_of_group(member, 'intromembers')
d858afac4870cacc18be79a0b2d6d7d51dd33e07
3,640,657
def details(request, slug): """ Show product set """ productset = get_object_or_404(models.ProductSet, slug=slug) context = {} response = [] variant_instances = productset.variant_instances() signals.product_view.send( sender=type(productset), instances=variant_instances,...
9ac9b3f975a6501cfb94dd5d545c29c63a47a125
3,640,658
def applies(platform_string, to='current'): """ Returns True if the given platform string applies to the platform specified by 'to'.""" def _parse_component(component): component = component.strip() parts = component.split("-") if len(parts) == 1: if parts[0] in VALID_PL...
4692fb0d302948e07a1b2586f614dfcfa5618503
3,640,659
import threading def _GetClassLock(cls): """Returns the lock associated with the class.""" with _CLASS_LOCKS_LOCK: if cls not in _CLASS_LOCKS: _CLASS_LOCKS[cls] = threading.Lock() return _CLASS_LOCKS[cls]
98b034a0984431a752801407bfbc5e5694ad44ae
3,640,660
from apysc._expression import event_handler_scope def _get_expression_table_name() -> TableName: """ Get a expression table name. This value will be switched whether current scope is event handler's one or not. Returns ------- table_name : str Target expression table name. """ ...
61d3207d51264e876a472cbd2eea43de730508ac
3,640,661
def measure_option(mode, number=1, repeat=1, timeout=60, parallel_num=1, pack_size=1, check_correctness=False, build_option=None, replay_db=None, sav...
dc3ce9bed84c90d62773e118470943a24896390e
3,640,662
import gc import time import joblib def make_inference(input_data, model): """ input_data is assumed to be a pandas dataframe, and model uses standard sklearn API with .predict """ input_data['NIR_V'] = m.calc_NIR_V(input_data) input_data = input_data.replace([np.nan, np.inf, -np.inf, None], np.na...
472c6eaadf0f9dd705e8600ccb4939d67f387a0e
3,640,663
def property_elements(rconn, redisserver, name, device): """Returns a list of dictionaries of element attributes for the given property and device each dictionary will be set in the list in order of label :param rconn: A redis connection :type rconn: redis.client.Redis :param redisserver: The redis...
70ee3de0a18a84e9f21df341c685c1380a4ab164
3,640,664
def _dtype(a, b=None): """Utility for getting a dtype""" return getattr(a, 'dtype', getattr(b, 'dtype', None))
c553851231f0c4be544e5f93738b43fa98e65176
3,640,665
def parse_garmin_tcx(filename): """ Parses tcx activity file from Garmin Connect to Pandas DataFrame object Args: filename (str) - tcx file Returns: a tuple of id(str) and data(DataFrame) DF columns=['time'(datetime.time), 'distance, m'(float), 'HR'(int), 'cadence'(int), 'speed, m/s'(int)] """...
bc8052850b9aa9fdab82de2814d38ae62aa298c6
3,640,666
def get_decay_fn(initial_val, final_val, start, stop): """ Returns function handle to use in torch.optim.lr_scheduler.LambdaLR. The returned function supplies the multiplier to decay a value linearly. """ assert stop > start def decay_fn(counter): if counter <= start: return...
d84c0f0305d239834429d83ba4bd5c6d6e945b69
3,640,667
from typing import Optional async def is_logged(jwt_cookie: Optional[str] = Cookie(None, alias=config.login.jwt_cookie_name)): """ Check if user is logged """ result = False if jwt_cookie: try: token = jwt.decode( jwt_cookie, smart_text(orjson.du...
e6e3ed4003dc6b60f3b118a98b0fbfb3bcb3b60a
3,640,668
from typing import List def cached_query_molecules( client_address: str, molecule_ids: List[str] ) -> List[QCMolecule]: """A cached version of ``FractalClient.query_molecules``. Args: client_address: The address of the running QCFractal instance to query. molecule_ids: The ids of the mole...
33d8c336daba7a79ba66d8823ba93f35fa37c351
3,640,669
def _domain_to_json(domain): """Translates a Domain object into a JSON dict.""" result = {} # Domain names and bounds are not populated yet if isinstance(domain, sch.IntDomain): result['ints'] = { 'min': str(domain.min_value), 'max': str(domain.max_value), 'isCategorical': domain.is_...
c1d9d860ea1735feacfb7349f4516634e217ea5b
3,640,670
def draw_point(state, x, y, col=COLORS["WHITE"], symb="▓"): """returns a state with a placed point""" state[y][x] = renderObject(symb, col) return state
64b500fdacda30b0506397d554e8ce6d3b7b4a66
3,640,671
def _vars_to_add(new_query_variables, current_query_variables): """ Return list of dicts representing Query Variables not yet persisted Keyword Parameters: new_query_variables -- Dict, representing a new inventory of Query Variables, to be associated with a DWSupport Query current_query_vari...
fd5ea2209b374ab9987a05c139ba1f28805f3eff
3,640,672
def Ak(Y2d, H, k): """ Calculate Ak for Sk(x) Parameters ---------- Y2d : list list of y values with the second derived H : list list of h values from spline k : int index from Y2d and H Returns ------- float A...
baea453b9c7b023b78c1827dc23bacbd8fd6b057
3,640,673
def cycle_list_next(vlist, current_val): """Return the next element of *current_val* from *vlist*, if approaching the list boundary, starts from begining. """ return vlist[(vlist.index(current_val) + 1) % len(vlist)]
48e2ac31178f51f981eb6a27ecf2b35d44b893b4
3,640,674
def _cal_hap_stats(gt, hap, pos, src_variants, src_hom_variants, src_het_variants, sample_size): """ Description: Helper function for calculating statistics for a haplotype. Arguments: gt allel.GenotypeArray: Genotype data for all the haplotypes within the same window of the haplotype to be...
10c3105fe582078d1f24cd740600ccf3c6863407
3,640,675
import json def read_cfg(file): """Read configuration file and return list of (start,end) tuples """ result = [] if isfile(file): with open(file) as f: cfg = json.load(f) for entry in cfg: if "start" in entry: filter = (entry["start"], entry.get("end...
bb9c20b03e95f45708eab17313bc446cc1540308
3,640,676
import scipy def least_l2_affine( source: np.ndarray, target: np.ndarray, shift: bool = True, scale: bool = True ) -> AffineParameters: """Finds the squared-error minimizing affine transform. Args: source: a 1D array consisting of the reward to transform. target: a 1D array consisting of ...
5a6d6d69400327c30d21ae205cab88fd95d856d6
3,640,677
def mark_item_as_read( client: EWSClient, item_ids, operation="read", target_mailbox=None ): """ Marks item as read :param client: EWS Client :param item_ids: items ids to mark as read :param (Optional) operation: operation to execute :param (Optional) target_mailbox: target mailbox ...
80b3fc0b47a9a0044538a2862433a50d5ad36edb
3,640,678
import math def AIC_score(y_true, y_pred, model=None, df=None): """ calculate Akaike Information Criterion (AIC) Input: y_true: actual values y_pred: predicted values model (optional): predictive model df (optional): degrees of freedom of model One of model or df is requr...
6b59dea007f414b0bdc6b972434cb1c2def40bb2
3,640,679
def to_rgb(data, output=None, vmin=None, vmax=None, pmin=2, pmax=98, categorical=False, mask=None, size=None, cmap=None): """Turn some data into a numpy array representing an RGB image. Parameters ---------- data : list of DataArray output : str file path vmin : float or list...
477241dd890b78d7bbf56d3095b42f106af694a7
3,640,680
import requests def id_convert(values, idtype=None): """ Get data from the id converter API. https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/ """ base = 'http://www.pubmedcentral.nih.gov/utils/idconv/v1.0/' params = { 'ids': values, 'format': 'json', } if idtype...
a60698fb20ba94445bbd06384b8523e92bfb91a3
3,640,681
import base64 def authenticate_user(): """Authenticate user""" username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username, password=password).first() if user is not None: ma_schema = UserSchema() user_data = ma_schema.dum...
8e15a3bddf4700c1b207798e3162e3fcef0e7d79
3,640,682
import typing import inspect import warnings def map_signature( r_func: SignatureTranslatedFunction, is_method: bool = False, map_default: typing.Optional[ typing.Callable[[rinterface.Sexp], typing.Any] ] = _map_default_value ) -> typing.Tuple[inspect.Signature, typing.Opti...
e0655bab739b59b0fad94772654a70ce4e6f84fd
3,640,683
def get_random(X): """Get a random sample from X. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- array-like, shape (1, n_features) """ size = len(X) idx = np.random.choice(range(size)) return X[idx]
e493b68ae5b7263786a1a447a0cff78d1deeba24
3,640,684
def _save_update(update): """Save one update in firestore db.""" location = {k: v for k, v in update.items() if k in _location_keys} status = {k: v for k, v in update.items() if k in _update_keys} # Save location in status to enable back referencing location from a status status["location"] = _locat...
109ca0add974f1ac4b604ca7923dbb3444cee9b0
3,640,685
def get_secondary_connections(network, user): """ Finds all the secondary connections (i.e. connections of connections) of a given user. Arguments: network: the gamer network data structure. user: a string containing the name of the user. Returns: A list containing the secondary connecti...
4e53f6e43f2fb132932381370efa4b3a3cd4793c
3,640,686
def get_regression_function(model, model_code): """ Method which return prediction function for trained regression model :param model: trained model object :return: regression predictor function """ return model.predict
fca4a0767b1e741952534baf59ac07cece2c9342
3,640,687
def beam_motion_banding_filter(img, padding=20): """ :param img: numpy.array. 2d projection image or sinogram. The left and right side of the image should be empty. So that `padding` on the left and right will be used to create an beam motion banding image and be ...
5191c1f3022711459ce81cfbf0c4d6c6fb7dcd41
3,640,688
def log(session): """Clear nicos log handler content""" handler = session.testhandler handler.clear() return handler
086e362c8195b917c826fc8b20d3095210ac82fd
3,640,689
import os import gzip def load_mnist(path, kind='train'): """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels-idx1-ubyte.gz' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte.gz' % kind) with gzip.open(labels_path, 'rb') as lbpath: lbpath.read(8) ...
94a123ea29017bd666deebe95f6926e32edf23d8
3,640,690
def calculate_dvh(dose_grid, label, bins=1001): """Calculates a dose-volume histogram Args: dose_grid (SimpleITK.Image): The dose grid. label (SimpleITK.Image): The (binary) label defining a structure. bins (int | list | np.ndarray, optional): Passed to np.histogram, can be ...
007c7eb9c2ddca9809ac2c86f7bf6d34ed14d41b
3,640,691
import torch def build_target(output, gt_data, H, W): """ Build the training target for output tensor Arguments: output_data -- tuple (delta_pred_batch, conf_pred_batch, class_pred_batch), output data of the yolo network gt_data -- tuple (gt_boxes_batch, gt_classes_batch, num_boxes_batch), groun...
4608acb06f8fb0d682058841a8b8151e73b89e7b
3,640,692
def dataframe_with_new_calendar(df: pd.DataFrame, new_calendar: pd.DatetimeIndex): """ Returns a new DataFrame where the row data are based on the new calendar (similar to Excel's VLOOKUP with approximate match) :param df: DataFrame :param new_calendar: DatetimeIndex :return: DataFrame """ ...
4f5b39494080f3eae9083c78d6dd1666c1945e35
3,640,693
def get_language_titles(): """ Extract language and title from input file. """ language_titles = {} input_file = open("resources/events/%s.tsv" % args.event).readlines() for line in sorted(input_file): try: language, title = line.split('\t')[0], line.split('\t')[1].strip() except IndexError: language, t...
dedfa8720194aef1b27c7762041692625c2955e7
3,640,694
def _find_additional_age_entities(request, responder): """ If the user has a query such as 'list all employees under 30', the notion of age is implicit rather than explicit in the form of an age entity. Hence, this function is beneficial in capturing the existence such implicit entities. Returns a ...
971bc0805c607134b6947e0d61ebab6f217c6961
3,640,695
def merge_local_and_remote_resources(resources_local, service_sync_type, service_id, session): """ Main function to sync resources with remote server. """ if not get_last_sync(service_id, session): return resources_local remote_resources = _query_remote_resources_in_database(service_id, sess...
1809caa17c3a8a32a5a3236b313c575ec939c0d8
3,640,696
def alertmanager(): """ to test this: $ curl -H "Content-Type: application/json" -d '[{"labels":{"alertname":"test-alert"}}]' 172.17.0.2:9093/api/v1/alerts or $ curl -H "Content-Type: application/json" -d '{"alerts":[{"labels":{"alertname":"test-alert"}}]}' 127.0.0.1:5000/alertmanager """ alert_json=request.get_...
1e204bd6dce8368c3401cb7e13ea062abebafd71
3,640,697
import argparse def parse_args(): """Process arguments""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--train', '-t', required=True, type=str, help="Training ProteinNet data") ...
c37d11327cb0d0baf3049943320c5bed6fb18e18
3,640,698
def RefundablePayrollTaxCredit(was_plus_sey_p, was_plus_sey_s, RPTC_c, RPTC_rt, rptc_p, rptc_s, rptc): """ Computes refundable payroll tax credit amounts. """ rptc_p = min(was_plus_sey_p * RPTC_rt, RPTC_c) rptc_s = min(was_plus_sey_s * RP...
e282139921045fe8e286abbde6bb4ae44151a50d
3,640,699