content
stringlengths
22
815k
id
int64
0
4.91M
def get_internal_plot_drive_to_use(): """ Same as above but returns the next drive. This is the drive we will use for internal plots. We do this to make sure we are not over saturating a single drive with multiple plot copies. When you run out of drives, these scripts will fail. """ ...
5,332,400
def store_build_time(tsuite, res, host, build_time): """Handle storing the build time for processing. Args: tsuite: runtime tsuite instance res: resource listing type host: host of the process build_time: time in seconds required to create""" if res not in tsuite.test_report: tsuite.test_rep...
5,332,401
def _build_discretize_fn(value_type, stochastic, beta): """Builds a `tff.tf_computation` for discretization.""" @computations.tf_computation(value_type, tf.float32, tf.float32) def discretize_fn(value, scale_factor, prior_norm_bound): return _discretize_struct(value, scale_factor, stochastic, beta, ...
5,332,402
def expand_mapping_target(namespaces, val): """Expand a mapping target, expressed as a comma-separated list of CURIE-like strings potentially prefixed with ^ to express inverse properties, into a list of (uri, inverse) tuples, where uri is a URIRef and inverse is a boolean.""" vals = [v.strip() for...
5,332,403
def home(request): """Handle the default request, for when no endpoint is specified.""" return Response('This is Michael\'s REST API!')
5,332,404
def create_message(sender, to, subject, message_text, is_html=False): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: ...
5,332,405
def get_agent(runmode, name): # noqa: E501 """get_agent # noqa: E501 :param runmode: :type runmode: str :param name: :type name: str :rtype: None """ return 'do some magic!'
5,332,406
def find_splits(array1: list, array2: list) -> list: """Find the split points of the given array of events""" keys = set() for event in array1: keys.add(event["temporalRange"][0]) keys.add(event["temporalRange"][1]) for event in array2: keys.add(event["temporalRange"][0]) ...
5,332,407
def to_subtask_dict(subtask): """ :rtype: ``dict`` """ result = { 'id': subtask.id, 'key': subtask.key, 'summary': subtask.fields.summary } return result
5,332,408
def _partition_labeled_span( contents: Text, labeled_span: substitution.LabeledSpan ) -> Tuple[substitution.LabeledSpan, Optional[substitution.LabeledSpan], Optional[substitution.LabeledSpan]]: """Splits a labeled span into first line, intermediate, last line.""" start, end = labeled_span.span fir...
5,332,409
def is_active(relation_id: RelationID) -> bool: """Retrieve an activation record from a relation ID.""" # query to DB try: sups = db.session.query(RelationDB) \ .filter(RelationDB.supercedes_or_suppresses == int(relation_id)) \ .first() except Exception as e: rais...
5,332,410
def vectorize_with_similarities(text, vocab_tokens, vocab_token_to_index, vocab_matrix): """ Generate a vector representation of a text string based on a word similarity matrix. The resulting vector has n positions, where n is the number of words or tokens in the full vocabulary. The value at each position indicate...
5,332,411
def get_puppet_node_cert_from_server(node_name): """ Init environment to connect to Puppet Master and retrieve the certificate for that node in the server (if exists) :param node_name: Name of target node :return: Certificate for that node in Puppet Master or None if this information has not been found ...
5,332,412
def get_notebook_workspace(account_name: Optional[str] = None, notebook_workspace_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNotebookWorkspaceResult: ...
5,332,413
def get_current_player(player_one_turn: bool) -> str: """Return 'player one' iff player_one_turn is True; otherwise, return 'player two'. >>> get_current_player(True) 'player one' >>> get_current_player(False) 'player two' """ if player_one_turn: return P1 else: retu...
5,332,414
def dis_table_reformat(): """ Reformat table (and recalculate any formulae) """ if not dis_in_table(): return _recalc() _reformat()
5,332,415
def CityscapesGTFine(path: str) -> Dataset: """`CityscapesGTFine <https://www.cityscapes-dataset.com/>`_ dataset. The file structure should be like:: <path> leftImg8bit/ test/ berlin/ berlin_000000_000019_leftImg8bit.png ...
5,332,416
def test_ecs_mxnet_training_dgl_cpu(cpu_only, py3_only, ecs_container_instance, mxnet_training, training_cmd, ecs_cluster_name): """ CPU DGL test for MXNet Training Instance Type - c4.2xlarge DGL is only supported in py3, hence we have used the "py3_only" fixture to...
5,332,417
def is_word(s): """ String `s` counts as a word if it has at least one letter. """ for c in s: if c.isalpha(): return True return False
5,332,418
def index_all_messages(empty_index): """ Expected index of `initial_data` fixture when model.narrow = [] """ return dict(empty_index, **{'all_msg_ids': {537286, 537287, 537288}})
5,332,419
def compute_affine_matrix(in_shape, out_shape, crop=None, degrees=0.0, translate=(0.0, 0.0), flip_h=False, flip_v=False, resize=False, ...
5,332,420
def Bern_to_Fierz_nunu(C,ddll): """From semileptonic Bern basis to Fierz semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.""" ind = ddll.replace('l_','').replace('nu_','') return { 'F' + in...
5,332,421
def enforce_boot_from_volume(client): """Add boot from volume args in create server method call """ class ServerManagerBFV(servers.ServerManager): def __init__(self, client): super(ServerManagerBFV, self).__init__(client) self.bfv_image_client = images.ImageManager(client) ...
5,332,422
def img_to_yuv(frame, mode, grayscale=False): """Change color space of `frame` from any supported `mode` to YUV Args: frame: 3-D tensor in either [H, W, C] or [C, H, W] mode: A string, must be one of [YV12, YV21, NV12, NV21, RGB, BGR] grayscale: discard uv planes return: ...
5,332,423
def assemblenet_kinetics600() -> cfg.ExperimentConfig: """Video classification on Videonet with assemblenet.""" exp = video_classification.video_classification_kinetics600() feature_shape = (32, 224, 224, 3) exp.task.train_data.global_batch_size = 1024 exp.task.validation_data.global_batch_size = 32 exp.ta...
5,332,424
def sendTelegramMessage(TOKEN, CHAT_ID, MSG): """ Function to send message to telegram bot Parameters ---------- TOKEN : STRING Telegram secret token. CHAT_ID : STRING Telegram chat id of user/ group to which you want to send msg. MSG : TYPE Message sent to telegram....
5,332,425
def channel_selection(inputs, module, sparsity=0.5, method='greedy'): """ ํ˜„์žฌ ๋ชจ๋“ˆ์˜ ์ž…๋ ฅ ์ฑ„๋„์ค‘, ์ค‘์š”๋„๊ฐ€ ๋†’์€ ์ฑ„๋„์„ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค. ๊ธฐ์กด์˜ output์„ ๊ฐ€์žฅ ๊ทผ์ ‘ํ•˜๊ฒŒ ๋งŒ๋“ค์–ด๋‚ผ ์ˆ˜ ์žˆ๋Š” ์ž…๋ ฅ ์ฑ„๋„์„ ์ฐพ์•„๋ƒ…๋‹ˆ๋Œœ. :param inputs: torch.Tensor, input features map :param module: torch.nn.module, layer :param sparsity: float, 0 ~ 1 how many prune channel of ou...
5,332,426
def format_host(host_tuple): """ Format a host tuple to a string """ if isinstance(host_tuple, (list, tuple)): if len(host_tuple) != 2: raise ValueError('host_tuple has unexpeted length: %s' % host_tuple) return ':'.join([six.text_type(s) for s in host_tuple]...
5,332,427
def get_cpu_stats(): """ Obtains the system's CPU status. :returns: System CPU static. """ return psutil.cpu_stats()
5,332,428
def test_get_user_invalid_id(mock_user_qs): """ If there is no user with the specified ID, ``None`` should be returned. """ mock_user_qs.get.side_effect = get_user_model().DoesNotExist backend = authentication.VerifiedEmailBackend() retrieved_user = backend.get_user(42) assert retrieve...
5,332,429
def load_gene_metadata(gtf_file : str) -> Dict[str, Dict[str, Union[int, str]]]: """ Read gene metadata from a GTF file. Args: gtf_file (str): path to GTF file Returns: A Dict with each GeneId pointing to a Dict of metadata keys -> values """ ...
5,332,430
def get_plugins() -> dict[str, Plugin]: """ This function is really time consuming... """ # get entry point plugins # Users can use Python's entry point system to create rich plugins, see # example here: https://github.com/Pioreactor/pioreactor-air-bubbler eps = entry_points() pioreacto...
5,332,431
def test_odrive_motors(odrv): """ Give two position commands to both axis """ print('Testing motors...') odrv.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL odrv.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL time.sleep(0.5) odrv.axis0.controller.set_pos_setpoint(1000.0,...
5,332,432
def _deserialise_list_of(collection_type, kind, owning_cls, field, value): """ Deserialise a list of items into a collection objects of class `kind`. Note that if the value is None, we return None here so that we get a more meaningful error message later on. Args: kind: Type to deserialise ...
5,332,433
def get_minmax_array(X): """Utility method that returns the boundaries for each feature of the input array. Args: X (np.float array of shape (num_instances, num_features)): The input array. Returns: min (np.float array of shape (num_features,)): Minimum values for each feature in array. ...
5,332,434
def getAllHeaders(includeText=False): """ Get a dictionary of dream numbers and headers. If includeText=true, also add the text of the dream to the dictionary as 'text' (note that this key is all lowercase so it will not conflict with the usual convention for header names, even if "Text" would be an...
5,332,435
def zscore(arr, period): """ ZScore transformation of `arr` for rolling `period.` ZScore = (X - MEAN(X)) / STDEV(X) :param arr: :param period: :return: """ if period <= 0: raise YaUberAlgoArgumentError("'{}' must be positive number".format(period)) # Do quick sanity checks of a...
5,332,436
def _load_event_data(prefix, name): """Load per-event data for one single type, e.g. hits, or particles. """ expr = '{!s}-{}.csv*'.format(prefix, name) files = glob.glob(expr) dtype = DTYPES[name] if len(files) == 1: return pandas.read_csv(files[0], header=0, index_col=False, dtype=dtype...
5,332,437
def users(): """list all users along with their associated tibanna user groups""" API().users()
5,332,438
def test_weak_ref(v): """Check that weak references can be made to Vectors.""" assert weakref.ref(v) is not None
5,332,439
async def test_entity_device_info_update(hass, mqtt_mock): """Test device registry update.""" registry = dr.async_get(hass) config = { "automation_type": "trigger", "topic": "test-topic", "type": "foo", "subtype": "bar", "device": { "identifiers": ["hello...
5,332,440
def check_file(file_id: str, upsert: bool = False) -> File: """Checks that the file with file_id exists in the DB Args: file_id: The id for the requested file. upsert: If the file doesn't exist create a placeholder file Returns: The file object Raises: NotFoundError: F...
5,332,441
def edit_config_popup(icon): """Open a window to edit config.""" padx = 4 pady = 6 # creating popup window window = tk.Tk() window.title("Pypit config") window.after(1, lambda: window.focus_force()) # focus on create window.bind("<Escape>", lambda e: window.destroy()) # destroy on Esc...
5,332,442
def parse(volume_str): """Parse combined k8s volume string into a dict. Args: volume_str: The string representation for k8s volume, e.g. "claim_name=c1,mount_path=/path1". Return: A Python dictionary parsed from the given volume string. """ kvs = volume_str.split(",") ...
5,332,443
def expect_warnings_on(db, *messages, **kw): """Context manager which expects one or more warnings on specific dialects. The expect version **asserts** that the warnings were in fact seen. """ spec = db_spec(db) if isinstance(db, util.string_types) and not spec(config._current): yield...
5,332,444
def longest_common_substring(text1, text2): """ๆœ€้•ฟๅ…ฌๅ…ฑๅญๅญ—็ฌฆไธฒ๏ผŒๅŒบๅˆ†ๅคงๅฐๅ†™""" n = len(text1) m = len(text2) maxlen = 0 span1 = (0, 0) span2 = (0, 0) if n * m == 0: return span1, span2, maxlen dp = np.zeros((n+1, m+1), dtype=np.int32) for i in range(1, n+1): for j in range(1, m+1)...
5,332,445
def make_subclasses_dict(cls): """ Return a dictionary of the subclasses inheriting from the argument class. Keys are String names of the classes, values the actual classes. :param cls: :return: """ the_dict = {x.__name__:x for x in get_all_subclasses(cls)} the_dict[cls.__name__] = cls ...
5,332,446
def _parse_realtime_data(xmlstr): """ Takes xml a string and returns a list of dicts containing realtime data. """ doc = minidom.parseString(xmlstr) ret = [] elem_map = {"LineID": "id", "DirectionID": "direction", "DestinationStop": "destination" } ack = _single_element(doc,...
5,332,447
def tocopo_accuracy_fn(tocopo_logits: dt.BatchedTocopoLogits, target_data: dt.BatchedTrainTocopoTargetData, oov_token_id: int, pad_token_id: int, is_distributed: bool = True) -> AccuracyMetrics: """Computes accuracy metrics. ...
5,332,448
def cols_from_html_tbl(tbl): """ Extracts columns from html-table tbl and puts columns in a list. tbl must be a results-object from BeautifulSoup)""" rows = tbl.tbody.find_all('tr') if rows: for row in rows: cols = row.find_all('td') for i,cell in enumerate(cols): ...
5,332,449
def get_score_park(board: List[List[str]]) -> Tuple[int]: """ Calculate the score for the building - park (PRK). Score 1: If ONLY 1 park. Score 3: If the park size is 2. Score 8: If the park size is 3. Score 16: If the park size is 4. Score 22: If the park s...
5,332,450
def kernel_epanechnikov(inst: np.ndarray) -> np.ndarray: """Epanechnikov kernel.""" if inst.ndim != 1: raise ValueError("'inst' vector must be one-dimensional!") return 0.75 * (1.0 - np.square(inst)) * (np.abs(inst) < 1.0)
5,332,451
def submission_parser(reddit_submission_object): """Parses a submission and returns selected parameters""" post_timestamp = reddit_submission_object.created_utc post_id = reddit_submission_object.id score = reddit_submission_object.score ups = reddit_submission_object.ups downs = reddit_submiss...
5,332,452
def run(): """Runs the command line interface via ``main``, then exists the process with the proper return code.""" sys.exit(main(sys.argv[1:]) or 0)
5,332,453
def test_setupTestKeep(): """ Test setting up test Keep directory """ print("Testing setupTestKeep") keepDirPath = keeping.setupTestKeep() assert keepDirPath.startswith("/tmp/bluepea") assert keepDirPath.endswith("test/bluepea/keep") assert os.path.exists(keepDirPath) assert keepDir...
5,332,454
def dashboard(): """Displays dashboard to logged in user""" user_type = session.get('user_type') user_id = session.get('user_id') if user_type == None: return redirect ('/login') if user_type == 'band': band = crud.get_band_by_id(user_id) display_name = band.display...
5,332,455
def parse_site(site_content, gesture_id): """ Parses the following attributes: title, image, verbs and other_gesture_ids :param site_content: a html string :param gesture_id: the current id :return: { title: str, img: str, id: number, compares: [ { verb: [s...
5,332,456
def test_multiprocessing_function () : """Test parallel processnig with multiprocessing """ logger = getLogger ("ostap.test_multiprocessing_function") logger.info ('Test job submission with module %s' % multiprocessing ) ncpus = multiprocessing.cpu_count() from multiprocessing i...
5,332,457
def main(): """ Main function for run script. """ app.run()
5,332,458
def fnCalculate_Bistatic_Coordinates(a,B): """ Calculate the coordinates of the target in the bistatic plane A,B,C = angles in the triangle a,b,c = length of the side opposite the angle Created: 22 April 2017 """ u = a*math.cos(B); v = a*math.sin(B); return u,v
5,332,459
def _fn_lgamma_ ( self , b = 1 ) : """ Gamma function: f = log(Gamma(ab)) >>> f = >>> a = f.lgamma ( ) >>> a = f.lgamma ( b ) >>> a = lgamma ( f ) """ return _fn_make_fun_ ( self , b , Os...
5,332,460
def convolve_smooth(x, win=10, mode="same"): """Smooth data using a given window size, in units of array elements, using the numpy.convolve function.""" return np.convolve(x, np.ones((win,)), mode=mode) / win
5,332,461
def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False, Lm=None): """ Multioutput conditional for an independent kernel and shared inducing features. Same behaviour as conditional with non-multioutput kernels. The covariance matrices used to calculate t...
5,332,462
def bq_wait_for_rows(bq_client: bigquery.Client, table: bigquery.Table, expected_num_rows: int): """ polls tables.get API for number of rows until reaches expected value or times out. This is mostly an optimization to speed up the test suite without making it flaky. """ ...
5,332,463
def descent(x0, fn, iterations=1000, gtol=10**(-6), bounds=None, limit=0, args=()): """A gradient descent optimisation solver. Parameters ---------- x0 : array-like n x 1 starting guess of x. fn : obj The objective function to minimise. iterations : int Maximum number of...
5,332,464
def test_fields(): """Try using 'fields' getter""" TestSchema = Unischema('TestSchema', [ UnischemaField('int_field', np.int8, (), ScalarCodec(IntegerType()), False), UnischemaField('string_field', np.string_, (), ScalarCodec(StringType()), False), ]) assert len(TestSchema.fields) == 2 ...
5,332,465
def count_teams_for_party(party_id: PartyID) -> int: """Return the number of orga teams for that party.""" return db.session \ .query(DbOrgaTeam) \ .filter_by(party_id=party_id) \ .count()
5,332,466
def num_series(datetime_series) -> pd.Series: """Return a datetime series with numeric values.""" return datetime_series(LENGTH)
5,332,467
def obtain_ranks(outputs, targets, mode=0): """ outputs : tensor of size (batch_size, 1), required_grad = False, model predictions targets : tensor of size (batch_size, ), required_grad = False, labels Assume to be of format [1, 0, ..., 0, 1, 0, ..., 0, ..., 0] mode == 0: rank from distance (sm...
5,332,468
def warn(path: str, msg: str, req: "RequirementDirective" = None): """ Log a warning """ req_id = req.requirement_id or "UNKNOWN" if req else "UNKNOWN" print(f"WARNING: {path} | {req_id} | {msg}")
5,332,469
def sample_a2c_params(trial: optuna.Trial) -> Dict[str, Any]: """ Sampler for A2C hyperparams. """ lr_schedule = trial.suggest_categorical("lr_schedule", ["linear", "constant"]) learning_rate = trial.suggest_loguniform("learning_rate", 1e-5, 1) n_steps = trial.suggest_categorical("n_steps", [4, ...
5,332,470
def standard_parameter_writer_bounds_mask(filename, params, pmin, pmax, mask, pid=None): """ Standard parameter writer with parameter bounds and mask. The standard parameter writer writes a space separated file containing 1 header line (# value min max mask) pl...
5,332,471
def location_parser(selected_variables, column): """ Parse the location variable by creating a list of tuples. Remove the hyphen between the start/stop positions. Convert all elements to integers and create a list of tuples. Parameters: selected_variables (dataframe): The dataframe contain...
5,332,472
def get_qmf_bank(h, n_band): """ Modulates an input protoype filter into a bank of cosine modulated filters Parameters ---------- h: torch.Tensor prototype filter n_band: int number of sub-bands """ k = torch.arange(n_band).reshape(-1, 1) N = h.shape[-1] t = t...
5,332,473
def test_theme_manager_themes(themes): """Test ThemeManager.themes""" tm = ThemeManager(themes=themes) theme_names = [t.name for t in themes] assert len(tm.themes) == len(themes) for theme in tm.themes: assert theme.name in theme_names
5,332,474
def compare_one(col, cons_aa, aln_size, weights, aa_freqs, pseudo_size): """Compare column amino acid frequencies to overall via G-test.""" observed = count_col(col, weights, aa_freqs, pseudo_size) G = 2 * sum(obsv * math.log(obsv / aa_freqs.get(aa, 0.0)) for aa, obsv in observed.items()) ...
5,332,475
def open(uri, mode='a', eclass=_eclass.manifest): """Open a Blaze object via an `uri` (Uniform Resource Identifier). Parameters ---------- uri : str Specifies the URI for the Blaze object. It can be a regular file too. The URL scheme indicates the storage type: * carray: Ch...
5,332,476
def create_df(dic_in, cols, input_type): """ Convert JSON output from OpenSea API to pandas DataFrame :param dic_in: JSON output from OpenSea API :param cols: Keys in JSON output from OpenSea API :param input_type: <TBD> save the columns with dictionaries as entries seperately :return: Cleaned D...
5,332,477
def GenerateApiMap(base_dir, root_dir, api_config): """Create an apis_map.py file in the given root_dir with for given api_config. Args: base_dir: str, Path of directory for the project. root_dir: str, Path of the map file location within the project. api_config: regeneration config for all apis....
5,332,478
def file_updated_at(file_id, db_cursor): """ Update the last time the file was checked """ db_cursor.execute(queries.file_updated_at, {'file_id': file_id}) db_cursor.execute(queries.insert_log, {'project_id': settings.project_id, 'file_id': file_id, '...
5,332,479
def test_get_files_directory(runner: click.testing.CliRunner) -> None: """It returns file in directory.""" with runner.isolated_filesystem(): os.mkdir("dir") with open("dir/file.toml", "w") as f: f.write("content doesnt matter") src = "dir" expected = [pathlib.Path("...
5,332,480
def generate_comic_testers(): """For each comic scraper, create a test class.""" g = globals() if "TESTALL" in os.environ: # test all comics (this will take some time) scraperclasses = scraper.get_scraperclasses() else: # Get limited number of scraper tests on Travis builds to ma...
5,332,481
def action_to_upper(action): """ action to upper receives an action in pddl_action_representation, and returns it in upper case. :param action: A action in PddlActionRepresentation :return: PddlActionRepresentation: The action in upper case """ if action: action.name = action.name.uppe...
5,332,482
def load_qa_frame(filename, frame=None, flavor=None): """ Load an existing QA_Frame or generate one, as needed Args: filename: str frame: Frame object, optional flavor: str, optional Type of QA_Frame Returns: qa_frame: QA_Frame object """ from lvmspec.qa...
5,332,483
def generate_model_example(model: Type["Model"], relation_map: Dict = None) -> Dict: """ Generates example to be included in schema in fastapi. :param model: ormar.Model :type model: Type["Model"] :param relation_map: dict with relations to follow :type relation_map: Optional[Dict] :return:...
5,332,484
def compare_folder(request): """ Creates the compare folder path `dione-sr/tests/data/test_name/compare`. """ return get_test_path('compare', request)
5,332,485
def _get_param_combinations(lists): """Recursive function which generates a list of all possible parameter values""" if len(lists) == 1: list_p_1 = [[e] for e in lists[0]] return list_p_1 list_p_n_minus_1 = _get_param_combinations(lists[1:]) list_p_1 = [[e] for e in lists[0]] list_...
5,332,486
def test_get_unitary_matrix_CNOT(target_wire): """Test CNOT: 2-qubit gate with different target wires, some non-adjacent.""" wires = [0, 1, 2, 3, 4] def testcircuit(): qml.CNOT(wires=[1, target_wire]) get_matrix = get_unitary_matrix(testcircuit, wires) matrix = get_matrix() # test the...
5,332,487
def system_mass_spring_dumper(): """ใƒžใ‚นใƒใƒใƒ€ใƒณใƒ‘็ณปใฎ่จญ่จˆไพ‹""" # define the system m = 1.0 k = 1.0 c = 1.0 A = np.array([ [0.0, 1.0], [-k/m, -c/m] ]) B = np.array([ [0], [1/m] ]) C = np.eye(2) D = np.zeros((2,1),dtype=float) W = np.diag([1.0, 1.0]) ...
5,332,488
def explore_voxel( start_pos: tuple, masked_atlas: ma.MaskedArray, *, count: int = -1, ) -> int: """Explore a given voxel. Ask Dimitri for more details. Seems like this is a BFS until a voxel with a different value is found or the maximal number of new voxels were seen. Parameters...
5,332,489
def plot_compressed_channel_stats(stats, color=None, y_center=False, title=None): """ Similar to plot_channel_stats except everything is represented in a single plot (i.e. no subplots). """ plt.figure(figsize=(6,4)) ax = plt.gca() # If requested, center all axes around 0 if y_center...
5,332,490
def get_green_button_xml( session: requests.Session, start_date: date, end_date: date ) -> str: """Download Green Button XML.""" response = session.get( f'https://myusage.torontohydro.com/cassandra/getfile/period/custom/start_date/{start_date:%m-%d-%Y}/to_date/{end_date:%m-%d-%Y}/format/xml' ) ...
5,332,491
def calculateSecFromEpoch(date,hour): """ Calculates seconds from EPOCH """ months={ '01':'Jan', '02':'Feb', '03':'Mar', '04':'Apr', '05':'May', '06':'Jun', '07':'Jul', '08':'Aug', '09':'Sep', '10':'Oct', '11':'Nov', '12':'Dec' } year=YEAR_PREFIX+date[0:2] month=months[date[2:4]] day=d...
5,332,492
def star_noise_simulation(Variance, Pk, nongaussian = False): """simulates star + noise signal, Pk is hyperprior on star variability and flat at high frequencies which is stationary noise""" Pk_double = np.concatenate((Pk, Pk)) phases = np.random.uniform(0, 2 * np.pi, len(Pk)) nodes0 = np.sqrt(Pk_do...
5,332,493
def main(): """Make a jazz noise here""" args = get_args() words1 = {} for line in args.file1: for word in line.split(): words1[word] = 1 words2 = {} for line in args.file2: for word in line.split(): words2[word] = 1 for key in words1: if k...
5,332,494
def test_cancel_already_done_normal(client): """attempt to cancel application that already-done lottery 1. create 'done' application 2. attempt to cancel that application target_url: /lotteries/<id> [DELETE] """ token = login(client, test_user['secret_id'], test_use...
5,332,495
def get_seq_num(): """ Simple class for creating sequence numbers Truncate epoch time to 7 digits which is about one month """ t = datetime.datetime.now() mt = time.mktime(t.timetuple()) nextnum = int(mt) retval = nextnum % 10000000 return retval
5,332,496
def test_trydoer_throw(): """ Test TryDoer testing class with throw to force exit """ tymist = tyming.Tymist(tock=0.125) doer = TryDoer(tymth=tymist.tymen(), tock=0.25) assert doer.tock == 0.25 assert doer.states == [] assert tymist.tyme == 0.0 do = doer(tymth=doer.tymth, tock=doer...
5,332,497
def get_packages_for_file_or_folder(source_file, source_folder): """ Collects all the files based on given parameters. Exactly one of the parameters has to be specified. If source_file is given, it will return with a list containing source_file. If source_folder is given, it will search recursively all...
5,332,498
def sanitize_tag(tag: str) -> str: """Clean tag by replacing empty spaces with underscore. Parameters ---------- tag: str Returns ------- str Cleaned tag Examples -------- >>> sanitize_tag(" Machine Learning ") "Machine_Learning" """ return tag.strip().rep...
5,332,499