content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def expanded_velocities_from_line_vortices( points, origins, terminations, strengths, ages=None, nu=0.0, ): """This function takes in a group of points, and the attributes of a group of line vortices. At every point, it finds the induced velocity due to each line vortex...
228f7aa527dd1e9386bdc76da7c6e3c58698e58c
27,800
def normcase(path): """Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes.""" return 0
d52dca00cc9db607d4ba22c12ba38f512a05107b
27,801
def typeof(obj, t): """Check if a specific type instance is a subclass of the type. Args: obj: Concrete type instance t: Base type class """ try: return issubclass(obj, t) except TypeError: return False
67fbcf8b1506f44dba8360a4d23705a2e8a69b47
27,802
def get_all_clusters(cluster_type, client_id): """Get a list of (cluster_name, cluster_config) for the available kafka clusters in the ecosystem at Yelp. :param cluster_type: kafka cluster type (ex.'scribe' or 'standard'). :type cluster_type: string :param client_id: name of the client maki...
8860435edfde332fd78e3bf01789a2831d884165
27,803
from .. import getPlottingEngine def plot(x, y, show=True, **kwargs): """ Create a 2D scatter plot. :param x: A numpy array describing the X datapoints. Should have the same number of rows as y. :param y: A numpy array describing the Y datapoints. Should have the same number of rows as x. :param colo...
0b43a2b1e442ae19feaf0fb3a64550cad01b3602
27,804
def get_transform_ids(workprogress_id, request_id=None, workload_id=None, transform_id=None, session=None): """ Get transform ids or raise a NoObject exception. :param workprogress_id: Workprogress id. :param session: The database session in use. :raises NoObject: If no transform is founded. ...
08fbd67eb932c7c48b04528dd0863e67669e526e
27,805
from typing import Optional def get_link(hub_name: Optional[str] = None, link_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLinkResult: """ The link resource format. Latest API Versi...
b94a7d2ed3977afbff0699e861da67e1267581b4
27,806
import os import json def rest_scaffold(context, model, app="", api_root="", **kwargs): """ Take name of app and model, return context for template that includes a single variable: the configuration for the rest scaffold. """ # get paging details is_paged = kwargs.pop("is_paged", None) if ...
72ad9b4970488a78f7fcf6a9359e46c98a05d1c2
27,807
import random def selection_elites_random(individuals : list, n : int = 4, island=None) -> list: """ Completely random selection. Args: individuals (list): A list of Individuals. n (int): Number to select (default = 4). island (Island): The Island calling the method (default = Non...
2f7df4e8a347bcd9a770d0d15d91b52956dbd26c
27,808
import ctypes def ekssum(handle, segno): """ Return summary information for a specified segment in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html :param handle: Handle of EK. :type handle: int :param segno: Number of segment to be summarized. :type ...
9c9920d29ed1c1c85524a511119f37322143888c
27,809
def compare_prices_for_same_urls( source_df: pd.DataFrame, target_df: pd.DataFrame, tagged_fields: TaggedFields ): """For each pair of items that have the same `product_url_field` tagged field, compare `product_price_field` field Returns: A result containing pairs of items with same `product_ur...
dc23577169bf6788ecd17eb2fc6c959e367b5000
27,810
def _check_param(dict_): """ check dictionary elements and reformat if need be :return: dictionary reformat """ # default empty dictionary _ = {} if "google_users" in dict_: _["google_users"] = _check_param_google_users(dict_["google_users"]) else: _logger.exception(f"N...
17ccc017fb4a34f3d68ef7150165185e62c7a8dc
27,811
def fetch_dataset_insistently(url: str, link_text_prefix: str, user_agent: str) -> dict: """Fetch the approved routes dataset.""" proxies = get_proxies_geonode() + get_proxies() print(f'{len(proxies)} proxies found.') for i, proxy in enumerate(proxies): print(f'Fetching dataset, try with proxy [...
c98985becc3989980782c4886e18fe7fa56f8d06
27,812
import numpy def _dense_to_one_hot(labels_dense): """Convert class labels from scalars to one-hot vectors.""" num_classes = len(set(labels_dense)) num_labels = labels_dense.shape[0] labels_to_numbers = {label: i for i, label in enumerate(list(set(labels_dense)))} labels_as_numbers = numpy.asarray(...
49cc3ab6bc5f4ec81323321a9fe13d4da030fb4a
27,813
def swish(x): """Swish activation function. For more info: https://arxiv.org/abs/1710.05941""" return tf.multiply(x, tf.nn.sigmoid(x))
40766f934d2e691dc28d5dcd3a44c37cef601896
27,814
def fatorial(n=1): """ -> Calcúla o fatorial de um número e o retorna :param n: número """ f = 1 for i in range(1, n + 1): f *= i return f
5c64b8ccf4a62a1b4294e576b49fbf69e85972ec
27,815
def retrieve_context_nw_topology_service_name_name_by_id(value_name): # noqa: E501 """Retrieve name by ID Retrieve operation of resource: name # noqa: E501 :param value_name: ID of value_name :type value_name: str :rtype: NameAndValue """ return 'do some magic!'
4dcc0b25c6fd76bf94e14d63cb9731946b97b06a
27,816
def conv1x1(in_planes, out_planes, wib, stride=1): """1x1 convolution""" # resnet_wib = False resnet_wib = True resnet_alpha = 1E-3 if not wib: return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) else: return WibConv2d(alpha=resnet_alpha, ...
0ce1d9d47ff98dc7ce607afafb4ea506c850afc3
27,817
def get_rules(fault_block, zone): """Get rules for fault block and zone names. In this model the rules depend only on the zone; they do NOT vary from fault block to fault block for a given zone. Args: fault_block (str) Name of fault block. zone (str) Zone name. ...
12b19cd795ecf618995a2f67f3844792b372d09d
27,818
from operator import concat def conv_cond_concat(x, y): """Concatenate conditioning vector on feature map axis.""" x_shapes = tf.shape(x) y_shapes = tf.shape(y) return concat([ x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])], 3)
583ed5df67245b483531f8e3129ba88b9ec811ef
27,819
def get_clusters(cloud_filtered): """ Get clusters from the cloud. Parameters: ----------- cloud: pcl.PointCloud() Returns: ----------- clusters: pcl.PointCloud() array N """ clusters = [] tree = cloud_filtered.make_kdtree() ec = cloud_filtered.make_EuclideanCl...
b4b7fa0ff8b7f362783bc94727253a2eb41f6f7e
27,820
import json def errorResult(request, response, error, errorMsg, httpStatus = 500, result = None, controller = None): """ set and return the error result @param controller: pylon controller handling the request, where cal context is injected and later retrieved by trackable """ response.status_int...
df386f939751ea268907c016120db7219c3e93bc
27,821
from typing import Dict import logging def parse_main(text: str = "") -> Dict: """ A loop for processing each parsing recipe. Returns a dict of parsed values. """ if text == "": logging.warning("Empty string provided for parsing") parsed_data = {} for recipe in parser_recipe: ...
4574b3e9dce321f169f31031e46e572fac14fce3
27,822
def main(): """ Returns the answer. """ return 42
f6800af5efb0b65f7c7afdd5ea0ede896fd740f8
27,823
import subprocess def sub_proc_launch(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """Launch a subprocess and return the Popen process object. This is non blocking. This is useful for long running processes. """ proc = subprocess.Popen(cmd.split(), stdout=stdout, stderr=stderr) return pro...
3ad582b4c915c65e56833c5cd66c03dcb6765b11
27,824
def collect_accuracy(path): """ Collects accuracy values in log file. """ r1 = None r5 = None mAP = None r1_content = 'Rank-1 ' r5_content = 'Rank-5 ' map_content = 'mAP:' with open(path) as input_stream: for line in input_stream: candidate = line.strip() ...
fa94724f16a332fe18d13df3cc0fbcdd060fe897
27,825
from typing import Type from typing import Mapping def recursively_get_annotations(ty: Type) -> Mapping[str, Type]: """Given a type, recursively gather annotations for its subclasses as well. We only gather annotations if its subclasses are themselves subclasses of Deserializable, and not Deserializable i...
ba531eeba8006aa9393fa2487c056d6309df43d4
27,826
def sector_model(): """SectorModel requiring precipitation and cost, providing water """ model = EmptySectorModel('water_supply') model.add_input( Spec.from_dict({ 'name': 'precipitation', 'dims': ['LSOA'], 'coords': {'LSOA': [1, 2, 3]}, 'dtype': '...
528548e24052913a315804a782cb74cef53b0f08
27,827
def maybe_flip_x_across_antimeridian(x: float) -> float: """Flips a longitude across the antimeridian if needed.""" if x > 90: return (-180 * 2) + x else: return x
50fac7a92d0ebfcd003fb478183b05668b9c909c
27,828
def contour_check(check_points, random_walk): """check_points have dim (n, ndim) random_walk has 3 elements. [0] is boundary unit vectors (can be in any space), [1] is boundary ls (relative to origin) [2] is origin returns: indexer of [True,..... etc.] of which points are in or not ...
fa973c943c4827bd180eb95a3bbc3e0a7d2beb2a
27,829
def _get_erroneous_call(report_text: str) -> str: """.""" erroneous_line = [ line for line in report_text.splitlines() if line.startswith('> ') and RAISES_OUTPUT_SIGNAL_IN_CONTEXT in line ][0] erroneous_assertion = erroneous_line.lstrip('> ') erroneous_assertion = string_remove_from_start(er...
125267db8fb978285fc44ec078364b214c022ca9
27,830
def write_output(features, forecast_hours, poly, line, point): """ writes output to OUTDATA dict depending on query type :param features: output from clipping function :param forecast_hours: list of all queried forecast hours :param poly: boolean to identify a polygon query :param line: boolean...
abc92e597e4d8a409f7c4d0e0b224a76b4a6cd63
27,831
def index(): """ Index set as main route """ return render_template('index.html', title='Home')
bacc433a4523a9b390bdde636ead91d72303cf01
27,832
def plus_one(digits): """ Given a non-empty array of digits representing a non-negative integer, plus one to the integer. :param digits: list of digits of a non-negative integer, :type digits: list[int] :return: digits of operated integer :rtype: list[int] """ result = [] carry ...
a11668a1b2b9adb9165152f25bd1528d0cc2bd71
27,833
def run_experiment(input_frame, n_samples=1, temperature=1, npartitions=1): """ Runs experiment given inputs. Takes `n_samples` samples from the VAE Returns a list of size `n_samples` of results for each input """ encoder_data = a.get_encoder() decoder_data = a.get_decoder() vae = a.g...
2729a977b14235bf5a0e020fbe8a528a5906f212
27,834
def to_angle(s, sexagesimal_unit=u.deg): """Construct an `Angle` with default units. This creates an :class:`~astropy.coordinates.Angle` with the following default units: - A number is in radians. - A decimal string ('123.4') is in degrees. - A sexagesimal string ('12:34:56.7') or tuple ...
106a5be01c3f9150862c1e02f5cd77292b029cf6
27,835
def simpleBlocking(rec_dict, blk_attr_list): """Build the blocking index data structure (dictionary) to store blocking key values (BKV) as keys and the corresponding list of record identifiers. A blocking is implemented that simply concatenates attribute values. Parameter Description: rec_dict...
5bf9b85ad84ffa3dc11a39a876cbcfefe09a5b2c
27,836
def get_marker_obj(plugin, context, resource, limit, marker): """Retrieve a resource marker object. This function is used to invoke plugin._get_<resource>(context, marker) and is used for pagination. :param plugin: The plugin processing the request. :param context: The request context. :param ...
5e66ca50382c6e8a611983252ce44bf50019177b
27,837
import sys import importlib import logging def import_project_module(project_name, project_dir): """Import project module, from the system of from the project directory""" if "--installed" in sys.argv: try: module = importlib.import_module(project_name) except Exception: ...
40f11f65cbd7114a8c10c59d262d9398d713f919
27,838
def generative(max_value: int = FIBONACCI_MAX) -> int: """ This is the fully generative method for the Fibonacci sequence. The full sequence list is generated, the even ones are sought out, and summed --> benchmark: 8588 ns/run :param max_value: The ceiling value of Fibonacci numbers to be added ...
086076d2599297fd23eaa5577985bd64df10cc81
27,839
import traceback def add_vendor_cves(ms_directory, neo4jpasswd, logger=structlog.get_logger()): """ Adds CVEs to database. :param ms_directory: directory where the microsoft files are downloaded :param neo4jpasswd: password to neo4j database :param logger: logger for the method :return: outpu...
74e6f46a68eed13f4f4f10a04e60cdd5a9599c6b
27,840
def enc_net(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = Net(num_classes, **kwargs) # if pretrained: # model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))...
ff8429e6b0e5ef522f6f2a3b0b10a76951a95db8
27,841
def get_bytes(data): """ Helper method to get the no. of bytes in the hex""" data = str(data) return int(len(sanatize_hex(data)) / 2)
014715aa301370ba2d3598c02b66c5b88741b218
27,842
import collections def _group_by(input_list, key_fn): """Group a list according to a key function (with a hashable range).""" result = collections.defaultdict(list) for x in input_list: result[key_fn(x)].append(x) return result
288c108588f9e4ea60c4dac6ff656c8c8ffde580
27,843
import json def set_parameters_in_cookie(response: Response) -> Response: """Set request parameters in the cookie, to use as future defaults.""" if response.status_code == HTTPStatus.OK: data = { param: request.args[param] for param in PARAMS_TO_PERSIST if param in ...
bc5f4e225bdef907ee794e3f8f95ac3d78677046
27,844
from _pytest.logging import LogCaptureFixture import json from typing import Any import logging def test_wild_dlq_error(mock_handler: MagicMock, mock_rsmq: MagicMock, caplog: LogCaptureFixture) -> None: """test error level logs when message fails to successfully reach DLQ""" mock_handler.return_value = False,...
d00c32e27833975d819b333c723734d24b3ead65
27,845
from typing import VT from typing import Optional def teleport_reduce(g: BaseGraph[VT,ET], quiet:bool=True, stats:Optional[Stats]=None) -> BaseGraph[VT,ET]: """This simplification procedure runs :func:`full_reduce` in a way that does not change the graph structure of the resulting diagram. The only thing...
38474e11094a21e581a18591b7649fdbdd977d72
27,846
def map_coords_to_scaled(coords, orig_size, new_size): """ maps coordinate indices relative to the original 3-D image to indices corresponding to the re-scaled 3-D image, given the coordinate indices and the shapes of the original and "new" scaled images. Returns integer indices of the voxel that con...
74236074a0c6c5afbb56bd5ec75caaf517730040
27,847
def _PromptToUpdate(path_update, completion_update): """Prompt the user to update path or command completion if unspecified. Args: path_update: bool, Value of the --update-path arg. completion_update: bool, Value of the --command-completion arg. Returns: (path_update, completion_update) (bool, bool)...
2759e9c42c702a69fa617fc3302cb3c850afc54a
27,848
import os def answer_cells_of_dir(submission_dir): """ get the contents of all solution cells of all ipynb files in a directory """ cells = {} files = os.listdir(submission_dir) for filename in files: if not filename.endswith(".ipynb"): continue noext = filename...
ad62795c5037d74aa8a9f0b125f1ad97cd0ad600
27,849
def _get_static_covariate_df(trajectories): """The (static) covariate matrix.""" raw_v_df = ( trajectories.static_covariates.reset_coords(drop=True).transpose( 'location', 'static_covariate').to_pandas()) # This can then be used with, e.g. patsy. # expanded_v_df = patsy(raw_v_df, ...patsy detail...
15c8f367452fc5007ad93fd86e04cfea07e96982
27,850
import json def answer_cells_of_nb(a_ipynb): """ get the contents of all answer cells (having grade_id) in an a_ipynb file """ cells = {} with open(a_ipynb) as ipynb_fp: content = json.load(ipynb_fp) for cell in content["cells"]: meta = cell["metadata"] ...
3b011d48a8ccfa13d462cccf1b0a58440231a1ce
27,851
def _transpose_augment(img_arr): """ 对称扩增 """ img = Image.fromarray(img_arr, "L") return [np.asarray(img.transpose(Image.FLIP_LEFT_RIGHT))]
096c8db4c008c78a5f22bffeea8bb64fb0a4de09
27,852
def open_sciobj_file_by_path(abs_path, write=False): """Open a SciObj file for read or write. If opened for write, create any missing directories. For a SciObj stored in the default SciObj store, the path includes the PID hash based directory levels. This is the only method in GMN that opens SciObj fil...
8c5852de544be21c61636df03ddb681a6c084310
27,853
def mps_to_kmh(speed_in_mps): """Convert from kilometers per hour to meters per second Aguments: speed_in_mps: a speed to convert Returns: speed_in_kmh: a speed in m/s """ return speed_in_mps / 1000.0 * 3600.0
5a37cbca17f8262043b7e1cb2b193b4c9d146766
27,854
import logging def tokenize_and_remove_stopwords(txt,additional_stopwords): """ Runs tokenization and removes stop words on the specified text Parameters ----------- txt: text to process additional_stopwords: path to file containing possible additional stopwords on each line Returns ...
a118747bbd030e37ee0ed5f421f56390e1bd5b38
27,855
async def async_setup_entry(hass, config_entry, async_add_entities): """Add the Wiser System Switch entities.""" data = hass.data[DOMAIN][config_entry.entry_id][DATA] # Get Handler # Add Defined Switches wiser_switches = [] for switch in WISER_SWITCHES: if switch["type"] == "room": ...
5a83f0888fadab08c573378dce4167f2d01478c1
27,856
def get_keep_dice_check(input_prompt): """ Enables returning a yes or no response to an input prompt. :param input_prompt: String yes no question. """ return pyip.inputYesNo(prompt=input_prompt)
c7b8a1392c3e17a1acba615079848245a1b6e167
27,857
import sh def get_pending_jobs(sort=True): """Obtains the list of currently pending (queued) jobs for the user.""" username = getusername() # see squeue man page for status code (%t specifier) listjob = sh.pipe_out(("squeue", "-u", username, "--noheader", "--format=%i %t"), split=True) rslt = [] # treat o...
5b03917885f8a09463c65a456c251cf753abdae2
27,858
def getOverlapRange(rangeA, rangeB): """ Calculate the overlapping range between rangeA and rangeB. Args: rangeA (list, tuple): List or tuple containing start and end value in float. rangeB (list, tuple): List or tuple containing start and end value in float. Retu...
5f3bd22f5ec317d2bde87c92b027f658a80431fb
27,859
def multiply_values(dictionary: dict, num: int) -> dict: """Multiplies each value in `dictionary` by `num` Args: dictionary (dict): subject dictionary num (int): multiplier Returns: dict: mapping of keys to values multiplied by multiplier """ return ( {key: value * ...
16eb87d60da64d648113858ba5cb4308137e0a14
27,860
def send_alarm(address, email_type, template_data={}): """ Send an email message to the given email address immediately, bypassing any queues or database system. :param address: The email address to send this message to. :param email_type: str defining this email template e.g EMAIL_WELCOME. Defined in e...
2564a3d5c27f092e3e940d907b2cc2bc986257c2
27,861
def serialize_curve_point(p: Point) -> bytes: """ Serialize an elliptic curve point ``p`` in compressed form as described in SEC1v2 (https://secg.org/sec1-v2.pdf) section 2.3.3. Corresponds directly to the "ser_P(P)" function in BIP32 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#...
9e002df4b18245cb4ce54f1aede5687279aae5bb
27,862
def gcom_so_config(revision=None): """ Create a shared object for linking. """ config = BuildConfig( project_label=f'gcom shared library {revision}', source_root=gcom_grab_config(revision=revision).source_root, steps=[ *common_build_steps(fpic=True), Link...
ddcd625cd1393b38e1871f46a2f1b8738a904f1f
27,863
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") "...
4c058afdb03b9d85a32e654f83beec95b72785ee
27,864
def get_basic_details(args, item): """ :param args: { "item_code": "", "warehouse": None, "doctype": "", "name": "", "project": "", warehouse: "", update_stock: "", project: "", qty: "", stock_qty: "" } :param item: `item_code` of Item object :return: frappe._dict """ if not item:...
6ddd7f3249d55a073d57c466e8994c1ccf8b1aa7
27,865
def validate_standard_json(json_to_test: dict) -> bool: """ validate fixed json against schema """ valid_json_flag = False schema_to_use = get_standard_json_schema() valid_json_flag = validate_json(json_to_test, schema_to_use, True) return valid_json_flag
97004d7f5e4758dedeaa4ecaf0ee4a67955336c9
27,866
from typing import Any def put_observation_field_values( observation_id: int, observation_field_id: int, value: Any, access_token: str, **kwargs, ) -> JsonResponse: # TODO: Also implement a put_or_update_observation_field_values() that deletes then recreates the field_value? # TODO: Return...
644c69599816cb4215990dffb13f0e6843ab6da1
27,867
from typing import Any def desg_to_prefix(desg: str) -> Any: """Convert small body designation to file prefix.""" return (desg.replace('/', '').replace(' ', '') .replace('(', '_').replace(')', '_'))
badde1e3ec9c3f669c7cce8aa55646b15cc5f4c8
27,868
def get_logger(name=None, log=False, level=INFO, path=None): """ Returns the appropriate logger depending on the passed-in arguments. This is particularly useful in conjunction with command-line arguments when you won't know for sure what kind of logger the program will need. :param name: ...
be321f4704e98db7a8f4d6033004194104bbee64
27,869
def get_url_for_packages(provenance): """Return url for every package (versioned) as specified in provenance It traverses passes provenance ... Examples -------- >>> get_url_for_packages({'cmtk' : '3.2.2-1.4build1'}) {'cmtk': 'http://example.com/cmtk_3.2.2-1.4build1.deb'} Parameters ...
f89678b9e263bf7053a4d0c9b24e1a4f8d46d180
27,870
def stop_job(job_name: Text, execution_id: Text) -> JobInfo: """ Stop a job defined in the ai flow workflow. :param job_name: The job name which task defined in workflow. :param execution_id: The ai flow workflow execution identify. :return: The result of the action. """ return ...
0e67a061cbb730ffb6ebe57b11d32a3c110566dc
27,871
def find_user(): """ Determines current user using the username value of the current session user and returns the current user as a dict. """ current_user = mongo.db.users.find_one({"username": session["user"]}) return current_user
249836f8f1a23ff34bc55f112db2f4670672a7a1
27,872
def field2nullable(field, **kwargs): """Return the dictionary of swagger field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.allow_none: omv = kwargs['openapi_major_version'] attributes['x-nullable' if omv < 3...
dd5d4cd63aeede4ef9356baa9fe9a48bd5f87841
27,873
def zero_expand3d(inputs, stride=1): """Expand the inputs by zeros explain the expand operation: given stride = 1 [[[1, 2] --> [[[1, 0, 2] [3, 4]] [0, 0, 0] [3, 0, 4]] [[5, 6] [7, 8]]] [[0, 0, 0] [0, 0, 0] ...
4944b3f5f42811955b76fa46082dc5617fb648b7
27,874
import json def _load_setup_cfg(): """Load the setup configuration from the 'setup.json' file.""" try: with open(ROOT / 'setup.json') as setup_json_file: return json.load(setup_json_file) except json.decoder.JSONDecodeError as error: # pylint: disable=no-member raise Dependenc...
b3e26e25f18098a51210221299f3a1066c92e5db
27,875
import json def toJSON(obj, opt_pretty=False, for_cloud_api=True): """Serialize an object to a JSON string appropriate for API calls. Args: obj: The object to serialize. opt_pretty: True to pretty-print the object. for_cloud_api: Whether the encoding should be done for the Cloud API or the lega...
3f3d79d0b3b200ed3a05b55ea671eccae99543ce
27,876
import urllib def load_config_file_koe(filename): """ Loads in a config file for KOE to run Args: filename: Filename (can be absolute or relative path, or a URL) to read config file from. Returns: dict: Configuration file as a dict object. """ config_values = {} # First try t...
e04b162a396f5e3e4747855f7c69b9cad017bb39
27,877
def select_by_type(transcripts, log): """Filter transcripts depending on different type""" # Difference types: UTR5_number and UTR5_boundary candidates, dtype, dcrit = analyse_difference_type_utr5_number_or_boundary(transcripts, log) if candidates is not None: return candidates, dtype, dcrit ...
2b1b7311459e7a305a2cbc64d295114f5bca3fc3
27,878
def lorentzian_distance(x, y): """Calculates the Lorentzian Distance. Args: x (np.array): N-dimensional array. y (np.array): N-dimensional array. Returns: The Lorentzian Distance between x and y. """ dist = np.log(1 + np.fabs(x - y)) return np.sum(dist)
d11cc411aa22aab14b1b3ee2dd606d5a8efb6fe7
27,879
def check_database_status(database_name, env): """This function looks for a DatabaseCreate task and returns a http response or the Database itself depeding on the context. If the DatabaseCreate task is still running of failed, a http response is returned, otherwise this functions tries to retrieve the D...
17d9f616d20638c4624e5b35a042d9265ccf625f
27,880
def get_flat_schema(schema_name=None): """Flatten the specified data model schema, defaulting to the core schema, useful for retrieving FITS keywords or valid value lists. """ return _schema_to_flat(_load_schema(schema_name))
6f43a095015c25bdace05cf473f252ac699b33f9
27,881
def repeat3(img): """ Repeat an array 3 times along its last axis :param img: A numpy.ndarray :return: A numpy.ndarray with a shape of: img.shape + (3,) """ return np.repeat(img[..., np.newaxis], 3, axis=-1)
eddd3469d8d02457b87ef00c13ef7213d3a5568b
27,882
import time import tqdm def encode_strategies(strategies, batch_size=stg.JOBLIB_BATCH_SIZE, parallel=True): """ Encode strategies Parameters ---------- strategies : Strategies array Array of strategies to be encoded. Returns ------- numpy array ...
c77fcd28c69b447e43fc9eef359b32426771d6bd
27,883
def generate_authenticator(data, authenticator_key): """ This function will generate an authenticator for the data (provides authentication and integrity). :param data: The data over which to generate the authenticator. :type data: :class:`str` :param authenticator_key: The secret key to be used b...
8203c9f487d2acf6a8a0bbd907bc1f8cc9dc026c
27,884
import torch import logging def detection_target_layer(proposals, gt_class_ids, gt_boxes, gt_masks): """Subsamples proposals and generates target box refinement, class_ids, and masks for each. Inputs: proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might be zero padd...
539578c3be6a9872d812ccdb236c0cc43d7efe85
27,885
def multi_recall(pred_y, true_y, labels): """ Calculate the recall of multi classification :param pred_y: predict result :param true_y: true result :param labels: label list :return: """ if isinstance(pred_y[0], list): pred_y = [item[0] for item in pred_y] recalls = [binary_...
a11984b6c509b9b95d65ad148ca712099ff91a66
27,886
def is_safe_range(expression): """ Return true if an expression is safe range. This function receives an expression in safe range normal form and returns true if all its free variables are range restricted. """ try: return extract_logic_free_variables( expression ...
e6a23b250f936cc78918ad15eb1122a419a8b872
27,887
def star_marker_level(prev, curr): """Allow markers to be on the same level as a preceding star""" return (prev.is_stars() and not curr.is_stars() and prev.depth == curr.depth)
3311c452c8f138cd8fa75b67109e75a9bf30902c
27,888
from typing import Optional from typing import Sequence def get_mail_addresses(ids: Optional[Sequence[str]] = None, key_word: Optional[str] = None, output_file: Optional[str] = None, sendtype: Optional[str] = None, status: Opt...
52590cc1c12788e47aa81adc1e9f51bbd9092f31
27,889
import torch def load_checkpoint( file, model: torch.nn.Module, optimizer: torch.optim.Optimizer = None, lr_scheduler: torch.optim.lr_scheduler._LRScheduler = None, strict: bool = True, ): """Loads training states from a checkpoint file. Args: file: a file-like object (has to imp...
f4eb59a303a5bf13ff1bdb9f37ca577a4d9e0419
27,890
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x' """ try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip()
6709cfc772ecc79993563f43c2d8ea4526f222c6
27,891
def mac_timezone(): """Determine system timezone""" output = cmdmod['cmd.run']("/usr/sbin/systemsetup -gettimezone") return {'mac_timezone': output[11:]}
e5e8e45fdbd54d1741dd80a76a47f26f43640293
27,892
import os def count_files(directory, filters, extension, show_files=False, **kwargs): """counts the number of files in the first level of a directory Parameters ---------- directory : str path of directory to be checked filters : str filter present in file to be checked extens...
ddc6d23cc42cb4e83bd9127456af1ed013212b42
27,893
from .storage import create_results_archive import sys def run_emcee_seeded(light_curve, transit_params, spot_parameters, n_steps, n_walkers, output_path, burnin=0.7, n_extra_spots=1, skip_priors=False): """ Fit for transit depth and spot parameters given initial gues...
09c3979eec25f6190f0cd1d158bff7f03d45af68
27,894
def lookup_loc_carriers(model_run): """ loc_carriers, used in system_wide balance, are linked to loc_tech_carriers e.g. `X1::power` will be linked to `X1::chp::power` and `X1::battery::power` in a comma delimited string, e.g. `X1::chp::power,X1::battery::power` """ # get the technologies associa...
85c20bd789e0250405dded9e0e4a56777047ef5a
27,895
def filldown(table, *fields, **kwargs): """ Replace missing values with non-missing values from the row above. E.g.:: >>> from petl import filldown, look >>> look(table1) +-------+-------+-------+ | 'foo' | 'bar' | 'baz' | +=======+=======+=======+ | 1 ...
1f14d9e3aba6791ab9d512c647053ad41fcfab59
27,896
def realworld_bring_peg(fully_observable=True, time_limit=_TIME_LIMIT, random=None, log_output=None, environment_kwargs=None, safety_spec=None, delay_spec=None, ...
496c7e31fee93d87d10cbee7bb6369c417956b23
27,897
def schedule_gemm(cfg, s, A, B, C, batched=False, schedule_transforms=True): """Schedule GEMM, single and batched Parameters ---------- cfg : Config Schedule configuration s : tvm.te.schedule.Schedule Operator schedule A : tvm.te.Tensor 2D/3D Tensor, shape [n, k]/[b, n...
2a99a20f4e9634bdaa06d114a9eafb7406736bc3
27,898
import math def distance(x1: float, y1: float, x2: float, y2: float) -> float: """Возвращает расстояние между двумя точками на плоскости""" return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
2113cb5926492ba89820ebb7f42de6993e46e3cb
27,899