content
stringlengths
22
815k
id
int64
0
4.91M
def test_dead(): """Test control of dead jobs""" jobs = bg.BackgroundJobManager() j = jobs.new(crasher) j.join() nt.assert_equal(len(jobs.completed), 0) nt.assert_equal(len(jobs.dead), 1) jobs.flush() nt.assert_equal(len(jobs.dead), 0)
5,288,600
def check_still_complete( segments_in: Tuple["BaseSegment", ...], matched_segments: Tuple["BaseSegment", ...], unmatched_segments: Tuple["BaseSegment", ...], ) -> bool: """Check that the segments in are the same as the segments out.""" initial_str = join_segments_raw(segments_in) current_str = j...
5,288,601
def display_samurai(vals): """ prints the squares in order of: top left, top right, bottom left, bottom right, middle. Note that the middle square overlaps with the other 4 and will contain duplicate values """ if not vals: print("Solution not found, please check if test is valid....
5,288,602
def reinforce_loss(disc_logits, gen_logprobs, gamma, decay): """The REINFORCE loss. Args: disc_logits: float tensor, shape [batch_size, sequence_length]. gen_logprobs: float32 tensor, shape [batch_size, sequence_length] gamma: a float, discount factor for cumulative reward. decay: a float, ...
5,288,603
def generate_configuration_files(family, database): """Generate copy configuration files. """ simba_root = os.environ["SIMBA_ROOT"] family_dir = os.path.join(simba_root, "make", "arduino", family) configuration_fil...
5,288,604
def test_mnemonic_colors(all_terms): """Make sure color shortcuts work.""" @as_subprocess def child(kind): def color(t, num): return t.number_of_colors and unicode_parm('setaf', num) or '' def on_color(t, num): return t.number_of_colors and unicode_parm('setab', num)...
5,288,605
def static(path): """Jinja2 filter version of staticfiles. Hopefully.""" return staticfiles_storage.url(path)
5,288,606
def custom_after_log(resource_name, logger, log_level): """After call strategy that logs to some logger the finished attempt.""" def log_it(retry_state): log_message = f"Finished call to `{resource_name}` after " \ f"{retry_state.seconds_since_start:0.3f}(s), this was " \ ...
5,288,607
def _testThresholdPen(): """ >>> from fontPens.printPointPen import PrintPointPen >>> from random import seed >>> seed(100) >>> glyph = _makeTestGlyph() >>> pen = ThresholdPointPen(PrintPointPen()) >>> glyph.drawPoints(pen) pen.beginPath() pen.addPoint((100, 100), segmentType='line')...
5,288,608
def stage_symlink(meta, params): """ Stage a directory or file by symlinking. """ ln_path = which('ln') item = params['file'] src_dir = item[0] % meta if len(item) == 1: dst_dir = src_dir else: dst_dir = item[1] % meta if os.path.lexists(dst_dir): actual_path = os...
5,288,609
def sample_image(n_row, batches_done): """Saves a grid of generated digits ranging from 0 to n_classes""" # if folder doen't exist os.makedirs(opt.output_static_dir, exist_ok=True) os.makedirs(opt.output_v1_dir, exist_ok=True) os.makedirs(opt.output_v2_dir, exist_ok=True) os.makedirs(opt.output...
5,288,610
def SubmitIntermoduleRequest(module, path, data=None, deadline=None): """Helper method for making calls from one GAE module to another. Args: module: GAE module name, as found in the corresponding .yaml file. path: The path portion of the intermodule URL. data: Optional data dictionary to be submitted...
5,288,611
def processed_file(suffix, directory='process', magnification='10X', temp_tags=tuple()): """Format output file pattern, for example: processed_file('aligned.tif') => 'process/10X_{well}_Tile-{tile}.aligned.tif' """ file_pattern = f'{directory}/{magnification}_{{well}}_Tile-{{tile}}.{suffix}' if suff...
5,288,612
def cherrypick( src: Mapping[Any, Any], dst: MutableMapping[Any, Any], fields: Optional[Iterable[FieldSpec]], picker: Optional[Callable[[_T], _T]] = None, ) -> None: """ Copy all specified fields between dicts (from src to dst). """ picker = picker if picker is not None e...
5,288,613
def issue_shell_command(cmd: str, my_env=None): """ Issues a command in a shell and returns the result as str. Parameters: cmd - command to be issued (str) In python3.x, stdout,stderr are both b'' (byte string literal: bytes object) and must be decoded to UTF-8 for string concatenation etc...
5,288,614
def load_CIFAR10(ROOT): """ load all of cifar """ np_names = ['np_train_data', 'np_train_labels', 'np_test_data', 'np_test_labels'] print(all([os.path.isfile(os.path.join(ROOT, name)) for name in np_names])) if all([os.path.isfile(os.path.join(ROOT, name)) for name in np_names]): print("Np files...
5,288,615
def get_summit_config_path(config_dir_name=".summit"): """Returns the path to the summit config directory""" home = pathlib.Path.home() return home / config_dir_name
5,288,616
def merge_coco_results(existing_coco_results, new_coco_results, image_id_offset): """ Merges the two given coco result dicts into one. :param existing_coco_results: A dict describing the first coco results. :param new_coco_results: A dict describing the second coco results. :return: A dict containing t...
5,288,617
def process_regex(regex): """ This function parse a regex string into a dictionary of fields and regexes Format: <field1> -> <regex1> <field2 -> <regex2> etc.""" res_dict = {} lines = regex.split("\n") for l in lines: tok = l.split("->") if len(tok) != 2: ...
5,288,618
def sum_xalpha_j(samples, alpha): """Get F(x1,x2,..)= (1*x1**alpha+2*x2**alpha+...) = sum j x_j^alpha Args: samples (array_like): [N_samples, N_x] array of samples alpha (float): power of x Returns: feature (array_like): [N_samples, 1] feature grad_feature (array_like): [...
5,288,619
def apache_apachecfg_secure_list( pdaf_scale_factor: int, pytestconfig: "_pytest.config.Config", tmp_path_factory: TempPathFactory, ) -> Generator[List[Path], None, None]: """Provides the location of the apache configuration file for the secure apache service.""" yield from _apache_apachecfg_secure(...
5,288,620
def krfp(smi): """Calculate Klekota-Roth fingerprint using padelpy.""" # Warning: as this function uses padel it requires descriptors.xml to be # in the running directory and have KlekotaRothFingerprinter set to true # we don't want to copy and remove the descriptors.xml file for each smiles # sepa...
5,288,621
def rgb2gray(img: T.Tensor): """ Converts a batch of RGB images to gray. :param img: a batch of RGB image tensors. :return: a batch of gray images. """ if len(img.shape) != 4: raise ValueError('Input images must have four dimensions, not %d' % len(img.shape)) retur...
5,288,622
def get_object_for_editing(request, uid, target_klass=None): """ Return the specified instance by uid for editing. If a target_klass is provided, uid will be checked for consistency. If the request has no logged-in user, a 401 Response will be returned. If the item is not found, a 404 Response will...
5,288,623
def before_request(): """Updates session with values coming from the query string if present. If credentials are invalid, set error flag, for error wrapper to redirect to settings page. """ update_session_for('editorial_features', coercion=lambda x: x == 'enabled') if is_changing_credentials()...
5,288,624
def update_account(trade_account, trade_info, trade_exchange, trade_date): """ Update the account and strategy Parameters ---------- trade_account : Account() trade_info : list of [Order(), float, float, float] (order, trade_val, trade_cost, trade_price), trade_info with out factor ...
5,288,625
def get_price_including_tax(soup): """ Analyze "soup" to extract price with tax. Args: soup -- bs4.BeautifulSoup from http request of book url. Return: price with tax """ table = soup.table cell = table.find_all("td") price_including_tax = cell[3].text return price_includ...
5,288,626
def test_particles_jf002_particles_jf002_v(mode, save_output, output_format): """ TEST :3.9.1 The Particle Schema Component [ check length of element information items ] : Particle Derivation OK (elt:Any) element R drived by restriction from wildcard (any) B : B's namespace=##any, R's targetNamespac...
5,288,627
def broadcast_to(x, shape): """ Performs the equivalent of :obj:`numpy.broadcast_to` for :obj:`COO`. Note that this function returns a new array instead of a view. Parameters ---------- shape : tuple[int] The shape to broadcast the data to. Returns ------- COO The b...
5,288,628
def get_julian_datetime(date): """ Convert a datetime object into julian float. Args: date: datetime-object of date in question Returns: float - Julian calculated datetime. Raises: TypeError : Incorrect parameter type ValueError: Date out of range of equation """ #...
5,288,629
def invoke(kind, topology=None, inputs=None, schemas=None, params=None): """ Invoke an SPL operator with an arbitrary number of input ports and arbitrary number of output ports. """ if topology is None: topology = inputs.topology # Add operator invocation op = topology.graph.addOp...
5,288,630
def is_dev_environment() -> bool: """Returns True if the project source code structure is found in the working directory""" return os.path.isdir("caos") and \ os.path.isdir("caos/_cli_commands") and \ os.path.isfile("caos/_cli.py") and \ os.path.isdir("docs") and\ ...
5,288,631
def get_weather_forecast(*args: tuple): """ Получение и озвучивание прогнза погоды :param args: город, по которому должен выполняться запос """ # в случае наличия дополнительного аргумента - запрос погоды происходит по нему, # иначе - используется город, заданный в настройках if args[0]: ...
5,288,632
def GetSQLite3Connection(database_file_path): """Returns a tuple of SQLite3's (connection, cursor) to database_file_path. If the connection has been created before, it is returned directly. If it's not, this function creates the connection, ensures that the foreign key constraint is enabled, and returns. Ar...
5,288,633
def create_table(dynamodb, table_name, partition_key, sort_key={}, rcu=15, wcu=5): """ Purpose: Create an DynamoDB Table by name Args: dynamodb (DynamoDB Resource Object): DynamoDB Object owning the Table table_name (String): Name of table to return partition_key (Dict): Dict...
5,288,634
def add_labels_to_pr(repo: GithubRepository, pull_id: int, *labels: str, override_token: str = None) -> None: """ References: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue """ url = ("https://api.github.com/re...
5,288,635
def sync(overwrite): """Download ESA catalogue.""" if not check_catalog() or overwrite: download_catalog() else: click.echo('Database already downloaded.')
5,288,636
def _equal(a, b, rtol, atol): """Returns True if a == b. a and b are both strings, floats or numpy arrays.""" # python 2/3 compatibility: convert raw bytes to string a = fix_string(a) b = fix_string(b) if isinstance(a, str): return a == b return np.allclose(a, b, rtol=rtol, atol=atol)
5,288,637
def test_fetch_embed(): """Test fetch_embed.""" texts = ["test 1", "测试1"] res = fetch_embed(texts, livepbar=False) assert np.array(res).shape == (2, 512) assert np.array(res).mean() > -0.1
5,288,638
async def on_message(message): """Sends a message to a user if they have a message in their inbox and nrm is not toggled. More details in cogs.message""" user = await client.pg_con.fetch("SELECT * FROM message WHERE id = $1", message.author.id) # member.id) if user and len(user[0]['msg']) > 0 and u...
5,288,639
def is_rm_textfile(filename): """Returns True if the given filename is a known remarkable-specific textfile.""" if filename.endswith('.json'): return True if filename.endswith('.content'): return True if filename.endswith('.pagedata'): return True if filename.endswith('.bookm...
5,288,640
def get_postcode_data_GCR(postal_code): """request data from geocoder.ca""" URL = "https://geocoder.ca" PARAMS = {'postal': postal_code, 'geoit': "XML"} resp = requests.get(url = URL, params = PARAMS) resp = resp.content.decode() root = ET.fromstring...
5,288,641
def old_run_convert_task(conv): """Exec the audio convert""" logger.warning('Convert audio file :> %s' % str(conv)) filename = conv.split(' ')[1].strip() if os.path.isfile(filename): logger.debug("File exists!") else: logger.error("Error: File don't exist!") # Option 1 : Popen...
5,288,642
def get_piis_for_date(query_str, year=None, loaded_after=None): """Search ScienceDirect through the API for articles and return PIIs. Parameters ---------- query_str : str The query string to search with. year : Optional[str] The year to constrain the search to. loaded_after : O...
5,288,643
def test_third_pct(performance_list, performances): """The third_pct property should return the percentage of third placed performances in the list""" assert performance_list.third_pct == performance_list.thirds / performance_list.starts
5,288,644
def postDailyStandUp(): """ Post in slack the daily standup for all users in a specific channel """ team_meet_up = services.datastore().retrive_daily_team_meetup() msg = prepare_standup_message(team_meet_up) slack.post_with_attachment(msg, config["channel"]) return "ok"
5,288,645
def download_to_file(url, token, target_file=None, cleanup=True): """Context manager for downloading a fixed file to a target_file.""" if target_file is None: filename = pathlib.Path(tempfile.mkstemp()[1]) else: filename = pathlib.Path(target_file) try: headers = {"Accept": "*/*"...
5,288,646
def get_sandbox(report=MAIN_REPORT): """ Retrieves the current sandbox instance attached to this report. Typically, this is used to retrieve the sandbox without running the students' code. Args: report (:py:class:`pedal.core.report.Report`): The report with the sandbox instance....
5,288,647
def sheva_na_after_long_vowel(last_vowel, prev, guess): """`sheva` after long vowel is `sheva-na` Source: [Simanim] 3.1.3 > `sheva` after a long vowel without an accent is a `sheva-na`. Source: [HaMillon] 2.16.3 > `sheva` after a long vowel is `sheva-na`. """ if ( guess.vowel == T....
5,288,648
def testGameMap(): """ ***TEST CASES*** """ # testing item adj/name collision testsword = Weapon("elvish sword", "A blade of Elvish make.", 2, weight=2) testsword2 = Weapon("rusty elvish sword", "A discarded old blade of Elvish steel.", 2) testsword3 = Weapon("sword elvish rusty", "A mix of adjectiv...
5,288,649
def verify_coeffs(method, past_image_keys): """ Parameters ---------- method past_image_keys Raises ------ AttributeError If a key does not exist. TypeError If a key is not callable. """ method_params = past_image_keys[method] cwd = os.getcwd() os.c...
5,288,650
def load_opcode_dict(): """ Opens and parses a special text file that contains a list of opcodes and their textual "nice names". :return: """ global opcode_to_name_dict global opcode_values_to_name_dict opcode_to_name_dict.clear() opcode_values_to_name_dict.clear() location = os.path...
5,288,651
def conv1x1BN(in_planes, out_planes, stride=1, groups=1, dilation=1, require_relu=False): """1x1 convolution with padding followed by batch-normalization""" if require_relu is True: return cm.ConvBNReLU(in_planes=in_planes, out_planes=out_planes, ...
5,288,652
def add_evil_node(in_fname, out_fname, kernel_fname, attack): """Add an evil node to the devicetree Args: in_fname (str): Filename of input devicetree out_fname (str): Filename to write modified devicetree to kernel_fname (str): Filename of kernel data to add to evil node attack...
5,288,653
def mutate(q): """ Perform a raw mutation. Args: q (str): The mutation to run Example: >>> import mage >>> mage.connect() >>> mage.mutate("createAssessment(input: {type: EXTERNAL, name: "test", assessmentClientId: "12345"}) {id}) """ from mage import endpoint ...
5,288,654
def __open_dataset(filename, client, worker, decode_times=True, **kwargs): """ read one input file. the type is automatically determined. Parameters ---------- filename : str path of the file client: dask.distributed.Client client object in distributed computation ...
5,288,655
async def get_recipe_summary( start=0, limit=9999, session: Session = Depends(generate_session), user: bool = Depends(is_logged_in) ): """ Returns key the recipe summary data for recipes in the database. You can perform slice operations to set the skip/end amounts for recipes. All recipes are sorted by ...
5,288,656
def delete_files(root, files, origin, target): """ Here we invert the origin and target on the file logic so we can reverse the sync and delete the extra files """ files_scanned = 0 files_unchanged = 0 files_updated = 0 files_deleted = 0 files_skipped = [] files_not_found = [] c...
5,288,657
def compose_tweet() -> str: """Generates the message that gets tweeted out. This function does not actually send the Tweet out; this function is separated from the function that sends the Tweet in order to assist with testing and development, in addition to addressing separation of concerns. Return...
5,288,658
def plot_sv(model, customed_model: bool, axes, x: np.ndarray = np.array([])): """ 在图中标注支持向量 Args: model (): SVM模型 customed_model (bool): 是否使用自定义核(拉普拉斯核) axes (matplotlib.axes._base._AxesBase): 要绘图的Axes实例 x (np.ndarray): 使用自定义核时的原始数据 Returns: None ...
5,288,659
def calc_grad_norms(model): """Computes a gradient clipping coefficient based on gradient norm.""" norms = [] for p in model.parameters(): if p.grad is None: continue modulenorm = p.grad.data.norm() norms += [modulenorm] return norms
5,288,660
def load_filtered_data(detector): """ Load a filtered dataset and the corresponding mask. :param detector: an instance of the class Detector :return: the data and the mask array """ root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename( initialdir=detector.datad...
5,288,661
def put_user(user_id): """update a user""" user = storage.get("User", user_id) if user is None: abort(404) if not request.get_json(): return make_response(jsonify({'error': 'Not a JSON'}), 400) for attr, val in request.get_json().items(): if attr not in ['id', 'email', 'creat...
5,288,662
def force_gd1(pot,ro,vo): """Return the force at GD-1""" # Just use R=12.5 kpc, Z= 6.675 kpc, phi=0 R1= 12.5 Z1= 6.675 p1= 0. return (potential.evaluateRforces(pot,R1/ro,Z1/ro,phi=p1, use_physical=True,ro=ro,vo=vo), potential.evaluatezforces(pot,...
5,288,663
def test_random_gun(mock_event: dict) -> None: """ Test to make sure the random gun chooses randomly :param mock_event: Mock AWS lambda event dict """ # Arrange mock_event["body"]["Player1"]["character_class"] = "creator" mock_event["body"]["Player1"]["action"] = "attack" mock_event...
5,288,664
def test_run_pyinfra_script_script_is_none(): """Test pyinfra_script""" assert mech.utils.run_pyinfra_script(host='foo', username='vagrant') is None
5,288,665
def count(self): """自定义一个count函数,替代Paginator内的count函数""" sql, params = self.object_list.query.sql_with_params() sql = sql % params cache_key = md5(sql.encode('utf-8')).hexdigest() # 先去redis内取 rows = cache.get(cache_key) # 如果取不到,再去数据库内查询 if not rows: rows = self.object_list.count(...
5,288,666
def wait_on_event(event, timeout=None): """ Waits on a single threading Event, with an optional timeout. This is here for compatibility reasons as python 2 can't reliably wait on an event without a timeout and python 3 doesn't define a ``maxint``. """ if timeout is not None: event.wait(...
5,288,667
def potentialAxi(R,pot,vc=1.,ro=1.): """ NAME: potentialAxi PURPOSE: return the potential INPUT: R - Galactocentric radius (/ro) pot - potential vc - circular velocity ro - reference radius OUTPUT: Phi(R) HISTORY: 2010-11-30 - Written - Bov...
5,288,668
def convert_hcc_hg(rsun, b0, l0, x, y, z=None): """Convert Heliocentric-Cartesian (HCC) to Heliographic coordinates (HG) (given in degrees).""" if z is None: z = np.sqrt(rsun**2 - x**2 - y**2) # z[z < 0] = np.NAN b0 = np.deg2rad(b0) l0 = np.deg2rad(l0) cosb = np.cos(b0) sinb = ...
5,288,669
def create_filter_dict(filter_type: str, filter_by: str, filter_value: List[Any], operator: str) -> Dict[str, Any]: """Creates a dictionary with the filter for the list-incidents request. :param filter_type: The filter type. :param filter_by: The field name to filter by. :param filter_value: The filter...
5,288,670
def readGeneratorState(lrms): """ Get the content of state file provided by lrmsObj """ state_dir = lrms.cfg.getConfigValue(config.SECTION_COMMON, config.STATEDIR, config.DEFAULT_STATEDIR) state_file = os.path.join(state_dir, lrms.getStateFile()) state_data = None if os.path.exi...
5,288,671
def save_vehicle_manifest(vin, signed_vehicle_manifest): """ Given a manifest of form uptane.formats.SIGNABLE_VEHICLE_VERSION_MANIFEST_SCHEMA, save it in an index by vin, and save the individual ecu attestations in an index by ecu serial. """ check_vin_registered(vin) # check arg format and registration ...
5,288,672
def test_include_trailing_comma() -> None: """Test for the include_trailing_comma option""" test_output_grid = isort.code( code=SHORT_IMPORT, multi_line_output=WrapModes.GRID, line_length=40, include_trailing_comma=True, ) assert test_output_grid == ( "from third_...
5,288,673
def simulate_qubit_pairs_3D_lattice(cbrt_n, m): """ Simulates a set of qubits in a 3D lattice grid of shape cbrt_n x cbrt_n x cbrt_n. Performs six seperate rounds when applying gates to ensure that the depth of the circuit is accurate Runs the simulation a total of m times and returns the mean a...
5,288,674
def _fofactory(tag, attribs): """ Factory to create each element with the fo: namespace. """ return ElementTree.Element(_foname(tag), attribs)
5,288,675
def calMultiRegression(bt,sf,of,leadingTime,ty1,ty2,py1,py2,predictors,fstType,pError,sError,oError,bError,countE): """ calculate multiple regression bt: best track data ty1: year1 ty2: year2 predictors: predictors fstType: fst variable type pError: prediction er...
5,288,676
def compute_Omegas(M_omega, lambdas, method='lbfgs', n_epoch=1000, lr=1.): """Compute Omegas directly from M_omega""" Ws = compute_Ws(M_omega, lambdas, method=method, n_epoch=n_epoch, lr=lr) Omegas = Omegas_from_Ws(Ws, M_omega, lambdas) return Omegas
5,288,677
def ensemble_transfer_matrix(NAtoms, kd, g1d, gprime, gm, Delta1, Deltap, Omega): """ NAtoms: The number of atoms kd: The product of the wavevector k of the input quantum field (and also approximately the wavevector of the classical drive) and the dis...
5,288,678
def cli(ctx, opt_input, opt_output, opt_minify, opt_force): """Migrate JSON detections to BBox.v2""" # ------------------------------------------------ # imports from os.path import join from pathlib import Path from dataclasses import asdict from tqdm import tqdm from vframe.utils import file_utils...
5,288,679
def graph_model(fgraph, *model_args, **model_kwargs): """Create a PyMC3 model from a Theano graph with `RandomVariable` nodes. """ model = pm.Model(*model_args, **model_kwargs) nodes = [n for n in fgraph.toposort() if isinstance(n.op, RandomVariable)] rv_replacements = {} for n...
5,288,680
def synthesis2(model, text, CONFIG, use_cuda, ap, speaker_embeddings=None, style_wav=None, truncated=False, enable_eos_bos_chars=False, #pylint: disable=unused-argument do_trim_silence=False, ...
5,288,681
def get_resource_name(prefix, project_name): """Get a name that can be used for GCE resources.""" # https://cloud.google.com/compute/docs/reference/latest/instanceGroupManagers max_name_length = 58 project_name = project_name.lower().replace('_', '-') name = prefix + '-' + project_name return name[:max_nam...
5,288,682
def imresize(img, size, return_scale=False, interpolation='bilinear'): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, a...
5,288,683
def do_test(template_str, context_dict=None, autoescape=True, lang_code="en-us"): """ Use django's templating engine to render a template against a context Arguments: :param template_str: The template to render :param context_dict: The context to render the template against ...
5,288,684
def get_punctuality_list_for_buses(buses_coordinates: pd.DataFrame, stops_coordinates: pd.DataFrame, api_key: str = None, path: Path = None, proximity: int = 10, ...
5,288,685
def pytest_collection(session: _pytest.main.Session): """ See :func:`_pytest.hookspec.pytest_collection_modifyitems` for documentation. Also see the "`Writing Plugins <https://docs.pytest.org/en/latest/writing_plugins.html>`_" guide. """ if is_nait_mode(): f = pytest.File(py.path.local(_...
5,288,686
def rpc_schema_exists(schema): """ test that an event-machine schema exists """ return eventstore(schema).storage.db.schema_exists()
5,288,687
def test_requirements_binder(): """ Test that requirements.txt is a subset of Binder requirements This test does not check requirements versions, it only verifies existence """ pip_requirements = get_parsed_requirements("requirements.txt") binder_requirements = get_parsed_requirements(".binder/r...
5,288,688
def test_int_128_passthrough(value): """ int 128-bit with passthrough """ result = ormsgpack.unpackb(ormsgpack.packb(value, option=ormsgpack.OPT_PASSTHROUGH_BIG_INT, default=lambda x: {"int": x.to_bytes(16, "little", signed=True)})) assert list(result.keys()) == ["int"] assert int.from_bytes(res...
5,288,689
def find_beat(v): """ find the beat of a vector format midi using the autocorrelation function """ # binary vector for testing autocorrelation v2 = [0 if x[0] == -1 else 1 for x in v] result = [] # no need to check more than 24*4 = 96 # i.e. 4 quarter notes of standard midi for lag i...
5,288,690
def dd_status(img_size: int) -> float: """ function to read the output file of dd and convert it to a percent completion :param img_size: size of the image :return: percent completion of dd """ config = configparser.ConfigParser() config.read(get_config()) con = config['configuratio...
5,288,691
def main(): """Main""" generate_analytics_columns(Converter.get_supported_types()) loop = asyncio.get_event_loop() loop.run_until_complete(run())
5,288,692
def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ return get_config_vars().get(name)
5,288,693
def _check_add_only_permission(ooi_data, filesystem_data): """ Checks that no existing data will be overwritten """ filesystem_data = {_to_lowercase(*feature) for feature in filesystem_data} ooi_data = {_to_lowercase(*data) for data in ooi_data} intersection = filesystem_data.intersection(ooi_...
5,288,694
def plot_contour(data_dir="./_output",out_dir='./',num_layers=2,num_frames=1000,ref_lines=[-130e3,-30e3],color=True): """Plot a contour plot of a shelf based simluation Note that to get a nice contour you may have to change the number of output times a solution is written out in `shelf.py` """ ...
5,288,695
def interpolate_line2d(xs, ys=None, interpol=3, window=3, verbose=3): """interpolate 2D vector. Description ----------- Smoothing a 2d vector can be challanging if the data is low sampled. This function contains two steps. First interpolation of the input line followed by a convolution. Parame...
5,288,696
def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. """ anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1 anchors = _ratio_enum(anchor, asp...
5,288,697
def matplotBandGaps(x1, y1, x2, y2, xlabel, ylabel, filename, title=None, addOLS = True, first=False): """ A function used to plot band gaps. ... Args ---------- x : list (dim:N) A list containing numeric values with np.nan as non-entries y : list (dim:N) A list containing nu...
5,288,698
def _front_operate( callback, work_pool, transmission_pool, utility_pool, termination_action, operation_id, name, payload, complete, timeout, subscription, trace_id): """Constructs objects necessary for front-side operation management. Args: callback: A callable that accepts packets.FrontToBackPack...
5,288,699