content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def air_cargo(): """ [Figure 10.1] AIR-CARGO-PROBLEM An air-cargo shipment problem for delivering cargo to different locations, given the starting location and airplanes. Example: >>> from planning import * >>> ac = air_cargo() >>> ac.goal_test() False >>> ac.act(expr('Load(C2,...
7cbcf38abad878b7f381904a16eb440d602a5e34
3,613,360
import tempfile def create_spooled_temporary_file(filepath=None, fileobj=None): """ Create a spooled temporary file. if ``filepath`` or ``fileobj`` is defined its content will be copied into temporary file. :param filepath: Path of input file :type filepath: str :param fileobj: Input file ob...
5254c01194a94063e405c721735fb9e390fd8380
3,613,362
def _split_comma_separated(string): """Return a set of strings.""" return set(filter(None, string.split(',')))
855c23c7a6602c9306b73016cc66573773d1d502
3,613,363
def make_ur_axialregion(asm_input, reg, mat_dict, flow_rate): """Process DASSH Assembly AxialRegion input to obtain un-rodded region input parameters; to be used when instantiating un-rodded region objects as axial regions in DASSH Assembly object""" model = asm_input['AxialRegion'][reg]['model'] ar...
70dc0e07fb5e707fb22c11ed036b4418e2412172
3,613,364
from typing import Optional from typing import Callable from re import T def deprecate( remove_by_version: str, replacement: Optional[str] = None ) -> Callable[[T], T]: """Return a function that can be used to deprecate functions. Currently this is only used for deprecation of hook functions, but it may b...
b18a5abcc63d3ad142d5c13a0f592cee39503bc5
3,613,365
def triangular(n): """Compute the n-th triangular number.""" return np.floor_divide(n * (n + 1), 2)
d328f4c8c38452fbadcacd59f583e37c86ce4e02
3,613,366
from bs4 import BeautifulSoup def list_captures(): """Get a list of the videos and photo files on the GoPro Use BeautifulSoup to parse the GoPro's list of captures This list of captures is provided by the Cherokee webserver on the GoPro To get this capture the GoPro Hero 3 Black """ page = ur...
3931c2017825d3df3a0fcd36d78c7f086e3c4f3c
3,613,367
def get_nbest(lat, n, aw=1.0, lw=1.0, ip=0.0): """Obtain nbest hypotheses with scores from the lattice.""" hyps, scores = [], [] nbest_paths = lat.nbest(n, aw=aw, lw=lw, ip=0.0) for path in nbest_paths: hyp = [arc.dest.sym for arc in path] # sos, eos, and other tokens are stripped ...
235f49f24ed55c40f653146c2fae39fa960fcdf5
3,613,368
def get_tests(): """Parse the TESTS file. Parse the TESTS file and return a list of Entry objects """ if not check_test_index(): add_ids_test_index() in_file = open(TESTS, 'rb') entries = [] entry = Entry() cur = entry.buffer counter = 1 is_pre = False pre_sapces = 0...
8a532b2e710cff5db86f55aa5bd3e1096a84a52c
3,613,370
def interpolate(xs: list, ys: list, zs: list, ratio: float) -> list: """ This interpolates between two points """ x = xs[1] - xs[0] y = ys[1] - ys[0] z = zs[1] - zs[0] return [xs[0] + x * ratio, ys[0] + y * ratio, zs[0] + z * ratio]
63816ec83adbabef21ea92ee36a92884417755cc
3,613,371
import hashlib def str_to_sha256(s: str): """Generate a 256 bit integer hash of an arbitrary string.""" return int.from_bytes(hashlib.sha256(s.encode("utf-8")).digest(), "big")
90fcae50485e1469cdb0f363e4110011d5e6b642
3,613,372
def comment(pitch_id): """This will add a comment """ pitches = Pitch.query.all() comment_form = CommentForm() comments = Comment.query.all() if comment_form.validate_on_submit(): comment = Comment(comment = comment_form.comment.data, upvote = comment_form.vote.data,pitch_id = pitch_id,u...
84ce837f77f8f0d6317d5b7ab71615400b58737e
3,613,373
def get_template_redirects(site, template_name): """Gets the names of all of the template-space redirects to the provided template. The names come without namespaces. Example, if `site` is a enwiki site object: >>> get_template_redicts(site, "Hexadecimal") [u'hexdigit'] """ print(template_n...
a201e1d59864dad58afb34a82db89afe164ed4aa
3,613,374
def GetActiveWindow(*args): """ GetActiveWindow() -> Window Get the currently active window of this application, or None """ return _misc_.GetActiveWindow(*args)
13cfcd3b47cfa431c81f602498b5c77cc9f49db4
3,613,375
def get_pysyd_parameters(args, parallel, CLI): """ Basic function to call the individual functions that load and save parameters for different modules. Parameters ---------- args : argparse.Namespace command-line arguments CLI : bool `True` if running pysyd via command line ...
1e0ead51a82cd4692b9b3129038e8462f2bf3924
3,613,376
def cityscapes_palette(num_cls=None): """ Generates the Cityscapes data-set color palette. Data-Set URL: https://www.cityscapes-dataset.com/ Color palette definition: https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py Original source taken from: ...
b1a69a4e511e541f13aeb584003b7f4ec0dde956
3,613,377
import numpy def entropymatrix(elements): """Calculates the unnormalized Shannon entropy for a numpy matrix.""" entropysum = 0 result = 0.0 for (x, y), value in numpy.ndenumerate(elements): element = elements[x, y] if element > 0: result += xlogx(element) entrop...
b959f099d2f853da2987bc2bff4022bd6999687b
3,613,378
from typing import Optional def dislodged_unit_type_from_area( area_id: AreaID, board_state: np.ndarray) -> Optional[UnitType]: """Returns the type of any dislodged unit in the province.""" if board_state[area_id, OBSERVATION_DISLODGED_ARMY] > 0: return UnitType(UnitType.ARMY) elif board_state[area_id, ...
739c31ca93dc77006e2909b51b19411656817628
3,613,379
def try_with_lazy_context(error_context, f, *args, **kwargs): """ Call an arbitrary function with arbitrary args / kwargs, wrapping in an exception handler that attaches a prefix to the exception message and then raises (the original stack trace is preserved). The `error_context` argument should be...
7e2a4cfee7b4acf5a449b4b07f8c56baca5a63d3
3,613,380
def make_tweet_fn(text, time, lat, lon): """An alternate implementation of make_tweet: a tweet is a function. >>> t = make_tweet_fn("just ate lunch", datetime(2012, 9, 24, 13), 38, 74) >>> tweet_text_fn(t) 'just ate lunch' >>> tweet_time_fn(t) datetime.datetime(2012, 9, 24, 13, 0) >>> latit...
3f465f91dce37641e1ce391f6025c742d9e6ef36
3,613,381
import hashlib import base64 import secrets import traceback def user_login(): """ Endpoint for login password submission """ try: hashfunc = hashlib.sha256() hashfunc.update(request.form["password"].encode("utf-8")) stored_hash = DSCLIENT.get(DSCLIENT.key("config", "password_hash")) ...
4a81b690630e7d14bd60220ffaf323b0555230f1
3,613,382
def initial_wumpus_axioms(xi, yi, width, height, heading='east'): """ Generate all of the initial wumpus axioms xi,yi = initial location width,height = dimensions of world heading = str representation of the initial agent heading """ axioms = [axiom_generator_initial_location_assertions...
fb94f7e562518be272a3971018b4597d66ad253e
3,613,383
def feed(): """Live Video Feed """ global accessGranted print "/feed Requested" print accessGranted if accessGranted: return render_template('index.html') else: return redirect(url_for('login'))
04f12a55cc5904999cdc199ecab00800728583cb
3,613,384
def frametimes_from_file(infile): """infile is a frametimes file each row has [frame number, start dur, stop] in seconds Returns ------- ft: array [start, duration, stop] in seconds for each frame """ ft = np.loadtxt(infile, delimiter = ',', usecols = (1,2,3), skiprows =...
8a23d1612dc876c10aef6c19d45307ff98ff9e72
3,613,386
def _get_wordpiece_detokenized_text( token_span: _SpanType, raw_prediction: _RawPredictionType, tokenizer: tokenization.FullTokenizer) -> str: """Gets the normalized answer token text given the token span.""" answer_tokens = tokenizer.convert_ids_to_tokens( raw_prediction["long_token_ids"][token_span[...
ad807a5827df46193260953905596152bb59c5f8
3,613,387
def select_sentiment_by_date(search_string, search_date): """ Query column(s) from `search_string` in the tweets table where date LIKE `search_date` :param search_string: column name(s) to Query :param search_date: date to search :return: Query results from search_string and search_date """ ...
efa7877ebc1707a6ca4e70c005d61e80399b6ddf
3,613,388
import pandas as pd def noaaDateConv(dataframe): """ This function takes a dataframe with datetime values and converts it into a format that the NOAA ccg tool can easily read :param dataframe: A dataframe that has to have a column labeled 'datetime' which contains dt.datetime formatted items ...
2556009e803ce1406ed5845636ff7cad4d5c1d21
3,613,389
def sms_rest(msg): """ :param msg: <str> :return: <int> return the difference between length of message and capacity of sms """ if sms_is_limited(msg): return 70 - len(msg) return 160 - len(msg)
c9dfca6d5770ff3e20832b0221f664ef8ab8ec2b
3,613,390
import numpy def mel_filter_bank(fs, nfft, lowfreq, maxfreq, widest_nlogfilt, widest_lowfreq, widest_maxfreq,): """Compute triangular filterbank for cepstral coefficient computation. :param fs: sampling frequency of the original signal. :param nfft: number of points for the Fourier Transform :param l...
4aae716001b281e1008cb9d98e1a6d6a7f7fe491
3,613,391
def mod3(): """ Create a simple model for multiple incorporation tests """ class mod3(mod1, mod1b, Model): def __init__(self, name, description): super().__init__(name, "Model 3") self.a = self.createVariable("a",dimless,"a") self.b = self.createVariable(...
4897a039075743dade45676e3f76cc5b671d6e1b
3,613,392
def is_convex_polygon(polygon): # noqa """Return True if the polynomial defined by the sequence of 2D points is 'strictly convex': points are valid, side lengths non- zero, interior angles are strictly between zero and a straight angle, and the polygon does not intersect itself. See: https://stack...
bd5ff1efc10e2455c3c65279869c34aff5c17373
3,613,393
def make_paragraph(text): """ An example function that takes in text and returns a paragraph from it that can be used in the Knuth-Plass Algorithm. """ # Turn chunk of text into a paragraph L = [] for ch in text: if ch in ' \n': # Add the space between words ...
e702db1698abcda587d8d4cf7c0b298b005355c3
3,613,394
def even_time_series_spacing(dfi, n, t0=None, t_n=None): """Interpolate irregularly spaced time series. To obtain regularly spaced data. Parameters ---------- dfi : pandas dataframe dataframe with one dimensional index containing time stamps as index values. n : int n...
98c3ecda0a82e989de80b7c27fd73f952b851401
3,613,395
import zipfile def loader(path_zip, file_img): """ Load imagefile from zip. """ with zipfile.ZipFile(path_zip, 'r') as myzip: img = Image.open(myzip.open(file_img)) return img.convert('RGB')
22606417819087100120be2cae0f549c5b405056
3,613,396
def get_triplets_at_q(grid_point, bz_grid, reciprocal_rotations=None, is_time_reversal=True, swappable=True): """Parameters ---------- grid_point : int A grid point in the grid type chosen by is_dense_gp_map. ...
a6e2142c8bb972bf4011fd36de7f8f34559f462a
3,613,397
def search_text_to_suggestion(search_text: SearchText, term: OntologyTerm) -> ConditionMatchingSuggestion: """ Does this term match the search_text, if so, add it as a suggestion (possibly with some validation) """ cms = ConditionMatchingSuggestion() if match_info := search_text.matches(term): ...
8113134ce1b1c46a375bf38ab213c0693cbeb2e6
3,613,398
import json def get_section_with_options(section_name): """ Takes section name(str) and returns section with option=value keys as json """ section_dict = {} option_value = {} for option, value in SAMBA_CONFIG_PARSER.items(section_name): option_value[option] = value section_dict[s...
52a8ab8437cfd4925a11e4472f999a433b5865bd
3,613,399
def get_bios_reader(model_name: str): """ Constructs and returns a Biosbias Reader based on the model name. """ if model_name == "BERT": bert_indexer = PretrainedTransformerIndexer('bert-base-uncased') tokenizer = PretrainedTransformerTokenizer('bert-base-uncased') reader = TextC...
098764998fd2123bbbd55e4cdfadd1ddf7e3b0ab
3,613,400
import json def mocked_json_dumps(monkeypatch): """Monkeypatch json.dumps.""" mock_dumps = mock.MagicMock() monkeypatch.setattr(json, "dumps", mock_dumps) return mock_dumps
f49ecf285976d76416fff7b8f045807575de6425
3,613,401
def locale_factory(factory): """ Decorator which defines a factory function which set forms locale. If not defined locale 'en_US' is used :param factory: function :return: str with locale """ global _get_locale _get_locale = factory return factory
10c306a54ddfd7215c3fa12b0ceacb4e8f177e0e
3,613,402
import io def get_mne_sample(n_trials=10): """Return sample data from the mne dataset. ``` In this experiment, checkerboard patterns were presented to the subject into the left and right visual field, interspersed by tones to the left or right ear. The interval between the stimuli was 750 ms. ...
a546c550bd0b884be7ea864e140453ca3bbc2bac
3,613,403
def sample_affine_transform(batchsize, n_dims, rotation_bounds=False, scaling_bounds=False, shearing_bounds=False, translation_bounds=False, enable_90_r...
fc9083498d52bc6e300defbe698278515af0c7f6
3,613,404
def get_square_lattice(height: int) -> RectangularLattice: """Returns a lattice of all points in a square of the given height. Args: height (int): Height of the lattice. Returns: The lattice. """ return get_rectangle_lattice(height, height)
1a977fe97194c777104a1e4befc53e27a381a5bd
3,613,405
def fpn_search(fpn_arch, in_channels): """Fpn search warpper.""" return FPN_Search(in_channels=in_channels, out_channels=64, num_outs=4, fpn_arch_str=fpn_arch)
1be6e45c2a6108b26ddfec7ce998cdbbf1cfefd9
3,613,406
from typing import Optional from typing import Dict from typing import Iterable from typing import Any from typing import List def get_fixture_dicts( domain: str, data_type_id: str, filter_in: Optional[Dict[str, Optional[Iterable]]] = None, filter_out: Optional[Dict[str, Any]] = None, ) -> List[Dict]:...
92ade8b539db93f7e85e4b7e0a1542b9ceaf19ab
3,613,407
def speedup(i): """ Input: { samples1 - list of original empirical results samples2 - list of new empirical results (lower than original is better) (key1) - prefix for min/max/mean in return dict (key2) - prefix for min/max/mean in return dict ...
053a6d0831f8d11f34fa29e5117ea7c66e5f4bad
3,613,408
from typing import Dict from typing import Any def deserialize_trade(data: Dict[str, Any]) -> Trade: """ Takes a dict trade representation of our common trade format and serializes it into the Trade object May raise: - UnknownAsset: If the fee_currency string is not a known asset - De...
e436066d70c348368bdddc811be0d4e6d7c903da
3,613,409
import json def load_data(file=json_file): """Loads json file :param file: Path object to load data from :return: JSON data """ if not file.is_file(): soup = get_soup() enchantment_data = generate_enchantments(soup) minecraft_items = generate_items(enchantment_data) ...
618f24388c7e79f78ca6f03880990f3f489ffbb0
3,613,411
def tag_to_entity(tag_seq, label_alphabet): """ Collect predicted tags(e.g. BIO) in order to get entities including nested ones """ entities = [] for idj, tag in enumerate(tag_seq): try: tag = label_alphabet.get_instance(tag) if tag.split('-', 1)[0] == 'B' or tag...
8759a9e2e5be5aab0267909ebab82cffdb16b896
3,613,412
def calc_d(D_o, t, inner=False): """Return the outer or inner diameter [m]. :param float D_o: Outer diameter [m] :param float t: Layer thickness [m] :param boolean inner: Select diameter """ if inner: return D_o - 2 * t else: return D_o + 2 * t
eaadfed210c0b06b7fd0bbc500fe093461d9766c
3,613,413
def tobs(): """Temperature observations from the last year""" results = session.query(Stations.name, Measurements.date, Measurements.tobs).\ join(Measurements, Stations.station == Measurements.station).\ filter(Measurements.date> first_date()[0]).\ ...
c3912633e58303d955c9599a350d52d2f9a94c52
3,613,414
from typing import Any def get_fake_prune_images() -> tuple[int, dict[str, Any]]: """Get fake prune images response""" status_code = 200 response = { "ImagesDeleted": [FAKE_LONG_ID], "SpaceReclaimed": 123 } return status_code, response
1031fb6bea58c696471da7cd452ff5f12fb14d53
3,613,415
def get_function_path(f): """ Passes the internal func_code to a attribute called internal_code on the wrapper. Then we call the wrapper attribute which throws metadata of the internal function, and gets the path. :param f: function :return: path """ # does the wrapper is defining the new at...
ae88ffe5e452dc7d2ae001786ba4b58fea072528
3,613,416
def get_all_completed_labels(engine, label_task_id, dataset_id=None, label_status="admin_complete"): """ Get latest label history entries for all completed (approved) labels :param engine: :param label_task_id: :param dataset_id: optionally specify a dataset ID to only return labels for this datase...
16fe3d4b59a5fb2fc438c8f1b625de3a45be7b4b
3,613,417
def rnn_stack(params=None, tier : int = None, last_tier = False, dropout = 0, recurrent_dropout = 0, ): """MultiRnn cell. Options Args: params = params class with cell args tier = int designating the tier number ...
4bd416d8dca8b73c1961d6d48efa8e17f943b76d
3,613,418
from typing import Dict from typing import Any import requests def signed_api_call(service: str, path: str = "/", method: str = 'GET', configuration: Configuration = None, secrets: Secrets = None, params: Dict[str, Any] = None) -> requests.Response: """ ...
f75597dc9f259004af36c8c68511fa2167fce2e0
3,613,419
def check_and_get_org_by_repo(repo_id, user): """ Check whether repo is org repo, get org info if it is, and set base template. """ org_id = get_org_id_by_repo_id(repo_id) if org_id > 0: # this repo is org repo, get org info org = get_org_by_id(org_id) org._dict['is_staff...
1c6270a8dd0bd13da21b0317bc8ce1ce4fbccc79
3,613,420
def upload_large(file, **options): """ Upload large files. """ upload_id = utils.random_public_id() with open(file, 'rb') as file_io: upload = None current_loc = 0 chunk_size = options.get("chunk_size", 20000000) file_size = getsize(file) chunk = file_io.read(chunk_si...
e23e853fd3ac1309f26e7a6ae30f83aba4350066
3,613,421
import logging def kappa(y_true, y_pred, weights=None, allow_off_by_one=False): """ Calculates the kappa inter-rater agreement between two the gold standard and the predicted ratings. Potential values range from -1 (representing complete disagreement) to 1 (representing complete agreement). A kappa ...
ec3d76c221e7e485ef6e0af91db752cdc08eac65
3,613,422
from typing import Collection def get_post(id): """获取文章 """ post = Post.query.get_or_404(id) post.reading_num += 1 models.add_or_update(post) root_comment_list = db.session.query(Comment).filter_by( post_id=post.post_id, root_comment_id=-1).all() comment = { i: db.session.q...
7b623969c1bd4699707025bac17be987e5a7a70c
3,613,423
def sample_noise_using_sigma(log_sigma_sample, n_obs): """Produces a sample of residual noises based on sigma values. Args: log_sigma_sample: (tf.Tensor) Samples of log sigmas, shape (n_sample, ) n_obs: (int) Number of observation to sample for each sigma value. Returns: (tf.Tensor...
76972f056ef05916c7ecff757f40ba0a62e342e0
3,613,424
def rjd_to_jdn(rjd: int) -> int: """Return Julian day number (JDN) from Reduced Julian Day (RJD) number. :param rjd: Reduced Julian Day (RJD) number. :type rjd: int """ return rjd + 2400000
cfb26706b16f6421449353c97960e417f77a4647
3,613,425
def clip_pad_images(tensor, pad_shape, pad=0): """ Clip clip_pad_images of the pad area. :param tensor: [c, H, W] :param pad_shape: [h, w] :return: [c, h, w] """ if not isinstance(tensor, paddle.Tensor): tensor = paddle.to_tensor(tensor) H, W = tensor.shape[1:] h = pad_shape[...
638befe5a41329f57cd9f8ef612c9303838d158b
3,613,426
def make_tree_parallel_nj(distance_matrix: np.ndarray, names: np.ndarray) -> Tree: """ Nj tree is made from random sampling with replacement from the distance matrix. :param distance_matrix: :param names :return: """ np.random.seed(randint(0, 1000000)) selected_ids = np.random.choice(np....
2586726eb0a254d892099ca25a15ceb3141646a1
3,613,427
def get_doc_for_user(trunk_id, user): """Retrieves document based on user's visit history. If the user has visited a particular revision (document of a trunk), user will see that document, else user will be directed to the latest revision. We pass user instead of using users.get_current_user, so that this f...
dee5140df1e8d965b62b903012aad28502827682
3,613,428
def resolve_match_norm_seq_alleles(data, maf_data): """ Resolves matched normal seq alleles. """ norm_allele1 = "" for col in MATCHED_NORMAL_SEQ_ALLELE1_COLUMNS: if col in data.keys(): norm_allele1 = process_datum(data.get(col,"")) break norm_allele2 = "" for col in ...
25a2a7cbd18f72f910c5750128ec33b328a4fe69
3,613,429
def __lt__(self, other): """Computes the rich comparison LOWER THAN between two images. Parameters ---------- self : ee.Image Left operand. other : ee.Image | numeric | list[numeric] Right operand. If numeric, an ee.Image is created from its value. If list, an ee.Image with ...
aa596d0017ed41e727e2a46c5931d9efe4d4d5f1
3,613,430
def _missing_synset(lex: lmf.Lexicon, ids: _Ids) -> _Result: """synset of sense is missing""" synset_ids = ids['synset'] return {s['id']: {'synset': s['synset']} for e in _entries(lex) for s in _senses(e) if s['synset'] not in synset_ids}
2629b50780c04c49ec5fcecdad77a84ff71cadc2
3,613,432
def create_component_analysis_timing_graph(durations, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, dpi=DPI): """Create graph with component analysis timings.""" N = len(durations) component_selectors = ["security_issues", "source_licenses", ...
c8fdffe67f8c379666b9aec54918de6030b6fff5
3,613,433
def ask_for_path(): """asks for the path to the GPS-device and returns it if no path is specified: returns the standard PATH""" print("\nGib den Pfad zum GPS-Geraet ein (NICHT zum Unterordner 'GPX').") print("Falls Standardpfad uebernommen werden soll: keine Eingabe") inp = input(">> ") if inp ...
1bb66e2faf21993f36a44a7a8caa158cd6514745
3,613,434
def add_til2(*args): """add_til2(char name, int flags) -> int""" return _idaapi.add_til2(*args)
0d2a43b723c71637d16d732dbca8bc3a55c32cf3
3,613,435
def meta_sync_register(model, fields=None, exclude=()): """ 注册ORM模型(model)为需要进行元数据同步的类 Args: model 需要进行数据同步的model,必须继承至django.db.models.Model fields 需要进行数据同步的字段 exclude 不需要进行数据同步的字段 Examples: class DemoModel(models.Model): param1 = models.CharField(max_lengt...
fbd8d9ee1e31783932d5c2f401da21339f09bc8d
3,613,436
def is_neq_prefix(text_1, text_2): """Return True if text_1 is a non-equal prefix of text_2""" return text_1 != text_2 and text_2.startswith(text_1)
f9e7f835ec577dc539cd586da5e6f9e2e0903a74
3,613,437
def find_common_cond_attrs(sql_obj1, sql_obj2): """ Find common attributes for SQL join condition :param sql_obj1: :param sql_obj2: :return: """ commonpr_list = [] for project1 in sql_obj1.pr_list: for project2 in sql_obj2.pr_list: if project1.alias == project2.alias...
20db9c2f7d8ad1479e94411f7384fcc52a6b90f4
3,613,438
import json def read_config(fn, perm="r"): """ Read config file which consists parameters used in program. :param str fn: Name of config file (config.json) :param str perm: Mode in which the file is opened :return: Config file paramteres """ with open(fn, perm) as file: config = ...
f77a1dbb9b1e0f9f43dbef745f550485f1003cf7
3,613,439
import optparse def getParse(): """Desc: get Options parse.""" usage='''\ Desc: This is dataprocessing Tool FOR Beverly. # python datapro.py --dir ./dir/data''' parser = optparse.OptionParser(usage=usage) parser.add_option("-d","--dir",dest="dataDir",help="This is the data dir path") pars...
0f4c085c857c238f03505abaead76b0c21268fda
3,613,440
import re def get_version_from_git_describe(): """Determine a version by incrementing the git version in the context of master. This calls `git describe`, if git is available. Returns: version from `git describe --tags --always --dirty` if git is available; otherwise, None """ bran...
0739a6e00ea2f978fb42e206e662fcfcec95f67b
3,613,442
from typing import Tuple def check_invalid_indentation(path: str) -> Tuple[int, str, str, IndentationErrorType]: """ Check if the file contains any indentation errors. :param path: Path to file :return: Tuple[line number: int, error line: str, previous start of ...
5ca3f6ee26f9c6b616f274c0e1ac454143ab35fc
3,613,443
import functools def timed_info(func): """Decorator to measure and logger.info a function's execution time.""" @functools.wraps(func) def timed_(*args, **kwargs): return _timed(func, logger.info, *args, **kwargs) return timed_
5282c8df0ee9f983373063898a30e27a908f15c4
3,613,445
def get_label_base(label_path): """ Gets directory independent label path """ return '/'.join(label_path.split('/')[-2:])
16748bdb197249f157a288e2c664374ad432e6c7
3,613,446
def computeTriadCounts(G, signs): """ :param - G: graph :param - signs: Dictionary of signs (key = node pair (a,b), value = sign) return type: List, each position representing count of t0, t1, t2, and t3, respectively. return: Return the counts for t0, t1, t2, and t3 triad types. Count each triad only once...
e8c4bee1516531ed36f7ea5dd6ebaf9d8414b9a3
3,613,447
def properties_var(): """ Stream properties: 1. n_chunks 2. chunk_size """ return (200, 250)
b5f5619ed1f44fe3c18e865f1374eed26042643d
3,613,448
def cli_command(fn): """Register function as subcommand.""" command = SUBPARSERS.add_parser(fn.__name__, description=fn.__doc__) command.set_defaults(func=fn) unspecified = object() args = reversed(list(zip_longest( reversed(fn.__code__.co_varnames[:fn.__code__.co_argcount]), revers...
d75063f6a1850cb339c88b25cdc451760f4a8358
3,613,450
import random def mutate(file, factor): """Mutate $factor% of bytes in the $file""" file = bytearray(file) mutations = len(file) * factor if mutations is 0 and factor is not 0: mutations = 1 while mutations > 0: random_byte = random.randint(0,255) random_position = random.randint(0, len(file)-1) file[r...
663013b46c71858260d055080fd20f5e0cf495eb
3,613,451
def forward_fill_series(s1, s2): """ For two pandas series with DateTimeIndex , return corresponding series with the same numer of entries, forward-filled. :type s1: pd.Series :type s2: pd.Series """ def dedup_index(s): """ Deduplicate index values of pd.Series""" df = s.to...
e918c94ed81b79ffd038c059b4c263d024da4bb0
3,613,452
import uuid def uuid_uri(prefix): """Construct a URI using a UUID""" return prefix + str(uuid.uuid1())
2361583122396296d40ff5b1c284662a918fc871
3,613,453
from typing import Any def is_raw_json_null(py_obj: Any) -> bool: """ Checks if the given Python object is a raw JSON null. :param py_obj: The Python object to check. :return: True if the Python object is a raw JSON null, False if not. """ # Must be None return...
1d206ed8242caeb806a646aa617a3bf6707fd5d8
3,613,454
async def async_setup_entry(hass, config, async_add_entities): """Create wallbox sensor entities in HASS.""" wallbox = hass.data[DOMAIN][CONF_CONNECTIONS][config.entry_id] station = config.data[CONF_STATION] async def async_update_data(): try: return await hass.async_add_executor_...
92e7cbfd7c638bbe76224fc7d4f569c138a6b7ca
3,613,455
from datetime import datetime def various_indexes(request): """Parametrized cached index of various types with source.""" source = mangasource.MangaSource( 'test source', 'http://www.source.com/', '_', index_tag=request.param['tag'], index_attrs=request.param['attr'] ) now = datet...
3b37ae2ceae04008ef2c6eba18edebd4c0e53450
3,613,456
import re def underscore_2_space(string: str): """ Return string with underscores replaced by spaces. """ return re.sub('[_]', ' ', string)
a4ef9b19cda662ec4714cab58e1f502f668b6aaa
3,613,457
import six def jid_to_time(jid): """ Convert a salt job id into the time when the job was invoked """ jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != "_"): return "" year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = ji...
1b32020476cc60ade1baac6a14054bde005bb8b9
3,613,458
def iotc_connect_by_uid_parallel( tutk_platform_lib: CDLL, p2p_id: str, session_id: c_int ) -> c_int: """Used by a client to connect a device and bind to a specified session ID. This function is for a client to connect a device by specifying the UID of that device, and bind to a tutk_platform_free sess...
cea50ae94370fe0930e8ad23f8fc9e9810f0cfbd
3,613,459
from typing import Iterator from typing import Callable from typing import Optional import multiprocessing import importlib def import_entry_point() -> Iterator[Callable[[str], Optional[int]]]: """ Yields a function that imports a module in a seperate Python process and returns the exit code. """ cont...
07b5cb8620cee039351cc894707eb8fe3c457daf
3,613,460
import numpy def sort_radius_front_to_back( render_position, render_direction, objects, object_positions ): """Sorts objects from front to back based on their distance from the camera. :param numpy.array render_position: The position of the camera the scene is being rendered f...
58bc47bc729c695c005a26b7df7d67f3d2791c51
3,613,461
def preprocess_inputs(batched_data, max_sub_l, max_vcpt_l, max_vid_l, device="cuda:0"): """clip and move to target device""" max_len_dict = {"sub": max_sub_l, "vcpt": max_vcpt_l, "vid": max_vid_l} text_keys = ["q", "a0", "a1", "a2", "a3", "a4", "sub", "vcpt"] label_key = "answer_idx" qid_key = "qid"...
a453e68f6b799ef3215befeacf8d93704ecc3fcc
3,613,462
def make_diff_prop_modified(pname, pval1, pval2): """Return a property diff for modification of property PNAME, old value PVAL1, new value PVAL2. PVAL is a single string with no embedded newlines. Return the result as a list of newline-terminated strings.""" return [ "Modified: " + pname + "\n", ...
b4201b178a1438075bc84048057f100d337abe99
3,613,463
import scipy def mean_confidence_interval(data, confidence=0.95): """ Calculates 95% confidence intervals (CI). Taken from: https://stackoverflow.com/questions/15033511/compute-a-confidence-interval-from-sample-data : data (pd.DataFrame): : confidence (float): """ a = 1.0 * ...
60ca47d15287cd88cf1599c9987ddca6bf35778e
3,613,464
import torch from typing import Optional from typing import Union from typing import Tuple def wmean( x: torch.Tensor, weight: Optional[torch.Tensor] = None, dim: Union[int, Tuple[int]] = -2, keepdim: bool = True, eps: float = 1e-9, ) -> torch.Tensor: """ Finds the mean of the input tensor...
db742eb5d899b190609a8e40cd9e4a65f52a45cd
3,613,465
def GetDeleteSQLByName(name): """获取 Delete 配置 SQL 语句""" PS = __ParserSQL__() return PS.GetDeleteSQLByName(name)
ffc0c999b7a0aa595e53008d3688abe6ccdd6c8f
3,613,466
def authorized_access(response): """Check if access is authorized""" return check_uuid(response.headers.get("Bearer"))
1f636ca56b0215fcba1be77c3f308a4db06f3fce
3,613,468