content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_all_slots(cls): """Iterates through a class' (`cls`) mro to get all slots as a set.""" slots_iterator = (getattr(c, '__slots__', ()) for c in cls.__mro__) # `__slots__` might only be a single string, # so we need to put the strings into a tuple. slots_converted = ((slots,) if isinstance(slot...
97e4b78ea90f87f54ea86de8b2a8cab36952605f
671,606
def m_per_sec_to_km_per_h(speed) : """ Переводить (м/с) в (км/год) """ return speed * 3.6
20b5f5e60d4ff431e05ac07d886cf62afe00ed4b
671,607
import subprocess def run_local_job(params_file, num_gpus): """ Run a (potentially parallel) job on a single node locally. Args: params_file (str): name of the file from which to load the nn params. num_gpus (int): number of GPUs Returns: p (su...
cddecec984253c23eeea2fd0158b06dd3020a9af
671,609
def set_network_engine_mode_to_inline(api, configuration, api_version, api_exception, policy_id): """ Sets the value of the firewall_setting_network_engine_mode property of a policy. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :param ...
0385476dd8a4e97f3901723e692c64b3698952ee
671,610
import socket def port_scan(host, port): """ connect or die!! """ s = socket.socket() try: s = s.connect((host, port)) return True except Exception: return False
d912d119c457a44679b3416c2eade678ed005e03
671,611
def min_peak(peak): """ Minimum peak criteria Parameters ---------- peak : float The minimum peak pixel value in a leaf """ def result(structure, index=None, value=None): return structure.vmax >= peak return result
ab2a168d689286f28ef767b99b99462bb75ccb69
671,612
def _exclude(term): """ Returns a query item excluding messages that match the given query term. Args: term (str): The query term to be excluded. Returns: The query string. """ return f"-{term}"
7a52ea8fbebab1c4b1fc0c8e94f24ee43c9d5362
671,613
import os def getCCSpec(compiler): """ Helper function to return the key-value string to specify the compiler used for the make system. """ cc = compiler if compiler else None if not cc and "CC" in os.environ: cc = os.environ["CC"] if cc: return "CC=\"%s\"" % cc else: ...
e901aca627a7a6d9bd5aaf91413af090757d012c
671,614
import os import shutil def createBackup(filename): """ Creates a backup file based on the file at filename. If it exists, prints an error message and returns. @ In, filename, string (to be appended with '.bak') @Out, bool, False on success or True on fail """ bakname = filename+'.bak' if not os....
ae053e7a59b4a5cd761bfbca04dcbe99adba56fb
671,615
def make_QC_header(coverage, identity, length): """ Create a header for the read QC file """ cols = "\t".join(["dataset", "read_ID", "passed_QC", "primary_mapped", "read_length", "fraction_aligned", "identity"]) header = "\n".join(["# TALON run filtering settings:", ...
c9022bf60c3c6f10188fedef5a17d70ca0f1675a
671,616
def is_float32(t): """ Return True if value is an instance of a float32 (single precision) type. """ return t.typecode == "f"
5c5b2c06f1ce3b09d7a7006909a47bc24c67b6ee
671,617
def join(left, right): """ Join two dag paths together :param str left: A node dagpath or name. :param str right: A node name. :return: A dagpath combining the left and right operant. :rtype:str """ dagpath = "%s|%s" % (left.strip("|"), right.strip("|")) if left.startswith("|"): ...
5397047bf78d15e40286922ea70a6d97680d33e9
671,618
def hidden_facet_data_two(): """ A second sample TestingHiddenFacets object we are going to facet on """ return { 'first_name': 'Boston', 'last_name': 'Bruins', 'sid': 2, 'unfaceted_string': 'world', 'unfaceted_integer': 456, 'disabled_string': 'apple', 'd...
6022ab88255bc5012c348fd11313d7cbb9b4d1ce
671,619
def setdefault(dict_, key, default=None): """Similar to dict.setdefault""" if dict_[key] == '': dict_[key] = default return dict_[key]
7ed220a0b8a51b459377a7f8d4edc6a005495818
671,620
def js_time(python_time: float) -> int: """Convert python time to js time, as the mephisto-task package expects""" return int(python_time * 1000)
74b2635c480b689523030970c98aa6df40f8fb75
671,621
def boxBasics(box): """basic statistics of box. Returns (mean,var)""" mean=box.box_data.mean() var=box.box_data.var() return (mean,var)
0e9493722637adef80e606225bd712546c998470
671,622
def generator_to_list(function): """ Wrap a generator function so that it returns a list when called. For example: # Define a generator >>> def mygen(n): ... i = 0 ... while i < n: ... yield i ... i += 1 # This is ...
cb4d6ad2af71347145f8483a506426bdbab9f9c0
671,623
import os def get_image_path(image_lists, label_name, index, image_dir, category): """"Returns a path to an image for a label at the given index. # Arguments image_lists: Dictionary of training images for each label. label_name: Label string we want to get an image for. index: Int offset of...
511ba795b36384ae42ebc591b91ba2db1e9c91f3
671,624
def find_area(coordinates): """ Requires an list or a numpy array of shape (2,4) """ X1 = coordinates[0][0:2] Y1 = coordinates[0][2:4] X2 = coordinates[1][0:2] Y2 = coordinates[1][2:4] dx = min(max(X1[1],X1[0]),max(X2[1],X2[1]))- max(min(X1[0],X1[0]),min(X2[0],X2[0])) dy = ...
935665a47b488e6601a33689bdf52ee1a3c53df4
671,625
import socket import logging def create_socket(host, port): """ Function which create socket with server :return: nothing """ try: tcp_ip = socket.gethostbyname(host) tcp_port = port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((tcp_ip, tcp_port...
13d6f38ad75e89a0e3f5cd607912abe02216cc5c
671,626
import torch def normalize_kernel2d(x: torch.Tensor) -> torch.Tensor: """Normalizes kernel.""" if len(x.size()) < 2: raise TypeError("input should be at least 2D tensor. Got {}" .format(x.size())) norm: torch.Tensor = x.abs().sum(dim=-1).sum(dim=-1) return x / (norm.uns...
cf0a108926f7e503c01ca93eded4bb11d86ea720
671,627
from typing import Mapping def strip_indexes(indexes): """Strip fields from indexes for comparison Remove fields that may change between MongoDB versions and configurations """ # Indexes may be a list or a dict depending on DB driver if isinstance(indexes, Mapping): return { k...
37fd93c18c8201209794b6849fd3bc00175ab1d1
671,628
def horizontal_refold(Au, i: int): """ Assuming that A was a 3D tensor that was horizontally unfolded to Au, this returns the original 3D tensor A. Must suply the unfolded tensor Au and the length of the central dimension i """ S = Au.shape r3 = S[1] // i return Au.reshape(S[0], i, r3)
1c6367dc2663b2203fb66b811778a0cb4ce2b0c6
671,629
import contextlib import socket def get_local_port(): """Return free local port. """ with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.bind(("", 0)) return sock.getsockname()[1]
8dd8a965f681a191ff9ac532b942f5cc956e1bd1
671,630
import subprocess def my_serial(): """Return Serial Number.""" return [x for x in [subprocess.Popen("system_profiler SPHardwareDataType |grep -v tray |awk '/Serial/ {print $4}'", shell=True, stdout=subprocess.PIPE).communicate()[0].strip()] if x]
47b71fc6a9a5f0f7978580c36399b541d89258ff
671,632
def subclass_by_name(key: str): """ Evaluates the subclasses of the abstract base class Queue and returns the subclass with key in its name :param key: :return: """ for cls in eval('QueueABC').__subclasses__(): if key.lower() in cls.__name__.lower(): return cls
6d3e8e52f4d78ac54479b8ee43be0b5ab40ec8dd
671,633
def get_min_key_for_max_value(d): """ For a dictionary d, get the key for the largest value. If largest value is attained several times, get the smallest respective key. """ sorted_keys = sorted([key for key in d.keys()]) values = [d[key] for key in sorted_keys] max_value = max(val...
af5dfb5f9471e3b4757e129cc81eb0f89579c7fc
671,634
def session_position(df): """Proportion of way through session in which survey was clicked.""" for i, r in enumerate(df.session): if r["id"] == df.survey_request["id"]: if len(df.session) == 1.: return None else: return i / (len(df.session) - 1)
43abfc36a405d40be5ce647aa581bf491dec9deb
671,635
def find_subtree(tree, node_id): """ Recurse through the tree until the node is found Then return the node Args: tree: Node containing full tree node_id: string id directing which nodes to traverse Returns: Node containing full tree """ # We have reached the correct...
a899d00d25eac865c29b2d0926fb5e9cec85deae
671,636
def one_step_integrator(state, ders, I, dt): """RK4 integrates state with derivative and input for one step of dt :param state: state of the variables :param ders: derivative functions :param I: input :param dt: time step :return: state after one integration step""" D = len(state) # 1 k1 = [ders[i](state,I) ...
f78fdf108c0ca82b5c93f36eab9c5f2da1d8ad5a
671,637
import os def get_all_files(train_data_file): """ get all files """ train_file = [] train_path = train_data_file if os.path.isdir(train_path): data_parts = os.listdir(train_path) for part in data_parts: train_file.append(os.path.join(train_path, part)) else: ...
d03c07ba00824842b33d971d9950a867fd3d394d
671,638
def fraction_of_contacts(cm, ref_cm): """ Given two contact matices of equal dimensions, computes the fraction of entries which are equal. This is comonoly refered to as the fraction of contacts and in the case where ref_cm represents the native state this is the fraction of native contacts. ...
0c49d72c196d78e6be6a6c1903b250d668bdb96a
671,639
def get_students(selection_db, aws_db, applicants_sql, student_fields_sql): """ Calls the database and gets student information. Input: database connection object, SQL query, dict of fields name/ID Returns: dictionary of student information, key=student ID """ students = {} with selection_d...
5295e1564f60f07eebaa0e1ae8654522c21db1c9
671,640
def monthly_soil_heat_flux2(t_month_prev, t_month_cur): """ Estimate monthly soil heat flux (Gmonth) [MJ m-2 day-1] from the mean air temperature of the previous and current month, assuming a grass crop. Based on equation 44 in Allen et al (1998). If the air temperature of the next month is availabl...
9f75d40953114d2f96cab7dee59c511a9ecc25c8
671,641
def find_closest_smaller_value(find_value, list_of_values): """ Returns the closest value from a list of values that is smaller than find_value :param find_value: The value we are searching for :param list_of_values: The list of values :return: The index of the closes value in the list. Returns -1 i...
e221b3c55f330c3e884fcc2ebcfe7363527effb0
671,642
import torch import typing def normalize_labels(labels: torch.Tensor) -> typing.Tuple[torch.Tensor, int]: """Normalize a list of labels, for example: [11, 11, 20, 20, 60, 60, 6, 6] => [0, 0, 1, 1, 2, 2, 3, 3] """ if labels.ndim > 1: raise ValueError("Input must be a 1d tensor, not {}".format(l...
ee2cb652b21bc6d5840942d80e36ba5e7bee31c2
671,643
def test_function_attributes(cache): """ Simple tests for attribute preservation. """ def tfunc(a, b): """test function docstring.""" return a + b cfunc = cache()(tfunc) assert cfunc.__doc__ == tfunc.__doc__ assert hasattr(cfunc, 'cache_info') assert hasattr(cfunc, 'cache_clear'...
591e0148a5fbeb2cece1114f728a34ed6c453b9c
671,644
import os def call_amber_package(request, config, function): """ Create temporary files and invoke the `function` using `config`. """ # Create unique workdir and save file workdir = request['workdir'] if not os.path.isdir(workdir): os.mkdir(workdir) tmp_file = os.path.join(workdi...
de9ace3643b7cdeaf50cfa334c4a66f1833e6d85
671,645
import re def FillParagraph(text,width=70,indentLinesBy=0): """ >>> txt = "123 567 90 123\\n456 89\\n" >>> print FillParagraph(txt,width=10) 123 567 90 123 456 89 >>> print FillParagraph(txt,width=10,indentLinesBy=3) 123 567 90 123 456 89 >>> txt = '123 567 \\n' >>> print FillParagraph...
d5cbc05c090ecca5f64fa519e2772b2154b029bd
671,646
def get_fbonds(graph, key): """Get all the possible forming bonds of a certain type Arguments: graph (nx.Graph): graph object of a molecule key (str): string representing the bond type to be examined Returns: list: list of bonds that can be made of this type """ possible_fb...
e3fa72362fc7d3b0d48693c9bf932223a0305458
671,647
def compute_colors(H): """ hypograph -> hypograph with colors based on evidenced not evidenced - "color: red" evidenced - "color: green" """ clr_unevidenced = 'rgba(194, 91, 91' clr_evidenced = 'rgba(91, 194, 92' for (n, d) in H.nodes_iter(data=True): if d['evidenced'] == 1: ...
13c2adad02156dd19fba708ffebf803fca0933d6
671,648
def _get_prop(title): """Get property name from plot title. Parameters: title (str): Plot title. Returns: str """ if 'vel' in title: return 'vel' elif 'sigma' in title: return 'sigma' else: return 'default'
fad17861a3d3520682adae6d825ef552ae6ab0da
671,649
def bind(instance, func, as_name=None): """ Bind the function *func* to *instance*, with either provided name *as_name* or the existing name of *func*. The provided *func* should accept the instance as the first argument, i.e. "self". """ if as_name is None: as_name = func.__name__ ...
ee7bf95abaf0fdb1751f96a3982784e762203f29
671,650
import os def _package_files(directory: str, suffix: str) -> list: """ Get all of the file paths in the directory specified by suffix. :param directory: :return: """ paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: ...
760e82e2d3836bc575e47d89f532d2c4fabe20b3
671,651
def _event_QListWidgetAddRemove(self): """ Return current selection changed signal for QListWidget. """ return self.itemAddedOrRemoved
b93f48402c30db32fe7fa1438c7e638d1f135909
671,652
def transl_mol(mol, vec): """Translates a molecule""" atms = [] for atm_i in mol: atms.append( (atm_i[0], ) + tuple(i + j for i, j in zip(atm_i[1:4], vec)) ) continue return atms
da005b684ba0edbfbf81cf22e6a5a49174f45cae
671,653
import logging import requests import json def obtain_token(ip,username,password): """This is a function that obtains a HyperFlex API access token. A HyperFlex API access token authorizes API operations on a HyperFlex cluster. Args: ip: The targeted HyperFlex Connect or Cluster Management IP ...
0bb86f9d8d30874ff0326fa11acd1d27115f12ce
671,654
def fill_in_particular_status(response, ids, template_to_fill, object="harvester"): """Replaces `template_to_fill` (e.g. `FULL_IDS`) in templated response to objects with given `ids` """ if len(ids) == 0: response = response.replace(f"{object} {template_to_fill} is", "none is") elif len(ids) == ...
cc5a88dbbfc5415dcc96843c37f1e50410a94aad
671,656
def n_process(data, L, R): """ Apply panning gains based on chosen pan law. Params ------- data : ndarrary Input audio data. (samples, channels) currently only support max of 2 channels Returns ------- output_buffer : ndarray Panned input audio. (samples, channels) ...
92e8543e1b794fbc3b700f54ce20131cc85f12f7
671,658
def split_readme(readme_path, before_key, after_key, options_key, end_key): """Return split readme.""" with open(readme_path) as readme_file: readme = readme_file.read() top, rest = readme.split(before_key) before, rest = rest.split(after_key) _, rest = rest.split(options_key) _, bottom...
7d4a082700f5618038105027a3aa78cc971689ad
671,659
def get_chef_cookbook_params(hostname="sonic"): """ :return: """ chef_cookbook = dict() chef_cookbook["name"] = hostname chef_cookbook["description"] = "This is a sample cookbook file for chef" chef_cookbook["json_class"] = "Chef::Role" chef_cookbook["default_attributes"] = dict() ch...
b1b38e4e805833605c2c05fc533ae4094acc3d91
671,660
def _nonnegative_nonzero_integer(x): """Check for nonnegative and nonzero integer.""" if x is not None: try: x = int(x) except ValueError: raise ValueError( "'stata_check_log_lines' must be a nonzero and nonnegative integer, " f"but it is '...
90dbabc8e10c3806d7cc1771a7607fbd9d0da0d2
671,661
def CollectionToResourceType(collection): """Converts a collection to a resource type: 'compute.disks' -> 'disks'.""" return collection.split('.', 1)[1]
6b98b7c84e4cfea7f4733bd46e623c16d2f00409
671,662
def empty_kubeconfig(): """Generate and return a kubeconfig object.""" return { "apiVersion": "v1", "contexts": [], "clusters": [], "current-context": "", "kind": "Config", "preferences": {}, "users": [], }
83b571376b92f0839d9e893ce0a7bc53fda59891
671,664
def find_last_break(times, last_time, break_time): """Return the last index in times after which there is a gap >= break_time. If the last entry in times is further than signal_separation from last_time, that last index in times is returned. Returns -1 if no break exists anywhere in times. """ i...
01d883bc0c67022a32397f87703acf109f95bd55
671,665
import torch def inner_product(this, that, keepdim=True): """ Calculate the inner product of two tensors along the last dimension Inputs: this, that ...xD torch.tensors containing the vectors Outputs: result ... torch.tensor containing the inner products ...
221ab83e11d96e542099be7db8abe4d53640bf38
671,667
def test_side_effect(x): """ int -> int """ y,a = 1,0 #z: int z = x return z
fb099ae55a7465639b700bfeb8b20ec173464735
671,668
import re def clean(value): """ Remove all unnecessary characters from ArticlesItem date and turn in into datetime value :param value: values to be processed :type: list :return: datetime """ return [re.sub(r'[*_]', '', "\n".join(value)).strip()]
2aef8415e43ff2aebdf4252e12567c4870971c75
671,669
import requests import json def get_games_summary_data(s_month, s_day, s_year, e_month = None, e_day = None, e_year = None): """ Returns a JSON file containing the summary of the games played on a specified day. Currently working on allowing the user to specify a date range. :param s_month: Start mon...
076cccec9044631134a4084e81be7833f89ba38d
671,670
def displayhtml (public_key): """Gets the HTML to display for reCAPTCHA public_key -- The public api key""" return """<script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="%(PublicKey)s"></div>""" % { 'PublicKey' : public_key }
84e4bf8c5ef36c1c4213e9eefa35882638578fc4
671,671
def prod(xs): """Computes the product along the elements in an iterable. Returns 1 for empty iterable. Args: xs: Iterable containing numbers. Returns: Product along iterable. """ p = 1 for x in xs: p *= x return p
563aad9e60e8c214ff7c1af4fb1f9549868927b4
671,672
def root_url() -> str: """Root API route. No functions. Returns ------- str Error and message about API usage. """ return "Folder data microservice.\nWrong request. Use /api/meta/<folder> to get folder list."
942189c25e488ea15ddcd9805aca24d7c9e4cce4
671,673
def measureDistance(pointA, pointB): """ Determines the distance pointB - pointA :param pointA: dict Point A :param pointB: dict Point B :return: int Distance """ if (pointA['chromosome'] != pointB['chromosome']): distance = float('inf'); if ('position...
baf35b72d4d502af89792790e334c30ec4d5cadd
671,674
from typing import Union def maybe_int(string: str) -> Union[int, str]: """Try to cast string to int. Args: string: Input string. Returns: Maybe an int. Pass on input string otherwise. Example: >>> maybe_int('123') 123 >>> maybe_int(' 0x7b') 123 ...
79c7a6d852a8f68effc3a0180ff25f751d49df37
671,675
from unittest.mock import call def torch(on=None): """lets you turn on/off the torch (flashlight) of the phone""" if on is True: command = "termux-torch on" call(command, shell=True) return True elif on is False: command = "termux-torch off" call(command, shell=True) return True else: return False
3482dee4b6c92d3b0931399b53bf1a23a7d5a38b
671,676
import torch def generate_sample_rgbd(gen, fixed_z, test_y_rotate, angle_range=8, num_sample=4, device=torch.device("cuda")): """ generate sample images with multiple y angles using given generator model """ latent_z = fixed_z[:num_sample] latent_z = torch.cat( [torch.cat([latent_z[i].res...
3497608880e032533ee97914e419290080cce39e
671,677
def args_to_dict(args): """ Convert template tag args to dict Format {% suit_bc 1.5 'x' 1.6 'y' %} to { '1.5': 'x', '1.6': 'y' } """ return dict(zip(args[0::2], args[1::2]))
b7a3fc75ff4f4df4060d189c42e3c54c9b518f36
671,678
def create_temporal_folds(exp): """ Returns list of as_of_dates to be used in temporal cross validation """ as_of_dates = [] temporal = exp['temporal_deltas'] data_starts = temporal['data_starts'] data_ends = temporal['data_ends'] test_label_span = temporal['test_label_span'] test_sp...
0051aba0747b90dab3f86ae2d04ebe3ce3f00536
671,679
def get_image_frames(content_tree, namespaces): """find all draw frames that must be converted to draw:image """ xpath_expr = "//draw:frame[starts-with(@draw:name, 'py3o.image')]" return content_tree.xpath( xpath_expr, namespaces=namespaces )
cd849487dd9f3ddbf03ec63b3630285323ae3866
671,680
def is_structure_line(line): """Returns True if line is a structure line""" return line.startswith('#=GC SS_cons ')
78017b53de123141f9263a3a34e2c125bb585d88
671,681
import argparse def str2bool(input_bool): """ Determine if input is True or False Parameter: string(string): string representation of a bool Return: string(string): string representation of a bool """ if isinstance(input_bool, bool): return input_bool if input_bool.lower(...
60b77dcdfc3cdb747f5a2b15cc728c79ffb3ae04
671,682
def GetRefreshInterval(queuetime_in_sec, runtime_in_sec, method_submission):# {{{ """Get refresh_interval for the webpage""" refresh_interval = 2.0 t = queuetime_in_sec + runtime_in_sec if t < 10: if method_submission == "web": refresh_interval = 2.0 else: refres...
1001e227c43a9f0da780e6580ef6ad307292b96a
671,683
def load_QtCSS_StyleSheet(path): """Loads the QtCSS style sheet""" with open(path, "rt") as f: lines = f.read() return lines
ed043db4f8ac838031961f8a76e5c3572e22cd70
671,684
def _align_interval(interval): """ Flip inverted intervals so the lower number is first. """ (bound_one, bound_two) = interval return (min(bound_one, bound_two), max(bound_one, bound_two))
4e6d510bb489127d842b2ef917e234c90cd032ab
671,685
def graphql_custom_class_field(field_func): """Decorator that annotates a class exposing a field in GraphQL. The field appears in the GraphQL types for any of the class's subclasses that are annotated with graphql_object or graphql_interface. It is not useful to decorate a function with graphql_cu...
ab3d2d3a6896f61ccfc35caf3519975d593898d0
671,686
def get_project_options(defaults=None): """project-related options """ if defaults is None: defaults = {} options = { # The path to a file containing project attributes. '--project-attributes': { 'action': 'store', 'dest': 'project_attributes', ...
2b7863ab3e6de3f80ac4d96191fe0c29c7fce90d
671,687
def some_data(): """Use fixtures instead of setUp & tearDown methods to provide data or do whatever... https://docs.pytest.org/en/latest/fixture.html""" return 42.
e6009aa39b34850457b8cf3119df5ae025e49cb1
671,688
import os def count_batches(folderpath): """ Returns the number of training data batches in the input folder. Input: string specifying path Returns: int specifying the number of batches """ return sum(["training_images_batch" in filename for filename in list(os.walk(folderpath)...
957957c492774c65530c9e7bce139d2faf393d60
671,689
def select(ds, **selection): """ Returns a new dataset with each array indexed by tick labels along the specified dimension(s) Parameters ---------- ds : xarray Dataset A dataset to select from selection : dict A dict with keys matching dimensions and values given by scalars...
9bea1a7d9f61c707bc0b733e42620e7f4a4779d7
671,690
import glob def get_data(path): """"Gives back a list of all .csv files in the given path""" files = [f for f in glob.glob(path + "/*.csv", recursive=True)] return files
70c27a91088254792ea0d78fafe618eae68e0b5a
671,691
def _get_schema_table_name_map(table_name): """a method to split a qualified table into it's parts """ parts = table_name.split('.') schema_index = 1 table_index = 2 if len(parts) == 2: schema_index = 0 table_index = 1 return {'schema': parts[schema_index].lower(), 'table_...
a3e903720919623e76de4c10a94c895db1f1fc5c
671,692
import re def check_update(old_time, new_time): """시간을 비교해서 업데이트 해야할지, 말아야할지 결정 Args: old_time: kcdc 업데이트 날짜와 시간 new_time: 각 사이트 업데이트 날짜와 시간 Returns: 새로 업데이트 해야한다면 True, 아니라면 False """ def check_time(time_list): if time_list[0] not in ["2020", "20"]: t...
d6c7b6d6fead86fbc61cae815faa9d4b488e1db3
671,693
def one_and_none(first, second): """ Check if one element in a pair is None and one isn't. :param first: To return True, this must be None. :type first: str :param second: To return True, this mustbe false. :type second: str """ sentinel = True if first is None and second is not None e...
acb745e0ae2d1e10c697b1c4390b42e60528287c
671,694
def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is No...
76b00e34480cede3c9b94de4612bd2c3aa64567c
671,695
import random def create_url( ticker, exp_date_str): """create_url :param ticker: ticker to look up :param exp_date_str: expiration """ srv = random.randrange(1, 3, 1) if exp_date_str: return ( f'https://query{srv}.finance.yahoo.com/v7/' f'finan...
c6b5d1b2beb2c9951886d56ef78211ec7e9dfd54
671,696
def getSubclasses(cls): """ Fetch all existing subclasses of a class. :param cls: :return: """ return set(cls.__subclasses__()).union([s for c in cls.__subclasses__() for s in getSubclasses(c)])
77a9e9c98b25a3c5dd180f30356686fb46313804
671,697
def accuracy_score(data): """ Given a set of (predictions, truth labels), return the accuracy of the predictions. :param data: [List[Tuple]] -- A list of predictions with truth labels :returns: [Float] -- Accuracy metric of the prediction data """ return 100 * sum([1 if p == t else 0 for p, ...
7170b9e60905736321b7300903a19661c8508380
671,698
def parse_html(fileName): """ """ return None
58735e4e23a1ebacdbc26ef555d5f874b6774be7
671,699
def prune_graph(adj_lists, relations): """The function is used to prune graph based on the relations that are present in the training Arguments: adj_lists {dict} -- dictionary containing the graph relations {set} -- list of relation ids Returns: dict -- pruned graph """ ...
15db50339284f7e303d2ed0cc8466207dad366e7
671,700
def split_lines_by_comment(lines): """Doc.""" lines_list = [] new_lines = [] in_multi_line_comment = False for line in lines: line = line.strip() if not line: continue if not in_multi_line_comment: if line.startswith('/*'): in_multi_l...
1b5d8f67e8fc8c2d937a9e09d7ca0d42cc3ef49f
671,701
import os import sys def _updated_gmt_datadir(code_dir): """ Add the code's current directory to evirionment variable GMT_DATADIR so that script can access its data files. """ if os.environ.get("GMT_DATADIR") is not None: sep = ";" if sys.platform == "win32" else ":" return f"{sep}...
b0a8f40987a79cb1f94f8c1c8360c89fcc01021b
671,702
import os def get_dir_names(dir_path): """Create a list that contains the parameter directories names""" dir_names = next(os.walk(dir_path))[1] return dir_names
788fb6183726a56aae50240f393dde99caee425e
671,703
def as_time(arg): """Defines the custom argument type TIME. Converts its input into an integer if it lacks a unit suffix, otherwise a float. Args: arg (str): A command line argument. Returns: Value of arg converted to a float (duration) or integer (integrations). Raises: ...
78bc63378e17850da505ca383fe96986cd86630d
671,704
import requests import json def put_item(client, item) -> tuple[int, str]: """PUT updated item to FOLIO inventory Args: client: FolioClient item: JSON representation of item as a dictionary Returns: Tuple of HTTP status code and message if error. """ url = f"{client.okap...
874eaae3f33daf04529e1048b6b1c19082ca0ead
671,705
def abbreviate(measure): """Get abbreviation of measure.""" lstr = measure.lower().replace(' ', '').replace('-', '') if lstr in ('dice', 'dicecoefficient', 'dicesimilaritycoefficient', 'sorensendicecoefficient', 'sorensendiceindex', 'sorensenindex', 'sorensondicecoefficient',...
f4b02abfeb4772da75dbf038b5d7616ffb3899c7
671,706
import argparse def parse_arguments(): """Parse command line argument.""" parser = argparse.ArgumentParser( description='Check a consul service health' ) parser.add_argument('-t', '--token', default=None) parser.add_argument('service') parser.add_argument('-H', '--host', default='local...
dc13d53dbb0243214f23ee35688d090f6d82bea9
671,707
import os import json def _load_starmap(): """Load the starmap from static data.""" static = os.environ.get("STATIC_DATA", os.path.realpath( os.path.dirname(__file__))) jump_map = os.path.join(static, "jumpmap.json") if not os.path.isfile(jump_map): raise RuntimeError("missing data:...
1b055c5cc47dfea42da28fb90b9bcb6b398e5718
671,710
def convert_html_tags_to_jats(xml_etree): """ This methods receives an etree node and replace all "html tags" to jats compliant tags. """ tags = ( ('strong', 'bold'), ('i', 'italic'), ('u', 'underline'), ('small', 'sc') ) for from_tag, to_tag in tags...
eb250aa247ab4aee95378d12cc106ec6630f33af
671,711
def compare_hashes(hash_input_1: dict, hash_input_2: dict, kwargs): """ Compares two dicts of hashes, and returns a true value if the number of successful matches exceed the success ratio. The threshold for matching depends on the cutoff. There is two modes: similar and identical. :param hash_inpu...
2144d6c8612127812c901864069ecca095eda438
671,712
def _is_valid_input_row(row, conf): """ Filters blank rows and applies the optional configuration filter argument if necessary. :param row: the input row :param config: the configuration :return: whether the row should be converted """ # Filter blank rows. if all(value == None for v...
cff8797e32a74f5144f4705db14e604618a26136
671,713