content
stringlengths
22
815k
id
int64
0
4.91M
def _center_size_bbox_to_corners_bbox(centers, sizes): """Converts bbox center-size representation to corners representation. Args: centers: a tensor with shape [N, 2] representing bounding box centers sizes: a tensor with shape [N, 2] representing bounding boxes Returns: corners: tensor with shap...
5,358,300
def get_starting_month(number_of_months_to_get, include_actual_month=True, actual_date=datetime.datetime.now()): """ Get starting month based on parameters :param number_of_months_to_get: Numbers of months to get - e.g: 2 :param include_actual_month: Include...
5,358,301
def signal_handler(sig, frame): """ Suppress stack traces when intentionally closed """ print("SIGINT or Control-C detected... exiting...") sys.exit(0)
5,358,302
def main() -> None: """Main function entrypoint.""" parser = argparse.ArgumentParser() parser.add_argument( "--load_module", type=str, default="./complainers", help="A local python module or just a folder containing all complainers. " "The difference is that the modul...
5,358,303
def cvt_raise_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """raise_stmt: 'raise' [test ['from' test | ',' test [',' test]]]""" # 0 1 2 3 2 3 4 5 #-# Raise(expr? exc, expr? cause) assert ctx.is_REF, [node] if len(node.children) == 1: return ...
5,358,304
def user_in_user_groups(user_id, **options): """ Get all user groups a user belongs to :param user_id: The id of user :param user_id: str :param options: Generic advanced options dict, see online documentation :type options: dict, optional :re...
5,358,305
def read_book(title_path): """Read a book and return it as a string""" with open(title_path, "r", encoding = "utf8") as current_file: #encoding = "utf8" causes a problem when running the code in Python 2.7. However, it runs normally when using Python 3.5. text = current_file.read() text = text.r...
5,358,306
def count_number(file_name, number): """ 统计一个大文件里指定 byte 的个数,为了跑在不同进程上所以没有优化 """ print('searching %s:(%s)' % (number, getpid())) with open(file_name, 'rb') as f: count = 0 while True: data = f.read(1024) if not data: break for d in...
5,358,307
def eval_whole_scene_one_epoch(sess, ops, test_writer): """ ops: dict mapping from string to tf ops """ global EPOCH_CNT is_training = False test_idxs = np.arange(0, len(TEST_DATASET_WHOLE_SCENE)) num_batches = len(TEST_DATASET_WHOLE_SCENE) total_correct = 0 total_seen = 0 loss_sum = 0 ...
5,358,308
def _create_save_name(save_path: str, case_date: date, field_names: list, fix: str = "") -> str: """Creates file name for saved images.""" date_string = case_date.strftime("%Y%m%d") return f"{save_path}{date_string}_{'_'.join(field_names)}{fix}.png"
5,358,309
def print_document(update: Update, context: CallbackContext) -> None: """Don't print received document""" name, permission_to_print = user_info(update.message.from_user) if not permission_to_print: update.message.reply_text("You are not allowed to print, request permission with /start") retu...
5,358,310
def list_favorite_queries(): """List of all favorite queries. Returns (title, rows, headers, status)""" headers = ["Name", "Query"] rows = [(r, favoritequeries.get(r)) for r in favoritequeries.list()] if not rows: status = '\nNo favorite queries found.' + favoritequeries.usage else: ...
5,358,311
def random_portfolio_weights(weights_count) -> np.array: """ Random portfolio weights, of length weights_count. """ weights = np.random.random((weights_count, 1)) weights /= np.sum(weights) return weights.reshape(-1, 1)
5,358,312
def matrix2list(mat): """Create list of lists from blender Matrix type.""" return list(map(list, list(mat)))
5,358,313
def convert_handle(handle): """ Takes string handle such as 1: or 10:1 and creates a binary number accepted by the kernel Traffic Control. """ if isinstance(handle, str): major, minor = handle.split(':') # "major:minor" minor = minor if minor else '0' return int(major, 16)...
5,358,314
def list_canned_image_help(scripts_path, fullpath): """ List the help and params in the specified canned image. """ found = False with open(fullpath) as wks: for line in wks: if not found: idx = line.find("long-description:") if idx != -1: ...
5,358,315
def index(request): """Display start page""" return HttpResponseRedirect(reverse('admin:index'))
5,358,316
async def check_data(user_input, hass, own_id=None): """Check validity of the provided date.""" ret = {} if(CONF_ICS_URL in user_input): try: cal_string = await async_load_data(hass, user_input[CONF_ICS_URL]) try: Calendar.from_ical(cal_string) except Exception: _LOGGER.error(traceback.format_exc(...
5,358,317
def write_mllr(fout, Ws, Hs=None): """ Write out MLLR transformations of the means in the format that Sphinx3 understands. @param Ws: MLLR transformations of means, one per feature stream @ptype Ws: list(numpy.ndarray) @param Hs: MLLR transformations of variances, one per feature stream @pt...
5,358,318
def run( uri, entry_point="main", version=None, parameters=None, docker_args=None, experiment_name=None, experiment_id=None, backend="local", backend_config=None, use_conda=None, storage_dir=None, synchronous=True, run_id=None, run_name=None, env_manager=None,...
5,358,319
def general_search_v2(params, sed_mod, lnprior, Alambda, sed_obs, sed_obs_err=0.1, vpi_obs=None, vpi_obs_err=None, Lvpi=1.0, Lprior=1.0, cost_order=2, av_llim=-0.001, debug=False): """ when p = [teff, logg, [M/H], Av, DM], t...
5,358,320
def test_bigquery_value_check_missing_param(kwargs, expected): """Assert the exception if require param not pass to BigQueryValueCheckOperatorAsync operator""" with pytest.raises(AirflowException) as missing_param: BigQueryValueCheckOperatorAsync(**kwargs) assert missing_param.value.args[0] == expec...
5,358,321
def demangle_backtrace(backtrace): """ Returns a demangled backtrace. Args: * backtrace, a backtrace to demangle """ new_bt = [] frame_regex = re.compile(FRAME_PATTERN) lines = backtrace.splitlines() for line in lines: frame = frame_regex.match(line) if frame: ...
5,358,322
def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, ids_avail_vals, obs_shapes, obs_dtypes, keys): """ Control a single environment instance using IPC and shared memory. """ env = env_fn_wrapper.x() agent_ids = env.all_possible_agent_ids parent_pipe.close() def _write_obs(...
5,358,323
def resource_path(base_path, rel_path): """ Get absolute path to resource, works for dev and for PyInstaller """ import sys # PyInstaller creates a temp folder and stores path in _MEIPASS return os.path.join(getattr(sys, '_MEIPASS', base_path), rel_path)
5,358,324
def legendre(N, x): """ Returns the value of Legendre Polynomial P_N(x) at position x[-1, 1]. """ P = np.zeros(2 * N) if N == 0: P[0] = 1 elif N == 1: P[1] = x else: P[0] = 1 P[1] = x for i in range(2, N + 1): P[i] = (1.0 / float(i)) * ((2 * i - 1...
5,358,325
def updateFile(path, value): """ Replaces the contents of the file at the given path with the given value. :param path: The file path of the file to overwrite. :type path: string_types :param value: The string to overwrite the file with. :type value: string_types """ serializeDate = la...
5,358,326
def skip_any_whitespace(doc, idx): """Iterate through characters in ``doc`` starting from index ``idx`` until a non-whitespace character is reached. This iteration will also attempt to ignore comments. Args: doc (str): The JSPEC document. idx (int): The starting index for the iterator. ...
5,358,327
def normalized_cross_correlation(f, g): """ Normalized cross-correlation of f and g. Normalize the subimage of f and the template g at each step before computing the weighted sum of the two. Hint: you should look up useful numpy functions online for calculating the mean and standard deviati...
5,358,328
def sphere_coordinates(sphere, inversion=False): """ Compute spherical coordinates (longitude, latitude) on a sphere. Parameters ---------- sphere: (AimsTimeSurface_3_VOID) a sphere mesh: vertices must be on a sphere with center 0. inversion: bool if True, the longitude coord is...
5,358,329
def example_parameter_sets() -> Dict[str, ExampleParameterSet]: """Lists the available example parameter sets. They can be downloaded with :py:func:`~download_example_parameter_sets`.""" # TODO how to add a new model docs should be updated with this part examples = chain( _wflow.example_paramet...
5,358,330
def get_height(img): """ Returns the number of rows in the image """ return len(img)
5,358,331
def save_channels_data(data_frame, prefix, project): """Save channels displacement data to local cache Saves data inside the one_params CACHE DIR. Parameters ---------- data_frame : pandas DataFrame DataFrame containing data to save. prefix : str Specify the PR...
5,358,332
def wpt_ask_for_name_and_coords(): """asks for name and coordinates of waypoint that should be created""" name = input("Gib den Namen des Wegpunkts ein: ") print("Gib die Koordinaten ein (Format: X XX°XX.XXX, X XXX°XX.XXX)") coordstr = input(">> ") return name, coordstr
5,358,333
def car_following_with_adp(distance_2_tan, radian_at_tan, distance_integral, K, estimated_dis, rec): """ Control with `distance_2_tan`, `radian_at_tan` and `distance_integral` with `K` trained from the ADP algorithm. While following the car in front of it with a simple P controller and `distance_2_c...
5,358,334
def registerFactoryAdapter(for_, klass): """register the basic FactoryAdapter for a given interface and class""" name = getIfName(for_) class temp(FactoryAdapter): factory = klass zope.component.provideAdapter(temp, name=name)
5,358,335
def setup_sdk_imports(): """Sets up appengine SDK third-party imports.""" if six.PY3: return sdk_path = os.environ.get('GAE_SDK_PATH') if not sdk_path: return if os.path.exists(os.path.join(sdk_path, 'google_appengine')): sdk_path = os.path.join(sdk_path, 'google_appengine...
5,358,336
def construct_full_available(cards, suits): """ Construct suit availability grid - a list of available suits for each rank slot in each player's deck. Returns grid and array giving the the total number of available suits for each slot. """ num_players, num_in_deck = cards.shape num_availabl...
5,358,337
def combine_csvs(csv_paths:list, output_path:str): """ Function to combine csvs (also remove duplicates) and save as a csv Args: csv_paths: list of str the list of paths to csvs to be combined output_path: str Path to save combined csv in Returns: N...
5,358,338
def get_commands_blacklist() -> list: """ Get commands from `features.yml` to blacklist, preventing them from being added to the bot :returns: list """ log.info("Getting commands blacklist...") cmds = [] if osp.isfile(features_path): with open(features_path, 'r') as file: ...
5,358,339
def fit_gaussians(estimated_hapcov, chromosomes=None, output_dir=None, cov_max=None, cov_min=None, level=0, cov_sample=None): """ Fits a 7-component Gaussian mixture model to the coverage distribution of the sample, using the appropriate attributes of the PloidyEstimation object. The cent...
5,358,340
def remove_outliers(cords, eps: int = 1, min_samples: int = 2): """ Remove outlying cells based on UMAP embeddings with DBScan (density based clustering) Call as: sub.obs["d_cluster"] = remove_outliers(sub.obsm["X_umap"], min_samples = 10) Args: cords: adata UMAP coordinates, typically adata.ob...
5,358,341
def sum_squares(n): """ Returns: sum of squares from 1 to n-1 Example: sum_squares(5) is 1+4+9+16 = 30 Parameter n: The number of steps Precondition: n is an int > 0 """ # Accumulator total = 0 for x in range(n): total = total + x*x return total
5,358,342
def load_election_dates(): """ This is from before we had direct access to election data and needed it, we are still using the data from a csv, to populate the ElectionClassDate model. """ logger.info('Loading election dates...') import pandas as pd frame = pd.read_excel('data/election_dates.x...
5,358,343
def resolve_attribute(thing, name): """ A replacement resolver function for looking up symbols as members of *thing*. This is effectively the same as ``thing.name``. The *thing* object can be a :py:func:`~collections.namedtuple`, a custom Python class or any other object. Each of the members of *thing* must be of ...
5,358,344
async def test_form_user_already_configured(hass): """Test we abort if already configured.""" await setup.async_setup_component(hass, "persistent_notification", {}) config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "1.1.1.1", CONF_PORT: 12, CONF_SYSTEM_ID: 46}, ) confi...
5,358,345
def moment_fluxes(indices, wts_left, wts_right, xi_left, xi_right): """ Computes moment fluxes inputs: ------- num_nodes: number of quadrature nodes, depends on inversion algorithm indices: moment indices, size [ num_moments, num_internal_coords ] wts_left: weights on the left side, ...
5,358,346
def main_app(): """ Initializes and handles PySimpleGUI Frames and Windows """ sg.SetOptions(element_padding=(0, 0)) progressbar = [[sg.ProgressBar(100, orientation='h', size=(31, 10), key='progressbar')]] textWaiting = [[sg.Text('STATUS: NONE', font=('Helvetica', 10), size=(20, 1), ...
5,358,347
def get_args(): """Get the command-line arguments""" parser = argparse.ArgumentParser( description='Emulate wc (word count)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', help='Input file(s)', ...
5,358,348
def froc_curve_per_side(df_gt, df_pred, thresholds, verbose, cases="all"): """ Compute FROC curve per side/breast. All lesions in a breast are considered TP if any lesion in that breast is detected. """ assert cases in ["all", "cancer", "benign"] if not cases == "all": df_exclude = df_g...
5,358,349
def make_lists(*args, **kwargs): """ The make_lists function attaches auxiliary things to an input key_list of (normally) AD objects. Each key gets exactly one auxiliary thing from each other list -- these lists can be as long as the key_list, or have only one item in (in which case they don't have ...
5,358,350
def current(): """Prints the current configuration """ yaml.register_class(profile.ProfileData) #yaml.register_class(dict) builder_data.register_classes(yaml) data = { 'profile': profile.get(), 'builder': { 'filepath': builder_data.get_storage_filepath(), ...
5,358,351
def get_free_comment_url_ajax(content_object, parent=None, ajax_type='json'): """ Given an object and an optional parent, this tag gets the URL to POST to for the creation of new ``FreeThreadedComment`` objects. It returns the latest created object in the AJAX form of the user's choosing (json or x...
5,358,352
def getDefensivePacts(playerOrID, askingPlayerOrID): """ Returns a list of CyPlayers who have a Defensive Pact with playerOrID. The askingPlayerOrID is used to limit the list to players they have met. """ pacts = [] askedPlayer, askedTeam = getPlayerAndTeam(playerOrID) askingPlayer, askingTeam = getPla...
5,358,353
def test_tensor_has_basic_operations(free_alg): """Test some of the basic operations on tensors. Tested in this module: 1. Addition. 2. Merge. 3. Free variable. 4. Dummy reset. 5. Equality comparison. 6. Expansion 7. Mapping to scalars. 8. Base p...
5,358,354
def cosine_score(vector1, vector2): """Calculate cosine cosine score between two spectral vectors.""" return np.dot(vector1, vector2)/np.sqrt(np.dot(np.dot(vector1, vector1), np.dot(vector2, vector2)))
5,358,355
def fixture_times() -> Problem[int]: """Generate a problem which tests a times function.""" @test_case(4, 6) @test_case(-2, 16) @test_case(2, -3, aga_hidden=True, aga_output=-6) @problem() def times(x: int, y: int) -> int: """Compute x * y.""" return x * y return times
5,358,356
def get_axis_bounds(ax=None): """Obtain bounds of axis in format compatible with ipyleaflet Returns: bounds np.array with lat and lon bounds. bounds.tolist() gives [[s, w],[n, e]] """ if ax is None: ax = plt.gca() return np.array([ax.get_ylim(), ax.get_xlim()]).T
5,358,357
def test_log_command_error(fixed_time, tmpdir): """Test the --log option logs when command fails.""" cmd = FakeCommand(error=True) log_path = tmpdir.joinpath("log") cmd.main(["fake", "--log", log_path]) with open(log_path) as f: assert f.read().startswith("2019-01-17T06:00:37,040 fake")
5,358,358
def get_pymatgen_structure(cell:tuple) -> Structure: """ Get pymatgen structure from cell. Args: cell: Cell (lattice, scaled_positions, symbols). """ return Structure(lattice=cell[0], coords=cell[1], species=cell[2])
5,358,359
def test_run_command_no_output(): """Test run a command without output""" # GIVEN a command that returns no output cmd = ["cd", "./"] # WHEN running it with execute command res = execute_command(cmd) # THEN assert that the empty string is returned assert res == ""
5,358,360
def lambda_handler(event, context): """ launch the function Stop_Instances() in the lambda function Handler for the Lambda function "lambda_function.lambda_handler" Timeout need to be more than 1 minute, so that our function can run perfectly if you have an important number of instances to be shut...
5,358,361
def get_next_event(event_id: int): """Returns the next event from the selected one. This route may fail if the event is not repeated, or if the event is too far ahead in time (to avoid over-generation of events). """ # TODO(funkysayu): Implement the user visibility limit. # Check if we already...
5,358,362
def conditional_samples(x_3, x_prime_3, MC_method, M): """Generate mixed sample sets of interest distributed accroding to a conditional PDF. Parameters ---------- x_3 : np.ndarray Array with shape (n_draws, 3). x_prime : np.ndarray Array with shape (n_draws, 3). MC_method : stri...
5,358,363
def logcmd(message): """ Logs command out of message in a file. """ if not path.isdir("SAVES"): os.mkdir("SAVES") with open("SAVES/cmdlog.txt", "a") as fw: time = strftime("%d.%m.%Y %H:%M:%S", gmtime()) fw.write("[%s] [%s (%s)] [%s (%s)] '%s'\n" % (time, message.server.name, ...
5,358,364
def recombine(geno_matrix, chr_index, no_loci): #, no_samples): """ Recombine at randomly generated breakpoints. """ recomb = {0: 0, 1: 2, 2: 1, 3: 3} # '0|1' <-> '1|0' no_samples = geno_matrix.shape[0] #print(no_samples) masked, bp_list = designate_breakpoints(chr_index, no_loci, no_sample...
5,358,365
def update_record_files_async(object_version): """Get the bucket id and spawn a task to update record metadata.""" # convert to string to be able to serialize it when sending to the task str_uuid = str(object_version.bucket_id) return update_record_files_by_bucket.delay(bucket_id=str_uuid)
5,358,366
def check_platform(): """ str returned """ import platform return platform.system()
5,358,367
def partie(nb_joueurs, bot, mode_bot, reprendre_partie=None,automat=False): """ Fonction principale regroupant les appels des moments fondamentaux pour la parte Azul """ hauteur_partie, largeur_partie = 600,1025 cree_fenetre(largeur_partie,hauteur_partie) rectangle(0,0,largeur_partie,...
5,358,368
def get_field_keys(table): """ Field keys for a selected table :param table: :return: list op dictionaries """ cql = 'SHOW FIELD KEYS FROM \"{}\"'.format(table) response = db_man.influx_qry(cql).get_points() return [x for x in response]
5,358,369
def extract_text_from_spans(spans, join_with_space=True, remove_integer_superscripts=True): """ Convert a collection of page tokens/words/spans into a single text string. """ if join_with_space: join_char = " " else: join_char = "" spans_copy = spans[:] if remove_intege...
5,358,370
def cf_resource_pool(cli_ctx, *_): """ Client factory for resourcepools. """ return cf_connectedvmware(cli_ctx).resource_pools
5,358,371
def make_packing_list(doc): """make packing list for Product Bundle item""" if doc.get("_action") and doc._action == "update_after_submit": return parent_items = [] for d in doc.get("items"): if frappe.db.get_value("Product Bundle", {"new_item_code": d.item_code}): for i in get_product_bundle_items(d.item_co...
5,358,372
def init_log(): """ Initialise the logging. """ level = script_args.log_level log_dir = os.path.abspath(script_args.log_dir) logger = logging.getLogger(__name__) log_format = ( '[%(asctime)s] [%(levelname)s] ' '[%(name)s] [%(funcName)s():%(lineno)s] ' '[PID:%(process)d] %(mes...
5,358,373
def get_bcolz_col_names(cols): """整理适应于bcolz表中列名称规范,返回OrderedDict对象""" trantab = str.maketrans(IN_TABLE, OUT_TABLE) # 制作翻译表 # col_names = OrderedDict( # {col: get_acronym(col.translate(trantab)) for col in cols}) col_names = OrderedDict() for col in cols: if col in (AD_FIELD_NAME, ...
5,358,374
def classify_loss(logits, target, eps): """ """ if eps > 0: loss = cross_entropy_with_smoothing(logits, target, eps, None) else: loss = F.cross_entropy(logits, target.view(-1)) return loss
5,358,375
def flip(position, adjacent): """finds the furthest position on grid up to which the player has captured enemy pieces""" interval = (adjacent[0] - position[0], adjacent[1] - position[1]) if adjacent[0] < 0 or adjacent[0] > (8*tile_size): return False elif adjacent[1] < 0 or adjacent[1] > (8*til...
5,358,376
def is_android_raw(raw): """ Returns a string that describes the type of file, for common Android specific formats """ val = None # We do not check for META-INF/MANIFEST.MF, # as you also want to analyze unsigned APKs... # AndroidManifest.xml should be in every APK. # classes.dex an...
5,358,377
def icmp_worker(shutdown: Event, q: queue.Queue): """A worker thread which processes ICMP requests; sending packets and listening for matching responses.""" state = {} with ICMPv4Socket(None, True) as sock: while not shutdown.is_set(): # Send one try: item =...
5,358,378
def zeros_from_spec(nested_spec, batch_size): """Create nested zero Tensors or Distributions. A zero tensor with shape[0]=`batch_size is created for each TensorSpec and A distribution with all the parameters as zero Tensors is created for each DistributionSpec. Args: nested_spec (nested Te...
5,358,379
def type_to_str(t): """Return str of variable type.""" if not hasattr(t, "broadcastable"): return str(t) s = broadcastable_to_str(t.broadcastable) if s == "": s = str(t.dtype) else: s = dtype_to_char(t.dtype) + s return s
5,358,380
def install_packages(): """ will Install python packages for accessing google cloud :return: """ print("Installing packeges.") print_log("Initiated...") global pip_sources for pip_pkg in pip_sources: s = check_call([sys.executable, '-m', 'pip', 'install', pip_pkg]) print...
5,358,381
def save(self, fname="", ext="", slab="", **kwargs): """Saves all current database information. APDL Command: SAVE Parameters ---------- fname File name and directory path (248 characters maximum, including the characters needed for the directory path). An unspecified direc...
5,358,382
def test_feature_flexiblerollout_stickiness_50_customfield_39(unleash_client): """ Feature.flexible.rollout.custom.stickiness_50 should be enabled without customField=39 """ # Set up API responses.add(responses.POST, URL + REGISTER_URL, json={}, status=202) responses.add(responses.GET, URL + FEA...
5,358,383
def rollout( env, agent, max_path_length=np.inf, render=False, render_kwargs=None, fast_rgb=True ): """ The following value for the following keys will be a 2D array, with the first dimension corresponding to the time dimension. - observations - acti...
5,358,384
def _get_colors(data, verbose=False): """ Get how often each color is used in data. Parameters ---------- data : dict with key 'path' pointing to an image verbose : bool, optional Returns ------- color_count : dict Maps a grayscale value (0..255) to how often it was...
5,358,385
def data_dir(): """The data directory.""" return DATA
5,358,386
def create_single_test(j): """Walk through the json cases and recursively write the test cases""" si = [] for tnum, c in enumerate(j['cases']): if 'cases' in c: si.extend(create_single_test(c)) else: si.extend(write_testcase(c, tnum)) return si
5,358,387
def _token_text(token): """Helper to get the text of a antlr token w/o the <EOF>""" istream = token.getInputStream() if istream is None: return token.text n = istream.size if token.start >= n or token.stop >= n: return [] return token.text
5,358,388
def show_interface(enode, dev, shell=None): """ Show the configured parameters and stats of an interface. :param enode: Engine node to communicate with. :type enode: topology.platforms.base.BaseNode :param str dev: Unix network device name. Ex 1, 2, 3.. :rtype: dict :return: A combined dict...
5,358,389
def status(task=None, tasktypes=None, nightstr=None, states=None, expid=None, spec=None, db_postgres_user="desidev_ro"): """Check the status of pipeline tasks. Args: Returns: None """ dbpath = io.get_pipe_database() db = pipedb.load_db(dbpath, mode="r", user=db_postgres_us...
5,358,390
def event_role_invite(transaction): """ GET /role-invites/1/event :param transaction: :return: """ with stash['app'].app_context(): event = EventFactoryBasic() db.session.add(event) role_invite = RoleInviteFactory() db.session.add(role_invite) db.session....
5,358,391
def get_params_for_category_api(category): """Method to get `GET` parameters for querying MediaWiki for category details. :param category: category name to be passed in params. :return: GET parameters `params` """ params = CATEGORY_API_PARAMS.copy() params['cmtitle'] = 'Category:' + category ...
5,358,392
def get_dict_or_generate(dictionary, key, generator): """Get value from dict or generate one using a function on the key""" if key in dictionary: return dictionary[key] value = generator(key) dictionary[key] = value return value
5,358,393
def test_number_columns_defaults_to_3(entries_27, settings_number_of_columns_null): """The number of columns defaults to 3 if not provided""" instance = EvenVMCView() rows = instance.process_entries(entries_27) num_cols = len(rows[0]) assert num_cols == 3
5,358,394
def createNotInConfSubGraph(graphSet, possibleSet): """ Return a subgraph by removing all incoming edges to nodes in the possible set. """ subGraph = {} for i in graphSet: subGraph[i] = graphSet[i] - possibleSet return subGraph
5,358,395
def _backprop_gradient_pure(dL, L): """ Given the derivative of an objective fn with respect to the cholesky L, compute the derivate with respect to the original matrix K, defined as K = LL^T where L was obtained by Cholesky decomposition """ dL_dK = np.tril(dL).copy() N = L.shape[...
5,358,396
def get_random_instance() -> random.Random: """ Returns the Random instance in the random module level. """ return random._inst
5,358,397
def to(cond, inclusive = True): """ Stream elements until the one that fits some condition. Arguments: cond -- Either a function or some other object. In the first case, the function will be applied to each element; in the second case, the object will be compared (using =...
5,358,398
def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, ...
5,358,399