content
stringlengths
22
815k
id
int64
0
4.91M
def aggregate_hts(style="all_modes_combined"): """Use the 'processed' version of the HTS table to summarize the flows. Using the 'style' parameter, you can: - aggregate by mode using 'by_mode' - aggregate by mode and o&d location types using 'by_mode_and_location_type' - aggre...
21,500
def pix2sky(shape, wcs, pix, safe=True, corner=False): """Given an array of corner-based pixel coordinates [{y,x},...], return sky coordinates in the same ordering.""" pix = np.asarray(pix).astype(float) if corner: pix -= 0.5 pflat = pix.reshape(pix.shape[0], -1) coords = np.asarray(wcsutils.nobcheck(wcs).wcs_pix...
21,501
def getRelativeSilenceVideo(videoPath): """Function to get relative silence videos before and after each video""" silVid = ['', ''] vidData = getVideoDataFromPath(videoPath) videoNameList = videoPath.split('/') tempVidName = videoNameList[0] + '/' + videoNameList[1] + '/' + videoNameList[2] + '/Sile...
21,502
def phase_space_plot(data_fname="kadowaki2019.tsv", ned_fname="objsearch_cz2000-12000_500arcmin.txt", plot_fname="phasespace.pdf", plot_udgs=True, local_env=True, udg_only=True, mfeat="Re"): ...
21,503
def convert_to_xyxy_coordinates(boxes: tf.Tensor) -> tf.Tensor: """Convert boxes to their center coordinates y_cent, x_cent, h, w -> y_min, x_min, y_max, x_max Arguments: - *boxes*: A Tensor of shape [N, ..., (y_cent, x_cent, h, w)] Returns: A tensor of shape [N, ..., num_boxes, (y_min, x_m...
21,504
def debug(args, env, cwd, type_="debug"): """Command to debug the firmware with GDB""" soc = get_soc_name(args.soc) board = get_board_name(args.board) if not os.path.exists(f"build/{soc}/{board}/zephyr/zephyr/zephyr.elf"): raise SystemExit("No Zephyr elf found. Run \"./elements-fpga.py compile "...
21,505
def ceilo2nc(full_path: str, output_file: str, site_meta: dict, keep_uuid: Optional[bool] = False, uuid: Optional[str] = None, date: Optional[str] = None) -> str: """Converts Vaisala / Lufft ceilometer data into Cloudnet Level 1b netCDF file. Thi...
21,506
def classify(mapper: object, files: list or dict, samples: list = None, fmt: str = None, demux: bool = None, trimsub: str = None, tree: dict = None, rankdic: dict = None, namedic: dict =...
21,507
def apply(): """Run terraform apply. Raises an exception if the Terraform is invalid.""" # Validate and format the terraform files. os.chdir(TERRAFORM_DIR) subprocess.check_call(['terraform', 'validate']) subprocess.check_call(['terraform', 'fmt']) # Setup the backend if needed and reload modul...
21,508
def test_traverse_nonexistent_fk(): """Comparing with a reverse FK traversal that does not exist for the model.""" user = UserFactory(profile=None) profile = ProfileFactory(user=UserFactory(profile=None)) user_has_profile = R(profile=profile) user_has_no_profile = R(profile=None) # filter() tes...
21,509
def get_better_loci(filename, cutoff): """ Returns a subset of loci such that each locus includes at least "cutoff" different species. :param filename: :param cutoff: :return: """ f = open(filename) content = f.read() f.close() loci = re.split(r'//.*|', content) ...
21,510
def paginate_data(data_list, page=1 ,per_page=10): """将数据分页返回""" pages = int(math.ceil(len(data_list) / per_page)) page = int(page) per_page = int(per_page) has_next = True if pages > page else False has_prev = True if 1 < page <= int(pages) else False items = data_list[(page-1)*per_page : p...
21,511
def get_all_element_frequencies(sequences): """ UC Computes the frequencies of each element across a collection of sequences. """ pass
21,512
def writec(s,font,color,text,border=1): """write centered text to a surface with a black border <pre>writec(s,font,color,text,border=1)</pre> """ w,h = font.size(text) x = (s.get_width()-w)/2 y = (s.get_height()-h)/2 write(s,font,(x,y),color,text,border)
21,513
def setup(bot: Bot) -> None: """Sync cog load.""" bot.add_cog(Sync(bot)) log.info("Cog loaded: Sync")
21,514
def quat_to_rotmat(quat): """Convert quaternion coefficients to rotation matrix. Args: quat: size = [B, 4] 4 <===>(w, x, y, z) Returns: Rotation matrix corresponding to the quaternion -- size = [B, 3, 3] """ norm_quat = quat norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keep...
21,515
def has_multimethods(cls): """ Declare class as one that have multimethods.""" for name, obj in cls.__dict__.items(): if isinstance(obj, MethodDispatcher): obj.proceed_unbound_rules(cls) return cls
21,516
def elastic_depth(f, time, method="DP2", lam=0.0, parallel=True): """ calculates the elastic depth between functions in matrix f :param f: matrix of size MxN (M time points for N functions) :param time: vector of size M describing the sample points :param method: method to apply optimization (defau...
21,517
def run_coro_thread(func: callable, *args, **kwargs) -> Any: """ Run a Python AsyncIO coroutine function within a new event loop using a thread, and return the result / raise any exceptions as if it were ran normally within an AsyncIO function. .. Caution:: If you're wanting to run a coroutine...
21,518
def test_choice_retries_on_failure(mock_input): """ Tests the function will continue to retry until a valid option has been entered """ answer = choice('Choose: ', choices=CHOICES) assert answer == 'Major'
21,519
def get_all_ports(entity): """ Recursively descends through the entity hierarchy and collects all ports defined within the parameter or any of its children. Parameters ---------- entity : Entity The root from which to start collecting. Returns ------- list of Port ...
21,520
def phase_plane_curves(hstar, hustar, state, g=1., wave_family='both', y_axis='u', ax=None, plot_unphysical=False): """ Plot the curves of points in the h - u or h-hu phase plane that can be connected to (hstar,hustar). state = 'qleft' or 'qright' indicates whether the specified s...
21,521
def rinex_sopac(station, year, month, day): """ author: kristine larson inputs: station name, year, month, day picks up a hatanaka RINEX file from SOPAC - converts to o hatanaka exe hardwired for my machine """ exedir = os.environ['EXE'] crnxpath = hatanaka_version() doy,cdoy,cyyyy,...
21,522
def deploy(**kwargs): """Deploy a PR into a remote server via Fabric""" return apply_pr(**kwargs)
21,523
def word_list2tensor(word_list, dictionary): """ args word_list: [batch_size, seq_len, token_id] dictionary: Dictionary return source, target [batch_size, seq_len, token_id] """ word_list_padded = add_word_padding(word_list, dictionary) batch = torch.LongTensor(word_list_padded) ...
21,524
def canonicalize_monotonicity(monotonicity, allow_decreasing=True): """Converts string constants representing monotonicity into integers. Args: monotonicity: The monotonicities hyperparameter of a `tfl.layers` Layer (e.g. `tfl.layers.PWLCalibration`). allow_decreasing: If decreasing monotonicity is c...
21,525
def killIfHasMore(sprite, partner, game, resource, limit=1): """ If 'sprite' has more than a limit of the resource type given, it dies. """ if sprite.resources[resource] >= limit: killSprite(sprite, partner, game)
21,526
def test_pipeline_split_shared_parameter_with_micro_batch_interleaved_stage1_opt_shard(): """ Feature: test PipelineSplitSharedParameter with MicroBatchInterleaved in auto parallel. Description: net with MicroBatchInterleaved in semi auto parallel. Expectation: success. """ context.set_auto_para...
21,527
def add_gdp(df, gdp, input_type="raw", drop=True): """Adds the `GDP` to the dataset. Assuming that both passed dataframes have a column named `country`. Parameters ---------- df : pd.DataFrame Training of test dataframe including the `country` column. gdp : pd.DataFrame Mapping betw...
21,528
def get_options(cmd_args): """ Argument Parser. """ parser = argparse.ArgumentParser( prog='activitygen.py', usage='%(prog)s -c configuration.json', description='SUMO Activity-Based Mobility Generator') parser.add_argument( '-c', type=str, dest='config', required=True, help='...
21,529
def validate_partition_manifests(manifests): """ Check the correctness of the manifests list (no conflicts, no missing elements, etc.) :param manifests: List of the partition manifests """ for manifest in manifests: assert isinstance(manifest, Manifest) partitions_names = {} pa...
21,530
def partida_7(): """partida_7""" check50.run("python3 volleyball.py").stdin("A\nA\nA\nB\nA\nB\nA\nA\nB\nA\nA", prompt=False).stdout("EMPIEZA\nSACA A\nGANA A\nA 1 B 0\nSACA A\nGANA A\nA 2 B 0\nSACA A\nGANA A\nA 3 B 0\nSACA A\nGANA B\nA 3 B 0\nSACA B\nGANA A\nA 3 B 0\nSACA A\nGANA B\nA 3 B 0\nSACA B\nGANA A\nA 3 ...
21,531
def test_is_team_guid__false(): """ Test that an invalid team GUID is recognized. """ assert not is_team_guid("not a guid")
21,532
def no_background_patches(threshold=0.4, percentile=99.9): """Returns a patch filter to be used by :func:`create_patches` to determine for each image pair which patches are eligible for sampling. The purpose is to only sample patches from "interesting" regions of the raw image that actually contain a subst...
21,533
def start_thread(): """Start new thread with or without first comment.""" subject = request.form.get('subject') or '' comment = request.form.get('comment') or '' if not subject: return error('start_thread:subject') storage.start_thread(g.username, subject, comment) flash('New Thread Sta...
21,534
def copyrotateimage(srcpath, dstpath, rotate=False, deletesource=False): """ Copying with rotation: Copies a TIFF image from srcpath to dstpath, rotating the image by 180 degrees if specified. """ #Handles special case where source path and destination path are the same if srcpath==dstpath: ...
21,535
def main_sim_multi(cor = 0.75, rs = 0.5): """ multitask simulated data """ dic1, rel1, turk1, dic2, rel2, turk2 = simulate_multitask(cor) lc1 = crowd_model.labels_collection(turk1, rel1) lc2 = crowd_model.labels_collection(turk2, rel2) for rs in [0.1, 0.2, 0.3, 0.4, 0.5]: res = main...
21,536
def get_package_data(name, package=None): """Retrieve metadata information for the given package name""" if not package: package = models.Package(name=name) releases = {} else: releases = package.get_all_releases() client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') ...
21,537
def _extract_xbstream( input_stream, working_dir, xbstream_binary=XBSTREAM_BINARY ): """ Extract xbstream stream in directory :param input_stream: The stream in xbstream format :param working_dir: directory :param xbstream_binary: Path to xbstream :return: True if extracted successfully ...
21,538
def info(*k, **kw): """ Wraps logging.info """ log.info(*k, **kw)
21,539
def describe_default_cluster_parameters(ParameterGroupFamily=None, MaxRecords=None, Marker=None): """ Returns a list of parameter settings for the specified parameter group family. For more information about parameters and parameter groups, go to Amazon Redshift Parameter Groups in the Amazon Redshift Clust...
21,540
def execute_experiment_two_files_bin(result: dict, experiment_id: str, compression_method: str, nsnps: int, nsamples: int, N: int = 1) ...
21,541
def load_version(pkg_dir, pkg_name): """Load version from variable __version__ in file __init__.py with a regular expression""" try: filepath_init = path.join(pkg_dir, pkg_name, '__init__.py') file_content = read_file(filepath_init) re_for_version = re.compile(r'''__version__\s+=\s+['"](...
21,542
def feedforward( inputs, input_dim, hidden_dim, output_dim, num_hidden_layers, hidden_activation=None, output_activation=None): """ Creates a dense feedforward network with num_hidden_layers layers where each layer has hidden_dim number of units except...
21,543
def test_gradient_accumulation_multi_batch(tmpdir, explicit_loops): """ from _base: increase batches per step and number of steps """ for graph_runner in [run_mm_graph, run_complex_graph]: np.random.seed(1234) label_array = np.random.randint(0, hidden_size, batch_size) accl_ini...
21,544
def _test(): """ >>> solve("axyb", "abyxb") axb """ global chr import doctest def chr(x): return x doctest.testmod()
21,545
def thumbnail_image(url, size=(64, 64), format='.png'): """ Convert image to a specific format """ im = Image.open(urllib.request.urlopen(url)) # filename is last part of URL minus extension + '.format' pieces = url.split('/') filename = ''.join((pieces[-2], '_', pieces[-1].split('.')[0], '_thumb',...
21,546
def _basic_rebuild_chain(target: database.Target) -> RebuildChain: """ Get a rebuild chain based purely on 'rebuild info' from Jam. """ chain: RebuildChain = [(target, None)] current: Optional[database.Target] = target assert current is not None while True: reason = current.rebuild_r...
21,547
def test_md013_good_indented_code_block(): """ Test to make sure this rule does not trigger with a document that contains a long line within an indented code block, but with the code_block value turned off. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan",...
21,548
def ravel_group_params(parameters_group): """Take a dict(group -> {k->p}) and return a dict('group:k'-> p) """ return {f'{group_name}:{k}': p for group_name, group_params in parameters_group.items() for k, p in group_params.items()}
21,549
def dir_manager( path: ty.Optional[ty.Union[pathlib.Path, str]] = None, cleanup=None ) -> ty.Generator[pathlib.Path, None, None]: """A context manager to deal with a directory, default to a self-destruct temp one.""" if path is None: d_path = pathlib.Path(tempfile.mkdtemp()) if cleanup is No...
21,550
def decode_orders(game, power_name, dest_unit_value, factors): """ Decode orders from computed factors :param game: An instance of `diplomacy.Game` :param power_name: The name of the power we are playing :param dest_unit_value: A dict with unit as key, and unit value as value :param ...
21,551
def _convert_to_type(se, allow_any=False, allow_implicit_tuple=False): """ Converts an S-Expression representing a type, like (Vec Float) or (Tuple Float (Vec Float)), into a Type object, e.g. Type.Tensor(1,Type.Float) or Type.Tuple(Type.Float, Type.Tensor(1,Type.Float)). If allow_implicit_tuple is...
21,552
def index(): """Returns a 200, that's about it!!!!!!!""" return 'Wow!!!!!'
21,553
def file_sort_key(file): """Calculate the sort key for ``file``. :param file: The file to calculate the sort key for :type file: :class:`~digi_edit.models.file.File` :return: The sort key :rtype: ``tuple`` """ path = file.attributes['filename'].split(os.path.sep) path_len = len(path) ...
21,554
def merge_tables(pulse_data, trial_data, merge_keys=TRIAL_GROUPER): """Add trial-wise information to the pulse-wise table.""" pulse_data = pulse_data.merge(trial_data, on=merge_keys) add_kernel_data(pulse_data) return pulse_data
21,555
def writeFFDFile(fileName, nBlocks, nx, ny, nz, points): """ Take in a set of points and write the plot 3dFile """ f = open(fileName, "w") f.write("%d\n" % nBlocks) for i in range(nBlocks): f.write("%d %d %d " % (nx[i], ny[i], nz[i])) # end f.write("\n") for block in range(...
21,556
def eos_deriv(beta, g): """ compute d E_os(beta)/d beta from polynomial expression""" x = np.tan(beta/2.0) y = g[4] + x * g[3] + x*x * g[2] + x*x*x*g[1] + x*x*x*x*g[0] y = y / ((1.0 + x*x)*(1.0 + x*x)*(1.0 + x*x)) return y
21,557
def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ # First, we put the new ang...
21,558
def process_one_name(stove_name): """ Translates a single PokerStove-style name of holecards into an expanded list of pokertools-style names. For example: "AKs" -> ["Ac Kc", "Ad Kd", "Ah Kh", "As Ks"] "66" -> ["6c 6d", "6c 6h", "6c 6s", "6d 6h", "6d 6s", "6c 6d"] """ if len(stov...
21,559
def job_dispatch(results, job_id, batches): """ Process the job batches one at a time When there is more than one batch to process, a chord is used to delay the execution of remaining batches. """ batch = batches.pop(0) info('dispatching job_id: {0}, batch: {1}, results: {2}'.format(job_i...
21,560
def get_temperature(): """ Serves temperature data from the database, in a simple html format """ logger = logging.getLogger("logger") #sqlite handler sql_handler = SQLiteHandler() logger.addHandler(sql_handler) logger.setLevel(logging.INFO) con = sqlite3.connect(db) cur = ...
21,561
def command_result_processor_category_empty(command_category): """ Command result message processor if a command category is empty. Parameters ---------- command_category : ``CommandLineCommandCategory`` Respective command category. Returns ------- message : `str` "...
21,562
def _parse_path(**kw): """ Parse leaflet `Path` options. http://leafletjs.com/reference-1.2.0.html#path """ color = kw.pop('color', '#3388ff') return { 'stroke': kw.pop('stroke', True), 'color': color, 'weight': kw.pop('weight', 3), 'opacity': kw.pop('opacity', 1...
21,563
def random_rotation(x, rg, row_axis=1, col_axis=2, channel_axis=0, fill_mode='nearest', cval=0., interpolation_order=1): """Performs a random rotation of a Numpy image tensor. # Arguments x: Input tensor. Must be 3D. rg: Rotation range, in degrees. row_axis: Index of...
21,564
def create_app(config_name: str) -> Flask: """Create the Flask application Args: config_name (str): Config name mapping to Config Class Returns: [Flask]: Flask Application """ from app.config import config_by_name from app.models import User, Iris from app.controlle...
21,565
def load_module(): """This function loads the module and returns any errors that occur in the process.""" proc = subprocess.Popen(["pactl", "load-module", "module-suspend-on-idle"], stderr=subprocess.PIPE) stderr = proc.communicate()[1].decode("UTF-8") return stderr
21,566
def time_struct_2_datetime( time_struct: Optional[time.struct_time], ) -> Optional[datetime]: """Convert struct_time to datetime. Args: time_struct (Optional[time.struct_time]): A time struct to convert. Returns: Optional[datetime]: A converted value. """ return ( datet...
21,567
def _parse_input(): """ A function for handling terminal commands. :return: The path to the experiment configuration file. """ parser = argparse.ArgumentParser(description='Performs CNN analysis according to the input config.') parser.add_argument('-i', '--experiments_file', default='experiment...
21,568
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False): """ The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M...
21,569
def we_are_buying(account_from, account_to): """ Are we buying? (not buying == selling) """ buy = False sell = False for value in TRADING_ACCOUNTS: if (value.lower() in account_from): buy = True sell = False elif (value.lower() in account_to): ...
21,570
def register(param, file_src, file_dest, file_mat, file_out, im_mask=None): """ Register two images by estimating slice-wise Tx and Ty transformations, which are regularized along Z. This function uses ANTs' isct_antsSliceRegularizedRegistration. :param param: :param file_src: :param file_dest: ...
21,571
def parse_geoname_table_file(fpath, delimiter='\t'): """ Parse the table given in a file :param fpath: string - path to the file :param delimiter: string - delimiter between columns in the file :returns: list of dict """ if not os.path.isfile(fpath): fstr = "path is not a file: {}"....
21,572
def test_welcome_page_view_integration_test(client, settings): """Assert that anonymous client can access WelcomePageView and that welcome.html used as a template""" settings.STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.StaticFilesStorage" ) response = client.get("") asser...
21,573
def wait_for_compute_jobs(nevermined, account, jobs): """Monitor and wait for compute jobs to finish. Args: nevermined (:py:class:`nevermined_sdk_py.Nevermined`): A nevermined instance. account (:py:class:`contracts_lib_py.account.Account`): Account that published the compute jobs. ...
21,574
def test_gridsearch(): """Check that base trees can be grid-searched.""" # AdaBoost classification boost = AdaBoostClassifier() parameters = {'n_estimators': (1, 2), 'base_estimator__max_depth': (1, 2), 'algorithm': ('SAMME', 'SAMME.R')} clf = GridSearchCV(boost, ...
21,575
def plot4halovtimeradinterp(x_func,v_func,snaps,zs,title,x_label,y_label,radii): """ Plots a 2x2 grid of profile data vs time for 4 most massive halos. .. deprecated:: 0.0.0 plot4halovtimeradinterp uses the outdated data format of a list of Snapshot instances. This results in inaccu...
21,576
def assertInStdout(proc_output, expected_output, process, cmd_args=None, *, output_filter=None, strict_proc_matching=True, strip_ansi_escape_sequences=True): """ Assert that 'outp...
21,577
def _delete_pool_member(members): """Deletes pool members""" ServerPoolMember.objects.filter(id__in=members).delete()
21,578
def test_btrial(): """Test module btrial.py by downloading btrial.csv and testing shape of extracted data has 45 rows and 3 columns """ test_path = tempfile.mkdtemp() x_train, metadata = btrial(test_path) try: assert x_train.shape == (45, 3) except: shutil.rmtree(test_path) raise()
21,579
def f1_score_loss(predicted_probs: tf.Tensor, labels: tf.Tensor) -> tf.Tensor: """ Computes a loss function based on F1 scores (harmonic mean of precision an recall). Args: predicted_probs: A [B, L] tensor of predicted probabilities labels: A [B, 1] tensor of expected labels Returns: ...
21,580
def get_alarm_historys_logic(starttime, endtime, page, limit): """ GET 请求历史告警记录信息 :return: resp, status resp: json格式的响应数据 status: 响应码 """ data = {'alarm_total': 0, "alarms": []} status = '' message = '' resp = {"status": status, "data": data, "message": messag...
21,581
def showCities(): """ Shows all cities in the database """ if 'access_token' not in login_session: return redirect(url_for('showLogin')) cities = session.query(City).order_by(City.id) return render_template('cities.html', cities=cities)
21,582
def symb_to_num(symbolic): """ Convert symbolic permission notation to numeric notation. """ if len(symbolic) == 9: group = (symbolic[:-6], symbolic[3:-3], symbolic[6:]) try: numeric = notation[group[0]] + notation[group[1]] + notation[group[2]] except: n...
21,583
def round_vector(v, fraction): """ ベクトルの各要素をそれぞれ round する Args: v (list[float, float, float]): Returns: list[float, float, float]: """ v = [round(x, fraction) for x in v] return v
21,584
def accept(model): """Return True if more than 20% of the validation data is being correctly classified. Used to avoid including nets which haven't learnt anything in the ensemble. """ accuracy = 0 for data, target in validation_data[:(500/100)]: if use_gpu: data, target = ...
21,585
def parse_tcp_packet(tcp_packet): """read tcp data.http only build on tcp, so we do not need to support other protocols.""" tcp_base_header_len = 20 # tcp header tcp_header = tcp_packet[0:tcp_base_header_len] source_port, dest_port, seq, ack_seq, t_f, flags = struct.unpack(b'!HHIIBB6x', tcp_header) ...
21,586
def control_browser(cef_handle, queue): """ Loop thread to send javascript calls to cef """ while not cef_handle.HasDocument(): time.sleep(2) cef_handle.ExecuteFunction('window.setWidth', 0) while True: operation = queue.get() cef_handle.ExecuteFunction(operation[0], operatio...
21,587
def find_balanced(text, start=0, start_sep='(', end_sep=')'): """ Finds balanced ``start_sep`` with ``end_sep`` assuming that ``start`` is pointing to ``start_sep`` in ``text``. """ if start >= len(text) or start_sep != text[start]: return start balanced = 1 pos = start + 1 while...
21,588
def main(): """ This script depicts caffeine n times and writes the runtime into a file. - without augmentations with fingerprint picking - with augmentations with fingerprint picking - without augmentations without fingerprint picking - with augmentations without fingerprint pic...
21,589
def write_json(druid, metadata): """Outputs the JSON data file for the roll specified by DRUID.""" output_path = Path(f"output/json/{druid}.json") output_path.parent.mkdir(parents=True, exist_ok=True) with output_path.open("w") as _fh: json.dump(metadata, _fh)
21,590
def test_rk38(): """Test "corrected" 3rd-order Runge-Kutta""" rk38 = chk_ode(ints.rk38) ref = np.array([2,2.7846719015333337,4.141594947022453,6.619134913159302,11.435455703714204]) assert np.allclose(rk38,ref)
21,591
def get_jhu_counts(): """ Get latest case count .csv from JHU. Return aggregated counts by country as Series. """ now = datetime.datetime.now().strftime("%m-%d-%Y") url = f"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{now}.csv...
21,592
def set_debug(boolean): """Enable/Disable OpenGL debugging - specifically, this turns on/off calling of glGetError after every call.""" screen.debug = boolean if boolean: oglError.ErrorChecker.registerChecker(None) else: oglError.ErrorChecker.registerChecker(lambda:None)
21,593
def sectionsToMarkdown(root): """ Converts a list of Demisto JSON tables to markdown string of tables :type root: ``dict`` or ``list`` :param root: The JSON table - List of dictionaries with the same keys or a single dictionary (required) :return: A string representation of the markdow...
21,594
def rename_files(source_dir, file_type, rfam_acc): """ :param source_dir: :param file_type: :return: """ if not os.path.exists(source_dir): raise IOError if file_type == "SEED": seed_file_loc = os.path.join(source_dir, rfam_acc) if not os.path.exists(seed_file_loc...
21,595
def VonMisesFisher_sample(phi0, theta0, sigma0, size=None): """ Draw a sample from the Von-Mises Fisher distribution. Parameters ---------- phi0, theta0 : float or array-like Spherical-polar coordinates of the center of the distribution. sigma0 : float Width of the distribution. ...
21,596
async def async_init_flow( hass: HomeAssistantType, handler: str = DOMAIN, context: Optional[Dict] = None, data: Any = None, ) -> Any: """Set up mock Roku integration flow.""" with patch( "homeassistant.components.roku.config_flow.Roku.device_info", new=MockDeviceInfo, ): ...
21,597
def _get_filtered_topics(topics, include, exclude): """ Filter the topics. :param topics: Topics to filter :param include: Topics to include if != None :param exclude: Topics to exclude if != and include == None :return: filtered topics """ logging.debug("Filtering topics (include=%s, ex...
21,598
def test_reg_file_bad_type(tmp_path): """ Test that RegistryFile raises error about bad file type """ bad_path = tmp_path / "my_folder" bad_path.mkdir() with pytest.raises(PrologueError) as excinfo: RegistryFile(bad_path) assert f"Path provided is not a file {bad_path}" in str(excinfo.value)
21,599