content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import warnings def _url_from_string(url): """ Generate actual tile url from tile provider definition or template url. """ if "tileX" in url and "tileY" in url: warnings.warn( "The url format using 'tileX', 'tileY', 'tileZ' as placeholders " "is deprecated. Please use '...
f3d4393163e48a7949f3229c55ea8951411dcd63
3,639,400
import socket def get_reverse_dns(ip_address: str) -> str: """Does a reverse DNS lookup and returns the first IP""" try: rev = socket.gethostbyaddr(ip_address) if rev: return rev[0] return "" # noqa except (socket.herror, socket.gaierror, TypeError, IndexError): ...
58a27e25f7a9b11ab7dcddebeea743b7864f80f1
3,639,401
def abs_path(file_path): """ Returns the absolute path from the file that calls this function to file_path. Needed to access other files within aide_gui when initialized by aide. Parameters ---------- file_path: String The relative file path from the file that calls this function. """ ...
63e4a4b0c8fafb5920c78310fda90b119fd18104
3,639,402
def function(x: np.ndarray) -> float: """The ellipse function is x0^2 + 2 * x1^2 + 3 * x2^2 + ...""" return np.linalg.norm(np.sqrt(np.arange(1, 1 + len(x))) * x) ** 2
efe468177ff232d45d18385fa2744a9cf63739eb
3,639,403
def replace_with_encoded_bits(one_hot_matrix, enum_val, add_value, last_col_index): """ Generate encoded bits for a categorical data value using one hot encoding. :param one_hot_matrix: matrix representing the encoding of categorical data value to 1-hot encoding :param enum_val: categorical data value,...
d5ee111d74071fdbaa3890b35a193aa9e24df745
3,639,404
def cosine_similarity(n_co_elements, n_first_element, n_second_element): """ Description A function which returns the cosine similarity between two elements. Arguments :param n_co_elements: Number of co-elements. :type n_co_elements: int :param n_first_element: Size of the f...
ea35e47ecf3e77a95d535b0421afbe5f3a679817
3,639,405
def AddForwardEulerDynamicsConstraint(mp, A, B, x, u, xnext, dt): """ Add a dynamics constraint to the given Drake mathematical program mp, represinting the euler dynamics: xnext = x + (A*x + B*u)*dt, where x, u, and xnext are symbolic variables. """ n = A.shape[0] Aeq = np.hstack(...
e0070aa28b61833330706e3934cbfaa8eb1c1d1b
3,639,406
import json async def light_pure_rgb_msg_fixture(hass): """Return a mock MQTT msg with a pure rgb light actuator message.""" light_json = json.loads( await hass.async_add_executor_job(load_fixture, "ozw/light_pure_rgb.json") ) message = MQTTMessage(topic=light_json["topic"], payload=light_json...
93156674ece713d6c9371f64840852a3d5d292b5
3,639,407
import csv def make_header_names_thesaurus(header_names_thesaurus_file=HEADER_NAMES_THESAURUS_FILE): """ Get a dict mapping ideal domain-specific phrases to list of alternates. Parameters ---------- header_names_thesaurus_file : str Filepath. Returns ------- Dict of {'ideal phrase': ['alt_phrase0', 'alt_p...
20f89be5dfbdf0feac5facddcaeeddb346d394a8
3,639,408
def split_train_valid_test(adata_here, training_proportion=0.6, validation_proportion=0.2, test_proportion=0.2, rng=None,copy_adata=False): """Split cells into training, validation and test """ ...
ccff7c2b1372b74429bb6acb04df1dd66ad5c113
3,639,409
def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False, check_serial_no=True): """get stock ledger entries filtered by specific posting datetime conditions""" conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %...
a25b1df6b692975c94f335e40d342617c3a95086
3,639,410
def index(request): """ Main index. Editor view. """ # Render editor body = render_to_string('editor.html', {}) data = { 'body': body } # Render page layout return render(request, 'index.html', data)
bab60def7716ae11d328a95274d2ee7b6305dbaf
3,639,411
def isUsdExt(ext): """ Check if the given extension is an expected USD file extension. :Parameters: ext : `str` :Returns: If the file extension is a valid USD extension :Rtype: `bool` """ return ext.lstrip('.') in USD_EXTS
5c2f7a48869c9ab4a94b4d8a84e892b76938e91a
3,639,412
def _get_dflt_lexicon(a_pos, a_neg): """Generate default lexicon by putting in it terms from seed set. @param a_pos - set of positive terms @param a_neg - set of negative terms @return list(3-tuple) - list of seed set terms with uniform scores and polarities """ return [(w, POSITIVE, 1....
b06a1f81629368447227a846ac3216220beaa77b
3,639,413
import os def process_dst_overwrite_args(src, dst=None, overwrite=True, src_to_dst_func=None): """ Check when overwrite is not allowed, whether the destination exists. """ src = os.path.abspath(src) if ds...
201726c93ce918ff7bcf4d66cd0181ed62d1b061
3,639,414
def rct(target_t : Tensor, source_t : Tensor, target_mask_t : Tensor = None, source_mask_t : Tensor = None, mask_cutoff = 0.5) -> Tensor: """ Transfer color using rct method. arguments target_t Tensor( [N]CHW ) C==3 (BGR) float16|32 source_t Tensor( [N]CHW ) C==3 (BGR) float16|32 ...
87f350c3e8cef10ef2e3bc883457acf861ab064c
3,639,415
def random_policy(num_actions): """ Returns a policy where all actions have equal probabilities, i.e., an uniform distribution. """ return np.zeros((num_actions,)) + 1 / num_actions
9a95865cf3bc7634bc4bf033f343b5811ba40c9f
3,639,416
def find_object(func, name, *args, **kwargs): """Locate an object by name or identifier This function will use the `name` argumetn to attempt to locate an object. It will first attempt to find the object by identifier and if that fails, it will attempt to find the object by name. Since object...
6ee8085d42883798c1f3ab5d0a7711af26b2b614
3,639,417
import os def mkdir(path): """ Make a directory, if the parent directory exists. """ path = abspath(path, fse.get_working().get_full_path()) parent_path, d = os.path.split(path) parent = fse.find_dir(parent_path) if parent: entry = fse.create(name=d, parent=parent, depth=parent.depth+1, is_directory=True) ...
6306e9fe3645b7db8cb478361186626fc294e4d5
3,639,418
import os def _get_cognitive_services_client() -> ImageSearchClient: """Get the cognitive service client to run the searches against. Ensure there is a COGNITIVE_KEY and COGNITIVE_ENDPOINT configured in your app setting for the function, or your local.settings.json file when running locally. Ret...
f52a8a85a60401a5da2b7388fbd295954a54602a
3,639,419
import os def getZeroPadding(path): """Get original zero padding, so can be re-added.""" files = listVisibleFiles(path) zero_padding = len(getNumSubString(os.path.splitext(files[0])[0])) return zero_padding
19b044027d4309c6b3977333958801802f287650
3,639,420
import logging def weld_segments(gdf_line_net, gdf_line_gen, gdf_line_houses, debug_plotting=False): """Weld continuous line segments together and cut loose ends. This is a public function that recursively calls the internal function weld_line_segments_(), until the problem cannot be si...
913f5432fddaaf592ce8a4fa4a4a813fcd26c868
3,639,421
def CreateHSpline(points, multiple=False): """ Construct an H-spline from a sequence of interpolation points Args: points (IEnumerable<Point3d>): Points to interpolate """ url = "rhino/geometry/nurbscurve/createhspline-point3darray" if multiple: url += "?multiple=true" args = [point...
b5f7b2000dcce04a60087ab32956fa4701d1dadc
3,639,422
def get_instance_embedding_loss(embedding, instance_loss_type, instance_labels, crop_area, crop_min_height, num_samples=10, simi...
ff1e08ea60f4c937fd44bec967eda37d6916ef00
3,639,423
def str_to_array(value): """ Check if value can be parsed to a tuple or and array. Because Spark can handle tuples we will try to transform tuples to arrays :param value: :return: """ try: if isinstance(literal_eval((value.encode('ascii', 'ignore')).decode("utf-8")), (list, tuple)): ...
d565021781a3c2c19c882073ddc6cbd24334b74a
3,639,424
import inspect def get_current_func_name(): """for python version greater than equal to 2.7""" return inspect.stack()[1][3]
002d318bcab98639cab6c38317322f247a1ad0e0
3,639,425
def getParmNames(parmsDef): """Return a list of parm names in a model parm definition parmsDef: list of tuples, each tuple is a list of parms and a time constraint. Call with modelDict[modelname]['Parms]. Returns: List of string parameter names Here's an example of how to remove unused parms f...
785661200c388f23c5f38ae67e773a43fd8f57b3
3,639,426
def dict_merge(lft, rgt): """ Recursive dict merge. Recursively merges dict's. not just simple lft['key'] = rgt['key'], if both lft and rgt have a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. """ if not isinstance(rgt, ...
c939fed14ff10452663bc5a32247b21f6170897a
3,639,427
def modified_zscore(x: np.ndarray) -> np.ndarray: """ Modified z-score transformation. The modified z score might be more robust than the standard z-score because it relies on the median for calculating the z-score. It is less influenced by outliers when compared to the standard z-score. Param...
8f0933bf30ec55ba6305c9bd926437bb0715a938
3,639,428
def update_profile(email, username, name, bio, interest, picture=None): """更新 profile""" db = get_db() cursor = db.cursor() # query user user = get_user_by_email(email) email = user['email'] profile_id = user['profile_id'] if profile_id is None: # add profile cursor.exe...
0b13d81f9d36198d4660179eae7616d8f25ee37e
3,639,429
import zlib import marshal def serialize(object): """ Serialize the data into bytes using marshal and zlib Args: object: a value Returns: Returns a bytes object containing compressed with zlib data. """ return zlib.compress(marshal.dumps(object, 2))
650cbc8937df5eae79960f744b69b8b12b623195
3,639,430
def logo_if(interp, expr, block, elseBlock=None): """ IF tf instructionlist (IF tf instructionlist1 instructionlist2) command. If the first input has the value TRUE, then IF runs the second input. If the first input has the value FALSE, then IF does nothing. (If given a third input, IF acts ...
94f143f59fa02f059469f8f17a3ff11093110c84
3,639,431
import itertools def select_model_general( df, grid_search, target_col_name, frequency, partition_columns=None, parallel_over_columns=None, executor=None, include_rules=None, exclude_rules=None, country_code_column=None, output_path="", persist_cv_results=False, per...
1c286b8cf922a50c1c1071aa0d0506b0cf102a6b
3,639,432
def create_arma_sample(ar_order=1, ma_order=1, size=100): """Get a random ARMA sample. Parameters ---------- ar_order, ma_order, size : int Values for the desired AR order, MA order and sample size. Returns ------- An ARMA sample as a pandas Series. """ ar_coeff = np.linspa...
e859413cee0a20e51fc80aeffbb75b3ada83f010
3,639,433
def get_img(file_path, gray=False): """ 获取输入图片 :param file_path: 图片文件位置 :param gray: 是否转换为灰度图 :return: img """ try: img = Image.open(file_path) if gray: img = img.convert('L') return img except Exception: print("不支持的图片格式") return None
ac3ad78a1ce877905f550ebc43b7e9a6335fd762
3,639,434
from datetime import datetime def working_days(days: int): """Return a list of N workingdays Keyword arguments: days -- days past """ dates = [] today = datetime.utcnow() for i in range(days): day = today - timedelta(days=i) day = day.date() dates.append(day) ...
222002b53bcf536f7b31993a22424446fcce24cc
3,639,435
def GetFile(message=None, title=None, directory=None, fileName=None, allowsMultipleSelection=False, fileTypes=None): """ An get file dialog. Optionally a `message`, `title`, `directory`, `fileName` and `allowsMultipleSelection` can be provided. :: from fontParts.ui import GetFi...
b81ba1e11764231c8c04164316e4ee55b0305044
3,639,436
def str_to_dtype(s): """Convert dtype string to numpy dtype.""" return eval('np.' + s)
e0ff793404af5a8022d260fde5878329abbac483
3,639,437
from typing import Callable from typing import Tuple def integrate_const( f: Callable, t_span: Tuple, dt: float, y0: np.ndarray, method: str = 'runge_kutta4' ) -> Tuple[np.ndarray, np.ndarray]: """ A Python wrapper for Boost::odeint runge_kutta4 (the only one supported right now) stepp...
e43479c829fd46e0f4cdd8c7918294577e91beed
3,639,438
def cleanup(serialized): """ Remove all missing values. Sometimes its useful for object methods to return missing value in order to not include that value in the json format. Examples:: >>> User(Serializable): ... def attributes(): ... return ['id', 'name', 'bir...
5e4bfd13408ec8272c4fc4e9a499349e13dd2798
3,639,439
from typing import Optional from typing import List async def discover_devices( wave_devices: Optional[List[WaveDevice]] = None, ) -> List[WaveDevice]: """Discovers all valid, accessible Airthings Wave devices.""" wave_devices = wave_devices if isinstance(wave_devices, list) else [] device: BLEDevice...
31b5a43b1be765ca4d67080f5a04d16477615fa6
3,639,440
import os import pickle def convert_examples_to_feats_lstm(examples, max_seq_length, glove_vocab, feat_file, language): """Loads a data file into a list of `InputBatch`s in glove+lstm manner""" print("#examples", len(examples)) if os.path.exists(feat_file): with open(feat_file, 'rb') as f: ...
734fbac9f0e2f1b203424f5b495ceb3ba056c3ab
3,639,441
import json def PyValueToMessage(message_type, value): """Convert the given python value to a message of type message_type.""" return JsonToMessage(message_type, json.dumps(value))
576237ebbacb85ac4c51be8b5523f4f95cfcc019
3,639,442
from typing import Any from typing import get_origin def istype(obj: Any, annotation: type) -> bool: """Check if object is consistent with the annotation""" if get_origin(annotation) is None: if annotation is None: return obj is None return isinstance(obj, annotation) else: ...
c1903ea2ec6c0b6b9006a38f7c0720c88987b706
3,639,443
import logging import platform def test_cand_gen(caplog): """Test extracting candidates from mentions from documents.""" caplog.set_level(logging.INFO) if platform == "darwin": logger.info("Using single core.") PARALLEL = 1 else: logger.info("Using two cores.") PARALLE...
44cf505a7eedef55e6322eafebfb92ad3b882697
3,639,444
def spending_from_savings(take_home_pay: float, savings: float) -> Decimal: """ Calculate your spending based on your take home pay and how much you save. This is useful if you use what Paula Pant calls the anti-budget, instead of tracking your spending in detail. This number can be used as input fo...
da26cae052bd27efb11893440353d53e8b6aed89
3,639,445
import sys def stdlib_public_names(module: str, *, version: str = None) -> set[str]: """ Return a set of public names of a stdlib module, in specific Python version. If no version is given, default to the current version. The `version` parameter takes argument of the form `3.9`, `4.7`, etc. """ ...
4a16226a58c58ef66ef4f439160cab72b4902ad0
3,639,446
def large_asymmetric_bulge(data): """ :param data: image data as array :return: the width and location of the largest asymmetric bulge (if any) in the sequence """ # retrieve the lengths of the bars in the sequences (the counts) from the palindrome function score, upper_half_counts, lower_half_c...
be7aef1cc6a2443de3ecff5099d6e28554544f7a
3,639,447
import requests def request(host, path, bearer_token, url_params): """Given a bearer token, send a GET request to the API. Args: host (str): The domain host of the API. path (str): The path of the API after the domain. bearer_token (str): OAuth bearer token, obtained using client_id an...
8f322307bfc1cf48ff5e1a7e52df18e5c9dc7ddf
3,639,448
def find_unique_distances(distance_ij: pd.Series) -> np.ndarray: """Finds the unique distances that define the neighbor groups. :param distance_ij: A pandas ``Series`` of pairwise neighbor distances. :return: An array of unique neighbor distances. """ unique_floats: np.ndarray = np.sort(distance_ij...
ca4d8252c4b79bd536a10a058ca5f75b9f39416e
3,639,449
from typing import Dict from typing import Any def session(monkeypatch: pytest.MonkeyPatch) -> nox.Session: """Fixture for a Nox session.""" registry: Dict[str, Any] = {} monkeypatch.setattr("nox.registry._REGISTRY", registry) @nox.session(venv_backend="none") def test(session: nox.Session) -> No...
646403d4383c6e426d736bf55278e001db2a40e1
3,639,450
import yaml def _load_yaml_with_clear_tag(stream): """Like yaml.safe_load(), but everything with a !clear tag before it will be wrapped in ClearedValue().""" loader = yaml.SafeLoader(stream) loader.add_constructor('!clear', _cleared_value_constructor) try: return loader.get_single_data() ...
dec04cec96fae797250d1fb37491755ceaea399c
3,639,451
def highlights(state_importance_df, exec_traces, budget, context_length, minimum_gap=0, overlay_limit=0): """generate highlights summary""" sorted_df = state_importance_df.sort_values(['importance'], ascending=False) summary_states, summary_traces, state_trajectories = [], [], {} seen_in...
50c1dddaad88fa697f850380b215c2fb9e5f1a13
3,639,452
def draw_figure(canvas, figure, loc=(0, 0)): """ Draw a matplotlib figure onto a Tk grafica loc: location of top-left corner of figure on grafica in pixels. Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py """ figure_canvas_agg = FigureCanvasAgg(figure) figure_canvas...
02e4bc4a6cd475c63239170c0dae0648199c46b5
3,639,453
def find_struct(lines): """Finds structures in output data""" struct = '' name1 = '' name2 = '' seq1 = '' seq2 = '' result = [] for line in lines: if line.startswith('; ========'): break if line.startswith('; ALIGNING'): line = line.split() ...
b7f7e5c70fe0b1111f33e43a40bb9fdde4182b68
3,639,454
from typing import Callable def chain(*fs: Callable) -> Callable: """ Compose given functions in reversed order. Given functions f, g, the result of chain is chain(f, g) = g o f. >>> def f(x: int) -> int: ... return x + 1 >>> def g(x: int) -> str: ... return str(x) >>> chai...
4956a955a760d5243988f8fc6fdb0303e3351704
3,639,455
def astra_fp_2d_fan(volume, angles, source_object, object_det): """ :param volume: :param angles: degrees :return: """ detector_size = volume.shape[1] proj_geom = build_proj_geometry_fan_2d(detector_size, angles, source_object, object_det) rec = astra_fp_2d(volume, proj_geom) return...
5114730387bd43585bb56a16e5e930491aa87fd2
3,639,456
from typing import Mapping def get_remappings_prefix() -> Mapping[str, str]: """Get the remappings for xrefs based on the prefix. .. note:: Doesn't take into account the semicolon `:` """ return _get_curated_registry()['remappings']['prefix']
02cb1bb1cfa4ffb177327442c6fb63c4fc3fa320
3,639,457
import json def generate_schema(): """ schema generation from today filename dataset """ today = date.today().strftime("%d_%m_%Y") complete_dataset = pd.read_csv(f"complete_dataset_{today}.csv") json_schema = pd.io.json.build_table_schema(complete_dataset) with open("json_schema_for_big_query.json...
67dca17ddfae8f3530e8ced2a730c28657fa77ca
3,639,458
def binary_truncated_sprt_with_llrs(llrs, labels, alpha, beta, order_sprt): """ Used in run_truncated_sprt_with_llrs . Args: llrs: A Tensor with shape (batch, duration). LLRs (or scores) of all frames. labels: A Tensor with shape (batch,). alpha : A float. beta: A float. ...
4d4f67d1ad9407df1cf8bfdc0e4c5cf775fcc57b
3,639,459
import time def backoff(action, condition, max_attempts=40): """ Calls result = action() up to max_attempts times until condition(result) becomes true, with 30 s backoff. Returns a bool flag indicating whether condition(result) was met. """ timeout = 30 for attempt in range(max_attempts): result = acti...
93fe5ff9ee672073eb9eb4792572e41d4b4c3faa
3,639,460
def get_file_info(repo, path): """we need change_count, last_change, nbr_committers.""" committers = [] last_change = None nbr_changes = 0 for commit in repo.iter_commits(paths=path): #print(dir(commit)) committers.append(commit.committer) last_change = commit.committed_date...
6ff99df399d35b79d0e2a5635b1e76e1f65fe0bd
3,639,461
import requests import urllib3 def retryable_session(session: requests.Session, retries: int = 8) -> requests.Session: """ Session with requests to allow for re-attempts at downloading missing data :param session: Session to download with :param retries: How many retries to attempt :return: Sessio...
a57d2021077997ab14576df35b4e5ad9d281575e
3,639,462
def apply_affine(x, y, z, affine): """ Apply the affine matrix to the given coordinate. Parameters ---------- x: number or ndarray The x coordinates y: number or ndarray The y coordinates z: number or ndarray The z coordinates affi...
b940c98da65a61cd46d2ad85ec33c791619341a0
3,639,463
from scipy.ndimage import binary_dilation def binary_dilation_circle(input, radius): """Dilate with disk of given radius. Parameters ---------- input : array_like Input array radius : float Dilation radius (pix) Returns ------- TODO """ structure = binary_disk...
c769b3aa652dc960cdd62dd19524d12f20e8b2bc
3,639,464
def square_valid(board: Board, n: int, pawn_value: int, x: int, y: int) -> bool: """Check if the square at x and y is available to put a pawn on it.""" return (coordinates_within_board(n, x, y) and square_playable(board, pawn_value, x, y))
725f65e64a8570e7483f103f0bf669cef3d7f1ef
3,639,465
def epb2jd(epb): """ Besselian epoch to Julian date. :param epb: Besselian epoch. :type epb: float :returns: a tuple of two items: * MJD zero-point, always 2400000.5 (float) * modified Julian date (float). .. seealso:: |MANUAL| page 76 """ djm0 = _ct.c_double() djm = ...
c5a9bcb422ab34ba0875d152cf8c39dda898e68b
3,639,466
def one_hot_decision_function(y): """ Examples -------- >>> y = [[0.1, 0.4, 0.5], ... [0.8, 0.1, 0.1], ... [0.2, 0.2, 0.6], ... [0.3, 0.4, 0.3]] >>> one_hot_decision_function(y) array([[ 0., 0., 1.], [ 1., 0., 0.], [ 0., 0., 1.], ...
a6eecff684ab926a46d746ca9c18e6b098308286
3,639,467
def combine_incomes(toshl_income, excel_income): """ Combines two data sources of incomes: toshl incomes and incomes from cashflow excel. :param toshl_income: Preprocessed dataframe of toshl incomes (after cleaning and splitting) :param excel_income: Raw excel income data :return: Total income data ...
31efb2d7b7420f3c71fcb12876cdc09d7ff748ec
3,639,468
def generate_k(data_set, k): """ Given `data_set`, which is an array of arrays, find the minimum and maximum for each coordinate, a range. Generate `k` random points between the ranges. Return an array of the random points within the ranges. """ centers = [] dimensions = len(data_set[0]) min_max = defaultdict(...
1fd4eb6a825a0ca2b8e6b8200081ecfded351c7d
3,639,469
import requests def __ping_url(url: str) -> bool: """Check a link for rotting.""" try: r = requests.head(url) return r.status_code in ( requests.codes.ok, requests.codes.created, requests.codes.no_content, requests.codes.not_modified, ) ...
e680cec006127bbe889dcab0291be3149f30d10e
3,639,470
def get_all_list_data(): """ Handles the GET request to '/get-all-list-data'. :return: Json with all list data """ conn = get_db() all_types = TypeDataAccess(conn).get_types(False) all_tags = TagDataAccess(conn).get_tags() all_groups = ResearchGroupDataAccess(conn).get_research_groups(F...
4a4a942e054d301f936ae7993b04aff6c554f91c
3,639,471
def truncate_range(data, percMin=0.25, percMax=99.75, discard_zeros=True): """Truncate too low and too high values. Parameters ---------- data : np.ndarray Image to be truncated. percMin : float Percentile minimum. percMax : float Percentile maximum. discard_zeros : ...
c9f56e593255ae6261b6f709b725cc952accc884
3,639,472
def obtain_dcdb_to_drugbank(biana_cnx, unification_protocol, output_pickle_file): """ Obtain a dictionary {dcdb : drugbank} """ up_table = return_unification_protocol_table(biana_cnx, unification_protocol) query = ('''SELECT DC.value, DB.value FROM externalEntityDCDB_drugID DC, {} U1, {} U2, exter...
02b9d5b6ddb29974d551123e7bb12a7a6aca3ca4
3,639,473
def duo_username(user): """ Return the Duo username for user. """ return user.username
92b2bfd5f6f3027787db493880139a8564597946
3,639,474
import random def random_number_list(data=[]): """ Add random number between 0 and 9 (both inclusive) to a list """ for i in range( 0, list_length ): # append a random int to the data list data.append( random.randint(0, 10)) return data
5a04409a40e1e65216579056f95024269da1fc5a
3,639,475
def _matrix_method_reshape(df: pd.DataFrame) -> pd.DataFrame: """ Reshape df for matrix method and deal with missing values. We first drop columns which contain all missing values, transpose the dataframe and then fill the remaining missing values with zero, to deal with missing items in some period...
64989a6c61d1d891a3190cc1f6a36c98cf562775
3,639,476
import glob import os import csv def orbitrap(file_path): """Import Orbitrap data from XCalibur export. Designed for scan by scan Orbitrap data. Original export of example data performed by Cech lab @ UNCG. Example data in MS_data external in Cech directory """ headers = ["scan", "rt", "mz", "drift", ...
3d627faac3988451e5dd8287dfe8487c2efc3897
3,639,477
import warnings def sim_bursty_oscillator(T, Fs, freq, prob_enter_burst=.1, prob_leave_burst=.1, cycle_features=None, return_cycle_df=False): """Simulate a band-pass filtered signal with 1/f^2 Input suggestions: f_range=(2,None), Fs=1000, N=1001 Paramet...
ea408f91f6160114f0077bd441ea049f848d2da1
3,639,478
def visualize_percent_diff(df): """Creates a visualization of difference in percentage of tweets of a topic across the entire US and returns the mean sentiment felt about the topic across the entire US Parameters: ----------- df: pd.DataFrame dataframe containing all tweets. Must conta...
d3f3404e5695a0191580f3df20eaf4c824d3e436
3,639,479
import six import inspect def basic_compare(first, second, strict=False): """ Comparison used for custom match functions, can do pattern matching, function evaluation or simple equality. Returns traceback if something goes wrong. """ try: if is_regex(second): i...
ee16806fd78f46c2bcf01a5263f6d0210c22f32a
3,639,480
def parse_line(line,): """Return a list of 2-tuples of the possible atomic valences for a given line from the APS defining sheet.""" possap = [] for valence, entry in enumerate(line[4:]): if entry != "*": possap.append((valence, int(entry))) return possap
d27ed66cb35084c9927cae8658d7ea8a421c69a4
3,639,481
def first_order_moments(X, min_words=3): """First-Order Moments Generate first order Moment of document-word frequency matrix. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Matrix of Document-word frequency. `n_samples` is the number of do...
b3105e50a3cf69b3dda62dfc07764ae8539ebc8f
3,639,482
from datetime import datetime def dashboard(): """Получить статистику по сайту""" user = get_user_from_request() if not user.is_admin: return errors.no_access() users = User.select().count() d = datetime.datetime.now() - datetime.timedelta(days=7) active_users = User.select().where(...
05363fd27ee6980258b7ea015a81e644799c5baa
3,639,483
def dct(f, axis=-1): """ Compute the Discrete Cosine Transform over the specified axis. :param f: The input array. :param axis: Axis along which the DCT is computed. The default is over the last axis. :return c: The computed DCT. """ # Size of the input along the specified axis. ...
3e6cd65a3088d948fb81f61c25b2f590facb8351
3,639,484
from pathlib import Path def get_create_data_dir(): """Get the data directory. When the directory does not exist it is created. """ # Calculate the dataset data dir data_dir = Path(get_data_dir()).expanduser() dataset = _dataset_settings['name'] dataset_dir = data_dir / dataset # Ens...
8fd7631504ab7b926f1f6b533d0fdabaa8cad592
3,639,485
def interpolate_bezier(points, steps=100, **kwargs): """Generates an array of waypoints which lie on a 2D Bezier curve described by n (x, y) points. The trajectory is guaranteed to include the start and end points though only on (x, y, z) axes. The curve generated is of the nth degree, where n = len(points...
403d8f6242947bc240920ea15ae6c0d72ec2d547
3,639,486
def _EAMS(track, Xmin=0.55, i0=12): """ Early-Age Main Sequence. Without this, the low-mass tracks do not reach an EEP past the ZAMS before 15 Gyr. """ i_EAMS = _IorT_AMS(track, Xmin, i0) return i_EAMS
4cde6c1e598366bbaf25ab98d2ec14b9f5a34d86
3,639,487
import uuid def neighboring_pairs(dataset, text_key='text', reuse_sentences=True): """Create a dataset consisting of neighboring sentence pairs. The input examples should have a key text_key associated with a tf.string value. The output examples have keys 'first' and 'second'. We only take sentence pairs...
815b04be745344e3a527c1eb07d22fd31bfffd94
3,639,488
def decode(tokenizer, token): """decodes the tokens to the answer with a given tokenizer""" answer_tokens = tokenizer.convert_ids_to_tokens( token, skip_special_tokens=True) return tokenizer.convert_tokens_to_string(answer_tokens)
4bbb58a6a0ed0d33411f9beee35ad0f2fb43698f
3,639,489
def davis_jaccard_measure(fg_mask, gt_mask): """ Compute region similarity as the Jaccard Index. :param fg_mask: (ndarray): binary segmentation map. :param gt_mask: (ndarray): binary annotation map. :return: jaccard (float): region similarity """ gt_mask = gt_mask.astype(np.bool) fg_mask =...
96e6c47cd3b8d71206f9cf903b3827840803cf10
3,639,490
def extract_logits(logits = None, seq_pos = None): """ Args logits: Tensor(batch_size,seq_length,vocab_size) e.g.(8,1024,50257) seq_pos: list(batch_size) Return: output_logits: Tensor(batch_size,1,vocab_size) extract the Specified logit according to the seq_pos list . """ ...
008931ca8677461de947d7a365521e1e72c53866
3,639,491
import subprocess def CollectSONAME(args): """Replaces: readelf -d $sofile | grep SONAME""" toc = '' readelf = subprocess.Popen(wrapper_utils.CommandToRun( [args.readelf, '-d', args.sofile]), stdout=subprocess.PIPE, bufsize=-1, ...
dda042430ec1acfb82f6622e0d3786f6be44f2f4
3,639,492
def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True): """ Pads a rectangle by the specified values on each individual side, ensuring the padded rectangle falls within the specified bounds. The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). """ # Unpack th...
032cafd373b59b725b8e2e28ba91e263ccae6e12
3,639,493
def gcs_csv_to_table(full_table_id: str, remote_csv_path: str) -> Table: """ Insert CSV from Google Storage to BigQuery Table. :param full_table_id: Full ID of a Google BigQuery table. :type full_table_id: str :param remote_csv_path: Path to uploaded CSV. :type remote_csv_path: str :returns...
bb0713848249e2eb4e6b89db652152c6485af0ee
3,639,494
import argparse def _get_client(args: argparse.Namespace) -> NodeClient: """Returns a pycspr client instance. """ return NodeClient(NodeConnectionInfo( host=args.node_host, port_sse=args.node_port_sse ))
0eff36345d99c50a6d8298021b9f875dd17a2afe
3,639,495
import math def turn_xyz_into_llh(x,y,z,system): """Convert 3D Cartesian x,y,z into Lat, Long and Height See http://www.ordnancesurvey.co.uk/gps/docs/convertingcoordinates3D.pdf""" a = abe_values[system][0] b = abe_values[system][1] e2 = abe_values[system][2] p = math.sqrt(x*x + y*y) long = math.atan(...
304facd429083032e611f2f9aca09b298a40a48b
3,639,496
def _TileGrad(op, grad): """Sum reduces grad along the tiled dimensions.""" input_shape = array_ops.shape(op.inputs[0]) # We interleave multiples and input_shape to get split_shape, # reshape grad to split_shape, and reduce along all even # dimensions (the tiled dimensions) to get the result # with shape in...
21294667ac3a31082cc2a3d09120330ce3ec1564
3,639,497
def obj_spatial_error_sum_and_naturalness_jac(s, data): """ jacobian of error function. It is a combination of analytic solution for motion primitive model and numerical solution for kinematic error """ # Extract relevant parameters from data tuple. # Note other parameters are used for calli...
e0f57a88e3b490abc8eb9dbc636701c4a06ffc05
3,639,498
from datetime import datetime def today(): """Ritorna il giorno di oggi in formato YYYYMMDD""" today = datetime.date.today() return today.strftime("%Y%m%d")
fdf9c83153667fb3324f31893bf3721566dea4d3
3,639,499