content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_services(services): """ Get all services from the response and make the comma-separated string. :param services: List of services. :return: comma-separated list. """ return ', '.join(services)
6c965dff4c85f772b41d10e12170547f156ee86e
56,745
import torch from typing import Optional from typing import Sequence from typing import Tuple from typing import Callable def training_components(model: str, classifier_type: str, n_classes: int, learning_rate: float, activation_function: str, l2_penalty: float, device:...
efdfe82537e6c65e6ded46ffacc7d8f4f2b455df
56,746
from typing import Union def request_photo_and_submit(update: Update, context: CallbackContext) -> Union[str, int]: """заносит информацию о пользователе в БД""" if update.message.text: utils.send_message(update=update, context=context, text="Необходимо отправить фото для сво...
9ffefe475102552d47eb9d52212e27ac4ecd7eef
56,747
def ref_and_res_to_scores(fileName=None, refPuncFileName=None, resPuncFileName=None): """ Get the scores by taking the reference punctuation and the restored punctuation while skipping the first and the last word to generate scores :param fileName: Consistent filename in format X_reference_punc.txt and ...
f7479288b504c6b2fbb42d2cc66d218946fc938f
56,749
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ): """Set up Picnic sensor entries.""" picnic_coordinator = hass.data[DOMAIN][config_entry.entry_id][CONF_COORDINATOR] # Add an entity for each sensor type async_add_entities( PicnicSensor(picnic...
3e26411db97999384cbb5cbd3ad4e127bec632f4
56,750
def check_for_default_value_for_missing_params(missing_params, method_params): """ :param missing_params: Params missing from Rule :param method_params: Params defined on method, which could have default value for missing param [{ 'label': 'action_label', 'name': 'action_parameter', 'fiel...
bad583976d4c88af93540c9d64f7b0711fd24e12
56,752
def svn_diff_hunk_reset_modified_text(*args): """svn_diff_hunk_reset_modified_text(svn_diff_hunk_t hunk)""" return _diff.svn_diff_hunk_reset_modified_text(*args)
ef9dd4bf4afa8acc55ecea0fc783e6a4487a5215
56,753
import random import string def mock_tweet(): """Generate some random tweet text.""" count = random.randint(70, 140) return ''.join([random.choice(string.ascii_letters) for _ in range(count)])
1a8f9937408acaaaf2534be0721a8e3203525eb3
56,754
def davidson_solver(A, neigen, tol=1E-6, itermax = 1000, jacobi=False): """Davidosn solver for eigenvalue problem Args : A (numpy matrix) : the matrix to diagonalize neigen (int) : the number of eigenvalue requied tol (float) : the rpecision required itermax (int) : ...
655eb8f86373775d0dbc09c4bc2ada093b00408a
56,755
def date_comparison(input_series, output_series): """ Compare the start and end dates for the input and output series and obtain the dates that completes the output series :param input_series: :param output_series: :return: """ first_input = input_series['data']['first'] last_input = in...
5910c2e3552d84a15e0b03bfb1dd97cf0cec0d66
56,756
def get_arc_info(a): """Get edge information about arc to draw it using graphviz :param a: arc :return: edge_id, src, target, edge_attribs """ assert isinstance(a, petrinet.Arc) src_id, target_id = str(a.src._id), str(a.target._id) _id = '{}->{}'.format(src_id, target_id) attribs = { ...
3c38d3984ae5312678cb39dcb287c1b36cce279b
56,757
def Domain(min, max) -> type: """ Create a Type restricted to the specified domain :param min: The lower bound of the domain :param max: The upper bound of the domain :return: A ValidatedType representing the specified domain """ return ValidatedType('Domain_{}-{}'.format(min, max), int, lam...
576c455339ac6076dd7b3796aec2f85a58b71b77
56,758
import json def parse_json(s, **kwargs): """Parse a JSON string into a dict.""" try: nb_dict = json.loads(s, **kwargs) except ValueError: # Limit the error message to 80 characters. Display whatever JSON will fit. raise NotJSONError(("Notebook does not appear to be JSON: %r" % s)[...
3a7e6db0799f85cb0dd616a9fed2a2c11e3153f3
56,759
def longitud_palabra(palabra, n): """ -Recibe: una palabra y un numero entero positivo(n) -Devuelve: - True, si la palabra tiene longitud n - False, en caso contrario """ return len(palabra) == n
33065b4302cee42d3921d7b75344c12c43d54cd6
56,760
def get_iqr_mask(sub_arr, index, iqr_fact = 1.5, within=True): """ """ # Mask to include only events within the IQR q25, q75 = _get_iqr(sub_arr) iqr = abs(q75 - q25) if within: mask = np.where((sub_arr > (q25 - iqr_fact * iqr)) & (sub_arr < (q75 + iqr_fact * iqr))) ...
2dad376b3cc5d38c27903b57f29460b671c30e1f
56,761
def retrieve_activities(start_time, end_time, activity_name): """ Retrieves all activities of a user between the time period or based on requested appliance """ try: if activity_name == "all": # Retrieves all activities - for usage/wastage reports records = ActivityLo...
5261221bba397c5def80c69bfb91045db4d2e44e
56,762
def run_cmd(command): """ :param command :return A map based on pass / fail run info """ logger.info("Running: {0}".format(command)) try: ret = subprocess.check_call(command, shell=True, env=os.environ) return {'success': True, 'return': ret, 'exception': None} except subproc...
413e49f1afd485cc695ceb7ae3683a3572fb5472
56,763
import math def ph(concentration): """Returns the pH from the hydronium ion concentration.""" return -math.log(concentration)
46e59ed147006ac4cc3aaefea5b10c015a9e18b9
56,764
def user_home(request): """ 用户主页 :param request: :return: """ all_wechat_user = WeChatUser.objects.all() reply = { "wechat_users":all_wechat_user, "username": request.user.username, 'active_class': 2 } return render(request,"newadmin/user_home.html",reply)
ea68822474d7624dcbc14b881e08ca137e3603b3
56,765
import match as matchmod # avoid circular import issues def subrepo(mctx, x): """``subrepo([pattern])`` Subrepositories whose paths match the given pattern. """ # i18n: "subrepo" is a keyword getargs(x, 0, 1, _("subrepo takes at most one argument")) ctx = mctx.ctx sstate = sorted(ctx.subst...
10f2f5798d516d7f87a2bc20965f2e8437ddeac8
56,766
def _app_or_default(app=None): """Returns the app provided or the default app if none. The environment variable :envvar:`CELERY_TRACE_APP` is used to trace app leaks. When enabled an exception is raised if there is no active app. """ if app is None: return getattr(_tls, "current_app",...
4a5425ce8cb66ec95eaf970d965e4cb16811e3bc
56,767
def add_details(img, screen_img, text, has_vision, has_finger, model_time): """ add details to the screen image. Args: img : current cv2 read image. screen_img : original cv2 read device image. text : current text. has_vision : bool has_finger : b...
8abfed6f079835ab5a4c8d78c67f72acf798e7b6
56,768
def migration_delete(context, id): """Deletes specified source.""" return db.migration_delete(context, id)
359932913e0c857152066b4214c5cbd474e78924
56,769
def build_model( voca_size=29331, hidden_size=512, lstm_layers_num=2, batch_size=10, max_epochs=200000, retrain=False, dump=False ): """ train a model with mini-batch gradient descend """ model = None if not retrain: try: f...
8752153088baf4c70c37f1a83dc06a2f0a88de1e
56,770
def map_value_to_RGB_string(value: float) -> str: """Support function to join mapping value and converting to Ploty string""" return create_RGB_string(map_value_to_RGB(value))
b7a2d08bf9dcdbe3192f6ed88a12a02d2bf6fecd
56,772
import torch def rgb2hsv(rgb:Tensor): """Compute luminance of an RGB image. Args: rgb (tensor): rgb image (shape:(H,W,C)) Returns: gray(tensor): gray-scale image(shape:(H,W)) Examples: >>> import cv2 >>> img=cv2.cvtColor(cv2.imread('../../images/cat.jpg'),cv2.COLOR...
c3d203f15f1a1448698be423c1348460daaa096b
56,773
def main(): """ диспетчер """ global B print (f"Привет. Это игра в животных") B = {} while sess() and (input("\nПродолжаем? (да/нет) ")[0] == "д"): pass return 0
f04c271fb8e3f6fb56ec573554b601be84715c63
56,774
def reviews_with_id(review_id=None): """ reviews route to handle http methods for given review by ID """ review_obj = storage.get('Review', review_id) if request.method == 'GET': if review_obj is None: abort(404, 'Not found') return jsonify(review_obj.to_json()) ...
0473c01bc346b84b263951ade4af73304bc350f6
56,775
def log_linear_transform(timeSeries, alpha): """Returns a time series where {x, y(x)} becomes {x, y'(x) = log y(x) + alpha x + c}""" startPoint = timeSeries[0,0] transform = map(lambda x,y: np.log(y) - alpha * (x-startPoint), timeSeries[:,0],timeSeries[:,1]) return np.transpose([timeSeries[:,0], np...
1aa7c2c59707abc3f9c886ac53543b9d40925e79
56,776
def snap_PL(l: list, start: float = None, stop: float = None, num_dims: int = None) -> list: """ Given a list `l` of PersLandscapeGrid types, convert them to a list where each entry has the same start, stop, and num_dims. This puts each entry of `l` on the same grid, so they can be added, av...
6ddbff1021351a90918c966e5d750c89e417d526
56,777
def construit_AD_aleatoire(LSet,epsilon, nbatt): """ LSet : LabeledSet epsilon : seuil d'entropie pour le critère d'arrêt """ if(entropie(LSet) <= epsilon): un_arbre= ArbreBinaire() un_arbre.ajoute_feuille(classe_majoritaire(LSet)) else: un_arbre= ArbreBinai...
7f5d2bd32783054b280bf392cffad6f518bc861a
56,778
def ms_nikud(key): """ Emulate the old Microsoft Windows behavior: Unshifted - like a US keyboard with CAPS locked Shifted - like level 1, except the top row gets the old-standard nikud """ ref_char = key.ref_chars[1] unshifted = ref_char.upper() try: shifted = old_si1452_nikud[r...
fc26a4848b7061abb44bda3ff10a155ca83b57b5
56,779
def wait_for_ready(restype, name, timeout=300, exit_on_err=False, _result_dict=None): """ Wait {timeout} for resource to be complete/ready/active. Args: restype: type of resource, which can be "build", "dc", "deploymentconfig" name: name of resource timeout: time in secs to wait for...
56671a2e6b6f716f2dcbf3f8fc66ba91497cd9ea
56,781
def hash_file(upload_context): """ Function run by HashFileCommand to calculate a file hash. :param upload_context: PathData: contains path to a local file to hash :return HashData: result of hash (alg + value) """ path_data = upload_context.params hash_data = path_data.get_hash() return...
3819e9617e5726cf4178a8382eb22b0ec8bd7da0
56,783
def can_make_ransom_note(magazine, ransom): """ Checks if you can make a ransom note out of a magazine. :param magazine: The array of words in the magazine :param ransom: The array of words in the ransom note :return: True: You can make a ransom note out of the magazine ...
00ce49f627eb28686c8ba2fe852f244e3eb94c86
56,784
import struct import ctypes def encipher(v, k): """ TEA coder encrypt 64 bits value, by 128 bits key, QQ uses 16 round TEA. http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html . >>> c = encipher('abcdefgh', 'aaaabbbbccccdddd') >>> b2a_hex(c) 'a557272c538d3e96' """ n=16 #qq use 16 delta = 0x9e3...
57d01a534f645f2464d16e90201c2ed1d37c77b9
56,785
def get_engine(db_url): """Connect to the database and engine :param db_url: Database URL to connect to :return: Database engine """ check_db_url(db_url) return create_engine(db_url)
e1cc89a6e12c98ffedde194bd3e7aead5652f504
56,787
def get_attr_of_pset(_id, ifc_file): """ Get all attributes of an instance by given Id param _id: id of instance return: dict of dicts of attributes """ dict_psets = {} try: defined_by_type = [x.RelatingType for x in ifc_file[_id].IsDefinedBy if x.is_a("IfcRelDefinesByType")] ...
6de5772ee0b86894c0986a631c20042751e0eb3e
56,788
from unittest.mock import call def connect(srv_addr=None): """ load dbus-module into PA, lookup address and connect to the dbus interface """ # load dbus-module if not loaded already if call('pactl list modules short | grep module-dbus-protocol', shell=True) == 1: print('load dbus-module into PA') check_c...
ffe9de3b8c14ff5208517773990a1c07416a2ace
56,789
def transform_log_event(log_group, log_stream, event): """ Turns the message into JSON if it isn't already, recognizing standard logging formats; adds tracking fields. """ message = event.get('message', '').strip() result = try_parse_json(message) if not result: result = try_pars...
94634ba504118d4fc5ad9cdc19709fb76ae334d6
56,790
def read_FASTA(filename, SplitHeader=True): """ Reads FastA file and returns a list of tuples, where first part is a list of header elements and second seq as a string read_FASTA('seqfile.fa', SplitHeader=True) [(['gi', '1114567', 'gb', 'NC_00245'], 'ATATAGGCGCTTGGTGCGCGGCGGGCGCGGCTAGCAGCAC...
4a641a709d32bf80d0c1cfe590653c55e12f2c5d
56,791
import time def timestamp2array(timestamps, t): """ 把时间戳的序列中的每一个时间戳转成特征数组,考虑了星期和小时, 时间戳: numpy.datetime64('2013-07-01T00:00:00.000000000') Args: timestamps: 时间戳序列 t: 一天有多少个时间步 Returns: np.ndarray: 特征数组,shape: (len(timestamps), ext_dim) """ vec_wday = [time.strptim...
7f44c98cc94a43f30f80a8e3fd5cc45376c4f62c
56,792
def active_matrix_from_angle(basis, angle): """Compute active rotation matrix from rotation about basis vector. Parameters ---------- basis : int from [0, 1, 2] The rotation axis (0: x, 1: y, 2: z) angle : float Rotation angle Returns ------- R : array-like, shape (3, ...
c007e8ab45c96fcf7a5f7c4af8ef0d3f51898750
56,793
def rebuild_paral_results(results): """Rebuild the correct way to store the results.""" scores = [results[i][0] for i in range(len(results))] best_pars_info = [results[i][1] for i in range(len(results))] times = [results[i][2] for i in range(len(results))] return scores, best_pars_info, times
ae7a1ab996c49053332702b44482bc1b440aeee1
56,794
def create_device(name: str, device_type: xcrun.simctl.device_type.DeviceType, runtime: xcrun.simctl.runtime.Runtime): """Create a new device, returning the identifier.""" command = 'create "%s" "%s" "%s"' % (name, device_type.identifier, runtime.identifier) device_id = _run_command(command) # The devi...
4a9045dd17bc87548cf61821f6ae398a89902e86
56,795
from typing import Dict def retrieval_results_to_str(results: Dict[str, float], name: str): """ retrieval results string """ return ("{:7s} | {:.3f} | {:.3f} | {:.3f} | {:.3f} | {:5.1f} | " "{:5.1f} | {:6.3f}").format(name, *[results[a] for a in EVALKEYS])
24b805223c75ce9b0c2e678061a0d1d351b0ab69
56,796
def format_tag(organization, standard, version, tag_name=None): """ Format a YAML tag. """ result = 'tag:{0}:{1}/{2}/'.format( organization, standard, version) if tag_name is not None: result += tag_name return result
743ee05c37b4be8ef1bb6e995641f2641c5df95d
56,798
from typing import Any from typing import Tuple def _validate_input(val: Any, args: 'ApplyMixtureArgs' ) -> Tuple[Any, 'ApplyMixtureArgs', bool]: """Validate args input and determine if we are operating on a density matrix or a state vector. """ is_density_matrix = False val_qi...
db4355d6f2f67272b10e918bb26e1d724d2a378f
56,799
def bot_text_agent(text): """ text agent responsible for any text processing to extract entities like GPE arguments: -- text: input text to be processed <string format> returns: -- weather agent response <ENTITY FOUND> -- small talk answer <PRE-DEFIND TALK FOUND> ...
d4d8ecb83a7f045248ec195d879a024f1a314abb
56,800
from datetime import datetime def create_bq_table_name(site_name, delta_days=0, time_partitioning_type=""): """return BigQuery table name""" TABLE_PREFIX = environ['BQ_TABLE_PREFIX'] prefix = TABLE_PREFIX + site_name """ Using auto table partitioning https://cloud.goo...
0048bdb2845a9a492c4c52141cd0db801257d4df
56,801
def batch_neighbors(queries, supports, q_batches, s_batches, radius): """ Computes neighbors for a batch of queries and supports :param queries: (N1, 3) the query points :param supports: (N2, 3) the support points :param q_batches: (B) the list of lengths of batch elements in queries :param s_ba...
5226fe185db206d2d1384085b10e3fc79528f6de
56,803
def add_state_name_col(df): """ Add a column of corresponding state names to a dataframe Params (df) a DataFrame with a column called 'abbrev' that has state abbreviations Return a copy of original DataFrame with extra column """ new_df = df.copy() names_map = {'CA': 'California', ...
8e1674006bdccf8a0c5c22dafd7231dd762d725f
56,804
def ex6(): """ Example 6 Minimizing the Tardiness file name: Example6.py Copyright Log Opt Co., Ltd. Consider a 4-activity problem with one machine resource. The due dates and processing times (durations) of the activities are kept in the dictionaries due={1:5,2:9,3:6,4:4} and dur...
62c66b693972d17b24bc6dc0a008ef164ed1b26a
56,805
import logging def track(params_file, directions="det", max_angle=30., sphere=None, seed_mask=None, n_seeds=1, random_seeds=False, stop_mask=None, stop_threshold=0, step_size=0.5, min_length=10, max_length=1000, odf_model="DTI"): """ Tractography Parameters ---------- ...
68b003c5f536826f17bbc509153d89cadb1b2b1a
56,807
def GlobalAveragePooling2D(input, n_class, name): """ replace Fully Connected Layer. https://www.facebook.com/groups/smartbean/permalink/1708560322490187/ https://github.com/AndersonJo/global-average-pooling/blob/master/global-average-pooling.ipynb :param input: a tensor of input :param n_class:...
aba8b1566e61d86b9e494d16179d3a6cd73866ff
56,808
def bill_calculator(load_profile, tariff, export_tariff): """ Not vectorized for now. Next step will be pass in multiple profiles for the same tariff 2 styles of NEM: Full retail and fixed schedule value. To-do -Both energy and demand calcs (anything that uses piecewise calculator) doesn't go belo...
c9741f5df7613c98775a4e22779478fc39d82f0e
56,809
def angularfreq(nsamples, samplerate): """ Compute angular frequencies """ angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate * PI2 / nsamples return angfreq
daf4cdd8591580f291a086f3316b10ec2565f356
56,810
def from_doc(doc): """ Read stub from doc """ return Stub( get(Doc.id_path, doc), get(Doc.output_path, doc), get(Doc.created, doc), get(Doc.modified, doc), get(Doc.title, doc), get(Doc.meta_summary, doc) )
ccb906285635b1dace9ce3d953af0c1f8bd1f1bd
56,811
def _allocation_request_for_provider(ctx, requested_resources, provider): """Returns an AllocationRequest object containing AllocationRequestResource objects for each resource class in the supplied requested resources dict. :param ctx: placement.context.RequestContext object :param requested_resources:...
2dd9415a160f203ee65f604336be9ddee5187eb7
56,812
def create_turkey_season(source_df, target_df, feature_name): """ Winter: December - February Spring: March - May Summer: June - August Autumn: September - November """ month_to_season_map = { "jan": "winter", "feb": "winter", "mar": "spring", "apr": "sprin...
65f996d80554a35fff6341ca500a0c09c64186bd
56,813
def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: # >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 # >>> x = -13 # >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 ...
52c28c0e511731e9e40ccd54c5c8c976fcc99324
56,814
def render_User_avatar(self, h, comp, model, *args): """Render a user's avatar""" with h.span(class_='avatar', title='%s' % (self.data.fullname)): avatar = self.get_avatar() if avatar: h << h.img(src=avatar) else: h << h.i(class_='ico-btn icon-user') return h....
c192b415cb297aedf22d626418ab58d159e7815a
56,815
def W3(DD,RR,DR,RD,Ndd,Nrr,Ndr,Nrd): """Returns the Landy & Scalay estimator for the cross-correlation and its error. The pair counts DD, RR, DR, RD are not required to be normalized. Ndd,Nrr,Ndr,Nrd are the normalizations factors for each pair count Parameters ---------- DD : ndarray ...
49fed635e32d810278f71eae98ebc65ca636664f
56,816
def energy_decay_curve_chu( data, sampling_rate, freq='broadband', noise_level='auto', is_energy=False, time_shift=True, channel_independent=False, normalize=True, plot=False): """ Implementation of the "subtraction of noise"-method after Chu ...
837203c3df2caae515a47df02018556e1413b9b9
56,817
def _reset_hard_to_refs_prefixed_ref(git, remote_name, ref, raises=True): """ deals with the git reset --hard command for long name ref (on the format 'refs/xxx') """ assert ref.startswith("refs/") # Check the ref format to retrieve the effective ref name to switch on if ref.startswith("refs/remotes") a...
c362093006e77c2965f9ce76ec2e85c8b45510a5
56,818
import typing def financial_statement_full_as_reported( apikey: str, symbol: str, period: str = "annual", ) -> typing.List[typing.Dict]: """ Query FMP /financial-statement-full-as-reported/ API. Company's "as reported" full income statement. :param apikey: Your API key. :param symbol:...
801c084de98eb640691136c79f5796c32f4ff4ab
56,819
def about(request): """ Share further details about the project. """ context = {'client_id': settings.OPENHUMANS_CLIENT_ID, 'oh_proj_page': settings.OH_ACTIVITY_PAGE} return render(request, 'main/about.html', context=context)
c738d29d1eed932dfe59dfc4a1c64c8ab6253dc3
56,820
def str2bool(v): """ Used to parse boolean args @link https://stackoverflow.com/a/43357954/3443137 """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: ...
18d7477dd152580aeddc9acd10d0ff5c6b5c166e
56,821
import warnings def kappa_t(wair,temp,pres,airf=None,dhum=None,dliq=None,chkvals=False, chktol=_CHKTOL,airf0=None,dhum0=None,dliq0=None,chkbnd=False, mathargs=None): """Calculate wet air isothermal compressibility. Calculate the isothermal compressibility of wet air. :arg float wair: Tot...
05bb89a2049928df1f66605b5f52207ac7cd8a90
56,822
def numpy_to_Point(this_numpy): """Convert a numpy array into a geometry_msgs/Point32 Arguments: this_numpy: a numpy array having one 3 element dimension (so that it can be squeezed to (3,) size) to populate a message from Returns: this_point32: geometry_msgs/Point32 message wi...
7a350307fc9e285279fc570c415cef915a343fa1
56,823
def value_is_float_not_int(value): """Return if value is a float and not an int""" # this is klugy and only needed to display deprecation warnings try: int(value) return False except ValueError: try: float(value) return True except ValueError: ...
f08f55dfc5e8b4eefef102f7fe097e4285d9dc7c
56,824
def add_noise(moves, noise_p, param): """Adds noise to the movement data. """ return np.array( [[moves[i, j] + np.sqrt(noise_p) * np.random.randn(len(moves[i, j])) for j in xrange(param['N_m'])] for i, _s in enumerate(param['scales'])])
bcb5d127f73286efd19a11401768538d17af1e1c
56,827
def policy_settings(request): """TLS termination policy settings""" return request.getfixturevalue(request.param)
3a65251ea7866e25c02bf8354cc7cc9bbb5552e8
56,828
import string def process_text(text, stem=True): """ Tokenize text and stem words removing punctuation """ text = text.translate(string.punctuation) tokens = word_tokenize(text) if stem: stemmer = PorterStemmer() tokens = [stemmer.stem(t) for t in tokens] return tokens
7084a614cf192aa400a7bef93f6b469c37348c70
56,829
import random def generate_random_DC_single_force_coupled_tensor(): """Function to generate random DC-single-force coupled tensor (M_11,M_22,M_33,M_12,M_13_M_23,F_x,F_y,F_z) using normal distribution projected onto a 3-sphere method. (Based on Pugh 2015,Appendix B and Muller, 1959; Marsaglia, 1972). Returns a...
565c2b40bc49ee0c194d9da25fe2e5d1dfa65c41
56,830
def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True): """Create a slot initialized to 0 with same shape as the primary object. Args: primary: The primary `Variable` or `Tensor`. name: Name to use for the slot variable. dtype: Type of the slot variable. Defaults to the type of `...
3b2a5d53475dcf816c2a75c318add085ace36b35
56,832
def process_lower(cont): """ Make the value in lowercase """ return cont.lower()
f863852b0aff952bce080e20360d6fcc571acc21
56,833
def get_colormap(): """Returns the current AgML colormap.""" global _COLORMAPS, _COLORMAP_CHOICE return _COLORMAPS[_COLORMAP_CHOICE]
986d2b92a71228fdfa21435f44ca99965702e94c
56,834
def dewarp_line(line,show=0,order=3): """Dewarp the baseline of a line based in estimate_baseline. Returns the dewarped image.""" line = line*1.0/amax(line) line = r_[zeros(line.shape),line] h,w = line.shape baseline = estimate_baseline(line,order=order) ys = polyval(baseline,arange(w)) ...
1e47c2e704e95d98766af6261aee7b2ac45ecc5f
56,835
def load_settings(filename, path='/', ignore=()): """ By default loads all settings from path '/general/data_collection/Settings/' or for example to load animal ID, use: path='/General/animal/' ignore - tuple - any paths including any element of ignore are returned as None """ f...
108a3b7ab6e83efbc2e2faac40873697722d13a5
56,836
def npl_loan_detail(request, pk): """ List the data a specific EBA Loan """ try: loan = Loan.objects.get(pk=pk) except Loan.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = NPL_LoanDetailSerializer(loan) return Response(serializer.data)
ce7e5597d40658069ed5cd6c9765e661ef84c55c
56,837
def cli_key_script_name(): """ Return the CLI script basename """ return "cli_salt_key.py"
5e4b1116b21e66e1642f5046f65010a0ffc78d2f
56,838
import urllib import logging def run_inference_on_image(image_url): """Runs inference on an image. Args: image: Image file name. Returns: Nothing """ # Read image from URL user_agent_header = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025...
ca2a2eeb1c4daaf79d9479d208c274189dc6e8d8
56,839
def main() -> int: """ Consider only horizontal and vertical lines. At how many points do at least two lines overlap? """ l, g = parse_input() lines: dict[tuple[int], tuple[int]] = l grid: list[list[int]] = g for line in lines: if line[0][0] == line[1][0]: mini = min(line[0][1], line[1][1]) maxi = max...
89a3debac8f9b598c9bef90ce45a1d0927f9bac6
56,841
def U_XX(j, n): """Makes a sequence of operations for XX basis. Args: j (int): Position of 'HH'. n (int): Length of the sequence. Returns: str: Sequence of operations. """ assert j < n - 1 assert n > 2 return 'I' * j + "HH" + 'I' * (n - j - 2)
b08a985be8d3105846e320bd9cc3a3548b4bd8eb
56,842
def get_bootstrap_setting(setting, default=None): """ Read a setting """ return BOOTSTRAP4.get(setting, default)
c60bb97721ad485d7929dd7edea5182f3473bb2e
56,843
from typing import Union from typing import Optional from typing import Dict from typing import Any def compile( sir: Union[serialization.SIR.SIR, str, bytes], *, unit_info: Optional[Dict[str, Any]] = None, **kwargs, ): """Compile SIR to source code. This is a convenience function which insta...
45c0d46a887dd9f7261259512f2a90d04fc5b1b5
56,844
def forgot_password(): """ User forgot password Input: email Output: 200 and a reset password email is sent to user 400 if email not exist """ data = request.get_json() if not data or not data.get("email"): return jsonify(error="request body must contain emai...
b29ff753ef26feab1289e1ffe9108a2cd9386dfd
56,846
def mape(y_true, y_pred): """ Mean absolute percentage error regression loss. Args: y_true ([np.array]): test samples y_pred ([np.array]): predicted samples Returns: [float]: mean absolute percentage error """ diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), K.eps...
3672984361c31a3054eb962d61a4f7f349760b77
56,847
def analyze(): """Analyze the frame and return the results""" if not request.is_json: return jsonify(error='Request must be json'), 400 try: frame = data_uri_to_cv2_img(request.json['frame']) except: # pylint: disable=bare-except return jsonify(error='Could not decode frame'), ...
c0cb538f5a306b696b55b81c8dc9c344f0629bb7
56,848
def train_and_eval(trial: optuna.Trial, ex_dir: str, seed: [int, None]): """ Objective function for the Optuna `Study` to maximize. .. note:: Optuna expects only the `trial` argument, thus we use `functools.partial` to sneak in custom arguments. :param trial: Optuna Trial object for hyper-para...
d92a3279ecfa741f1d852afd3bfb277da2654f61
56,849
def duplicate(my_list): """Return a new list that repeats the input twice""" return my_list + my_list
569f061ff02e996dd3c1a7030aed2934e61987f7
56,851
def get_predicted_changes(query_params): """ Get a list of predicted profitable changes. """ order = query_params.get('order_by') if order is not None: order = order.split(',') else: order = ['date'] all_predictions = predictions.get_predictions( instrument=query_params.g...
15150370309f1f4ba98a1df0e9977fcfb4d0cf99
56,852
def _get_default_generators( options, in_memory = False ): """Initialize default list of stats generators. Args: options: A StatsOptions object. in_memory: Whether the generators will be used to generate statistics in memory (True) or using Beam (False). Returns: A list of stats generator ...
fb92c7f5129685ccfadd356ee4bba9bf39cad560
56,853
def ucfirst(string): """Return string with first letter in upper case.""" if len(string) < 2: return string.upper() else: return string[:1].upper() + string[1:]
19c9be463e8c45db9ce7b5dfc91f7260bea9a81d
56,854
from typing import Callable from re import T def random_method(decorated: Callable[..., T]) -> Callable[..., T]: """Decorator usable on any method within a class that will provide an isolated torch random context. The decorator will store a `_random_instance` property on the object in order to persist succes...
1df1f654c8de146b11dd7189196ec4d403f23c0f
56,855
def get_word_counter(word_vocab): """ Convert a list of tuple of words and their frequencies in word vocabulary to dictionary. Key is word and value is its frequency. Args: word_vocab: A list of tuple of words and their frequencies. Returns: A dictionary with word as the key and its frequenc...
8e76652c721d9ca175f79d9bb0acfccfb90da647
56,856
import copy def cost_backlink(in_source_data, in_cost_raster, max_distance=None, source_cost_multiplier=None, source_start_cost=None, source_resistance_rate=None, source_capacity=None, source_...
27708dca1a2611af554a5acb786bdff737a3eb22
56,857
import torch def format_metric(val): """Format a tensor/number as a float with 4 digits""" if isinstance(val, torch.Tensor): val = val.detach().data return str('{:.4f}'.format(val))
337e266bca4ff0433e2c69864b1a493976d12c44
56,858
def estimate_value_from_state_action_ratios( data, gamma, state_action_ratio_fn): """Estimates value of policy given data and state-action density ratios. Args: data: The experience data to base the estimate on. gamma: Discount to use in the value calculation. state_action_ratio_fn: A funct...
01e516fd72a175648d069f559430b8a88d613574
56,859