content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _get_file_names(): """Returns the file names expected to exist in the input_dir.""" file_names = {} file_names['train'] = ['data_batch_%d' % i for i in xrange(1, 5)] file_names['validation'] = ['data_batch_5'] file_names['eval'] = ['test_batch'] return file_names
c2fb7a28fb7e0a1da0ab914f008f580e0f4b17b0
3,625,237
def index_of_best(list): """ low distance is better :param list: :return: """ a_list, error_count, error = remove_errors(list) return list.index(min(a_list))
03c484e0579cb78054ce9177cfe52520f692247a
3,625,238
def mold( content: VyList, shape: VyList, ) -> VyList: """Mold one list to the shape of the other. Uses the mold function that Jelly uses.""" # https://github.com/DennisMitchell/jellylanguage/blob/70c9fd93ab009c05dc396f8cc091f72b212fb188/jelly/interpreter.py#L578 if isinstance(content, str): ...
d28ccab5c3e3338b0e55dc1ff2be327721856919
3,625,239
import json import torch import copy import pickle def goal_optimization(model_exp_key, opt_exp_key=None, write_results=True): """ Optimize random goal states using a model-based estimator. Note: tailored to HalfCheetah-v2 environment currently. Args: model_exp_key (str): model-based experime...
fbe668784003dbce61bfbd499dc80cb26fed3457
3,625,240
import gzip import struct from functools import reduce import operator def _read_datafile(path, expected_dims): """Utility function for reading mnist data files.""" base_magic_num = 2048 with gzip.GzipFile(path) as f: magic_num = struct.unpack('>I', f.read(4))[0] expected_magic_num = base_...
12b0940e369769b8948867f30e7b0ee436723609
3,625,241
def _vsos(da, pos, method_sos="median"): """ vSOS = Value at the start of season Params ----- da : xarray.DataArray method_sos : str, If 'first' then vSOS is estimated as the first positive slope on the greening side of the curve. If 'median', then vSOS is estima...
6b4bf26d6c0d3b7d6fecfbed07dabf3ec202ae41
3,625,242
def parse_coordSys(config, coordSys=batoid.CoordSys()): """ @param config configuration dictionary @param coordSys sys to which transformations in config are added """ shift = [0.0, 0.0, 0.0] if any(x in config for x in ['x', 'y', 'z']): if 'shift' in config: raise ValueErr...
461ca4fe295ffa5bb47dd40d2af00f4034c5222c
3,625,243
import hashlib def password_hasher(password): """ Just hashes the password :param password: :return: 32 byte hash :rtype: bytes """ return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), b'salt', 100000)
44e921903c63f1703bbc79869f1a63a25bfe5916
3,625,244
def index_alpha_beta(i, ij, ik, points): """ Finds for each input point the index of it's bounding triangle and the alpha and beta value for that point in the triangle. Note this means that the following statements will always be true: alpha + beta <= 1 alpha >= 0 beta >= 0 f...
4799890b1e292bce19628779294e068f73744e76
3,625,245
import array def flac_read_file_f32(filename: str) -> DecodedSoundFile: """Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float.""" filenamebytes = _get_filename_bytes(filename) with ffi.new("unsigned int *") as channels, \ ffi.new("unsigned int *") as sample_rate,...
d455a941ef27cdc7b696fae648556c31b3664135
3,625,246
import ctypes def version() -> str: """ Version library :return: version """ pfun = _lib.zmVersionLib pfun.restype = None pfun.argtypes = (ctypes.c_char_p,) ver = ctypes.create_string_buffer(32) pfun(ver) return ver.value.decode("utf-8")
d91f04d7c614d11803df4d6d5b6f3b96c6d60202
3,625,247
def get_all_books(request): """ This view is to return all the books """ books = Book.objects.all() context = { 'books': books } return render(request, 'books/books.html', context=context)
059b9db54fdb52b1918de4e5c32f48f6400acf4e
3,625,248
def _GetSchemaPath(release_track, for_help=False): """Returns the resource schema path.""" return export_util.GetSchemaPath( 'compute', _GetApiVersion(release_track), 'TargetHttpsProxy', for_help=for_help)
02ef6e67daf4337859716cbc71edf41bb14cfaa5
3,625,249
def login(): """Login a user""" if not request.is_json: return jsonify(error="Missing JSON in request"), 400 username = request.json.get("username", None) password = request.json.get("password", None) remember = request.json.get("remember", False) if not username: return jsonify(...
5e0af9233b15ac81918dbbd0459fa192905d52f7
3,625,250
def client_host(server_host): """Return the host on which a client can connect to the given listener.""" if server_host == '0.0.0.0': # 0.0.0.0 is INADDR_ANY, which should answer on localhost. return '127.0.0.1' if server_host in ('::', '::0', '::0.0.0.0'): # :: is IN6ADDR_ANY, which should answer on localhost...
93d1b23c7714e5252efc866daa10dd5f7f53e0e7
3,625,252
def get_context(bot, update, session, user): """Create a context object for callback queries.""" context = CallbackContext(session, bot, update.callback_query, user) add_breadcrumb( crumb={ "query": update.callback_query, "data": update.callback_query.data, "user...
4cb0259e8dd1ddcde8e4142c92da5ba5b2514d33
3,625,253
def customer_all_detail(request, pk): """客户详情(不能更改信息)""" customer = get_object_or_404(Customer, pk=pk, is_valid=True) form = CustomerForm(instance=customer) # 添加上地址信息 # 下面这里引入异常处理,如果数据库里没有该字段,那么表单渲染为空 try: customer_shop = CustomerShop.objects.get(customer=pk) shopform = CustomerS...
a239f01a73a519880c6372bacd79370e07268841
3,625,254
import logging def logmethod(func): """ Decorator to add logging information around calls for use with . """ def _wrapper(self, *args, **kwds): logging.info("Start::%s.%s:%s", func.__module__, self.__class__.__name__, func.__name__) ...
7f8223ab99d6f9101088bff050f79fd0669231d4
3,625,255
def to_isbn(ean): """Convert EAN to ISBN""" clean = clean_isbn(ean) isbn = clean[3:-1] isbn.append(isbn_check_digit(isbn)) return ''.join(str(d) for d in isbn)
3537e28de6c296bb07d791fb7b7a87eec6539057
3,625,257
def markdown_cell(content): """ Create a markdown cell with a given content. """ return nbformat.notebooknode.NotebookNode({"cell_type": "markdown", "source": content, "metadata": {}})
fadb7ad9d2e3a1df3393aab5cef7f012612a99b0
3,625,258
def _replace_suffix(string, old, new): """Returns a string with an old suffix replaced by a new suffix.""" return string.endswith(old) and string[:-len(old)] + new or string
4e487f62126b130d973f249cd34abc5a75df3eaa
3,625,259
def compute_fig(grid, col_x, col_y, col_z, value_coupe, n_points, xlim, ylim): """uses user input parameters to compute the values to plot Parameters ---------- grid : pandas.DataFrame full data grid col_x : string horizontal column in final plot col_y : string vertical ...
0e8614cbf625560bce8ac533184c36d7b464e72e
3,625,260
def is_empty_json_response_from_s3(context): """Check if the JSON response from S3 is empty (but not None).""" return context.s3_data == {}
6ec3a41646de74d82f3786e772228da55d91b63a
3,625,261
def vault_value(key, default=None): """ Returns the secret referenced by the key supplied. If the vault has not been initialized, returns the provided default instead :param key: :param default: :return: """ if not vault_ready(): return default try: return _get_from_...
e7c055a4e1e8f6a1b7c8fb9fe1f2d219a84fb5e6
3,625,262
def show_expression_of_KO_genes( sample_meta_file: str, normalized_matrix: str, ko_list: list, ko_dict: dict = "", percentile: bool = False, heat: bool = False, ): """ Show expression of the genes that were actually knocked out. Parameters ---------- sample_meta_file ...
d647b2c54dd4049176667122196fcc8bd595549a
3,625,263
from datetime import datetime def preprocessEventData(eventData): """ Ensures that the event data dictionary is consistent before it reaches the template or event logic. - dates should exist and be date objects if there is a value - checkbaxes should be True or False - if term is ...
ceea909651a706e2aef532855788205d9b962f8c
3,625,264
def get_data(self): """Generate the PWM matrix Parameters ---------- self : ImportGenPWM An ImportGenPWM object Returns ------- matrix: ndarray The generated PWM matrix """ # Tpwmu=np.arange(fs*duration)/fs, Tpwmu = np.linspace(0, self.duration, self.fs * self....
e2aea3c7acfdda09601a5e1d92192390b1276310
3,625,265
def set_code_by_activity_hash(db, overwrite=False): """Use ``activity_hash`` to set dataset code. By default, won't overwrite existing codes, but will if ``overwrite`` is ``True``.""" for ds in db: if 'code' not in ds or overwrite: ds['code'] = activity_hash(ds) return db
539c4b0618ff9112136a4e697dce34efabf0bee6
3,625,266
def ca_time_sync(h_session, ultime): """ :param int h_session: Session handle :param ultime: """ ret = CA_TimeSync(h_session, CK_ULONG(ultime)) return ret
c80a5a328826d63f661bf0a20156ddf6147a2a19
3,625,267
def add_subparser(parser): """Add the subparser that needs to be used for this command""" plot_parser = parser.add_parser("plot", help=DESCRIPTION, description=DESCRIPTION) cli.get_basic_args_group(plot_parser) plot_parser.add_argument( "kind", type=str, choices=SINGLE_EXPERIME...
35f460076138655f7bc2db871bb1919fe29dfdaf
3,625,268
def Potential_bruteforce_parallel(x,m,softening,G=1.): """Returns the exact mutually-interacting gravitational potential for a set of particles with positions x and masses m, evaluated by brute force. Arguments: x -- shape (N,3) array of particle positions m -- shape (N,) array of particle masses s...
034f526d2597f9c418430ff26aeae2ee9adcf867
3,625,269
from typing import Mapping from typing import Any from typing import List import collections def _validate_plurals(mapping: Mapping[str, Any], ref: str) -> List[SchemaError]: """ Check that no graph field conflicts with a instance registry field. The instance registry field is iden...
b57096d223400385c2d1671e91359e6b52907a6a
3,625,270
def mock_validator_execute_validator(*args, **kwargs): """ Mock method to just return the builded command line without executing it. """ cls = args[0] command = args[1] return command
d03cc70f1f0a5bd59e7a116e3774b99aa8db5a03
3,625,271
def load_seq(seq_path): """Load HPatches sequences.""" seq = cv2.imread(seq_path, 0) n_patch = seq.shape[0] / 65 seq = np.reshape(seq, (n_patch, 65, 65, 1)).astype(np.float32) resized_seq = np.zeros((n_patch, 32, 32), np.float32) for i in range(n_patch): tmp_patch = cv2.resize(seq[i], (...
2f605ab5fcdc6c336613d8397e87721ba762ecf1
3,625,272
def mode_check_decorator(func): """Decorate load()/save() CookieJar methods.""" def wrapper(cls, **kwargs): try: filename = kwargs['filename'] except KeyError: filename = cls.filename res = func(cls, **kwargs) file_mode_checker(filename, mode=0o600) ...
3c36b920b84dc14bd23bd189c15b7b5247705c61
3,625,273
def has_gap(k1, k2, min_gap=0.002): """判断 k1, k2 之间是否有缺口""" assert k2['dt'] > k1['dt'] if k1['high'] < k2['low'] * (1-min_gap) \ or k2['high'] < k1['low'] * (1-min_gap): return True else: return False
642d9793dcc6f85d3bf21e1abf6f481292c053f1
3,625,274
def get_pronoun_lemmas(conll_document): """ Returns the list of lemmatized pronouns found in the given contents of a CONLL document (list of triples). :param conll_document: the contents of a CONLL file, as a list of triples :return: """ pronouns = [] for (form, lemma, pos) in conll_document...
17507968c67e145c754da940743cea554102f7f4
3,625,275
def isdisjoint(pth1, pth2): """ returns 0 if disjoint """ edge1 = list(pairwise(pth1)) edge2 = list(pairwise(pth2)) for edge in edge1: if edge in edge2: return 1 return 0
2632d3c336871ecfb0cb3693db2f86d8ae527792
3,625,276
def delete_post(post_id): """function for deleting a business by id""" business = Business.query.get_or_404(post_id) if business.business != current_user: abort(403) db.session.delete(business) db.session.commit() flash('Your post has been deleted!', 'success') return redirect(url_fo...
af445a24c71b57eb26b5cc2603ff6cc246f8859d
3,625,277
def retract(request): """retracts a cash invitations""" params = request.get_params(schemas.RetractSchema()) device = get_device(request) customer = device.customer access_token = get_wc_token(request, customer) postParams = { 'reason': 'other' } response = wc_contact( re...
7d93210b985e36300adfe3e20006a5bec5918b8e
3,625,278
def generate_fileattr_metadata(local_path, metadata): # type: (blobxfer.models.upload.LocalPath, dict) -> dict """Generate file attribute metadata dict :param blobxfer.models.upload.LocalPath local_path: local path :param dict metadata: existing metadata dict :rtype: dict :return: merged metadat...
4231af249ccc9f57f413ca02735ae57c3a91d8bc
3,625,279
def build_estimator(model_dir): """Build an estimator.""" m = tf.estimator.LinearClassifier( model_dir=model_dir, feature_columns=base_columns, optimizer=tf.train.FtrlOptimizer( learning_rate=0.1, l1_regularization_strength=1.0, l2_regularization_strength=1.0) ) return m
6ec9ad927d86aafc4bf8b20771ff8092ab652a50
3,625,280
import logging def _set_logger( logger_file_path: str, logger_name: str = "default_logger", write_to_console: bool = True, ) -> logging.Logger: """Set logger to log to the given path. Modified from https://docs.python.org/3/howto/logging-cookbook.html Args: logger_file_path (str): Fi...
338999fbcd34367f1dc4140143688965663bf486
3,625,281
def sort_and_print(body, num): """ Sorts the values of dictionaries and prints respective top sentences :param body: list of dictionaries of 'sentence': score :param num: no of sentences to be printed :return: prints """ result = [] rank = [] for sentdict in body: for sen...
400b11f84d0e68fb393c261736856257b4681c52
3,625,282
def get_trans_func(name): """ Retrieves the transformation module by name. """ trans_funcs = { "bottleneck_transform": BottleneckTransform, "basic_transform": BasicTransform, } assert ( name in trans_funcs.keys() ), "Transformation function '{}' not supported".format(...
2fbad8e9034734bedccf6a21842c389b63b26336
3,625,283
import torch def get_box_pair_info(box1, box2): """ input: box1 [batch_size, (x1,y1,x2,y2,cx,cy,w,h)] box2 [batch_size, (x1,y1,x2,y2,cx,cy,w,h)] output: 32-digits: [box1, box2, unionbox, intersectionbox] """ # union box unionbox = box1[:,:4].clone() unionbox[:, 0]...
6461d64ae2d5ef0338cb69dda40fad65882a8803
3,625,284
def bintogrid( x, y, unc=None, newx=None, dx=None, weighting="inversevariance", drop_nans=True, ): """ x = the independent variable (wavelength) y = the measurement (transit depth) unc = the uncertainty on the measurement (sigmas on the transit depths) newx = a (linearly)...
e392dadfda3eec08e32f2d74f1ac5729f00176c4
3,625,285
def parse_date(date_str: str) -> date: """Just a wrapper to avoid having to declare dateutil as a dependency in other projects.""" return dateutil_parser(date_str).date()
8fdf6ae162f46547f488a4ccd1b7fe82a60ac731
3,625,286
import torch def dagger(x: torch.Tensor) -> torch.Tensor: """Conjugate transpose of a batch of matrices. Matrix dimensions are assumed to be the final two, with all preceding dimensions batched over.""" return x.conj().transpose(-2, -1)
672d26333182803b18f3d1d10e49ef393e216f5f
3,625,287
def node_factory(edge_model, children_null=True, base_model=models.Model): """ Dag Node factory """ class Node(base_model, NodeBase): class Meta: abstract = True children = models.ManyToManyField( "self", blank=children_null, symmetrical=...
9b739490baab70a5b24a90b611e2db6e1a3664fa
3,625,288
def geometry_mask( geometries, out_shape, transform, all_touched=False, invert=False): """Create a mask from shapes. By default, mask is intended for use as a numpy mask, where pixels that overlap shapes are False. Parameters ---------- geometries : iter...
726865aff256bdb73c3215f57dd2c7bfa0a58dd6
3,625,289
def detection_area(self): """ Checks the area to have obstacles :return: float """ image = ImageGrab.grab(self.area) gray_img = ImageOps.grayscale(image) arr = np.array(gray_img.getcolors()) # print(arr.mean()) return arr.mean()
4893e33696a3e11db290dae28a8f346c21c02a51
3,625,290
from pathlib import Path import requests def _get_data_by_filename(fname: str) -> Path: """ Download file or used cached version. Args: fname (str): name of file to download Returns: Path: path at which file lives """ full_fname = DATA_PATH.joinpath(fname) # check if fil...
11b908b801db2c4002a837c78a3266608cbe3056
3,625,291
def build_input(data_path, batch_size, size, mode): """Build image and targets. Args: data_path: Filename for data. batch_size: Input batch size. mode: Either 'train' or 'eval'. Returns: volumes: Batches of volumes. [batch_size, volume_size, volume_size, volume_size] targets: Batches of targe...
20bce2efcbb7a4f1998b754daf1577af1c885507
3,625,292
def _get_publication(paper_entry: dict) -> Publication: """ Using a paper entry provided, this method builds a publication instance Parameters ---------- paper_entry : dict A paper entry retrieved from arXiv API Returns ------- Publication, or None A publication instanc...
bb530e8e4d6fbb5dad7438e18a1a63dc028b44b8
3,625,293
def get_table_13(): """表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数 Args: Returns: list: 表 13 玄関ポーチに設置された照明設備の人感センサーによる補正係数 """ table_13 = (0.9, 1.0) return table_13
91a89343800ad5e3c587371c91e7d256d9ed85a1
3,625,294
def Parse(text: str) -> ParsedUniversalDependencies: """Parses the provided text.""" doc = nlp(text) return __parse_tokens(doc)
9878eb1cfd82d2590663635ba659f997c5619f23
3,625,295
def Log_GetTimestamp(*args): """Log_GetTimestamp() -> wxChar""" return _misc_.Log_GetTimestamp(*args)
ec3574361a50cf12c8fd21bd9b51885905e61477
3,625,296
def find_left_anchor_index(fragment_info, fragments): """ Description: Use the fragment information to find which fragment is the left anchor :param fragment_info: [list[dict]] the list of fragment information :param fragments: [list] the list of fragments being searched :return: left_anchor_ind...
502473f7fee00a5ccd1ed3d6cf5c938e8c4d2041
3,625,299
def get_all_preconditions(action_set): """ Returns a set of all preconditions for the actions in the given set """ all_precons = set() for a in action_set: all_precons.update(a.precondition) return all_precons
1697c2d013b07bbfc24ca6273d16523eb1d83acf
3,625,300
def confusionmatrix(tt, tp, gn=['', '', ''], plot=False, title='', cmm='Blues', fontsize=20, ylabel='True', xlabel='Prediction'): """ Calculates and/or plots the confusion matrix for machine learning algorithm results. :type tt: list[float] :param tt: Real targets. :type t...
47e16c6df881e18f6cdf3317a5db575453269b9c
3,625,301
def _to_string(*args: Object) -> Object: """Convert an integer to a string""" if len(args) != 1: return Error("It must recieve one parameter") number: Object = args[0] if not isinstance(number, Integer): return Error("It must be an integer") return String(str(number.value))
397a3deae6464602e04732e940e65a87f9976261
3,625,302
from typing import Optional def compose_conformers(*conformers: Optional[Conformer]) -> Optional[Conformer]: """ Return a single conformer which is the composition of the input conformers. If a single conformer is given, return the conformer. """ conformers = tuple(filter(None, conformers)) ...
7f6b2856ea1cc79d287a864b9ff07d8fc15a69ed
3,625,303
def model_fn_builder(config: Configs, tasks, num_train_steps, pretraining_config=None): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): """The `model_fn` for TPUEstimator.""" log("Building model...") is_training = (mode == tf.estimat...
6eced6c3f1ffd6ad01ef1ff8c65096ea1cbf7ce6
3,625,304
def get_ul_inds(udeg, ls): """ """ # Turn `ls` into a slice if isinstance(ls, integers): ls = slice(ls, ls + 1) if isinstance(ls, slice): # List of indices user is accessing inds = [] # Fill in the `None`s if ls.start is None: ls = slice(0, ls...
49132020728129ca0288047f998b06a567b78164
3,625,305
def f_line(x, m, b): """ Line fit with equation y = mx + b Parameters ---------- x : array x values m : float slope b : float y-intercept Returns ------- y : array y values """ y = m*x + b return y
daf437461c2e8723a824e4083794d1f6ea6b368b
3,625,306
def extractLostInTranslation(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Third Prince Elmer' in item['tags']: return buildReleaseMessageWithType(item, 'Third Prince Elmer', vol, chp, frag=fr...
ed7802c168626e5d87a7dcade175ff1b8a54fd54
3,625,307
import random def determinize(perspective: cs.Perspective, mode=0) -> GameState: """Determinize the given perspective into a deterministic state. The mode parameter determines the way in which determinization happens. """ if mode == 0: is_declarer = perspective.player == perspective.declarer ...
6964a75dbafb784ea6e1ef9d0c03fdc774d3881e
3,625,308
def parse_value(file, section, key): """ Read ini file and returns unique value :param file: File to be parsed :type file: str :param section: Section targeted :type section: str :param key: Parameter to be read :type key: str :return: Read value :rtype: str """ config = Con...
f3658f28323a19836f41da86527c35a99dcffe1a
3,625,309
def demo_JmE(X, Y, DPiters=1000): """ Explore the posterior of our model. """ """ Create expert shell """ expert = MixtureOfExperts.experts.IndpendentRBF(input_dim=X.shape[1], output_dim=Y.shape[1], process_mean='Constant', ard=True) expert._p...
e7957d72dbb575d87cb5cb83f857432b40d98071
3,625,310
from bs4 import BeautifulSoup import json def magazineluiza_parser(html): """ Parser for magazineluiza.com.br. There's an attribute with a JSON containing all the info we need when the item is available. When it isn't, we must retrieve the info from another JSON, one much less complete (without b...
634f38ce32662594a9f14e8d27d835205317591a
3,625,311
def getDistance(sensor): """ Return the distance of an obstacle for a sensor. The value returned by the getValue() method of the distance sensors corresponds to a physical value (here we have a sonar, so it is the strength of the sonar ray). This function makes a conversion to a distance value ...
d00b1d201fb59939d2b8a2e57bfa35588780b6d5
3,625,312
import warnings def sjoin( left_df, right_df, how="inner", predicate="intersects", lsuffix="left", rsuffix="right", **kwargs, ): """Spatial join of two GeoDataFrames. See the User Guide page :doc:`../../user_guide/mergingdata` for details. Parameters ---------- left_...
aa27217a006d2cfc77ff1012ed1814f059da1717
3,625,313
def compute_BtBinv(B, C): """Create block inverses. Helper function that creates inv(B_i.T B_i) for each block row i in C, where B_i is B restricted to the sparsity pattern of block row i. Parameters ---------- B : {array} (M,k) array, typically near-nullspace modes for coarse grid, i....
65871a8bb1a4491aa3a7bc1b112ea1312717bd49
3,625,314
import random def fixed_onepoint(p_0, p_1): """ Given two individuals, create two children using one-point crossover and return them. The same point is selected on both genomes for crossover to occur. Crossover points are selected within the used portion of the genome by default (i.e. crossover do...
1db8157bbd3434c91fe82c64221a56c53bb56b36
3,625,315
def get_pipeline_ids(db_name='./grades.sqlite3'): """ :param db_name: :return: """ with lite.connect(db_name) as con: cur = con.cursor() result = cur.execute("SELECT pipeline_id FROM students") try: resut = (ids[0] for ids in result.fetchall()) except Exc...
7091d6098b33bbfbfba00f3e134b4d23b07f3b34
3,625,316
def update_individual_metadata(ts): """Update individual metadata in ts object. Returns new list of individuals with updated metadata """ individuals = [] oldname = None i = 0 for ind in ts.individuals(): popindex = ts.nodes()[ind.nodes[0]].population popname = ts.population...
4cfaf24fc4e68203e8206163fcb0686ac9fd9692
3,625,317
def get_trt_logger(): """ Get the global TensorRT logger created by Polygraphy. Returns: trt.Logger: The TensorRT logger. """ global TRT_LOGGER if TRT_LOGGER is None: TRT_LOGGER = trt.Logger() return TRT_LOGGER
06ca9e41932f936c3b31ae210de040954916816c
3,625,318
from pathlib import Path import torch def _convert_rx101_to_mobile( model_path: str, num_classes: int, output_path: str or Path = "./rx101_optimized_scripted1.ptl", ): """Function handling conversion of MSCG-Net Rx101 Models :param model_path: :param num_classes: :param output_path: :...
a8b92ca86d893266b5eab5ebe8a03112ffa74d1f
3,625,319
from datetime import datetime def unify_index_info_couch_dates_fmt(index_info): """Applies standardization to secondary keys 'date' type keys. @param index_info: is a index data to workout for """ clean_info = {} index_keys = [key for key in index_info.iterkeys()] for index_key in index_keys:...
3ae4ba10be563082ae60a0636ff5a1b4e464ff97
3,625,320
def stellar_dist(row: pd.Series, push: float) -> pd.Series: """Calculate the fluxes for the stellar objects at a given distance. For use with pandas.DataFrame.apply(). Requires the columns: - 'distance' - 'radio' - 'optical_in_mJy' Args: row: The pd.Series object containing...
401ce8b51df995b3e62a025750d5a0871c6e3b3f
3,625,321
import platform def mysql_config_path(): """ 根据平台查询mysql配置文件 :return: """ _platform = platform.system() print('当前平台为:{}'.format(_platform)) mysql_config = None if _platform == 'Darwin': mysql_config = "/Users/yuxiang/Documents/Developer/WeChat/baixiaotu-mini/sqlconfig.json" ...
c24632e4262ea1cfb903492b5d261a8cd5cbcd8e
3,625,322
import collections def calculate_case_distances( graph: nx.DiGraph, case: Case, *, additional_attributes: "list[str]" = [] ) -> "dict[str, float]": """ Extracts the distances between the current graph and a given case across trace, time, and the additional attributes provided. Arguments: ...
3e7383a983d611564edfa0689d22595e38ef83d6
3,625,323
import numpy def index_to_position(index, nelx, nely): """ Convert the index of a element to the centroid of the element """ return numpy.array([(index % nelx)+.5, index/nelx+.5])
1402251581df9e346097dbd561ef5f782f18da1e
3,625,324
import http def imdb(inp, api_key=None): """.imdb <movie> -- gets information about <movie> from IMDb""" if not api_key: return None content = http.get_json("https://www.omdbapi.com/", t=inp, apikey=api_key) if content["Response"] == "Movie Not Found": return "movie not found" e...
44fb0e2d4ae7940c4fc59c2788062072420a3b5b
3,625,325
def smooth(sig, window_size): """ Apply a uniform moving average filter to a signal. Parameters ---------- sig : ndarray The signal to smooth. window_size : int The width of the moving average filter. Returns ------- ndarray The convolved input signal with the...
f91cbbeff3402c730d7b4f711c05c1992eed9e3a
3,625,327
def filter_by_oid_alt(instructions, oid): """ For a given list of instructions and an Order ID, return the list of instructions that reference that Order ID. :param instructions: list of instructions :type instructions: list or tuple :param oid: Order ID :type oid: int :return: list of inst...
c7d6b1cfd2218adfba1612bf42ac19a15e98e776
3,625,328
def get_sequence_lineage(request, upi): """ Internal API. Get the lineage for an RNA sequence based on the classifications from all database cross-references. """ try: queryset = Xref.objects.filter(upi=upi).select_related('accession') results = queryset.filter(deleted='N') ...
2339a648a5bf12b033dd9fdfb86f667ce6b92210
3,625,329
import requests def get_function_fb_graph(): """Get call - facebook.""" return requests.get('http://graph.facebook.com')
38f790a006a3d8de981e66936e50b7be743e4d1b
3,625,330
def mat_to_pose_wxyz(mat): """Convert matrix to pos and wxyz quaternion.""" p = mat[:3, 3].tolist() p += tra.quaternion_from_matrix(mat).tolist() return np.array(p)
a98da080207daeec40657bf57fd5c44c1063d780
3,625,331
def setDefaultCompressionCodecName(compressionCodecName): """ :param compressionCodecName: java.lang.String """ return _java_type_.setDefaultCompressionCodecName(compressionCodecName)
8b8fbad360826c9a4a11e0e7b2c18ae473ea1e03
3,625,332
def do_ajax_update_no_effect(parser, token): """ Updates a target div by binding a onclick event to a link which uses jquery.metadata to parse for the target div and data source url """ try: args_list = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "...
61fd3dcc3a176b70c9b670bc91f0f055a6f8f84d
3,625,333
def standardize_rows(M): """ Distribute the rows of the cost matrix normally to allow for accurate comparisons of error and description cost. """ rv = np.matrix(M) for i in range(rv.shape[0]): mean = np.mean(M[i, :]) stdev = np.std(M[i, :]) rv[i, :]= (M[i, :]- mean)/stdev ret...
dd3abb0eebc15dd72c9b64b66217018c0295bd9f
3,625,334
def refine_group_join_event_msg(ctx: EventMsg) -> _GroupJoinEventMsg: """某人进群事件""" if not isinstance(ctx, EventMsg): raise ContextTypeError('Expected `EventMsg`, but got `%s`' % ctx.__class__) if ctx.EventName == EventNames.ON_EVENT_GROUP_JOIN: return _GroupJoinEventMsg(ctx) return None
4cd23b709e4d68e813d99d9ffd59a18b7cd87331
3,625,335
def parse_dlna(dlna_server): """ Return a dict of title: url from dlna """ res = [ s for s in upnpclient.Device("http://{}/rootDesc.xml".format(dlna_server)).services if s.name == "ContentDirectory" ][0].Browse( ObjectID="2$8", BrowseFlag="BrowseDirectChildren...
77eeed8cd2200cfa96c76e15b444cc511eb8c5f3
3,625,336
import random import pickle def sax_optimization(locator, data, time_series_len, BOUND_LOW, BOUND_UP, NGEN, MU, CXPB, start_gen, building_name): """ A multi-objective problem set for three objectives to maximize using the DEAP library and NSGAII algorithm: 1. Compound function of accurracy, complexity and...
f224e6039a30a444f94e3730acfa318344e384dc
3,625,337
def randomize_and_play_circuit(n_gates: int, init_state: str = "z"): """ :param n_gates: the depth of the circuit :param init_state: starting position on the bloch sphere :return: """ state = init_state for ind in range(n_gates): state = play_clifford(cliffords[np.random.randint(0, ...
c82620401fd9510c1d8b425613c013cd4cb831cc
3,625,338
def pair(dice): """Score the given roll in the 'Pair' category""" counts = dice_counts(dice) for i in [6, 5, 4, 3, 2, 1]: if counts[i] >= 2: return 2*i return 0
1076e00dd877e0381d990a4abe4942dd24c533fb
3,625,339
def get_data_for_fit(expt, mask): """ exlucdes pre-bleach frame (T[0]) from the array Parameters ---------- data: aicsimageio.aics_image.AICSImage mask: np.ndarray Returns ------- data_for_fit: np.ndarray """ norm_inside = _norm_extract(expt, mask) data_for_fit = norm_...
e6a02374f2d141f88beb5cc3157272af3424aafa
3,625,340
def gen_docker_image_reference(): """Generating a docker image reference including image ID. returns the docker image reference and image ID""" image_id = 'sha256:some-long-fake-id-with-numbers-{}' docker_image_refrence = 'this.is.some.fake.{}/registry:{}@{}'.format( fauxfactory.gen_alpha().lowe...
1b10c10992efdb991b5ea97b734d07e53181f647
3,625,341