content
stringlengths
22
815k
id
int64
0
4.91M
def cmap_to_mayavi(colormap: Colormap) -> np.ndarray: """ Convert a matplotlib colormap to mayavi format. Args: colormap: A matplotlib colormap object. Returns: The equivalent mayavi colormap, as a (255, 4) numpy array. """ return (colormap(np.linspace(0, 1, 255)) * 255).astype...
5,304,000
def show_task(project_id): """shows the tasks of a project that are stored in the database, given the project_id""" return render_template("project_tasks.html", project=Project.query.filter_by(project_id=project_id).first(), tasks=Task.query.filter_by(project_id=project_id).all())
5,304,001
def create_information_tear_sheet(factor_data, group_adjust=False, by_group=False): """ Creates a tear sheet for information analysis of a factor. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex D...
5,304,002
def get_fig_pv_combined(pv: PV, example_index: int): """ Create a combined plot 1. Plot the pv intensity in time 2. Plot the pv intensity with coords and animate in time """ traces_pv_intensity_in_time = get_trace_all_pv_systems( pv=pv, example_index=example_index, center_system=False ...
5,304,003
def data_frame_empty_typed(column_types: dict): """Creates and empty DataFrame with dtypes for each column given by the dictionary. Arguments: column_types (dict): A key, dtype pairs Returns: DataFrame: An empty dataframe with the typed columns """ df = pd.DataFrame() for n...
5,304,004
def are_periodic_neighbors(world_size, a, b): """ Given the world size and two ranks, return wether two ranks are periodic neighbours (i.e. they are in opposite borders of the grid). """ nrows, ncols = get_grid_size(world_size) pos = get_node_pos(world_size, False) if (ncols > 2) and (pos[a...
5,304,005
def file_content_to_list(file): """ Append each line of the file to a theèlist :param file: The file to transform into a theèlist :return: The the list """ lst = [] with open(file) as file_alias: for line in file_alias: lst.append(line) return lst
5,304,006
def ceph_health_check_base(namespace=None): """ Exec `ceph health` cmd on tools pod to determine health of cluster. Args: namespace (str): Namespace of OCS (default: config.ENV_DATA['cluster_namespace']) Raises: CephHealthException: If the ceph health returned is not HEALTH...
5,304,007
def _hash_layer(layer: Sequence[Hash32]) -> Sequence[Hash32]: """Calculate the layer on top of another one.""" return tuple(_calc_parent_hash(left, right) for left, right in partition(2, layer))
5,304,008
def RNN_classification(dataset, filename, save_model=False): """ Classification of data with a recurrent neural network, followed by plotting of ROC and PR curves. Parameters --- dataset: the input dataset, containing training and test split data, and the corresponding labels for ...
5,304,009
def get_sample_names(exprs_fname, start, end): """Loads PANDA input expression matrix to extract sample names from TSV. Args: exprs_fname (str): PANDA input expression matrix TSV start (int): start index (1-based inclusive) end (end): end index (1-based inclusive) Returns: ...
5,304,010
def test_tool_plugin_get_user_flags_invalid_level(): """Test that we return an empty list for invalid levels.""" arg_parser = argparse.ArgumentParser() resources = Resources([os.path.join(os.path.dirname(__file__), 'user_flags_config')]) config = Config(resources.get_file("config.yaml")) plugin_cont...
5,304,011
def get_users(uid=1, dl=0): """Method to get county coordinators emails.""" try: emails = [] sql = QUERY[uid] df = run_query(sql) data = df.values.tolist() for dt in data: val = dt[0] if dl > 0: val = {dt[0]: dt[1]} emai...
5,304,012
def make_function(match): """Returns a Function JSON Object""" return { 'type': 'f', #f for function 'name': match.group('name'), 'return_type': match.group('return_type'), 'parameters': get_parameters(match.group('parameters')) }
5,304,013
def table_class_imbalance(df, path): """ Saves a .csv file summary table with calculated percentage of examples by class to highlight class imbalance in the given path. Parameters ---------- df : pd.DataFrame data path : string the path/file prefix where output file will be save...
5,304,014
def Decimal_to_Binary(x : str) -> str: """ It Converts the Given Decimal Number into Binary Number System of Base `2` and takes input in `str` form Args: x `(str)` : It is the Positional Argument by order which stores the Decimal Input from User. Returns (str): The Output `returned...
5,304,015
def find_blobs(image, mask, border=0, maxblobs=300, maxblobsize=100, minblobsize=0, maxmoment=None, method="central", summary=False): """ find blobs with particular features in a map """ shape = image.shape ### create copy of mask since it will be modified now tmpmask = numpy.array(mask, numpy.int32) ## zero ou...
5,304,016
def register_and_center_via_speckles(cube_sci, cube_ref=None, AlignmentIterations = 5, gammaval = 1, min_spat_freq = 0.5, max_spat_freq = 3, fwhm = 8., debug = False , NegFit = True, recenter_median = True, subframesize = 151, imlib='opencv',interpolation='bilinear'): """ Registers frames based on the median speckl...
5,304,017
def sample_tv_signal( n, j_min=10, j_max=20, min_dist=5, bound=5, min_height=0.2, n_seed=None, t_seed=None, ): """ Creates a random piecewise constant signal. Creates a piecewise constant signal of shape (n,) with a random number of "jumps" (discontinuities). With minima...
5,304,018
def test_handle_string_invalid(artifacts_kwargs): """ GIVEN artifacts with an artifact that is not supported WHEN _handle_string is called with the artifacts THEN MalformedSchemaError is raised. """ artifacts = types.ColumnArtifacts("string", **artifacts_kwargs) with pytest.raises(exception...
5,304,019
def float32_variable_storage_getter(getter, name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, *args, **kwargs): """Custom variable getter that forces trainable variables to be stored in float32 precision a...
5,304,020
def _squad_em(pred_data, ref_data): """EM score for reading comprehension task""" em_score = eval_exact_match_score(pred_data, ref_data) return em_score
5,304,021
def add_slash(text: str): """returns the same text with slash at the end""" return text + '/'
5,304,022
def appndd(item, cell): """ Append an item to a double precision cell. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndd_c.html :param item: The item to append. :type item: Union[float,Iterable[float]] :param cell: The cell to append to. :type cell: spiceypy.utils.support_type...
5,304,023
def parse_response(text: str) -> Tuple[bool, str]: """ Parses a CommCare HQ Submission API response. Returns (True, success_message) on success, or (False, failure_message) on failure. >>> text = ''' ... <OpenRosaResponse xmlns="http://openrosa.org/http/response"> ... <message nature="...
5,304,024
def launch(context, service_id, subscription, every=EVERY): """ Initialize the module. """ return MeasRepUe(context=context, service_id=service_id, every=every, subscription=subscription)
5,304,025
def __detect_str_type(data) -> str: """ :column_type str :rtype str """ r = re.search("[^=]+=[^&]*&*", data) # application/x-www-form-urlencoded pattern if r: return "application/x-www-form-urlencoded" else: return "plain/text"
5,304,026
def iterable(x): """Check if the input is iterable, stolen from numpy.iterable()""" try: iter(x) return True except: return False
5,304,027
def search(phrases, limit): """Print cards whose question or answer combined contain all inputed phrases""" conn = sqlite3.connect(DATABASE) c = conn.cursor() query = 'SELECT * FROM cards WHERE ' for phrase in phrases: query += '(instr("question", "{}") > 0 OR instr("answer", "{}") > 0)'.for...
5,304,028
def conv2d_input_grad_wrap(input_size, weight, grad_output, stride, padding, dilation, groups): """Wrap of conv2d_input_grad for pytorch.""" input_size = tuple(i.item() for i in input_size) stride = tuple(_x.item() for _x in stride) padding = tuple(_x.item() for _x in padding)...
5,304,029
def test_with_good_arguments( get_wallpapers_filenames, get_temp_directory_path, create_delete_temp_directory, ): """ Test 'download_wallpapers' method of WallpaperDownloader class. Method is tested with the good parameters and checks the actual download of the files. Args: get...
5,304,030
def sort_key(entry): """Get the value for a key""" return entry[ds]
5,304,031
def estimation_error_rate(y_true, y_pred): """ Compute estimation error rate score Estimation error rate represents the mean absolute error computed between true and predicted labels, expressed as a percentage, i.e. mae / range(y_true). It is defined as follows: eer = mae / range(y_true) m...
5,304,032
def ldns_resolver_new_frm_fp(*args): """LDNS buffer.""" return _ldns.ldns_resolver_new_frm_fp(*args)
5,304,033
async def _populate_downloads(executor, dataset: Dataset, destination: str, prefix: str, recursive: bool) -> Tuple[List[ObjectState], int]: """function to concurrently check if the list of files exist in the object store and creates ObjectState instances Args: executor: ex...
5,304,034
def plot_gabor_contrib(prf_dir, roi, lhmerged=True): """Plot tunning contribution of each gabor sub-banks VS. ecc.""" df_list = [] hemis = ['lh', 'rh'] hemi_flags = [1, 1] for hemi in hemis: roi_dir = os.path.join(prf_dir, roi+hemi) if not os.path.exists(roi_dir): print '...
5,304,035
def requires_roles(roles): """ Assert the user has one of the required roles. :param list roles: the list of role names to verify :raises freshmaker.errors.Forbidden: if the user is not in the role """ def wrapper(f): @wraps(f) def wrapped(*args, **kwargs): if any(us...
5,304,036
def test_find_next_time_expression_exiting_dst(now_dt, expected_dt): """Test exiting daylight saving time for find_next_time_expression_time.""" tz = dt_util.get_time_zone("Europe/Vienna") dt_util.set_default_time_zone(tz) # match on 02:30:00 every day pattern_seconds = dt_util.parse_time_expression...
5,304,037
def test_simulation_no_valid_choosers(m): """ If there are no valid choosers after applying filters, simulation should exit. """ m.out_chooser_filters = 'choice == -1' m.run()
5,304,038
def cull_gammas(x, y, mRNA_to_miRNA: np.ndarray) -> np.ndarray: """ Removes gammas (sets them to 0) in such a way that the network remains connected. Currently very hacky: uses DFS to ensure connectivity. Would work better using a min-cut algorithm. """ legal = False while not legal: tem...
5,304,039
def print_solution(manager, routing, assignment): """Prints assignment on console.""" print('Objective: {} miles'.format(assignment.ObjectiveValue())) index = routing.Start(0) plan_output = 'Route for vehicle 0:\n' route_distance = 0 while not routing.IsEnd(index): plan_output += ' {} ->...
5,304,040
def primality_test(n: PositiveInt) -> bool: """Determine whether a number is a prime.""" # Optimization 1: Test from 2 to sqrt(n) only, since a factor will appear twice when we test from 2 to n. # Optimization 2: Do not test even numbers except 2, since all even numbers is divisible by 2. # Optimizati...
5,304,041
def trace(output_id: str, address: str = ""): """ CLI for trace. """ # Set address if address and len(address) > 0: set_address(address) res = web_trace(output_id) click.echo(res[0]["label"]) if "childNodes" in res[0].keys(): show_res(res=res[0]["childNodes"], indent=1, c...
5,304,042
def download_data(urls): """Download the binaries from a URL and return the destination filename Retry downloading if either server or connection errors occur on a SSL connection urls: list of several urls (mirror servers) or single url (string) """ # make sure urls becomes a list, in case use...
5,304,043
def hotfix_deploy(): """ deploy ONLY the code with no extra cleanup or syncing for small python-only hotfixes """ if not console.confirm('Are you sure you want to deploy to {env.environment}?'.format(env=env), default=False) or \ not console.confirm('Did you run "fab {env.environment} prein...
5,304,044
def diffusion_coeff(t, sigma): """Compute the diffusion coefficient of our SDE. Args: t: A vector of time steps. sigma: The $\sigma$ in our SDE. Returns: The vector of diffusion coefficients. """ return sigma**t
5,304,045
def get_step_chart(simulation_objects): """Get the step chart of the container levels.""" fig = plt.figure(figsize=(14, 7)) for obj in simulation_objects: df = get_log_dataframe(obj) container_list = obj.container.container_list for container in container_list: if hasatt...
5,304,046
def byte_xor(b: bytes, i: int) -> bytes: """ Calculate 'b XOR i' """ return int(bytes_to_int(b) ^ i).to_bytes(len(b), 'big')
5,304,047
def get_file_name(f_size): """ Returns file name whose filesize correstponds with the files size passed in as parameter. """ for x,(z,y) in movie_dict.items(): if z == f_size : return x
5,304,048
def test_auth_simple2_nok_1(conf_simple2, payload_simple2): """simple auth test nok because login does not match.""" jwt_token = jwt.encode(payload_simple2, "SECRET", "HS256").decode("utf-8") assert jwt_auth("user2@domain.ext", jwt_token, conf_simple2) is False
5,304,049
def get_form_errors(form): """ Django form errors do not obey natural field order, this template tag returns non-field and field-specific errors :param form: the form instance """ return { 'non_field': form.non_field_errors(), 'field_specific': OrderedDict( (field, fo...
5,304,050
def compute_scalar_metrics(metrics_dict: ScalarMetricsDict, subject_ids: Sequence[str], model_output: torch.Tensor, labels: torch.Tensor, loss_type: ScalarLoss = ScalarLoss.BinaryCrossEntropyWithLogits) -> None: ...
5,304,051
def query_db(db, query, args=(), one=False): """ Queries the database and returns a list of dictionaries. https://flask-doc.readthedocs.org/en/latest/patterns/sqlite3.html#easy-querying """ with db.cursor() as cur: logger.debug(f"Query: {query}") cur.execute(query, args) rv ...
5,304,052
def is_valid_url(url: str) -> bool: """Evaluate whether or not a URL is acceptible for retrieval.""" return current_session().is_valid_url(url)
5,304,053
def plot_poly(x,y,degree, *args): """ Plot the data with given degree of polynomial. Example: plot_poly(x,y,3) plot_poly(x,y,3,'x','y','title') Returns: p Usage: x_value = 100 p(x_value) gives the polynomial fit of x_value """ plt.figure(figsize=(12,8)) pl...
5,304,054
def get_kube_res_by_name(namespace, kube_res, res_name): """ A Wrapper of kubectl which parses resources from json :param res_name: The name of the resource :type res_name: str :param namespace: :type namespace: str :param kube_res: statefullset, deployment ... :type kube_res: str :r...
5,304,055
def __graph_initialization(module: MaxPooling, x: torch.Tensor, pos: torch.Tensor, edge_index: Adj = None) -> Data: """Graph initialization for asynchronous update. Both the input as well as the output graph have to be stored, in order to avoid repeated computation. The input graph is used for spotting cha...
5,304,056
def step_impl(context): """ :type context behave.runner.Context """ time.sleep(0.01) ok_(context.broker_socket.message["errorMessage"] == "Mockup error.")
5,304,057
async def choose(ctx: commands.Context, *choices: str): """Chooses between multiple choices.""" await ctx.send(random.choice(choices))
5,304,058
def comment_exists_in_blogpost(func): """Checks to make sure the comment exists or renders a 404""" def wrapper(self, blog_id, comment_id, *args, **kwargs): blog_post = BlogPost.get_by_id(int(blog_id), parent=BLOG_KEY) int_comment_id = int(comment_id) comment = Comment.get_by_id(int_comm...
5,304,059
def test_anomaly_table(): """Test to see that the database has an anomalies table""" assert 'anomaly' in di.engine.table_names()
5,304,060
def log_sum_exp(tensor, dim=-1): """ Safe log-sum-exp operation """ return torch.logsumexp(tensor, dim)
5,304,061
def test_tpe_optimizer_two_inputs(database, monkeypatch): """Check functionality of BayesianOptimizer wrapper for 2 dimensions.""" monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__))) process = subprocess.Popen(["orion", "--config", "./orion_config_tpe.yaml", "./rose...
5,304,062
def get_vrf_group(files_list: List[str]) -> Dict[str, List[str]]: """ Group files by VRF name. """ groups = {} for filename_path in files_list: filename_path = filename_path.replace("\\", "/") # print(filename_path) if "show" in filename_path \ or "display" in filename...
5,304,063
def get_legislator_political_positions_by_slug(slug): """ Get just this legislator's political positions https://github.com/INN/maine-legislature/issues/82 """ copy = get_copy() political_positions = {} leg_id = get_legislator_id_by_slug(slug) for row in copy['position_political']: ...
5,304,064
def prompt_messages(): """ Prompt the user for opening messages and :return: the workspace id of the user if he wants to change the timestamp """ ws_id = 0 if check_logs_timestamp(): input_message = "would you like to change the log timestamp from log collection time to log creation time...
5,304,065
def log_info_mssg_with_timestamp(mssg): """ For information messages only. Not for warning or error. Arguments: mssg -- 'message for operations' """ # Send to log. print time.asctime() logging.info(time.asctime()) log_info_mssg(mssg)
5,304,066
def config_bgp_neighbor_properties(dut, local_asn, neighbor_ip, family=None, mode=None, **kwargs): """ :param dut: :param local_asn: :param neighbor_ip: :param family: :param mode: :param kwargs: :return: """ st.log("Configuring the BGP neighbor properties ..") properties = ...
5,304,067
def scr_total( bscr, scr_op ): """ This function simply adds the SCR_Op to the BSCR """ return bscr + scr_op
5,304,068
def _eval_bernstein_dd(x, fvals): """Evaluate d-dimensional bernstein polynomial given grid of valuesv experimental Parameters ---------- x : array_like Values at which to evaluate the Bernstein polynomial. fvals : ndarray Grid values of coefficients for Bernstein polynomial ba...
5,304,069
def test_app_get_token_bad_credentials(username, password, client): """ test the example login with invalid credentials """ response = client.post( "/token", data={"username": username, "password": password} ) assert response.status_code >= 400
5,304,070
def check_confidence_interval_arguments( alpha: float = 0.05, n_bootstrap_samples: int = 10000, random_state: Optional[int] = None, ) -> Optional[ValueError]: """Check confidence interval arguments. Parameters ---------- alpha: float, default=0.05 Significant level of confidence int...
5,304,071
def worker(group_name): """ The main worker logic includes initialize proxy and handle jobs from the master. Args: group_name (str): Identifier for the group of all communication components """ proxy = Proxy(group_name=group_name, component_type="worker", ...
5,304,072
def load_tff_dat(fname, processor=None): """Read a tff.dat or dff.dat files generated by tff command Parameters ---------- fname : file or str File, or filename processor: callable or None A final output processor, by default a tuple of tuples is returned Returns ------- ...
5,304,073
def iter_tag_rows(repo_id: str, input_dir: str) -> Iterator[tuple]: """Iterate over tag rows of a repository.""" path = get_repository_csv_path(repo_id, input_dir, 'tags.csv') with open(path) as input_file: for row in csv.DictReader(input_file): yield format_tag(row, repo_id)
5,304,074
def is_luhn(string: str) -> bool: """ Perform Luhn validation on input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers * >>> test_cases = [79927398710, 79927398711, 79927398712, 79927398713, ... ...
5,304,075
def create(type_id='', path=''): """Create a document or directory""" if g.level < 2: return abort(401) inherited_level = 1 type_item=None path = path[:-1] if path.endswith('/') else path if type_id: type_item = mongo.db.types.find_one_or_404({'_id': type_id}) inherited_...
5,304,076
def boot(sock: socket, msg_parts: list, *args, **kwargs): """Boot user from room.""" if msg_parts[1:]: bootee = " ".join(msg_parts[1:]) ChatIO().pack_n_send(sock, prefixes.dict["client"]["cmds"]["boot"], bootee) else: print(sysMsgList.bootNoUser)
5,304,077
def test_vcfield_exact_lookups_work(modelname, name, number, parent_int, parent_str, lookup_arg, testmodels, make_instance, noise_data): """ Exact-match lookups on VirtualCompFields that match something should behave as follows: * T...
5,304,078
def latest_date_for_day( start_date: datetime_.date, end_date: datetime_.date, day_of_month: int ) -> Optional[datetime_.date]: """ Given an integer day of a month, return the latest date with that day of the month, bounded by the supplied start_date and end_date. If no such date exists, return None. ...
5,304,079
def handle_artist(command): """ Process the artist command """ conn = sqlite3.connect('myjazzalbums.sqlite') cur = conn.cursor() if command [-1] == "?": artist_name = command[6:-1].strip().title() else: artist_name = command[6:].strip().title() if artist_name == "Ken...
5,304,080
def cold_start( movielens: MovieLens, als_config: Dict[str, Any], split_test_users_into: int, ) -> None: """ >>> import os >>> als_config = { ... "factors": 1, ... "use_gpu": os.environ.get("TEST_ON_GPU", False), ... "random_state": 0 ... } >>> cold_start(getfi...
5,304,081
def generate_lda_distance(df, model, dictionary): """ 计算 LDA 主题模型距离 """ def compute_topic_distances(row): q1_bow = dictionary.doc2bow(row['cleaned_question1'].split()) q2_bow = dictionary.doc2bow(row['cleaned_question2'].split()) q1_topic_vec = np.array(model.get_document_topics...
5,304,082
def emcee_plots(lnp_fn, sampler, theta0=None, figout=True, plt=None, marginalized=True, triangle=True, chains=True): """ Plots diagnostic figures """ if plt is None: import pylab as plt from figrc import plotMAP, plotCorr, plotDensity import figrc d = {} ndim = lnp_fn....
5,304,083
def build_get_request(base, service_name, operation_name=None, params=None): """ Builds a get request out of a service/operation and optional params. operation_name may be left blank if going to a custom url. """ urlarr = [base, service_name] if operation_name is not None: urlarr.append(...
5,304,084
def rsys2graph(rsys, fname, output_dir=None, prog=None, save=False, **kwargs): """ Convenience function to call `rsys2dot` and write output to file and render the graph Parameters ---------- rsys : ReactionSystem fname : str filename output_dir : str (optional) path to d...
5,304,085
def upload_file(target_filepath, metadata, access_token, datatypes=None, base_url=OH_BASE_URL, remote_file_info=None, project_member_id=None, max_bytes=MAX_FILE_DEFAULT): """ Upload a file from a local filepath using the "direct upload" API. To learn more about this API endpo...
5,304,086
def dense(n_prev, n, *, activation="relu"): """Creates a dense, fully-connected layer. Args: n_prev: number of inputs from the previous layer n: number of nodes for this layer activation: activation function for this layer, one of {sigmoid, tanh, relu} """ unit = _nn...
5,304,087
def load_poses(pose_path: str, skip_params: bool) -> Tuple[tf.Tensor, tf.Tensor, float]: """Loads poses from file.""" with open(pose_path) as pose_file: pose_dict = json.load(pose_file) poses = [] parameters = [] for pose in pose_dict['frames']: poses.append(pose['transform_matrix'...
5,304,088
def patternMatch(pattern, dir='./'): """ :pattern: A file pattern to match the desired output. Input to a glob, so use traditional unix wildcarding. :dir: The directory to search. :returns: list of matching files in the target directory """ files = [] files = glob.glob(dir+pattern) ret...
5,304,089
def add_histogram_summary(tensor, name=None, prefix=None): """Adds a histogram summary for the given tensor. Args: tensor: A variable or op tensor. name: The optional name for the summary. prefix: An optional prefix for the summary names. Returns: A scalar `Tensor` of type `string` whos...
5,304,090
def tasks_page(): """ Tasks and completions page: tasks.html """ project = project_get_or_create() label_config = open(project.config['label_config']).read() # load editor config from XML task_ids = project.get_tasks().keys() completed_at = project.get_completed_at(task_ids) num_workers= ...
5,304,091
def update_model_weights(model, updates, weights_structure=None, force_update=False, trainable=True): """Update model weights directly inserting `updates` at correct locations. `updates` must be aligned to `model.(non_)trainable_weights` and is inserted according to model `weights_...
5,304,092
def cors_middleware( *, allow_all: bool = False, origins: UrlCollection = None, urls: UrlCollection = None, expose_headers: StrCollection = None, allow_headers: StrCollection = DEFAULT_ALLOW_HEADERS, allow_methods: StrCollection = DEFAULT_ALLOW_METHODS, allow_credentials: bool = False, ...
5,304,093
def save_df_to_pq(dataframe, where, *args, **kwargs): """ Save Pandas to Parquet, either using: 1) pyarrow.parquet.write_table is where file extension is ".parquet" https://arrow.apache.org/docs/python/generated/pyarrow.parquet.write_table.html or 2) pyarrow.parquet.write_dataset https://ar...
5,304,094
def trim_matrix(mat, i): """ Trims a matrix by deleting both a row and a column in a matrix (warning: inefficient) :param mat: matrix :param i: row index :return: """ mat = mat.copy() mat = mat.tocsr() delete_row_csr(mat, i) mat = mat.transpose() mat = mat.tocsr() delete...
5,304,095
def removeBottomMargin(image, padding): """Remove the bottom margin of width = padding from an image Args: image (PIL.Image.Image): A PIL Image padding (int): The padding in pixels Returns: PIL.Image.Image: A PIL Image """ return image.crop((0, 0, image.width, image.height - padding))
5,304,096
def num(val): """Return val as an int, float, or bool, depending on what it most closely resembles.""" if isinstance(val, (float, int)): return val elif val in ('True', 'False'): return val == 'True' elif isinstance(val, str): try: return int(val) except ...
5,304,097
def get_alerts_request(has_share_mode=None, resolution=None, agent_id=None, host_name=None, condition_id=None, limit=None, offset=None, sort=None, min_id=None, event_at=None, alert_id=None, matched_at=None, reported_at=None, source=None): """ returns the response ...
5,304,098
def quick_stop_adpd(led='G'): """ :param led: ['G' | 'R' | 'IR' | 'B'] :return: """ cfg_dict = {'G': 'adpd6', 'R': 'adpd7', 'IR': 'adpd8', 'B': 'adpd9'} led = led.upper() watch_shell.quick_stop('adpd', cfg_dict[led])
5,304,099