content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import email def _getcharset(resp, default='utf-8'): """ Extract the charset from an HTTPResponse. """ # In Python 3, HTTPResponse is a subclass of email.message.Message, so we # can use get_content_chrset. In Python 2, however, it's not so we have # to be "clever". if hasattr(resp, 'heade...
be80b5b1ab527be83cd55a297f3ba65023d38949
74,300
def self_consistent_update(u_kn, N_k, f_k): """Return an improved guess for the dimensionless free energies Parameters ---------- u_kn : np.ndarray, shape=(n_states, n_samples), dtype='float' The reduced potential energies, i.e. -log unnormalized probabilities N_k : np.ndarray, shape=(n_sta...
66d67a0f467f8d39405435012fc716238fab6bfd
74,301
import os def get_int_filename(filename): """ Get the integer value of a filename """ name = os.path.splitext(filename)[0] try: return int(name) except ValueError: return 0
b10d19ad016411a78454bbd010855c6ffb0dac71
74,302
def get_client_ip(request): """ Returns returns client's ip Args request object as given by django TODO This function isn't secure at the moment. Either use the package django-ipware or create your own. """ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') ...
5df00602a5fbe4b99bcd157205f28d962134d305
74,303
def find_address_of_type(host_elem, type_): """Return the host's address of the given type, or `None` if there is no address element of that type. """ address_elem = host_elem.find('./address[@addrtype="{}"]'.format(type_)) if address_elem is not None: return address_elem.get('addr')
ff821703d076865da3c6efe0d2d760c4fcb2c997
74,304
import re def IsValidAtom(atom): """Test if an atom conforms to the JHM definition of an atom""" return re.match("([_a-zA-Z][_\-a-zA-Z0-9]*)?",atom)
218e846db1559bb91ab1ab47c5955d43b8274866
74,305
def submit(command, args=None, kwargs=None, name=None, qtype=None, profile=None, queue=None, **kwds): """Submit a script to the cluster. Parameters ---------- command : function/str The command or function to execute. args : tuple/dict, optional Optional arguments to add ...
a7bde7fca3b84d501682a749c2475cc760a36892
74,306
import re def fuzzyfinder(user_input,collection): """ fuzzy matching, to obtain a fuzzy matched list. >>>collection = [ "user_name", "api_user", "school", "email" ] >>>fuzzyfinder("user",collection) ...
db01f13f3caf5dc9a21cfb180776c22b589f1a28
74,307
import pickle def cache_memoize(max_age): """ Memoize decorator that uses Django's cache facility. Parameters ---------- max_age : int Maximum age of memoized results, in seconds. """ def decorator(func): site = Site.objects.get_current() key_prefix = 'cache_m...
9d115f3889a34f21528af8e494452e068f00024a
74,308
import jinja2 import inspect def set_template_env(template_dir): """ Function that sets the Jinja2 template environment from a given dir. Returns nothing. Input: - template_dir path """ env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), lstrip_blocks=Tr...
0f2a5375b9f3e2fca26cd12c8878eca23479bf12
74,309
def bq_token_file_path_exists_mock(token_path): """ Mock bq_token_file_path_exist to return True """ return True
54958444c16c4244ab349d60b0add39723ba6d8b
74,310
def view_cadastrar_usuario_passivo(request, callback=None): """ View de cadastro de novos usuários passivos. :param callback: próxima página :param request: POST form :return: """ if request.method == 'POST': form = FormCadastraUsuarioPassivo(request.POST) ...
1c2940b613ea7a27f5a8f1395d579be511be2b86
74,311
def unsqueeze(input, axes, name=None): """ Insert single-dimensional entries to the shape of a Tensor. Takes one required argument axes, a list of dimensions that will be inserted. Dimension indices in axes are as seen in the output tensor. For example: .. code-block:: text Given a tens...
c6d6aa8ac54027164b501fd1c8105a2132dbf5a2
74,312
def get_tpu_run_config_from_hparams(hparams): """Create a TPU-suitable RunConfig from HParams.""" tf.logging.info('tpu_location: %s', hparams.tpu_params.tpu_location) tf.logging.info('gcp_project: %s', hparams.tpu_params.gcp_project) tf.logging.info('tpu_zone: %s', hparams.tpu_params.tpu_zone) cluster_resolve...
583cd835f1c292308acc61574559d6745b1bdefb
74,313
def masa_strugotine(volumen_strugotine, gustoca_materijala): """ """ return 1e-9*volumen_strugotine*gustoca_materijala
06e65566ff2a9c13fabe1316a7a290c1145a741c
74,314
def get_edges(img): """搜索图片边界 :param img: 图片 :return: left, right, top, bottom """ image = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR) img = cv2.medianBlur(image, 5) # 中值滤波,去除黑色边际中可能含有的噪声干扰 b = cv2.threshold(img, 15, 255, cv2.THRESH_BINARY) # 调整裁剪效果 binary_image = b[1] # 二值图--具有三...
80442261977266ec5e17e5b710fbd09838fca4a3
74,315
def load_data(data_dir): """Loads the data. Returns tuple (`train_ds`, `val_ds`).""" # Training data. train_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, validation_split=VALIDATION_SPLIT, subset="training", seed=123, image_size=(IMG_HEIGHT, IMG_...
eb5fb41d9d98517d5ab72dadc80e59f35fde4c4e
74,316
def put_events(environment, start_response, headers): """ Store events in backends POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), events: { stream_name1 : [event1, event2, ...], stream_name2 : [event1, event2, ...], ... } }...
168bad8c98542a3d194ca61cb7c49c90fe5d2ee5
74,317
def main(important_parameter, ignored_parameter): """ :return: The answer to everything """ important_field = important_parameter # this way the parameter was actually used, hence making it important. def realmain(): def actualrealrealmain(): def nownoteve...
abde26d4c49e4300497a39df4c78f1e1d4ed9b5d
74,318
from typing import List from typing import Dict from typing import Any def _postporcess_edn(decks: List[Dict[str, Any]]) -> Dict[str, Any]: """ Tweak the data representation to fit what mochi expects """ for d in decks: d['name'] = d['name'].split('::')[-1] d['id'] = edn_format.Keyw...
2a4bf126867c624ac89bb9589149d3ec50db8f7c
74,319
import os import urllib import time def DownloadData(output_folder, latlim, lonlim, dataset, level = None): """ This function downloads SoilGrids data from SoilGrids.org Keyword arguments: output_folder -- directory of the result latlim -- [ymin, ymax] (values must be between -50 and 50) lonlim...
b6ebd0a0322c20c547b55959c7037379cf76f832
74,320
from typing import Any def get_parent_dir(test_filepath: Any) -> Any: """Returns PurePath to parent directory of argument filepath. Arguments: test_filepath {Any} -- python Path to .robot file Returns: Any -- python PurePath to parent directory. See: https://docs...
31ae6cc161c292a61ce9ab0eea11b05ff532ae31
74,321
def drop_and_rearrange_columns( dataframe: pd.DataFrame, columns_to_keep: list[str] ) -> pd.DataFrame: """Drops and rearranges columns of a Pandas DataFrame. Args: dataframe (pd.DataFrame): Dataframe to operate on. columns_to_keep (list[str]): List of columns to keep in the order wanted. ...
c6b797270a7ab198bbcd03c88cedf8d75268db55
74,322
import re def get_regions_from_regex(logger, regex, region_list): """ search the regions list using regular expressions """ logger.debug("getting regions that match: %s", regex) regex_pattern = re.compile("^" + regex.replace("*", ".*") + "$") filtered_regions = filter(lambda x: regex_pattern.match(x["...
d774ef94ef3bad86972ade724ac528bb745a075d
74,323
def _hitgroup_content_to_sorl_dt(hg): """Convert given HitGroupContent object into valid solr dictionary, that can be added to index using at least pysolr.Solr connection """ doc = { 'group_id': hg.group_id, 'requester_id': hg.requester_id, 'requester_name': hg.requester_name, ...
fa4395e67d2f00bf309a0e04c54272b03411caaa
74,324
def bias_variable(shape, verbose=False): """Creates a CPU variable with constant initialization. Adds summaries. Args: shape: list, the shape of the variable. verbose: if set add histograms. Returns: Bias variable tensor with shape=shape. """ with tf.device('/cpu:0'): with tf.name_scope('bia...
3d0a730d29ee22c231a3e393a654f5c8aed89bce
74,325
import random def title(random=random, *args, **kwargs): """ Return a title! >>> mock_random.seed(0) >>> title(random=mock_random) 'captain' >>> title(random=mock_random, capitalize=True) 'Lieutenant' >>> title(random=mock_random, slugify=True) 'leftenant' """ return rando...
bb379bc6fe6cfb905017bde2f79d68f341757674
74,326
import grp def to_gid(name): """Return a gid, given a group name If the group name is unknown, raises a ValueError. """ if isinstance(name, int): try: grp.getgrgid(name) return name except KeyError: raise ValueError("No such group: %r" % name) ...
aa8a97aff1ef18b425139e4a2e1870d3517d6782
74,327
def tree_price(ap): """ Computes the price-dividend ratio of the Lucas tree. Parameters ---------- ap: AssetPriceModel An instance of AssetPriceModel containing primitives Returns ------- v : array_like(float) Lucas tree price-dividend ratio """ # == Simplify n...
54dc847f5ac91d9b74db22f7eed399e6fc5fad75
74,328
def initialize_clock(): # pragma: no cover """ Initialise le temps. Returns ------- Clock Une horloge """ return pygame.time.Clock()
2e57cdc3d2e0566a498c1517fe8e32a1972ea43d
74,329
def get_hdf_data(name, path): """Get data from a HDF5 file assuming there is replicates of data branching from the top-level nodes """ # First locate the dataset in the first result, # then grab that data for every run. hdf = h5py.File(name, 'r') return [hdf[node + path].value for node...
cb158becfba9bcc3d565f91ed0807b2a12a32853
74,330
def permutation(geo, ref_geo, thresh=1e-4): """ determine the permutation of one geometry that reproduces another (If there isn't one -- the geometries are not aligned, return None) """ natms = count(geo) syms = symbols(geo) xyzs = coordinates(geo) perm_idxs = [None] * natms for idx, (...
18dd8cd74cf015d7585810b674ca03259a4f8e63
74,331
from datetime import datetime def check_realistic_birth_date(date): """ Function to check if the inserted date of birth is not futurist. """ date = date.split("/") today = datetime.strftime(datetime.now(), "%d/%m/%Y").split("/") logic_1 = ( int(date[0]) > int(today[0]) and # Day ...
3b92d322881b9f4dafac6678a1627cec90c8cd50
74,332
import numpy def _generate_segments(im_orig, scale, sigma, min_size): """ segment smallest regions by the algorithm of Felzenswalb and Huttenlocher """ # open the Image im_mask = skimage.segmentation.felzenszwalb( skimage.util.img_as_float(im_orig), scale=scale, sigma=sigma, ...
83e32babd83f5a17353357094b1c986d7bbec635
74,333
from datetime import datetime def get_month_data_range(months_ago=1, include_this_month=False): """ A method that generates a list of dictionaries that describe any given amount of monthly data. """ today = datetime.datetime.now().today() dates_ = [] if include_this_month: # get ne...
8122f759d807dd687bb18e2c013cf32310023c6a
74,334
def getBoundingBoxCoordinates(box, height, width): """ returns coordinates of bounding box in pixels :param box: a Tensor returned of tensorflow object detection prediction of 1 set of ymin, xmin, ymax, xmax :param height: height of image :param width: width of image :return: ymin, xmin, ymax, x...
14f6e94b68d62893d3235c73c0c4943e6edaf4d2
74,335
def deletable_group(request, onefs_client): """Get the name of an existing group that it is ok to delete.""" return _deletable_group(request, onefs_client)
5f9d1533c86b8b153e060e3fabf34c7fd786b735
74,336
def calc_dh(eta): """Calculate the first derivative of the interpolation function Args: eta: the phase field Returns: the value of dh """ return 30 * eta ** 2 * (eta - 1) ** 2
557f3d932c0b380ad291f2af081d1ebe8fcd5baf
74,337
def parse_requirements(): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open('requirements.txt')) return [line for line in lineiter if line and not line.startswith("#")]
8cc21bd86d207338c2e97701e6a42d5ff8edd0ad
74,338
def scale_by_stddev(decay=0.9, eps=1e-8): """Rescale updates by the root of the centered exp. moving average of squares. References: [Hinton](www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) Args: decay: decay rate for the exponentially weighted average of squared grads. eps: term a...
5fb1cef48fd6486f6388e75ed4759726811ca1b4
74,339
import math def WassersteinMinFlowL1(h1, h2): """ Find the Wasserstein distance using a cutting plane on the dual """ def ID(x,y): return x*s+y n = len(h1) s = int(np.sqrt(n)) print(n,s) # Build model m = Model() #m.setParam(GRB.Param.TimeLimit, 300) #m.setParam(GRB.Param....
a87031f92a20ff671162d9b11d9da15712c66d79
74,340
def create_mesh_object_copies_with_applied_modifiers(scene): """ Creates copies of all mesh objects in the specified scene and applies then the edge split and mirror modifier on the copy. Afterwards it makes the mesh calculate triangle data via mesh.update(calc_tessface=True) """ non_empty_mesh_objects = ...
a3c1ddd939f3f513d4007346cacc0809adf95bc7
74,341
def compute_all_seclists(project_name): """ Make a list of all seclists for instances in project """ data_type = "instances" sections = get_section_data(project_name, data_type) seclists = [] for section in sections: instance_types = get_config_item(project_nam...
31ad8aee019ea10f986c5dd5a619e8ac7e23da09
74,342
def pol2cart(lon, lat): """ Utility function to convert longitude,latitude on a unit sphere to cartesian co-ordinates. """ x = np.cos(lat)*np.cos(lon) y = np.cos(lat)*np.sin(lon) z = np.sin(lat) return np.array([x,y,z])
74b760ebe126b022bd9b34a136f5c8fc2edea89c
74,343
def mod_padding_symmetric(image, factor=64): """Padding the image to be divided by factor.""" height, width = image.shape[0], image.shape[1] height_pad, width_pad = ((height + factor) // factor) * factor, ( (width + factor) // factor) * factor padh = height_pad - height if height % factor != 0 else 0 pa...
b08cc6285dee8bc99c979b081c88f2d4a3f77e06
74,344
def parse_http_response(data): """ Parses HTTP response data into a tuple in the form (cmd, headers). @param data: HTTP response data @type data: string @return: (cmd, headers) for the given data @rtype: tuple """ header, payload = data.split('\r\n\r\n') lines = header.split('\r\n') ...
da4680acd9dd429fdbffbe6927586ba23256286e
74,345
def filter_not_in(c, values, inclusion=None, exclusion=None): """Returns the entries of the specified collection whose values are not in the specified values for all the specified keys.""" values = to_set(values) return filter_not_with(c, lambda v: v in values, inclusion=inclusion, exclusion=exclusion)
677d850ccd2685d63b37b27fa679c821da64d97e
74,346
def get_project_names(): """Searches for Tracker projects at the Tracker home configuration file Returns: <list> -- List of project names """ trackerfile = TrackerFile() projects = trackerfile.get("projects", {}) project_names = [] if projects: for d in projects: ...
adf7a35a567d5cded2aa9100bb65ffa5f8fee2a4
74,347
def AircraftTraj(Nsim, npoint, Time=20, v=500/60, ra=0.25, rc=1/57, sigmac=1): """ Outputs N Aircraft trajectories in form of tuple Xa, Xc from point (0,0) horizontally la position along-track et cross-track. Simulation de N trajectoires d'avion par une discretisation du processus Gaussienn en n...
6829cee95e0b278dc131dd37719143c9dc072e42
74,348
import random from datetime import date from wbia.detecttools.pypascalmarkup import PascalVOC_Markup_Annotation import datetime def export_to_xml( ibs, species_list, species_mapping=None, offset='auto', enforce_viewpoint=False, target_size=900, purge=False, use_maximum_linear_dimension...
9fd9c2c2e224482d8870795c3690c32fbf334cc2
74,349
def setlocation(bot, trigger): """ Sets a nick's default city location """ if not trigger.group(2): bot.reply('Give me a location, like "Washington, DC" or "London".') return NOLIMIT api = bot.memory['owm']['api'] location_lookup = trigger.group(2) location_group_list = lookup_locat...
2d70de406319e10fcfa7c69791f7cc1c4aaa6aa6
74,350
from typing import Dict from typing import Tuple from typing import Union def sum_of_interaction_operator_gate_generators( n_modes: int, gates: Dict[Tuple[int, ...], Union[float, cirq.Gate]], ) -> openfermion.InteractionOperator: """The interaction operator that is the sum of the generators of the...
988d4d4d4285282eb3dfe60cb6ff670d51490adc
74,351
from typing import OrderedDict def remove_layers(summary): """ This is called when print_major_layers_only is True. Removes layers with no weights, like activation layers. Retain layers that manipulate shapes, otherwise reading the model summary can be confusing. """ new_summary =...
772dcc3fcfbe3828e84585c750e9384b0bcc08e6
74,352
def reasonability(x, val, mode): """ Checks to see if an array is within a set of bounds. """ if mode == 'high': return np.all(x <= val) if mode == 'low': return np.all(x >= val)
74d6c6388fc5427795c72ade2b423b113277b7cd
74,353
import os def to_module_path(path: str, proj_path: str=project_path) -> str: """ Convert the given file-system path to a python module path :param path: The full file or directory path of the path which is being converted to a module path :param proj_path: The project path that contains the file :retu...
6e63735539d6c7092f2312dd0e6b16c14432fe7e
74,354
def split_train_test(df, user_size, exer_size, test_size=0.2, time_order=False): """Split a dataset into `train_user_list` and `test_user_list`. Because it needs `user_list` for splitting dataset as `time_order` is set, Returning `user_list` data structure will be a good choice.""" # TODO: Handle duplic...
498c4ac48c018f8f4df72bb06b064ccc65fb2f30
74,355
def topological_ordering(A): """Return a topological ordering for the DAG with adjacency matrix A, using Kahn's 1962 algorithm. Raises a ValueError exception if the given adjacency does not correspond to a DAG. Parameters ---------- A: np.array the adjacency matrix of the graph, wh...
f5ea21b12e8a91308ff680e3bec3fef7ae4ca90c
74,356
def dhcp_relay_detailed_show(dut, interface="", family="ipv4", cli_type=""): """ API to show the DHCP relay detailed output :param dut: :return: """ cli_type = st.get_ui_type(dut, cli_type=cli_type) if cli_type in ['click', 'klish']: ip_val = "ip" if family == "ipv4" else "ipv6" ...
f85839d01c404ddfd9b2c9cc436acb6a54f32415
74,357
def project_3(request): """Third project page""" return render_to_response('frontend/project-3.html', locals())
3ecf54afb5f74be63a01c5c2b0aea54634e0360d
74,358
import logging def validateFiles(input_file, chrom_sizes_file_name, file_type, options=None): """ Call validateFiles on input_file, using chrom_sizes_file_name and file_type :param input_file: :param chrom_sizes_file_name: :param file_type: :return: """ array_call = ['validateFile...
bc52e336bd8116e58b71178ddf86c2979848b7dc
74,359
def calc_cum_abs_deriv(y, sigma=10, order=1, axis=-1): """ Calculates the curvature of the spike count vector `y`""" return np.cumsum(np.abs(gaussian_filter1d(y, sigma=sigma, order=order, axis=axis)), axis=axis)
85dea0d95b4ca41a87f16a8316d24dced89b9155
74,360
def isChildUri(parentUri, childUri): """Return True, if childUri is a child of parentUri. This function accounts for the fact that '/a/b/c' and 'a/b/c/' are children of '/a/b' (and also of '/a/b/'). Note that '/a/b/cd' is NOT a child of 'a/b/c'. """ return parentUri and childUri and childU...
a28a386c38a4d6722f6b7c8bcbeafb8092dbbe77
74,361
from typing import Any def outer(a: Any, b: Any) -> Any: """ Compute the outer product of *a* and *b* while allowing either of them to be an :class:`ArrayContainer`. Tweaks the behavior of :func:`numpy.outer` to return a lower-dimensional object if either/both of *a* and *b* are scalars (whereas ...
9fa62a06e11197f669cd68b20a4cbf6f1743b19d
74,362
def setup_users_eligible_for_object(*perms): """Post-save signal receiver producer to setup a new object Since this is the first time permissions are being setup, the `bulk_create` manager method is used for performance. """ @transaction.commit_on_success @wraps(setup_users_eligible_for_object...
307220cbd24a74d2e5a212c4119486895bb8e742
74,363
def verify_sorted(countykey_list): """! verify that read countykey_list is sorted @param countykey_list List of county regional keys """ countykey_list_is_sorted = np.all(np.array( countykey_list[:-1]) <= np.array(countykey_list[1:])) # this checks if it is sorted if countykey_list_is_sorte...
63898815303629aa9402f023c68d1d2cb4a22cdf
74,364
def _parseUnit(unitString): """string -> multiplier returns how many of the base SI units are equivalent to this unit """ [num, den, *junk] = unitString.split("/") + ["1", "1"] # split string into numerator and denominator [num, den] = [x.split("*") for x in [num, den]] # split by term [num, den...
6c952a47a40297797bf64496c4a6bc7ba0af8c95
74,365
def list_alias(): """ List all registered aliases. Returns: An array of dictionary containing the alias and the command that it points to. """ alias_table = get_alias_table() output = [] for alias in alias_table.sections(): if alias_table.has_option(alias, 'command'): ...
e0548b3c539bc5dd2bd5903282ab8a4a098f4f87
74,366
from re import S def chop_parts(value: TMP_RES, prec: int) -> TMP_RES: """ Chop off tiny real or complex parts. """ if value is S.ComplexInfinity: return value re, im, re_acc, im_acc = value # Method 1: chop based on absolute value if re and re not in _infs_nan and (fastlog(re) < -...
62836413ad0771edaf8414ec80b8f374b65157c5
74,367
def pearson_r(x, y): """Compute Pearson correlation coefficient between two arrays.""" # Compute correlation matrix: corr_mat corr_mat = np.corrcoef(x, y) # Return entry [0,1] return corr_mat[0,1]
e872d48eb5648cbd35eb0e38ad44427e93fae897
74,368
from typing import List from typing import Tuple def sampling_expectation(hamiltonians: List[PauliSum], bitstrings: List[np.array]) -> Tuple: """Mapped wrapper around ``sampling_expectation_z_base``. A function that computes expectation values of a list of hamiltonians w.r.t a li...
b034a8cbef798f0ce3cf8663ca7d252a8b24db1d
74,369
def size(b): """ Returns the size in bytes of the first netstring in the provided bytes object. WARNING: This function doesn't check for netstring validity. THROWS: ValueError if cannot determine size """ try: slen = b[:b.find(b':')].decode('ascii') return 2 + len(slen) + int(slen) e...
2b50a555e29c6d7cbdc419d3dfb336d60f907d0c
74,370
def cbcloud_api_mock(monkeypatch, cbc_cloud_api): """Mocks CBCloudAPI for unit tests""" cbcloud_api_mock = CBCloudAPIMock(monkeypatch, cbc_cloud_api) hashes = [ "405f03534be8b45185695f68deb47d4daf04dcd6df9d351ca6831d3721b1efc4", "0995f71c34f613207bc39ed4fcc1bbbee396a543fa1739656f7ddf7041930...
953a19d162f4b8926211803c7ea1b84ee2ccbad2
74,371
from unittest.mock import Mock def mock_executor(scheduler, debug=False, code_package=False): """ Returns an AWSGlueExecutor with AWS API mocks. """ s3_scratch_prefix = "s3://example-bucket/redun/" config = Config( { "glue": { "s3_scratch": s3_scratch_prefix, ...
951ef40970c6cd4d8e279f21c67c34a6f62627b3
74,372
from typing import Optional from typing import Union from typing import Tuple import numpy import io def _tile( z: int, x: int, y: int, scale: int = 1, ext: str = None, url: str = None, indexes: Optional[Union[str, Tuple]] = None, expr: Optional[str] = None, nodata: Optional[Union[...
955ad4e662e2d577fbf033538a6e0126c998e3b5
74,373
import yaml import os def parse_config(config_file): """ Parses config file for usage in model.py and find_groups_nest """ with open(config_file, 'r') as ymlfile: cfg = yaml.load(ymlfile) base = os.path.basename(config_file) base_and_extless = os.path.splitext(base)[0] cfg['simulat...
5156fc538f07adcb5174c9090b0206c4be3b7ec7
74,374
def dnlsim(system, u, t=None, x0=None): """Simulate output of a discrete-time nonlinear system. Calculate the output and the states of a nonlinear state-space model. x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t)) y(t) = C x(t) + D u(t) + F eta(x(t),u(t)) where zeta and eta are polynomials w...
d93646167f8fc99a83bf23eb0fb6e7a27d06333e
74,375
def person_search(value, type=None): """ Search for People & Groups which match a search term """ # Shortcuts groups = s3db.pr_group persons = s3db.pr_person items = [] # We want to do case-insensitive searches # (default anyway on MySQL/SQLite, but not PostgreSQL) value = value.lower...
a67e7f300aa40389f5e3445d4df45ce30cbefbd0
74,376
import torch def get_output_size(model, input_shape=(1, 3, 224, 224), device="cpu", dtype='float32'): """ Returns the shape of the convolutional features in output to the model. Parameters ---------- model pytorch model, neural network model. input_shape: tuple of int, shape o...
f9c4e79e2c38a424c723cfed6fc73fc63ddc3142
74,377
def checkPrecision(hp,pCentroids,pMeasure,optimisationIteration,distrib,m,directions,precisionCheck,structureCheck,newMeasure,lastMeasure,indexMin): """Deprecated - might not work""" if not precisionCheck: if newMeasure > lastMeasure : print('Error: new Distortion bigger than at previous ite...
cb82a552b18f77f51553ceef41797a90496bc288
74,378
import argparse def parse_args(debug=False): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Data Preprocess') # Required parser.add_argument('--hlgt_path', required=True) parser.add_argument('--hlt_path', required=True) parser.add_argument('--pt_path', req...
834fa422ba767a48e37d1d4daa4ed294d1ed6bd0
74,379
from typing import Union def mwdx(candles: np.ndarray, factor: float = 0.2, source_type: str = "close", sequential: bool = False) -> Union[ float, np.ndarray]: """ MWDX Average :param candles: np.ndarray :param factor: float - default: 0.2 :param source_type: str - default: "close" :param...
955d062ef364ab2d577f9789ba8e07a4cc0c1264
74,380
def str_function(connectable) -> str: """__str__ function for OutputBase and InputBase.""" infos = [] if connectable.owner: infos.append('owner: %s' % connectable.owner) if connectable.connected: infos.append('connected') else: infos.append('not connected') return '%s(%...
5ed2ba8575314c0fdf9046988f3977ab262ff0af
74,381
def find_subtracted_fits_fieldprojectidccd( dirlist, field, projectid, ccd, subtracttype='reverse', photreftype='oneframe', kernelspec='b/4;i/4;d=4/4', nworkers=8, maxworkertasks=1000): """This searches for all subtracted FITS files matching th...
78df223605e304569ace3535c0c0a26fa7d46468
74,382
def cinv(z): """Computes the reciprocal of a complex `z`. Args: z (:class:`~taichi.math.vec2`): The input. Example:: >>> @ti.kernel >>> def test(): >>> z = ti.math.vec2(1, 1) >>> w = ti.math.cinv(z) # [0.5, -0.5] Returns: :class:`~taichi.math....
a91147855999a60d8252e558eff47e0f17f2403e
74,383
from scipy.ndimage.interpolation import affine_transform import numpy def scale_and_rotate_image(im, angle=0.0, scale=None, order=5): """ Scale and then rotate and image in x, y axes Applies scale then rotates :param im: Image :param angle: Angle in radians :param scale: Scale [scale_x, scale_y]...
ab91bd3059add848a77aec225227c8a646c06912
74,384
def _in_exception_handler(identifier, on_conflict): """Returns a matcher for a node in the nearest ancestor `except` & binds `identifier`. Args: identifier: Name of variable to bind the identifier in the nearest ancestor exception handler to on_conflict: BindConflict strategy for binding the identifi...
cd5b9192b4e0ee140c24f1bc54931b7be5adb3d8
74,385
def reduced(f, G, *gens, **args): """ Reduces a polynomial ``f`` modulo a set of polynomials ``G``. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*g_1 + ... + q_n*g_n + r``, w...
e2972af73c4d067458aa1e15017393d898d271e3
74,386
import requests def save_running_config(host: str=HOST, username: str=USERNAME, password: str=PASSWORD, port: str=PORT) -> tuple: """GET RESTCONF function to save current running config Args: host (str): hostname or ip of device username (str): API username for authent...
6398c154a480b9616c433d90b4c6e4ec58be4fb9
74,387
def _delta_derivative_double_gamma_hrf(delta, t_r=1.0, dur=60.0, onset=0.0): """ Double Gamma HRF model. Parameters ---------- delta : float, temporal dilation to pilot the HRF inflation t_r : float, Time of Repetition, fMRI acquisition parameter, the temporal resolution dur : float, (d...
a39fd9ecb1e01d4e779eb7be5a481d1df5514c0e
74,388
def archive_thumbnails(request, inst, proposal): """Generate the page listing all archived images in the database for a certain proposal Parameters ---------- request : HttpRequest object Incoming request from the webpage inst : str Name of JWST instrument proposal : str ...
eaddad50cf2395d6919f29f800b5b3cb24c8b8c7
74,389
from typing import List import os import re def find_all_matched_files(directory: str, patternStr: str) -> List[str]: """ List the paths of files that match patternStr under the specified directory. """ if patternStr == "*.*": pattern = "\.*.*$" else: pattern = patternStr.replace("...
362d74d199700a4c1934b1b6aad0423d327377e4
74,390
def resize_to_make_it_fit(images, output_shape=(50, 50)): """Resizes the images to a given shape. """ max_time = max(images[i].shape[0] for i in xrange(len(images))) final_shape = (len(images),max_time) + output_shape result = np.zeros(final_shape, dtype="float32") volume_change = [] #resul...
87853984b3dd0e8df70cead07730e269f776f9d3
74,391
import ssl def get_ssl_context(): """Create an SSL context.""" context = ssl.SSLContext() context.verify_mode = ssl.CERT_NONE return context
182b18996632f335b1cdf4d73e8dd502881b0f73
74,392
def annotate_bmp( img, ellipses=None, old_pts=None, thickness=params.ellipse_thickness, windowsize=None, zoomaxes=None ): """Draw stuff on image.""" # draw ellipses (bmp,resize,img_size) = draw_ellipses_bmp( img, ellipses, thickness=thickness, windowsize=windo...
4935e8a34b26d131867e0c1203de43f0a8d87dc3
74,393
def b36encode(number: int) -> str: """Convert the number to base36.""" alphabet, base36 = ["0123456789abcdefghijklmnopqrstuvwxyz", ""] while number: number, i = divmod(number, 36) base36 = alphabet[i] + base36 return base36 or alphabet[0]
54046b8b0246eac6f08f7dea8b918f512f5e23d8
74,394
def change_id(id, num_samples=7): """ automatically change object id, mapping given class to a class with similar size returns list of changed ids for object replacement, of max size [num_samples] """ obj_pool = [75, 58, 127, 165, 159, 129, 116, 57, 35, 3, 20, 6, 9] # animals, people, chairs, etc vehicle_po...
141f75cef738b8ce140121609e2003bf1e2fd49d
74,395
def split_order_book(order_book_id: str): """ 对合约拆分成品种和年份俩个部分 :param order_book_id: :return: """ return order_book_id[:-4], order_book_id[-4:]
4692e95eb814de50f9effe7ed289f94712e265d6
74,396
def pro_avfid_superoperator_compsubspace_phasecorrected(U,L1,phases): """ Average process (gate) fidelity in the qubit computational subspace for two qutrits Leakage has to be taken into account, see Woods & Gambetta The phase is corrected with Z rotations considering both transmons as qubits """ ...
8dc731c8bd18133497b08b8a6dc0ccc68df8e4ac
74,397
from typing import Tuple from typing import List import base64 def prepare_hw_encryption_attrs(hw_session: HwSessionInfo, label: str) -> \ Tuple[int, int, List[int], bytes, bytes, bytes]: """ :param hw_session: :param label: :return: 0: protocol id 1: hw type id (see below) ...
8a868c72d9a0960cd918b6b345dfef114875b0cd
74,398
def find_list(item_list, func, with_index=False): """ Find an object from the list that matches the conditions :param with_index: :param item_list: :param func: :return: """ if with_index is True: return _find_list_with_index(item_list, func) for item in item_list: i...
b09762da3d8afa246c715153aecb9dac51342a81
74,399