content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def spawn_dates_times(df, spawn_dates=True, spawn_times=False): """ Build date/times column from a timeseries dataframe :param df: (pd.DataFrame) - dataframe with datetime index :param spawn_dates: (boolean) - whether to spawn year, month, day cols :param spawn_times: (boolean) - whether to spawn h...
ee58b5117d65fa3f217b16973dcdc06918c5474b
54,738
def parse_date(string, format=None): """ :type string: str :type format: NoneType or str :rtype: NoneType or date """ if format is None: formats = FORMATS else: formats = [format] for f in formats: try: return dt.datetime.strptime(string, f).date() except ValueError: pass return None
7282d401ba0ab2e2243c7c4ad990136ad80d2ee3
54,739
from typing import List def impurity_of_split_rec(points: List[DataPoint], split: float) -> float: """ Recursive method wrapper to split the data points into two arrays based on the split point provided and return the gini impurity measure for that split point. """ print("Printing split: {}".format(sp...
c3232595b4f1168472e3444939e57f5744a0b6da
54,740
import ctypes def GetConsoleOriginalTitle() -> str: """ GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher. """ if IsNT6orHigher: arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleOriginalT...
55900e0280253860b95a20acd2551f61a831d61d
54,741
def connection(): """ Function that provide the SQL connection to be uses by the ORM. Returns ------- (bool, SQL connection object) The first element of the tuple indicates whether the connection is to be closed after every query. The second element should provide an SQL connection ...
65b0122a0cc7b57ab553ac85a6db576e3d242de6
54,744
def mergeinput_preprocess_duo(df1, df2): """ Merge 2 data frames into one for full analysis. Output will be two form: long form and wide form long form: simply add 2 df on top of each other wide form: each row represents a request coordinate with result from both run. -> calculate ED relevant cols f...
9967be2ec1ccae8d6462c5c01f63d8641b523759
54,745
def mbeans(query=None): """ Returns a list of all the available MBeans in the server. The optional query parameter will filter the list by objectname """ return server.getQueryMBeans(ObjectName(query), None)
3ad2ed5b36196b55deeefa51ab7968b009b523de
54,746
def is_decimal_dtype(obj): """Check whether an array-like or dtype is of the decimal dtype. Parameters ---------- obj : array-like or dtype The array-like or dtype to check. Returns ------- bool Whether or not the array-like or dtype is of the decimal dtype. """ ret...
c2151eb94ff9aebd6694aa679d1cfcc75f08133f
54,747
def calculate_F1(max, compensate = 0, threshold = 0.5): """ Args: max (M,N) return: AP,TP,FP,FN,precision,recall,F1 """ if compensate < 0: compensate = 0 TP = 0 FP = 0 FN = 0 for i in range(len(max)): if max[i] > threshold: TP = TP + 1 ...
6aab529bbf1837472f0d711997b31fca0fcc3eee
54,748
import time def runtime(X, y, model_generator, method_name): """ Runtime (sec / 1k samples) transform = "negate_log" sort_order = 2 """ old_seed = np.random.seed() np.random.seed(3293) # average the method scores over several train/test splits method_reps = [] for i in range(3): ...
6cbb4a7e773f3c5dafcaf43aa6106be59dc4b87f
54,749
def get_mask(json_data, microplate_names): """Return wrapper for numpy array.""" return ControlMask(json_data, microplate_names)
d18fc86c9189b80f550d55646d8f2b94f924fe4d
54,750
def utc2sec(*utc): """Convert list composed of year,month,day,hour,minute,second [,microsec] :param utc: list of year,month,day,hour,minute,second :returns: number of seconds since the epoch 0001-01-01 """ utc2=list(utc) if len(utc)<7: utc2.append(0) return int(utc2micro(*utc2)/10*...
41b6469087414a8c210125b52060745f2cbaf380
54,751
def scale_sample(xy_sample,grid): """ This function is used to apply the shifts and scaling to the sample. """ sample = xy_sample.copy() if grid.dim == 2: sample[:,2] = sample[:,2] + grid.shifts[0]*sample[:,0] + grid.shifts[1]*sample[:,1] sample[:,0] = sample[:,0]/grid.b0 sample...
3f0ae32f198ec75d112ff7d36ea2505dcd75dbea
54,753
def radius_aperture(info_dict): """ Compute the radius of the aperture Parameters ---------- info_dict: dictionary wavelength: float wavelength in angstrom Returns -------- aperture: float radius of the aperture in arcsec """ if info_dict["psf_type"] == "gaussi...
d5055e6bdb3b5fd519ac2b96941a0338bc547b0c
54,754
from pathlib import Path def find_file(filename): """ Finds a file in the directory that has the same name as the parameter <filename>. If the file does not exist, the directory is searched for <filename.*> instead, and if only one match is found, that particular filename is returned. """ ...
4915739f11221f566a7fc6f381fc29bf30426908
54,755
def FermiDirac(Ef, EJ, T): """ Returns the Fermi-Dirac probability distribution, given the crystal's Fermi energy, the temperature and the energy where the distribution values is required. Args: | Ef: Fermi energy in J | EJ: Energy in J | T : Temperature in K Returns: ...
1e8fbfc0a9ef704340810f2b085afe3543f61356
54,756
def glXQueryVersion(dpy): """ dpy - Display* return - bool, int, int: support, major, minor""" major = Numeric.zeros(1, Numeric.Int32) minor = Numeric.zeros(1, Numeric.Int32) res = _glxlib.glXQueryVersion(dpy, major, minor) return res, major[0], minor[0]
28798bc9371bffd959025190af17b3d29cdd8a0b
54,757
import random def get_message_data(): """Default valid message data.""" return { 'message': ''' -----BEGIN PGP MESSAGE----- Version: Keybase OpenPGP v2.0.8 Comment: https://keybase.io/crypto wcBMA6Uvn0xuUMOaAQf/bGf4y9ZfKChSOAJs4M5V7K3nDC2p/sUNcfy8FzoIl9VE j2vT3bMZsaT3cJkQMfABqWgzq8VlQjRP1/m+bBX4jRUYV...
1e715936bcdd133a981403e6b523bd623e806b1b
54,759
def usgs_kyanite_parse(*, df_list, source, year, **_): """ Combine, parse, and format the provided dataframes :param df_list: list of dataframes to concat and format :param args: dictionary, used to run flowbyactivity.py ('year' and 'source') :return: df, parsed and partially formatted to fl...
25536570a06fffe43d36d4f62a0ff0a2ee98863d
54,760
from typing import List def prepare_element(sample_nist_component_def: component.ComponentDefinition): """Prepare a target element for remove tests.""" element = Element(sample_nist_component_def) parties: List[common.Party] = [] parties.append( common.Party(**{ 'uuid': 'ff47836c-...
08570b86e8eaf7c510c9b5cafa0071b3fe90edb9
54,761
import torch def flow_warp_tensor(mask, flow, coord=None): """ :param mask: 1xCxHxW :param flow: HxWx2 :return: """ if coord is None: shape = mask.shape[-2:] coord = torch.ones(shape).cuda().long() coord = torch.nonzero(coord).float() flow = flow2coord(flow, coord) flow = flow.unsqueeze(0...
0ff2ed886f5224708cdb8ee4f0129b952bb2de3e
54,762
def neighborhood_ambulance_combinations(neighborhoods, total_ambulance): """ This function returns all possible combinatios for neighborhoods and the number of ambulances they hold. Inputs: neighborhoods (Array of string) neighborhood names that contains ambulance stations total_ambula...
2e640ab8c089dc61e650978d7da1201f0032540b
54,765
def get_number_of_desktops(): """ Returns the number of virtual desktops. :return: The number of desktops. :rtype: util.PropertyCookieSingle (CARDINAL/32) """ cook = util.get_property(root, '_NET_NUMBER_OF_DESKTOPS') return util.PropertyCookieSingle(cook)
4899628116bac58fbeb23f5f9fddb248115e4cef
54,766
def scalar_to_array(input_x): """ Converts a scalar to a `Tensor`. Args: input_x (Union[int, float]): The input is a scalar. Only constant value is allowed. Returns: Tensor. 0-D Tensor and the content is the input. Raises: TypeError: If `input_x` is neither int nor float. ...
d7923256a1908df9f1633ebe946a871ad7a6bcbe
54,767
import json import requests def handle_action(): """Handle a response when a user clicks a button from Wizzy in Slack""" event_data = json.loads(request.form["payload"]) user = event_data['user']['id'] # if channel empty, it's a shortcut if event_data.get('channel') is None: # shortcut - g...
cb54f430e4e3317af658ef1068d893f4798a7c0e
54,768
from typing import List import copy def calc_permutation_matrix( system_order: List[int], size_list: List[int] ) -> np.ndarray: """calculate permutation matrix. permutation matrix can reorder the system order to [0, 1,..., n]. Parameters ---------- system_order : List[int] system_ord...
6544e03cb1febde14c15ad5fa6ac2c425dabec0a
54,769
import random def cvt_horizontal_flip( sample_input: Dataset, sample_output: Dataset, probability: float = 0.5 ) -> Dataset: """Converts the sample_input dataset to horizontal flips in sample_output dataset. Args: sample_input: input dataset passed to generate output dataset. sample_outpu...
2f15e5ed3aae75bda360f17f95e7722b70bb0bbc
54,771
def search(): """Display search options""" return render_template("search.html")
97193ebb2820b33f038a5f027caa5bde6889a788
54,772
def get_client_setting(setting: str, cid: str) -> ClientSetting: """Return client setting based on setting name and cid.""" for client_setting in get_setting(setting).clients: if client_setting.cid == cid: return client_setting raise ClientSettingNotFound()
e6292699c4a741541dede631fc1f5b42cbb744ec
54,773
def between(x, min, max, exclude_max=UNSET) -> ProcessBuilder: """ Between comparison :param x: The value to check. :param min: Lower boundary (inclusive) to check against. :param max: Upper boundary (inclusive) to check against. :param exclude_max: Exclude the upper boundary `max` if set to `t...
72417a83c8196b32a4c3838ec6e0b9b21c94d050
54,774
def parse_description(issue): """ :param issue: Issue object. :return: ROGA type: (a string that should be listeria/salmonella/vtec - otherwise they'll get others later. seq_ids: List of seqIDs which will later be written to file and used in ROGA report generation. """ # Take whatever i...
13ea063546a327dd94eff1fca8f03d9ea7ea1476
54,775
def feedback(data: FeedbackData) -> str: """ Pass the request data as FeedbackData object, as this can be customised in the model.py file to adapt based on deployed model to make predictions Parameters: data: Parse the request body data based on your model schema and pass this to pred...
cdfbe44e46c82282488f4d57d818b27c0279f488
54,776
def get_dataset(id_): """특정 dataset에 대한 정보 반환 Args: id_ (int): dataset ID Returns: _type_: _description_ """ result_json = {"datasetName": "", "image_metadata": []} query = Dataset.query.filter_by(id=id_).first() result_json["datasetName"] = query.name query = ImageM...
135b45947ebe604ee71d579c5aa9b373f9d8048f
54,777
def test_metathesis(word, anagram): """ Tests if a word and an anagram are a metathesis pair This is only true if the words are I. Anagrams II. Differ in two places """ count = 0 for para in zip(word, anagram): if para[0] != para[1]: count += 1 return count == 2
c26090d92b526ce7d2a84138e4248c884a19f5bc
54,778
from aac.plugins import ( gen_json, gen_plugin, gen_protobuf, gen_design_doc, gen_gherkin_behaviors, gen_plant_uml, specifications, ) def get_plugin_manager() -> PluginManager: """ Gets the plugin manager and automatically registers internal plugins. ...
8a8bc92205bf2334c41332e2f6a337fc0709a634
54,779
def get_token(username, password): """Returns a new token for login credentials.""" payload = {'username': username, 'password': password} key = username + password # simple key token = jwt.encode(payload, key, algorithm='HS256') # Convert bytes to string token = token.decode('utf-8') # Sto...
2abef9d55fb96fcc9567b934d1dccd55e29e3c96
54,780
def standardize(ds, dim="time"): """Standardize Dataset/DataArray .. math:: \\frac{x - \\mu_{x}}{\\sigma_{x}} Args: ds (xarray object): Dataset or DataArray with variable(s) to standardize. dim (optional str): Which dimension to standardize over (default 'time'). Returns: ...
99de2a60e340a7ad451daec27aad028485d4aa59
54,781
import warnings def predict(model, image_files, resize=False, show_image=True, cloud=None): """Predict using an model in a local or GCS directory (offline), or a deployed model (online). Args: model: if cloud is None, a local or GCS directory of a trained model. Otherwise, it specifies a deployed mod...
5cc4e7667032243448ab5b871c7728967698702b
54,782
import six def topics_offset_distance( kafka_client, group, topics, offset_storage='zookeeper', ): """Get the distance a group_id is from the current latest offset for topics. If the group is unkown to kafka it's assumed to be an offset 0. All other errors will not be caught. Thi...
d6f1ded7f609d86726b88eba494fec5fdc264e7d
54,784
def get_first_meeting_day_num(days: str): """ Returns the number representing the day of first meeting of the week :param days:str: Days field of WebReg list, example: "MWF" """ day_nums = get_day_nums(days) first_day_num = day_nums[0] return first_day_num
f86f2832ea7cec4356b1aae60a7a1ac17573fc35
54,785
from typing import Any from datetime import datetime def post_search(netid: str, client: ShrunkClient, req: Any) -> Any: """``POST /api/search`` Execute a search query. Request format: .. code-block:: json { "query?": "string", "set": { "set": "'user' | 'shared' | 'a...
a4d59bed2aee578d14fee1ecdb84d4e036c0d0b9
54,786
import smtplib def os_error(): """Operating system error. AKA EnvironmentError / IOError.""" try: smtplib.SMTP('localhost:a_port') except OSError: return "bad port number"
2b99d466f04369ab98bdb40c7a3417dd8c089744
54,787
def multivariate_potential(ptset2, meanvec, covmat): """ Vectorised evaluation of multivariate Gaussian pdf. Args: ptset: shape (N, d) mean: shape (d,) covar: shape (d,) Raises: AssertionError: if ptset, mean and covar have not consistent shape Returns: resul...
226c0958c9fd835c93ce33a3f42cd1abea62eba0
54,789
def restart(backend): """Restart the running server from an async test function. This fixture deals with possible differences between the environment of the test function and that of the server. """ async def restart(server): await backend.run_in_threadpool(AsyncioBackend().run, server.res...
518af91d3ebf1bd88f2faae1a06215dd6d67d9cf
54,791
def colinterp(a,x) : """Interpolates colors""" l = len(a)-1 i = min(l, max(0, int (x * l))) (u,v) = a[i:i+2,:] return u - (u-v) * ((x * l) % 1.0)
278eb403e220fee139a73ed6f764df93b6366bc9
54,792
def accepted_content_type(f): """ Check if the requested content type is application/json. """ def decorator(*args, **kwargs): if request.content_type != 'application/json': raise ServiceException('Content type must be application/json', 400) return f(*args, **kwargs) r...
5b0bcde03e4dc204ca95dd685b0715680f502633
54,793
import requests def get_articles_html(url_articles: str) -> str: """Wraps HTTP requests.get for testibility Parameters ---------- url_articles : str Articles URL Returns ------- str HTML page of articles """ articles_html = requests.get( url_articles, head...
4fcbf397d4986eed19a3528dde99cb5a81581a10
54,794
def ei_merit(X, surrogate, fX, XX=None, dtol=0): """Compute the expected improvement merit function. :param X: Points where to compute EI, of size n x dim :type X: numpy.array :param surrogate: Surrogate model object, must implement predict_std :type surrogate: object :param fX: Values at previ...
e53d35f93b7aeb5fca6c34e70ababb7812b78fc5
54,795
import soundfile as sf from pathlib import Path from typing import Optional from typing import List import logging def load_audio( path: Path, channel: Optional[int] = None, mmap: bool = False, channel_names: List[str] = ["left", "right"], ) -> MultiTrack: """load waveform from file""" multiTr...
bd853eb4fef33aad63a0267c5bb63ba91d457d3b
54,796
def render_robots_meta_tag(context): """ Returns the robots meta tag. """ request = context['request'] robots_indexing = None robots_following = None # Prevent indexing any unwanted domains (e.g. staging). if context.request.get_host() in settings.META_TAGGER_ROBOTS_DOMAIN_WHITELIST: ...
018084102031ca13a36f2563c6f05d810045432e
54,797
from typing import Dict def search(search_string)->Dict: """ API to search "search_string" in the stored documents :param search_string: search string provided by the user :type search_string: str :return: returns results i.e. return list of documents that are closest match to the search string ...
588960333a7140ad51ffc577741f9102e90d082f
54,798
def convert_lang_code(code): """ Map a language code to the canonical one that ConceptNet 5 uses, using the 'langcodes' library. """ return str(langcodes.get(code))
0da05bd40e6758038c28c3d585744d2ed63fe6f7
54,799
def solution_math( A: np.array, B: np.array, threshold: int = 1_000_000_000, scale: int = 1_000_000 ) -> int: """Math based method. See tutorial/examples in docs for more details.add() Parameters ---------- A : np.array integer part of the decimal numbers B : np.array decimal pa...
d87c860846968e49705ac8390aa5caded1381f84
54,800
def tag_list(context, addon, tags=[]): """Display list of tags, with delete buttons.""" c = dict(context.items()) c.update({'addon': addon, 'tags': tags}) return c
0b59aa158137eecd5210c631f053ae137762b690
54,801
def make_range_partition(min_val, max_val): """ Returns a new partitioning function that partitions keys in the range *[min_val:max_val]* into equal sized partitions. The number of partitions is defined by the *partitions* parameter """ r = max_val - min_val f = ("lambda k_n_p: int(round(fl...
6b9c15f93312a913dff432f0954e409b69f97572
54,802
import torch def sparse_mx_to_torch_sparse_tensor(sparse_mx): """Convert a scipy sparse matrix to a torch sparse tensor.""" sparse_mx = sparse_mx.tocoo().astype(np.float32) indices = torch.from_numpy(np.vstack((sparse_mx.row,sparse_mx.col)).astype(np.int64)) values = torch.from_numpy(sparse_mx.data) ...
cdf10274d87997fbe93085d48e738e3bad92edf9
54,803
def split_outside(a, sep, start="([{", end=")]}"): """Split string a at occurences of separator sep, except when it occurs inside matching groups of start and end characters.""" segments = split_by_group(a, start, end) res = [""] for seg in segments: if len(seg) == 0: continue if seg[0] in start: res[-1] +=...
efd84168831cac6af8ac1b88bdface450c0aea14
54,804
def gen_unique_image_path(standard_image_path, image_num): """ Generates a unique image path based on the standard_image_path by adding the IMAGE_IDENTIFIER_SEQUENCE followed by a number """ # Index where extension sequence starts (.jpg, .jpeg, or .png) extension_start = standard_image_path.lowe...
a42148e671d9d551099108b989cec0d9ec627c96
54,805
from typing import Optional from typing import Any def try_wrapper( func: callable, *args, ret_: Optional[Any] = None, msg_: str = "", verbose_: bool = True, **kwargs, ) -> Any: """Wrap ``func(*args, **kwargs)`` with ``try`` and ``except`` blocks. Args: func (callable) ...
3514663751028e8bcb9979f952045c053a325ff1
54,806
from typing import Dict from typing import Any from typing import List def _CreateSamples(results: Dict[str, Any], number_of_messages: int, message_size: int, cloud: str) -> List[sample.Sample]: """Handles sample creation from benchmark_scenario results.""" samples = [] common_metadata = { ...
a60652e74bd041dc183837746202dd3d3ed24ae5
54,807
def merge(df_list,merge_param_list): """ method to merge the list of data frames based on list of column identifiers. This returns intersection of values :param df_list: :param merge_param_list: :return merged data frame: """ merged = funs.reduce(lambda left, right: pd.merge(left, right,how...
b41a26f8c8b0ff69aa80e1d4d328b67a141d68ec
54,808
def yices_check_context(ctx, params): """Checks whether all the assertions stored in the context ctx are satisfiable. - params is an optional structure that stores heuristic parameters. - if params is NULL, default parameter settings are used. It's better to keep params=NULL unless you encounter perfo...
191f9776a2dd50ee5f56b515571c5a4cfe055b4c
54,809
import torch def collate_fn_v2_(data_batch): """ used for trained on the original complex dataset and tested on the ligand-only and protein-only datasets :param data_batch: :return: """ graphs, graphs3, Ys, Nodes = map(list, zip(*data_batch)) bg = dgl.batch(graphs) bg3 = dg...
18778a2da4986b8e4c42f5d902bc1be752fcca3f
54,810
def standardvariables_get(username=None, label=None, page=None, per_page=None): # noqa: E501 """List all instances of StandardVariable Gets a list of all instances of StandardVariable (more information in https://w3id.org/okn/o/sd#StandardVariable) # noqa: E501 :param username: Name of the user graph to ...
b04df9f32330541c316a7e8d67217c6bcbb0ab71
54,811
from re import S from re import T def construct_scale(root_note, scale_signature, scale_length=None): """Construct a musical scale from a root note Arguments: root_note -- A root note object from class Note scale_signature -- array of frequency ratios between consecutive notes on the scale scale_...
555099024c4e9fc8d2b487ddc7e57138084e494f
54,812
def get_env_logname(name): """ get_env_logname """ modname = name.split('.')[0].upper() envname = f"{modname}_LOGLEVEL" # print(envname) return envname
6fa8032ee77d94695363d976ea06a4e58f69c7f7
54,813
def horizontal_flip(image_array: ndarray): """ horizontal flip doesn't need skimage, it's easy as flipping the image array of pixels ! """ return image_array[:, ::-1]
a56b12889dad254e8618326d1a85d220827652d9
54,814
def lookup(a, idx, dim=0): """ Lookup the values of input array based on index. Parameters ---------- a : af.Array. Multi dimensional array. idx : is lookup indices dim : optional: int. default: 0. Specifies the dimension for indexing Returns ------- out : af....
9084d196de4f84bfdf568ea67b3fc34f357cc88c
54,815
from typing import VT from typing import Optional from typing import Callable from typing import List from typing import Set def match_connected_hboxes(g: BaseGraph[VT,ET], edgef: Optional[Callable[[ET],bool]] = None ) -> List[ET]: """Matches Hadamard-edges that are connected to H-boxes, as these ...
d26dd13ed41ff46d5d46a8df0e4704271570ea92
54,816
def n2N(n): """ Calculate the square matrix rank N for a packed storage size n Parameters ---------- n : int The packed length. Returns ------- N : np.uint64 The matrix rank. """ N = np.uint64((np.sqrt(8*n+1)-1)/2) return N
93f73c36a52a1fb4200c07a678b0f5527439092c
54,819
from typing import Union from typing import List from typing import Tuple from typing import Dict import requests def scrape_url(url: str, python_objects: Union[bool, List, Tuple] = False, nonstandard_attrs: bool = False, migrate_old_schema: bool = True, user_agent_str: st...
7edb4a94361bd72999a546a4ae53233b31222140
54,821
import time def ecs_container_instance(request, ecs_cluster, ec2_client, ecs_client, ecs_instance_type, ecs_ami): """ Fixture to handle spin up and tear down of ECS container instance :param request: pytest request object :param ecs_cluster: ecs cluster fixture :param ec2_client: boto3 ec2 client...
9bdf9bc4c16ab1a1c0219ce7c4910e1fa8472227
54,822
from typing import Dict def sound_mode_rev_map_factory(instance: DenonAVRFoundation) -> Dict[str, str]: """ Construct the sound_mode_rev_map. Reverse the key value structure. The sound_mode_rev_map is bigger, but allows for direct matching using a dictionary key access. The sound_mode_map is uses...
c93d33501d8c54c3e38fb7221f7515acdcc2f1c7
54,823
def get_objhash_from_object_desc(gitobjcontent): """returns object hash without control characters""" return gitobjcontent.split(" ")[1][:40]
662357569cb22bf77d6236e7c53a71f19f29823a
54,824
def wgs84_to_lv03(latitude, longitude, altitude=None): """Convert WGS84 to LV03. :param float latitude: latitude in degrees :param float longitude: longitude in degrees :param float altitude: altitude :rtype: (float, float, float) """ lat_sex = dms_to_sex(*dd_to_dms(dd=latitude)) lon_se...
eb7d4c91ce0d8e0d3eeb4b40c556920457b38f14
54,825
def decrypt(signature: str, js: str): """ Main function for decrypting the signature cipher. :param signature: original signature, encrypted :param js: base.js contents :return: the decrypted signature """ functions = get_dict_functions(js) signature = [char for char in signature] ...
d630449ac6e3221a23e3a349026a06ea22558447
54,826
def get_path(origin, dest): """ MapBox APIを用いてルート探索を行う Arguments: origin {list} -- 出発地の緯度経度 dest {list} -- 到着地の緯度経度 Returns: list -- ルート探索結果 """ api = mapbox.Directions() res = api.directions([{ 'type': 'Feature', 'geometry': { 'type': 'P...
76160f50c12f27ac8db92233cb2bd71863ae6991
54,828
import collections def update_dict(to_update, updates): """ Recursively updates a nested dict `to_update` from a nested dict `updates` """ for key, val in updates.items(): if isinstance(val, collections.Mapping): to_update[key] = update_dict(to_update.get(key, {}), val) else: ...
7697d2beb42d45e60e8fdfb1386842c168bffbcc
54,829
from typing import Optional def sin(duration: int, amp: complex, freq: float = None, phase: float = 0, name: Optional[str] = None) -> SamplePulse: """Generates sine wave `SamplePulse`. Args: duration: Duration of pulse. Must be greater than zero. amp: Pulse amplitude. freq: Pu...
5f5e1f0c00991158a80d530669fc82d433fb11e4
54,830
from typing import List def list_resources() -> List[str]: """ Lists all available resources by name. :returns: A list of resources by name. """ return _get_resources(_get_resources_json()["resources"]).keys()
dad3e4920d353d9de7f7f354d5cc49ab8f5e1449
54,831
import torch def computeMaskIntersection(gt, gtMask, pred, predMask): """ Compute intersection between GT instance and prediction. Increase efficiency by computing elementwise product between masks only inside the tight bounding box of the union of the prediction and target masks. """ if g...
69dbe02148f23f7f3925aebab0a1fc8afa6544fa
54,834
from typing import Tuple from typing import Union from typing import Dict def handle_merge_duplicate_facilities( facilities: DataFrame, ) -> Tuple[DataFrame, Union[Dict[str, str], None]]: """Drops duplicate facilities by name and some other logic. Returns facility DataFrame without duplicate facilities an...
e7e1cf96aa6bf541d55865361a52b476c897980e
54,835
def get_applicant(form): """ Gets applicant info, or adds if necessary """ applicant_result = Applicant.query.filter_by(email=form.get("email")).first() if applicant_result: applicant_id = applicant_result.applicant_id else: applicant_id = add_applicant(form) return applicant_i...
8072ee16e20939eeceacda7dc80729f108c9b3ec
54,837
def graphing(dataframe_after_LDA, title, color_list, labels): """ Function that given a dataframe after the LDA, returns a graph where each point corresponds to a frame, and each cluster correspond to a different location of the mouse during the experiment (HOME, CORRIDOR, FARCHAMBER) :param dataframe...
409f040951b2215a7ae7434d8d683827bfdc9bf1
54,839
def make_sentences(diff): """Create human-readable sentences out of the diff dict.""" info = [] for t in sorted(diff.keys()): if "old" in diff[t]: old_range = make_range(diff[t]["old"]["min"], diff[t]["old"]["max"]) new_range = make_range(diff[t]["new"]["min"], diff[t]["new"]...
a18865be04cab94c36278e70c048c1d3ec550447
54,840
def swsl_resnext101_32x16d(pretrained=True, **kwargs): """Constructs a semi-weakly supervised ResNeXt-101 32x16 model pre-trained on 1B weakly supervised image dataset and finetuned on ImageNet. `"Billion-scale Semi-Supervised Learning for Image Classification" <https://arxiv.org/abs/1905.00546>`_ ...
33c1a73fd00da4a64b77fc0408cb09ad66fbdbc1
54,842
def completeTreeNames(tree, useBS = False ) : """ Takes: - tree (ete3.Tree) - useBS (bool) [default = False] : uses bootstrap to name nodes Returns: (ete3.Tree) : the tree, but where the nodes without a name now have one that correspond to their post-order OR the...
07077fce3ea18ba40af578cd1b0768a71e7b16c8
54,843
from typing import Sequence import string def password(characters: Sequence[chr] = string.printable, length: int = 8, unique: bool = False) -> str: """ :param characters: The character pool that will be used when generating the password :param length: The total length of the pass...
949b6df79021cea6654c26bf4e3aeaacc80eab82
54,844
import json def build(kernel_desc, attrs=None, poly=True, use_repo=True): """ build kernel with compute description in json format Args: kernel_desc : str or dict of compute description attrs : dict of build attributes Returns: Module. """ if isinstance(kernel_desc, str...
d2c0926f9a14e465449687bd3bdafc1387211627
54,845
def bitsize(a): """ Compute the bitsize of an element of Z (not counting the sign). """ val = abs(a) res = 0 while val: res += 1 val >>= 1 return res
18755ee3bfe2a122702f3161135288f8fae2dc8b
54,846
def InjectDll(proc, name, entry = None): """Inject a dll with CreateRemoteThread in the remote process""" kernel32 = _GetModuleHandleA(b'kernel32') if not kernel32: raise Win32Exception() LoadLibraryEx = _GetProcAddress(kernel32, b'LoadLibraryA') if not LoadLibraryEx: raise Win32Exce...
28e635ecfba55bfb68585a233942ce8971698c4b
54,847
def find_module_corner2(mask, mode=0): """ mode == 0: detect corners of the convex of module mode == 1: detect corners of the approximated convex of module mode == 2: detect corners of the approximated contour of the module mode == 3: detect corners of the blurred mask of the module """ blur...
d69d76190c166be9ed6835ee7885463e166e37da
54,848
import random def gen_rand_lists(): """ Generate two lists with random numbers in [0,5], output them and compare their mean and tell who is greater """ def gen_list(): ll = [] for i in range(5): ll.append(random.randint(0, 5)) return ll def calc_avera...
03195edb47f43ce17933188523235f87472667d1
54,849
import time import zipfile def get_image_zip(project_id, project_name, json_data, filters=None): """ Create a zip file in memory containing the project's images and a descriptive JSON file. """ all_data = ProjectImageData.query.filter_by(project_id=project_id).all() date_time = time.localtime(...
eea6da48a5f6922f3584b03e9f39d8aa092df56f
54,850
def degre(poly): """Renvoie le degré du polynôme _poly_""" poly = clear_poly(poly) return len(poly)-1
cb8413dbde586e0a8383978ae646bee8f36d6a05
54,851
def store_forecast_values(forecast_id, forecast_df): """Store Forecast data Parameters ---------- forecast_id: string UUID of the associated forecast. forecast_df: DataFrame Dataframe with DatetimeIndex and value column. Returns ------- string The UUID of the as...
7315d566a0cbd6e4ac94347c61d369cfcd37c5f4
54,852
def gather_link_defn_lines(file_lines): """Returns all link def lines occuring after main content. Should be called with set of lines starting with first non-main-content line.""" ld_lines = [] for mdfl in file_lines: if is_ld_block_begin_line(mdfl): continue # ignore the b...
bd5b6a3d3fdb7153b2bbaae14745ca705ca7606e
54,853
def _hdf5_yt_attr(fh, attr, unit_registry=None): """ Read an hdf5 attribute. If there exists another attribute named <attr>_units, use that to assign units and return as either a unyt_array or unyt_quantity. """ val = fh.attrs[attr] units = "" ufield = "%s_units" % attr if ufield in...
a751fe3997af75f4bc4539873c65d0a32580c13c
54,854
import numpy def raster_rpn_calculator_op(*args_list): """Calculate RPN expression. Args: args_list (list): a length list of N+4 long where: - the first N elements are array followed by nodata - the N+1th element is the target nodata - the N+2nd element is an RPN ...
8742cd6087d9c5aa283b33cc29c5847658a32f73
54,855
import random def get_boundary_mutation_function(minimum, maximum): """ Returns a function that pushes a value to either the minimum or maximum allowed value for a gene; see :ref:`mutation-functions` :Valid For: ``"int"``, ``"[int]"``, ``"float"``, and ``"[float]"`` gene types :param minimum...
0f3e2b6b4d69e758fb1d439d2785306da7f537e8
54,856