content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _log_add(x, y): """ Add x and y in log space. """ if x == -np.inf: return y if y == -np.inf: return x return np.max([x, y]) + np.log1p(np.exp(-abs(x - y)))
ff4ab48c9ddb446f17456049d6f5317306cdc7a2
3,627,470
import asyncio def query_by_name(first, last, jurisdictions=None, timeout=None): """Query jurisdictions with an inmate name. :param first_name: Inmate first name to search. :type first_name: str :param last_name: Inmate last name to search. :type last_name: str :param jurisdictions: List of...
effff7fd1b75baea0a65b4a21e87894a39d1f783
3,627,471
import ray import psutil import time def test_basic(ray_start_with_dashboard): """Dashboard test that starts a Ray cluster with a dashboard server running, then hits the dashboard API and asserts that it receives sensible data.""" assert (wait_until_server_available(ray_start_with_dashboard["webui_url"]) ...
c31926cd6ce1976fec2adcdebebfe8c8b8a0bf99
3,627,472
def arc_length_3point(A, B, C): """ Returns length of arc defined by 3 points, A, B and C; B is the point in between """ ### Meticulously transcribed from # https://develop.openfoam.com/Development/openfoam/-/blob/master/src/mesh/blockMesh/blockEdges/arcEdge/arcEdge.C p1 = np.asarray(A) p2 = np.asa...
aa51863f08d6b4d22e8321252506bf575861e191
3,627,473
def dsymv(alpha, A, X, beta, Y, Uplo=CblasLower): """ returns y' This function computes the matrix-vector product and sum \M{y' = S{alpha} A x + S{beta} y} for the symmetric matrix A. Since the matrix A is symmetric only its upper half or lower half need to be stored. When Uplo is CblasUpper th...
d4bb0aed936dbf3e0d94b8e76f9b1ef24f5536a7
3,627,475
def view_categories(request): """View category posts view""" categories = Category.objects.all() ret_dict = { 'categories': categories, 'view_rss': 'rss/categories.xml', 'current_nav': 'categories', } ret_dict = __append_common_vars(request, ret_dict) return render(requ...
22cf5ef4e8c7a9aed13f5b528c44f2ecb9c93979
3,627,476
def zfill_to_collection_size(index: int, collection_size: int) -> str: """ Prepends amount of zeroes required for indexes to be string-sortable in terms of given collection size. Examples: for 10 items prepends up to 1 zero: 1 -> "01", 10 -> "10" for 100 items prepends up to 2 zeroes: 7 -> "...
df086ba9c4485dd0073c9a9b4485cb0c0d423859
3,627,477
def _make_grid_spec(storage) -> GridSpec: """Make a grid spec based on a storage spec.""" assert 'tile_size' in storage crs = CRS(storage['crs']) return GridSpec(crs=crs, tile_size=[storage['tile_size'][dim] for dim in crs.dimensions], resolution=[storage['resolu...
37d3b7cd005e4bf8e0d813bdefb0ef367b80dd6c
3,627,479
def gaussian_2d_cylind(shape, center, resolution, scale, sigma=1, min_range_rho=0): """Generate gaussian map. Args: shape (list[int]): Shape of the map. [y, x] sigma (float): Sigma to generate gaussian map. Defaults to 1. Returns: np.ndarray: Generated gaussian map. [rh...
6490bdb3edd7930ac6d0c899338d3487263c8daf
3,627,480
from datetime import datetime async def create_specific_guid(guid: str, data: GuidIn): """ Create a record w/ a guid specified in the path. Also cleans up expired records & caches the new record. Raises an exception if you try to overwrite an existing record. """ try: guid = validate...
67d1a3615e54cd330bf22e8846987b71360fde0a
3,627,481
def partition(predicate, values): """ Splits the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item...
27184fd908ab2d214db86b612e2e5cbec9393a07
3,627,482
def get_colors(color='ALL'): """ get color palette as a dictionary """ if color == 'ALL': return color_dict['palette'] return color_dict['palette'][color]
719fb6ce8a335c80694eb0418eace8ca4b7bc397
3,627,483
def avoid_line_too_long(pretty_html_text): """ detect any line with more than 998 characters """ lines = pretty_html_text.split('\n') new_lines = [] for line in lines: line_length = len(line) if line_length >= 998: # Cut the line in several parts of 900 characters ...
610021c6ee52e0b8cc0f20951383b9f559ce0f59
3,627,484
def stringify_tags(tags, human_readable=False): """ 格式化 Beancount 标签列表 """ if human_readable: if len(tags) == 0: return _('无') return ', '.join(f'#{t}' for t in tags) return ' '.join(f'#{t}' for t in tags)
c4b7fce339754fbd437972c8de4e3cc38ad9d6f5
3,627,485
from datetime import datetime def is_friday(): """判断是否是周五""" return datetime.date.today().weekday() == 4
b8536933c973677366e3b19c19cb57cbc33980c6
3,627,486
def _parse_exclude_images_commands(commands, experiments, reflections): """Parse a list of list of command line options. e.g. commands = [['1:101:200'], ['0:201:300']] or commands = [[101:200]] allowable for a single experiment. builds and returns a list of tuples (exp_id, (start, stop)) """ ...
e1decbcce826d1fe32a9b5c98b745f43e754a3b4
3,627,487
def thomson_spec_series(eleckineng, photeng, T, as_pairs=False): """ Thomson ICS spectrum of secondary photons by series method. Parameters ---------- eleckineng : ndarray Incoming electron kinetic energy. photeng : ndarray Outgoing photon energy. T : float CMB tempera...
a261aa1c344404f71c8a17712865276e28fc5831
3,627,488
def voxel_grid_sampling(coords: np.ndarray, voxel_size: float) -> np.ndarray: """Voxel grid sampling Args: coords: coords (N, C) voxel_size: voxel grid size Returns: samples: sample coords (M, C) """ N, C = coords.shape # get voxel indices. indices_float = coor...
145af0fc17887536ee3ebe466a3920d1abd717e9
3,627,489
def compute_skewness(data): """ Skewness of the data (per channel). Parameters ---------- data : ndarray, shape (n_channels, n_times) Returns ------- output : ndarray, shape (n_channels,) """ ndim = data.ndim return stats.skew(data, axis=ndim - 1)
563f7a10d882b23e9cbb717cae4b9f251de0fd11
3,627,490
def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): """Compute the one-dimensional FFT for real input. The returned array contains the positive frequency components of the corresponding :func:`fft`, up to and including the Nyquist frequency. Args: x (cupy.ndarray): Array ...
4ba7bf16788f7587e3a7076612d6a27d75749c7a
3,627,491
from typing import List from typing import Dict from typing import Any def from_protos( proto_list: List[american_option_pb2.AmericanEquityOption], american_option_config: "AmericanOptionConfig" = None ) -> Dict[str, Any]: """Creates a dictionary of preprocessed swap data.""" prepare_fras = {} for a...
20f7bb76873068744b6652966884c62650e1c8a6
3,627,494
def create_operator(key, value, context): """ Create operator instance along with its arguments Args: key: operator name value: operator arguments context (Dict): Python dictionary holding all imported modules Returns: Tasrif pipeline...
89a1a8603818faae1704d6e74ff2bc5b026a1fef
3,627,496
def est_positif_non_nul(valeur: any): """Indique si la valeur fournie est un entier positif non nul.""" if valeur is not None: if isinstance(valeur, int): return valeur > 0 if isinstance(valeur, float) and valeur.is_integer(): return valeur > 0 return False
03e799f73cfc3e112d61d638d6c120ede049991d
3,627,499
def cmd_issuer_hash(cert): """Returns hash of certificate issuer. """ return cert.get_issuer().hash()
d35d35c39ba9c33c5b0015bb9f4d4ddf433cd71d
3,627,500
def linearly_enhancing_details(alphas, numOfScales=2, window_scale=3): """ :param alphas: the high frequency component of the image calculated with Shearlet transformation. i * j * (kl) array, where i, j are equal to the height and width of the original image, kl is ...
bdba70e9b8d63da29c8a87c09857f6698dcd12fb
3,627,501
def strip_c(buf, dia): """This is the ugliest python function I've ever written and I'm ashamed that it exists. Can you tell that it's an almost line for line translation of a C program? The two embedded functions were macros. """ pos = bytes(buf, 'ascii', errors='replace') single_q = double_q =...
0d23d9826fdbba09b06d3a866d54bcda13d43509
3,627,502
def map_bool(to_bool) -> bool: """Maps value to boolean from a string. Parameters ---------- to_bool: str Value to be converted to boolean. Returns ------- mapped_bool: bool Boolean value converted from string. Example ------- >>> boolean_string = "True" # can ...
4e3bb175f653174a56cb6ddc72ba7bcc56755826
3,627,503
def _format_koff_text(properties, timeunit): """Format text for koff plot. """ tu = "ns" if timeunit == "ns" else r"$\mu$s" text = "{:18s} = {:.3f} {:2s}$^{{-1}} $\n".format("$k_{{off1}}$", properties["ks"][0], tu) text += "{:18s} = {:.3f} {:2s}$^{{-1}} $\n".format("$k_{{off2}}$", properties["ks"][1], t...
c657173779a7e63c149de364c3b5d3dfb27b4618
3,627,504
def annotate_heatmap(im, data=None, valfmt="{x:.2f}", textcolors=("black", "white"), threshold=None, **textkw): """ A function to annotate a heatmap. Parameters ---------- im The AxesImage to be labeled. data Data used to annotate. If No...
2409be396c214db7f9fb7e31254bbc6ebe3aca33
3,627,505
def fmt_val(val, shorten=True): """Format a value for inclusion in an informative text string. """ val = repr(val) max = 50 if shorten: if len(val) > max: close = val[-1] val = val[0:max-4] + "..." if close in (">", "'", '"', ']', '}', ')'): ...
c8a10f187d971f8b3f4222549375642b6c12a6a6
3,627,506
def get_rms_radius(ts): """ Calculate the RMS radius at the different iterations of the timeseries. """ r = [] for iteration in ts.iterations: x, w = ts.get_particle( ['x', 'w'], iteration=iteration ) r.append( np.sqrt( np.average( x**2, weights=w ) ) ) return( 1.e-6*np.array(r) ...
f5d7fcbb90e2f29d7e2a38427f7fdb5aea53c962
3,627,508
def encode_function_data(function=None, *args): """Encodes the function call so we can work with an initializer. Args: initializer ([brownie.network.contract.ContractTx], optional): The initializer function we want to call. Example: `box.store`. Defaults to None. args (Any, opt...
645f663e29672e96ce1cd18c727c4ed56b7d93db
3,627,509
def analyzeTarget(obj, targetPath): """ This function is used (more during the development cycle than in the runtime application) to analyze the difference between the vertex positions of a mesh object and those recorded in a file on disk. The result is a representation of each vertex displacemen...
2534ddf77ae356fbd189052890ab5e3c6b2b1dc0
3,627,510
def generate_ranklist(data, rerank_lists): """ Create a reranked lists based on the data and rerank documents ids. Args: data: (Raw_data) the dataset that contains the raw data rerank_lists: (list<list<int>>) a list of rerank list in which each el...
3ad3431efff6a7ad81b649a8654d5ec30184de74
3,627,511
def is_merge_brances_has_written(from_branch, to_branch, merge_msg="auto merge"): """ returns True, if merge is successful and it has modified some untracked_files return False, if there is nothing to merge """ for line in git("merge", from_branch, to_branch, "-m", merge_msg, _iter=True, _tty_out=F...
59d4580127d4627b5edc7478d7588710874ff693
3,627,512
def desktop_extra_assigner(self, user): """Assign the extra packages name of the selected desktop. Arguments --------- user: "Dictionary containing user's answers" Returns ------- "String containing question for the desktop extras" """ choice = ['Gnome extra', ...
529910c70e7dfd83ab58a4937668d35607457271
3,627,513
from typing import Dict from typing import Tuple from typing import List def _get_openmm_parameters( force: openmm.Force, ) -> Dict[Tuple[int, ...], List[Tuple[unit.Quantity, ...]]]: """Returns the parameters stored in a given force. Args: force: The force to retrieve the parameters from. Re...
12178a67b060f85da83929465a359d3f377c9a90
3,627,514
def create_scene(info, color="cpk", scale=1.0, show_bonds=False): """Create a fresnel.Scene object. Adds geometries for particles, bonds, and box (or boundingbox). Parameters ---------- info : list List containing N, types, typeids, positions, N_bonds, bonds, box color : str, default "...
1be9e76c7eb1379a516fbdc1bace26891648f505
3,627,515
from bs4 import BeautifulSoup def crawl_malware_domains(url): """ This function crawls the malware domain indicator and returns all the dataset links to be downloaded and scraped later. @param url (string) url of the indicator web page @return """ print('Crawling site: ...
93c518d7db9140951b6133b8157e87e0a7205577
3,627,516
import asyncio def ip_address_middleware(get_response): """A Middleware to attach the IP Address and if its Routable to the request object. """ if asyncio.iscoroutinefunction(get_response): async def middleware(request): client_ip, is_routable = get_client_ip(request) ...
e31213ef515d9b747e77a9b5f257ee6b394d8526
3,627,517
from datetime import datetime def parse_datetime(datetime_str: Text) -> datetime.datetime: """ form string parse datetime """ for str_format in cfg.datetime_str_formats: try: datetime_object = datetime.datetime.strptime(datetime_str, str_format) return datetime_object e...
860c24a80d8e8f555f554d4343f7f37357a0673e
3,627,518
import re import logging def get_gpu(): """Returns video device as listed by WMI. Not cached as the GPU driver may change underneat. """ wbem = _get_wmi_wbem() if not wbem: return None, None _, pythoncom = _get_win32com() dimensions = set() state = set() # https://msdn.microsoft.com/library/aa...
cb2ca5c26d9df4788d1f5596922ab97107649578
3,627,519
def findall(node, filter_=None, stop=None, maxlevel=None, mincount=None, maxcount=None): """ Search nodes matching `filter_` but stop at `maxlevel` or `stop`. Return tuple with matching nodes. Args: node: top node, start searching. Keyword Args: filter_: function called with every...
f7b8d5694c0d17de1476145aa8c603c3f7074bca
3,627,520
from typing import Union from typing import Iterable from typing import Mapping from typing import Optional from typing import Hashable def concat( objs: Union[ Iterable[FrameOrSeriesUnion], Mapping[Optional[Hashable], FrameOrSeriesUnion] ], axis=0, join="outer", ignore_index: bool = False...
5574293208e2b1b7a61733ffd48af04be55c639e
3,627,521
import random import string def create_hash(): """ Creates a unique hash for each URL. :return: Hash """ _hash = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) if UrlShortenModel.find_by_hash(_hash): create_hash() return _hash
36467353abe2a6f59746ff4bb403de74b2e6f2d5
3,627,522
def str_or_list_like(x): """Determine if x is list-list (list, tuple) using duck-typing. Here is a set of Attributes for different classes | x | type(x) | x.strip | x.__getitem__ | x.__iter__ | | aa | <class 'str'> | True | True ...
5ea7a6ff90f702c766401d0a973ac02347c66ade
3,627,523
from typing import Optional def get_carrier_gateway(carrier_gateway_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCarrierGatewayResult: """ An example resource schema demonstrating some basic constructs and validation rules. :param str carr...
ab70ed301bf14e47347a7d260f68594f6507c67b
3,627,524
def _bootstrap_dm(ids, dm, new_names=None): """Makes a bootstrapped distance matrix Parameters ---------- ids: array-like A list of ids in the distance matrix. These do not have to be unique. dm : DistanceMatrix The distance matrix object to resample. new_names: array_li...
8f1ad0203f43a5033d83e21fbb7eb3d6082e0d57
3,627,525
def ai(listAI, listHuman, list_all): """ AI计算落子位置 """ if len(listHuman) == 0: next_point[0] = 7 next_point[1] = 7 else: #listAI = listai #listHuman = listhuman for i in range(len(listAI)): listAIAndHuman.append(listAI[i]) for i in range(len(listHuman)): listAI...
869f77276f0a4ed92fd1be820329e44a750bb568
3,627,526
import itertools def list_as_range_strings(values): """ Format a list of single-range strings from a list of values; sorts input. :param values: :return: """ values.sort() # make sure numbers are consecutive value_groups = itertools.groupby(values, lambda n, c=itertools.count(): n - next(...
d4b8da4a1d6c501705cade252cff11eb7c898a9a
3,627,528
def squared_distance(v: Vector, w: Vector) -> float: """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2""" return sum_of_squares(subtract(v, w))
889f77eebc691d4d1f0f49e357ae06506f0eb5e0
3,627,529
def fp2tan(xfp, yfp): """ Convert focal plane to tangent plane coordinates Args: xfp, yfp: CS5 focal plane coordinates in mm return xtan, ytan where xtan=sin(theta)*cos(phi), ytan=sin(theta)*sin(phi) """ #- phi=0 aligned with +xtan = -RA = +HA = +xfp phi = np.arctan2(yfp, xfp) ...
97bbc6730a9321a18cbf0d60ab0393ee16a04d42
3,627,530
def bounding_box(fixtures, pose): """Get the axis aligned bounding box of the fixtures Args: fixtures (iterable): an iterable containing the fixtures to bound pose (tuple): an (x, y, theta) tuple. All fixtures will be transformed by this pose before the bounding box is c...
eaf8f6cfca0e97550a8579e7db3b99fd8ed8306f
3,627,531
def dir_key(dir_name): """ Used for sorting """ p = parse_dir(dir_name) if p is None: return 0 abits, wbits, r = p return 1000*abits + 100*wbits + int(100*r)
f8fc4af4f3fe1db6bf7a8e18d3e0fa9041729a31
3,627,532
def get_impact_from_xmlfile(element): """Gets the impact value of a step/testcase/suite from the testcase.xml/testsuite.xml/project.xml file """ return TCOBJ.get_impact_from_xmlfile(element)
9925c26956aaeb17672dabf5bb124830e0f2d32d
3,627,533
def readlist(infile): """Read each row of file as an element of the list""" with open(infile, 'r') as f: list_of_rows = [r for r in f.readlines()] return list_of_rows
50ea79f3c64e5e90a0f8b3bfd4cd8108304d57b2
3,627,534
def is_indvar(expr): """ An individual variable must be a single lowercase character other than 'e', followed by zero or more digits. :param expr: str :return: bool True if expr is of the correct form """ assert isinstance(expr, string_types), "%s is not a string" % expr return INDVAR_R...
4e9bd018da3950adb68d93ec36bdfafb8a7219c5
3,627,535
from scipy import signal def estimate_ringing_samples(system, max_try=100000): """Estimate filter ringing. Parameters ---------- system : tuple | ndarray A tuple of (b, a) or ndarray of second-order sections coefficients. max_try : int Approximate maximum number of samples to try....
689d1afb7fe99136fa3741099cb68af11151f437
3,627,536
def read_popularity(path): """ :param path: a path of popularity file. A file contains '<id>,<rank>' rows. :return: a set of popularity object ids """ ids = set() for line in open(path): try: ident = int(line.split(",", maxsplit=1)[0]) except (AttributeError, IndexErr...
a97f20b129bd7849a4bf9a91d40c23ad664b500b
3,627,537
def classify(tree, input): """classify the input using the given decision tree""" # if this is a leaf node, return its value if tree in [True, False]: return tree # otherwise find the correct subtree attribute, subtree_dict = tree subtree_key = input.get(attribute) # None if input is mi...
66b7558ac8658aa83b1796c17a637daa5a2309bb
3,627,538
def fmt_null_obj(obj): """将空对象转为空字符串(obj) \t\t@param: obj 传入对象 """ if not __check_null(obj): return '' if type(obj) in (list, tuple): # Change 'None' to '' obj_new = __fmt_null_ListTuple(obj) elif type(obj) == dict: # Change None's value to '' obj_new = __fmt_null...
fc52615d2db94485c9431a89c18c1b93fe6c7cb0
3,627,539
def email_loeschen(request): """ Dekrementiert die Anzahl der Formulare für eine E-Mail in der mitgliedBearbeitenView oder mitgliedErstellenView nach Löschen eines Formulars. Aufgaben: * Erfassen der Anzahl der E-Mails * Rechteeinschränkung: Nur angemeldete Nutzer können den Vorgang auslösen ...
46b6dd6d0e4728563e6f7e5530a9f1ebefb28141
3,627,540
def extendDynaForm(dynaform, dynainclude=None, dynaexclude=None, dynaproperties=None, append=False): """Extends an existing dynaform. If any of dynainclude, dynaexclude or dynaproperties are not present, they are retrieved from dynaform (if present in it's Meta class). While it is rather u...
656d0d86ffb5bb2f9141f1f5e2ecf616d9c56535
3,627,541
def _parse_write_checkpoint(write_checkpoint): """ Returns the appropriate value of ``write_checkpoint``. """ if isinstance(write_checkpoint, bool): if not write_checkpoint: write_checkpoint = "NONE" else: write_checkpoint = "ALL" if write_checkpoint.upper() not in ("...
752db50a4782fb13584ee0daf691f37edcb095eb
3,627,542
def compute_shape_features(df_samples, sig, center='trough'): """Compute shape features for each spike. Parameters --------- df_samples : pandas.DataFrame Contains cycle points locations for each spike. sig : 1d array Voltage time series. center : {'trough', 'peak'} Cent...
54605acbfa0b96aa1430401cc3aa3c0a2a2a1626
3,627,543
def uCSIsCyrillic(code): """Check whether the character is part of Cyrillic UCS Block """ ret = libxml2mod.xmlUCSIsCyrillic(code) return ret
e099fce1c26940bc7e5facc8ef783da5d9478126
3,627,544
def ping(): """ Send a ping query --- tags: - ping parameters: - in: query name: time description: timestamp required: false type: integer - in: states name: states description: states required: false type: string responses: 200: description: pong received """ ret...
21acff6108a07bf5f982260409843dc05662aa31
3,627,545
import string def names_to_usernames(names): """ Take the given list of names and convert it to usernames. "John Doe" -> "john.doe" Each name is stripped before conversion, then split by spaces. If the name contains anything except letters and spaces, raise an exception. If duplicate names...
0156f8402541e64dc1ed2b62d21bfcfbda55f167
3,627,546
def measurement_chain_with_equipment() -> MeasurementChain: """Get a default measurement chain with attached equipment.""" source = SignalSource( "Current measurement", output_signal=Signal(signal_type="analog", units="V"), error=Error(Q_(1, "percent")), ) ad_conversion = SignalT...
e9a673a37baf07cbe5a6e284755c66d9bf51e5c9
3,627,547
def get_all(): """ Get All Profiles --- /api/users/profiles_all: get: summary: Get all profiles Function security: - APIKeyHeader: [] tags: - Profile responses: '200': description: Returns all profiles '400': description: Us...
ae3f780a045b4c3d5b0430c38b411ead8de8fb13
3,627,548
import numpy def compose_matrix(scale=None, shear=None, angles=None, translate=None, perspective=None): """Return transformation matrix from sequence of transformations. """ M = numpy.identity(4) if perspective is not None: P = numpy.identity(4) P[3, :] = perspective...
95ae6e3ec348a49c15607e5e9e1f35c0a393b66f
3,627,549
def value_to_cpp(type_, value): """ Convert a python value into a string representing that value in C++. This is equivalent to primitive_value_to_cpp but can process arrays values as well Warning this still processes only primitive types @param type_: a ROS IDL type @type type_: builtin.str ...
c771656e3163efb1c077b22a1832a7e78440f132
3,627,550
def make_reference(x, crop_size, ref_type): """ ref_type: {'bmf', 'bt'} bmf: Ball-Mid-Frame, normalize by where the ball is at mid-frame tb: Track-Ball, normalize by where the ball is at each frame """ print('Running DataUtils:make_reference') assert(crop_size[0] % 2 == ...
10627c3c1174129ed1e90e44d348a87b1a5dacdf
3,627,551
def vessel_tip_coupling_data_to_str(data_list): """A list of vessel tip data elements is converted into a string.""" s = [] for v in data_list: s.append('VesselTipData(') s.append(' p = Point(x={}, y={}, z={}),'.format(v.p.x, v.p.y, v.p.z)) s.append(' vertex_id = {},'.format(v.vert...
6768afa9497e5343bc20736a963d81c7ec298867
3,627,552
def user_labels_insert(*args): """ user_labels_insert(map, key, val) -> user_labels_iterator_t Insert new (int, qstring) pair into user_labels_t. @param map (C++: user_labels_t *) @param key (C++: const int &) @param val (C++: const qstring &) """ return _ida_hexrays.user_labels_insert(*args)
9c255306ee2e42e947e4f9d939681a79e090e1d4
3,627,553
def RequestReasonInterceptor(): """Returns an interceptor that adds a request reason header.""" return HeaderAdderInterceptor(_GetRequestReasonHeader)
c85b4b1c2a4e893610df17bdfabda7effbfeed54
3,627,554
from typing import Union from typing import Dict from typing import Set from typing import Any def mem_usage_pd(pd_obj: Union[pd.DataFrame, pd.Series], index: bool = True, deep: bool = True, details: bool = True) -> Dict[str, Union[str, Set[Any]]]: """ Calculate the memory usage of a pandas o...
793a75301da3bb7e9ff784db55a26afdc347180c
3,627,555
import torch def gumbel_binary(theta, temperature=0.5, hard=False): """theta is a vector of unnormalized probabilities Returns: A vector that becomes binary as the temperature --> 0 """ u = Variable(torch.rand(theta.size())) z = theta + torch.log(u / (1 - u)) a = F.sigmoid(z / temperat...
530eff4fb887b863c65c2e2a669953f49b0b83db
3,627,557
import re def price_quantity_us_number(price): """Extract the numeric quantity of the price, assuming the number uses dot for decimal and comma for thousands, etc.""" p = re.sub('[^0-9.]', '', price.strip()) return p
9e35d8096bd3edfe80b6fae6ab0641107828a50b
3,627,558
import typing import re def build_global_regexes() -> typing.Dict[str, typing.Pattern]: """ Returns a list where each element is a tuple of ``(label, possible_regexes)``. """ nums = r'-?\d+' ip_atom = r'(({0})|({0}:)|(:{0})|({0}:{0})|({0}-{0})|(:))?'.format(nums) ip = r'^{0}(,{0})*$'.forma...
43ce3ef0b0bdd6afee39e1cb710272eab859e123
3,627,559
def _ratio_sample_rate(ratio): """ :param ratio: geodesic distance ratio to Euclid distance :return: value between 0.008 and 0.144 for ration 1 and 1.1 """ return 20 * (ratio - 0.98) ** 2
1cd2989937a992e2f558b01be6fadebc66c50782
3,627,561
def normalize_boolean(val): """Returns None if val is None, otherwise ensure value converted to boolean""" if val is None: return val else: return ensure_boolean(val)
c9cfb505fb4ace5c01ab06ff3c218cbb73cf915f
3,627,562
def make_braced_expr(tokens): """Make a braced expr from a recursive, nested list of tokens.""" result = "" for e in tokens[1:-1]: if isinstance(e, list): result += "".join([getattr(t, 'value', t) for t in flatten(e)]) else: result.append(e.value) contents = ''....
d928ae98b067bc79ac7284adffedd637cbeb750d
3,627,563
def basic_stats(G, area=None, clean_intersects=False, tolerance=15, circuity_dist="gc"): """ Calculate basic descriptive metric and topological stats for a graph. For an unprojected lat-lng graph, tolerance and graph units should be in degrees, and circuity_dist should be 'gc'. For a projected graph, ...
5f35239c7b5b572b39ce515d1a841d0e910d70fe
3,627,564
from typing import Counter def trip_finder(hand): """ Takes a 5-card hand, concats, only takes ranks If we get 3 of a kind only, returns list: [6, trip rank, 0, 0, 0, 0] """ cards = ''.join(hand)[::2] if Counter(cards).most_common(1)[0][1] == 3: if Counter(cards).most_common(2)[1][1] == 1: return [6, Coun...
42281d141bdb41e0c745610257cc4376a6262d64
3,627,565
def crossfadein(clip, duration): """ Makes the clip appear progressively, over ``duration`` seconds. Only works when the clip is included in a CompositeVideoClip. """ newclip = clip.copy() newclip.mask = clip.mask.fx(fadein, duration) return newclip
74c40f98c3c55069b132a306b2b6f6f763caccd4
3,627,566
import torch import time def get_feats(model, loader, logger, opt): """Obtain features and labels for all samples in data loader using current model. """ batch_time = AverageMeterV2('Time', ':6.3f') progress = ProgressMeter( len(loader), [batch_time], prefix='Test: ') # s...
91a053de5bbc188eb461fea10b2b650084eda8c6
3,627,567
from .mastercatalog import MasterCatalog def match(*args, verbose=True, threshold=0.036*u.arcsec): """ Find sources that match up between any number of dendrocat objects. Parameters ---------- *args : `~dendrocat.Radiosource`, `~dendrocat.Mastercatalog`, or `~astropy.table.Table` object ...
43cc2064a7f5cad7a421496f79a6f4549eb5a0ff
3,627,568
import re def show_user(func): """Register a function to be displayed to the user as an option""" global USER_FUNCTIONS try: key = re.search(r'\[(.+?)\]', func.__doc__).group(1) except AttributeError as e: key = func.__name__ print(e) USER_FUNCTIONS[key] = func retur...
1d9f0dd8217f7d493bed48a32c01453f7e1473b5
3,627,569
def check_balancing_time_gran(param_name, granmap, entity, comp='coarser', find_EC_=lambda x, y: y[-1]): """check if given granularity map specifies granularity appropriately as specified by c...
3e47918769fcdd770e09feca0ea1c281c8b7797a
3,627,570
def plot_integer_part(xs, ns, alpha, show=True): """Plot the integer part of real numbers mod alpha.""" fig = plt.figure() ax = plt.gca() xmin, xmax = alpha * (xs[0] // alpha), alpha * (xs[-1] // alpha) + alpha newxticks = np.linspace(xmin, xmax, int((xmax - xmin) // alpha) + 1) ax.xaxis.set_ma...
97107a6087f99fb9f6f39f58b26b0617a6f182fe
3,627,571
def array_to_sentence(vocab_dict, array: np.array, cut_at_eos=True): """ Converts an array of IDs to a sentence, optionally cutting the result off at the end-of-sequence token. :param array: 1D array containing indices :param cut_at_eos: cut the decoded sentences at the first <eos> :return: lis...
dd0fbe2426f429ef71325cfbebbe365c7e8a1cd7
3,627,572
import keras def make_time_scheme(dt, trend): """ Implémentation d'un schéma de RK4 sous forme de réseau de neurones """ state = keras.layers.Input(shape = trend.input_shape[1:]) # k1 k1 = trend(state) # k2 _tmp_1 = keras.layers.Lambda(lambda x : 0.5*dt*x)(k1) input_k2 = keras....
3777638ea910687d4e084133d0fb8c5268cb329a
3,627,573
def print_parameters(opt): """ Generate a string with the options pretty-printed (used in the --verbose mode). """ return str(cg.ParamBlock(opt, ''))
670b984d1cac8b0379d5200ca8ae1256935f0962
3,627,574
def compute_regularizer_fft(n, weight_tv, weight_l2): """Precompute 2D filter regularizer (total variation + L2) in Fourier domain. This function implements w^2 in eq. 23 of the paper: Fast Fourier Color Constancy, Barron and Tsai, CVPR 2017 https://arxiv.org/abs/1611.07596 Args: n: specifies the square...
74e481ca0517d984d443dafb04749ae68983e231
3,627,576
from pathlib import Path from typing import Optional import json async def read_data(*, file_path: Path) -> Optional[Box]: """Return the data read from file_path.""" if not file_path.is_file(): return None lock = FileLock(f"{file_path.as_posix()}.lck") with lock.acquire(): async with a...
0cb963cd42a199c18d71ff8e916269155e287cff
3,627,577
def savefacedata(request): """Save face data""" if request.method == "GET": return render(request, "savefacedata.html", {"form": FaceDataForm()}) else: try: fd = get_object_or_404(FaceData, user=request.user) form = FaceDataForm(request.POST, request.FILES, instance=f...
cf8d046ca5d754de96a2caa986cd506d4590c68b
3,627,578
import urllib def addToCal(url, date_from, date_end, summary): """ Add entry in calendar to period date_from, date_end """ vcal_entry = """BEGIN:VCALENDAR VERSION:2.0 PRODID:Pyvac Calendar BEGIN:VEVENT SUMMARY:%s DTSTART;VALUE=DATE:%s DTEND;VALUE=DATE:%s END:VEVENT END:VCALENDAR """ client = caldav.DAVC...
5d0914167ce26202f2ddf1b75550957798d55fb1
3,627,579
def SetIamPolicy(zone_ref, policy): """Set Iam Policy request.""" set_iam_policy_req = dataplex_api.GetMessageModule( ).DataplexProjectsLocationsLakesZonesSetIamPolicyRequest( resource=zone_ref.RelativeName(), googleIamV1SetIamPolicyRequest=dataplex_api.GetMessageModule() .GoogleIamV1SetIamPolic...
f2bbf272084aa874fbb39ccbf9742090445d55f2
3,627,581
def sticky_attribute_assignment(trackable, name, value): """Adds dependencies, generally called from __setattr__. This behavior is shared between Trackable and Model. Respects NoDependency indicators, but otherwise makes trackable objects out of common data structures and tracks objects by their attribute nam...
b8070181ec4c73aee852b164044e4a3c61e021d5
3,627,582