content
stringlengths
22
815k
id
int64
0
4.91M
def svg_icon(loader, name, css_class=""): """ Return inline SVG markup for an icon. This is a helper for generating inline SVGs for rendering icons in HTML that can be customized via CSS. See https://github.com/blog/2112-delivering-octicons-with-svg To color an icon dynamically (eg. on hover),...
75,000
def modprobe(ctx, config): """ Load the rbd kernel module.. For example:: tasks: - ceph: - rbd.create_image: [client.0] - rbd.modprobe: [client.0] """ log.info('Loading rbd kernel module...') for role in config: (remote,) = ctx.cluster.only(role).remotes...
75,001
def _check_task(taskid): """Check Spinnaker Task status. Args: taskid (str): Existing Spinnaker Task ID. Returns: str: Task status. """ try: taskurl = taskid.get('ref', '0000') except AttributeError: taskurl = taskid taskid = taskurl.split('/tasks/')[-1] ...
75,002
def test_validate_item_fields() -> None: """ Scenario: Validate arguments for creating / updating items before sending to API. Given: - User has provided valid credentials. - Headers and JWT token have been set. When: - When add/update_item is called. Then: - Ensure corr...
75,003
def right_stop(G, adorn=True): """ Compute the (adorned) right stop of G. Parameters ---------- G : Game The Game of interest. adorn : bool Whether to adorn the stop or not. Defaults to True. Returns ------- RS : Game The right stop of G. initiative : st...
75,004
def value_and_multigrad(fun, argnums=[0]): """Returns a function that returns both value and gradients wrt multiple arguments simultaneously.""" def combined_arg_fun(multi_arg, *args, **kwargs): extra_args_list = list(args) for argnum_ix, arg_ix in enumerate(argnums): extra_args_...
75,005
def generateCycles(maximum_divisor): """Generate a list where longestCycles[n] contains the length of the cycle with the longest period for 1/i for i <= n""" primeIndex = 0 nextPrime = primes[primeIndex] longestCyclePeriod = 0 longestCycleValue = 0 i = 1 while i <= maximum_div...
75,006
def test_OnePortRaw_to_XmlDataTable(input_file="OnePortRawTestFile.txt"): """Tests a one port raw ascii data table to an XmlDataTable transformation and saves the result in the tests directory. The one port file should be the output of Meas HP Basic program or similar. Average time without print is 7.2 ms f...
75,007
def set_data_dir(data_dir): """Sets the data directory. Args: data_dir (str): Path to the data folder. """ global DATA_DIR DATA_DIR = data_dir
75,008
def test_merge_interpolate_py(): """Merge with interpolate.""" context = Context() context.merge({"key": PyString("True")}) assert context["key"] is True
75,009
def deploy_disk_image(address, port, iqn, lun, image_path, node_uuid, configdrive=None, conv_flags=None): """All-in-one function to deploy a whole disk image to a node. :param address: The iSCSI IP address. :param port: The iSCSI port number. :param iqn: The ...
75,010
def read_tracking_data_txt( filepath_txt: Union[str, Path], links: Dict[str, Dict[int, int]] = None, ) -> Tuple[XY, XY, XY, XY, XY, XY]: """Parses a StatsPerform .txt file and extracts position data. Internal StatsPerform position data is stored as a .txt file containing all position data (for bo...
75,011
def loop(msg): """This is for creating loop to give the user options""" for i in msg: print(i, end=", ")
75,012
def dimension_reduction(csv_path: str, path_to_chunks: str = "../data/chunks", chunksize: int = 1000, verbose=0): """Reduce dimension of the 0.5 nm resolution spectra. To reduce the dimension of the dataset, we aim for 256 spectral channel...
75,013
def main(): """A simple test runner. This test runner is essentially equivalent to `unittest.main` from the standard library, but adds support for tornado-style option parsing and log formatting. The easiest way to run a test is via the command line:: python -m tornado.testing tornado.tes...
75,014
def _estimate_segments(df: pd.DataFrame, target_field: str = None, max_segments: int = 30) -> Optional[Union[List[Dict], List[str]]]: """ Estimates the most important features and values on which to segment data profiling using entropy-based methods. If no target column provided, maximum entropy column...
75,015
def show_images(images, file_to_save, cols=1, titles=None): """Display a list of images in a single figure with matplotlib. Parameters --------- images: List of np.arrays compatible with plt.imshow. cols (Default = 1): Number of columns in figure (number of rows is set to n...
75,016
def WT_EC50s(unkVec_2_15, Traf=True): """Returns dataframe of the Wild Type EC50s""" df = pd.DataFrame(columns=["Time Point", "Cell Type", "IL", "Data Type", "EC50"]) x0 = [1, 2.0, 1000.0] tps = np.array([0.5, 1.0, 2.0, 4.0]) * 60.0 data_types = [] cell_types = [] EC50s_2 = np.zeros(len(cel...
75,017
def implicit_op(op): """ implicit constant operand promotion """ if isinstance(op, ML_Operation): return op elif isinstance(op, SollyaObject) or isinstance(op, int) or isinstance(op, float): return Constant(op) elif isinstance(op, ML_FloatingPointException): return Constant(op, p...
75,018
def ToHex(data): """Return a string representing data in hexadecimal format.""" s = "" for c in data: s += ("%02x" % ord(c)) return s
75,019
def set_legend(ax, size=12, color=COLORS['black'], alpha=ALPHAS['translucent'], loc='best', frame=False, ncol=1, nscatter=1, **kwargs): """ Add and modify legend settings. :param ax: (mpl.axes) - plot axis :param size: (str) - size of legend labels :param color: (str) ...
75,020
def fill_missing_test(parameters: List[Parameter]) -> Tuple[str]: """Convenience function for testing job parameter fill missing""" param_set = JobParameterSet(parameters) param_set.fill_missing_parameters() return ( param_set.get_param_by_type(PseudoID).value, param_set.get_param_by_typ...
75,021
def start_dcd_server(): """Start dcd server.""" def filter_nondirs(server_args): """Remove non existent dirs from server args.""" f_args = [] for item in server_args: m = re.match(r"-I(.+)", item) if m: dir_name = m.group(1) if not...
75,022
def test_PostPlot(): """Validation of the PostPlot class to plot airgap flux automatically as postprocessing at the end of the simulation""" IPMSM_A = load(join(DATA_DIR, "Machine", "IPMSM_A.json")) simu = Simu1(name="PostPlot", machine=IPMSM_A) # Definition of the enforced output of the electrical m...
75,023
def parse_date(date_str: str, sep: str = None, format: str = None) -> datetime.date: """Returns a ``datetime.date`` if possible Args: date_str (str): The date which may not be in standard ISO format sep: Optional. The separator used to separate each time unit format: Optional. Format of...
75,024
def PopUp_Connect(): """The function PopUp_Connect() displays a pop up window if the connection failed If the user presses "yes", connection of the stages starts again If the user presses "no", it closes all the windows """ answer = msg.askyesno("Stage connection","Attempt to connect the stages failed. Do you wan...
75,025
def scrub_properties(orig_props): """Scrubs fields in API object properties for use in DM properties. Scrubbed fields include: - output-only fields common for most resources - output-only fields specific to a particular resource type Args: orig_props: the resource properties that need to be scrubbed ...
75,026
def _trend_grid(concentration_cube, weight_cube, *, clipping_threshold): """Build a grid for a decadal trend.""" assert concentration_cube.shape == weight_cube.shape assert clipping_threshold rows, cols, periods = weight_cube.shape # Flatten rows and cols of the concentration/weight cubes # A ...
75,027
def uniquify_reference_names(comp): """Replaces all the bound reference names in `comp` with unique names. Notice that `uniquify_reference_names` simply leaves alone any reference which is unbound under `comp`. Args: comp: The computation building block in which to perform the replacements. Returns: ...
75,028
def main(): """Berry Net Server""" berrynet = BerryNetProvider() berrynet.open() try: while True: results = berrynet.analyze('boardcam') detections = _parse_detections(results) for detection in detections: print(detection) time....
75,029
def load_csv_data(train_path, test_path=None, sep=',', nrows=None, x_cols=None, y_cols=None, drop_cols=None, onehot_cols=None, n_cols=None, random_cols=False, shuffle=False, scaling=None, dtype=None, validation_split=None, return_dataframe=True, ...
75,030
def fclayer(in_features, out_features): """ fully connected layers or dense layer :param in_features: input_dimension => channels * features :param out_features: output_dimension :return: (batch, windows, channels * features) => (*, *, output_dimension) """ fc = nn.Linear(in_features, out_fe...
75,031
def main(): """ Parse command-line arguments and then call the corresponding functions """ parser = argparse.ArgumentParser(description='Metha network analysis testing tool') parser.add_argument('--enable-logging', action='store_true') parser.add_argument('-p', '--path', required=True) subp...
75,032
def visual_mask(mask_img=None, mask_path=None): """ :param mask_path: :param palette: :return: """ palette = get_palette() if mask_img is None: mask_img = Image.open(mask_path) else: mask_img = Image.fromarray(np.array(mask_img, dtype=np.uint8)) mask_img.putpalette(p...
75,033
def print_to_readable(predictions, num_tokens, label_dict, input_path, output_path=None): """ Print predictions to human-readable format. """ if output_path is not None: fout = open(output_path, 'w') sample_id = 0 for line in open(input_path, 'r'): if output_path is not None: ...
75,034
def count_frequency_output(counts_dict, title, quantity, item, output_path_base): """ output frequency counts """ # counts_dict looks like: {item: quantity} frequencies = sorted(counts_dict.items(), key=lambda x: abs(x[1]), reverse=True) if sys.version_info[0] < 3: list_of_output_strings = [ uni...
75,035
def system(): """ Run system updates """ pass
75,036
def bench(problem, **kwargs): """ Complete benchmark with multiple simulation and performance parameters. """ run = model_type[problem]['run'] resultsdir = kwargs.pop('resultsdir') repeats = kwargs.pop('repeats') bench = get_ob_bench(problem, resultsdir, kwargs) bench.execute(get_ob_exe...
75,037
def window_replaced_message(callback: Callable[[HWND, HWND], None]) -> MessageEntry: """Listens for when a window is hung, and needs to be recreated. The first HWND will be set to the HWND of the new window handle, and the second is the HWND of the replaced window. The callback should be reused with wi...
75,038
def get_sse_mat(mats: Iterable[sp.spmatrix]) -> sp.spmatrix: """ Given multiple matrices, return the matrix of position-wise sum of squared errors to median. All input matrices must have the same shape, nonzero coordinates and format. Output matrix will have the same format as inputs. """ bg...
75,039
async def process_genre(callback: types.CallbackQuery, state: FSMContext): """ Process genre edit """ async with state.proxy() as data: data["genre"] = callback.data genre = int(callback.data) item = Criteria() item.genre = genre await state.update_data(item=item) # For "ty...
75,040
def energy_sum( df: pd.DataFrame, network: NetworkSchema, power_column: str = "generated" ) -> pd.DataFrame: """Takes the energy sum for a series of raw duid intervals and returns a fresh dataframe to be imported""" # These are the networks that run through the compat func COMPAT_NETWORKS = [Networ...
75,041
def tokenise_word(string, strict=False, replace=False, tones=False, unknown=False): """ Tokenise the string into a list of tokens or raise ValueError if it cannot be tokenised (relatively) unambiguously. The string should not include whitespace, i.e. it is assumed to be a single word. ...
75,042
def latsrf(method, target, et, fixref, lonlat): """latsrf(ConstSpiceChar * method, ConstSpiceChar * target, SpiceDouble et, ConstSpiceChar * fixref, ConstSpiceDouble [1][2] lonlat)""" return _cspyce0.latsrf(method, target, et, fixref, lonlat)
75,043
def _parse_common(xml, the_dict): """ Parse things in common for both variables and functions. This should be run after a more specific function like _parse_func or _parse_variable because it needs a member dictionary as an input. Parameters ---------- xml : etree.Element The xml re...
75,044
def validate_database_credentials(client): """ Validate the parsed database credentials :param client: String :return: """ output.message( output.host_to_subject(client), 'Validating database credentials', True ) _db_credential_keys = ['name', 'host', 'password', ...
75,045
def printTimeline(): """ Prints all statuses from loaded timeline """ logger = logging.getLogger("TALON") try: for status in timeline: printTweet(status) return except Exception, e: logger.error("Error printing timeline") logger.error(e) return
75,046
def add_stat(stat,op_type,schema,table): """ 统计生成了多少sql :param stat:格式为stat["flash_sql"]["schema"]["table"]["操作类型"] : :param op_type: update/delete/insert :param schema: :param table: :return: """ if not stat["flash_sql"].has_key(schema): stat["flash_sql"][schema]={} if ...
75,047
def sliding_window(n, seq): """ Copied from toolz https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window A sequence of overlapping subsequences >>> list(sliding_window(2, [1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)] This function creates a sliding window suitable f...
75,048
def change_course(request, pk): """ Изменение данных в курсе """ course = get_object_or_404(Course, pk=pk) if request.method == 'POST': form = CourseForm(request.POST, request.FILES, instance=course) if form.is_valid(): course = form.save() for csa in CourseStudentAc...
75,049
def interaction(multiindex): """ Return tuple of interaction between variables which this multiindex represents. Eg. (a) (1,1,1) -> (), (b) (1,2,1) -> (1,), (c) (2,3,1) -> (0,1) Tuple is always ordered smallest dim-index to largest. """ return tuple(np.where(np.array(multiindex, dtype=np.int8)...
75,050
def MyCallback(pct_complete, message): """ The callback function that gets status updates. Just prints a low-fi progress bar and reflects the status message passed in. Example: [###### ] Doing some thing... """ progress_bar = " [" + "".ljust(int(pct_complete * 10),'#') + "".ljust(10 - ...
75,051
def home(request): """Dashboard home.""" return render( request, 'dashboard/home.html', { 'quests': Questionnaire.objects.filter( created_at__year=date.today().year, ) }, )
75,052
def debug_messenger(reason: str = None): """ Simple call for debugging that will print the filename and line number to the screen. :param reason: :return: """ if reason is None: reason = "Programmer Neglected to Enlighten Us About the Need for Debugging This Section." fra...
75,053
async def test_user(hass, aioclient_mock): """Test a manual user configuration flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=None, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step...
75,054
def get_entities(config): """ Get a dictionary of lambda functions that create entity URLs :param config: dict :return: dict """ server = config['api'] entities = dict(project=lambda project: server + '/projects/{0}'.format(project), subject=lambda project, subject: serve...
75,055
def _append_string(path, content): """ Append string at the end of file. :param str path: string representing the full path of file :param str content: preformatted string to be added """ with open(path, 'a') as f: f.write(content)
75,056
def crypto_secretbox(message, nonce, key): """ Encrypts and returns the message ``message`` with the secret ``key`` and the nonce ``nonce``. :param message: bytes :param nonce: bytes :param key: bytes :rtype: bytes """ if len(key) != crypto_secretbox_KEYBYTES: raise exc.Valu...
75,057
def create_bins(bin_info_list, shuffle): """Creates a list of bins based on a string list of bin info.""" bins = [] for bin_info in bin_info_list: bins.append(DataBin(bin_info[0], bin_info[1], shuffle)) return bins
75,058
def getEmissionSelf(dataDirBase, NCVariable, RCPScenario, decade): """This function uses makeEmissionNCFile() to get the nc file path of the desired species arguemnt and returns the nc connection to that species. Parameters: Same as makeEmissionNCFile() dataDirBase: Working hardrive NCVariable...
75,059
def from_plus(path): """ Given the path to a CoNLL-U Plus file, return the corresponding plain CoNLL-U string. """ with open(path) as f: plus_fields = [field.upper() for field in parse_conllu_plus_fields(f)] plus_content = f.read() plus_sentences = parse(plus_content, plus_f...
75,060
def deregister_transit_gateway(GlobalNetworkId=None, TransitGatewayArn=None): """ Deregisters a transit gateway from your global network. This action does not delete your transit gateway, or modify any of its attachments. This action removes any customer gateway associations. See also: AWS API Documentation...
75,061
def test_uses_correct_sonar_version(): """Check that the version of Sonar Java plugin specified matches the version of downloaded plugin in sources. The version number is sufficiently distinct that it's enough we just verify it's in configuration file. """ config = ( pathlib.Path(__file__)....
75,062
def usage(): """Print command line usage.""" txt = f"[INFO] Usage: {(sys.argv[0])} month_abbr month_num current_year "\ "lead_months config_file" print(txt) print("[INFO] where") print("[INFO] month_abbr: Abbreviation of the initialization month") print("[INFO] month_num: Integer number of t...
75,063
def __coord_n(n, **_kwargs): """Get bare positions""" return np.arange(n + 1)
75,064
def vectorized_gaussian_logpdf(X, means, covariances): """ Compute log N(x_i; mu_i, sigma_i) for each x_i, mu_i, sigma_i https://stackoverflow.com/a/50809036/8395138 Args: X : shape (n, d) Data points means : shape (n, d) Mean vectors covariances : shape (...
75,065
def elementWise(A, B, operation): """ execute an operate element wise and return result A and B are lists of lists (all lists of same lengths) operation is a function of two arguments and one return value """ return [[operation(x, y) for x, y in zip(rowA, rowB)] for row...
75,066
def clear_canvas(scene): """ SUMMARY clears all objects on the canvas and adds the last compiled pdf image PARAMETERS scene: GraphicsScene RETURNS None """ scene.clear() pixmap = QtGui.QPixmap("tmp/temp-1.png") if not scene.show_pdf: pixmap.fill() tk...
75,067
def create_test_baymodel(context, **kw): """Create and return a test baymodel object. Create a baymodel in the DB and return a BayModel object with appropriate attributes. """ baymodel = get_test_baymodel(context, **kw) try: baymodel.create() except exception.BayModelAlreadyExists: ...
75,068
def _mutate_with_block_callee(blocks, blk_start, blk_end, inputs, outputs): """Mutate *blocks* for the callee of a with-context. Parameters ---------- blocks : dict[ir.Block] blk_start, blk_end : int labels of the starting and ending block of the context-manager. inputs: sequence[str] ...
75,069
def RenamePaths(path_rename: Dict[str, str]) -> None: """Rename files by rewriting the git history. Args: path_rename: Files to rename. All paths are relative to repository root. """ args = [] for k, v in path_rename.items(): args += ["--path-rename", f"{k}:{v}"] args.append("--force") args = git...
75,070
def fetch_spot_prices(region, start_time, end_time, instance_type, instance_version=INSTANCE_VERSION): """Fetches prices of EC2 spot instances from AWS. Args: region (str): region to look for instances in start_time (datetime.datetime): end_time (datetime.datetime): instance_typ...
75,071
def test_forward_with_parameter_in_sub_cell(): """ Feature: Custom cell bprop Description: Get the gradients of inputs when the forward net using Parameter in the sub-cell. Expectation: Get the correct gradients. """ class Net(nn.Cell): def __init__(self): super(Net, self)._...
75,072
def test_ap_beacon_rate_ht(dev, apdev): """Open AP with Beacon frame TX rate HT-MCS 0""" hapd = hostapd.add_ap(apdev[0], { 'ssid': 'beacon-rate' }) res = hapd.get_driver_status_field('capa.flags') if (int(res, 0) & 0x0000100000000000) == 0: raise HwsimSkip("Setting Beacon frame TX rate not suppo...
75,073
def test_labels_inheritance(report_for): """ Checks that label markers can be inherited. """ report = report_for(""" import allure pytestmark = allure.label('label_name1', 'label_value1') @allure.label('label_name2', 'label_value2') class TestMy: @allure.label('label_name3', '...
75,074
def _GetRollbackRelease(release_id, pipeline_id, target_ref): """Gets the release that will be used by promote API to create the rollback rollout.""" ref_dict = target_ref.AsDict() if release_id: return resources.REGISTRY.Parse( release_id, collection='clouddeploy.projects.locations.deliveryPi...
75,075
def load(data_dir=DEFAULT_DATA_DIR, delay=100, num_possible_symbols=10): """ Load Copy Problem data. Args: data_dir: A string. The data directory. delay: An integer. num_possible_symbols: An integer. Returns: A tuple with 6 elements: train inputs, train targets, val inputs, val targets, test...
75,076
def pool_experimental_measurements(property_id): """ Aggregates the distributions of measurements of the given property and saves the resulting aggregate mean, std, and n to property table :param property_id: the id of the property to aggregate """ measurements = Measurement\ ...
75,077
def perform_ocr_on_pdf(languages, input_file, output_file): """Perform OCR on the PDF, if requested in arguments.""" if languages is not None: subprocess.check_call( ["ocrmypdf", "--language", languages, input_file, output_file] ) else: shutil.copy2(input_file, output_fil...
75,078
def find_spaces(string_to_check): """Returns a list of string indexes for each string this finds. Args: string_to_check; string: The string to scan. Returns: A list of string indexes. """ spaces = list() for index, character in enumerate(string_to_check): if character == ' ': spaces.ap...
75,079
def calculate_activation_statistics(images, batch_size): """Calculates the statistics used by FID Args: images: torch.tensor, shape: (N, 3, H, W), dtype: torch.float32 in range 0 - 1 batch_size: batch size to use to calculate inception scores Returns: mu: mean over all activation...
75,080
def _should_recurse(start, config_lines, initial_indent): """Sometimes object are not expected to document every parameter and contain all the description at the top. This is valid, therefore we should not recurse and analyze what's next after the whole object. Returns whether or not to recurse as long a po...
75,081
def unwrap_eth(): """ Withdraw ETH by depositing wETH """ account = get_account() # Need to get the ABI and the Address of the contract weth = interface.IWeth(config["networks"][network.show_active()]["weth_token"]) # Deposit amount = 0.1 tx = weth.withdraw( Web3.toWei(amo...
75,082
def client() -> User: """Construct the User (client) class""" return User(username=USERNAME, auth=AUTH)
75,083
def mergeHashes(destHash,otherHash): """Merge count maps, adding otherHash into destHash""" for (ngram,othercount) in otherHash.viewitems(): destHash[ngram] += othercount #count = destHash.get(ngram,0) #method using std dict #destHash[ngram] = count + othercount
75,084
def dict_from_lst(lst, ordered=False): """ Return a dictionary from a Geosoft `geosoft.gxapi.GXLST` instance. :param lst: `geosoft.gxapi.GXLST` instance :param ordered: True to return an OrderedDict :returns: python dictionary from a Geosoft GXLST .. versionadded:: 9.1 """ ...
75,085
def enable_plugin(plugin_id, downloadable_plugins=None): """ Enables a single plugin, which entails: * If already enabled, return * If plugin not found, search online repository * Download if found in repository, else log and return * Recusively enable dependencies if found, els...
75,086
def parse_external_id(output, type=EXTERNAL_ID_TYPE_ANY): """ Attempt to parse the output of job submission commands for an external id.__doc__ >>> parse_external_id("12345.pbsmanager") '12345.pbsmanager' >>> parse_external_id('Submitted batch job 185') '185' >>> parse_external_id('Submitte...
75,087
def ldns_pkt_set_ra(*args): """LDNS buffer.""" return _ldns.ldns_pkt_set_ra(*args)
75,088
def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (encoded_digest, length) for path using hashlib.sha256()""" h, length = hash_file(path, blocksize) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') # unicode/str python2 ...
75,089
def check_loggers(): """ Logging check endpoint. This endpoint errors so as to verify that loggers are working. """ raise Exception("Test exception")
75,090
def CombineLogFiles(list_of_lists, logger): """Splices together multiple logcats from the same device. Args: list_of_lists: list of pairs (filename, list of timestamped lines) logger: handler to log events Returns: list of lines with duplicates removed """ cur_device_log = [''] for cur_file, c...
75,091
def test_nonlocal_failure(): """Tests that attempting to register a non-local type in multiple modules fails""" import pybind11_cross_module_tests as cm with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal() assert str(excinfo.value) == 'generic_type: type "NonLocalType" is already...
75,092
def test_create_device_lcd(): """ :py:func:`luma.core.cmdline.create_device` supports LCD displays. """ display_name = 'lcd1234' display_types = {'lcd': [display_name]} class args(test_spi_opts): display = display_name gpio = 'fake_gpio' backlight_active = 'low' mod...
75,093
def step_decrease(f: Callable[[Any], Any], x, step=1e-2, step_multiplier=2, iteration_limit=100000000): """ Continues to increment x with x + step till f(x) returns a value that is bigger than the previous value i.e stop when f(x) > f(x+s) step on x + step and for each step expand step with step * s...
75,094
def lcs_naive(first: str, index_f: int, second: str, index_s: int) -> int: """ Time Complexity: O(2^n) """ if index_f < 0 or index_s < 0: return 0 if first[index_f] == second[index_s]: return 1 + lcs_naive(first, index_f - 1, second, index_s - 1) return max( lcs_naive(f...
75,095
def verify(signify: Dict[str, str], snapshot: Path, filename: str="") -> Tuple[bool, List[str]]: """Verify the integrity of a given snapshot with signify. signify -- a dict with signify key and signify signed SHA256 checksums file snapshot -- the directory where the snapshot is stored filena...
75,096
def cf_explain(examples: List[Example], nmols: int = 3) -> List[Example]: """From given :obj:`Examples`, find best counterfactuals using :ref:`readme_link:counterfactual generation` :param examples: Output from :func:`sample_space` :param nmols: Desired number of molecules """ def is_counte...
75,097
def quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False): """ Compute the q-th quantile of the data along the specified axis. ..versionadded:: 1.15.0 Parameters ---------- a : array_like Input array or object that can be convert...
75,098
def build_classifier(img_shape, num_classes): """ Function: build_classifier Input: img_shape: image shape, num_classes: the number of image classes Output: CNN-based classifier model """ cinput = Input(shape=img_shape, name='classifier_input') H = Conv2D(64, kernel_size=(5, 5), acti...
75,099