content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pandas.core.sparse.array import ( SparseArray, _sparse_array_op, _wrap_result, _get_fill) def _arith_method_SPARSE_ARRAY(op, name, str_rep=None): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ def wrapper(self, other): if isinstance(other, np.nd...
ba045084dfecc89751e43eaea85fa53462fba98a
3,604,100
from typing import Callable def _embed(method: dict, link: Callable[[dict], str]) -> discord.Embed: """Generate an embed linking to a particular method.""" embed = discord.Embed(title=method["name"], url=link(method)) if "summary" in method: embed.description = method["summary"] return embed
f759589b7e6bac238ee6fe443d162303b90d967a
3,604,101
def check_thermodynamic_consistency(tab, spec, *XYf): """Thermodynamic consistency: relative error"""# ε = (∂E/∂V|_S - P)/P )""" XYf_DT = XYf[:] rho = XYf_DT[0] temp = XYf_DT[1] Pt = tab.get_table('P{s}_DT', spec)(*XYf_DT) dU_rho = tab.get_table('U{s}_DT', spec).dFx(*XYf_DT) dP_T = tab.get...
7dbf10d7a8a0e0742def3c09d20d5a5768b9dab4
3,604,102
def message(): """ Text message. :return: """ return "That's easy to fix, but I can't be bothered."
abff6c119536ffab9a4506d64afe067131e066a2
3,604,103
import yaml def represent_ordered_dict(dumper, data): """ Serializes ``OrderedDict`` to YAML by its proper order. Registering this function to ``yaml.SafeDumper`` enables using ``yaml.safe_dump`` with ``OrderedDict``s. """ return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_...
f8c83dd3b3ecf94077b7b465334ffa84df7e16a8
3,604,104
def get_url_from_web(user_id): """ Get user info according to user id. If user domain is 100505,the url is just 100505+userid; If user domain is 103505 or 100306, we need to request once more to get his info If user type is enterprise or service, we just crawl their home page info :param: user i...
b79173db38d887c845b97f16a842e30ccf8d9acc
3,604,105
def make_adjacencyW(ids, distances, sigma): """Create adjacency matrix with a Gaussian kernel. Args: ids (numpy array): for each vertex the ids to its nnn linked vertices + first column of identity. distances (numpy array): for each data the l2 distances to its nnn linke...
da4048a6c2d188107778617f755af0d246de23aa
3,604,106
import types def channel_threshold( img: types.RGBImage, channel: int, thresh_min: int, thresh_max: int = 255, colorspace: int = None) -> types.BinaryImage: """Apply binary thresholding to an image channel.""" if colorspace is not None: img = cv2.cvtColor(img, colorspace) channel...
0058cde9db19914d79e98342423bf0cac42f97f4
3,604,107
def efficientnet_b0(in_size=(224, 224), **kwargs): """ EfficientNet-B0 model from 'EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks,' https://arxiv.org/abs/1905.11946. Parameters: ---------- in_size : tuple of two ints, default (224, 224) Spatial size of the expe...
7bc53321e3395de5db901be09407a07e269c9014
3,604,108
def BackwardBranch(): """(read-only) MOve back toward the source, return index of new active branch, or 0 if no more.""" return lib.Topology_Get_BackwardBranch()
8d2757f482310b2fbc067ba9546c91036c9b976c
3,604,109
def search_cycles(hints): """ Metoda poszukuje cykli w hintach np trzech pól {2,3,4}. Wtedy można poznać ktore elementy nie znajduja w pozostalych hintach. Warunkiem do sprawdzenia jest czy suma mnogosciowa n pol ma n roznych wartosci. Problemem jest jednak przejrzenie wszystkich wyborow elementow d...
599cf94a4e72757a3925786d74ace0dd39cadf43
3,604,110
def parse_datetime_input(datetime_input): """Takes a string containing date/time and intervals in ISO-8601 format Returns a start and end Python datetime.datetime object datetimes are None if the string is not a date/time datetime_end is None if the string is not a date/time interval """ # Dat...
8b0af9722d5c75ea7812000abd02ea37675f9fa3
3,604,111
def raizCuadrada(n): """ estima la raiz cuadrada en 20 intervalos """ raiz = n/2 # La estimacion inicial sera 1/2 de n for k in range(20): raiz = (1/2)*(raiz + (n / raiz)) return raiz
5b3a36dc50d5fa8921dfcbe2a24f7467201c5339
3,604,112
def get_all_idr(): """ Restituisce la lista delle identity request presenti sul db :return: IdentityRequest[] """ return IdentityRequest.objects.all().order_by('-timestamp_identification')
901f22ac11709d6c0633740e92bfbdb1d0f3f214
3,604,113
def get_dot_size(val, verbose=False): """ Get the size of the marker based on val :param val: the value to test :param verbose: more output :return: the size of the marker in pixels """ markersizes = [6, 9, 12, 15, 18] # there should be one less maxmakervals than markersizes and then we...
aa84c98a3cb78822dd02a9062f9f9a325907b310
3,604,114
def get_unique_merged_queryset(exclude_self_id, model_name, q, q_0, q_1, q_2, q_3, q_4): """Merges querysets in specific order and removes duplicates if user appears in a later queryset""" last_q = None if q_4 is not None: last_q = q_4 else: last_q = q result = apps.get_model('co...
28090a0189acf3c8971325df24a33e8eb597867c
3,604,115
def get_transaction_error_sink(endpoint=_default_endpoint, timeout=_default_timeout) -> list: """ Get transaction error sink Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns -------...
77199c29b050cbafc9b089315129053466f2331e
3,604,116
def get_network_graph_spacy(document): """Convert the dependencies of the spacy document object to a networkX graph :param document: spacy parsed document object :return: networkX graph object and nodes list """ edges = [] nodes = [] # Ensure that every token is connected for s in doc...
684ee4c72627508e89ab0468d03596c7b15945e7
3,604,117
def preprocess_image(image_data, centroid, bbox_size, cropsize): """ Performs preproccessing on a single image for feeding into the network. :param image_data: raw image data as a bytestring :param centroid: the center of the bounding box to crop to, in pixel coordinates :param bbox_size: the side l...
533665759da91c5f3f7d423aa0c9e4ea44f47b57
3,604,118
def find_image_strings(strings): """ Given a list of strings that are potentially image file names, look for strings that actually look like image file names (based on extension). """ imageStrings = [] bIsImage = [False] * len(strings) for iString,f in enumerate(strings): bIsImage[iS...
27e3ea3818f10020ebc2ba012f794e8820d2854f
3,604,119
def tryAttrs(attrs, choices): """See if attrs has anything in choices; if so, return the first one encountered, otherwise return empty string.""" for choice in choices: if isReal(attrs[choice]): return attrs[choice] return ""
15839855e719adf7140fb42c7fba186ce16bd6f6
3,604,120
def solution_inference_resnet(img: np.ndarray) -> dict: """ Pipeline inference Args: img: image in uint8 RGB HWC format Returns: Dictionary with predicted class name """ global brick_classificator, resnet_color_classificator_brio if img is None: abort(409) partn...
223c39e4c7d1a4ce3e11a55cb2a15a2de4d6cef0
3,604,121
def generator(z_inp, is_training=False, getter=None, reuse=False): """ Generator architecture in tensorflow Generates data from the latent space Args: z_inp (tensor): variable in the latent space reuse (bool): sharing variables or not Returns: (tensor): last activation layer o...
05d416e620e710feb31a0a6e8ea590896b774b0c
3,604,122
import numpy import time def debugging(func): """Use this function as a decorator for other tests. It's purpose is to contain a set of test conditions and wrap tests with those conditions. exid, share, globals, cpu, gpu, operating_points, and intermediate_steps should be set in test """ def testCo...
ef6c470c2484b35925efce8ba3603c2a1b5f6c2a
3,604,123
def get_baremetal_offer(include_disabled=None,name=None,offer_id=None,zone=None,opts=None): """ Use this data source to access information about an existing resource. """ __args__ = dict() __args__['includeDisabled'] = include_disabled __args__['name'] = name __args__['offerId'] = offer_id...
4d49373d95a6357535239c0d8ba674b2fa7288f3
3,604,124
def rand_rho(d, sparse=False, density=None, dtype=complex): """Generate a random positive operator of size `d` with normally distributed entries and unit trace. See Also -------- rand_matrix, rand_herm, rand_pos, rand_uni """ return nmlz(rand_pos(d, sparse=sparse, density=density, dtype=dty...
9d9d20c18586f3aa3c1d2e168f4bde79fd809fe3
3,604,125
import six def _tuplify_version(version): """ Coerces the version string (if not None), to a version tuple. Ex. "1.7.0" becomes (1, 7, 0). """ if version is None: return version if isinstance(version, six.string_types): version = tuple(int(x) for x in version.split(".")) as...
97575c813ce585e7e928b129e67196dcece5db0a
3,604,126
from typing import Iterable from typing import Union from typing import List def get_git_root_paths(file_list: Iterable[str]) -> Union[str, List[str]]: """ Given a list of file paths, return a list of the root directories of the git working trees of the files. """ rslt = [] if isinstance(file_...
ec1bc46f629b12907564bdc577bbd60c9cb9d443
3,604,127
import math def is_hexagon(x): """ Checks if x is a hexagon number """ n = (1 + math.sqrt(8*x + 1))/4 return(n == round(n))
854aa38984d36cd956852a091318dd6edb0a06e1
3,604,128
import numpy def A_Mat(uv0, uv1, p00, p10, p01, p11, nPixels): """ Create a cooefficent A matrix. """ c1 = (uv1.u - uv0.u) * (uv1.v - uv0.v) coeffs = numpy.zeros((1, nPixels)) coeffs[0, p00] = c1 coeffs[0, p10] = -c1 coeffs[0, p01] = -c1 coeffs[0, p11] = c1 return coeffs
b3e9faecdc432e17c5da0ecf085f5e1c0e2b16a9
3,604,129
import os def intersect_files(flist1, flist2): """Return the intersection of two sets of filepaths, based on the file name (after the final '/') and ignoring the file extension. Examples -------- >>> flist1 = ['/a/b/abc.lab', '/c/d/123.lab', '/e/f/xyz.lab'] >>> flist2 = ['/g/h/xyz.npy', '/i...
fe4c6e23ea09c2e1770d3e49967f978615df5160
3,604,130
from typing import List import bisect def binary_search(elements: List[int], value: int) -> int: """Returns the index of the element closest to value. Args: elements (List): A sorted list. """ if not elements: return -1 closest_index = bisect.bisect_left(elements, value, 0, len(ele...
1e1cb3ebe1b897e480aa93747108365f0e8326fd
3,604,131
def kwargs_log_scale(unique_val, mode="equidistant", base=None): """Return arguments to set log_scale as one would wish. Parameters ---------- unique_val : np.array All unique values that will be plotted on the axis that should be put in log scale. axis : {"x","y"} Axis for which t...
2bf0946e587512973bccb62f3f0c65f684bc7116
3,604,132
import uuid def create_record_id(): """Create record id. :return: Record id string. :rtype: str """ return str(uuid.uuid4())
a582d8e0823061621e250f257ed4877032792fdc
3,604,133
def postprocess(scores, classes, bboxes, iou_threshold=0.3, score_threshold=0.5): """ Post-process the detection results. Non-maximum suppression. """ n = len(scores) det_num = 0 det_classes = [] det_scores = [] det_bboxes = [] idx = np.argsort(scores)[::-1] sorted_scores =...
4073e358687fca7e0a1bc99ab234b7a8ace1f825
3,604,134
def getGeneralDependency(dep): """ :type dep: basestring | DepType :rtype: DepType """ if dep in __H_GENERAL_DEPENDENCIES: return __H_GENERAL_DEPENDENCIES[dep] elif isinstance(dep, DepType): return dep else: return DepType.fromString(dep)
79d7d37f0396ee0d8ddb5b7842541364bd76cc20
3,604,135
from typing import Optional from typing import Dict import requests def query_active_segments(api_token: Optional[str] = ENVVAR_TELRAAM_API_TOKEN) -> Dict: """Returns information about all active segments. Parameters ---------- api_token: str Your personal Telraam API token. Returns ...
9ebe148ef05dd12b4d6d3c733cb8c11d550a8a0a
3,604,136
import six def _get_key(args, kwargs, remove_callback): """Calculate the cache key, using weak references where possible.""" # Use tuples, because lists are not hashable. weak_args = tuple(_try_weakref(arg, remove_callback) for arg in args) # Use a tuple of (key, values) pairs, because dict is not has...
5f85861395f2ff72e092b0a706ea0199a6bb6325
3,604,137
from typing import Dict from typing import List from typing import Any def get_geometries(handler: h5py.File) -> Dict[str, List[Any]]: """Return an array of smiles in the HDF5.""" group = handler["ligand"] smiles = group["index"]["ligand"][()] pdb = PDBContainer.from_hdf5(group) molecules = pdb.to...
1a3d847bf88454de036f152f77088533d5a0e232
3,604,138
from typing import Type from typing import Callable from typing import Any def is_type(tipe: Type) -> Callable[[Any], bool]: """ :param tipe: A Type :return: A predicate that checks if an object is an instance of that Type """ def predicate(value: Any) -> bool: """ :param value: An...
2b4be636675216c810f9e14f70fe8a5647552e3f
3,604,139
def select_options(element, swap=None, text_exclude=None): """Return dropdown option in key value pair Args: element : An select element swap : list of swapped values text_exclude : immutable object tuple of values to exclude from result Returns: return dict of...
f46d5b05db72ceaa51b1dc4bb3dd82f6516c3bce
3,604,140
def get_vnf_details(vnf_uuid, record, source="vtranscoder3d"): """ Append MANO (OSM) details (ns, vnf and vdu) by given VNF uuid Args: vnf_uuid (str): The uuid of the VNF record (dict): The original metric as it is sent from monitoring metrics generator source (str): The NFVI or applica...
c97b72bcdbc5aac88a4a04c9e60286265811766c
3,604,141
import subprocess,os def plugin_execute(command_name, result_output): """ The xnu framework will call this function with output of a command. The options for returning are as follows returns: (status, outstr, further_cmds) status: Boolean - specifying whether plugin execution succeede...
c72a231b86acd793758dcda364ea7720bf9e22e4
3,604,142
def compute_distance_matrix(x1, x2=None): """ Computes the distance matrix between x1 and x2. If x2 isn't given, it will set x2 as x1 and compute the inner distance matrix of x1. Parameters ---------- x1: numpy array like object with one feature where the rows designate samples. ...
6497799847f61d5d101559d2915dd921767f8888
3,604,143
def daily_data(): """ 日线行情 URL:https://tushare.pro/document/2?doc_id=27 """ df = pro.query('daily', ts_code='000001.SZ', start_date='20180701', end_date='20180718') return df
a08eb8657a7c7557a2b9c1f1b6521430837815ba
3,604,144
from rmgpy.rmg.main import RMG import os def load_rmg_py_job(input_file, chemkin_file=None, species_dict=None, generate_images=True, use_chemkin_names=False, check_duplicates=True): """ Load the results of an RMG-Py job generated from the given `input_file`. """ # Load the specifi...
838f76ee256fe11d8f213ecd761bd171d1ba7925
3,604,145
import re import keyword def get_docx_variables( text:str )->set: """ Given the string from a docx file with fairly simple code), returns a list of everything that looks like a jinja variable in the string. Limits: some attributes and methods might not be designed to be directly assigned in docassemble. Me...
214f2b1b5a8eef902c48e630be3e3f919083e775
3,604,146
def get_control_frame(window, mqtt_sender): """ Constructs and returns a frame on the given window, where the frame has Button objects to exit this program and/or the robot's program (via MQTT). :type window: ttk.Frame | ttk.Toplevel :type mqtt_sender: com.MqttClient """ # Const...
3eca7c6cb21458a2c26678755b4c53dc30f3ee67
3,604,147
def _CheckType(rval, arg, errfmt, span_id): """Shared between NewVar and Readonly.""" if arg.a and rval and rval.tag != value_e.MaybeStrArray: errfmt.Print("Got -a but RHS isn't an array", span_id=span_id) return False if arg.A and rval and rval.tag != value_e.AssocArray: errfmt.Print("Got -A but RHS ...
5ab6ceca86423b961eb31908d913a8c03826646e
3,604,148
import signal def downsample_utterance(features, seglist, n): """ Return the downsampled matrix with each row an embedding for a segment in the seglist. """ embeddings = [] for i, j in seglist: y = features[i:j+1, :].T y_new = signal.resample(y, n, axis=1).flatten("C") ...
b25ec58edaec4e9d8ecd6dc237eb39a2b5d57f4c
3,604,149
import time import logging from datetime import datetime import tqdm def get_detailed_data(con=None, data=None, _from=None, to=None, days_span=10): """ Function that retrieves the data Parameters ---------- data : Dataframe that contains tickers and FIGIs of instrument. Get it using get_instrume...
dda6221a1e931631e864a17d64c8572e0334869c
3,604,150
def initialize_direct(obj_store_config, manager_id, check_db=False): """ Given a fully-prepared configuration, initialize the manager and set the id. :param obj_store_config: dict, fully ready configuration to use :param manager_id: :param check_db: :return: """ global manager_singleton...
5e25a45d3dbe1c05f664b81d48822774f63b38aa
3,604,151
def get_analysis_list(uid): """get all analysis with user_id 'uid' as a list""" session = tables.get_session() if session is None: return None try: ip_table = IpAddrs() collection_table = CollectionTable() ips = ip_table.get_ips_by_uid(uid, session) res = [] ...
3ed94d7f7509e5c39c7a51763face107d6d7697f
3,604,152
import collections def _get_epoch_data(valid_loss_mean_val: float=3) -> EpochData: """Return testing epoch data.""" epoch_data = collections.OrderedDict([ ('train', collections.OrderedDict([ ('accuracy', 1), ('loss', collections.OrderedDict([('mean', (3, 4))])), ])), ...
655206741628fd16d2b896c4f95da6d0553a15dd
3,604,153
import os def is_root(): """Check admin permissions.""" return os.geteuid() == 0
f4d72e1139ef7e59f4c8764e65fb0d571ab8e32b
3,604,154
def em_step(dataset, lmm): """Complete one expectation and one maximization step. Parameters ---------- dataset : List of tuples; observations and design matrices. lmm : A linear mixed model object. Returns ------- A 3-tuple; the fixed effects, random effects covariance, and noise ...
6236062faba42d283ed3fdf68a363c565acc3328
3,604,155
def new_measure_get_meas_measure(data: dict) -> MeasureGetMeasMeasure: """Create GetMeasMeasure from json.""" return MeasureGetMeasMeasure( value=int_or_raise(data.get("value")), type=new_measure_type(data.get("type")), unit=int_or_raise(data.get("unit")), )
1e0c87dd99157d50dda17c0093d7c1ac385d42c3
3,604,156
def nexttwin(zahl): """Return the smallest prime twin following a given number.""" print(_("=== Find the next prime twin ===")) answer = "" while answer != "q": print(_("ENTER, a number or 'q'"), end=": ") answer = lies() if answer == "q": break try: ...
8e220815a9568b73b121fca1b13c8992d577e8d1
3,604,157
import requests def list_connect_admins(group_name): """ Return list of admins of connect group Return list of nested dictionaries with state, user_name, and state_set_by """ query = {"token": slate_api_token} group_members = requests.get( slate_api_endpoint + "/v1alpha1/groups...
168ee581fa16d2812a9d1c801fb30a63e70d9352
3,604,158
def MSI(record): """ "Maximise Severity if Invalid": propagate an alarm state on the linked record only if the alarm severity is `INVALID_ALARM`. When propagated, the alarm status will become `LINK_ALARM`. Example (Python source) ----------------------- `my_record.INP = MSI(other_record)` ...
872b13eafe3dd76a962f24d2f3108990b5fda40e
3,604,159
from typing import Any from typing import Optional def sample_or_pad_non_sorted_sequence( sequence: tf.Tensor, max_num_steps: int, pad_value: Any, random: bool, seed: Optional[int] = None, state: Optional[builders.ProcessorState] = None) -> tf.Tensor: """Samples or pads (with `pad_value`) el...
1bfaa78c95352dc792c5127e3a1c216959468ca0
3,604,160
def _get_compound_type_from_kind(kind): """Map compound kinds from Doxygen XML to internal class types.""" if kind == 'file': return File elif kind == 'dir': return Directory elif kind == 'group': return Group elif kind == 'namespace': return Namespace elif kind i...
451ee299a4f9fca3e7f9be0c0b764412ba0e8cd8
3,604,161
import requests def hp_update_firmware(url=None, dry_run=False): """ Apply HP firmware updates :param url: Full URL to the package containing firmware files :param dry_run: If firmware updates should be applied when found """ try: r = requests.get(url, stream=True, verify=False) e...
1ea4aa18d905b60b231a3c898bfb2409eae64903
3,604,162
def delete_group(token, group_id, customerid=None): """ Delete a contact group for the specified account Returns all the data in a dictionary format from the original JSON that is gathered from NodePing :param token: The NodePing API token for the account :type token: str :param group_id: The ...
51ff79b0348298d2bfc3bcf4e8c661d95bfde671
3,604,163
def close_connection(exception): """ Close any existing connection to the database. :param exception: An exception that is triggering the application teardown. """ database = getattr(g, "_database", None) if database is not None: database.close() return None
1ed0e2d74a8ac8fe1d05db7e7ce3929d17992f64
3,604,164
def draw_guess_buttons(colors): """ Draw guess buttons that input each a particular color to a guess. """ buttons = [] y = divider + SQUARESIZE//2 radius = pegsize pygame.draw.rect(screen, DARKEST_GRAY, (0, height-SQUARESIZE*2, width, SQUARESIZE*2)) for c in range(...
1d6b2a726cf108d01347bed5ddfb8d8e6ec7fc9c
3,604,165
import json def voter_guides_to_follow_retrieve_view(request): # voterGuidesToFollowRetrieve """ Retrieve a list of voter_guides that a voter might want to follow (voterGuidesToFollow) :param request: :return: """ voter_device_id = get_voter_device_id(request) # We standardize how we take in...
5737b7f75439d4837d34b51f1aea422a4dc4ce38
3,604,166
def cfg(): """Returns a Config object loaded with test_profile""" cfg = Config() cfg.source_config_file(cfg_file) return cfg
7da4f7a11445bbf3aa6963ad157b073745c62732
3,604,167
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None): """compute problem size, thread block and grid dimensions for this kernel""" threads = get_thread_block_dimensions(params, block_size_names) current_problem_size = get_problem_size(problem_size, params) grid = get_grid_dime...
1f19bc211b6f1d2dbaf454386468618bc2b98572
3,604,168
def update_token( user_id : str, token : str ): """ Updates a user's API token in the database Parameters: user_id (str): unique identification for the user token (str): authentication for API calls Returns: On Success: Boolean: True On Fail: Boolean: False """ ...
21900af6b8219913683064a3e8aefb263a6bd2dc
3,604,169
def _lam_hawkes_lite( ts, eval_ts, mu_kernel, phi_kernel, t_start=0.0, **kwargs): """ Intensity of Hawkes process given time series and parameters. Memory-lite version. CPU-hungry, could be improved with numba. Uses assignment so may need to be altered fo...
491158080f5ce9642536b2c6cae037c3889ff4bb
3,604,170
def dropin(name, *, contents): """ :param the name of the drop-in. This must be suffixed with ".conf". :param contents: the contents of the drop-in. : return Container Linux systemd drop-in object """ return { 'name': name, 'contents': cleanup_contents(contents) }
49f080c1849584ba8218e8baa9d3f15d2ffb48f2
3,604,171
def unique_id_map(slug): """ :param slug: A slug that specifies the type of object that we want to generate ID for. :return: Tuple of UniqueIdGenerator instance and an optional subclass of UniqueId collection. """ # turn slug into id name = '{}_id'.format(slug.replace('-', '_').lower()) retu...
37630df8824c2991d7dc744a47c74a7dd4bd32cf
3,604,172
def visible_limits(artists, axis): """ Determines the data limits for the data in a set of artists. Ignores non-visible artists Assumes each artist as a get_data method which returns a tuple of x,y Returns a tuple of min, max for the requested axis, or None if no data present Parameters ...
c820e4b46a4ce1ac8f30ca6468e0a46b66d6996a
3,604,173
def rand_sparse_ndarray(shape, stype, density=None, dtype=None, distribution=None, data_init=None, rsp_indices=None, modifier_func=None, shuffle_csr_indices=False): """Generate a random sparse ndarray. Returns the ndarray, value(np) and indices(np) Parameters ...
d6d064a24bd706c155a1d68a540ba1b56fbd01f3
3,604,174
def rand_simple_polygon(vertices): """ That's an unreliable hack to generate a random simple polygon. Beware, sometimes it is stuck in an infinite loop. """ poly = Polygon_2() while vertices > 0: x = randint(-5, 5) * 10 y = randint(-5, 5) * 10 poly.push_back(Point_2(...
a321c23ca7cc69d11ce1f75e8c7f26db00601879
3,604,175
def strip_constants(df, indices): """Remove columns from DF that are constant input factors. Parameters ---------- * df : DataFrame, of input parameters used in model run(s). * indices : list, of constant input factor index positions. Returns ---------- * copy of `df` modified to exclu...
5a68d9beaa39cb2651ccd995af20d25165ccb03e
3,604,176
def _GetBucketName(master_name): """Converts shortened master name to full master name. Buildbucket uses full master name (master.tryserver.chromium.linux) as bucket name, while Findit uses shortened master name (tryserver.chromium.linux). """ buildbot_prefix = 'master.' if (master_name.startswith(buildbot...
375e052db9da02e62c4fcd9f0ef28d0302aaebe6
3,604,177
def _getPushshiftData_(before, after, kind='submission', subreddit='de', size=1000): """ Fetches reddit data via the pushshift api: between "before" and "after" given as linux timestamps of "kind" submission or comment from "subreddit" of size "size" (maximum 1000) """ if...
58bc96a171887e8e672233e288b49d4873a5b27c
3,604,178
def prioritized_texts(): """ Retrieves all of the political statements from the database, prioritizes them with the manifesto model and returns at most as many texts given in the GET parameter `n`, ordered by their uncertainty. :return: { 'data': [ {'text_id': 1, 'label': 'left'}, ...
2a0eea5907207108aff83ef904ce64c405e21091
3,604,179
def null_space(M, k, k_skip=1, eigen_solver='arpack', tol=1E-6, max_iter=100, random_state=None): """ Find the null space of a matrix M. Parameters ---------- M : {array, matrix, sparse matrix, LinearOperator} Input covariance matrix: should be symmetric positive semi-definite...
0f05d8943ac8d77b4c5087de81b15159c98c5cb3
3,604,180
def get_view_content(view): """ Returns view content as string. """ return utils.execute_in_sublime_main_thread(lambda: view.substr(sublime.Region(0, view.size())))
18f7accd4efa6fc58e8f9df83776703006bb99e2
3,604,181
def is_liked(bvid: str = None, aid: int = None, verify: utils.Verify = None): """ 是否点赞视频 :param aid: :param bvid: :param verify: :return: """ if not (aid or bvid): raise exceptions.NoIdException if verify is None: verify = utils.Verify() if not verify.has_sess(): ...
e53c80af1df3448555701193327a8e9b669f7497
3,604,182
def namedtuples(stmt, from_iter = chain.from_iterable, map = starmap): """ Alternative to the .rows() execution method. Use:: >>> from postgresql.types.namedtuple import namedtuples >>> ps = namedtuples(db.prepare(...)) >>> for nt in ps(...): ... nt.a_column_name This effectively selects the execution ...
273de9c7aae9ff1060ec58bd41e8bc13674c5414
3,604,183
def review_request_dropdown_action_hooks(context): """Displays all registered action hooks for review requests.""" return action_hooks(context, ReviewRequestDropdownActionHook, "actions", "extensions/action_dropdown.html")
3b7be826101a3eb7a820fbde64250a56d27461bd
3,604,184
def merge_function_titles2specs(spec_array, titles_info): """ Attach human-friendly titles and descriptions to passed ETHFunctionSpec list. Processed elements: function titles and descriptions, function input arguments titles and descriptions, titles and descriptions of function outputs. :param sp...
7e73bf426289bc8a5874b803909519b2553bc371
3,604,185
from typing import Type def create_singledispatch_function_callback(ctx: FunctionContext) -> Type: """Called for functools.singledispatch""" func_type = get_proper_type(get_first_arg(ctx.arg_types)) if isinstance(func_type, CallableType): if len(func_type.arg_kinds) < 1: fail( ...
a8fb883383804ee7983bf929e1b7b4eea6dac47e
3,604,186
def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token.""" # Because of the sliding window approach taken to scoring documents, a single # token can appear in multiple documents. E.g. # Doc: the man went to the store and bought a ga...
e909ccc4e4a926a3059cd2beb960530db43f8235
3,604,187
import subprocess import shutil def get_logins(): """ Get number of logins this week :return: """ logins = {} # Count the number of logins in the weekly log cmd_out = subprocess.getstatusoutput('cat ' + data_dir + 'jupyterhub.log | grep -c "User logged in"')[1] logins['week'] = int(cm...
0407f93e2cc8a22e874e17cd2004ddb6efa1f136
3,604,188
def file_and_extension(path: str): """return filename and their extension.""" filename = path.split('/')[-1].split('.')[:-1][0] extension = path.split('.')[-1][0] return filename, extension
0b2ccae4ac054330e9b99b80ef6a657dd08d97ed
3,604,189
import os import dill import inspect import pickle def pickle_special_metrics(metrics, filename): """Pickle special metrics and dump to filename Args: metrics (list): List of special metrics filename (str): Path to the pickled file Return: True if special metric is not None, Fals...
d739bf159afd33743790c535624720a2ed356104
3,604,190
def input_details(interpreter, key): """Returns input details by specified key.""" return interpreter.get_input_details()[0][key]
b06bd5278fcc5d95da387cb506ac9b9f443d9f27
3,604,191
from typing import Union from typing import Sequence def _get_noise_shape( x: tf.Tensor, noise_shape: Union[Sequence[int], tf.TensorShape] ) -> Union[tf.Tensor, tf.TensorShape, Sequence[int]]: """Computes the shape of the binary mask for dropout.""" # If noise_shape is none return immediately. if noise_shap...
3788e83ea9ad755eca777bcca79746b53102d10c
3,604,192
def spread_to_trimesh(spread, cutoff): """Convert levelset to mesh by way of binary""" return binary_to_trimesh(spread_to_binary(spread, cutoff))
e7d4420af0850f643cfc6bfffafeac728ba4d429
3,604,193
def gauss_discrete(r0, i, j, w_s): # pragma: no cover """ 2D gauss function with a discrete center position """ i -= w_s // 2 j -= w_s // 2 A = 1. / (np.sqrt(np.pi) * r0) return A * np.exp(-(i ** 2 + j ** 2) / r0 ** 2)
f80484de44e4897810f1b50f986ba852dca11911
3,604,194
import os def get_path(b): """Get path for image build Args: b: build context Returns: path """ return os.path.join(*b._keypath)
8603a6e51f3edd2697ace38410b9d8d1d7a05028
3,604,195
import torch def add_edge(adj, node1, node2): """return a new adjacency matrix that inserts a symmetric edge between node1 and node2""" num_nodes, _ = adj.sizes() edge_index = torch.tensor([[node1, node2], [node2, node1]]) new_edge = SparseTensor(row=edge_index[0], col=e...
6713b066fcb539ea64969c91bcc5b842bb363248
3,604,196
def approxEntropy(N: int, p: float, r: int) -> float: """ Xét dãy H_{N} = (-Pr(r) log Pr(r)) + (-Pr(r+1) log Pr(r+1)) + ... + (-Pr(N) log Pr(N)) H_{N} là một dãy dương, tăng và có giới hạn là entropy của biến ngẫu nhiên nhị thức âm Do đó khi N càng lớn, hàm approxEntropy sẽ tiến đến entropy của biến ngẫ...
e967684e5892de86e58182c87c83fc61e302ea86
3,604,197
import io def read_item_names(): """Read the u.item file from MovieLens 100-k dataset and return two mappings to convert raw ids into movie names and movie names into raw ids. """ file_name = get_dataset_dir() + '/ml-100k/ml-100k/u.item' rid_to_name = {} name_to_rid = {} with io.open(file...
88c030e411ec832d9e958a9704bd99cddfa42074
3,604,198
def ds_point_plot(df, x, y, cmap='#1f77b4', plot_height=300, plot_width=500, x_axis_label=None, y_axis_label=None, title=None, margin=0.02): """ Make a datashaded point plot. Parameters ---------- df : pandas DataFrame DataFrame containing the data x ...
4c3cd39dd38fdeea50c508636108e5ae2c6525f3
3,604,199