content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def demosaic(cfa, pattern='RGGB'): """ Returns the demosaiced *RGB* colourspace array from given *Bayer* CFA using bilinear interpolation. Parameters ---------- CFA : array_like *Bayer* color filter array (CFA). pattern : unicode, optional **{'RGGB', 'BGGR', 'GRBG', 'GBRG'}*...
af50a6a8f19cbcbf60cc9e590fa12c12df65e0ca
10,497
import random def compare_skill(embedding, idx=None): """Display a skill its most similar skills in the embedding. Args: embedding (array): skills embedding idx (int): index to select skill, defaults to None (if None, a random index is chosen) Returns: df: dataframe o...
f885e744a3f32ba297a2429e7c69a2d7c37670da
10,499
def translate_df(df: DataFrame) -> DataFrame: """ Función para traducir directamente un DataFrame :param df: DataFrame a traducir :return: DataFrame """ regs = df.Country.count() #Contamos la cantidad de registros en la columna 'Country' para servir como delimitador del for # Usamos un for pa...
4cbe6281ca8b9900243a9928c26462bd35c38bdf
10,500
def _process_caption_jieba(caption): """Processes a Chinese caption string into a list of tonenized words. Args: caption: A string caption. Returns: A list of strings; the tokenized caption. """ tokenized_caption = [] tokenized_caption.extend(jieba.cut(caption, cut_all=False)) re...
d57ec779ff211217322c5a5c8399fc607c2d2919
10,502
import requests def create_connection(graph, node1, node2, linktype, propertydict=None, allow_dup=False): """ :param graph: :param node1: :param node2: :param linktype: :param propertydict: :return: """ data = {} data["graph"] = graph data["node1"] = node1 data["node2...
fcbb830d023005fdf008ecbcd73bcd6470545b81
10,503
from src.architectures import resnet50 as nn from src.architectures import resnet152 as nn from src.architectures import vgg16 as nn from src.architectures import vgg19 as nn def get_nn(config): """ Args: config: Path to the confi file generated during training Returns: Model instance ...
99ba4a9473b603800b318c49f0b8bbc02d504778
10,504
from typing import Any from typing import Union def get_functor(value: Any) -> Union[Functor, FunctorIter, FunctorDict]: """ Returns a base functor instance with a value property set to 'value' of the class for either dictionary, other iterable or uniterable type, and, where passed, a const property s...
475ed04f052daa4d301f29c511f8d8ad4ce2b0f3
10,505
def split_bibtexs_by_bib_style(bibtexs): """ Args: bibtexs (list of Queryset of Bibtex): Returns: list of tuple: (Style Key, Display Name, Bibtex List) """ # Get STYLE KYES bibtex_backet = dict() choices = expand_book_style_tuple(Book.STYLE_CHOICES) + list( Bibtex...
00736e347b8b2601a418ba5f19d872a27e2ed13c
10,506
def apply_gates(date, plate, gates_df, subpopulations=False, correlation=None): """ Constructs dataframe with channels relevant to receptor quantification. """ if date == "5-16": receptors = ['CD127'] channels = ['BL1-H'] else: receptors = ['CD25', 'CD122', 'CD132'] channels ...
725df1a46a90f28da56e329a492e1534d81737ae
10,507
from typing import Callable from typing import Optional def action_interaction_exponential_reward_function( context: np.ndarray, action_context: np.ndarray, action: np.ndarray, base_reward_function: Callable[[np.ndarray, np.ndarray], np.ndarray], action_interaction_weight_matrix: np.ndarray, r...
44d4b9a9a50334f273210ae8014aebe46661c61a
10,508
def deserialize_once_dates(dates): """ Deserializes the dates as expected within a once dates object. :param dates: The dates object :return: A 2-tuple containing all the deserialized date parameters """ return ( du_parser.parse(dates[RULE_ONCE_S_TIME]), du_parser.parse(dates[RUL...
1b1544abcf692c091e04965cb754279f4ecdf0f4
10,509
import copy def gen_CDR_MitEx( device_backend: Backend, simulator_backend: Backend, n_non_cliffords: int, n_pairs: int, total_state_circuits: int, **kwargs ) -> MitEx: """ Produces a MitEx object for applying Clifford Circuit Learning & Clifford Data Regression mitigation methods w...
04d78d36c3ef10252fd33079e0f44c7eab433bed
10,510
import trace def lambda_sum_largest_canon(expr, args): """ S_k(X) denotes lambda_sum_largest(X, k) t >= k S_k(X - Z) + trace(Z), Z is PSD implies t >= ks + trace(Z) Z is PSD sI >= X - Z (PSD sense) which implies t >= ks + trace(Z) >= S_k(sI + Z) >= S_k(X) We use the fact that ...
5f6d6a44c67255eb27ff98d48570303768fcdc61
10,511
def compare_bib_dict(item1, item2): """ compare bibtex item1 and item 2 in dictionary form """ # unique id check col_list = ["doi", "pmid", "pmcid", "title", "local-url"] for c in col_list: if (item1.get(c, "1") != '') and (item1.get(c, "1") == item2.get(c, "2")): return 1.0 s...
87d974adec31c5c5fb130d0b5fd8a2b750f67eff
10,512
def find_residues_lsfd(poles, H, fs): """Find residues from poles and FRF estimates Estimate the (in band) residue matrices from poles and FRF's by the Least Squares Frequency Domain Algorithm (LSFD). A residue matrix is the outer product of the mode vector and the modal participation factor. The ...
f4cd257c8478f32b04f7737197451371f6e1bb12
10,513
def create_regularly_sampled_time_points(interval: pendulum.Duration, start_time_point: pendulum.DateTime, count: int): """ Create a sequence of `count` time points starting at `start_time_point`, `interval` apart. Args: interval: The time interval between each point. start_time_point: The ...
22b133e10c6385b577ec9f1c32df932b6638e0f5
10,514
def create_model(bert_config, is_training, input_ids_list, input_mask_list, segment_ids_list, use_one_hot_embeddings): """Creates a classification model.""" all_logits = [] input_ids_shape = modeling.get_shape_list(input_ids_list, expected_rank=2) batch_size = input_ids_shape[0] seq_length = ...
a96b5804f43561db25ad1d24acfa2b476318a904
10,515
import numpy def where(condition: numpy.typing.ArrayLike, *args: PolyLike) -> ndpoly: """ Return elements chosen from `x` or `y` depending on `condition`. .. note:: When only `condition` is provided, this function is a shorthand for ``np.asarray(condition).nonzero()``. Using `nonzero` dir...
c577df0f9c7bf900026f868c06260d0e5f242732
10,517
async def async_attach_trigger( hass, config, action, automation_info, *, platform_type="event" ): """Listen for events based on configuration.""" event_types = config.get(CONF_EVENT_TYPE) removes = [] event_data_schema = None if config.get(CONF_EVENT_DATA): event_data_schema = vol.Sche...
da72cd5dfd17da52d3164c69f3a49aafedaf851a
10,518
def histogram_filter(x, lb=0, ub=1): """Truncates the tail of samples for better visualisation. Parameters ---------- x : array-like One-dimensional numeric arrays. lb : float in [0, 1], optional Defines the lower bound quantile ub : float in [0, 1], optional ...
35886093b23075a167443c29b30f2123dc1dcb70
10,519
import requests def create_tweet(food_name): """Create the text of the tweet you want to send.""" r = requests.get(food2fork_url, params={"q": food_name, "key": F2F_KEY}) try: r_json = r.json() except Exception as e: return "No recipe found. #sadpanda" # fetch top-ranked recipe ...
8bff622f3d15a184d05dc3bb9dd4291164e1ab46
10,520
from typing import List def sublist(lst1: List[T1], lst2: List[T1]) -> bool: """ Check `lst1` is sublist of `lst2`. Parameters ---------- lst1 : List[T1] List 1. lst2 : List[T1] List 2. Returns ------- bool `True` if `lst1` is sublist of `lst2`. Examp...
de687a9fa4e9b46b6dc21d3f6c3037299b2c5d55
10,521
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradien...
32c4faa4637943d2e82f5c91de75992237bb3986
10,522
from typing import Tuple import tqdm from typing import DefaultDict def combine_predictions(indices1: NpArray, confs1: NpArray, indices2: NpArray, confs2: NpArray) -> Tuple[NpArray, NpArray]: """ Joins two predictions, returns sorted top-3 results in every row """ dprint(indices1.shape...
af76da618c894396f37ad1dc48512bb3e2658770
10,523
def get_speed_limit(center, rad, speed_limit): """ Retrieves the speed limit of the intersection circle :param center: center coordinate point of the intersection circle :param rad: radius of the intersection circle :param speed_limit: speed limit of the intersection :type center: Coordinates ...
cb5ccc4e3cce4f65076f70fb8f462069c3fd16f5
10,524
def db_eval(techniques,sequences,inputdir=cfg.PATH.SEGMENTATION_DIR,metrics=None): """ Perform per-frame sequence evaluation. Arguments: techniques (string,list): name(s) of the method to be evaluated. sequences (string,list): name(s) of the sequence to be evaluated. inputdir (string): path to the technique...
caa5b557db75ac354a1e0fc3964fcf544ff8522f
10,527
def scale_constraint(source_obj, target_obj, maintain_offset=True): """ create scale constraint. :param source_obj: :param target_obj: :param maintain_offset: :return: """ return cmds.scaleConstraint(source_obj, target_obj, mo=maintain_offset)[0]
47398fc37c7510a8d02b2a372ecca4fd9c51b20e
10,528
def freq2note(freq): """Convert frequency in Hz to nearest note name. Parameters ---------- freq : float [0, 23000[ input frequency, in Hz Returns ------- str name of the nearest note Example ------- >>> aubio.freq2note(440) 'A4' >>> aubio.freq2note(220...
6810cd863b29f23f4bcbf657b5a4fc854f605640
10,529
def read_partpositions(filename, nspec, ctable=True, clevel=5, cname="lz4", quantize=None): """Read the particle positions in `filename`. This function strives to use as less memory as possible; for this, a bcolz ctable container is used for holding the data. Besides to be compressed in-memory, its ch...
7fb37c29ef6962bf77bb2d781a15d86835cbe1c6
10,530
def configure_l3(conf, tunnel_mode): """ This function creates a temporary test bridge and adds an L3 tunnel. """ s = util.start_local_server(conf[1][1]) server = util.rpc_client("127.0.0.1", conf[1][1]) server.create_bridge(DEFAULT_TEST_BRIDGE) server.add_port_to_bridge(DEFAULT_TEST_BRIDGE,...
72c8a1e782e4b147a7fd67bda5b3433438bc089a
10,533
def gradient_descent(y, tx, initial_w, gamma, max_iters): """Gradient descent algorithm.""" threshold = 1e-3 # determines convergence. To be tuned # Define parameters to store w and loss ws = [initial_w] losses = [] w = initial_w method = 'mse' for n_iter in range(max_iters): c...
147ee85a51647fed91c4c890e89e493c59ec1d14
10,534
import torch def farthest_point_sample(xyz, npoint): """ Input: xyz: pointcloud data, [B, N, 3] npoint: number of samples Return: centroids: sampled pointcloud index, [B, npoint] """ device = xyz.device B, N, C = xyz.shape # 初始化一个centroids矩阵,用于存储npoint个采样点的索引位置,大小为...
55663ede9a4306f2f9f89bbc4476bd61c06c2138
10,535
def loadData(fname='Unstra.out2.00008.athdf'): """load 3d bfield and calc the current density""" #data=ath.athdf(fname,quantities=['B1','B2','B3']) time,data=ath.athdf(fname,quantities=['Bcc1']) bx = data['Bcc1'] time,data=ath.athdf(fname,quantities=['Bcc2']) by = data['Bcc2'] time,data=ath.athdf(fname,qu...
202b61dc0c97fbcd4d0df86cede821e8cdeb14dc
10,536
def sparse_chain_crf_loss(y, x, U, b_start=None, b_end=None, mask=None): """Given the true sparsely encoded tag sequence y, input x (with mask), transition energies U, boundary energies b_start and b_end, it computes the loss function of a Linear Chain Conditional Random Field: loss(y, x) = NLL(P(y|x)),...
9bdbee3c9a634cabf63e08957beee83e22565043
10,537
import select async def query(database: Database, payload: PostionQueryIn): """ Find whether a point is within a country """ query = select([countries.c.name, countries.c.iso2, countries.c.iso3]) # Convert a GeoPoint into a format that can be used in postgis queries point = f"POINT({payload.location.l...
8459831e453ae6e33a596f18792cb8cc4e2d896f
10,539
from . import model import pysynphot as S def calc_header_zeropoint(im, ext=0): """ Determine AB zeropoint from image header Parameters ---------- im : `~astropy.io.fits.HDUList` or Image object or header. Returns ------- ZP : float AB zeropoint """ scale_ex...
9f196df1f7160f4dac77cc3ac5ff792225fb0fcb
10,540
def _convert_min_sec_to_sec(val): """ :param val: val is a string in format 'XmYsZ' like '0m5s3' meaning at secong 5,3 :return: >>> _convert_min_sec_to_sec('10m11s2') 611.2 """ _min = val.split('m')[0] _sec = val.split('m')[1].split('s')[0] _dsec = val.split('s')[1] if len(_dse...
f402e6221fa97ec5ccdb9b194478b916e85fdf85
10,541
def sitetester_home(): """ Home screen for Tester: A Tester can: a. Change their testing site b. View apspointments for the site they work at c. Create an appointment for their testing site d. View aggregate test results e. View daily test resu...
3879cbe8d2f4b9e51d9cb94362ba4eb09e1ae2cf
10,542
from datetime import datetime def datetime_to_fractional_year(input: datetime) -> float: """Converts a Python datetime object to a fractional year.""" start = date(input.year, 1, 1).toordinal() # type: ignore year_length = date(input.year + 1, 1, 1).toordinal() - start # type: ignore return input.ye...
576361cad890f709d6d02c56f53c43529211fb2b
10,543
from typing import Optional def _optical_flow_to_rgb( flow: tf.Tensor, saturate_magnitude: float = -1.0, name: Optional[str] = None, ) -> tf.Tensor: """Visualize an optical flow field in RGB colorspace.""" name = name or 'OpticalFlowToRGB' hsv = _optical_flow_to_hsv(flow, saturate_magnitude, name) ...
3e314411ae6c3efbcb619ead61d99df614959720
10,544
def shuffle_dict(dict_1, dict_2, num_shuffles=10): """ Shuffles num_shuffles times for two dictionaries that you want to compare against each other, shuffles them. returns two di """ shuffled_dict_1 = {} shuffled_dict_2 = [] for x in range(num_shuffles): for dataset_na...
6289f76ece3ecfb163ee3c9c1fe88d93fb259716
10,545
def clear_dd2_selection(val, n_clicks): """Clear Dropdown selections for Dropdown #2 (dd2) ( Dropdown to clear #2 of 2 ) Args: val (str): cascading response via `clear_dd2_selection()` callback n_clicks: int Returns: str: Resets selections to default, blank states. """ ...
66533ed8a534cf0f95d2c3d4cc5827a96b1b0aeb
10,546
def get_SHF_L_min_C(): """:return: 冷房負荷最小顕熱比率 (-)""" return 0.4
274728ea22800ade77bfe4e41bc41a05b97ac483
10,547
from typing import Union import pathlib def get_path(obj: Union[str, pathlib.Path]) -> pathlib.Path: """Convert a str into a fully resolved & expanded Path object. Args: obj: obj to convert into expanded and resolved absolute Path obj """ return pathlib.Path(obj).expanduser().resolve()
88641ea4a6ae54aea12b7d0c9afca8d6f475b8d0
10,549
import re def verify_policy_type_id(policy_type_id): """ :type policy_type_id: str :param policy_type_id: policy type id - e.g. storage-policy-00000001 :rtype: int :return: Fixed policy type ID :raises: ValueError: policy type id """ if not re.match("storage-policy-\d+", policy_type_...
ff1bf183add0f2ce1dba78345a7b9fdbc2048e6c
10,550
def f_fg_iou(results): """Calculates foreground IOU score. Args: a: list of [T, H, W] or [H, W], binary mask b: list of [T, H, W] or [H, W], binary mask Returns: fg_iou: [B] """ y_out = results['y_out'] y_gt = results['y_gt'] num_ex = len(y_gt) fg_iou = np.zeros...
7580f1d9317437c7f3568106c4aa1f31bff99ed4
10,551
def render_template(template, defaults): """Render script template to string""" if not isinstance(template, Template): filename = template.format(**defaults) template = Template(filename=filename) return template.format(**defaults)
e44554132663d8e9d4287258a27559a3ab757912
10,552
def get_hash(string): """ FNV1a hash algo. Generates a (signed) 64-bit FNV1a hash. See http://www.isthe.com/chongo/tech/comp/fnv/index.html for math-y details. """ encoded_trimmed_string = string.strip().encode('utf8') assert isinstance(encoded_trimmed_string, bytes) i64 = FNV1_64A_INIT ...
c2315b8cc6b133b158f99ddbfd6afcd50562d7c0
10,553
def load_seq_sizes(def_vars): """Load sequence sizes.""" seq1_sizes, seq2_sizes = {}, {} if def_vars.get("SEQ1_LEN"): seq1_sizes = read_chrom_sizes(def_vars.get("SEQ1_LEN")) elif def_vars.get("SEQ1_CTGLEN"): seq1_sizes = read_chrom_sizes(def_vars.get("SEQ1_CTGLEN")) else: cle...
3ba9ea6057bed3f787adfaf05cbd2a374d7a4357
10,554
from pathlib import Path from typing import Optional def extract_source(source_path: Path) -> (Path, Optional[str]): """Extract the source archive, return the extracted path and optionally the commit hash stored inside.""" extracted_path = source_path.with_name(source_path.stem) commit_hash = None # ...
4659ac1bf79662ffe0d444c3d0053528fbb28a48
10,555
def correct_distribution (lines): """ Balance the distribution of angles Define an ideal value of samples per bin. If the count per bin is greated than the the average, then randomly remove the items only for that bin """ angles = np.float32(np.array(lines)[:, 3]) num_bins = 21 hist...
bb69e63fedf353ca5a5b64d47971bc037575905e
10,556
def numDockedWindows(): """ Determine the amount of docked windows (i.e. visible on all desktops). return - Number of windows. """ stdout = runCommand(COMMAND_LIST_WINDOWS) result = -2 # first two windows are actually not windows and don't count for i in iter(stdout.splitlines()): if i...
41d98c9c18c5ffc675ca241411a3f470f125ec90
10,557
def get_value(hive, key_name, value_name): """ >>> get_value( ... HKEY_LOCAL_MACHINE, ... "SOFTWARE/Microsoft/Windows/CurrentVersion/Explorer/StartMenu", ... "Type") [1, 'group'] >>> get_value( ... HKEY_CURRENT_USER, ... "Software\\Microsoft\\Windows\\CurrentVersion\\...
61abd243eab56eda43ac5f33bbe19ea1c1a78475
10,559
def addScore(appId: str, scoreName: str, value: int, userId: str, checksum: str=Header(None), db=Depends(Database)): """ Add user score to leaderboard """ validateParameters(appId=appId, scoreName=scoreName, value=value, userId=userId, checksum=checksum) with db.trans...
de957586bfa3508ac52ed438922d401bfe1ddc74
10,560
def has_affect(builtin: str) -> bool: """Return `True` if the given builtin can affect accessed attributes.""" if builtin not in PYTHON_BUILTINS: raise ValueError(f"'{builtin}' is not a Python builtin") return builtin in PYTHON_ATTR_BUILTINS
7bb2897659d8e4b68c1b7f0cb7b1870bcca616cf
10,561
def get_plot_for_different_k_values(similarity, model_name): """ This function plots points after applying a cluster method for k=3,4,5,6. Furthermore prints silhouette score for each k :param similarity: Contains our dataset (The similarity of RIPE monitors) :return: A list containing silhouette score ...
e4437ccac9ef1cac8d498df3467e3c8a02e449ce
10,562
def RandomBrightness(image, delta, seed=None): """Adjust the brightness of RGB or Grayscale images. Tips: delta extreme value in the interval [-1, 1], >1 to white, <-1 to black. a suitable interval is [-0.5, 0.5]. 0 means pixel value no change. Args: image: Tensor or arr...
efdcb6ad5b3339d3ba8f85264f50020645d17c87
10,563
def fetch_rfc(number): """ RFC fetcher >>> fetch_rfc("1234") (u'https://tools.ietf.org/html/rfc1234', 'Tunneling IPX traffic through IP networks') """ url = "https://tools.ietf.org/html/rfc%s" % (number, ) xml, dummy_response = fetch_and_parse_xml(url) title = xml.xpath('string(//meta[@...
81d91e7a3255077a9b0fb66807fadf35c165d2a0
10,564
def samefile(path1, path2, user=None): """ Return :obj:`True` if both path arguments refer to the same path. """ def tr(p): return abspath(normpath(realpath(p)), user=user) return tr(path1) == tr(path2)
1d898eff82502c5aece2f60ffc562529e4dd3062
10,565
def get_list_coord(G, o, d): """Get the list of intermediate coordinates between nodes o and d (inclusive). Arguments: G {networkx} -- Graph o {int} -- origin id d {int} -- destination id Returns: list -- E.g.: [(x1, y1), (x2, y2)] """ edge_data = G.get_edge_da...
901d64d81493408ed8a17b99701088daea7fd40f
10,566
from datetime import datetime def todays_date(): """ Returns today's date in YYYYMMDD format. """ now = datetime.datetime.now() date_str = "{0}{1}{2}".format(now.year, now.strftime('%m').zfill(2), now.strftime('%d').zfill(2)) return date_str
fb94f5af79640363ed58bbe0191def5d465cd37a
10,567
def kl_divergence(p_probs, q_probs): """"KL (p || q)""" kl_div = p_probs * np.log(p_probs / q_probs) return np.sum(kl_div[np.isfinite(kl_div)])
153a5cae3a20f79d92ce7ececf085ee344baf6a9
10,568
def colors_to_main(colors, main_colors): """ Mapping image colors to main colors and count pixels :param: colors: all colors in image :param: main_colors: input main colors (blue, green, yellow, purple, pink, red, orange, brown, silver, white, gray, black) :return: colors """ ...
0ccc41f199cb2aaad78fb7583d8aeb2bb1646e12
10,569
def get_arg_value_wrapper( decorator_func: t.Callable[[ArgValGetter], Decorator], name_or_pos: Argument, func: t.Callable[[t.Any], t.Any] = None, ) -> Decorator: """ Call `decorator_func` with the value of the arg at the given name/position. `decorator_func` must accept a callable as a paramete...
3ffb17927fd784571a7d0f22bcc46e7191711c91
10,570
def yaml_request(request: quart.local.LocalProxy) -> bool: """Given a request, return True if it contains a YAML request body""" return request.content_type in ( "text/vnd.yaml", "text/yaml", "text/x-yaml", "application/vnd.yaml", "application/x-yaml", "applicatio...
9aa31eff17d799058e272193266af46b87b618ae
10,571
def validatePath(path): """ Returns the validated path. :param path: string or unicode - Path to format .. note:: Only useful if you are coding for both Linux and Windows for fixing slash problems. e.g. Corrects 'Z://something' -> 'Z:' Example:: fpath = xbmc.validatePath(somepath...
cb809f3a78de96d220302700d5d2a68e402fed4c
10,572
import requests def get_raster_availability(layer, bbox=None): """retrieve metadata for raster tiles that cover the given bounding box for the specified data layer. Parameters ---------- layer : str dataset layer name. (see get_available_layers for list) bbox : (sequence of float|str)...
bcd0c78dcc807830dc3b9e7883ecfe51e8c5fb14
10,573
def absolute_error(observed, modeled): """Calculate the absolute error between two arrays. :param observed: Array of observed data :type observed: numpy.ndarray :param modeled: Array of modeled data :type modeled: numpy.ndarray :rtype: numpy.ndarray """ error = observed - modeled r...
ef5aa10fbe25689c1197c1ce7a54401be020de1e
10,574
from typing import Optional def prepare_tempdir(suffix: Optional[str] = None) -> str: """Preapres a temprary directory, and returns the path to it. f"_{version}" will be used as the suffix of this directory, if provided. """ suffix = "_" + suffix if suffix else None dir_str = mkdtemp(suffix, "wars...
fcc562240c8bbe3211d460d0888342fe422ef27a
10,575
def parse_number(string): """ Retrieve a number from the string. Parameters ---------- string : str the string to parse Returns ------- number : float the number contained in the string """ num_str = string.split(None, 1)[0] number = float(num_str) retur...
e3833873311ec142edcd2ba0301894bb000dff78
10,576
def catch_exception(func): """ Decorator that catches exception and exits the code if needed """ def exit_if_failed(*args, **kwargs): try: result = func(*args, **kwargs) except (NonZeroExitCodeException, GitLogParsingException) as exception: Logger.error(exception...
17075b508d490d9623b047bc854a0dfe654fd255
10,577
def _coord_byval(coord): """ Turns a COORD object into a c_long. This will cause it to be passed by value instead of by reference. (That is what I think at least.) When runing ``ptipython`` is run (only with IPython), we often got the following error:: Error in 'SetConsoleCursorPosition'. ...
baf2dd26e5e9307074fc04a6870353206e49c291
10,578
from typing import Union from typing import Dict def _list_flows(output_format='dict', **kwargs) -> Union[Dict, pd.DataFrame]: """ Perform the api call that return a list of all flows. Parameters ---------- output_format: str, optional (default='dict') The parameter decides the format of ...
67d7e0d2a75cc1f6dbeb66af354282cff0983be0
10,579
def _take_many_sparse_from_tensors_map(sparse_map_op, sparse_handles, rank=None, name=None): """Read `SparseTensors` from a `SparseTensorsMap` and concatenate them. The input `sparse_handles` must b...
ab9a646f573823de300bd78d0fb5ff7d23311445
10,580
def rts_smooth(kalman_filter, state_count=None): """ Compute the Rauch-Tung-Striebel smoothed state estimates and estimate covariances for a Kalman filter. Args: kalman_filter (KalmanFilter): Filter whose smoothed states should be returned state_count (int or None): Number o...
6b3df9f2015c525a385114b657954dba1ec731a2
10,581
def play_episode(args, sess, env, qnet, e): """ Actually plays a single game and performs updates once we have enough experiences. :param args: parser.parse_args :param sess: tf.Session() :param env: gym.make() :param qnet: class which holds the NN to play and update. :param e: chance of...
2a1c257a1c03dc71e1b7f5a4a102eb5ab080fa49
10,582
def to_categorical(y, num_columns): """Returns one-hot encoded Variable""" y_cat = np.zeros((y.shape[0], num_columns)) y_cat[range(y.shape[0]), y.astype(int)] = 1.0 return Variable(FloatTensor(y_cat))
29918d01c011daec2f87d5ee0075899ed9c366d8
10,583
def extract_light_positions_for_rays(ray_batch, scene_info, light_pos): """Extract light positions for a batch of rays. Args: ray_batch: [R, M] tf.float32. scene_info: Dict. light_pos: Light position. Returns: light_positions: [R, 3] tf.float32. """ ray_sids = extract_slice_from_ray_batch( ...
490afd9b98dfb6f28a67e32be38f1dda9486ee63
10,585
def cdf(x, c, loc=0, scale=1): """Return the cdf :param x: :type x: :param c: :type c: :param loc: :type loc: :param scale: :type scale: :return: :rtype: """ x = (x - loc) / scale try: c = round(c, 15) x = np.log(1 - c * x) / c return 1.0 /...
22ed6c2972c0cfc6c096939b630620555f9f0c3d
10,586
import json import yaml def load_dict(file_name): """ Reads JSON or YAML file into a dictionary """ if file_name.lower().endswith(".json"): with open(file_name) as _f: return json.load(_f) with open(file_name) as _f: return yaml.full_load(_f)
a098a8582e22fba2c9c2b72fbf3e3f769f740a98
10,588
import requests import re def get_next_number(num, proxies='', auth=''): """ Returns the next number in the chain """ url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php' res = requests.get('{0}?nothing={1}'.format(url, num), proxies=proxies, auth=auth) dat = res.content pattern = re.compile(r'next ...
74fe86908363e6272452d5b08dfdf5745af99758
10,589
import io import gzip import json def gzip_str(g_str): """ Transform string to GZIP coding Args: g_str (str): string of data Returns: GZIP bytes data """ compressed_str = io.BytesIO() with gzip.GzipFile(fileobj=compressed_str, mode="w") as file_out: file_out.write...
05d503e7b4a4ad69b6951146c787486048bc6f7e
10,590
import _locale def get_summoner_spells(): """ https://developer.riotgames.com/api/methods#!/968/3327 Returns: SummonerSpellList: all the summoner spells """ request = "{version}/summoner-spells".format(version=cassiopeia.dto.requests.api_versions["staticdata"]) params = {"tags": "all...
7667c97c474578fbe771bdeaccd1d6b4f0a2d5d0
10,591
def solve_covariance(u) -> np.ndarray: """Solve covariance matrix from moments Parameters ---------- u : List[np.ndarray] List of moments as defined by the ``get_moments()`` method call of a BayesPy node object. """ cov = u[1] - np.outer(u[0], u[0]) return cov if cov.shape ...
234698e7ae1baf2d471791888e2b488c59cd5e88
10,594
def interact_ids(*columns: Array) -> Array: """Create interactions of ID columns.""" interacted = columns[0].flatten().astype(np.object) if len(columns) > 1: interacted[:] = list(zip(*columns)) return interacted
6c0657723097b472e03abaf9d784fedf447463bc
10,595
def _get_depthwise(): """ We ask the user to input a value for depthwise. Depthwise is an integer hyperparameter that is used in the mobilenet-like model. Please refer to famous_cnn submodule or to mobilenets paper # Default: 1 """ depth = '' while depth not in ['avg', 'max']: ...
c102b534b4e9143917fde369670f9aaaad321f7b
10,596
def LoadPartitionConfig(filename): """Loads a partition tables configuration file into a Python object. Args: filename: Filename to load into object Returns: Object containing disk layout configuration """ valid_keys = set(('_comment', 'metadata', 'layouts', 'parent')) valid_layout_keys = set(( ...
dab5fe288044587c9cc32ad9c6811ea0c79ea75a
10,597
def get_own(): """Returns the instance on which the caller is running. Returns a boto.ec2.instance.Instance object augmented by tag attributes. IMPORTANT: This method will raise an exception if the network fails. Don't forget to catch it early because we must recover from this, fast. Also, it will...
056f47a47036fc1ba0f778d81ce8234dfc122a8f
10,598
from datetime import datetime from typing import List from typing import Mapping def create_report( name: str, description: str, published: datetime, author: Identity, object_refs: List[_DomainObject], external_references: List[ExternalReference], object_marking_refs: List[MarkingDefinitio...
81331d99b95540a9d7b447cf50a996965d9e2a10
10,599
def get_curve_points( road: Road, center: np.ndarray, road_end: np.ndarray, placement_offset: float, is_end: bool, ) -> list[np.ndarray]: """ :param road: road segment :param center: road intersection point :param road_end: end point of the road segment :param placement_offset: o...
9bc22c1894332a70e904d4c543606c3f38606064
10,600
def default_inputs_folder_at_judge(receiver): """ When a receiver is added to a task and `receiver.send_to_judge` is checked, this function will be used to automatically set the name of the folder with inputs at judge server. When this function is called SubmitReceiver object is created but is not saved...
0f45a374a32feb19ffe17d394831123ca8af68c8
10,601
def remove_extension(string): """ Removes the extention from a string, as well as the directories. This function may fail if more than one . is in the file, such as ".tar.gz" Args: string: (string): either a path or a filename that for a specific file, with extension. (e.g. /usr/di...
8bdd3818696745c5955dfb5bd7725d87e1284103
10,602
def _theme_static(path): """ Serve arbitrary files. """ return static_app.static(path, 'theme')
c93815b041632c313961afbe7ef254117c4259de
10,603
def create_link(link: schemas.Link, db: Session = Depends(get_db)): """Create link """ # Check if the target already exists db_link = crud.get_link_by_target(db=db, target=link.target) if db_link: raise HTTPException(status_code=400, detail="link already registered") response = crud.cre...
b220403b6d054df0f0e6f0538573038b0f7895b3
10,604
def encode_rsa_public_key(key): """ Encode an RSA public key into PKCS#1 DER-encoded format. :param PublicKey key: RSA public key :rtype: bytes """ return RSAPublicKey({ 'modulus': int.from_bytes(key[Attribute.MODULUS], byteorder='big'), 'public_exponent': int.from_bytes(key[Att...
38b1c3b4ee361415fa8587df7dbfdd94d00fdbe1
10,605
def is_block_valid(new_block, old_block): """ simple verify if the block is valid. """ if old_block["Index"] + 1 != new_block["Index"]: return False if old_block["Hash"] != new_block["PrevHash"]: return False if caculate_hash(new_block) != new_block["Hash"]: ret...
8447ca7b7bbb75748601d4a79d97047ad7ef07ab
10,606
import urllib def add_get_parameter(url, key, value): """ Utility method to add an HTTP request parameter to a GET request """ if '?' in url: return url + "&%s" % urllib.urlencode([(key, value)]) else: return url + "?%s" % urllib.urlencode([(key, value)])
640de1f111ff9080386f855e220e8eaaad113a0a
10,607
def get_simple_match(text): """Returns a word instance in the dictionary, selected by a simplified String match""" # Try to find a matching word try: result = word.get(word.normalized_text == text) return result except peewee.DoesNotExist: return None
e8365b6129e452eb17696daf8638a573e8d0cb4b
10,608
def ipv_plot_df(points_df, sample_frac=1, marker='circle_2d', size=0.2, **kwargs): """Plot vertices in a dataframe using ipyvolume.""" if sample_frac < 1: xyz = random_sample(points_df, len(points_df), sample_frac) else: xyz = dict(x=points_df['x'].values, y=points_df['y'].values, z=points_d...
a957629bcf7b9acbff314f243a3cae9803bda69d
10,609
def admin_login(): """ This function is used to show the admin login page :return: admin_login.html """ return render_template("admin_login.html")
495841f7cb352a07d8214f99b99ca8be7179839f
10,611