content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def value_to_name(klass): """ Generate a function to convert an IntEnum value to its name. :param type klass: the class defining the IntEnum :returns: a function to convert a single number to a name :rtype: int -> str """ def the_func(num, terse_unknown=False): """ Convert ...
69e45e9e07388dacc27d5cc5b4d3822d6d716d3d
47,484
def np_ortho(shape, random_state): """ Builds a theano variable filled with orthonormal random values """ g = random_state.randn(*shape) o_g = linalg.svd(g)[0] return o_g.astype(theano.config.floatX)
f5762934c902cd6118aaec6a43f0856c0992702d
47,485
def force_func(biorbd_model: biorbd.Model, use_excitation: bool = False): """ Define the casadi function that compute the muscle force. Parameters ---------- biorbd_model : biorbd.Model Model of the system. use_excitation : bool If True, use the excitation of the muscles. R...
23866a48b0501d86612e85835ec177730d89d47c
47,486
def _is_valid_case(obj): """Returns True if ``obj`` is a valid test case Criteria for being a valid test case: - Is a class and a subclass of :class:`WebDriverTestCase <webdriver_test_tools.testcase.webdriver.WebDriverTestCase>` - Is not :class:`WebDriverTestCase <webdriver...
09d7d07af46e24354f81256430b21e0cb6462fce
47,489
def cajeroExist(): """ Verifica la existencia de un registro en CajaCajero :return: """ try: movimientoid = CajaCajero.objects.latest('id_movimiento') except CajaCajero.DoesNotExist: movimientoid = None pass return movimientoid
74ff2c0a6c8fedeb8b1e2b819e07f397dc4bb775
47,490
def get_reaktor(): """Returns the reaktor instance from the app globals.""" if not hasattr(g, '_reaktor'): g._reaktor = Reaktor(**current_app.config['REAKTOR_CONFIG']) return g._reaktor
eeaefb7f7eb2498a0bac8d4cbc3e3399fe69fc78
47,491
def _Bezier3Seg(p1, p2, c1, c2, gs): """Return a 'B' segment, transforming coordinates. Args: p1: (float, float) - start point p2: (float, float) - end point c1: (float, float) - first control point c2: (float, float) - second control point gs: _SState - used to transform coordina...
f4d661bdcf0e9b294d4c428c54ed1c5d682a1ed7
47,493
import torch def gather( v: torch.Tensor, split_in: qp.utils.TaskDivision, comm: qp.MPI.Comm, dim: int, ) -> torch.Tensor: """Return the contents of v, changed from split based on split_in on communicator comm and dimension dim, to not-split i.e. fully available on all processes.""" # ...
8c54dc42e7fae4bc75ad151737f5b40fd0d96aed
47,494
def match_nans(x, y): """Performs pairwise matching of nans between ``x`` and ``y``. Args: x, y (ndarray or xarray object): Array-like objects to pairwise match nans over. Returns: x, y (ndarray or xarray object): If either ``x`` or ``y`` has missing data, adds nans in the same...
8bbeba78210d9344c4b8faa57454462e7b761ad8
47,495
def index(): """User's homepage after logging or signing in""" # Fetch posts of user and whoever the user follows. posts = Posts.query.all() return render_template("index.html", posts=posts)
74a4f72231fd3ccb8e3b03aa5f9ed37250c75e7c
47,496
def calculator_post(): """index_get""" return CalculatorController.post()
413b31a61c85139415c7a69fc7788e9121c57d99
47,497
import numpy import random def randomPairs(n_records, sample_size): """ Return random combinations of indices for a square matrix of size n records. For a discussion of how this works see http://stackoverflow.com/a/14839010/98080 """ n = int(n_records * (n_records - 1) / 2) if sample_siz...
378634b99a83c8f18c9c137737c32e6d12816ae7
47,498
def is_parsed_result_successful(parsed_result): """Returns True if a parsed result is successful""" return parsed_result['ResponseMetadata']['HTTPStatusCode'] < 300
717f8aa88b814405a5a008e9706338fd0f91a7ff
47,499
from typing import Tuple def _generate_random_pos_def_tri_diag( batch_shape: Tuple, outer_dim: int, inner_dim: int, has_sub_diag: bool ) -> Tuple[np.ndarray, SymmetricBlockTriDiagonal]: """ Create a random tri-diagonal symmetric positive definite matrix. This works by creating a lower triangular tri-...
d3f59a2fa58b92ae39a9a52e72b77dd5fdff89a2
47,500
import json def get_deployment(*, name, namespace, k8s_client, raw=True): """Get a Deployment resource. Parameters ---------- namespace : `str` The Kubernetes namespace where the Strimzi Kafka cluster operates. name : `str` The name of the Deployment. k8s_client A Kube...
c1fd2cdc74b6713f993a84727bbf7398a0351070
47,501
def algorithm2(f,r1,r2,x0,y0,L = (1,1),maxit = [1000,1000],tol = [1e-3,1e-3],warmstart=True,): """ Variable projection method for problems of the form min_{x,y} f(x,y) + r_1(x) + r_2(y) with $f$ Lipschitz smooth and r_1, r_2 are convex and proxible. Input ----- f - function retu...
fcac0a26031db8536f91b4432faaeb2e125bfaed
47,502
def PopularTagsPerLang(df, lang, top_k = 10): """ Function: Get top k tags with largest number of fanworks by media and in selected language. Input: - df: pandas.DataFrame. - lang: list[str], languages to include. - top_k: int, number of top tags to include. Output: - df_top: pandas....
c5e0d4e459924292880b3eaee770412083ea59e7
47,503
def hist_match(source, template): """ Adjust the pixel values of a grayscale image such that its histogram matches that of a target image Arguments: ----------- source: np.ndarray Image to transform; the histogram is computed over the flattened array templat...
9dfff0344bb1dbb81a9e19833a9296c31f19187f
47,504
def design_matrix(x): """ Build the design matrix for linear regression for a given array of x-values. This creates a (N, 2) matrix, where the first column are the x values and the second contains all 1. """ X = np.empty((len(x), 2), dtype=x.dtype) X[:, 0] = x X[:, 1] = 1 retur...
726662f47802084d1e04bced45d5625568be8647
47,505
def r_min_KimKim(T_sat, sigma, h_fg, rho, deltaT_sub): """ minimum droplet radius """ r_min = 2*T_sat*sigma / (h_fg * rho * deltaT_sub) return r_min
c2e9a7e0741f6d663a73ff04eb32939732c34f36
47,506
def get_prefix(given_name): """ Assuming the given name adheres to the naming convention of crab this will extract the prefix element of the name. :param given_name: Name to extract from :type given_name: str or pm.nt.DependNode :return: str """ return str(given_name).split(':')[-1].sp...
192c4331c511b936d0eb320f6453ed61d0064ef9
47,507
def get_predicates(): # noqa: E501 """get_predicates Get a list of predicates used in statements issued by the knowledge source # noqa: E501 :rtype: List[BeaconPredicate] """ df = dh.load_edges() d = df.groupby(['edgelabel', 'relation']).size().to_dict() predicates = [] for (edge_l...
d174ae8553ba4b279b711e116ae6d574bddfe7b2
47,508
def cat_transform(train_var: np.array, test_var: np.array): """remap number to categorical variable and save dictionaries. test_var is then mapped according to the train_var""" dict_list = [] train_var_shape = train_var.shape test_var_shape = test_var.shape if len(train_var.shape)==1: tr...
87cf094a700676e3d67e5d56d8059e902cbb6196
47,509
def cov(data): """ Covariance matrix note: specifically for mean-centered data note: numpy's `cov` uses N-1 as normalization """ return _np.dot(data.T, data) / data.shape[0]
12ffb86e30237a07b3bcf213c1677793de0e4bf7
47,510
def dynesty_loglike_bma(cube, interpolator): """Dynesty log likelihood wrapper for BMA.""" theta = build_params(cube, coordinator, fixed, use_norm) return log_likelihood(theta, star, interpolator, use_norm, av_law)
a302773cafca43946d995fe33b6b20c0d5bc51dd
47,511
def get_graph_from_workflow(workflow): """ :type workflow: dart.model.workflow.Workflow """ entity = GraphEntity('workflow', workflow.id, workflow.data.name, workflow.data.state) return {'results': graph_entity_service().get_entity_graph(entity).to_dict()}
8a4ef74228ad4563a3cacefe4469e9136c72a1d9
47,512
def justice_league_super(superhero): """Fetch the Justice League character whose super name matches the path variable supplied by the user, or a 404 if not.""" canonicalized = superhero.replace(" ", "").lower() for character in justice_league_members: search_term = character["superhero"].rep...
560ea906140b0496528f58dbbdb759b5d40c4a01
47,516
from datetime import datetime import time def store(username, group, usersList): """Store the scraped users list in a file saved into a folder that has the same name as the username.""" date = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%S') path = '{}/{}{}.pkl'.format(_base_director...
c22b143183985c373109eb1b7237292fe3f652c7
47,517
import re import zipfile def northwind(table_name): """ Yield a stream of "records" as dictionaries, with certain adjustments. So it turns out my source of NorthWind data has a bizarre nonstandard format: Embedded commas are those followed by whitespace! The usual csv module doesn't handle that by default and ...
303fa89d19e12c17ab14cc0591a4182ce28f489c
47,518
from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC def get_rbf_svm_classifier(X_train, y_train, random_state=None, cv_folds=5): """ A classifier that performs classification based on support vector machine. X - a (n_training_examples, n_featu...
12681ff67b4ea4422a9d586f72190abbfb59e564
47,519
import nipype.interfaces.utility as niu import nipype.pipeline.engine as pe from nipype.interfaces.fsl.epi import Eddy from clinica.utils.dwi import generate_acq_file, generate_index_file def eddy_fsl_pipeline(low_bval, use_cuda, initrand, name="eddy_fsl"): """Use FSL eddy for head motion correction and eddy curr...
85539355d60efc49e68217bc0eb6b9dfff934cba
47,520
def calc_z1_from_Vs30(Vs30_in_meter_per_sec): """ Calculate z1 (basin depth) from Vs30. The correlation used here is z1 = 140.511 * exp(-0.00303 * Vs30), where the units of z1 and Vs30 are both SI units. This formula is documented in Section 2.5 (page 30) of the following PhD thesis: Shi, Ji...
b1fe0d4b28e85308a74ee574447d85825a730d57
47,521
import copy def rand_replace(rep_fun): """ Wrapper of contrastive sample generate functions. """ def gen_neg_subwords(example, tokenizer, cont_ent_idx, auxiliary_json=None, max_seq_len=128): cont_example = copy.deepcopy(example) entities = cont_example.entities if not entitie...
f044c444a774ada638691a006c649d10a0e64e92
47,522
def locate_ellipsoid(frame, spacing=1, rad_range=None, maxfit_size=2, spline_order=3, threshold=0.1): """Locates an ellipsoid in a 3D image and returns center coordinates and radii along x, y, z. The function fully analyzes the vesicle. Parameters ---------- image3d: 3D ndarray...
eea3ee01c137c051e729330d9cd78d94519bfa4e
47,523
def _hist_bin_sturges(*input_data): """ Sturges histogram bin estimator. A very simplistic estimator based on the assumption of normality of the data. This estimator has poor performance for non-normal data, which becomes especially obvious for large data sets. The estimate depends only on size ...
2d952357d8ae96ac89ded17673d677ef2ff8b953
47,524
def dialog_response(attributes, endsession): """ create a simple json response with card """ return { 'version': '1.0', 'sessionAttributes': attributes, 'response':{ 'directives': [ { 'type': 'Dialog.Delegate' } ...
dc652f754f8c5eed46e6bf299e68fb6c30244436
47,525
import concurrent import json def api_cert_info(): """ Return a JSON with the certificate info """ with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: cert_list = [] for hostinfo in executor.map(lambda x: get_certificate(x[0], int(x[1]))...
cb6c0ce9cc162aca59df8d27031e2fe850e923d6
47,530
def mbed_os_support(): """! Function used to determine if host OS is supported by mbed-lstools @return Returns None if host OS is not supported else return OS short name @details This function should be ported for new OS support """ result = None os_info = mbed_lstools_os_info() if (os_inf...
f982ff17caf3345ded984607e856a26e15222172
47,531
def sub_field(k, v): """Return a nested dictionary with field keys k and value v.""" res = {} field_d = res fields = k.split('.') for f in fields[:-1]: field_d[f] = {} field_d = field_d[f] field_d[fields[-1]] = v return res
193869fdfaca84172c71ca935f5fdb312682b19e
47,532
def mkkekz(u_t, v_t, wap, utt, vtt, p_l, lat, nlat, ntp, nlev): """Compute the zonal mean - eddy KE conversions from u and v. Arguments: - u_t: a 3D zonal velocity field; - v_t: a 3D meridional velocity field; - wap: a 3D vertical velocity field; - utt: a climatological mean 3D zonal velocity f...
fb4bbec756b00a969f99b65b81e111842bc2d110
47,533
def sieve5(n): """Return a list of the primes below n.""" """from http://codereview.stackexchange.com/questions/42420/sieve-of-eratosthenes-python""" prime = [True] * n result = [2] append = result.append sqrt_n = (int(n ** .5) + 1) | 1 # ensure it's odd for p in range(3, sqrt_n, 2): ...
73aa9c984cb877df66d17480457b18cd0fd927e5
47,534
def make_chapter_xml((time,name)): """ Creates the xml for the chapter """ chapter = Template(""" <ChapterAtom> <ChapterTimeStart>$time</ChapterTimeStart> <ChapterDisplay> <ChapterString>$name</ChapterString> <ChapterLanguage>eng</ChapterLanguage> </ChapterDisplay> </Ch...
48720d11d7ede90a81c94997084a5659840127e0
47,535
def dropout(input, rate=.5, noise_shape=None, training=False, name=None): """ Apply dropout on `input`. Args: input (Tensor): The input tensor. rate (float or tf.Tensor): The rate of dropout. noise_shape (tuple[int] or tf.Tensor): Shape of the noise. If not specified, us...
3c4fb09a846a98f8bd5c4c6e596170f31dbd1830
47,536
def refresh_pkce_token( client_id: str, refresh_token: str ) -> RefreshingToken: """ Request a refreshed PKCE user token. Parameters ---------- client_id client ID refresh_token refresh token Returns ------- RefreshingToken automatically refreshing u...
b0428ba80460c089a4c82d0bf6b895adac32d70f
47,537
def jsonify_new_book(book): """return json object of newly uploaded book""" book_data = {'book_id': book.book_id, 'title': book.title, 'author': book.author, 'image_url': book.image_url, 'genre': book.genre, 'description': book.des...
f43742a58adf5624703f1f2705fe93f0566c798a
47,538
def build_smod(builder, a, b, name): """Builds expression for signed int modulo.""" rem = BuildSRem(builder, a, b, "") neg_rem = BuildMul(builder, rem, ConstInt(TypeOf(rem), -1, True), "") return BuildSelect(builder, _mod_scale(builder, a, b), neg_rem, rem, name)
d329822f075298b242bf3f379dc5cf887829012a
47,539
def upload_indicators_command( client: QRadarClient, ref_name=None, element_type=None, timeout_type=None, query=None, time_to_live=None, limit=1000, page=0, ): """ Finds indicators according to user query and updates QRadar reference set Returns: (string, dict). Huma...
338e9870c56b64a743cb5c9974ca6976cc06aa3f
47,540
def create_stream(context=None): """ create a stream. .. note:: case 1. context is None. Get the context and create a new stream. case 2. context is not None. Create a new stream on existing context. Args: context (int): If context is None, it will get context and then create a stre...
65258ea31a1f8058252160761e04ae85db9be6b2
47,541
import torch def get_prediction(model, batch, device): """Get predicted labels for given input batch and model.""" images = torch.tensor(batch, dtype=torch.float).to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1) return predicted
e8bb4257dc19f26fa206e26fa844ec9717974e52
47,542
def keep_points_outside_shape(xy_iterable, shape, exclusion_buffer): """From an iterable of (x, y) iterables, select points outside a shapely shape, with an exclusion buffer (positive)""" return [ np.array(xy, dtype=np.float32) for xy in xy_iterable if not shape.buffer(exclusion_buffer)....
fa04fc3d5354a7fb609aec95a28ca9ab0e7c5061
47,544
def ControlsAreSame(control1, control2): """return 1 if control1 and control2 are the same control, otherwise return 0""" return _AutomationClient.instance().dll.CompareElements(control1.Element, control2.Element)
03b0625e3da27c7f8b841d2eda38968d1c5fd636
47,546
def close(): """ Close all pool connections and shutdown the pool. """ global db_pool db_pool.close() return db_pool
49356105507890d612cc6dcc11c748c0cf1be6d5
47,547
import torch def build_optimizer(network, optimizer:str, learning_rate:float): """Optimizer creation Args: network (torch.model): Network to train optimizer (str): optimizer type one of [sgd,adam,rmsprop] learning_rate (float): float learning rate Returns: [torch.optim.op...
7a4604d2001edba1fdc0f0b80ee7ab2c2e167084
47,550
def test_creating_tables_from_models(): # language=rst """ Creating tables from models --------------------------- Say I have some model: """ class Foo(models.Model): a = models.IntegerField() def __str__(self): return f'Foo: {self.a}' # @test clas...
b4ed5f203ae09e6d51c1c601de0d9e6e9a873ded
47,551
def send_msg(app, msg): """ Send an openflow message. """ return app.send_request(event.SendMsgRequest(msg=msg))()
5895a10bea0636608b86e98c2f188b422ab4a8b1
47,552
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. ...
0567e993e9c1f132311ee4c3d31ae1001a4ae036
47,553
async def get_crypto(symbol): """Returns the data of a crypto. symbol: bytes """ data = crypto.get(symbol.encode()) if data: return orjson.loads(data) return None
59121d7145a6a1f56bbc1452d73e804250fa1608
47,554
def get_monthly_fields(cases, varlist, from_time, to_time, pressure_adjust=True, raw_data_path=get_input_datapath(), model='NorESM'): """ Get monthly fields of files (i.e. not averaged) :param cases: list of cases to load :param varlis...
4c7a15524fc281c72f1c1ced0fa7fca51e8180f2
47,555
def valid_search_inputs_1(): """Basic search input tests for Sra and Ena (single inputs)""" return [ [ 0, 20, ["covid-19"], None, None, None, None, None, None, None, None, ...
d576c50c26eb5d606b3b4cdf5223ecf2a11fdb15
47,556
import random def chooseRandPixel(mask): """ Returns [x,y] numpy array of random pixel. NOTE: the returned [x, y] correspond to [row, col] in the mask @param {numpy matrix} mask from which to choose random pixel. E.g., self.level_dims = self.slide.level_dimensions sel...
dd643005588155c437739033e1e3ce6c9d1fe94f
47,557
def _setup_batch(batch_shape): """Create random time points with batch_shape and a Constant kernel""" num_data = 9 np.random.seed(1234) shape = batch_shape + (num_data,) return ( tf.convert_to_tensor( generate_random_time_points(expected_range=4.0, shape=shape), tf.float64 ...
ac6c628ee30b324a6b0b6c13a5477b0679077d6a
47,558
import warnings def get_directed_edges( nodes, edges, direction="oneway", from_id_col="u", to_id_col="v", node_id_col="id", force_bidirectional=False, network_type=None, ): """Prepares the edges and nodes for exporting to different graphs.""" allowed_network_types = Conf._possi...
66be62d88487c0123029d5e93ec46c151e82b846
47,560
def list_split(l, indices): """Split list at given indices. Closed lists have the same first and last elements. If the list is closed, splitting wraps around if the first or last index is not in the indices to split. Parameters ---------- l : list A list. indices : list ...
a882842f6d51eeda010017dbdd2bfa722ebb363d
47,561
def create_filing(token=None, filing_json=None, business_id=None, filing_date=EPOCH_DATETIME, bootstrap_id: str = None): """Return a test filing.""" filing = Filing() if token: filing.payment_token = str(token) filing.filing_date = filing_date if filing_json: filing.filing_json = fi...
b82090be5bb53e2d64a1907ecc5a8ad0d2970ce1
47,562
from typing import List def get_tracks_as_np_strings(labels: Labels) -> List[np.string_]: """Get list of track names as `np.string_`.""" return [np.string_(track.name) for track in labels.tracks]
bcbbc5567fdf48d99318de89b07eee480349ea75
47,564
import torch def _model_validation_for_base(opt, base_model, device, tokenizer, with_mask=False): """ validation set 을 μ΄μš©ν•˜μ—¬ λͺ¨λΈ 정확도 계산 """ corpus_list, asp_info = loader.load_validation_data() transform = nlp.data.BERTSentenceTransform( tokenizer, max_seq_length=opt["bert_max_len"], pad...
ef5c029cd8666f444206c58c53f031a4a351538b
47,565
def no_op(ctx, node, name, args): """Skip node.""" return None
1fede015a843657f3959bb8da4c2216a8674e60c
47,566
from typing import Union def log_likelihood(z:Union[np.ndarray,float,int], x:np.ndarray, P:np.ndarray, H:np.ndarray, R:np.ndarray) -> Union[np.ndarray,float,int]: """ Returns log-likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance...
c50098e557bab4f2095458bf61c9ed91ddb14121
47,568
import operator def recession_index(data, compare=operator.gt): """returns the index of the start of the recession Parameters ---------- data: DataFrame GDP data to search compare: function compare quarters (change to < to find end) Returns ------- int : iloc of star...
4bcdedffb094cb3d0112796c1ad39d666bd435a1
47,569
def copy_tree(t): """Returns a copy of t. Only for testing purposes. >>> t = tree(5) >>> copy = copy_tree(t) >>> t = tree(6) >>> print_tree(copy) 5 """ return tree(root(t), [copy_tree(b) for b in branches(t)])
64fcd5e820b14d5a34daf221defceb00949ed04d
47,570
import time def wait_for_element_not_visible( driver, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=settings.LARGE_TIMEOUT ): """ Searches for the specified element by the given selector. Raises an exception if the element is still visible after the specified timeout. @Params driver ...
2e76b4d81e0ef3342f110e5c7c89e4d4ef30ad43
47,572
from .irc import ConnectInfo as IRCConnectInfo def connect_info_factory(info_type: str, **kwargs): """ Creates a specific ConnectInfo based on the type of connection we are looking for. Any additional kwargs specified are passed on to the appropriate ConnectInfo constructor. :param info_type: the con...
dcca8457f5e7a4f4dec76687859d33cd3274c7af
47,573
def entity_similarity(algo, entity1, entity2): """ measure the similarity of the two entities :param algo: the algorithm to measure similarity :param entity1, entity2: two entities to measure analogy :return: [float] in [0. 1) """ if algo == "jaccard": return jaccard_similarity_score...
a886180219d6f4347fab605719305d86c97eec7a
47,574
import warnings import functools def deprecated(func): """ Decorator to be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. Usage:: @other_decorators_must_be_upper @deprecated def some_old_function(x,y): return...
ef4ca24b5da4a4df2b3c2a11f2e6b71791233a85
47,576
import requests def metadata_label_cbor(self, label: str, **kwargs): """ Transaction metadata per label. https://docs.blockfrost.io/#tag/Cardano-Metadata/paths/~1metadata~1txs~1labels~1{label}~1cbor/get :param label: Metadata label :type label: str :param return_type: Optional. "object", "js...
0d64f86aa2baf95ac4815fd1edf041412e0679b7
47,578
def uses_gpu(*args): """Mark to differentiate tests that use the GPU is some capacity. These tests will be run on CPU-only test nodes and on test nodes with GPUS. To mark a test that must have a GPU present to run, use :py:func:`tvm.testing.requires_gpu`. Parameters ---------- f : function...
20cf77b58216b0f8b0d0d68beb7c5b3c833f9e69
47,579
def get_imbalances(regressions): # Deprecated """ Generates a numpy array of the imbalances. For a value *x* where *x* is the beta of a regression: ========= ====== ======================================================= *x* < 0 **-1** The regression had a negative beta value *x* = nan **0** The regression ...
f755c9ca1253d511b33dbe1f1884d9bb4431f80a
47,580
def get_optimizer(learning_rate, config): """Returns the optimizer of choice given the configurations.""" if isinstance(config, experiment.MomentumOptimizer): optimizer = tf.keras.optimizers.SGD( learning_rate=learning_rate, momentum=config.momentum, nesterov=config.nesterov ) ...
7f49cab554fcda1cb38f4d146d99c2e9e0916365
47,582
def get_gitlab_project_data(initial_data, headers, resources): """ Get all directories and files of given projects. Parameters ---------- initial_data: list List of all top level projects headers: dict The authorization header that GitLab expects resources: list A li...
dce6a29de688ccf2999d6a48d98693cb38138dd9
47,583
from typing import List import re def convert_observations(observations:str)->List[str]: """ Parses a string with observations separated by comas. Args: observations: str -> Obesrvations string, each observation must be separated by a coma. Example "Green, ugly, has ...
45c43303d9d2819094120a25a639cd1d02fa4d8c
47,584
def prepare_data(data, nlags): """prepares data for LSTM model, x=last nlags values, y=(nlags+1)'th value""" data_x, data_y = [], [] for i in range(data.shape[0]): for j in range(0, data.shape[1] - nlags): data_x.append(data[i, j : j + nlags]) data_y.append(data[i, j + nlags]...
147389d381f689c68fff44b6b036777e25669c4f
47,585
import math def divisors(n: int) -> list[int]: """Get the proper divisors of a number n""" limit = int(math.sqrt(n)) + 1 proper_divisors = {1} for i in range(2, limit): if n % i == 0: proper_divisors.add(n // i) proper_divisors.add(i) return list(proper_divisors)
0a71ecccbda802d3a3575f024073fac575355ffa
47,586
def compressImage(image, height): """ Note: Should probably replace this method with one from photutils or PIL.Image. Will probably be faster/more accurate and can handle both increasing and decreasing resolution """ """ Compresses the image to a given size. Given that 3D printing cannot handle fine resolution, a...
83cb9faf1576dda452dbfa391038de6c7e8ee3e0
47,587
def get_lsb_num(num): """docstring""" cnt = 0 while not (num >> cnt) & 1: cnt += 1 # return cnt + 1
6abf34d4831b80310dbf57bf08b7fce0b6c0a73d
47,588
def foreign_key( table_name: str, schema: str, parent_name: str, parent_schema: str ) -> str: """Return column names (child and parent) of the foreign key.""" return f""" SELECT att2.attname as child_column, att.attname as parent_column FROM (SELECT unnest(con1.co...
e1c7221fd308ee44f7b09718e66028351262334a
47,589
from pathlib import Path def available_models(): """Check for available neural network models. This function returns a list of all neural network models saved. If None is available, it returns a message informing there's no models previously saved. Returns ------- dirs : list Lis...
f3bbfa56ea0eaa2e06467e479cdefd18d02e8021
47,590
def problem33(nr_digits): """Problem 33 - Digit canceling fractions""" a_sum = 1 b_sum = 1 for a in range(10**(nr_digits - 1), (10**nr_digits) - 1): for b in range(a + 1, 10**nr_digits): # print(a/b); a_str = str(a) b_str = str(b) for sa in rang...
b771db51002a3a408d57cb3422d64c69611f0e53
47,591
async def test(ctx): """Tests if the parameters taken in the function match the parameters that the event has""" return ctx
25ad99daa6685a596cf6f88d9a38b55d2b117ef8
47,592
def add_entrypoints(setupcfg: ConfigUpdater, opts: ScaffoldOpts): """Add [options.entry_points] to setup.cfg""" new_section_name = "options.entry_points" if new_section_name in setupcfg: return setupcfg, opts new_section = ConfigUpdater() new_section.read_string(templates.setup_cfg(opts)) ...
fc6c4fc6a35bf6b521141ca1fb4a85ebfe601fea
47,593
def create_top_video_photo(): """ Creates a video which contains the estimated lane line markers using a top view and the top view image :return: """ def process_image(image): warped, warped_cam, perspec = lane_finder.find_lanes_using_window(image) return warped_cam find_lanes_...
5e2f2d4fd3eb95ee3a339c957c04cd60d30b33bc
47,594
def expr2bdd(expr): """Convert an expression into a binary decision diagram.""" return bdd(expr2bddnode(expr))
fbaf81d2af0b9aed6729850ca40764fa825a5079
47,595
import zlib def iterative_decompress( stream, offset, size, chunk_size=4096, wbits=DETECT_HEADER, retry=False ): """ decompress data from stream chunk-wise """ decompressor = zlib.decompressobj(wbits) n_read = 0 decomp = b'' return_err = None try: while n_read < size: ...
37e33f9150e696b8bc42cb8a9676110a97b3a7d3
47,597
import math def compute_dimension(bounds, pixel_resolution: tuple): """ :param bounds: :param pixel_resolution: width and height of pixels in the units of its coordinate reference system extracted from transformation of image :return: """ output_width = int(math.ceil((bounds[2] - bounds[0...
83d3c133a8471d41d69cad4fb00d529e36634731
47,599
def conv_block(x, growth_rate, name): """A building block for a dense block. # Arguments x: input tensor. growth_rate: float, growth rate at dense layers. name: string, block label. # Returns Output tensor for the block. """ # assuming channels last bn_axis = 3...
c3ee75eee954f47287bc9571c56a6d1be5f63daa
47,600
def get_all_permission(only_value=True): """ θΏ”ε›žε½“ε‰ζ‰€ζœ‰ζœ‰ζ•ˆζƒι™ @param only_value εͺθΏ”ε›žvalue,ζˆ–θ€…ζœ¬θΊ« """ num = get_permission_num() # ζœ‰ζ•ˆ(θƒ½ε‡ηΊ§ηš„)ηš„ζ‰€ζœ‰ζƒι™ # noinspection PyBroadException try: # print(timeit.timeit('UserOnline.query.order_by(UserOnline.online_user_num.desc(), ...
4c850ec6307f53f344c47569a4adf2d99ae320a4
47,601
def poly_legendre(l, m): """ polynomial coefficients of legendre y = sqrt(1 - z^2) """ z, y = symbols('z y', real=True) return Poly(sympy_legendre(l, m), domain='R', gens=(z, y)).as_dict()
4844164e88fd76d94c59a3293930be546b2955ad
47,602
def tab_focus(*, info): """A model to complete on open tabs in the current window.""" model = _tabs(win_id_filter=lambda win_id: win_id == info.win_id, add_win_id=False) special = [ ("last", "Focus the last-focused tab"), ("stack-next", "Go forward through a stack of focus...
94be7966971b6aea60ea3b4998a7fda5bae24cdf
47,603
def _load_records(filename): """Read file and return a dataset of tf.Examples.""" return tf.data.TFRecordDataset(filename, buffer_size=_READ_RECORD_BUFFER)
48f08d48bb4eea2d4541d094fd6e9297f836fc1a
47,604
def get_location(t): """ get location of list of token. """ def get_loc(t, idx): if isinstance(t, list): return get_loc(t[idx], idx) elif isinstance(t, Token): return t.loc else: raise TypeError(f'{type(t)}') if isinstance(t, Token): ...
37f76d2904eee24dfc44619a42a1adb90db4584f
47,605
def get_rounds(number): """Create a list containing the current and next two round numbers. :param number: int - current round number. :return: list - current round and the two that follow. """ return [number, number + 1, number + 2]
18e3bd356dc86196bad9c0002e84a2390bd8d86a
47,606