content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def PPVfn(Mw, fc, Rho, V): """Calculates the peak-particle-velocity (PPV) at the source for a given homogeneous density and velocity model. :param Mw: the moment magnitude :type Mw: float :param fc: the corner frequency in Hz :type fc: float :param Rho: Density at the source in kg/m**3 ...
5629abb351e46ff41f11feef00bd8b7195b90e8f
3,637,868
import math def extract_feature_label(feat_path, lab_path, audio_sr=22050, hop_size=1024): """Basic feature extraction block. Parameters ---------- feat_path: Path Path to the raw feature folder. lab_path: Path Path to the corresponding label folder. audio_sr: int samp...
2bdca45bcfe19e0b103d4b1762aab6ddf8e67b89
3,637,869
import re def get_m3u8_url(text): # type: (str) -> Union[str, None] """Attempts to get the first m3u8 url from the given string""" m3u8 = re.search(r"https[^\"]*\.m3u8", text) sig = re.search(r"(\?sig=[^\"]*)", text) if m3u8 and sig: return "{}{}".format(clean_uri(m3u8.group()), sig.group(...
25373d6fe8958dc28c6ddcb4eda1b02c9497fd18
3,637,872
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.rando...
df8c812a81d22082add014a8bb17e8cc4966f58c
3,637,873
from typing import Union from typing import Optional def object_bbox_flip( bbox: remote_blob_util.BlobDef, image_size: remote_blob_util.BlobDef, flip_code: Union[int, remote_blob_util.BlobDef], name: Optional[str] = None, ) -> remote_blob_util.BlobDef: """This operator flips the object bounding bo...
8be9a58c2c8a10e8aaba402d45abf25edc42c0ab
3,637,874
def compile(spec): """ Args: spec (dict): A specification dict that attempts to "break" test dicts Returns: JsonMatcher. """ return JsonMatcher(spec)
bddb743e9f4fcbf3987363007f67c7e8dcf44c37
3,637,875
import itertools def labels_to_intervals(labels_list): """ labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs Args: labels_list: list of labels of each frame e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}] Retu...
65b63ea3e6f097e9605e1c1ddb8dd434d7db9370
3,637,876
def get_wolfram_query_url(query): """Get Wolfram query URL.""" base_url = 'www.wolframalpha.com' if not query: return 'http://{0}'.format(base_url) return 'http://{0}/input/?i={1}'.format(base_url, query)
0122515f1a666cb897b53ae6bd975f65da072438
3,637,877
from typing import Sequence def center_of_mass(points: Sequence[float]) -> np.ndarray: """Gets the center of mass of the points in space. Parameters ---------- points The points to find the center of mass from. Returns ------- np.ndarray The center of mass of the points. ...
8d142a0b2b680900d5a20a0119702124bcdf3db6
3,637,878
def get_posts(session, client_id, now=None): """Returns all posts.""" now = _utcnow(now) try: results = _get_post_query(session, client_id)\ .order_by(MappedPost.created_datetime.desc()) posts = tuple(_make_post(*result) for result in results) return PaginatedSequence(posts) except sa.exc....
8cf5eb1ef9ec84a8d98cd8cc285ade7725f0dc5a
3,637,879
def tessellate_cell(csn, children, acells, position, parent, cell_params): """ Tessellate a cell. :param int csn: Cell number. :param ndarray children: Array specifying children of each cell. :param ndarray acells: Array specifying the adjacent cells of each cell. :param ndarray position: Array...
0c9993f49a147488488c7131d772c1996bc12d0f
3,637,880
import torch def add_eig_vec(g, pos_enc_dim): """ Graph positional encoding v/ Laplacian eigenvectors This func is for eigvec visualization, same code as positional_encoding() func, but stores value in a diff key 'eigvec' """ # Laplacian A = g.adjacency_matrix_scipy(return_edge_ids=False)...
a7487f048dfd14cc4d9e04e8a754327dd9c8b19a
3,637,881
import numpy as np from scipy import ndimage from skimage.morphology import ball def _advanced_clip( data, p_min=35, p_max=99.98, nonnegative=True, dtype="int16", invert=False ): """ Remove outliers at both ends of the intensity distribution and fit into a given dtype. This interface tries to emulate...
9444db42b146798900fde89d8436b742ba9082a6
3,637,882
def allocate_buffers(engine): """ Allocates all buffers required for the specified engine """ inputs = [] outputs = [] bindings = [] # Iterate over binding names in engine for binding in engine: # Get binding (tensor/buffer) size size = trt.volume(engine.get_binding_shape...
b7f28c256a1ec169392a4cfb27347ae742c922bb
3,637,883
def D_to_M(D, ecc): """Mean anomaly from eccentric anomaly. Parameters ---------- D : float Parabolic eccentric anomaly (rad). ecc : float Eccentricity. Returns ------- M : float Mean anomaly (rad). """ with u.set_enabled_equivalencies(u.dimensionless_a...
2f6b6ac3c3a0d02456f0e9b03dd6a183583a8bb4
3,637,884
def dict_merge(a, b): """Merge a and b. Parameters ---------- a One dictionary that will be merged b Other dictionary that will be merged """ return _merge(dict(a), b)
2209659fafb6c1d7d8877bfe923ca98516d255bc
3,637,885
import copy def merge_dictionary(src: dict, dest: dict) -> dict: """ Merge two dictionaries. :param src: A dictionary with the values to merge. :param dest: A dictionary where to merge the values. """ for name, value in src.items(): if name not in dest: # When field is n...
12305510a9a2d50bcdc691cb7fe8d5a573621e69
3,637,886
def create_from_source(wp_config, source: Location): """ Using a Location object and the WP config, generates the appropriate LuhSql object """ if isinstance(source, SshLocation): ssh_user = source.user ssh_host = source.host elif isinstance(source, LocalLocation): ssh_u...
3854d70889a1fdc0517f2557431887ca560acb14
3,637,887
def eye(N, M=None, k=0, dtype=DEFAULT_FLOAT_DTYPE): """ Returns a 2-D tensor with ones on the diagnoal and zeros elsewhere. Args: N (int): Number of rows in the output, must be larger than 0. M (int, optional): Number of columns in the output. If None, defaults to N, if defined,...
952da74fbedfaa433244a65cff463ccf0b389cf1
3,637,888
import requests def team_game_log(request, team_id, season): """Individual team season game log page. """ response = requests.get(f'http://{request.get_host()}/api/teams/{team_id}/{season}/Regular') return render(request, 'main/team_games.html', context=response.json())
1e4c59febb2d5d5f2c3496242c8de8068c4bb329
3,637,890
def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower,weak_upper): #def infer_labels(fn_pickle,testdata, fout_pickle, weak_lower=0.935,weak_upper=0.98): """ - this is the linear case of getting labels for new spectra best log g = weak_lower = 0.95, weak_upper = 0.98 best teff = weak_lower = 0.9...
8321f8cdc8c7cfb97106a3eba8c5846a108adcb5
3,637,891
import pylab as pl def figure(*args, grid=True, style='default', figsize=(9, 5), **kwargs): """ Returns a matplotlib axis object. """ available = [s for s in pl.style.available + ['default'] if not s.startswith('_')] if style not in available: raise ValueError(f'\n\n Valid Styles are {avai...
58a50dfda449518c1fed06a380ec0dac82eb1943
3,637,893
def boundcond(stato): """This function applies the boundary conditions that one chooses to adopt. The boundaries can be reflective, periodic or constant. It takes as input the state to be evolved. """ if bc=='const': status=''.join(('.',stato,'.')) #constant boundaries elif bc=='refl': ...
826ea52b1b2bbda01b88f03ce546757225a3bec8
3,637,894
def get_compare_collection(name, csv_line): """get compare collection data""" session = tables.get_session() if session is None: return {'isExist': False} response = {} try: collection_table = CollectionTable() cid = collection_table.get_field_by_key(CollectionTable.collectio...
4312336786de0cd2107e4d662d5527bed37e89b9
3,637,896
from qutepart.indenter.base import IndentAlgNormal as indenterClass from qutepart.indenter.base import IndentAlgBase as indenterClass from qutepart.indenter.base import IndentAlgNormal as indenterClass from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass from qutepart.indenter.python import IndentAlgPy...
3d6f905b66fa7808ad6863e891c30b0d0fb02e7f
3,637,897
import json def scheming_multiple_choice_output(value): """ return stored json as a proper list """ if isinstance(value, list): return value try: return json.loads(value) except ValueError: return [value]
d45bbb1af249d0fed00892ccc55cf8f28f7f099f
3,637,898
def logmap(x, x0): """ This functions maps a point lying on the manifold into the tangent space of a second point of the manifold. Parameters ---------- :param x: point on the manifold :param x0: basis point of the tangent space where x will be mapped Returns ------- :return: vecto...
be18b7a78f13f7159572429cf77fbc763747076b
3,637,899
def parse_field(source, loc, tokens): """ Returns the tokens of a field as key-value pair. """ name = tokens[0].lower() value = normalize_value(tokens[2]) if name == 'author' and ' and ' in value: value = [field.strip() for field in value.split(' and ')] return (name, value)
be5533cc53fc73fe84d8bd79465ef03ba22cfa5f
3,637,900
def evaluate_models_exploratory(X_normal:np.ndarray, X_te:np.ndarray, X_adv_deepfool:np.ndarray, X_adv_fgsm:np.ndarray, X_adv_pgd:np.ndarray, X_adv_dt:np.n...
17435e38512c9c158db6d6ae12ab44c38f573c61
3,637,901
from typing import Iterable from typing import Optional def is_valid_shipping_method( checkout: Checkout, lines: Iterable["CheckoutLineInfo"], discounts: Iterable[DiscountInfo], subtotal: Optional["TaxedMoney"] = None, ): """Check if shipping method is valid and remove (if not).""" if not chec...
01cbbc493d74057c8f2e252cfd217b3cd108b97c
3,637,905
async def load_gdq_index(): """ Returns the GDQ index (main) page, includes donation totals :return: json object """ return (await load_gdq_json(f"?type=event&id={config['event_id']}"))[0]['fields']
6d1383990a2fb98c7a42b4423f21728f4f473e1a
3,637,906
def deleteRestaurantForm(r_id): """Create form to delete existing restaurant Args: r_id: id extracted from URL """ session = createDBSession() restaurant = session.query(Restaurant).get(r_id) if restaurant is None: output = ("<p>The restaurant you're looking for doesn't exist.<...
530a03f17bb28e7967c375d7da6f6e077584cd37
3,637,907
def split_pkg(pkg): """nice little code snippet from isuru and CJ""" if not pkg.endswith(".tar.bz2"): raise RuntimeError("Can only process packages that end in .tar.bz2") pkg = pkg[:-8] plat, pkg_name = pkg.split("/") name_ver, build = pkg_name.rsplit("-", 1) name, ver = name_ver.rsplit(...
3568fc28c54e7de16e969be627804fbb80938d65
3,637,909
def gaussian(k, x): """ gaussian function k - coefficient array, x - values """ return k[2] * np.exp( -(x - k[0]) * (x - k[0]) / (2 * k[1] * k[1])) + k[3]
f58279de58992efd34bd1fa84bbecc64e3dd52ee
3,637,910
def coins(n, arr): """ Counting all ways e.g.: (5,1) and (1,5) """ # Stop case if n < 0: return 0 if n == 0: return 1 ways = 0 for i in range(0, len(arr)): ways += coins(n - arr[i], arr) return ways
cb269db7aef58ae2368a6e6dc04ce6743ebd3d0e
3,637,912
def compute_diff(old, new): """ Compute a diff that, when applied to object `old`, will give object `new`. Do not modify `old` or `new`. """ if not isinstance(old, dict) or not isinstance(new, dict): return new diff = {} for key, val in new.items(): if key not in old: ...
f6e7674faa2a60be17994fbd110f8e1d67eb9886
3,637,913
def assign_nuts1_to_lad(c, lu=_LAD_NUTS1_LOOKUP): """Assigns nuts1 to LAD""" if c in lu.keys(): return lu[c] elif c[0] == "S": return "Scotland" elif c[0] == "W": return "Wales" elif c[0] == "N": return "Northern Ireland" else: return np.nan
7d9ceb2d2eaedf72eef8243d5880b547c989d2fb
3,637,915
async def get_all_persons(): """List of all people.""" with Session(DB.engine) as session: persons = session.query(Person).all() return [p.to_dict() for p in persons]
455533d6ee6b4139354c524d6fd6db29ff2ad123
3,637,916
from typing import List from typing import Dict def pivot_pull(pull: List[Dict[str, str]]): """Pivot so columns are measures and rows are dates.""" parsed_pull = parse_dates(pull) dates = sorted(list(set(row["sample_date"] for row in parsed_pull))) pivot = list() for date in dates: row = {...
53d945cff023c9cb0233b3198a89da1e57ba18d6
3,637,917
def _location_sensitive_score(W_query, W_fil, W_keys): """Impelements Bahdanau-style (cumulative) scoring function. This attention is described in: J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben- gio, “Attention-based models for speech recognition,” in Ad- vances in Neural Information Processing...
4c91f7f682c1a06303c877a81f434cb265dcb1af
3,637,918
def dh_noConv( value, pattern, limit ): """decoding helper for a single integer value, no conversion, no rounding""" return dh( value, pattern, encNoConv, decSinglVal, limit )
55c2306efc1873a283fc4ed24be6677816029122
3,637,919
def chooseFile(): """ Parameters ---------- None No parameters are specified. Returns ------- filenames: tuple A tuple that contains the list of files to be loaded. """ ## change the wd to dir containing the script curpath = os.path.dirname(os.path.realpath(__fi...
480125e9cef6e2334dd21a113fead441388b1f10
3,637,920
def reward_strategy(orig_reward, actualperf, judgeperf, weight={'TP':1, 'TN': 1, 'FP': -1, 'FN':-1}): """ """ assert list(weight.keys()) == ['TP', 'TN', 'FP', 'FN'], "Please assign weights to TP, TN, FP and FN." # assert sum(weight.values()) == 0, "Summation of weight values needs to be 0." if actua...
3bed44a11197898a94939ed2cc9a400243f604b6
3,637,921
def get_user_ids_from_primary_location_ids(domain, location_ids): """ Returns {user_id: primary_location_id, ...} """ result = ( UserES() .domain(domain) .primary_location(location_ids) .non_null('location_id') .fields(['location_id', '_id']) .run().hits ...
9707cda74324c983add4872ca4b27057b7ab8809
3,637,922
def get_next_states(state: State): """Create new states, but prioritize the following: asdjkgnmweormelfkmw Prioritize nothing... """ out = [] # First we check hallways. for i in HALLWAY_IND: # Check if the room has any crabs hall = state.rooms[i] if hall.is_empty(...
fdc270ef292ce1c1507937975743f8877844b063
3,637,923
def _build_trainstep(fcn, projector, optimizer, strategy, temp=1, tau_plus=0, beta=0, weight_decay=0): """ Build a distributed training step for SimCLR or HCL. Set tau_plus and beta to 0 for SimCLR parameters. :model: Keras projection model :optimizer: Keras optimizer :strategy: tf.dis...
2ceb7aa171835b45376f11e28fd4fe323d1ac7f1
3,637,924
def get_environment(): """ Light-weight routine for reading the <Environment> block: does most of the work through side effects on PETRglobals """ ValidExclude = None ValidInclude = None ValidOnly = True ValidPause = 0 #PETRglobals.CodeWithPetrarch1 = True #PETRglobals.CodeWithPetrarch2...
966cb1ad713f5b0c87cdabe12475b4239d5b7469
3,637,926
def create_variables_from_samples(sample_z_logits, sample_z_logp, sample_b, batch_index, sequence_index): """ Create the variables for RELAX control variate. Assumes sampled tokens come from decoder. :param sample_z_logits: [B,T,V] tensor containing sampled processed logits created by stacking logits during...
615e73b136b16979257eb5b32ec9a696c17730be
3,637,927
from typing import OrderedDict import copy def get2DHisto_(detector,plotNumber,geometry): """ This function opens the appropiate ROOT file, extracts the TProfile2D and turns it into a Histogram, if it is a compound detector, this function takes care of the subdetectors' addition. Note t...
5759bc16686642e377c9bd37dde73374f74870ac
3,637,928
import shlex import json import traceback import time def binlog2sql(request): """ 通过解析binlog获取SQL :param request: :return: """ instance_name = request.POST.get('instance_name') save_sql = True if request.POST.get('save_sql') == 'true' else False instance = Instance.objects.get(instanc...
82cf06637024a0feb2c2ae0203cd795d3f6eb944
3,637,929
def smtp_config_generator_str(results, key, inp): """ Set server/username config. :param kwargs: Values. Refer to `:func:smtp_config_writer`. :type kwargs: dict :param key: Key for results dict. :type key: str :param inp: Input question. :type inp: str """ if results[key] is N...
f2cccfaf569f005e03bb351379db85de7146eda0
3,637,930
def default_rollout_step(policy, obs, step_num): """ The default rollout step function is the policy's compute_action function. A rollout step function allows a developer to specify the behavior that will occur at every step of the rollout--given a policy and the last observation from the env--to d...
a6e9dff784e46b9a59ae34334a027b427e8d230a
3,637,932
def perfilsersic(r_e, I_e, n, r): """Evaluate a Sersic Profile. funcion que evalua a un dado radio r el valor de brillo correspondiente a un perfil de sersic r_e : Radio de escala I_e : Intensidad de escala n : Indice de Sersic r : Radio medido desde el centr...
b8cd900d28be3fef1efc142c07012174f30c9f9d
3,637,933
import numpy as np from scipy import interpolate def background_profile(img, smo1=30, badval=None): """ helper routine to determine for the rotated image (spectrum in rows) the background using sigma clipping. """ bgimg = img.copy() nx = bgimg.shape[1] # number of points in direction of...
59b090a2c05d8a520a3c9f980885c9488bdc7615
3,637,934
def get_object(bucket,key,fname): """Given a bucket and a key, upload a file""" return aws_s3api(['get-object','--bucket',bucket,'--key',key,fname])
6687c657ba364757bd519f370c546ad9b7b033f7
3,637,935
import glob def find_file(filename): """ This helper function checks whether the file exists or not """ file_list = list(glob.glob("*.txt")) if filename in file_list: return True else: return False
42895e66e258ba960c890f871be8c261aec02852
3,637,936
def tweetnacl_crypto_secretbox(max_messagelength=256): """ max_messagelength: maximum length of the message, in bytes. i.e., the symbolic execution will not consider messages longer than max_messagelength """ proj = tweetnaclProject() state = funcEntryState(proj, "crypto_secretbox_xsalsa20po...
b380c2848da0c271895dcf893adf1d12c5d86289
3,637,938
def parameterized_dropout(probs: Tensor, mask: Tensor, values: Tensor, random_rate: float = 0.5, epsilon: float = 0.1) -> Tensor: """ This function returns (values * mask) if random_rate == 1.0 and (value...
36d26d0deda5b4394457e235e61f334ea6dc767d
3,637,939
from typing import Optional def get_auto_scale_v_core(resource_group_name: Optional[str] = None, vcore_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAutoScaleVCoreResult: """ Represents an instance of an auto scale v...
e3eda57b7afdfe2a7e1b7e3e958b5140a7120a95
3,637,940
import json def text_output(xml,count): """Returns JSON-formatted text from the XML retured from E-Fetch""" xmldoc = minidom.parseString(xml.encode('utf-8').strip()) jsonout = [] for i in range(count): title = '' title = xmldoc.getElementsByTagName('ArticleTitle') title = parse_xml(title, i, '') pmid = ...
0c48a67b123b55ed5c8777d5fd0ad009578ba1ae
3,637,941
from datetime import datetime def datetime2str(target, fmt='%Y-%m-%d %H:%M:%S'): """ 将datetime对象转换成字符串 :param target: datetime :param fmt: string :return: string """ return datetime.datetime.strftime(target, fmt)
9111040a6136ef675929d30f3aba3eb983b45197
3,637,942
def periodic_targets_form(request, program): """ Returns a form for the periodic targets sub-section, used by the Indicator Form For historical reasons, the input is a POST of the whole indicator form sent via ajax from which a subset of fields are used to generate the returned template """ ...
62e6ef666f113c5aefda858e91c31f3dfd0bcacf
3,637,943
import sqlite3 def get_db(): """Returns an sqlite3.Connection object stored in g. Or creates it if doesn't exist yet.""" db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db
1a8be7a3d42123db213cd4c2a5968bdede92e677
3,637,944
def is_string_like(obj): # from John Hunter, types-free version """Check if obj is string.""" return isinstance(obj, basestring)
5b3b66dd0706f1f0e0257ea50ba48f463a07d6ca
3,637,945
import json def _export_gene_set_pan_genome(meth, pan_genome_id): """Export orthologs from Pangenome as external FeatureSet objects. [26] :param pan_genome_id: ID of pangenome object [26.1] :type pan_genome_id: kbtypes.KBaseGenomes.Pangenome :ui_name pan_genome_id: Pangenome ID :return: Gen...
5dfc5a6d253a66cf7ff50c736f9fdaa43a2334a8
3,637,946
def makeId(timestamp=0, machine=0, flow=0): """ using unix style timestamp, not python timestamp """ timestamp -= _base return (timestamp << 13) | (machine << 8) | flow
0443714cd5e87c93dc8ee8a156cd406f481c6d82
3,637,949
import time def _get_token(cls, token_type): """ when token expire flush,return token value """ assert token_type in ['tenant_access_token', 'app_access_token'], token_type if not hasattr(cls.request, token_type) or hasattr(cls.request, token_type) or\ time.time() >= getattr(cls.re...
15ee9c6926f929960b20ee68901f1d675f43639a
3,637,950
from typing import Iterator def chunk(it: Iterator, size: int) -> Iterator: """ Nice chunking method from: https://stackoverflow.com/a/22045226 """ it = iter(it) return iter(lambda: tuple(islice(it, size)), ())
8cd199b1d2092373a156dac74cd80b700fb70fcd
3,637,951
def sort_by_directory(path): """returns 0 if path is a directory, otherwise 1 (for sorting)""" return 1 - path.is_directory
1cd066e69885901ae1b2b167feb061e98ed5f3ed
3,637,952
import json def read_config(config): """ Read config file containing information of type and default values of fields :param config: path to config file :return: dictionary containing type and or default value for each field in the file """ dic_types = json.load(open(...
ebdf6a001f65fb2ad2c3da6015a5b8998f1fda4a
3,637,953
def is_right_hand_coordinate_system3(pose): """Checks whether the given pose follows the right-hand rule.""" n, o, a = pose[:3, 0], pose[:3, 1], pose[:3, 2] return n.dot(n).simplify() == 1 and o.dot(o).simplify() == 1 and a.dot(a).simplify() == 1 and sp.simplify(n.cross(o)) == a
f6b1fcff1d3502c78db294fe2ad496a214c13366
3,637,954
def model_airmassfit(hjd, am, rawflux, limbB1, limB2, inc, period, a_Rs, Rp_Rs, show=False): """ Return the bestfit model for the lightcurve using 4 models of airmass correction: 1. model with no airmass correction 2. model with exponential airmass correction 3. model with linear airmass correction ...
6cc74f5820aff6a36fdd89c37df141d82a558dab
3,637,955
def common_params_for_list(args, fields, field_labels): """Generate 'params' dict that is common for every 'list' command. :param args: arguments from command line. :param fields: possible fields for sorting. :param field_labels: possible field labels for sorting. :returns: a dict with params to pa...
6e432213a504b2423dca4add79c860d9bffe4ad4
3,637,956
def _finditem(obj, key): """ Check if giben key exists in an object :param obj: dictionary/list :param key: key :return: value at the key position """ if key in obj: return obj[key] for k, v in obj.items(): if isinstance(v, dict): item = _finditem(v, key) ...
0f7c5b801acfae6a66d175163d726cba22380f7c
3,637,957
def decompress(obj): """Decompress LZSS-compressed bytes or a file-like object. Shells out to decompress_file() or decompress_bytes() depending on whether or not the passed-in object has a 'read' attribute or not. Returns a bytearray.""" if hasattr(obj, 'read'): return decompress_file(obj)...
58f090f02e76e90606b7ec83d2f9567235b90213
3,637,958
def trailing_whitespace(text): """Gets trailing whitespace of text.""" trailing = "" while text and text[-1] in WHITESPACE_OR_NL_CHARS: trailing = text[-1] + trailing text = text[:-1] return trailing
ddb3fba9d41261f45a0ea3e0ffd03949950532ce
3,637,959
import numpy def rjust(a, width, fillchar=' '): """ Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings ...
05d99fcd2600bcfee19c60b75f50af868d853a87
3,637,960
import tempfile def form_image_helper(caption_list, dummy=True, image_suffix='.jpg'): """ :param caption_list: <class 'list'> :param dummy: <class 'bool'> :param image_suffix: <class 'str'> :return: <class 'dict'> [dict of dummy images for form submission in django unittest] """ try: ...
b299ce536de33fe04821a7c1306dfff61000eed4
3,637,961
from typing import Any import inspect def is_complex_converter(obj: Any) -> bool: """Check if the object is a complex converter.`""" return isinstance(obj, ComplexConverterABC) or inspect.isclass(obj) and issubclass(obj, ComplexConverterABC)
d6069161819f348a4cec516f348ed93d59d38a74
3,637,962
def some_task(): """ Some task """ get_word_counts('python.txt') get_word_counts('go.txt') get_word_counts('erlang.txt') get_word_counts('javascript.txt') return "Task Done"
a6dcacaf22cb39b886feb4566d05b48c0e7db1e3
3,637,965
def _accelerate(f, n_devices): """JIT-compiled version of `f` running on `n_devices`.""" if n_devices == 1: return fastmath.jit(f) return fastmath.pmap(f, axis_name='batch')
f9735078b012d49e15aa16b9911b2c897f9987c1
3,637,966
from datetime import datetime def parse_shadowserver_time(time_string: Text) -> datetime.datetime: """Parse a date on the format '2018-10-17 20:36:23'""" try: return datetime.datetime.strptime(time_string[:19], '%Y-%m-%d %H:%M:%S') except: print(time_string) raise
9cf267bac24fcd4efdc73d4839493b9440c178ce
3,637,967
import random def sample_along_rays(rng, origins, directions, radii, num_samples, near, far, genspace_fn, ray_shape, sin...
0745c1e7ed152c93c49bfcf59bb0255422b018ec
3,637,968
import PIL def resize(img, size, interpolation=PIL.Image.BILINEAR): """Resize image to match the given shape. This method uses :mod:`cv2` or :mod:`PIL` for the backend. If :mod:`cv2` is installed, this function uses the implementation in :mod:`cv2`. This implementation is faster than the implementati...
fa2a407f42672e5ea91e8e2bd1c186d4ca05d98c
3,637,969
def build_punt(): """ Construye la ventana del registro del usuario""" easy = PA.dividir_puntajes("facil") medium = PA.dividir_puntajes("medio") hard = PA.dividir_puntajes("dificil") rows = len(max([easy, medium, hard], key=len)) def create_table(data, dif): return sg.Table( ...
a97dc74855ccb8e65096d74c7fe59d89d5a3f92b
3,637,970
def true_fov(M, fov_e=50): """Calulates the True Field of View (FOV) of the telescope & eyepiece pair Args: fov_e (float): FOV of eyepiece; default 50 deg M (float): Magnification of Telescope Returns: float: True Field of View (deg) """ return fov_e/M
7735135d326f3000ac60274972263a8a71648033
3,637,971
async def test_html_content_type_with_utf8_encoding(unused_tcp_port, postgres_db, database_name, async_finalizer): """Test whether API endpoints with a "text/html; charset=UTF-8" content-type work.""" configure(unused_tcp_port, database_name, postgres_db.port) html_content = "<html><body>test</body></html>...
74d76c70ede4ad7b6c65170142136a6278c39802
3,637,972
def _increment_inertia(centroid, reference_point, m, mass, cg, I): """helper method""" if m == 0.: return mass (x, y, z) = centroid - reference_point x2 = x * x y2 = y * y z2 = z * z I[0] += m * (y2 + z2) # Ixx I[1] += m * (x2 + z2) # Iyy I[2] += m * (x2 + y2) # Izz I[...
f95d8c01061243929fa1d3dd48903bedc938bbd8
3,637,973
def token_addresses( request, token_amount, number_of_tokens, blockchain_services, cached_genesis, register_tokens): """ Fixture that yields `number_of_tokens` ERC20 token addresses, where the `token_amount` (per token) is distributed among the addresses behind `b...
8c79175f3a1ca312dfb03de60262f019b74b965c
3,637,974
def saturating_sigmoid(x): """Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1].""" with tf.name_scope("saturating_sigmoid", [x]): y = tf.sigmoid(x) return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1))
d779f059251cc99e40bf5d13ee2d31bc786c48b7
3,637,975
def simulate_strategy(game, strategies, init_states, func): """ Harvest an accurate average payoff with the two strategies, considering traversing all possible private cards dealt by nature game : the pyspiel game strategies : the index of player's strategy, a length two list ...
47f60a2998ed8deba95b32edfa4221d7f2d767cc
3,637,976
async def is_nsfw_and_guild_predicate(ctx): """A predicate to test if a command was run in an NSFW channel and inside a guild :param ctx: The context of the predicate """ if not ctx.guild or not ctx.channel.is_nsfw(): raise NotNSFWOrGuild() return True
20e5ec228f337fcae1e28ad12cde515be9e50f4b
3,637,977
from typing import Optional def get_account(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountResult: """ Get information on your DigitalOcean account. ## Example Usage Get the account: ```python import pulumi import pulumi_digitalocean as digitalocean example = di...
64758aacd0f294a2f08e60d59edec6c088942e11
3,637,978
import six def get_partition_leaders(cluster_config): """Return the current leaders of all partitions. Partitions are returned as a "topic-partition" string. :param cluster_config: the cluster :type cluster_config: kafka_utils.utils.config.ClusterConfig :returns: leaders for partitions :rtype...
07aed255fa6d2ec65854d4a5ed1ab1ada6dcca73
3,637,979
def WR(df, N=10, N1=6): """ 威廉指标 :param df: :param N: :param N1: :return: """ HIGH = df['high'] LOW = df['low'] CLOSE = df['close'] WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) ...
28cccd0b5f7d0a0a772327901b838e9bf8aa862d
3,637,982
from hask3.lang.hindley_milner import Function def make_fn_type(params): """Turn type parameters into corresponding internal type system object. Returned object will represent the type of a function over the parameters. :param params: a list of type paramaters, e.g. from a type signature....
876d1d9c4243e0ed8a71b9fda2b2469519f4c89b
3,637,983
def export(request, wid): """Export the logs from the given workflow :param request: HTML request :param pk: pk of the workflow to export :return: Return a CSV download of the logs """ dataset = LogResource().export( Log.objects.filter(user=request.user, workflow__id=wid) ) # C...
ff06c49642a4ab84b7c779522a13ce56e19cc9a9
3,637,984
def _validate_valid_xml(value): """ Checks whether the given value is well-formed and valid XML. """ try: # Try to create an XML tree from the given String value. _value = XML_DECL.sub(u'', value) _ = etree.fromstring(_value.encode('utf-8')) return True except et...
dbdcce58a6dbbbaf90b98c6f56fa7f9c6f830e00
3,637,985
import importlib import pkgutil def import_submodules(package, recursive=True): """Import all submodules of a module, recursively, including subpackages :param recursive: bool :param package: package (name or actual module) :type package: str | module :rtype: dict[str, types.ModuleType] """ ...
df1756f59763adf446a6e42f92c5bb193a8740bd
3,637,986
def seasonal_pattern(season_time): """Just an arbitrary pattern, you can change it if you wish""" return np.where(season_time < 0.4, np.sin(season_time * 2), 1 / np.exp(3 * season_time))
06430ce5d3da7d44fc4a8b5e32ca4d5567b1cc15
3,637,987