content
stringlengths
22
815k
id
int64
0
4.91M
def prune_equal_fanin(model: torch.nn.Module, k: int = 2, validate: bool = True, device: torch.device = torch.device('cpu')) -> torch.nn.Module: """ Prune the dense layers of the network such that each neuron has the same fan-in. :param model: pytorch model :...
54,900
def reprojShapefile(sourcepath, outpath=None, newprojdictionary={'proj': 'longlat', 'ellps': 'WGS84', 'datum': 'WGS84'}): """ Convert a shapefile into a new projection sourcepath: (dir) the path to the .shp file newprojdictionary: (dict) the new projection definitions (default ...
54,901
def training(): """ Training grounds main (an edge of town menu item) """ vscr = game.vscr game.party.place = Place.TRAINING_GROUNDS mw = vscr.meswins[-1] vscr.cls() vscr.disp_scrwin() while True: mw.print( "\n*** training grounds ***\nc)reate a character\ni)nspec...
54,902
def filter_files(file_path, selected=('bacteria', 'virus')): """filter files based on filepath""" base = file_path.stem for s in selected: if s in base: return True return False
54,903
def test_cli_parse_file(mocker, runner): """ Ensures that parser command works properly """ m = mock.mock_open(read_data='foo') mocker.patch.object(io, 'open', m) e = runner.invoke(Cli.parse, ['/parse/path']) assert e.output == """File: /parse/path start block rules service_bloc...
54,904
def test_get_set_emits_change_event() -> None: """Test that basic attribute getters and setters emits a change event.""" subscriber = Mock() mapping = DummyMapping() mapping.changed.subscribe(subscriber) mapping["key"] = "value" assert mapping["key"] == "value" subscriber.assert_called_once(...
54,905
async def _parse_at(text: str): """ @人格式:“@UID ”(注意最后有空格) Args: text (str): 原始文本 Returns: tuple(str, int[], dict): 替换后文本,解析出艾特的 UID 列表,AT 数据 """ pattern = re.compile(r"(?<=@)\d*?(?=\s)") match_result = re.finditer(pattern, text) uid_list = [] names = []...
54,906
def train(model, dataloader, optimizer, epoch, n_epochs, log_interval=100, device='cpu'): """ Train the model. Args: model -> Model for training. dataloader -> Dataloader. optimizer -> optimizer. epoch -> Current Epoch number (1 <= epoch < n_epochs) n_epochs -> Total...
54,907
def mask_rcnn(features, mode, params, labels=None, class_targets=None, box_targets=None, box_rois=None, proposal_to_label_map=None, detections=None): """Mask-RCNN mask model. This is the mask part of the model (Mask-RCNN), which generates mask outputs. In addition, it also generates m...
54,908
def global_phik_from_rebinned_df(data_binned:pd.DataFrame, noise_correction:bool=True, dropna:bool=True, drop_underflow:bool=True, drop_overflow:bool=True) -> Tuple[np.ndarray, np.ndarray]: """ Global correlation values of bivariate gaussian derived from chi2-value from rebinned...
54,909
def findInWorkDir(filename): """Find a file name in user's work directory.""" return findFile(filename, sciflo.grid.getRootWorkDirFromConfiguration())
54,910
def find_cheats(**kwargs): """ Find cheat notes according to keywords """ # Load config defaults config = load_config() if config is None: logger.error('No valid config file found. Consult README.md') sys.exit(1) filetypes = config.search['filters'] if config.search.get('filters'...
54,911
def get_tfrecords(dset_dir, split='train'): """Get tfrecords that match training, validation, and test sets. Works off the TfSet protobuf. Args: dset_dir: dataset directory of tfrecords. split: train or eval. Returns: Relevant tfrecords from dset_dir. Raises: IOError: if tfset.pbtxt protob...
54,912
def VerboseCompleter(unused_self, event_object): """Completer function that suggests simple verbose settings.""" if '-v' in event_object.line: return [] else: return ['-v']
54,913
def blend2(*args, **kwargs): """ This command creates a surface by blending between given curves. Returns: `string[]` Object name and node name """ pass
54,914
def jpeg_dynamic_quality(original_photo, use_dynamic_quality=True): """Return an integer representing the quality that this JPEG image should be saved at to attain the quality threshold specified for this photo class. Args: original_photo - a prepared PIL JPEG image (only JPEG is supported) """...
54,915
def gen_formats(fmt): # type: (srcgen.Formatter) -> None """Generate an instruction format enumeration""" fmt.doc_comment(''' An instruction format Every opcode has a corresponding instruction format which is represented by both the `InstructionF...
54,916
def load_input_into_list(): """ Takes our input and returns it into a comprehensive list with split terms :return: The list of lists for our input :rtype: list """ return [line.replace('-', ' ').replace(':', '').split(' ') for line in open("inputs/day2_01.txt", "r").read().splitlines()]
54,917
def isImageValid(img_path: str, min_sz: int = 256): """Validates whether the input image fits for the training/test procedure""" img = Image.open(img_path) if min(img.size) < min_sz or img.layers != 3: return False else: return True
54,918
def SplitClovisTask(task): """Splits a ClovisTask in smaller ClovisTasks. Args: task: (ClovisTask) The task to split. Returns: list: The list of ClovisTasks. """ # For report task, need to find the traces first. if task.Action() == 'report': trace_bucket = task.ActionParams().get('trace_bucket...
54,919
def load_cifar5(random_state=42): """Loads the datasets for CIFAR5 vs CIFAR5. In-Distribution: 'dog', 'frog', 'horse', 'ship', 'truck' Out-of-Distribution: 'airplane', 'automobile', 'bird', 'cat', 'deer' Args: random_state (int): The random state used for the train validation split. ...
54,920
def fake_config_dir(request, tmp_path, monkeypatch): """Isolate tests. Avoid interference of an existing config dir in the developer's machine """ if "no_fake_config_dir" in request.keywords: # Some tests need to check the original implementation to make sure # side effects of the sh...
54,921
def test_get_with_default_from_portfolio_value_by_startyear_by_allocation(): """tests get_statistics_by_allocation""" portfolio_returns_by_allocation = portfoliofinder.Returns(EXPECTED_SPECIFIC_RETURNS, EXPECTED_PORTFOLIO_ALLOCATIONS) portfolio_v...
54,922
def MC2000BGetFrequency(hdl,frequency): """ Get the internal reference frequency Args: hdl: the handle of opened MC2000B device frequency:get internal reference frequency Returns: 0: Success; negative number: failed. """ val = c_int(0) ret = GetFrequency(hdl,val) fr...
54,923
def p(*args): """ Convenience function to join the temporary directory path with the provided arguments. """ return os.path.join(temp_dir, *args)
54,924
def decrypt_paste(encrypted: bytes, key: bytes) -> str: """Decrypts a Pastegram paste""" iv = encrypted[:12] encrypted_message = encrypted[12:-16] tag = encrypted[-16:] cipher = AES.new(key, AES.MODE_GCM, iv) contents = cipher.decrypt_and_verify(encrypted_message, tag) return contents.decode...
54,925
def DistanceTest(tester, leftFile, rightFile, diffFile, htmlFile): """ General distance test function """ options = OOO() diffCount = 0 left = XmlRfcParser(leftFile, quiet=True, cache_path=None, no_network=True).parse() left = BuildDiffTree(left.tree, options) right = XmlRfcParser(rightFile, qui...
54,926
async def list_(hub, ctx, top=None, expand=None, **kwargs): """ .. versionadded:: 1.0.0 List all resource providers for a subscription. :param top: The number of results to return. Default returns all providers. :param expand: The properties to include in the results. For example, use 'metadata' ...
54,927
def get_bccaqv2_opendap_datasets( catalog_url, variables: List[str] = None, rcp: str = None, method: ParsingMethod = ParsingMethod.filename, models=None, ) -> List[str]: """Get a list of urls corresponding to variable and rcp on a Thredds server. We assume that the files are named in a cert...
54,928
def test_calculate_nodata(statsdict): """Set results for a key to None if no data""" measure = CountStore() key = '42' calc = SQLTimeSeries(statsdict=statsdict, countstore=measure) empty = DataFrame() calc.__enter__() calc.calculate(key, empty, empty, empty) vals = calc.vals assert v...
54,929
def poll_single_alert(outdir: str) -> (str, dict): """ Connect to and poll fink servers once. Parameters ---------- outdir: str Directory to store incoming alerts. It must exist. Returns --------- topic: str Topic name. None if no alert has been returned from the servers. ...
54,930
def show_passwd(): """显示所有账户""" global passwd_infor print("官网\t用户名\t密码\t邮箱\t手机号") for temp in passwd_infor: print("%s\t%s\t%s\t%s\t%s" % (temp["net"], temp["name"], temp["passwd"], temp["email"], temp["phone"]))
54,931
def computeTF(doc_info,freqDict_list): """ tf =(frequency of the term in the doc/total number of terms in the doc :param doc_info: :param freqDict_list: :return: """ TF_scores =[] for tempDict in freqDict_list: id = tempDict['doc_id'] for k in tempDict['freq_dict']: ...
54,932
def render_pretty_expression(expr, indent = ''): """Renders a node to a string in a pretty way.""" if isinstance(expr, list): if expr != [] and expr[0] in ['declare-const', 'declare-fun']: return render_expression(expr) if all(map(lambda e: not isinstance(e, list), expr)): ...
54,933
def assign_fingerprint_wells(fingerprint, treatment, dose): """Returns a set of wells along the edge that serve as barcode for the plate based on the fingerprint word Parameters ---------- fingerprint : str treatment : str the drug used to treat fingerprint wells dose : float ...
54,934
def parent_request(parent_request_dict, ts_dt): """A parent request as a model.""" dict_copy = copy.deepcopy(parent_request_dict) dict_copy["created_at"] = ts_dt dict_copy["updated_at"] = ts_dt dict_copy["status_updated_at"] = ts_dt return Request(**dict_copy)
54,935
def generateBackground(df): """(pd.DataFrame)->pd.DataFrame generate data used as prediction background """ x, y = df.columns[2:4] minX, maxX = df.iloc[:, 2].min(), df.iloc[:, 2].max() minY, maxY = df.iloc[:, 3].min(), df.iloc[:, 3].max() # here are about 90000 points, it will slow down the ...
54,936
def convert_pool2d(g, op, block): """Operator converter for pool2d.""" adaptive = op.attr("adaptive") ceil_mode = op.attr("ceil_mode") global_pooling = op.attr("global_pooling") ksize = op.attr("ksize") paddings = op.attr("paddings") padding_algorithm = op.attr("padding_algorithm") pool...
54,937
def spark_filter(func: typing.Callable[[pyspark.rdd.RDD], pyspark.rdd.RDD]=default_function(1)): """Spark's filter :param Callable func: The function to apply. :input RDD data: The RDD to convert. :output RDD result: The resulting RDD. """ def inner(data: pyspark.rdd.RDD) -> ReturnType[pyspark....
54,938
def load_sample(filename): """Helper to get the content out of the sample files""" with open(os.path.join(SAMPLES, filename)) as f: return f.read()
54,939
def test_sph_harm_sft(): """ Tests the SFT by doing SFT -> ISFT -> SFT -> ISFT """ f = np.random.rand(16, 16) coeffs = spherical.sph_harm_transform(f) # we are constraining the bandwidth to n/2 here, so f1 != f f1 = spherical.sph_harm_inverse(coeffs) coeffs1 = spherical.sph_harm_transform(f1) ...
54,940
def test_rnn_discriminator(): """Tests the RNNDiscriminator.""" # pylint: disable=unused-variable batch_size = 3 vocab_size = 32 tok_emb_dim = 10 rnn_dim = 4 debug = True d = _RNNDiscriminator(**locals()) preds = d(Variable(torch.LongTensor(batch_size, 20).fill_(1))) assert pre...
54,941
async def async_api_turn_on(hass, config, directive, context): """Process a turn on request.""" entity = directive.entity domain = entity.domain if domain == group.DOMAIN: domain = ha.DOMAIN service = SERVICE_TURN_ON if domain == media_player.DOMAIN: supported = entity.attribute...
54,942
def configure_time_synchronization(upstream, chrony=True): """2.2.1 Time Synchronization""" if chrony: configure_chrony(upstream) else: configure_ntp(upstream)
54,943
def d10(test, part): """Day 10 commands""" data = fileutils.load_lines(10, test) fn = { 1: part_1, 2: part_2, }.get(part) fn(data)
54,944
def calculate_r_effective(df: pd.DataFrame, window_length: int = 7) -> pd.Series: """Calculate the effective reproduction number, :math:`R_e`. More explanation can be found in the `Wikipedia article <Wikipedia>`_. Note: The infection counter is only reset to zero once a person becomes infected aga...
54,945
def test_peek_empty_dequeue(build_empty_dequeue): """Test peek method for empty queue.""" assert build_empty_dequeue.peek() is None
54,946
def hydration(workspace): """Function for calculating hydration quantities Args: workspace (dict): workspace or dictionary with 'hydration_inputs', see above Returns: results (dict) : 'hydration_results' dictionary, see above Raises: TypeError: If 'hydration_inp...
54,947
def nb_permutations(word): """Retourne le nombre de permutations possibles d'un mot. >>> nb_permutations("AAB") 3 >>> nb_permutations("ABC") 6 """ num = factorial(len(word)) mults = Counter(word).values() den = reduce(operator.mul, (factorial(v) for v in mults), 1) return int(nu...
54,948
def test_X2_Y2(augmenter): """ 2D X, 2D Y """ X_aug, Y_aug = augmenter.augment(X2, Y2) assert X_aug.shape == ( N * augmenter.repeats, T if not isinstance(augmenter, (Resize, Crop)) else int(T / 2), ) assert Y_aug.shape == ( N * augmenter.repeats, T if not isin...
54,949
def escape(data, entities={}): """Escape &, <, and > in a string of data. You can escape other strings of data by passing a dictionary as the optional entities parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. """ data = data.replace("&...
54,950
def rand(sharding_spec: ShardingSpec, *size, dtype=None, layout=torch.strided, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format, process_group=None, init_rrefs=False) -> ShardedTensor: """ Returns a :class:`Shard...
54,951
def live_plt( queue, title, x_limit, y_top_limit, y_bottom_limit, x_label, y_label, dir_fig, file_fig, ): """ Plots the data from the queue. If the queue is empty the function waits for new input. Args: queue: Queue with the data that is to be plotted...
54,952
def UploadPerfData(master_name, perf_id, test_name, builder_name, build_number, revision, perf_data, point_id, dry_run=False, testing_dashboard=True): """Uploads perf data. Args: Please see the help for command-line args. Returns: A boolean value indicating whether ...
54,953
def prediction_change_finder(old, new, labels, class_names, phase): """[summary] Args: old (Python list): List of predictions from the Nearest Neighbour on the features directly from the feature extractor. new (Python list): List of predictions on the embedding after being trained on any desire...
54,954
def create_model_area_preferences(apps, schema_editor, **kwargs): """ Make sure that all existing model areas have preference objects assigned :param apps: :param kwargs: :return: """ ModelArea = apps.get_model("waterspout_api", "ModelArea") ModelAreaPreferences = apps.get_model("wat...
54,955
def add(x: int, y: int) -> int: """Add two int numbers.""" return x + y
54,956
def parse(manifest_path, defaults): """ Parses a valid emane manifest file and converts the provided configuration values into ones used by core. :param str manifest_path: absolute manifest file path :param dict defaults: used to override default values for configurations :return: list of core conf...
54,957
def plotEigenvalues(x: np.ndarray): """ @param x: contains the matrix for which the eigenvalues are computed @return: plots the eigenvalues of the given matrix x """ print("Plotting eigenvalues") eigenvalues, _ = np.linalg.eigh(x) eigenvalues = eigenvalues[::-1] max_val = np.max(eigenval...
54,958
def main(): """ parses arguments and get route ID passing by station given as argument """ if len(sys.argv) < 3: log(f'{sys.argv[0]} <input-dir> <station-name> [csv-cffi]') sys.exit(1) inputdir = os.path.expanduser(sys.argv[1]) station_name = str(sys.argv[2]) # TODO use argparse i...
54,959
def test_slack_celery_shutdown_callback(default_options, webhook, mocker): """Test the slack celery shutdown callback.""" these_options = locals() these_options.pop("default_options") these_options.pop("mocker") options = get_options(default_options, **these_options) mocked_post_to_slack = mocke...
54,960
def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly after linearly increasing during a warmup period. From: https://github.com/uds-lsv/bert-stable-fine-tuning/blob/master/src/transfor...
54,961
def otc(): """ Return spr for otc in period """ if request.method == "GET": return redirect(url_for("insertdata", name="otc")) f_data, l_data = get_user_dates_or_return_today() title = "otc" query = queryes["otc"] query_result = con_to_firebird( query, ( ...
54,962
def compute_target_weights(context, data): """ Compute ordering weights. """ # Initialize empty target weights dictionary. # This will map securities to their target weight. weights = {} # If there are securities in our longs and shorts lists, # compute even target weights for each sec...
54,963
def fit_databoxes_model(ds, model, xscript=0, yscript=1, eyscript=None, command="", settings={}, **kwargs): """ Loops over the supplied databoxe(s) and fits them using the supplied model kwargs are sent to "data.load_multiple()" which are then sent to "data.standard()". Useful ones to keep in m...
54,964
def ProcessOptionMultiprocessingParameters(ParamsOptionName, ParamsOptionValue): """Process parameters for multiprocessing and return a map containing processed parameter names and values. Arguments: ParamsOptionName (str): Command line multiprocessing parameters option name. ParamsOpti...
54,965
def salt_password(password, salt=None, hash_name='sha1'): """Generate hashed password with salt hash(password + salt) if salt is not given, generate_random_code will be used for generating the salt value """ if isinstance(password, unicode): password = password.encode('utf8') if isinst...
54,966
def _perm_find(arr, x): """ Find permutation cutoff in array. """ return np.sum(np.abs(arr) >= np.abs(x)) / float(len(arr))
54,967
def rayleigh_ritz(A, B, U): """ Rayleigh-Ritz procedure. Extended for general eigen value problems e.g. Ax = λBx. Parameters ---------- A : (n, n) array_like A real or complex matrix of shape (n, n). Matrix A in eigen value problems Ax = λBx. B : (n, n) array_like A ...
54,968
def get_max_text_size(lines: List[str], font: str) -> Size: """Return the approximate size in pixels of the smallest bounding box that can enclose every line of text at a font size of 1pt""" font_file = findfont(font) font_image = PILtruetype(font_file, size=1000) text_sizes = map(font_image.getsize, li...
54,969
def parse_response(response): """ Function used to remove the extra chars from the respone (bytes type) after it was converted to string, Base64 decode it and decrypt it The function will return an array, the first 3 elements will be memory, cpu usage and uptime. All elements after that will have th...
54,970
def get_file(file_path): """ 获取给定目录下的所有文件的绝对路径 :param file_path: 文件目录 :param pattern: 默认返回所有文件,也可以自定义返回文件类型,例如:pattern="*.py" :return: 文件路径列表 """ all_file = [] files = pathlib.Path(file_path) f = files.rglob('*.md') for file in f: pure_path = pathlib.PurePath(str(file)) ...
54,971
def sachdr2origin(header): """ Provide a sac header dictionary, get a filled origin table dictionary. A few things: 1) If sac reference time isn't event-based, origin time is unknown 2) magnitude is taken first from hdr['mag'], hdr['imagtyp'] if defined, then replaced by hdr['user0'],hdr['kus...
54,972
def input_board(layer: List[str], grid: List[str], coord: Tuple[int,int], flag: Optional[str]=None) -> bool: """ Function to test a coordinate on the board either revealing a mine or a number Args: layer: List[str]: a list of all uncovered values of the gameboard to show to the player grid: Lis...
54,973
def gauss_to_tesla(gauss): """Converts gauss to tesla""" return gauss*1e-4
54,974
def main() -> None: """Establish and run REST server.""" logging.basicConfig(level=logging.DEBUG) args = RestHandlerSetup({"auth": {"secret": "secret"}, "debug": True}) args["fruit"] = {} # this could be a DB, but a dict works for now server = RestServer(debug=True) server.add_route("/api/fru...
54,975
def test_map_remote_schema_ref(schema, expected_schema): """ GIVEN schema and context WHEN _map_remote_schema_ref is called with the schema and context THEN the expected schema is returned. """ # pylint: disable=protected-access context = "doc.ext" returned_schema = ref_helper._map_remo...
54,976
def quick_sort(arr, first, last): """ Quicksort Complexity: O(n log(n)) """ if first < last: pos = partition(arr, first, last) # Start our two recursive calls quick_sort(arr, first, pos-1) quick_sort(arr, pos+1, last)
54,977
def _build_plugin_invocation(name, plugin, execdir, builder): """Add a '--plugin=NAME=PATH' argument if the language descriptor requires one. """ tool = _get_offset_path(execdir, plugin.path) builder["inputs"] += [plugin] builder["args"] += ["--plugin=protoc-gen-%s=%s" % (name, tool)]
54,978
def draw_free_energies(entry_list, label='', T_min=300, T_max=2000, legends=None, size=4): """ Plot the Gibbs free energy of a common species from two different library entries Args: entry_list (list): A list of RMG Thermo Entry or Entry.data label (str): The species label used for the figu...
54,979
async def test_drop_tip_with_trash(session_manager, protocol, protocol_file): """ Bradford Assay is using drop_tip() with no arguments that assumes tip drop into trash-box. In this test we are confirming that that trash location is being inferred from a command, and trash is listed as a container fo...
54,980
def linearPolar(src, center, maxRadius, flags, dst=None): """ linearPolar(src, center, maxRadius, flags[, dst]) -> dst """ pass
54,981
def main(): """The main function. Returns: None. """ for i, G in enumerate(generate_graphs()): print(f"G{i} is " f"{nx.node_connectivity(G)}-connected and " f"{nx.edge_connectivity(G)}-edge connected.")
54,982
def su_decon(fname, d_inp, d_out, pnoise, **kwargs): """ Wiener deconvolution using SU's sushape function. d_inp : 1d array Notes ----- Is shaper a matrix? Bash complains about too long list of arguments => trough files. """ from fullwavepy.ioapi.su import array2su from fullwavepy.nd...
54,983
def create_artefact_file(artefact_path: str, artefact_kind: str) -> str: """ Create artefat file with specified PreLoadFilePath and kind :param artefact_path: artefact file PreLoadFilePath :param artefact_kind: artefact file kind :return: artefact file srn (ResourceID) """ logger.info("Crea...
54,984
def blue_channels(ibands_image, mbands_image, fc_image): """ Create plot of RBG blue layer for fc, ibands, mband """ blue1 = ibands_image.channel('blue') blue2 = mbands_image.channel('blue') blue3 = fc_image.channel('blue') blues = plt.figure() blues.suptitle("RBG blue layer for fc...
54,985
def docs(session: nox.Session) -> None: """ Build the docs. Pass "serve" to serve. """ session.install(".[docs]") session.chdir("docs") session.run("sphinx-build", "-M", "html", ".", "_build") if session.posargs: if "serve" in session.posargs: print("Launching docs at h...
54,986
def preprocess_labels(y, y_name=None, index=None, verbose=0): """ Does basic preparation of the labels. Turns them into Series, and wars in case the target is not binary. Args: y (pd.Series, list, np.array): Provided labels. y_name (str, optional): Name of the y variable, that will...
54,987
def G3_SF(tensors, cutoff_type, rc, lambd, zeta, eta, i="ALL", j="ALL", k="ALL"): """BP-style G3 symmetry functions. NOTE(YS): here diff_jk is calculated through diff_ik - diff_ij instead of retrieving the distance calcualted in cell_list_nl. This makes is easier to get the jacobian with grad(sf, [dif...
54,988
def createKey(problemData): """ Creates the key for a given 'problemData' list of number of item types. """ key = '' for itData in problemData: key += str(itData) + ',' # Remove the last comma return key[:-1]
54,989
def tier_2_client_turnover(): """ Real Name: Tier 2 Client Turnover Original Eqn: Tier 2 Clients/Client Lifetime Units: Persons/Month Limits: (None, None) Type: component Subs: None This is the flow of Tier 2 clients leaving the practice. """ return tier_2_clients() / client_lif...
54,990
def create_app(): """Creates and returns the Flask WSGI application and initializes helping components""" # Initialize json support for wtforms wtforms_json.init() # Define the WSGI Application object app = Flask(__name__) # Configurations app.config.from_object('server.config') #...
54,991
async def provider(config, suite): """Get provider to test subject.""" if not 'provider' in config and not config['provider']: raise "No 'provider' was specified in the config file" path_parts = config['provider'].split('.') mod_path, class_name = '.'.join(path_parts[:-1]), path_parts[-1] mo...
54,992
def _ebtranslateErrors(failure): """This just re-raises the failure so that the translateErrors decorator around this errback can intercept it if it wants to.""" failure.raiseException()
54,993
def test_process_event(n, e, l, s, i, os, kput, fput, boto3_client, monkeypatch): """Process events.""" notification = {"Records": [{} for _ in range(n)]} process_event(notification, None, "e", "l", "s", i, os) assert boto3_client("kinesis").put_records.call_count == kput ass...
54,994
def start_cluster(seed_data, cluster): """Bring up cassandra on cluster nodes, SEEDs first""" # Start SEED nodes first. print("=> Starting cassandra cluster SEED nodes") started_nodes = [] for node in seed_data: node_start_cassandra(node['zone'], node['name']) started_nodes.append(no...
54,995
def forward_step(alpha,u,uPrev,N): """ Steps forward-euler algo one step ahead. Implemented in a separate function for code-reuse from crank_nicolson() """ for x in xrange(1,N+1): #loop from i=1 to i=N u[x] = alpha*uPrev[x-1] + (1.0-2*alpha)*uPrev[x] + alpha*uPrev[x+1]
54,996
def get_slug_from_request(request): """Returns the slug of the currently displayed category. """ slug = request.path.split("/")[-1] try: int(slug) except ValueError: pass else: slug = request.path.split("/")[-2] return slug
54,997
def debug_enclave_driver(name, enclaves, **kwargs): """Wraps cc_binary with dependency on enclave availability at runtime. Creates a cc_binary for a given enclave. The cc_binary will be passed '--enclave_path=<path to instance of |enclave|>' for 1 enclave, or '--<enclave_name>=<path to instance of |enclave_n...
54,998
def even_or_odd(value: int) -> bool: """ BIG-O Notation = O(1) """ return value % 2 == 0
54,999