content
stringlengths
22
815k
id
int64
0
4.91M
def _check_excessive_login_attempts(user): """ See if account has been locked out due to excessive login failures """ if user and LoginFailures.is_feature_enabled(): if LoginFailures.is_user_locked_out(user): _generate_locked_out_error_message()
77,800
def bind(group_data, skeleton_data): """ Bind the group data to the skeleton data using constraints. Doing this will not only take translation into account but also a proper rotation which is needed for a decent result. :param dict group_data: :param dict skeleton_data: """ # point cons...
77,801
def Weld(thisMesh, angleToleranceRadians, multiple=False): """ Makes sure that faces sharing an edge and having a difference of normal greater than or equal to angleToleranceRadians share vertexes along that edge, vertex normals are averaged. Args: angleToleranceRadians (double): Angle at w...
77,802
def _get_all_classes(**kwargs): """ Perform a GET call to get a dictionary containing all traffic classes :param kwargs: keyword s: requests.session object with loaded cookie jar keyword url: URL in main() function :return: List of all traffic classes in the table """ target_url...
77,803
def config(**kwargs): """ Configure anprx's settings Parameters --------- **kwargs keyword arguments that exist in settings Raises ------ InvalidSetting if keyword argument is not in settings Returns ------- None """ for key, value in kwargs.items(...
77,804
def find_by_username(username): """ function that finds user by username """ return Users.find_by_username(username)
77,805
def create_cobra_model_from_patric_model(model_id, id_type='modelseed', validate=False): """ Create a COBRA model from a PATRIC model. Parameters ---------- model_id : str ID of model id_type : {'modelseed', 'bigg'} Type of IDs ('modelseed' for _c or 'bigg' for '[c]) validate : ...
77,806
def regionDailyTimeSeries(C, region): """" Returns a summed time series the length of axis 0 for C subet by the passed region name """ minLat, maxLat, minLon, maxLon, resolution = cnm.getRegionBounds(region) C_PNW, ynew, xnew = cnm.mask2dims(C, longitude, latitude, 0, minLon, maxLon, minLat, maxLat) C_PNW_daily...
77,807
def oauth2(roles=None, required=True, throw_exception=True): """Decorate a Flask route to connect with BDC-Auth Provider. You can specify user roles required to access a resource. Make sure to set the following variables to the app: - ``BDC_AUTH_CLIENT_ID``: Application Client Id - ``BDC_AUTH_CLI...
77,808
def add_one_set(ns: str, ws: str, etype: str, ename: str, member_type: str, members: List[str], attributes: dict or None) -> None: """ To support adding a new set. :param ns: namespace :param ws: workspace :param etype: type of the set, must exist ...
77,809
def atSendCmdGetTradingDaysCondition(market, begin_day, end_day): """ 获取交易日日期 :param market: 市场代号 :param begin_day: 交易日起始时间 :param end_day: 交易日结束时间 :return: list 指定范围内的交易日 """ func_name = 'atSendCmdGetTradingDaysCondition' atserial.ATraderGetTradingDaysByCondition_send(market, begin_...
77,810
def offset(string: str, row: int, column: int, start_line_index: int = 0) -> int: """get offset from string at row column position Return: offset: int """ if not string: raise ValueError("unable get offset from empty string") if start_line_index: row -= start_index li...
77,811
def convertAndExecuteCombineArchive(location): """ Read and execute a COMBINE archive. :param location: Filesystem path to the archive. """ from .teconverters import inlineOmexImporter inlineomex = inlineOmexImporter.fromFile(location).toInlineOmex() executeInlineOmex(inlineomex)
77,812
def train_val_split( dataset: Dataset, batch_size: int, val_split: float, shuffle: bool = True, num_workers: int = 4, collate_fn: Callable = None, pin_memory: bool = True, drop_last: bool = False, timeout: float = 0, worker_init_fn: Callable = None, val_transform: Callable = ...
77,813
def _format_label(duration, start_time, end_time): """ Formats a time block label. :param duration: Duration. :param start_time: Start time. :param end_time: End time. :return: Formatted string with duration, start, and end time. """ return 'Asleep {} ({} to {})'.format( ...
77,814
def get_categories(category_path, parent_category, exclude_str, save_cats_path, verbose): """ Process the categories file to get a list of all sub-categories of the specified parent :param category_path: Path to categories json file :param parent_category: Parent category :param exclude_str: Comma s...
77,815
def get_cold_plasma_coefficients(nu, B, n_e, theta, T): """Get radiative transfer coefficients appropriate for a cold plasma. (Seeing as this module is called "synchrotron" this code may not quite belong here, but...) *nu* Observing frequency, in Hz [note: all inputs are broadcast as vectors] ...
77,816
def qsort(array: List[int]) -> None: """ QuickSort public interface. """ random.seed() _qsort_aux(array, 0, len(array) - 1)
77,817
def update_license(data): """Add license information to the template Args: data (Dict): Data to be updated in the template Returns: str: Updated license """ authors = [ "{:s} ({:s})".format(name, DATA["authors"][name]) for name in DATA["authors"].keys() ] ma...
77,818
def get_caller_module(depth=2): """ Get the module of the caller. """ frame = sys._getframe(depth) module = inspect.getmodule(frame) # Happens when there's no __init__.py in the folder if module is None: return get_caller_module(depth=depth) return module
77,819
def halfSpaceFromRaDec(ra, dec, radius): """ Take an RA, Dec and radius of a circular field of view and return a HalfSpace Parameters ---------- ra in degrees dec in degrees radius in degrees Returns ------- HalfSpace corresponding to the circular field of view """ ...
77,820
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ i...
77,821
def unique(data): """ in python 3: TypeError: '<' not supported between instances of 'int' and 'str' need to keep the same Type of member in List """ data.sort() l = len(data) - 1 i = 0 while i < l: if (data[i] == data[i + 1]): del data[i] i -= 1 ...
77,822
def export_config_file(): """ Exporting a configuration file of the current pipeline state """ with open("config.yaml", 'w') as config_file: yaml.dump(connection. execute_method("get_pipeline_creation", {}), config_file) print("Exported successfull...
77,823
def interval_ends( first: datetime.date, last: datetime.date, interval: Interval ) -> Iterator[datetime.date]: """List intervals. Args: first: A date. last: A date. interval: An interval. Yields: Dates corresponding to the starts/ends of intervals between `first` and ...
77,824
def add_returning(query: QueryBuilder, fields: List[AnyStr]) -> AnyStr: """Build the string query to add final RETURNING statement. :param query: Current query builder instance :param fields: Fields to be returned """ if fields is None: return str(query) return f"{str(query)} RETURNIN...
77,825
def main(): """ Entry Point. """ if len(sys.argv) > 1: sysargs = sys.argv[:] parser = _build_option_parser() opts, urls = parser.parse_args(sysargs[1:]) try: for url in create(*urls): sys.stdout.write(url + opts.delimiter) except Except...
77,826
def PtknsToStr(path_tokens): """ There are three ways to store paths: As a single string: '/Protein/Phe/Ca' <- the format entered by the user As a list of tokens ['Protein', 'Phe', 'Ca'] <- split into tokens As a list of nodes in a tree (pointers to nodes in a tree hierarchy) This functio...
77,827
async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors...
77,828
def drawb(shape, col=None, mod=pyxel): """ Like draw, but renders only the outline of a shape. Args: shape: A Pymunk shape, body or space mod: mod namespace that transforms the scene. col (int): A color index """ try: method = shape.drawb except AttributeError: ...
77,829
def strings(binary): """ Runs and returns the results of the command strings on a binary file :params str binary: the path to the binary :return: the raw result of the strings command """ return execute("strings {}".format(binary))
77,830
def _make_abbreviation(key, tag_name, attrs, is_empty=False): """ Make abbreviation from string @param key: Abbreviation key @type key: str @param tag_name: Expanded element's tag name @type tag_name: str @param attrs: Expanded element's attributes @type attrs: str @param is_empty: Is expanded element empty or...
77,831
def parse_internal_function( code: ast.FunctionDef, sig: FunctionSignature, context: Context ) -> LLLnode: """ Parse a internal function (FuncDef), and produce full function body. :param sig: the FuntionSignature :param code: ast of function :return: full sig compare & function body """ ...
77,832
def traverse_grid(start_cell, direction, num_steps): """ Helper function that iterates over the cells in a grid in a linear direction and returns a list of their indices. """ indices = list() for step in range(num_steps): row = start_cell[0] + step * direction[0] col = start_...
77,833
def get_iris(use_colouring = True): """ Loads the four dimensional Fisher Iris dataset. If the 'iris.data' file is not present in the working directory, this function attempts to download it. The last column of the dataset(the text labels) are ommitted. """ iris = [] colours = [] if...
77,834
def __format_size(file_size): """ Format file size information depending on the amount of bytes. """ file_size = int(file_size) list_units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] list_index = 0 while file_size > 1000: file_size = float(file_size) / 1000 l...
77,835
def upsert_columns(columns, run_id, on_conflict=None): """Perform an upsert of a batch of column objects. """ if not on_conflict: on_conflict = ['table_id', 'object_id'] if len(columns) == 0: return Column.objects \ .on_conflict(on_conflict, ConflictAction.UPDATE) \ ...
77,836
def cli(ctx, shell): """Completion helpers for keep""" commands = utils.read_commands() if shell == 'zsh': for cmd, fields in commands.items(): print("{cmd}:{desc}".format(cmd=cmd, desc=fields['desc'])) elif shell == 'bash': for cmd in commands.keys(): print(quot...
77,837
def test_contains(): """Test basic contains logic.""" bounds = CompositionBounds(components={"spam", "eggs"}) assert bounds.contains(CompositionBounds(components={"spam"})) assert not bounds.contains(CompositionBounds(components={"foo"})) assert not bounds.contains(RealBounds(0.0, 2.0, '')) asse...
77,838
def testsuite(): """ Return a PyUnit testsuite for the epytext module. """ tests = unittest.TestSuite() parse_tests = unittest.makeSuite(ParseTestCase, 'test') tests = unittest.TestSuite( (tests, parse_tests) ) return tests
77,839
def parse_wiggle_header(header): """ :param header: :return: """ _, chrom, start, step = header.strip().split() foo, chrom = chrom.split('=') assert foo == 'chrom', 'Unexpected wiggle header: {}'.format(header) bar, start = start.split('=') assert bar == 'start', 'Unexpected wiggle h...
77,840
def minEditDistance(s1, s2): """Compute minimum edit distance converting s1 -> s2 with operations.""" len1 = len(s1) len2 = len(s2) # Create two-dimensional structure such that m[i][j] = 0 # for i in 0 .. len1 and for j in 0 .. len2 m = [None] * (len1 + 1) op = [None] * (len1 + 1) ...
77,841
def pack_format(flat: FlatFmt) -> bytes: """pack collection of indexes into a tagged byte format.""" max_idx = max(flat, key=lambda idx: idx or 0) if max_idx > 0xFFFF: format_str = '>L' elif max_idx > 0xFF: format_str = '>H' else: format_str = '>B' packer = struct.Struct(...
77,842
def test_get_diff(): """test if the difference is calculated correctly between the first two sound of a sound correspondence list""" # test without exception # set up: mock class, 2 attributes, 1 var for input-param monkey_adrc = AdrcMonkey() monkey_adrc.sedict = {"k<k": 2, "k<c": 1, "i<e": 2, ...
77,843
def create_dataset(save_path, patchsize, volume, mask=None, class_list=None, random_order=True, batchsize=32, file_format='hdf5', kwargs={}, show_progress=False): """ Extract patches and save them to file, with one dataset/array/directory per class. save_pa...
77,844
def end_move(board): """ Prints the board after a swipe, pauses for .2 seconds, places a new random piece and prints the new state of the board Arg board: board - the board you're finishing a move on """ #Print the board clear() print_board(board) #Pause for .2 seconds pause(0.2) ...
77,845
def get_or_404(*args, **kwargs): """Returns a model instance fetched by key or raises a 404 Not Found error. Example: from tipfy import RequestHandler from tipfy.appengine.db import get_or_404 from mymodels import Contact class EditContactHandler(RequestHandler): de...
77,846
def sisnr_objf(x: th.Tensor, s: th.Tensor, eps: float = EPSILON, zero_mean: bool = True, non_nagetive: bool = False) -> th.Tensor: """ Computer SiSNR Args: x (Tensor): separated signal, N x S s (Tensor): reference signal, N x S ...
77,847
def _path_in_ignore_dirs(source_path: str, ignore_dirs: list) -> bool: """Checks if the source path is to be ignored using a case sensitive match Arguments: source_path: the path to check ignore_dirs: the list of directories to ignore Return: Returns True if the path is to be ignored...
77,848
def load_drivers(conf): """Imports all the driver files corresponding to this agent. Returns: Dictionary of driver objects with a specified service type and vendor name """ ld = load_driver.ConfiguratorUtils(conf) drivers = ld.load_drivers(const.SERVICE_TYPE) for service_type, driver_nam...
77,849
def absolute_difference_error(output, target, is_mean=False, name="absolute_difference_error_loss"): """Return the TensorFlow expression of absolute difference error (L1) of two batch of data. Parameters ---------- output : Tensor 2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, h...
77,850
def maximum_knapsack(items, limit): """ Berechnet die Lösung für Maximum Knapsack über Dynamic Programming (ähnlich wie Subset Sum) """ # Erstelle Tabelle table = [[None for j in range(len(items) + 1)] for i in range(limit + 1)] # Fülle erste Zeile mit 0 (da der Wert im Knapsack mit 0 Gegenständen imme...
77,851
def render_line_numbers(self) -> None: """ While background rendering is done for all "line-slots" (to overpaint remaining "old" numbers without lines) we render line-numbers only for existing string-lines. """ if self.displayLineNumbers and self.rerenderLineNumbers: self.rerenderLineNumbers...
77,852
def configure_logging(): """ Currently just logging to the terminal stderr stream, but this could easily be extended to produce a log file or e.g. email alerts. """ logger = logging.getLogger("coverview_test") formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(pathname)s - Line %(li...
77,853
def gpio_read(gpio_pin: int) -> bool: """Return an input or output pin state.""" return (GPIO.input(gpio_pin) == GPIO.HIGH)
77,854
def auth0_url_encode(byte_data): """ Safe encoding handles + and /, and also replace = with nothing :param byte_data: :return: """ return base64.urlsafe_b64encode(byte_data).decode('utf-8').replace('=', '')
77,855
def replace_jax_simple_full_softmax_vars_to_tf( jax_initial_vars: NestedMap) -> NestedMap: """Replaces JAX Simple Full Softmax vars to TF compatible vars. Args: jax_initial_vars: JAX ConvBNAct layer vars. Returns: tf_initial_vars which is TF compatible with ConvBNAct. """ tf_initial_vars = jax_i...
77,856
def test_neg_read_offset_outside_of_device(pyocf_ctx, c_int_sector_randomize): """ Check that read operations are blocked when IO offset is located outside of device range """ vol, queue = prepare_cache_and_core(Size.from_MiB(2)) data = Data(int(Size.from_KiB(1))) completion = io_op...
77,857
def test_format_single_notebook(): """ Test formatting a single notebook in an directory of unformatted notebooks formats only that notebook """ data_path = pathlib.Path(f"{__file__}").parent / "data" source_notebook_path = data_path / "unformatted" / "spaces.ipynb" copy_notebook_path = data...
77,858
def _fmt(x, pos): """ Used for nice formatting of powers of 10 when plotting logarithmic """ a, b = '{:.2e}'.format(x).split('e') b = int(b) if abs(float(a) - 1) < 0.01: return r'$10^{{{}}}$'.format(b) else: return r'${} \times 10^{{{}}}$'.format(a, b)
77,859
def packdata(list_data): """Takes in a list of a cycle of sampling and returns a json representation""" pass
77,860
def _get_html(url, error_message="Erro: "): """Fetches the HTML source of the given URL using the requests lib.""" # Checking arguments type if (type(url) is not str) or (type(error_message) is not str): raise TypeError("Erro: os argumentos devem ser strings.") # Obtaining the html of the page...
77,861
def quint4(scale, zero_point): """ Consturct a quantized unsigned int4 data type with ``scale`` (float) and ``zero_point`` (uint8). The real value represented by a quint4 data type is float_val = scale * (uint4_val - zero_point) """ return get_quantized_dtype("quint4", scale, zero_point)
77,862
def word_averaging(wv, words): """Calculate average word vectors. Args: wv: The keyed vectors instance to use to get word vectors as :class:`gensim.models.keyedvectors.WordEmbeddingsKeyedVectors`. words: The words to transform into vectors as :class:`list` of :class:`str`. Returns: ...
77,863
def create_full_X_test_2d( X_ranges: MatrixLike2d, x_indices: Optional[List[int]] = [0, 1], fixed_values: Optional[Union[ArrayLike1d, float]] = None, fixed_values_real: Optional[Union[ArrayLike1d, float]] = None, baseline: Optional[str] = 'left', mesh_size: Optional[int] = 41 ) -> Tuple[Matrix,...
77,864
def mkdir(dirname): """ Creates directory `dirname` if it does not exist already. .. seealso:: http://stackoverflow.com/a/5032238/1913780 """ if dirname == "": return try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise
77,865
def create_win_salt_restart_task(): """ Create a task in Windows task scheduler to enable restarting the salt-minion Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' service.create_win_salt_restart_task() """ # Updated ...
77,866
def is_temple_project(): """Raises `InvalidTempleProjectError` if repository is not a temple project""" if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE): msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE) raise temple.exceptions.InvalidTempleProjectErro...
77,867
def plot_serial_corr(): """Makes a plot showing serial correlation for pink noise. """ np.random.seed(19) betas = np.linspace(0, 2, 21) corrs = [] for beta in betas: signal = thinkdsp.PinkNoise(beta=beta) wave = signal.make_wave(duration=1.0, framerate=11025) corr = ser...
77,868
def test_example2(): """Example 2: 2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6) """ p = IntCode("2,3,0,3,99") p.run() assert p.mem.dump() == "2,3,0,6,99"
77,869
def prepare_mol(filename, header, add_hydrogens=True): """ """ atoms = [] coordinates = [] with open(filename, 'r') as f: molfmt = f.read() mol = Chem.MolFromMolBlock(molfmt) # get formal charge charge = Chem.GetFormalCharge(mol) # Get coordinates conf = mol.GetCo...
77,870
def init_parser(): """Initialize and return the command line parser.""" autoddoc_description =\ ("AutoDDoc 0.1\n" "Documentation generator script for D using DDoc.\n" "Copyright Ferdinand Majerech 2011.\n\n" "AutoDDoc scans subdirectories of the current directory for D or DDoc...
77,871
def publish_images_to_channel(images): """ Publish retrieved images to telegram channel. """ chat_id = settings.telegram_chat_id for image in images.values(): caption = f'{image["image_date"]} - {image["image_caption"]}' image_url = image['image_url'] try: publish_to...
77,872
def validate_labels(labels: Dict[str, str]): """Validate labels. Args: labels: labels to verify Raises: ValueError: if labels is not a mapping of string key value pairs. """ for k, v in labels.items(): if not isinstance(k, str) or not isinstance(v, str): raise Va...
77,873
def _plot_elbow_chart(dendrogram_list): """ Plots an elbow chart with jump distances and acceleration Parameters ---------- dendrogram_list Returns ------- """ sns.set_style("whitegrid") sns.despine() fig, ax = plt.subplots(figsize=(8, 8)) cluster_jumps = [joining[2] ...
77,874
def build_put_async_relative_retry400_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status. See https://aka.ms/azsdk/py...
77,875
def open_recipe_file(file, recipes_path=None, github_repo='bioconda/bioconda-recipes'): """ Open a file at a particular location and return contents as string """ if recipes_path: return open(f'{recipes_path}/{file}').read() else: # if no clone of the repo is available locally, download fro...
77,876
def delete_video(input_m3u, index): """ delete IN.M3U INDEX: update m3u by deleting video at specified index """ m3u8_obj = m3u8.load(input_m3u) segment = m3u8_obj.segments[int(index)] print("Deleting {}".format(segment.uri)) del(m3u8_obj.segments[int(index)]) with open(input_m3u, "w")...
77,877
def get_comment_statistics(): """ Collects and prints all feedback together with the associated user id. Additionally, shows how many users left feedback and the average length of a feedback message. :return: """ comments = {} non_empty_count = 0 comment_length = 0 number_of_users ...
77,878
def cytoscapegraph(graph, onto=None, infobox=None, style=None): """Returns and instance of icytoscape-figure for an instance Graph of OntoGraph, the accomanying ontology is required for mouse actions""" from ipywidgets import Output, VBox, GridspecLayout from IPython.display import display, Image ...
77,879
def confidence_interval(data, column_name, confidence_level): """ get a 95% confidence interval from a bootstrap dataframe column Parameters ---------- data : pandas dataframe the bootstrap dataframe generated by :py:func:`.bootstrapLE` column_name : string the statistic that y...
77,880
def dist_to_freq(dist: float, bw: float, ts: float) -> float: """ """ return int(2 * dist * bw / (299792458 * ts))
77,881
def batch_files(pool_size, limit): """ Create batches of files to process by a multiprocessing Pool """ batch_size = limit // pool_size filenames = [] for i in range(pool_size): batch = [] for j in range(i * batch_size, (i + 1) * batch_size): filename = 'numbers/numbers_%d...
77,882
def implements(numpy_function): """Register an __array_function__ implementation""" def decorator(func): QUANTITY_FUNCTIONS[numpy_function] = func return func return decorator
77,883
def test_serialization_partition(): """ This tests the serialization of partition explainers. """ AutoTokenizer = pytest.importorskip("transformers").AutoTokenizer AutoModelForSeq2SeqLM = pytest.importorskip("transformers").AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained("Helsinki-N...
77,884
def merge_imd_with_other_set(imd_df, other_df): """Merge IMD data with other data based on postcode. Parameters ---------- imd_df : pandas.DataFrame Deprivation data other_df : pandas.DataFrame Other data Return ---------- merged_df : pandas.DataFrame Two datas...
77,885
def metadata_standard_index_delete(context, data_dict): """ Placeholder function for deleting a metadata search index. May be implemented as required by another plugin. You must be authorized to delete a search index. :param id: the id or name of the metadata standard :type id: string """ ...
77,886
def time_location_plot(time_locations, ax=None, cmap=None, freq='30min', datetime_format='%H:%M'): """Plots the location of individuals/groups of individuals as a function of time. Parameters ---------- time_locations : pd.Series The locations, indexed by 'datetime' and another index (e.g. ...
77,887
def encode_note_mat_to_atr_mat(nmat, length=None, tgt_pad_length=None, eo=0, ep=0, estimate_ep=False, w=0): """ Convert note m...
77,888
def preBuildPage(site, page, context, data): """ Add collections to every page context so we can access them from wherever on the site. """ directory_path = page.path.split("/") config = context['__CACTUS_SITE__'].config extra = { "CURRENT_PAGE": page, "CONFIG": config.get('...
77,889
def get_iarc_app_title(app): """Delocalized app name.""" from mkt.webapps.models import Webapp with no_translation(app.default_locale): delocalized_app = Webapp.with_deleted.get(pk=app.pk) return unicode(delocalized_app.name)
77,890
def box_ball_location_on_collision( ball_loc, box_loc, box_rot_matrix, box_corner=HITBOX, box_offset=HITBOX_OFFSET, ball_radius=92 ): """Closest box location for there to be a collision with the ball""" ball_local_loc = (ball_loc - box_loc).dot(box_rot_matrix) hit_local_loc = box_local_collision_locatio...
77,891
def list_missing_data_cols(df, back_color="red"): """ This function reports statistics on missing data in the datasets. """ lst_cols_missing = list(df.columns[df.isnull().any()]) lst_cols_miss_data = [(col, df[col].isnull().sum()) for col in lst_cols_missing] lst_cols_miss_data = sorted(lst_cols...
77,892
def plot_secant_method(): """Illustrates the Secant Method. The Secant Method replaces the derivative in Newton’s method with an estimate. The code for this function is taken from the Python CompEcon toolbox by Randall Romero-Aguilar [RA20]_ and has been slightly altered to fit the style of these ...
77,893
def compute_wu_bound_strong(lipschitz_constant, gamma, n_samples, batch_size, verbose=True): """ compute the bound in the strongly convex case basically copied from https://github.com/tensorflow/privacy/blob/1ce8cd4032b06e8afa475747a105cfcb01c52ebe/tensorflow_privacy/privacy/bolt_on/optimizers.py ""...
77,894
async def init_wiki(): """ Async-creates the wiki object and sets its .soup to actual JSON. return: gbfwiki.wiki wiki """ wiki = Wiki() await wiki._init() return wiki
77,895
def main(argv: Union[List[str], None] = None) -> int: """Drive the lookup.""" error, message, strings = verify_request(argv) if error: print(message, file=sys.stderr) return error command, config = strings with open(config, 'rt', encoding=ENCODING) as handle: configuration ...
77,896
def shrink_ss(inputs_, theta_, q): """ Special shrink that does not apply soft shrinkage to entries of top q% magnitudes. :inputs_: TODO :thres_: TODO :q: TODO :returns: TODO """ abs_ = tf.abs(inputs_) thres_ = tf.contrib.distributions.percentile( abs_, 100.0-q, axi...
77,897
def pig_latin(wrd): """Returns the Pig Latin version of a word. For words that begin with a consonant, take the consonant/consonant cluster and move it to the end of the word, adding the suffix 'ay' to the end of the word. For words that begin with a vowel, leave the word as is and add the suffix ...
77,898
def select_config( configs: List[cconfig.Config], index: Optional[int], start_from_index: Optional[int], ) -> List[cconfig.Config]: """ Select configs to run based on the command line parameters. :param configs: list of configs :param index: index of a config to execute, if not `None` :...
77,899