content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from tvm.relay.testing import mlp def mlp_net(): """The MLP test from Relay. """ return mlp.get_net(1)
4e48dfb04bab1434bd581b7fc6cd5e2257c88022
16,862
def groupByX(grp_fn, messages): """ Returns a dictionary keyed by the requested group. """ m_grp = {} for msg in getIterable(messages): # Ignore messages that we don't have all the timing for. if msg.isComplete() or not ignore_incomplete: m_type = grp_fn(msg) ...
9ebf63cfe81e8c8b6f19d90c725415cafdbcd636
16,864
import math def regular_poly_circ_rad_to_side_length(n_sides, rad): """Find side length that gives regular polygon with `n_sides` sides an equivalent area to a circle with radius `rad`.""" p_n = math.pi / n_sides return 2 * rad * math.sqrt(p_n * math.tan(p_n))
939ff5de399d7f0a31750aa03562791ee83ee744
16,865
def dbl_colour(days): """ Return a colour corresponding to the number of days to double :param days: int :return: str """ if days >= 28: return "orange" elif 0 < days < 28: return "red" elif days < -28: return "green" else: return "yellow"
46af7d57487f17b937ad5b7332879878cbf84220
16,866
def create_model(data_format): """Model to recognize digits in the MNIST data set. Network structure is equivalent to: https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/examples/tutorials/mnist/mnist_deep.py and https://github.com/tensorflow/models/blob/master/tutorials/image/mn...
d6fe45e5cfef5246a220600b67e24cddceeebd3a
16,867
def run_noncentered_hmc(model_config, num_samples=2000, burnin=1000, num_leapfrog_steps=4, num_adaptation_steps=500, num_optimization_steps=2000): """Given a (centred) model, this function transform...
95065fb8c8ee778f0d300b46f285f8f3bb026aed
16,868
import collections def get_project_apps(in_app_list): """ Application definitions for app name. Args: in_app_list: (list) - names of applications Returns: tuple (list, dictionary) - list of dictionaries with apps definitions dictionary of warnings """ apps = [] wa...
4e9be8ffddf44aba740414a8ee020376eda3a761
16,869
def read(G): """ Wrap a NetworkX graph class by an ILPGraph class The wrapper class is used store the graph and the related variables of an optimisation problem in a single entity. :param G: a `NetworkX graph <https://networkx.org/documentation/stable/reference/introduction.html#graphs>`__ :retur...
cb5db29d210d944047dbdf806ecfaaa274d517e8
16,870
def slog_det(obs, **kwargs): """Computes the determinant of a matrix of Obs via np.linalg.slogdet.""" def _mat(x): dim = int(np.sqrt(len(x))) if np.sqrt(len(x)) != dim: raise Exception('Input has to have dim**2 entries') mat = [] for i in range(dim): row ...
20b4016653d83303ac671a5d2641d4c344393b0a
16,871
def make_optimiser_form(optimiser): """Make a child form for the optimisation settings. :param optimiser: the Optimiser instance :returns: a subclass of FlaskForm; NB not an instance! """ # This sets up the initial form with the optimiser's parameters OptimiserForm = make_component_form(optimis...
745c4a9c4268d31687215f4acec709a5eacfcbf0
16,872
def prepare_for_evaluate(test_images, test_label): """ It will preprocess and return the images and labels for tesing. :param original images for testing :param original labels for testing :return preprocessed images :return preprocessed labels """ test_d = np.stack([preprocessing_for_te...
abe60fc558c6cc2c951a4efee758d2746608d8d1
16,873
async def async_setup(hass, config): """Set up the PEVC modbus component.""" hass.data[DOMAIN] = {} return True
cde898e2904f8e9cfcf60d260ee2476326877dd9
16,875
from typing import Any def deserialize_value(val: str) -> Any: """Deserialize a json encoded string in to its original value""" return _unpack_value( seven.json.loads(check.str_param(val, "val")), whitelist_map=_WHITELIST_MAP, descent_path="", )
d01ce83488ea743aae298b15d1fe5f4faac6adbc
16,876
import six import collections def stringify(value): """ PHPCS uses a , separated strings in many places because of how it handles options we have to do bad things with string concatenation. """ if isinstance(value, six.string_types): return value if isinstance(value, collections.It...
1ca24ff986f3cd02c845ad0e11b8b1cfd3c7f779
16,878
def read_requirements_file(path): """ reads requirements.txt file """ with open(path) as f: requires = [] for line in f.readlines(): if not line: continue requires.append(line.strip()) return requires
ab224bd3adac7adef76a2974a9244042f9aedf84
16,879
def vsa_get_all(context): """ Get all Virtual Storage Array records. """ session = get_session() return session.query(models.VirtualStorageArray).\ options(joinedload('vsa_instance_type')).\ filter_by(deleted=can_read_deleted(context)).\ all()
3568997b060fbeab115ec79c2c0cba77f78c6cba
16,880
import threading def thread_it(obj, timeout = 10): """ General function to handle threading for the physical components of the system. """ thread = threading.Thread(target = obj.run()) thread.start() # Run the 'run' function in the obj obj.ready.wait(timeout = timeout) # Clean u...
02ed60a560ffa65f0364aa7414b1fda0d3e62ac5
16,882
def _subsize_sub_pixel_align_cy_ims(pixel_aligned_cy_ims, subsize, n_samples): """ The inner loop of _sub_pixel_align_cy_ims() that executes on a "subsize" region of the larger image. Is subsize is None then it uses the entire image. """ n_max_failures = n_samples * 2 sub_pixel_offsets = np...
f96a2bc9b4c55976fd4c49da3f59afa991c53ff1
16,883
def obj_setclass(this, klass): """ set Class for `this`!! """ return this.setclass(klass)
4447df2f3055f21c9066a254290cdd037e812b64
16,884
def format(number, separator=' ', format=None, add_check_digit=False): """Reformat the number to the standard presentation format. The separator used can be provided. If the format is specified (either 'hex' or 'dec') the number is reformatted in that format, otherwise the current representation is kept...
6890ed398eb7c173540c0392b9ed8ef66f8d170b
16,885
def parse_equal_statement(line): """Parse super-sequence statements""" seq_names = line.split()[1:] return seq_names
ee0de00a990ac10c365af16dccf491b7ea8ed785
16,886
def B5(n): """Factor Variables B5.""" return np.maximum(0, c4(n) - 3 * np.sqrt(1 - c4(n) ** 2))
bc2fbd91e337310fe5d4326d55440ce2055da650
16,887
def y_yhat_plots(y, yh, title="y and y_score", y_thresh=0.5): """Output plots showing how y and y_hat are related: the "confusion dots" plot is analogous to the confusion table, and the standard ROC plot with its AOC value. The y=1 threshold can be changed with the y_thresh parameter. """ # The ...
82a8154bd618cc1451a44b2b42fca0407e9979cb
16,888
def _derive_scores(model, txt_file, base_words): """ Takes a model, a text file, and a list of base words. Returns a dict of {base_word: score}, where score is an integer between 0 and 100 which represents the average similarity of the text to the given word. """ with open(txt_file, 'r') as...
9c377b5dec742f5ba174f780252fd78d162a8713
16,889
def features_ids_argument_parser() -> ArgumentParser: """ Creates a parser suitable to parse the argument describing features ids in different subparsers """ parser = ArgumentParser(add_help=False, parents=[collection_option_parser()]) parser.add_argument(FEATURES_IDS_ARGNAME, nargs='+', ...
df24ebaff182c88c7ad6cf38e2e4a5784d54a48b
16,891
def isolate_blue_blocks(image, area_min=10, side_ratio=0.5): """Return a sequence of masks on the original area showing significant blocks of blue.""" contours, _ = cv2.findContours( blue(image).astype(np.uint8) * 255, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE ) rects = [] for c in contours: ...
7cd6e895750f208e18c60a48d2bc0e8d1710d6c0
16,892
from typing import Union from io import StringIO from pathlib import Path from typing import Optional from typing import Dict from typing import Callable from typing import List from typing import Tuple def read_gtf( filepath_or_buffer: Union[str, StringIO, Path], expand_attribute_column: bool = True, inf...
c7478d88ce5d6d6e823bf28c965f366b9b8d1522
16,893
def trimAlphaNum(value): """ Trims alpha numeric characters from start and ending of a given value >>> trimAlphaNum(u'AND 1>(2+3)-- foobar') u' 1>(2+3)-- ' """ while value and value[-1].isalnum(): value = value[:-1] while value and value[0].isalnum(): value = value[1:] ...
e9d44ea5dbe0948b9db0c71a5ffcdd5c80e95746
16,895
def hrm_job_title_represent(id, row=None): """ FK representation """ if row: return row.name elif not id: return current.messages.NONE db = current.db table = db.hrm_job_title r = db(table.id == id).select(table.name, limitby = (0, 1)).first() ...
ca3d2bfb4056b28b712f4cbf37c8c91d840c0161
16,896
def is_empty_array_expr(ir: irast.Base) -> bool: """Return True if the given *ir* expression is an empty array expression. """ return ( isinstance(ir, irast.Array) and not ir.elements )
dcf3775e7544ad64e9a533238a9549ed21dc3393
16,897
def get_raw_entity_names_from_annotations(annotations): """ Args: annotated_utterance: annotated utterance Returns: Wikidata entities we received from annotations """ raw_el_output = annotations.get("entity_linking", [{}]) entities = [] try: if raw_el_output: ...
482be69ef5fec52b70ade4839b48ae2f4155033b
16,898
def nextPara(file, line): """Go forward one paragraph from the specified line and return the line number of the first line of that paragraph. Paragraphs are delimited by blank lines. It is assumed that the current line is standalone (which is bogus). - file is an array of strings - line is the...
a104042225bc9404a5b5fe8f5410a3021e45f64d
16,899
def build_asignar_anexos_query(filters, request): """ Construye el query de búsqueda a partir de los filtros. """ return filters.buildQuery().filter(ambito__path__istartswith=request.get_perfil().ambito.path).order_by('nombre')
1a176182fa0559bac56df17f32345d2c4c22b1f1
16,900
def _median(data): """Return the median (middle value) of numeric data. When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values: >>> median([1, 3, 5]) 3 >>> median...
f05a6b067f95fc9e3fc9350b163b3e89c0792814
16,902
def num_translate(value: str) -> str: """переводит числительное с английского на русский """ str_out = NUM_DICT.get(value) return str_out
8555556843ea5235f462dbb7b092eaa09168ab0e
16,903
def get_patch_shape(corpus_file): """Gets the patch shape (height, width) from the corpus file. Args: corpus_file: Path to a TFRecords file. Returns: A tuple (height, width), extracted from the first record. Raises: ValueError: if the corpus_file is empty. """ example = tf.train.Example() t...
054a43d1aa7809b55c57fa0e7574dd43273f4bae
16,904
import re def _TopologicallySortedEnvVarKeys(env): """Takes a dict |env| whose values are strings that can refer to other keys, for example env['foo'] = '$(bar) and $(baz)'. Returns a list L of all keys of env such that key2 is after key1 in L if env[key2] refers to env[key1]. Throws an Exception in case of ...
78ee345ed67d61994245efff8b103d908aa1a7a4
16,905
def get_children_as_dict(parent): """For a given parent object, return all children as a dictionary with the childs tag as key""" child_list = getChildElementsListWithSpecificXpath(parent, "*") child_dict = {} for child in child_list: value = get_children_as_dict(child) if child.tag not ...
054d3591a34536c79e0e5b3715dad6e414d29d46
16,906
import itertools import six def get_multi_tower_fn(num_gpus, variable_strategy, model_fn, device_setter_fn, lr_provider): """Returns a function that will build the resnet model. Args: num_gpus: number of GPUs to use (obviously) variable_strategy: "GPU" or "CPU" m...
72e149d25cc6c80a8ea4c5f35f9215cb71aa2a65
16,908
from typing import Union def extract_by_css( content: str, selector: str, *, first: bool = True ) -> Union[str, list]: """Extract values from HTML content using CSS selector. :param content: HTML content :param selector: CSS selector :param first: (optional) return first found element or all of t...
b03d76c893c0f23da332c9978bedc5c9c408e840
16,909
def generate_styles(): """ Create custom style rules """ # Set navbar so it's always at the top css_string = "#navbar-top{background-color: white; z-index: 100;}" # Set glossdef tip css_string += "a.tip{text-decoration:none; font-weight:bold; cursor:pointer; color:#2196F3;}" css_string += "a.ti...
44b36321dedba352c6aa30a352c7cd65cca1f79a
16,910
from pathlib import Path def get_config_file() -> Path: """ Get default config file. """ return get_project_root()/'data/config/config.yaml'
92bc2af7e55b424bcf10355790f377c90a73cf9b
16,911
def kilometers_to_miles(dist_km): """Converts km distance to miles PARAMETERS ---------- dist_km : float Scalar distance in kilometers RETURNS ------- dist_mi : float Scalar distance in kilometers """ return dist_km / 1.609344
61707d483961e92dcd290c7b0cd8ba8f650c7b5b
16,912
def _objc_provider_framework_name(path): """Returns the name of the framework from an `objc` provider path. Args: path: A path that came from an `objc` provider. Returns: A string containing the name of the framework (e.g., `Foo` for `Foo.framework`). """ return path.rpartition("/"...
607c040a9a9c56a793473ffcba779fc7d7a64ed5
16,913
def sample_publisher(name='EA'): """Create and return a sample publisher""" return Publisher.objects.create(name=name)
da3d859897c9c3a6f98aa9a7950d77d1390a7527
16,915
def AddGlobalFile(gfile): """ Add a global file to the cmd string. @return string containing knob """ string = '' if gfile: string = ' --global_file ' + gfile return string
70c4bee610766bbea4faf4e463f88ee65f8804f5
16,916
def read_file(filename): """Opens the file with the given filename and creates the puzzle in it. Returns a pair consisting of the puzzle grid and the list of clues. Assumes that the first line gives the size. Afterwards, the rows and clues are given. The description of the rows and clues may interleave ...
332ea941aef3b484e2083bfcc734d4bc9fd7f62c
16,918
def login_user(request): """View to login a new user""" user = authenticate(username=request.POST['EMail'][:30], password=request.POST['Password']) if user is not None: if user.is_active: login(request, user) send_email("ROCK ON!!!", "User login - " + user.first_name + " " + ...
ce3c126192df1aeab171438587cdc78a51ebda77
16,919
def gdf_convex_hull(gdf): """ Creates a convex hull around the total extent of a GeoDataFrame. Used to define a polygon for retrieving geometries within. When calculating densities for urban blocks we need to retrieve the full extent of e.g. buildings within the blocks, not crop them to an arbitrar...
c636e67b77ed312a952e7f4af3b3535c983417e3
16,920
from typing import Dict from typing import Any def room_operating_mode(mode: str) -> Dict[str, Any]: """Payload to set operating mode for :class:`~pymultimatic.model.component.Room`. """ return {"operationMode": mode}
df5d1434d5994eca266a3fd06b6a742710bad0eb
16,921
from typing import Dict from typing import Any def _validate_options(data: Dict[str, Any]) -> Dict[str, Any]: """ Looks up the exporter_type from the data, selects the correct export options serializer based on the exporter_type and finally validates the data using that serializer. :param data: A...
8d380d3052c3e1cd4d859fa46829034ba1cf6860
16,922
def householder_name (name, rank): """Returns if the name conforms to Householder notation. >>> householder_name('A_1', 2) True >>> householder_name('foobar', 1) False """ base, _, _ = split_name(name) if base in ['0', '1']: return True elif rank == 0: if base in...
63ff3395e065a79b4d5ee76fb3092efa0cb32b2b
16,923
def calculateDerivatives(x,t,id): """ dxdt, x0, id_, x_mean = calculateDerivatives(x,t,id) Missing data is assumed to be encoded as np.nan """ nm = ~np.isnan(t) & ~np.isnan(x) # not missing id_u = np.unique(id) id_ = [] dxdt = [] x0 = [] x_mean = [] for k in range(0...
86a6e2fc3e50e65ffd162728b79b50ab6ee09a81
16,924
import requests import time def SolveCaptcha(api_key, site_key, url): """ Uses the 2Captcha service to solve Captcha's for you. Captcha's are held in iframes; to solve the captcha, you need a part of the url of the iframe. The iframe is usually inside a div with id=gRecaptcha. The part of the url we ...
e610a265d03be65bfd6321a266776a8102c227d0
16,925
def clean_crn(crn, duplicates = True, trivial = True, inter = None): """Takes a crn and removes trivial / duplicate reactions. """ new = [] seen = set() for [R, P] in crn: lR = sorted(interpret(R, inter)) if inter else sorted(R) lP = sorted(interpret(P, inter)) if inter else sorted(P) ...
28f4e8eac7b6aea0505491ef55ce54d8d05f0069
16,927
def get_db_mapping(mesh_id): """Return mapping to another name space for a MeSH ID, if it exists. Parameters ---------- mesh_id : str The MeSH ID whose mappings is to be returned. Returns ------- tuple or None A tuple consisting of a DB namespace and ID for the mapping or N...
ae3f8de5c93ab0230a7c87edfa2d3996a9c8667b
16,928
def MC_dBESQ_gateway(N = 10**6, t = 0, n0 = 0, test = 'laguerre', method = 'laguerre', args = [], num_decimal = 4): """ Monte Carlo estimator of expected dBESQ using birth-death simulation, exact BESQ solution, dLaguerre simulation or PDE systems. :param N: int, Number of simulations :param T: posi...
6d09ca8ef2f772e194c7ae656ec4bf9e8a2b6948
16,929
def resolve_image(image): """ Resolve an informal image tag into a full Docker image tag. Any tag available on Docker Hub for Neo4j can be used, and if no 'neo4j:' prefix exists, this will be added automatically. The default edition is Community, unless a cluster is being created in which case Enterpris...
7d03b936f90c459a2dade179d9e38bd17c8c1af8
16,931
def _cifar_meanstd_normalize(image): """Mean + stddev whitening for CIFAR-10 used in ResNets. Args: image: Numpy array or TF Tensor, with values in [0, 255] Returns: image: Numpy array or TF Tensor, shifted and scaled by mean/stdev on CIFAR-10 dataset. """ # Channel-wise means and std devs cal...
286ab555d30fd779c093e3b8801821f8370e1ca8
16,932
def get_value_counts_and_frequencies(elem: Variable, data: pd.DataFrame) -> Categories: """Call function to generate frequencies depending on the variable type Input: elem: dict data: pandas DataFrame Output: statistics: OrderedDict """ statistics: Categories = Categories() _scale...
7afe35dc605c1eb25158c8a948eeabcfb0027dc6
16,933
def determineLinearRegions(data, minLength=.1, minR2=.96, maxSlopeInterceptDiff=.75): """ Determine regions of a plot that are approximately linear by performing linear least-squares on a rolling window. Parameters ---------- data : array_like Data within which linear regions a...
318672634082ae87b18f087e8aee65efc1da3f59
16,934
def compute_dispersion(aperture, beam, dispersion_type, dispersion_start, mean_dispersion_delta, num_pixels, redshift, aperture_low, aperture_high, weight=1, offset=0, function_type=None, order=None, Pmin=None, Pmax=None, *coefficients): """ Compute a dispersion mapping from a IRAF multi-spec descri...
94fcb70652bad0f2fa26cf73981129f3ae949d8b
16,935
def normalize_pcp_area(pcp): """ Normalizes a pcp so that the sum of its content is 1, outputting a pcp with up to 3 decimal points. """ pcp = np.divide(pcp, np.sum(pcp)) new_format = [] for item in pcp: new_format.append(item) return np.array(new_format)
ea0feeda3f8515b538ae62b08aad09a16ddb2a73
16,936
def calc_line_flux(spec, ws, ivar, w0, w1, u_flux): """ calculate the flux and flux error of the line within the range w0 and w1 using trapz rule""" u_spec = spec.unit u_ws = ws.unit ivar = ivar.to(1./(u_spec**2)) spec_uless = np.array(spec) ws_uless = np.array(ws) ivar_uless = np.array(ivar) if ivar.unit != ...
78206ce98025ead64e207bd69a8adf1a31178744
16,937
def boolean(entry, option_key="True/False", **kwargs): """ Simplest check in computer logic, right? This will take user input to flick the switch on or off Args: entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1. option_key (str): What kind of Boolean we are setting. W...
d62b36d08651d02719b5866b7798c36efd2a018f
16,938
import tqdm import copy def edge_preserving_filter(ref_map: np.ndarray, guided_image: np.ndarray, window_size: int, epsilon: float = 1e-10) -> np.ndarray: """ Perform edge - preserving filtering on the newly created reference map. :param ref_map: Classification reference map. ...
1ca88240c26fd4eae67f869bc95a8b0ce885260b
16,939
from typing import List def preprocess_annotated_utterance( annotated_utterance: str, not_entity: str = NOT_ENTITY, ) -> List[str]: """Character Level Entity Label Producer Named-entity of each character is extracted by XML-like annotation. Also, they would be collected in a l...
b148f19017b97a0f4859abc129cdca50fd187c15
16,940
from typing import List from typing import Tuple import jinja2 def generate_constant_table( name: str, constants: List[Constant], *, data_type: str = "LREAL", guid: str = "", lookup_by_key: bool = False, **kwargs ) -> Tuple[str, str]: """ Generate a GVL constant table, with no inte...
54b491ac3673c68a0e7ef819389e393e921d841f
16,941
def filter_stop_words(text): """ Filter all stop words from a string to reduce headline size. :param text: text to filter :return: shortened headline """ words = filter(lambda w: not w in s, text.split()) line = "" l = 0 for w in words: if l < 20: line += w + " "...
d27b63018fa8f7b2d072e768c54ce4a056c58ff1
16,942
def importPublicKey(publickey): """ Cette fonction permet de exporter la clé public, elle prend en paramètre use clé public """ return RSA.importKey(publickey)
b744efc95fc154edcf4149134b7b307e75a0bb17
16,943
def _format_contact(resource, key): """ Return the contact field with the correct values. This is mainly stripping out the unecessary fields from the telecom part of the response. """ contacts = resource.pop(key) resource[key] = [] for contact in contacts: contact["telecom"] = _...
57291dfdf2a724df2cd2342891aa96309648a9c1
16,944
from datetime import datetime def get_day_type(date): """ Returns if a date is a weeday or weekend :param date datetime: :return string: """ # check if date is a datetime.date if not isinstance(date, datetime.date): raise TypeError('date is not a datetime.date') day_type = "" ...
72d74746a7782e0f45b3b7d0292b4cbd4ad9f167
16,945
def case_insensitive_equals(name1: str, name2: str) -> bool: """ Convenience method to check whether two strings match, irrespective of their case and any surrounding whitespace. """ return name1.strip().lower() == name2.strip().lower()
28b7e5bfb5e69cf425e1e8983895f1ad42b59342
16,946
def get_access_token(cmd, subscription=None, resource=None, scopes=None, resource_type=None, tenant=None): """ get AAD token to access to a specified resource. Use 'az cloud show' command for other Azure resources """ if resource is None and resource_type: endpoints_attr_name = cloud_resourc...
9a5190db41e4061698ead3846a6e53f42e64deed
16,947
def ensure_listable(obj): """Ensures obj is a list-like container type""" return obj if isinstance(obj, (list, tuple, set)) else [obj]
bdc5dbe7e06c1cc13afde28762043ac3fb65e5ac
16,948
def merge_dicts(*dicts: dict) -> dict: """Merge dictionaries into first one.""" merged_dict = dicts[0].copy() for dict_to_merge in dicts[1:]: for key, value in dict_to_merge.items(): if key not in merged_dict or value == merged_dict[key]: merged_dict[key] = value ...
b32a9f4bed149144a3f75b43ed45c8de4351f3d1
16,949
from re import X def winner(board): """ Returns the winner of the game, if there is one. """ for moves in _winner_moves(): if all(board[i][j] is X for (i, j) in moves): return X elif all(board[i][j] is O for (i, j) in moves): return O return None
c6e3b35b2cf37ff3da4fe5cd306f7a6f78603f16
16,950
def specified_kwargs(draw, *keys_values_defaults: KVD): """Generates valid kwargs given expected defaults. When we can't realistically use hh.kwargs() and thus test whether xp infact defaults correctly, this strategy lets us remove generated arguments if they are of the default value anyway. """ ...
bd3dfdcbb084a87b0c60d9221692f8fbd3e70333
16,951
def add_image(): """User uploads a new landmark image, and inserts into db.""" imageURL = request.form.get("imageURL") landmark_id = request.form.get("landmark_id") new_image = LandmarkImage(landmark_id=landmark_id, imageurl=imageURL) db.session.add(new_image) d...
dce5f9c21daef67b1a13b1d590fe027213c408e0
16,952
def merge(link1: Node, link2: Node) -> Node: """ Merge two linklists. Parameters ----------- link1: Node link2: Node Returns --------- out: Node Notes ------ """ link = Node(None) ptr = link while link1 and link2: if link1.val <= link2.val: ...
5d40acbd1ffb595a7f4605c3181ede19fb4adbb3
16,953
def l1_norm_optimization(a_i, b_i, c_i, w_i=None): """Solve l1-norm optimization problem.""" cvx.solvers.options['show_progress'] = not CVX_SUPRESS_PRINT # Non-Weighted optimization: if w_i is None: # Problem must be formulated as sum |P*x - q| P = cvx.matrix([[cvx.matrix(a_i)], [cvx.ma...
0966516185c99b936a1fcc8b3d4c74e67587bc63
16,954
def set_order(market, order_type, amount, price, keys, stop_price=None): """ Create an order Arguments: market (str) : market name, order_type (str) : may be "limit", "market", "market_by_quote", "limit_stop_loss" amount (float) : positive if BUY order, and negative for SELL ...
8f9823be8a39d404062114432604c8480aed20c6
16,955
import calendar def convert_ts(tt): """ tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1) >>> tt = time.strptime("23.10.2012", "%d.%m.%Y") >>> convert_ts(tt) 1350950400 tt: time.struct_time(tm_year=1513, tm_mon=1...
a3c2f5ae3d556290b6124d60fd4f84c1c2685195
16,956
def data_context_path_computation_context_path_comp_serviceuuid_optimization_constraint_name_post(uuid, tapi_common_name_and_value=None): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_optimization_constraint_name_post creates tapi.common.NameAndValue # noqa: E501 :param uuid...
fef62699a5a16385ffeeb47f252c1a3142fa9c96
16,957
import re import json def receive_github_hook(request): """a hook is sent on some set of events, specifically: push/deploy: indicates that the content for the repository changed pull_request: there is an update to a pull request. This function checks that (globally) the event is val...
874a71c3c9c002f3714ce0b4bb80586e8d67d7e8
16,958
import torch def dice(y, t, normalize=True, class_weight=None, ignore_label=-1, reduce='mean', eps=1e-08): """ Differentable Dice coefficient. See: https://arxiv.org/pdf/1606.04797.pdf Args: y (~torch.Tensor): Probability t (~torch.Tensor): Ground-truth label normalize (b...
dd0b6fb75688ed0579a3bf9a513f73d0b785e57e
16,959
def read_start_params(path_or_database): """Load the start parameters DataFrame. Args: path_or_database (pathlib.Path, str or sqlalchemy.MetaData) Returns: params (pd.DataFrame): see :ref:`params`. """ database = load_database(**_process_path_or_database(path_or_database)) opt...
31cc6d5f538a8616f9eda676e4bf8757f02f1cb3
16,960
def calcCovariance(modes): """Return covariance matrix calculated for given *modes*.""" if isinstance(modes, Mode): array = modes._getArray() return np.outer(array, array) * modes.getVariance() elif isinstance(modes, ModeSet): array = modes._getArray() return np.dot(arra...
7803e765dcf4ad40158040013691bd0f3d7775be
16,962
def sparse_tensor_value_to_texts(value): """ Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings representing its values. This function has been modified from Mozilla DeepSpeech: https://github.com/mozilla/DeepSpeech/blob/master/util/text.py # This Source Code Form is...
e1133532ecd88478d9a5a96773e413992e6566f8
16,963
def coding_problem_45(rand5): """ Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive). Note: for n >= 24, rand5() ** n is a multiple of 7 and therefore rand5() ** 24 % 7 is an unb...
8e26c6f95d953e0a8b3d8a33232c886742a535ce
16,964
def handle_rss_api(output, kwargs): """ Special handler for API-call 'set_config' [rss] """ name = kwargs.get('keyword') if not name: name = kwargs.get('name') if not name: return None feed = config.get_config('rss', name) if feed: feed.set_dict(kwargs) else: ...
73bd10dc2a40cc1648423372e8fcae065e83dbce
16,965
def progress(job_id, user: User = Depends(auth_user), db: Session = Depends(get_db)): """ Get a user's progress on a specific job. """ job = _job(db, job_id) check_job_user(db, user, job) progress = rules.get_progress_report(db, job, user) return progress
fc581297463bc46ce461811d7f675cc99ee63b65
16,966
import json def getRoom(borough): """Return a JSON dataset for property type of airbnb listing""" prpt = db.session.query(data.Borough, data.Room_Type, data.Price, data.Review_Rating, data.review_scores_cleanliness, data.review_scores_value, data.host_r...
2ae05f1f5a501b0a8e25dfc7b212cb0aeecbc0f1
16,967
def get_info(name_file, what='V', parent_folder='txt_files'): """Get data from txt file and convert to data list :param name_file : name of the file, without txt extension :param what : V = vertices, E = edges, R = pose :param parent_folder""" file_path = get_file_path(name_file, parent_folder) ...
f06608340622c7173dffabb6c08f178b9e887e73
16,968
def receive_message( sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" header = _receive_data_on_socket(sock, 16) length = _UNPACK_INT(header[:4])[0] actual_op = _UNPACK_INT(header[12:])[0] if operation != actual_op: ...
0c1cd762a2a0889d2894993e0f5362e0acdaee36
16,969
def cycle_interval(starting_value, num_frames, min_val, max_val): """Cycles through the state space in a single cycle.""" starting_in_01 = (starting_value - min_val) / (max_val - min_val) grid = np.linspace(starting_in_01, starting_in_01 + 2., num=num_frames, endpoint=False) grid ...
34fa0d60b9d5d99eee9666d70c77e4375d37ace8
16,970
def commit_ref_info(repos, skip_invalid=False): """ Returns a dict of information about what commit should be tagged in each repo. If the information in the passed-in dictionary is invalid in any way, this function will throw an error unless `skip_invalid` is set to True, in which case the invalid ...
86425248cd4a90aa75d03c2965d63aba3a38e81d
16,971
def function(x, axis=0, fast=False): """ Estimate the autocorrelation function of a time series using the FFT. :param x: The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. :param ax...
cb71d63ee35adde701eba91e068b0f6898005f04
16,972
def find_binaries(*args, **kwargs): """Given images data, return a list of dicts containing details of all binaries in the image which can be identified with image_id or image_tag. One of image_id or image_tag must be specified. :params: See `find_image` :exception: exceptions.ImageNotFound ...
0bc4345279f11cc751f4aee62a7773f0fa21643a
16,973
import copy def solve_version(d): """ solve version difference, argument map d is deepcopied. """ # make copy d = copy.deepcopy(d) v = d.get('version', 0) # functions in _update for f in _update_chain[v:]: d = f(d) return d
ce6a412cc2350a3f6c97c7e1f649a537c35f6722
16,974