content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def uuid_mole_index(moles, mole_uuid): """Return the index of the first mole with the specified uuid.""" for i, mole in enumerate(moles): if mole["uuid"] == mole_uuid: return i return None
851877da59f6a6dd8c06b9bb2d462f6239d512e7
48,800
from typing import Optional import random import scipy def edge_plate2( plate: int = 384, sigma: Optional[float] = None, spread: Optional[float] = None, invert: Optional[float] = None, randomise_edges: bool = False, ) -> Plate: """ Create a plate with an edge effect. Use a diffusion mo...
8b2b487961943b264f388a3a02abfafba1cf9e0e
48,801
from datetime import datetime import logging def check_if_sent(cursor, database, sensor, relaxation): """ Verify if the notification for given sensor was sent or not within the period specified by relaxation. :param cursor: cursor to database connection :param database: database connection :param ...
abad352d3766bf5ce4993751d82670fef770c7be
48,802
def to_timetable(stops_df, stop_times_df, trips_df) -> Timetable: """Convert a pandas timetable to Raptor algorithm datatypes""" # Stations and stops, i.e. platforms stations = Stations() stops = Stops() for s in stops_df.itertuples(): station = Station(s.stop_uic, s.stop_uic) stat...
c8416b93708a79b2b99821ed8dd675ff68ae609d
48,803
import requests def cobjects(url='/display/DOCS/REST+Complex+Objects'): """Scrape Cobjects spec.""" print('==> Cobjects', end='') degenerated = {} u_types = set() d_types = {} for name, href in indexer(url): print('.', end='') page = bs(requests.get(BASE + href).text).select...
a6eb6f1181cfbe0c512d02c3a6d9f5fc68a754e8
48,804
def pearson_between_feature(X,threshold): """ Computes the Pearson Correlation between each feature and drops the higlhy correlated features Keyword arguments: X -- The feature vectors y -- The target vector threshold -- Threshold value used to decide which features to keep (above the threshold) """ if verbos...
fa2917780cdd6e79e02dea14b60074e8afda7a2f
48,805
import torch def bin_concrete_sample(a, temperature, hard = False, eps = 1e-8): """" Sample from the binary concrete distribution """ device = torch.device("cuda" if a.is_cuda else "cpu") U = torch.rand(a.shape) L = Variable(torch.log(U + eps) - torch.log(1. - U + eps)).to(device) X = torch.sigmoid((L + a) / ...
c4aa4f0c3b200e90302ded19af4d717d6dd45f62
48,806
from re import DEBUG def product_update(uuid): """ Product update route :return Endpoint with RESTful pattern # pylint: disable=line-too-long See https://madeiramadeira.atlassian.net/wiki/spaces/CAR/pages/2244149708/WIP+-+Guidelines+-+RESTful+e+HATEOS :rtype flask.Response --- ...
68d88eacdbfa017e1f35c1ed872db2f5e9f9ac88
48,807
from typing import Dict from typing import List def check_procs(procs: Dict[int, Popen]) -> List[bool]: """Checks on the status of running jobs. Args: procs (Dict[int, Popen]): A dictionary where the keys are the worker ids and the values are the process objects ...
bc1166764417cfcfaacd75ba66d194429e562800
48,808
from typing import List def compute_permutation_distance( distance_matrix: np.ndarray, permutation: List[int] ) -> float: """Compute the total route distance of a given permutation Parameters ---------- distance_matrix Distance matrix of shape (n x n) with the (i, j) entry indicating the ...
953bed917e5284e43eb99016e54875a53ab384a4
48,809
def dashboard(request): """ Display applications owned by the current user. Include dependency info in the context! """ if not utils.email_check(request): return HttpResponseRedirect(reverse('profiles_my_profile_detail')) # all apps by this user apps_data = {} for app i...
c70e68965605105bde82a4936a6348a63171ad96
48,810
def create_bus_trace(net, buses=None, size=5, patch_type="circle", color="blue", infofunc=None, trace_name='buses', legendgroup=None, cmap=None, cmap_vals=None, cbar_title=None, cmin=None, cmax=None, colormap_column="vm_pu"): """ Creates a plotly trace of pandapower bus...
36e07ac2c3ea5fa9518bc7bf13d7e65c48d54cc4
48,811
def encrypt(text): """encrypt """ if text is None or not isinstance(text, str): return None return AESCipher.cipher.encrypt(text)
552ce18cdafd5c0b73dc65e12f64aea504a85daf
48,812
def fft_convolve(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ Non batched FFT Convolution. This function performs n-dimensional convolution based on input dimensionality. Parameters ----------- signal: af.Array - An n-dimensional array. kernel: af.Array - A...
19994a93c0d6d5684a180b5c82933d42c5b2f8e8
48,813
def pick_frames(poses, is_train=True): """Pick valid frames, each ~GAP apart. Since some frames may have invalid poses, we first extract the longest segment we can without a gap larger than GAP (for 'train') We then sample from this longest segment. For 'train', some sampled frames might be invalid,...
368ec0b2545796511b0d243a371e01402f7bd608
48,814
async def info(msg, mobj): """ Return current channel/guild information """ chan = mobj.channel serv = mobj.guild chan_name, serv_name = None, None chan_id, serv_id = 0, 0 if hasattr(chan, 'name'): chan_name = chan.name if hasattr(serv, 'name'): serv_name = serv.name if hasattr(c...
e2ca3a3dad6b5b13305aa15d08809f8a73e61b42
48,815
import time def run_graph(device, input_shape, axes, num_layers, py, scale, train, num_iters): """Run the graph and print its execution time. Args: device: string, the device to run on. input_shape: shape of the input tensor. axes: axes that are to be normalized across. num_layers: ...
c2b37e564fbb18fb12c89951fdedd7a1a4ed30ac
48,816
import torch def make_masked_coordinate_tensor(mask, dims=(28, 28, 28)): """Make a coordinate tensor.""" coordinate_tensor = [torch.linspace(-1, 1, dims[i]) for i in range(3)] coordinate_tensor = torch.meshgrid(*coordinate_tensor) coordinate_tensor = torch.stack(coordinate_tensor, dim=3) coordina...
521454567e38f63c315ad1db198bb632d8a56658
48,817
def atleast_2d_col(A): """ Return the input `A` as a 2d column array. """ return atleast_2d(A,'col')
098c47d921d0390b68fdddee491139af68a98b56
48,818
def f_read_raw_mat_length(filename, data_format='f4'): """f_read_raw_mat_length(filename,data_format='float',end='l') Read length of data """ f = open(filename,'rb') tmp = f.seek(0, 2) bytes_num = f.tell() f.close() if data_format == 'f4': return int(bytes_num / 4) else: ...
07ad3d0c425fd01f3985c4f3daf5a762bf59f76c
48,819
def automl_params_overwrite(params): """Overwrite some training options based on the selected automl mode""" params_copy = params.copy() if params_copy["forecasting_style"].startswith("auto"): params_copy["season_length"] = get_seasonality(params_copy["frequency"], DEFAULT_SEASONALITIES) par...
47107601b935b645b75fe04afbfea04594a6b581
48,820
def parse_StatsReq(msg, packet): """ Parse StatReq messages Args: msg: packet: """ # Get type = 16bits # Get flags = 16bits of_stat_req = packet[0:4] ofstat = unpack('!HH', of_stat_req) msg.stat_type = ofstat[0] msg.flags = ofstat[1] start = ...
11b5ebd453a7b3554b003b2acfba4880834f810c
48,821
def apply_feature( context, entity, feature, values, country=None, start_date=None, end_date=None, comment=None, authority=None, date_formats=[], ): """This is pretty specific to the needs of OFAC/CSL data.""" feature = feature.replace("Digital Currency Address - ", "") ...
5e5a7c90f376253dd80818dd59ae27ecc146a5ef
48,822
import io import os def test_precmd_handler_runs(): """Test attached precmd handler is executed. If it executes the value in val will change to True. """ # Treat val as a box (list) instead of a variable to get around Pythons # scoping rules. val = [False] def precmd(line): val[0...
75f19d84f184108e7f5a8002a451b4f2b674536c
48,823
def plot_rolling_returns_multiple(returns_arr, factor_returns=None, logy=False, ax=None, names_arr=None, extra_bm=0): """ Plots cumulative rolling returns versus some benchmarks'. This is based on https://github.com/quantopian/pyfolio/blob/master/pyfolio/plotting.py, but modified to plot multiple rolli...
9e47f9e6cd92c087d0f6a1bbf04005d93a0528af
48,824
def _analyze_gens(gens): """Support for passing generators as `*gens` and `[gens]`. """ if len(gens) == 1 and hasattr(gens[0], '__iter__'): return tuple(gens[0]) else: return tuple(gens)
f32eb1faf7f1aae2f8d4eff72609732db8655899
48,825
def canonical_representation(a, d, DE): """ Canonical Representation. Given a derivation D on k[t] and f = a/d in k(t), return (f_p, f_s, f_n) in k[t] x k(t) x k(t) such that f = f_p + f_s + f_n is the canonical representation of f (f_p is a polynomial, f_s is reduced (has a special denominator...
75397c72e8f78a4ad2fd81fec01d26652c406b9f
48,826
import csv def load_protocol_from_csv_file(path, session=None): """ Read a (.csv) paradigm file consisting of values yielding (occurence time, (duration), event ID, modulation) and returns a paradigm instance or a dictionary of paradigm instances Parameters ---------- path: string, ...
88cd72f017e5b3773755765b059c19a6cc68e602
48,827
def get_driver(worker_url=None): """ :rtype: dao.control.worker.provisioning.foreman.ForemanDriver """ module, obj = CONF.worker.provision_driver.rsplit('.', 1) LOG.info('Load %s from %s', obj, module) module = eventlet.import_patched(module) return getattr(module, obj)(worker_url)
398fb74fa7cf0bd72d629411409afa77268d503f
48,828
def preparation_time_in_minutes(number_of_layers: int) -> int: """ Args: number_of_layers (int): the number of layers you want to add to the lasagna. Returns: int: how many times you would spend making them. """ return 2 * number_of_layers
90b6e6f518acbba514af5d3ab77dff2e5735535a
48,829
def quicksort(x): """ Describe how you are sorting `x` Goal: First: Select a pivot point. In this case the first bin in the list. Second: Put all of other items in the list ordered arround the pivot variable Third: Recursively do the same to each side of the list Fourth: If the list be...
a2c8d23331a694c31f5ab7974feecc3243145da8
48,830
import os def normpath(path): """Returns the fully resolved absolute path to a file. This function will return the absolute path to a file as seen from the directory the script was called from. """ if path and path[0] == '/': return os.path.normpath(path) return os.path.normpath(os.p...
b07e26e7a7b03abf72024c0f1165658b255a4114
48,831
from typing import Union def gb_to_mib(gb: Union[int, float]) -> float: """ Gigabyte (Gb) to Mebibyte (MiB) :param gb: Gigabytes (Gb) :return: Mebibytes (MiB) """ return gb * 953.674
4a30792df2dbb0220223460f4f5cbe999a102b77
48,832
from typing import Optional from typing import Tuple import os def getPendingUpdate() -> Optional[Tuple]: """Returns a tuple of the path to and version of the pending update, if any. Returns C{None} otherwise. """ try: pendingUpdateFile=state["pendingUpdateFile"] pendingUpdateVersion=state["pendingUpdateVersio...
97ac9c473d200518973f60fada0b5e33f51b57a6
48,833
from typing import Iterator from typing import Tuple def walk_sources_from_command(command: instances.FilesRelatedCommand, filesystem: Filesystem ) -> Iterator[Tuple[str, str, str]]: """Typical iteration by command settings.""" return walk(command.so...
832909f1cafdf65cbaff999a2f9cca13969e17f5
48,834
def can_access_uri_part(context, request, uri_part): """Tell if current user can to access a URI part relative to context.""" assert uri_part is not None traverser = zope.traversing.publicationtraverse.PublicationTraverser() try: view = traverser.traverseRelativeURL(request, context, uri_part) ...
c1f94f63336d08b49ea99ffda414bf36bf9ab61b
48,835
def get_trainables(): """Get all the trainable variables in the current default session.""" sess = tf.get_default_session() result = {} for tvar in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES): result[tvar.name] = sess.run(tvar).tolist() return result
6ddba43186b1f2b56da4db65910db17a6330f89b
48,836
def _encode_entity_id(entity_type, entity_id): """See xidCgiDelimiter = "?xid=" """ return "xid=%s.%s" % (entity_type, entity_id)
fc6e36a4027f7a63e05e8dfab7f40681b3e26585
48,837
import os def save_hdf_file(file_path, idata, key_path='entry', overwrite=True): """ Write data to a hdf5 file. Parameters ---------- file_path : str Output file path. idata : array_like Data to be saved. key_path : str Key path to the dataset. overwrite :...
dada0d56117968fc979c3d59a893e0c565a4fd2f
48,838
def _create_pdb_atoms_from_cif(cif_atoms, cif_fields, identifier): """ Transform mmCIF atoms into pdb atoms. Parameters ---------- cif_atoms : list of str lines with atoms details in CIF format cif_fields : dict (str : int) key: field name value: index where to look for s...
7b4b693b8580a12ef5996aaa986acf3c671215dc
48,839
def discard_non_functional_deployments( deployments: SynchronizedDeployments) -> SynchronizedDeployments: # noqa """Discards deployments that were not expired, but are no longer functional, e.g. were cancelled.""" log = get_logger(__name__) all_nodes = [] for nodes in deployments.nodes: ...
bcbaf41a83fb78950f8ccb1e6e917bd6fb2cf197
48,840
def get_session(): """获取当前用户session""" return request.environ.get('beaker.session')
4bfcbd73251e7b928624ae7b3e00353be9650dad
48,841
def find_average_record(sen_set, voting_dict): """ Input: a set of last names, a voting dictionary Output: a vector containing the average components of the voting records of the senators in the input set Example: >>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': [-1,-1,-1], 'Rav...
ef0c0aeb5a75c0335de57ae6cca1c013fe59b8b0
48,842
def HTTP_POST_flask_config_general(): """This endpoint expects json of generalConfig. Optional argument 'restart' may be passed. When argument 'restart=true', the device starts automatically with new configuration.""" try: config = request.get_json() dabing.postConfig(config...
c401a64e69655db4a559c158e967faeff6615c3a
48,843
import re def get_allparams_cleaned_mdl(mydata): """输入是被定位出来的含有出事model内容的mdl列表,称为mydata。输出被正则替换掉全部参数的mdl列表""" # 这一段注释是测试代码,用于验证正则表达式 # pattern = re.compile(r"\'([-]*[0-9.E]*\-*\d*)[+-]*.*?\'") # 这是当初为钟灿写的正则,我现在也看不太懂了。 # for line in mydata: # if "'" in line: # print(line) # print(pattern.finda...
e3af1dc0959a602367a28b67fb29e1d848db1d0d
48,844
def transformer_ae_small(): """Set of hyperparameters.""" hparams = transformer.transformer_small() hparams.batch_size = 2048 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.num_hidden_layers = 3 hparams.hidden_size = 384 hparams.filter_size = 2048 hparams.add_hparam("com...
3c7cfd4b71c8e3e9169101ecc4bd4177ae4dfd60
48,845
import warnings def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=False, min_size_factor=0.5, max_size_factor=3, slic_zero=False): """Segments image using k-means clustering in Color-(x,y,z) spa...
2002c09b4a4a97ab9c5c7ae1349a9eff7aa83561
48,846
import os import tqdm def build_from_path(in_dir, out_dir, num_workers=1, index=1): """Preprocesses the Biaobei dataset from a given input path into a given output directory. Args: in_dir: The directory where you have downloaded the Biaobei dataset out_dir: The directory to write the output in...
61f47efc99aeb1230049aaa657d1635b7b9ef5f7
48,847
def str_ljust(x, width, fillchar=' '): """Fills the right side of string samples with a specified character such that the strings are right-hand justified. :param int width: The minimal width of the strings. :param str fillchar: The character used for filling. :returns: an expression containing the fil...
947c6413fdd331f962d2525784ef4f3eb05e3b2e
48,848
from datetime import datetime def partition_folder_path(file_path): """ This function provides the output path to which the data frame will be created :param file_path: file path from config_utils for the value 'output_file_path' :return: output file path with date partition """ file_path = fi...
3974344ba77caa2f04f025d1d79b852a6171ded3
48,849
def index(request): """Loads main page containing a MapBox map and the weight sliders.""" return render(request, "map/index.html")
df1c347e6743f8c139796cb5cca72855c0c95703
48,850
def parse_move(s: str) -> int: """ :param s: :return: """ try: v = int(s) except ValueError: v = -1 return v
5e450c0726ae2420aca41967c2e750ba6238a140
48,851
def exception_to_string(exc: Exception) -> str: """Convert exception to string stackrace""" # Either use passed original exception or whatever we have return TRACEBACK_HEADER + "".join(format_tb(exc.__traceback__)) + str(exc)
b383f257bbb2071966be21b259943ba1edaf7a57
48,852
def indice_x_norm(x_selected:float, x_norm:pd.Series): """ This function finds the indices for different values of the independent variable (x). The script considers the selected x_fixed point (for example: 0.15, 0.30, 0.45, 0.60, 0.75, 0.90). The output of the function are the observed limits fo...
731a68cb702a8d813312b703e072a9634c0d9489
48,853
def get_all_drives(session, start=None, limit=None, return_type=None, **kwargs): """ Retrieves details for all drives for the VPSAOS. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type start: int :param start: Th...
1d5fe34be20725daa9eb07eab2c35b51f2523088
48,854
def cache(self, key, fn): """ :param self: the object that will hold the cached value :param key: the key/attribute for the cached value :param fn: the function returning the value to be cached :return: the value returned by fn on first call """ if not hasattr(self, key): value = fn...
4d7c67d2e3892e4b2db57625075c4515ff89da99
48,855
def cursorColorForColormap(colormapName): """Get a color suitable for overlay over a colormap. :param str colormapName: The name of the colormap. :return: Name of the color. :rtype: str """ return _COLORMAP_CURSOR_COLORS.get(colormapName, 'black')
ec418f2f3b26b900ff6c8d2e5bb8f05b4701743d
48,856
import time def alarm_to_time(alarm: str): """ This function converts the time when the alarm is setted into seconds """ time_alarm = time.strptime(alarm + ":00", "%Y-%m-%dT%H:%M:%S") return time.mktime(time_alarm)
863dffc8832c5518bd24e9ba4524818835e724e5
48,857
def _compute_ious(dt, gt): """ compute pairwise ious """ ious = np.zeros((len(dt), len(gt))) for g_idx, g in enumerate(gt): for d_idx, d in enumerate(dt): ious[d_idx, g_idx] = _jaccard(d, g) return ious
8c3ceb268fcecc5beec246f9120b8e46e52d90ed
48,858
def get_top_articles(): """Most popular three articles of all time""" sql = """SELECT articles.title, COUNT(*) AS views FROM articles, log WHERE log.path = '/article/' || articles.slug GROUP BY articles.title ORDER BY views DESC LIM...
c1027e4b92263f3ce943fa74f6842bd4a601d6ce
48,859
import os import urllib import json def wiki_request(store, **params): """Build a network request for a given store""" # Default parameter params["format"] = "json" # Build request url = os.path.join(store, WIKI_API_FILE) data = urllib.parse.urlencode(params).encode() res = opener.open(url, data) #...
9984d1b2840fca35d33babc5773e22245b47ff05
48,860
import copy def overlap2(data): """ """ # Make a copy of the data. data2 = copy.copy(data) # Extract the first and last year and month. firstYear = int(data2[0][0][0 : 4]) firstMonth = int(data2[0][0][5 : 7]) lastYear = int(data2[-1][0][0 : 4]) lastMonth = int(data2[-1][0][5 : 7]...
5787b9b796cf6de16ac1d363536bcf92f47a5c6d
48,861
def meridional_curve(n_0, pitch, length, r_i, theta_i, npoints=40): """ Points on path of a ray passing through a grin lens. Args: n_0: index of refraction at center of grin lens [unitless] pitch: pitch or period of the lens [unitless] length: axial length of the lens [mm] r...
59a0de1cca1a1194d8b1c06b987606605bdce016
48,862
def restore_model(session, saver, path): """ Initializes a model that has been previously trained and returns global step Args: session: Tensorflow session saver: Tensorflow saver path: Path where model to be loaded is Returns: Global step variable """ logger.info...
2322dd46641cefae51eec493f522854242195d50
48,863
from pathlib import Path def strip(fileName): """strip debugging informations from shared libraries and executables - mingw only!!! """ if CraftCore.compiler.isMSVC() or not CraftCore.compiler.isGCCLike(): CraftCore.log.warning(f"Skipping stripping of {fileName} -- either disabled or unsupported with ...
56a6e396fd625541bf84d4f6764585687e77ebbb
48,864
import json from datetime import datetime def get_fake_users(): """Restituisce una lista di utenti fake""" with open('db/fake-data/users.json') as f: data = json.load(f) users = [] for row in data['results']: user = { 'username': row['login']['username'], ...
d3aabc54a3c3fd643143ac1dec4c25619d2e5575
48,865
def spherical_to_cartesian(theta, phi, rho): """ Converts spherical coordinates into cartesian. """ x = rho * np.sin(phi) * np.cos(theta) y = rho * np.sin(phi) * np.sin(theta) z = rho * np.cos(phi) return x, y, z
6348107f9616888aa5101a94e21f69f4a56f090f
48,866
def insert(df: pd.DataFrame, col_name, col_value, allow_duplicates=False): """Adds a column to the end of the DataFrame :param df: DataFrame :param col_name: name of column to insert :param col_value: value of column to insert """ return df.insert(len(df.columns), col_name, col_value, allow_dup...
bb7fb40cb4eb0ae8ecc78dffef587a1492d5869b
48,867
def doChangePageSize(request, pageSize): """ Changes page size in user preferences""" try: u = User.objects.get(user=request.user.id) u.pagesize = pageSize u.save() return HttpResponse(_('saved pagesize %s') % pageSize) except Exception, inst: return HttpResp...
af97024e4b6160b6da9fefb65874c323e455eb12
48,868
def _solve_lagrange123_com_slow(i, q, xtol=1e-6): """ Solve for L1, L2, or L3 x position in the CoM frame in units of semi-major axis *a*. Parameters ---------- i : {1,2,3} L point to solve for q : float Mass ratio m2/m1 xtol : float Tolarance value for solver. ...
1fd8f08aa48ecc2f1d6b8937b63bcb44c187e7df
48,869
def is_abs_bpath(d): """Returns true if it's an absolute blaze path""" return is_valid_bpath(d) and d.startswith('/')
d19714764754230afa7e4485268c6962483a9e2d
48,870
import functools def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False): """Returns a network_fn such as `logits, end_points = network_fn(images)`. Args: name: The name of the network. num_classes: The number of classes to use for classification. weight_decay: The l2 coefficient f...
8870afd081de02a087663021228956424684605d
48,871
def job_product(job_name, pre_request=None): """Decorator to register a function as a job product handler. Example:: @job_product('build-playlist-report') def playlist_report_product(results): csv_file = "\n".join(results['file_lines']) response = HttpResponse(conte...
666316fd58153ec06d957d21b1af62e05f7fb007
48,872
def blockplural(parser, token): """ Same as plural filter Example: {% blockplural amount %}{% trans "Book" %}{% endblockplural %} """ nodelist = parser.parse(('endblockplural',)) parser.delete_first_token() tag_name, amount = token.split_contents() return PluralNode(nodelist, am...
09fbb2bca90157c229d29fc30ef04bbec62a1b5a
48,873
import re def preprocess_text(input: TextPreprocessingInput) -> TextProcessingOutput: """Clean up text data based on selected preprocessing steps.""" text = input.text if PreprocessingStep.REMOVE_SPECIAL_CHARACTERS in input.preprocessing_steps: text = re.sub(r"\W", " ", text) if Preprocessi...
edf43ff51e01944dddb6bce4d9b66cdba8761bf1
48,874
def sdss_fits_url(plate, mjd, fiber): """Return the URL of the spectrum FITS file""" return SDSS_URL % dict(plate=plate, mjd=mjd, fiber=fiber)
1b212b52ab2403500a66470e5c0444749d4d8db3
48,875
import attr def verbose(message): """Color format a message for verbose messages""" if __use_colors(): return "%s%s%s" % (COLOR_VERB, message, attr(0)) else: return message
7fb97f110929a4003c5bb05a0d7787c4c92be09c
48,876
import numpy def dropout_constr(options, use_noise, trng, sampling): """This constructor takes care of the fact that we want different behaviour in training and sampling, and keeps backward compatibility: on older versions, activations need to be rescaled at test time; on newer veresions, they are res...
1a19d64f8fd106127c26be3ddc006280b70cc0a6
48,877
def to_inter_sets(lines): """Groups linked entities and interpretation set.""" group_by_qid = defaultdict(set) for cols in lines: group_by_qid[cols[0]].add(cols[2]) return group_by_qid
f8a513a53e674d38809980eafb8e14384bd12012
48,878
def gini_index(targets) -> float: """ Computes the gini index for a given target labels. Arguments: targets: A numpy array of shape (n_samples, ) Returns: The gini index for the given target labels. """ label_count = np.bincount(targets) return 1 - np.sum((label_count / len(t...
5dbc2698c198fed96b970e54f570b5e299b0649b
48,879
def _call_slugs(filename, symbolic, strategy_file, affinity=None, logfile=None, other_options=None): """Call `slugs` and log memory usage and time. @param filename: path to SlugsIn file @param symbolic: if `True`, then make symbolic strategy @param strategy_file: dump st...
2c1d31c08a15fe9832f30ed987141db001ff48b3
48,880
from hyperopt import hp, fmin, rand, Trials import hyperopt.pyll.stochastic def hyperopt_fit (model, X, Y, T, p0, **estimation_settings): """Calls Hyperopt. Exists to make passing arguments to the objective function easier. Arguments: model, X, Y, T, p0, estimation_settings: Just like other ...
b4c17bed702e10637bb85bae8dbfbd7b1385dad7
48,881
from datetime import datetime def get_type(data_field, derives=None): """ Parse type defined in <DataField> object and returns it. Parameters ---------- data_field : eTree.Element <DataField> or <DerivedField> XML element that describes a column. derives : eTree.Element <DataField> XML eleme...
a1699f0c300862acc01db525db967c15dba16e52
48,882
import mpmath def matrix_product(m1, m2): """ Args: m1 (mpmath.matrix or numpy.ndarray): first matrix m2 (mpmath.matrix or numpy.ndarray): second matrix Returns: matrix product m1 * m2 with same data type as m1 and m2 """ if isinstance(m1, mpmath.matrix) and isinstan...
19716cd2829fb37904c60a2d47c7fb45c350eb8c
48,883
import subprocess def exec_command_rc(*cmdargs, **kwargs): """ Wrap creating subprocesses. Return exit code of the invoked command. """ # 'encoding' keyword is not supported for 'subprocess.call'. # Remove it thus from kwargs. if 'encoding' in kwargs: kwargs.pop('encoding') re...
6660cb77743bb819c453111acc63f78c1175774e
48,884
import random def random_points_and_masses(max_points=10, min_mass=0.5, max_mass=2.0, max_coord=rbf_high, min_separation=0.5): """ returns: -shape [N, 3] numpy array of points, where N is between 2 and max_points -shape [N] numpy array of masses """ num_points = ra...
de4105f7f75001bf19669560f05aeb71a4116def
48,885
import PIL def imresize(image, factor, interp="nearest", mode=None): """ resize an image with a specified resizing factor, this factor can also be the target shape of the resized image specified as tuple. """ interp_methods = { "nearest": PIL.Image.NEAREST, "bicubic": PIL.Image.BIC...
866628560f5096c649a01de7a0d4f6116c992af6
48,886
def enum_class_getitem(context, builder, sig, args): """ Return an enum member by index name. """ enum_cls_typ, idx = sig.args member = enum_cls_typ.instance_class[idx.literal_value] return context.get_constant_generic(builder, enum_cls_typ.dtype, member.v...
554aee101408e072050134e2f6990f79780d516e
48,887
def get_key_from_insecure_cbc(encryption_oracle): """Recovers the key from the lazy encryption oracle using the key also as iv. The approach used is the simple one outlined in the challenge description. """ block_length = find_block_length(encryption_oracle.encrypt) prefix_length = find_prefix_lengt...
1d5e087b0bb93fddb72ccba40bd2c5a5482d376d
48,888
def mises_pari_rembourse_si_perdant(cotes, mise_max, rang=-1, remb_freebet=False, taux_remboursement=1, output=False): """ Calcule les mises lorsque l'un des paris est rembourse. Par defaut, la mise remboursee est placee sur la cote la plus haute et le remboursement e...
d3bff4e8187a666d6b8869bb39dd28f1f32d8c36
48,889
import collections def sort_2GX(*msg): """ Route T-Stick messages for T-Stick #015. """ if msg[0] == 0: return False elif msg[0] == 1: named_return = collections.namedtuple('tstick_sensor', 'rawcapsense') rawcapsense = msg[1:] return named_return(list(rawcapsense)) ...
291812e80e12ca6da5cec9afb43cc741cced156d
48,890
import io, csv def export_tweets(): """ Export all results as CSV file from the latest tweet. :param limit: limit the number of result to be returned """ @copy_current_request_context def generate(): output = io.StringIO() writer = csv.DictWriter(output, dialect='unix', fiel...
591800f25457142eec550c7ca264abad303ae2be
48,891
def read_double(fid, count=1): """ Read 64bit float from bti file """ return _unpack_simple(fid, '>' + ('d' * count), count)
5b21cd58ee74532c8c70d71b662b5cc5761a5bf6
48,892
import time def is_rover_in_perpetual_loop(Rover): """ Check to see if rover is is in perpetual loop Inputs: Rover (Rover object) Returns: bool statement of the sign uniformity of the latest Rover steers """ if Rover.angling_towards_sample_start_time and not Rover.approaching_s...
aa94810c9d962f453a1353d62a0af3c16ea5f637
48,893
import os def is_cuttingboard(fn, size_th): """Decides if fn belongs to the cutting board of if it contains information. The criterion to decide if a file is part of a recording is the following. If a video is part of a recording it has to have a size of aprox 4GB (maximum size of a file in the FAT s...
226750694f7cc2f31bed107a95535a416aee4459
48,894
def gdf_geom_clip(gdf_in, clip_geom): """Filter a dataframe to contain only features within a clipping geometry Parameters --------- gdf_in geopandas dataframe to be clipped in province_geom shapely geometry of province for what we do the calculation Returns ------- fil...
6c3ef364b25474aee42cf8894f83983caffce505
48,895
def getAnm(P, mstr, Bmat, findmin, findmax, Ndec): """ Return the (N+1)^2-element list containing SHDs of STFTs :param P: STFTs of the M channels of recordings :param mstr: Dict containing the microphone array properties :param Bmat: List of response equalisation matrices :param findmin: Index ...
2d2278d02168dc45b50f8aa27fc7ccd034444d5d
48,896
def _(message, *_): """ NOOP implementation of sphinx.locale.get_translation shortcut. """ return message
faf850b4bd49141b28b39debffb4e284ddc0d4d3
48,897
import random import colorsys def random_color_hsv(): """random a hex color, only random h value to get a brighter color""" h, s, v = random.random(), 1, 1 float_rgb = colorsys.hsv_to_rgb(h, s, v) return convert_rgb([int(x * 255) for x in float_rgb])
15dda41912caff17e86e3adfa410b5dce1f38630
48,898
from typing import Callable from re import S from re import T from typing import Optional def optional(f: Callable[[S], T], x: Optional[S]) -> Optional[T]: """Apply ``f`` to ``x`` if ``x`` is not ``None``.""" if x is None: return None return f(x)
07587950ef738164906bfb0b19622c6cb24f3fe4
48,899