content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_scheduler_plugin(name): """Return a scheduler plugin :param str name: The name of the scheduler plugin. :rtype: SchedulerPlugin """ if _SCHEDULER_PLUGINS is None: raise SchedulerPluginError("No scheduler plugins loaded.") if name not in _SCHEDULER_PLUGINS: raise Schedul...
948f0a9215c053ea0cf5e6905dd8cfbcef4bf9f4
48,500
def ferret_custom_axes(id): """ Custom axis information for stats_probplot_values Ferret PyEF """ size = 1 for axis in ( pyferret.X_AXIS, pyferret.Y_AXIS, pyferret.Z_AXIS, pyferret.T_AXIS, pyferret.E_AXIS, pyferret.F_AXIS ): axis_info = pyferret.get_axis_info(id, pyferret....
8b6624008ef5d1f3e8a5462f10fb5c4419c3d58c
48,501
def get_service_bus_namespace(name=None,resource_group_name=None,opts=None): """ Use this data source to access information about an existing ServiceBus Namespace. :param str name: Specifies the name of the ServiceBus Namespace. :param str resource_group_name: Specifies the name of the Resource Grou...
656687d571e39771921a15ef445ba7689bb82b3f
48,502
def extract_default_context(context, response, url): """ Gets default information if not all info is retrieved """ context = Context() if not context else context if not context.url or not context.permalink: current_app.logger.debug('getting default url info: %s', url) context.url = con...
79944fa6a0f9c6c484fcb1688b323740f763e6ef
48,503
def get_raasi(raagam_index=None): """ Get raasi of the specified raagam index @param raagam_index:ID of the raaga @return: raasi """ if raagam_index==None: raagam_index=settings.RAAGA_INDEX return _get_raaga_attribute("Raasi",raagam_index)
1f8b43f382ac8212526808aa459bd0e8d6461a11
48,504
from datetime import datetime import os def make_work_dir(args): """Make directory to store outputs, logs, and intermediate data. If not provided, create a timestamped directory in current working directory. """ work_dir = args.work_dir if not work_dir: timestamp = datetime.datetime....
bd7ae24291655235a8079c7751815785d6253421
48,505
def _player_id(player): """Lookup and return the NHL API player ID for an idividual player""" players = _all_player_ids() player_id = players.get(player) if not player: raise JockBotNHLException(f"Player Not Found {player}") return player_id
06a23a11dbd8e27c42107136f33853337f14b431
48,506
def mk_minus(ctx, x): """ mk_minus(Int_ctx ctx, Int_net x) -> Int_net Parameters ---------- ctx: Int_ctx x: Int_net """ return _api.mk_minus(ctx, x)
0cf8ec3e9e4f17aed8685023a55dde4e9d85b402
48,507
def cred_secret_issue_proof(params, num_privs, num_pubs): """ The proof that the mixed public / private credential issuing is correct """ G, _, _, _ = params n = num_privs + num_pubs # Contruct the proof zk = ZKProof(G) ## The variables bCx0 = zk.get(Gen, "bCx_0") u, g, h, Cx0, pub = ...
81ede9c55280376024364b9eb7b74fafda945786
48,508
import os def _is_unc_path(some_path) -> bool: """True if path starts with 2 backward (or forward, due to python path hacking) slashes.""" return ( len(some_path) > 1 and some_path[0] == some_path[1] and some_path[0] in (os.sep, os.altsep) )
a2cd156bf5367cc73673ad86505aa094da3fae86
48,509
def makePlane(w, l): """ 4 points make a plane about the origin of size w, l """ return [mathutils.Vector(x) for x in [(-w/2, -l/2, 0), (-w/2, l/2, 0), (w/2, l/2, 0), (w/2, -l/2, 0)]]
0b80b7a560d444167f78f97719807e9119b7bd9b
48,510
def calculate_gravity(a: Body3D, b: Body3D): """ Calculate the acceleration of body A due to the force of gravity applied by body B. """ def gravity(pos_a, pos_b): if pos_a < pos_b: return 1 elif pos_a > pos_b: return -1 else: return 0 retu...
a31a73b3299a700763a7dd03a2ff35dbe5ac400e
48,511
def _get_first_window(split_text): """Get first :const:`~gensim.parsing.keywords.WINDOW_SIZE` tokens from given `split_text`. Parameters ---------- split_text : list of str Splitted text. Returns ------- list of str First :const:`~gensim.parsing.keywords.WINDOW_SIZE` tokens...
3a556236ce9c59ba906c94f7a48f78639e55f09c
48,512
def scope_access_level(app, uid, wid, scid): """Check the access level of the given player to the given world and scope. If the scope is global, the world creator has creator access, everybody else is a visitor. If the scope is personal, the owner has creator access. (This is actually in the sco...
1e1828daa9608c028651a986fca1ecc741a41b72
48,513
def member_to_badge_proximity(fileobject, time_bins_size='1min', tz='US/Eastern'): """Creates a member-to-badge proximity DataFrame from a proximity data file. Parameters ---------- fileobject : file or iterable list of str The proximity data, as an iterable of JSON strings. time_b...
01b730c158714e8e071c97bd0f7e3cdb2d6e407b
48,514
from .. import __producer_version__ def get_producer_version(): """ Internal helper function to return the producer version """ return __producer_version__
7f9a8df4269feba968ebc945098c33f721ee9d8e
48,515
def consensus_tree() -> str: """Gets the consensus tree page. :return: The consensus tree page. """ # Set the default options if "analyoption" not in session: session["analyoption"] = constants.DEFAULT_ANALYZE_OPTIONS if "bctoption" not in session: session["bctoption"] = constan...
401bae7670836eb79962eeccb45a063012f2c69b
48,516
def fitgaussian(data): """Returns (height, x, y, width_x, width_y) the gaussian parameters of a 2D distribution found by a fit""" xx, yy, dx, dy, angle = fastfit.d4s(data) # For some reason x and y are exchanged params = [np.max(data), yy, xx, dy/4, dx/4, -angle, np.min(data)] errorfunction = la...
4b995cec58530d57644f9f0e01f100cb89279ecd
48,517
def mapped_state(state): """ Mapped a given state into the state as neural network input, insert trivial vehicles until vehs_num = 18 :param state: given state :return: new state """ num_diff = 18 - len(state) for i in range(num_diff): state.append([0, 0, 0, 0, 0, 2]) return sta...
1732565f6ef307fb67c92f2adac9c81591acf4c5
48,518
import os import pickle def load_wm_model_from_file(model, filepath): """ Loads the data required for the usnx embed_model function """ MODEL_SUFFIX, HISTORY_SUFFIX, TRIGGER_SUFFIX = "MODEL", "HISTORY", "TRIGGER.npz" if filepath is not None: filepath = os.getcwd()[0:os.getcwd( ).rfind...
db9568a23c481e3110d09b1d0837f2a9a4117f00
48,519
def uniform_non_negative_integers_with_sum(count, sum_): """Returns list of size `count` of integers >= 0, summing to `sum_`.""" positive = uniform_positive_integers_with_sum(count, sum_ + count) return [i - 1 for i in positive]
4c080fec7627a61c0dea16ba9aa08b9664b75c73
48,520
from .profiles import display_profile_rc def cms_create_display_profile() -> qc3const.PyCapsule: """Artificial functionality. The function emulates built-in display profile reading profile resource attached to the package. Returns a handle to lcms built-in display profile wrapped as a Python object. ...
0a064603ad5a1c509fae82b219b3bf0977a3f837
48,521
import nomenclator.utilities def mocked_has_multiple_views(mocker): """Return mocked 'nomenclator.utilities.has_multiple_views' function.""" return mocker.patch.object(nomenclator.utilities, "has_multiple_views", )
be763e2c76b30a2ad82325483c3456b336f8f5f2
48,522
def pre_post_process_layer(prev_out, out, process_cmd, dropout_rate=0., epsilon=1e-12, name=''): """ Add residual connection, layer normalization and droput to the out tensor ...
264c24e6300d8322fb24496b33d255c14337fb2f
48,523
from typing import Optional import os def lookup_file_from_mixcli_userhome(filename: str) -> Optional[str]: """ Try to lookup a file with given name, if environment variable for MixCli user home is present, is a valid dir, and if a file with given name is found in that dir. :param filename: Name of e...
d732d0143eefffbacc7c7c15a4c2c8868bbef73e
48,524
import sys def get_dns_records(domain, rdtype, nameserver): """Retrieves the DNS records matching the name and type and returns a list of records""" records = [] try: dns_resolver = dns.resolver.Resolver() dns_resolver.nameservers = [nameserver] dns_response = dns_resolver.query(do...
122cd91c88a433c60b849cd47d143e1c5d3c030b
48,525
def create_renderer(window, attach_callbacks=True): """ This is a helper function that wraps the appropriate version of the Pyglet renderer class, based on the version of pyglet being used. """ # Determine the context version # Pyglet < 2.0 has issues with ProgrammablePipeline even when the cont...
db588ad1365464e8101cbfaff3e0fa586ce7c67b
48,526
import sys def _ffmpeg_fmt(dtype): """ Convert numpy dtypes to format strings understood by ffmpeg. Parameters ---------- dtype : numpy dtype Data type to be converted. Returns ------- str ffmpeg format string. """ # convert dtype to sample type dtype = n...
790edb881ef8c31a72da4ea3caf7badafa1b492c
48,527
def pct(n, d, mul=100.0, **kwargs): """ Percentage by the same logic. You can override mul and nan if you like. """ return rat(n, d, mul=mul, **kwargs)
023b765c4a76843992a87e7f055ada5c32903aad
48,528
def findIKhandles(): """ Returns a list of all IK handles in the scene """ return mc.ls(type="ikHandle")
4c56380fb80f8201d34a5d47c264cf1972e22c11
48,529
def when_all(*desired_flags): """ Register the decorated function to run when all of ``desired_flags`` are active. Note that handlers whose conditions match are triggered at least once per hook invocation. For backwards compatibility, this decorator can pass arguments, but it is recommended to...
1e1b60d91924ff3ad206827611e796df52c3ccbb
48,530
from typing import Optional def ingest_dns_record_by_fqdn( neo4j_session: neo4j.Session, update_tag: int, fqdn: str, points_to_record: str, record_label: str, dns_node_additional_label: Optional[str] = None, ) -> None: """ Creates a :DNSRecord node in the graph from the given FQDN and performs DNS res...
89949fe77f1324116fecb21a826a00ebce334fa9
48,531
def detail_url(profile_id): """Return profile detail url""" return reverse('profile-detail', args=[profile_id])
641549d9a1f0d6183531b81ede83da455e458188
48,532
import os def fetch_result_csv_fp(dir): """ Find result CSV in dir. Currently just finds the first non-system file CSV in dir, assuming only one exists; more sophisticated checks need to be added. :param dir: directory to search in. :return: path to csv. """ csv = [os.path.join(dir, x) for x i...
70fe1a13f82412dd529daef604bb7edadab15dfe
48,533
def main() -> int: """Main code""" parser = _get_parser() args = parser.parse_args() spec_url = args.spec_url spec_file = args.spec_file enforce_defaults = args.enforce_defaults schema = _load_spec(spec_file, spec_url) validator = _create_validator(schema, enforce_defaults) file_p...
ef92b9e2ab99f6d75903c8d50993938147e5d065
48,534
from typing import Union from typing import Sequence import re def inis2dict(ini_paths: Union[str, Sequence[str]]) -> dict: """ Take one or more ini files and return a dict with configuration from all, interpolating bash-style variables ${VAR} or ${VAR:-DEFAULT}. :param ini_paths: path or paths to .i...
df31c79f09ebe1980bb270c59d58410d54773649
48,535
def run_empty_query(dataset_name: str): """Returns basic stats (group and row count, etc.) over the dataset. A GET request since no query is passed.""" query = {} should_stream = bool_request_arg('stream') return do_run_query(dataset_name, query, should_stream)
3c78b5266326c9a360be09cf666937c741444e07
48,536
import os def get_files(d, sites=None, exts=None): """Get list of files in the specified directory, optionally filtering by file extension(s)""" l = [] if type(exts) in (str, basestring): exts = [exts] for fname in os.listdir(d): file_ext = os.path.splitext(fname)[1].lower() if...
a38a08bc236c28c28794786056dbafaaeff21a85
48,537
import json def read_training_schema(): """Responsible for reading the schema from schema_training.json """ params=read_params() path = params['data_schemas']['training_schema'] with open(path) as f: schema=json.load(f) LengthOfDateStampInFile = schema['LengthOfDateStampInFile'] Le...
08b0938d86a9234591723dc6b092b25b2adfd88b
48,538
def propagate(w,b,X,Y): """ 实现前向传播的代价函数及反向传播的梯度 输入: w -- 权重,一个numpy数组,大小为(图片长度*图片高度*3,1) b -- 偏差,一个标量 X -- 训练数据,大小为(图片长度*图片高度*3,1) Y -- 真实“标签”向量,大小为(1,样本数量) 输出: cost -- 逻辑回归的负对数似然代价函数 dw -- 相对于w的损失梯度,因此与w的形状相同 db -- 相对于b的损失梯度,因此与b的形状相同 """ m = X.shape[1] #...
6c84f8fbff0992f29a50518d787cdcad2332d32f
48,539
def extend_segments(X_conv, X_cont, peaks, min_diff_trav, cqt_window, sr, bin_thresh_segment, perc_tail): """ The segments surfaced by the convolution have tails that fade to 0, we want the binarizing threshold to be lower for these tails than the rest of the array """ new_cont = X_cont.copy() a...
c0a5f6f379be96a80dd28cc944c14b3689004786
48,540
def minus(a, b, rm_na=False): """ show whats in list b which isn't in list a """ if rm_na: a=rm_na(a) b=rm_na(b) s = set(b) return [x for x in a if x not in b] #return list(set(a).difference(set(b)))
3c2074872f623b4e837005ab6407bd24ab2b164c
48,541
def moveeffect_059(score: int, move: Move, user: Pokemon, target: Pokemon, battle: AbstractBattle) -> int: """ Move Effect Name: Averages the user's and target's Defense/Special Defense. """ adef = user.base_stats.get("def", 0) aspd = user.base_stats.get("spd", 0) odef = target.base_stats.get(...
121417b863b0e0dd6f6ef0fe5c43a951828ddd17
48,542
import re def re_group(regexp, text): """search for regexp in text, return 1st group on match""" m = re.search(regexp, text) if m: return m.group(1)
107a0cca5cf0c303ec817e84db0d5238ca00115d
48,543
def adapt_field(field): """ Convert sql field name to application field """ if field in app_fields: adapted_field = app_fields[field] if adapted_field != '': return adapted_field return field
b4b76945e37a9ecca798d1a481a7048366e88080
48,544
def im_to_double(im): """ """ min_val = np.min(im.ravel()) max_val = np.max(im.ravel()) return (im.astype('float') - min_val) / (max_val - min_val)
306fc3a7ab582182d3c7f149fdd8592fd850f632
48,545
def dos_from_bands(bands, smearing, npoints): """ Compute DOS from bands :param bands: The `BandsData` to be used as input. :param smearing: Smearing width in eV :param npoints: Number of points """ bands_data = bands.get_bands(also_occupations=False, also_labels=False) _, weights = ban...
fdb04989332011196eb7e12790f5dc27c65b6053
48,546
import numpy def cubeellipse(theta, lam=0.6, gamma=1.0, s=4.0, r=1.0, h=1.2): """Create an RGB colormap from an input angle theta. Takes lam (a list of intensity values, from 0 to 1), gamma (a nonlinear weighting power), s (starting angle), r (number of revolutions around the circle), and h (a hue fac...
54b5c36c544e344c7235cc0969e8f974097faaa2
48,547
from typing import IO from typing import Any def load(f: IO[str]) -> Any: """YAML load data from stream Args: f (IO[str]): IO Stream with data Returns: Any: YAML Data """ yml = ruamel.yaml.YAML(typ="safe") return yml.load(f)
a28f64dbb71efc48e559cf4df80cdf436b3ba8a8
48,548
def substrings(a, b, n): """Return substrings of length n in both a and b""" a_substrings = set(substring_tokenize(a, n)) b_substrings = set(substring_tokenize(b, n)) return a_substrings & b_substrings
a0f089280616985606f1fa65333274b3e9a55094
48,549
def iteritems(dictionary): """Replacement to account for iteritems/items switch in Py3.""" if hasattr(dictionary, "iteritems"): return dictionary.iteritems() return dictionary.items()
591bba21a1026d2e9d380555623c8ca78d3ed466
48,550
def validate_testapps(apis, api_configs): """Ensures the chosen apis are valid, based on the config.""" if "all" in apis: return [key for key in api_configs] for api in apis: if api not in api_configs: raise RuntimeError("Testapp given as flag not found in config: %s" % api) return apis
4726ae4e28bb57e2fa812cd0fa3721d38ba1103a
48,551
def _encrypt_bhv(trace): """ 加密轨迹 :param trace: :return: """ with open('ysf_slider.js', 'rb') as f: js = f.read().decode() ctx = execjs.compile(js) return ctx.call('getCompress', trace)
6be3b7012b835ad6fd561c9fb377a87bbbb14b09
48,552
import copy def prune_basis(basis, use_copy=True): """ Removes primitives that have a zero coefficient, and removes duplicate shells This only finds EXACT duplicates, and is meant to be used after uncontracting If use_copy is True, the input basis set is not modified. """ if use_cop...
8847539ce717868e9383db52e39008bbae2882f0
48,553
def insert(node, data): """ Insert data in BST rooted at node if necessary, and return new root. Assume node is the root of a Binary Search Tree. @param BinaryTree node: root of a binary search tree. @param object data: data to insert into BST, if necessary. >>> b = BinaryTree(8) >>> b = ...
7f4afbdbf766f2e8aca20f23fc53ee7a909d876d
48,554
def read_version(other_file_name, filename): """Read the the current version or build of the app""" version = "" version = read_file(other_file_name, filename) if version: version = version.rstrip() if not version: version = "__UNKNOWN__" return version
5c462299e66b9c3272122488416a7c15f7df463a
48,555
def api_tag_list(): """Listing for all tags. """ tags = db.session.query(database.TagRecord).all() return _tags_response(tags)
ec7ae513546001bf64b2b3c486dfc42daacd5c8a
48,556
def load_file_as_str(file_path: str) -> str: """ Loads the file at a specificed path, returns an error otherwise :param file_path (str): The path to the file you want to load :return _file a str of the contents of the file """ _file = "" try: with open(file_path, "r") as fp:...
45eaa87ed0570f618d1eef2c5e05a06dea97b2dc
48,557
def add_variables(md, g, deadline: int, start, vertices_t, searchers=None): # TODO IMPORTANT change to allow for different zetas! """Create the variables for my optimization problem :param searchers: :param start: :param vertices_t: :param deadline """ # variables related to searcher po...
c48fbd78121600525ed203adb33a5f86bb3afa22
48,558
def _dol_to_lod(dol): """Convert a dict-of-lists into a list-of-dicts. Reverse transformation of :func:`_lod_to_dol()`. """ keys = list(dol.keys()) lod = [] for i in range(len(dol[keys[0]])): lod.append({k: v[i] for k, v in dol.items()}) return lod
9e8a98d2502797ae27cae88ab2a0ec7fda4aff34
48,559
def infomap(adata: AnnData, basis: str = "umap", color: str = "infomap", *args, **kwargs): """\ Scatter plot for infomap community detection in selected basis. Parameters ---------- adata: :class:`~anndata.AnnData` an Annodata object. %(scatters.parameters.no_adata|basis)s ...
eec92a19e93c080137aba2648d96c30ed9ba72df
48,560
import mss.tools def partscreen(x, y, top, left, debug_mode=False, monitor_resolution=None): """ take screeenshot for a part of the screen to find some part of the image """ global partImg debug("entered screenpart") with mss.mss() as sct: monitor = {"top": top, "left": left, "width":...
e2b08a714669734da6d4f3e708271fd97a439876
48,561
def get_base_complex_data(model, complex_id): """If a complex is modified in a metabolic reaction it will not have a formation reaction associated with it. This function returns the complex data of the "base" complex, which will have the subunit stoichiometry of that complex""" # First try unmodifi...
c91841798c11b6e867130c7d6128756492e738e3
48,562
import os import re def _CheckLGTMsForPublicAPI(input_api, output_api): """Check LGTMs for public API changes. For public API files make sure there is an LGTM from the list of owners in PUBLIC_API_OWNERS. """ results = [] requires_owner_check = False for affected_file in input_api.AffectedFiles(): ...
b53ef351b7cb93ace1d38301fbcf22dff2918e38
48,563
def update_content(content_id): """ **Update Information of a Specific Content Record** This function allows user to update a specific content information through their content_id. :param content_id: id of the content :type content_id: int :return: content information updat...
8a83cd349e3b1030eaeac967cc0804ee51d8ffb6
48,564
def compute_winner_index(interactions, game=None): """Returns the index of the winner of the Match""" scores = compute_final_score(interactions, game) if scores is not None: if scores[0] == scores[1]: return False # No winner return max([0, 1], key=lambda i: scores[i]) retu...
7cd5e0cb357ee3bc0505e6d5467ed651d097c08e
48,565
def get_shard_index(shard_name): """Returns tuple of shard index, num_shards based on a shard name.""" if shard_name in ['0', '-']: return 0, 1 shard_begin, shard_end = shard_name.split('-') num_bytes_used = max(len(shard_begin), len(shard_end)) / 2 if shard_begin: shard_begin = int(shard_begin, 16) ...
69a6bc62b64287599536ed5d529392de6e362e7e
48,566
def decode_segmap(label_mask, dataset='pascal'): """Decode segmentation class labels into a color image Args: label_mask (np.ndarray): an (M,N) array of integer values denoting the class label at each spatial location. Returns: np.ndarray: the resulting decoded color image. """...
cdead8c808783bd93cbb80f2317e8e24b71e7172
48,567
def PullToBrepFace1(thisCurve, face, tolerance, multiple=False): """ Pulls this curve to a brep face and returns the result of that operation. Args: face (BrepFace): A brep face. tolerance (double): A tolerance value. Returns: Curve[]: An array containing the resulting curves a...
aa8823baa84e8b0503d956f9c43fc7481dbd2745
48,568
import os def clone_file_path(filename, target_dir, suffix=""): """ Create same file in different directory [Including sub dirs] :param filename: str, Filename to clone :param target_dir: Target dir :param suffix: Suffix to use for renaming :return: str, New file absolute path """ # G...
8fc017b3c73d2ff193413ee2fd99e994612b4a46
48,569
from typing import Type import sys def try_expanding_enum_to_union(typ: Type, target_fullname: str) -> ProperType: """Attempts to recursively expand any enum Instances with the given target_fullname into a Union of all of its component LiteralTypes. For example, if we have: class Color(Enum): ...
0c5cad46a443bc55cece4b8939dc142bafd05382
48,570
def medfilereader(filename, varsToExtract = 'all', sessionToExtract = 1, verbose = False, remove_var_header = False): """ Reads in Med Associates file stored as single column and returns variables as lists. Args: filename - file to be read i...
86c9f773fe4e95574eb7f109831a243beb0c7b5b
48,571
import math import logging def sieve_of_eratosthenes(n): """Generate a list of all prime numbers between 1 and 'n' using optimised Sieve of Eratosthenes algorithm""" list_of_primes = []; # Initialise list with all EVEN items as False list_of_numbers = [True, False] * int(n / 2) # Add the last i...
4bb5e623ea7b057575d07dfbf8d460836fa63b8c
48,572
def get_label(node_name): """ Function that returns the label of a specific docker node (eg. label can be loc=edge). Args: node_name: name of the docker node Returns: dictionary of the label: dict["label"] = "value" """ return_dict = {} cmd = "sudo docker node inspect -f '{{ range $k, $v...
0656a6777f4af94cc8e62c660821f2fcd9c4649e
48,573
def product_vector4_4x4(vector,matrix): """mulipli le vector 4 par une matrice care de 4""" x = matrix[0][0]*vector[0] + matrix[0][1]*vector[1] + matrix[0][2]*vector[2] + matrix[0][3]*vector[3] y = matrix[1][0]*vector[0] + matrix[1][1]*vector[1] + matrix[1][2]*vector[2] + matrix[1][3]*vector[3] z = matrix[2][0]*vec...
13a90165fd2a08af0d380f3b2bc541554f377b11
48,574
def ghostnet(**kwargs): """ Constructs a GhostNet model """ cfgs = [ # input e.g. 512 x 512 # k, t, c, SE, s # stage1 [[3, 16, 16, 0, 1]], # 256 x 256 # stage2 [[3, 48, 24, 0, 2]], [[3, 72, 24, 0, 1]], # 128 x 128 # stage3 [[5, 7...
ba619b9006e343e71ad917ccc5668ff891435a49
48,575
import pandas as pd import os def fatality(path): """Drunk Driving Laws and Traffic Deaths a panel of 48 observations from 1982 to 1988 *number of observations* : 336 *observation* : regional *country* : United States A dataframe containing : state state ID code year year mrall ...
7a3bc135d19290f5812414935fde0008746af715
48,576
def soft_normal(v, alpha): """ソフト正規化関数""" v_norm = np.linalg.norm(v) softmax = v_norm + 1 / alpha * np.log(1 + np.exp(-2 * alpha * v_norm)) return v / softmax
bb81b4d6be688629e354ffb9a17780e55e86591f
48,577
def wrap_decoder(trg_vocab_size, max_length, n_layer, n_head, d_key, d_value, d_model, d_inner_hid, prepostprocess_dropout, attention_dropout, relu_dr...
25d828de5a7c4e590fe8e09152fa226f4d72606b
48,578
def eval_feature_detail(Info_Value_list,out_path=False): """ format InfoValue list to Dataframe :param Info_Value_list: Instance list of Class InfoValue :param out_path:specify the Dataframe to csv file path ,default False :return:DataFrame about feature detail """ rst = Info_Value_list ...
aa911f01c8b41964e0883f23a76784ffae57aa7e
48,579
import os import tempfile import subprocess def evaluate_metric_once(scenario, metric, seeds): """Runs one evaluation of metric by running a roll out of scenario with each random seed in seeds. """ runner = FindResourceOrThrow( "drake/examples/acrobot/spong_sim_main_cc") env_tmpdir = os.ge...
23212d13b2d8f95b7aa1441387e36bb61f7aac42
48,580
def get_answer_phrase(question, sentence): """ Given a question and the sentence with an answer, extract the answer. :param question: Question asked of us. :param sentence: Sentence with question in it. :return: string phrase of answer """ # Tokenize question for W-word q_toks = nltk.wo...
856b1667361bf1b8faf5d6ea3ffe6a071ef32ef8
48,581
def get_search_queries(phrase): """Return querysets to lookup different types of objects. Args: phrase (str): searched phrase """ return { 'skills': _search_skills(phrase), 'users': _search_users(phrase), 'tasks': _search_orders(phrase)}
3d279b435932df28e19170d3277ec5e1a281e21d
48,582
def sortclosestpoints(pt0, pts): """return pt index in pts sorted by increasing distance from pt0 Note: cartesian distance """ x1, y1 = pt0 x2, y2 = np.array(pts).T diffx = x1 - x2 diffy = y1 - y2 dist = np.hypot(diffx, diffy) sortedindices = np.argsort(dist) sortedistances ...
2fb81bd1c8e975f12dd34b7aa3d8124c53b6c9a8
48,583
def prune_properties(document, paths): """Prune given properties from a document. This assumes properties will always have an object (dict) as a parent. The function modifies the document in-place, but also returns the document for convenience. (The return value may be ignored.) """ for path in...
299734c7c09513f6e6b840ec126d85975b39cfc0
48,584
def HT_DCPERIOD(df): """ 函数名:HT_DCPERIOD 名称: 希尔伯特变换-主导周期 简介:将价格作为信息信号,计算价格处在的周期的位置,作为择时的依据。 [文库文档](https://wenku.baidu.com/view/0e35f6eead51f01dc281f18e.md) NOTE: The ``HT_DCPERIOD`` function has an unstable period. python API real=HT_DCPERIOD(close) :return: """ close = d...
f1ca7a7a4b05512a4ecac43b1c9adbf5dcdddd95
48,585
import os def parse_dataset_configs(root: str): """ Parse dataset configuration file Args: root(str): (absolute, expanded) path to dataset root directory Returns: ConfigParser Raises: FileNotFoundError: configuration file does not exists """ cfg_path = os...
10d95a75cf71f367f558c5a75e1026401f56a737
48,586
def exp(str_in, expansion): """exp(): """ return perm(str_in, expansion)
191a20d550f494f7d17aaaadf9251c25912ddb5d
48,587
import itertools def compat_tee(iterable): """Return two independent iterators from a single iterable. Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html """ # Note: Using a dictionary and a list as the default arguments here is # deliberate and safe in this instance. def gen...
025e809961bd098aaede070c2fa8090c59d31b5a
48,588
def uint8(image:'np.ndarray')->'np.ndarray': """Convert to uint8 Args: image('np.ndarray'): Returns: Raises: """ # Change range 0-1 to 0-255 and change type to uint8 return (image*255).astype(np.uint8)
e38a61d93c2e70f33a5d6768d1b870f96e5ebb67
48,589
def _p(pp, name): """ make prefix-appended name """ return '%s_%s'%(pp, name)
0a38c89384830b8fc11cb19187c684112408c784
48,590
def map_to_parent(t_class, parents_info_level): """ parents_info_level: {<classid>: [parent]}, only contains classid that has a super-relationship """ if t_class in parents_info_level: assert len(parents_info_level[t_class]) < 2, f"{t_class} has two or more parents {parents_info_level[t_class]}...
a92cf3671aff03724ac89ef024089df06ae28d4a
48,591
from typing import Optional from typing import cast import ftplib import re from datetime import datetime import logging def _get_mtime(c: FTPClient, path: str) -> Optional[int]: """Returns timestamp of last modification""" try: mdtm = cast(ftplib.FTP, c).sendcmd("MDTM " + path) # mdtm-respons...
e3319e7775f236398fee9b06d1d2ddf0da300d46
48,592
def argParse(): """Parses commandline args.""" desc='Scrape the doxygen generated xml for docstrings to insert into python bindings' parser = ArgumentParser(description=desc) parser.add_argument("function", help="Operation to perform on docstrings", choices=["scrape","sub","copy"]) parser.add_...
6536c83561727ca0e9b1c39ec670ea0d3d9c4ae2
48,593
import uuid def get_temp_entity_table_name() -> str: """Returns a random table name for uploading the entity dataframe""" return "feast_entity_df_" + uuid.uuid4().hex
62d8b0ca2d58fb813db88caa753f93e412c62ad0
48,594
def _sort_mixed(values) -> np.ndarray: """order ints before strings in 1d arrays, safe in py3""" str_pos = np.array([isinstance(x, str) for x in values], dtype=bool) nums = np.sort(values[~str_pos]) strs = np.sort(values[str_pos]) return np.concatenate([nums, np.asarray(strs, dtype=object)])
a7aa58f6f33737285c563492d99f3d62dc8a6ade
48,595
def lpmm2lpph(lpmm, n, pixelPitch): """Convert resolution specified in Line-Pair per Milli Meters (LPMM) to Line-Pair per Picture Height (LPPH) Parameters ---------- lpmm : float resolution in terms of Line-Pair per Milli-Meters (LPMM) n : integer Number of pixels in the picture...
e4cfaa0376830cb3a33c05ad1d2eba78ff6312e0
48,596
def isPalindrome1(s, indent): """Return True if s is a palindrome and False otherwise.""" print indent, "isPalindrome called with", s if len(s) <= 1: print indent, "About to return True from base case" return True else: ans = s[0] == s[-1] and isPalindrome1(s[1:-1], indent + inde...
38fe4a949a4795ec5e957a3d05949c8a46ab0559
48,597
from typing import Tuple def _parse_gcs_url(gsurl: str) -> Tuple[str, str]: """ Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob. """ parsed_url = urlparse(gsurl) if not parsed_url.netloc: raise AirflowException('Plea...
12f2a8dbff5bab0f7586d17ac777a07e6efadc1f
48,598
from typing import Iterable import tqdm import sys import difflib def check_style(po_files: Iterable[str], no_wrap=False, quiet=False, diff=False) -> int: """Check style of given po_files. Prints errors on stderr and returns the number of errors found. """ errors = 0 for po_path in tqdm(po_files,...
46e219d3c0dda17239505861ba20b20f25bfd150
48,599