content
stringlengths
22
815k
id
int64
0
4.91M
def test_no_global_imports_of_banned_package(): """This test ensures that neither of the banned packages are imported module wise in any of our code files. If one of the dependencies is needed, they should be imported within a function.""" banned_packages = ["spacy", "mitie", "sklearn", "duckling"] ...
69,900
def extract_text_subscribe(es: elasticsearch.Elasticsearch, pulsar_topics: str = "extract_text", pulsar_connection_string: str = "pulsar://localhost:6650"): """ :param es: :param pulsar_topics: :param pulsar_connection_string: :return: """ ...
69,901
def maildir_to_mailbox(maildir_path, mbox_path): """ slightly adapted from maildir2mbox.py, Nathan R. Yergler, 6 June 2010 http://yergler.net/blog/2010/06/06/batteries-included-or-maildir-to-mbox-again/ Port to Python 3 by Philippe Fremy """ # open the existing maildir and the target mbox fi...
69,902
def white_balance(img, mode='hist', roi=None): """ Corrects the exposure of an image based on its histogram. Inputs: img = An RGB image on which to perform the correction, correction is done on each channel and then reassembled, alternatively a single channel can be input but is not r...
69,903
def save_examples(queries, passages, neighbors_path, q_ids, max_cand, examples_path, is_training, train_eval=False): """Save examples for the given q_ids as TFRecords.""" encoded_passages_p...
69,904
def aes_encrypt(text, passphrase = None): """ Encrypt text with passphrase :param text: The text to be encrypted. :param passphrase: The key material :return: """ if not passphrase: passphrase = getpass.getpass('Enter passphrase: ').encode('utf-8') passphrase_cfm = getpass.ge...
69,905
def remove_host(mac, *args, **kwargs): """ Delete a host from the system Variables: mac => MAC Address of the host to be deleted Arguments: None Data Block: None Result example: {"success": True} """ STORAGE.delete_node(mac) return make_api_...
69,906
def get_ordered_tests(tests_setup, test_type): """Determines the order of tests to be run, filtered to only return the specified type. Args: tests_setup (dict): Map of test name to its configuration (see: res/test/translator.json). test_type (str): Which apps are to be tested. Must be one of "c...
69,907
def flip(message, txt): """ <text> -- Flips <text> over. :param message: Slackbot message object :param txt: Text to flip :return: Message to slack channel """ global table_status chan = message._body['channel'] text = txt.strip() if re.match(re_table, text): table_statu...
69,908
def cli(ctx, path, **kwds): """Create a Galaxy tool tarball. This will use the .shed.yml file to prepare a tarball (which you could upload to the Tool Shed manually). """ def build(realized_repository): tarpath = shed.build_tarball(realized_repository.path) outpath = realized_reposi...
69,909
def ilr(X: np.ndarray): """ Isometric Log Ratio transformation. Parameters --------------- X : :class:`numpy.ndarray` Array on which to perform the transformation, of shape :code:`(N, D)`. Returns -------- :class:`numpy.ndarray` ILR-transformed array, of shape :code:`(N...
69,910
def _stub_create_regularizer(op_slice, model_stub): """Create a StubOpRegularizer for a given OpSlice. Args: op_slice: A op_regularizer_manager.OpSlice. model_stub: Module name where REG_STUB and ALIVE_STUB will be found. Returns: StubOpRegularizer with stubbed regularization and alive vectors. ""...
69,911
def standard_method(row, iters): """ Given a tape represented as a row of Booleans, compute (in-place) the next row according to the Rule 110 ruleset. Assume that the tape wraps around to form a cylinder, i.e. for a tape of length `n`, column 0 is adjacent to column 1 and column n-1. Inputs: ...
69,912
def compute_mi(dataset, target_name, vocab, level=None): """ compute the mutual information for each token in a lexicon """ if not level: # bucket based on bottom/top 30% response = dataset.datafile_to_np( datafile=dataset.whole_data_files[target_name]) response = respons...
69,913
def split_code_to_cells(code): """converts code to a list of AbstractCell :param code: string representing the code :return: list of AbstractCell """ raw_cells = _split_to_raw_cells(code) return _raw_cells_to_cells(raw_cells)
69,914
def step_impl(context): """ :type context: behave.runner.Context """ context.browser.get('http://localhost:8000/accounts/login/') name_textfield = context.browser.find_element_by_name('username') name_textfield.send_keys('Douglas Phillips') price_textfield = context.browser.find_element_by_n...
69,915
def filter_out(word, infile, outfile): """ Reads a file line by line and writes an output file containing only the lines that DO NOT contains 'word'. """ print("Filtering out lines containing", word, "...") with open(infile, "r") as infile: lines = infile.readlines() with open(ou...
69,916
def slurmSrun(projName, libStart, libEnd, walltime, repeatDir, repeat, sliceCount): """ Create the srun SLURM script which will group all SLURM submissions together """ slurmName = projName + "_" + str(repeat) libRange = str(libStart) + "-" + str(libEnd) lines = [] lines.append("#!/bin/b...
69,917
def plot_prod_data_with_t0(job): """Generate plots for production data with t0 as a vertical line.""" import pandas as pd from reproducibility_project.src.analysis.equilibration import ( plot_job_property_with_t0, ) # plot t0 df = pd.read_csv(job.fn("log.txt"), delim_whitespace=True, h...
69,918
def present(name, service_name, auth=None, **kwargs): """ Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to cont...
69,919
def pytest_addoption(parser): """Add funcx-specific command-line options to pytest.""" parser.addoption( "--funcx-config", default="prod", help="Name of testing config to use" ) parser.addoption( "--endpoint", metavar="endpoint", help="Specify an active endpoint UUID" ) parser.ad...
69,920
def registration(request): """Render the registration page""" #redirect to the index page if user is authenticated if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": # create an instance of the reg form using values within the pos request # ...
69,921
def formatPageDataEvent(eventFormatter, topic, contributorId): """Format a PageData event. """ tm = time.strftime("%X") messageDict = { ROW_UPDATE: [ { ROW_NUM: 1, SPAN_UPDATE: [ { START_COL: 20, ...
69,922
def url_collapse_path(uripath): """Mimic standard lib's _url_collapse_path() but return a tuple That is, a tuple of path, trailing slash, everything else (query and fragment). The only other difference is that the path component will have at most one leading slash. The upstream namesake double-pre...
69,923
def compute_use_days(personnel): """计算已用天数 1/如果”改善状态”字段是“改善“,则等于改善日期-问题日期 2/如果"改善状态”字段是“持续“,则等于当前日期-问题日期 :param personnel:个人操作质量单条数据对象 :return:天数 """ use_day = 0 try: now_date = datetime.date.today() # 现在日期 improve_status = personnel.improve_status.name # 改善状态 improve_date = personnel.improve_date # 改善...
69,924
def layer_test(test_case, layer_cls, kwargs={}, input_shape=None, input_dtype=None, input_data=None, expected_output=None, expected_output_dtype=None, fixed_batch_size=False): """ Test routine for a layer with a single input tensor and single output tensor. """ if input...
69,925
def remove_special_char(in_seq): """ Function is responsible for normalize strings to defined format (UPPERCASE with '_' replacing any special character) :param in_seq: list of strings :return: list of strings """ _sub = re.sub(" {1,5}", "_", in_seq.strip()).lower() _chars = ['*', '\\', '&', '/', '+'] for x in ...
69,926
def register_stack( stack_name: str, metadata_store_name: str, artifact_store_name: str, orchestrator_name: str, container_registry_name: Optional[str] = None, secrets_manager_name: Optional[str] = None, step_operator_name: Optional[str] = None, feature_store_name: Optional[str] = None, ...
69,927
def _convert_one_samp(file_path_rain, file_path_norain, mode, crop_size, stride): """Proprocess the image pair of rain image(O) and background(B). Args: file_path_rain: The file path of the rain image. file_path_norain: The file path of the norain image, crop_size: Crop size for extract...
69,928
def make_annotation_set_public(annotation_set): """ Makes a given annotation_set public. """ logger.debug("Making annotation_set public: " + annotation_set.name) public_group, created = Group.objects.get_or_create(name='Public') assign_perm('view_annotationset', public_group, annotation_set)
69,929
def position_from_msg(tf_msg, fmt='xyz'): """Extract position from geomety_msg/TransformStamed message.""" return numpy.array([getattr(tf_msg.transform.translation, d) for d in fmt])
69,930
def test_relative_humidity_from_dewpoint_with_f(): """Test Relative Humidity accepts temperature in Fahrenheit.""" assert_almost_equal(relative_humidity_from_dewpoint(70. * units.degF, 55. * units.degF), 58.935 * units.percent, 3)
69,931
def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False): """Return the string to configure NAVIGATION_LINKS.""" f = u"""\ {0}: ( ("{1}/archive.html", "{2[Archive]}"), ("{1}/categories/{3}", "{2[Tags]}"), ("{1}/rss.xml", "{2[RSS feed]}"), ),"...
69,932
def fixture_spring_metadata( first_read, second_read, spring_tmp_path, checksum_first_read, checksum_second_read ): """Return metada information""" metadata = [ { "path": str(first_read.absolute()), "file": "first_read", "checksum": checksum_first_read, ...
69,933
def get_clocks(work, start_date = None, end_date = None, errant_clocks = None, case_sensitive = False, adjust_clocks = True): """Filter work by messages conataining the word 'clock' """ if errant_clocks is not None: work = work[~work.hash.isi...
69,934
def loss_K(loss_mat, Segmentation = False): """ TF function to calculate loss from the loss matrix: Inputs: y_true: true values (N,D) y_pred: predicted values (N,D) loss_mat: matrix of loss values for selecting outputs (D,D) """ loss_mat = tf.constant(loss_mat,dtype=tf.float32) if Segmentation: def lo...
69,935
def ActionClear( request, id, command ): """ Clear trash or cache folders and than redirect back """ if request.user.is_anonymous( ) and not settings.LIMITED_ANONYMOUS: return HttpResponseRedirect( '%s?next=%s' % (settings.LOGIN_URL, request.path) ) lib_id = int( id ) home = get_ho...
69,936
def ConvertArgsToSingleString(*args): """ :param *args: """ max_line_total, width_used, total_lines, = 0, 0, 0 single_line_message = '' # loop through args and built a SINGLE string from them for message in args: # fancy code to check if string and convert if not is not n...
69,937
def saveResults(filename, folder = VAR_DIR, **arrays): """Saves numpy arrays to a specified folder (defaults to a var folder outside verion control).""" file_path = os.path.join(folder, filename) if not(os.path.exists(folder)): os.makedirs(folder) np.savez(file_path, **arrays)
69,938
def pygame_simulation(pygame, first_click=False, folder=None, size=(1000, 1000), fLOG=fLOG, delay=200, flags=0): """ Simulation graphique. Illuste la résolution du puzzle :param pygame: module pygame :param first_click: attend la pression d'un clic de sou...
69,939
def diff_left(l1, l2): """ Computes which elements are in l1 but not in l2 :param l1: Array :param l2: Array :return: diff -> Array """ diff = l1.copy() for e2 in l2: for e1 in l1: if e1 == e2: diff.remove(e1) return diff
69,940
def calc_gradient_penalty(params, d_model, obs_mag, g_out, conditions, true_mag): """Calculate the gradient penalty Args: params: the hyperparameters used for training d_model: the Discriminator model obs_mag: the ground truth observed galaxy magnitudes g_out: the output of the ...
69,941
def _add_pos1(token): """ Adds a 'pos1' element to a frog token. """ result = token.copy() result['pos1'] = _POSMAP[token['pos'].split("(")[0]] return result
69,942
def sample_generator(dataset: tf.data.Dataset, n_workers: int = 4): """TF dataset -> python generator Args: dataset: n_workers: Thanks to @velikodniy """ iterator = dataset.make_one_shot_iterator() handlers = iterator.get_next() with tf.Session() as sess: @backgrou...
69,943
def check_JR(profile, committee): """Test whether a committee satisfies JR. Parameters ---------- profile : abcvoting.preferences.Profile approval sets of voters committee : set / list / tuple set of candidates Returns ------- bool Reference --------- Aziz,...
69,944
def save_hierarchy(interpretation, sset): """ This function adds all the hierarchy of a given *interpretation* in *sset*. """ node = interpretation while node is not None: # When an interpretation is already found in the set, we can stop. if node in sset: break ss...
69,945
def create_geoip_db(): """Open GeoIP DB if available, download if needed""" try: # Try to open an existing GeoIP DB geoip_db = open_database('GeoLite2-City.mmdb') return geoip_db except IOError: try: #Download GeoIP DB sys.stderr.write("\nCouldn't fi...
69,946
def dogecoin_ecc_start(): """Starts ecc context (required for running any key function).""" lib.dogecoin_ecc_start()
69,947
def reformat_comment(comment: str, add_tab=False): """ :param comment: :param add_tab :return: """ comment = re.sub(r'\s+', ' ', comment) sentence_len = 0 tmp = [] for word in comment.split(' '): if sentence_len >= 70: sentence_len = len(word) tmp.a...
69,948
def are_ensembles_created(path, number_of_ensembles): """Checks and reads the ensembles ids from the ensembles file in the path directory """ ensemble_ids = [] try: with open("%s%sensembles" % (path, os.sep)) as ensembles_file: for line in ensembles_file: ense...
69,949
def untokenize(words): """ Untokenizing a text undoes the tokenizing operation, restoring punctuation and spaces to the places that people expect them to be. Ideally, `untokenize(tokenize(text))` should be identical to `text`, except for line breaks. """ text = ' '.join(words) step1 = text.rep...
69,950
def test_is_symmetric_not_square(): """Input must be a square matrix.""" mat = np.array([[-1, 1, 1], [1, 2, 3]]) np.testing.assert_equal(is_symmetric(mat), False)
69,951
def ingest_running(): """ Starts up the fake ingest/metricproxy combo and also adds a write_http config to use that. Yields the final config with write_http configured and the ingest interface """ with fake_backend.run_all() as (ingest, mp_url): def render_config(config): re...
69,952
def parse_chebi_xml(filename): """Keeps data in lists so we can capture multiple values eventually, do not know what to expect at the moment. ChEBI keeps substance names in two places, <NAME> and <SYNONYM> tags. """ _chebi_id = None _definition = [] _names = [] # do not use list to keep or...
69,953
def run_formatters(session: Session) -> None: """Run all project formatters. Formatters to run: 1. isort with autoflake to remove all unused imports. 2. black for sinle style in all project. 3. add-trailing-comma to adding or removing comma from line. 4. isort for properly imports sorting. ...
69,954
def show_img(img_arr, label_arr, meta, index, label_fn=default_label_fn): """ Given a numpy array of image from CIFAR-10 labels this method transform the data so that PIL can read and show the image. Check here how CIFAR encodes the image http://www.cs.toronto.edu/~kriz/cifar.html """ one_img = img_...
69,955
def sexp2tree(sexp): """ Parameters ---------- sexp: list[str] Returns ------- NonTerminal Notes ----- Please note that the input ``sexp'' is assumed to be the raw version in RST-DT. So, if you want to convert a loaded S-expression after preprocessing, please use ``treetk.s...
69,956
def populate_db(session, total_users=3): """Populate database with total_users simulated users and their actions.""" users = generate_users(session, total_users) run_simulation(session, users)
69,957
def catl_sdss_dir(catl_kind='data', catl_type='mr', sample_s='19', catl_info='members', perf_opt=False, print_filedir=True, Program_Msg=fd.Program_Msg(__file__)): """ Extracts the path to the catalogues Parameters ---------- catl_kind: string, optional (default = 'data') type of cat...
69,958
def save_test_sample(real_imgs_lab, fake_imgs_lab1, fake_imgs_lab2, save_path, plot_size=14, scale=1.6, show=False): """ Create a grid of ground truth, grayscale and 2 colorized images (from different sources) and save + display it to the user. """ batch_size = real_imgs_lab.size()[0] plot_size ...
69,959
def wait_for_pool_ready( batch_client, blob_client, config, pool_id, addl_end_states=None): # type: (batch.BatchServiceClient, azure.storage.blob.BlockBlobCLient, # dict, str, List[batchmodels.ComputeNode]) -> # List[batchmodels.ComputeNode] """Wait for pool to enter steady state a...
69,960
def create_adv_inputs(states): """ Create the input for the ADV Net: cab-positions + psng-positions """ # For testing this only works for 2 agents and 2 passengers assert len(states) == 2 assert len(states[0]) == 11 # passengers are the same for all cabs pass1_x, pass1_y = states[0][7],...
69,961
def fizz_buzz(num): """ return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives, all depending on the argument of the function, a number that is divisible by, 3, 5, or both 3 and 5, respectively. """ if not isinstance(num, int): raise TypeError("Expected integer as...
69,962
async def create_oauth2(lb: LoadBalancer, name="oauth2", listener_port=5556, pool_port=32555, protocol="HTTP", algo="ROUND_ROBIN", members=None): """Convenience function to create an OAuth2 Client App Listener and Pool. Users need to deploy an OAuth2 Client App t...
69,963
def test_question_answer_correct0(): """Test correctness of the last answer added when is set to correct """ q = exam.Question("Who are you?") a1 = exam.Answer() a2 = exam.Answer() q.add_answer(a2) q.add_answer(a1, True) assert q.correct_answer == a1 assert q.correct_index == 1
69,964
def get_bodylength(data, tail_tag: str='', head_tag: str=''): """ get length of mouse body at all frames and avg length""" if not tail_tag or not head_tag: print('Need to have the name of the head and tail bodyparts to extract bodylength from DLC data') return False else: # Calculate...
69,965
def get_diagonal_quadface_from_2points(mesh,vi): """ similar to above: get_diagonal_polyline_from_2points from given 2diagonal vertices [iv1,iv3], get the whole diagonal quads [v1,v2,v3,v4] """ H = mesh.halfedges es1 = np.where(H[:,0]==vi[0])[0] es2 = np.where(H[:,0]==vi[1])[0] f1 = H[es...
69,966
def run_export(): """run export.""" net = get_network(backbone_name=config.backbone, args=config) assert config.pretrained is not None, "checkpoint_path is None." param_dict = load_checkpoint(config.pretrained) load_param_into_net(net, param_dict) config.height = config.train_image_size c...
69,967
def run_petronia(bus: EventBus, args: UserArguments) -> int: """ Run the actual Petronia program. """ if args.platform: platform_module = get_user_platform_module(args.platform) else: platform_module = get_platform_module() return run_platform_main(bus, platform_module)
69,968
async def async_setup_entry(hass, entry, async_add_entities): """Set up Guardian switches based on a config entry.""" guardian = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] platform = entity_platform.current_platform.get() for service_name, schema, method in [ (SERVICE_DISABLE_AP, None, "as...
69,969
def weighted_sw_index(matrix, n_avg=1, n_iter=1): """Calculate the weighted small world coefficient omega of a matrix.""" C = weighted_clustering_coeff_z(matrix) L = weighted_characteristic_path_length(matrix) indices = [] for i in range(n_avg): random_graph = random_reference(matrix, n_iter=n_iter) ...
69,970
def _print_failed_notebook_errors(failed_notebooks: Mapping[str, str]) -> None: """Print exceptions from failed notebooks.""" sys.stderr.write("\n") for failure, exp_repr in failed_notebooks.items(): sys.stderr.write(BASE_ERROR_MESSAGE.format(notebook=failure, exp=exp_repr)) sys.stderr.write( ...
69,971
def tracker(): """Creates a progress bar to gauge the evolution of the last function.""" with Progress() as progress: task = progress.add_task("[#F76E11]Processing...", total=160) while not progress.finished: progress.update(task, advance=1) time.sleep(3)
69,972
def prepare_file_path(filename): """ Checks filepath if it exists, otherwise create all necessary dirs @param filename: logging filename / filepath @return: None """ tmp = os.path.dirname(filename) if tmp: try: os.makedirs(tmp) except OSError as exception: ...
69,973
def test_add_study_route(initialize_test_db, api_client): """Test adding study records to metadata store""" response = api_client.post( "/studies", json={"id": "STU:1234567", "title": "Test study"} ) assert response.status_code == 200 study = response.json() assert "id" in study and stud...
69,974
def get_weatherdata_by_provider(provider, filepath=""): """Load weather data of one specified provider. args: provider (str) : provider that has to be present in the config return: no return """ # load credentials load_dotenv(os.path.join(filepath, ".env")) try: aut...
69,975
def apply_feature_filters_empty_test(): """Check for pass when no valid filters are provided.""" # capture -- mean: 1; stdv: 0; median: 1; min: 1; max: 1; len: 6 capture = [1, 1, 1, 1, 1, 1] filters = [] # No filter given -- pass pass_filters = filtering.apply_feature_filters(capture, filters) ...
69,976
def saveimg(img, path): """ img: numpy array of image. RGB. """ im = Image.fromarray(img) im.save(os.path.join(path))
69,977
def generate_cli(): """ Generate a simplistic command-line interface. """ parser = argparse.ArgumentParser() commands = parser.add_subparsers() validation = commands.add_parser('validation') validation.set_defaults(func=run_validation_suite) custom = commands.add_parser('custom') custom.set_defaults(func=ru...
69,978
def dict_to_cvode_stats_file(file_dict: dict, log_path: str) -> bool: """ Turns a dictionary into a delphin cvode stats file. :param file_dict: Dictionary holding the information for the cvode stats file :param log_path: Path to were the cvode stats file should be written :return: True """ ...
69,979
def _check_contains_na(X: pd.DataFrame, variables: List[Union[str, int]]) -> None: """ Checks if DataFrame contains null values in the selected columns. Parameters ---------- X : Pandas DataFrame variables : List The selected group of variables in which null values will be examined. ...
69,980
def isNumber(test): """ Test if the string is a valid number Return the converted number or None if string is not a number. """ try: test = str(test) if re.search('\.',test): try: return float(test) except: return None ...
69,981
def put(obj=None): #py:put """Puts down an object. If Reeborg carries more than one type of objects, the type must be specified as an argument, otherwise an exception will be raised. """ if obj is None: RUR._put_() else: RUR._put_(obj)
69,982
def add_instances_to_subnets(subnet_list, instance_list): """ Using the subnet nodes as father to build the instance nodes and adding them to the subnet nodes children """ if len(subnet_list) < 1: return [] # Sorting the instance list to avoid the search # when several instances are...
69,983
def assert_raises(error): """Context manager to assert that an error is raised. This can be nice if we don't want to clutter up a notebook with error messages. Parameters ---------- error: class inheriting from Exception or BaseException The type of error to catch, e.g. ValueError. Exa...
69,984
def default_pyinstaller_way(pyInstallerDir : str, pyInstallerZip : str,path_to_python : str) -> bool: """ if we failed in compiling the bootloader, we will just install the "plain" pyinstaller, and keep it up with the dropper """ if os.path.exists(pyInstallerDir): time.sleep(5) # we wait to...
69,985
def unskew_S1(S1, M, N): """ Unskew the sensivity indice (Jean-Yves Tissot, Clémentine Prieur (2012) "Bias correction for the estimation of sensitivity indices based on random balance designs.", Reliability Engineering and System Safety, Elsevier, 107, 205-213. doi:10.1016/j.ress.2012.06.0...
69,986
def deform_face_geometric_style(lms, p_scale=0, p_shift=0): """ deform facial landmarks - matching ibug annotations of 68 landmarks """ lms = deform_scale_face(lms.copy(), p_scale=p_scale, pad=0) lms = deform_nose(lms.copy(), p_scale=p_scale, p_shift=p_shift, pad=0) lms = deform_mouth(lms.copy(), p_sca...
69,987
def _inf_time_obs(rho,istate,Obs=False,delta_t_Obs=False,delta_q_Obs=False,Sd_Renyi=False,Srdm_Renyi=False,alpha=1.0): """ This function calculates various quantities (observables, fluctuations, entropies) written in the diagonal basis of a density matrix 'rho'. See also documentation of 'Diagonal_Ensemble'. The f...
69,988
def AnyListItemValidates(list_item_validator): """ Validate that at least one item in the list complies with 'list_item_validator'. """ @wraps(AnyListItemValidates) def _validate(value): if not isinstance(value, list): raise Invalid('expected a list') list_item_sche...
69,989
def get_array(pdi, field, name): """Gets an array from a vtkDataObject given its field association and name. Notes: - Point Data: 0 - Cell Data: 1 - Field Data: 2 - Row Data: 6 Args: pdi (vtkDataObject) : the input data object field (int or str) : the field ...
69,990
def save_images(input_imgs, output_imgs, epoch, path, offset=0, batch_size=64): """ """ input_prefix = "inp_" output_prefix = "out_" out_folder = "{}/{}".format(path, epoch) out_folder = os.path.abspath(out_folder) if not os.path.isdir(out_folder): os.makedirs(out_folder) ...
69,991
def main(): """ Main entrance of the functionality """ pars = argparse.ArgumentParser() pars.add_argument("-d", "--default", type=str, default=None, help="The fallback place to look for YAML information") args = pars.parse_args() if args.default: check_repo(arg...
69,992
def power_set(numbers: Set[int]) -> List[Set[int]]: """ Finds all subsets of the given set """ indexed_numbers: List[int] = list(numbers) result: List[Set[int]] = [] result.append(set()) for i in range(0, len(indexed_numbers)): subsets: List[Set[int]] = build_subsets( result, indexed_numbers[i] ) r...
69,993
async def on_dayssincetundexasked(ctx): """Responds with the days since Tundex last asked""" await dayssincetundexasked(ctx, JSON_FILEPATH)
69,994
def getBaseObject(object): """Return base object and dropSelf indicator for an object.""" if inspect.isbuiltin(object): # Builtin functions don't have an argspec that we can get. dropSelf = 0 elif inspect.ismethod(object): # Get the function from the object otherwise # inspec...
69,995
def split_list(l, break_pts): """returns list l split up into sublists at break point indices""" l_0 = len(l) sl = [] # Return a list containing the input list if no breakpoints indices selected if len(break_pts) == 0: return [l] # Else splits the list and return a list of sub lists. A...
69,996
def run(hive_context, showlog_table, keywords_mapping_table, create_keywords_mapping, start_date, end_date, load_minutes, keyword_threshold, effective_keywords_table): """ # This script goes through the showlog and identifies all the # keywords that comprise a portion of the overall traffic greater ...
69,997
def repr_dps(n): """Return the number of decimal digits required to represent a number with n-bit precision so that it can be uniquely reconstructed from the representation.""" dps = prec_to_dps(n) if dps == 15: return 17 return dps + 3
69,998
def _remove_rotating_file_handlers(logger: logging.Logger): """ Given a logging.Logger object, removes all BaseRotatingHandler handlers contained in 'logger.handlers'. If 'logger.handlers' does not have BaseRotatingHandler handlers, it's a no-op. :param logger: A logging.logger object. "...
69,999