content
stringlengths
22
815k
id
int64
0
4.91M
def test_association_end_updates(create, diagram): """Test association end navigability connected to a class.""" c1 = create(ClassItem, UML.Class) c2 = create(ClassItem, UML.Class) a = create(AssociationItem) connect(a, a.head, c1) c = get_connected(a, a.head) assert c is c1 connect(a,...
5,336,800
def get_voca(base_persons, vertices, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): """ Create VOCA model with specific parameters. Parameters: ---------- base_persons : int Numb...
5,336,801
def _l2_project_reference(z_p, p, z_q): """Projects distribution (z_p, p) onto support z_q under L2-metric over CDFs. The supports z_p and z_q are specified as tensors of distinct atoms (given in ascending order). Let Kq be len(z_q) and Kp be len(z_p). This projection works for any support z_q, in particula...
5,336,802
def _make_blocksizes(bricksize, surveysize, nlods, dtype, factor=(1,1,1), verbose=None): """ CURRENTLY NOT USED. Calculate the minimum blocksize to read at each lod level. Clip to the survey size. Also compute the memory needed to hold one buffer for each lod. Note that the genlod algorithm current...
5,336,803
def kit2fiff(): """Convert KIT files to the fiff format. The recommended way to use the GUI is through bash with:: $ mne kit2fiff """ _check_mayavi_version() from ._backend import _check_backend _check_backend() from ._kit2fiff_gui import Kit2FiffFrame gui = Kit2FiffFrame() ...
5,336,804
def sweep_dec_given_x(full_model, z_dec_model, sample1, sample2, sample_layer_name, sweep_z_samples=False, nb_samples=10, nargout=1, tqdm=tqdm): """ sweep the latent space given two samples in the original space specific...
5,336,805
def process(observation, current_game_state): """ Args: observation: An observation, which agents get as an input from kaggle environment. current_game_state: An object provided by kaggle to simplify game info extraction. Returns: processed_observations: A prepared observation to sav...
5,336,806
def test_cli_config_debug( app: Cli, valiant_app_title: str, valiant_version: str, valiant_license: str ) -> None: """Test the default output from the `config` command with -vvv.""" command = app.find("config") command_tester = CommandTester(command) result = command_tester.execute("-vvv") asse...
5,336,807
def source_files(goto, wkdir, srcdir=None): """Source files appearing in symbol table. Source file path names in symbol table are absolute or relative to wkdir. If srcdir is given, return only files under srcdir. """ wkdir = srcloct.abspath(wkdir) srcs = [dfn['file'] for dfn in pa...
5,336,808
def textBlurBackground(img, text, font, fontScale, textPos, textThickness=1, textColor=(0, 255, 0), kneral=(33, 33), pad_x=3, pad_y=3): """ Draw text with background blured, control the blur value, with kernal(odd, odd) @param img:(mat) which you want to draw text @param text: (s...
5,336,809
def local_response_normalization_2d_v2(in_vw, alpha, k, beta, n): """ cross-channel local response normalization for 2D feature maps - input is bc01 output[i] = value of the i-th channel = input[i] / (k + alpha * sum(input[j]^2 for j) ** beta) - where j is over neighboring channels (from ...
5,336,810
def mhc_datasets(table='mhc_data', path='./iedb/', remove_c=False, remove_u=False, remove_modes=False): """ Parameters: 'table' is the table that the data is retrieved - must be 'mhc_data', 'mhc_test1', 'mhc_test2', or 'mhc_train' 'path' is where the database i...
5,336,811
def add_new_user(): """ This function adds a new user :return: Response Code """ newuser = {} if request.method == "POST": try: newuser['username'] = str(request.data.get('username').strip()) newuser['first_name'] = str(request.data.get('first_name').strip()) ...
5,336,812
def has_wildcard(url) -> bool: """ Check if the url contains a wildcard in last subdomain. :param url: The url to check :type url: str :return: True if the url contains a wildcard in the last subdomain, False otherwise :rtype: bool """ subdomain = extract(url).subdomain return subdo...
5,336,813
def tmle_calculator(y, ystar1, ystar0, ystara, h1w, h0w, haw, splits, measure='ate', lower_bound=None, upper_bound=None): """Function to calculate TMLE estimates for SingleCrossfitTMLE, and DoubleCrossfitTMLE """ if measure in ["ate", "risk_difference"]: # Unbounding if continuou...
5,336,814
def gen_gap(Pn, T, Q): """Runs the generalization gap test. This test simply checks the difference between the likelihood assigned to the training set versus that assigned to a held out test set. Inputs: Pn: (n X d) np array containing the held out test sample of dimensio...
5,336,815
def saveWithGDAL(path, image, writeHeader=True, interleave='BSQ'): """ Write this image to a file. *Arguments*: - path = the path to save to. - image = the image to write. - writeHeader = true if a .hdr file will be written. Default is true. - interleave = data interleaving for ENVI fil...
5,336,816
def get_shapes(node, intermediate=False, exclusive=False): """Get the shapes of given node. Args: node (str): Node to query its shapes intermediate (bool): Get intermediate shapes when True. exclusive (bool): Only return the intermediate shapes if True. Please note that the ...
5,336,817
def solve_mip_mlp_elided(verif_instance): """Compute optimal attack loss for MLPs, via exactly solving MIP.""" assert MIP_SOLVERS, 'No MIP solvers installed with cvxpy.' assert verif_instance.type == utils.VerifInstanceTypes.MLP_ELIDED params, bounds, obj, obj_const = ( verif_instance.params, verif_instan...
5,336,818
def compute_kullback_leibler_check_statistic(n=100, prngstate=None): """Compute the lowest of the survival function and the CDF of the exact KL divergence KL(N(mu1,s1)||N(mu2,s2)) w.r.t. the sample distribution of the KL divergence drawn by computing log(P(x|N(mu1,s1)))-log(P(x|N(mu2,s2))) over a sample...
5,336,819
def build_signature(inputs, outputs): """Build the signature for use when exporting the graph. Args: inputs: a dictionary from tensor name to tensor outputs: a dictionary from tensor name to tensor Returns: The signature, a SignatureDef proto, specifies the input/output tensors to bind when runni...
5,336,820
def fuse_depthwise_conv2d(input_graph_def): """Modifies the provided graph by fusing a set of ops into a single _FusedDepthwiseConv2d op. DepthwiseConv2dNative + BiasAdd + Activation => _FusedDepthwiseConv2dNative Args: input_graph_def: A GraphDef containing a model. Returns: Modified graph with Fu...
5,336,821
async def test_item_search_properties_jsonb(app_client): """Test POST search with JSONB query (query extension)""" items_resp = await app_client.get("/collections/naip/items") assert items_resp.status_code == 200 first_item = items_resp.json()["features"][0] # EPSG is a JSONB key params = {"qu...
5,336,822
def _validate_device_classes(ext_auxiliary_devices: Collection[Type[Any]], ext_primary_devices: Collection[Type[Any]], ext_virtual_devices: Collection[Type[Any]], package_name: str) -> None: """Validates the extension device classe...
5,336,823
def pandas_to_example_str(obj, *, local_data_model=None) -> str: """ Convert data frame to a Python source code string. :param obj: data frame to convert. :param local_data_model: data model to use. :return: Python source code representation of obj. """ if local_data_model is None: ...
5,336,824
def get_results_object_model(target_node, paths_dict, name_to_description, q1_doid_to_disease, probs=False): """ Returns pathway results as an object model :param target_node: target_node DOID:1234 :param paths_dict: a dictionary (keys OMIM id's) with values (path_name,path_type) :param name_to_description: a dict...
5,336,825
def main(): """ Main program that deals with user input """ clear() print_script_info() update_league_path() # choose between importing or deleting item sets answer = None # only accept answers "", "b" (delete) or source name while answer not in ["", "b"] + [source.name for source in ...
5,336,826
def MaxLonSep( maxarc, baselat ): """Calculates the maximum separation in longitude that a point can have from a reference point at latitude baselat and still be within a given great circle arc length, maxarc, of the reference point. All quantities in radians.""" if abs(baselat) + maxarc <= 0.5 * pi...
5,336,827
def auto_read(filename): """Automatically determine the format of filename and open accordingly""" #XXX: this won't work correctly on pipes #would be better to use file magic f = open(filename, 'r') firstchar = f.read(1) f.close() if firstchar == '#': return gnucap_read(filename) else: return sp...
5,336,828
def WaitForOperation(client, messages, operation_name, operation_description=None, project=None, timeout=180): """Wait for an operation to complete. Polls the operation requested approximately every second, showing a progress indicator. Returns when the operation has com...
5,336,829
def get_unstaged_files(gitobj): """ ref: http://gitpython.readthedocs.io/en/stable/tutorial.html#obtaining-diff-information """ diff = [] diff.extend(gitobj.index.diff(gitobj.head.commit)) diff.extend(gitobj.index.diff(None)) return {"changed": diff, "untracked": gitobj.untracked_files}
5,336,830
def conv2d( inp: Tensor, weight: Tensor, bias: Optional[Tensor] = None, stride: Union[int, Tuple[int, int]] = 1, padding: Union[int, Tuple[int, int]] = 0, dilation: Union[int, Tuple[int, int]] = 1, groups: int = 1, conv_mode="CROSS_CORRELATION", compute_mode="DEFAULT", ) -> Tensor: ...
5,336,831
def find_tex_directives(texfile, ignore_root_loops=False): """Build a dictionary of %!TEX directives. The main ones we are concerned with are: root Specifies a root file to run tex on for this subsidiary TS-program Tells us which latex program to run TS-options ...
5,336,832
def projects(): """ Handles the GET & POST request to '/projects'. GET: requests to render page POST: request to edit project with sent data :return: render projects page / Json containing authorisation error / manage(data) function call """ if request.method == "GET": return render_...
5,336,833
def lock(): """Lock new dependencies without upgrading""" OPTIONS['upgrade'] = False run_configurations(recompile, read_config)
5,336,834
def evolve_fqe_givens_sector(wfn: Wavefunction, u: np.ndarray, sector='alpha') -> Wavefunction: """Evolve a wavefunction by u generated from a 1-body Hamiltonian. Args: wfn: FQE Wavefunction on n-orbitals u: (n x n) unitary matrix. sector: Optional either 'a...
5,336,835
def eval_on_holdout(args, action_selection, reg_and_traj_transferer, lfd_env, sim): """TODO Args: action_selection: ActionSelection reg_and_traj_transferer: RegistrationAndTrajectoryTransferer lfd_env: LfdEnvironment sim: DynamicSimulation """ holdoutfile = h5py.File...
5,336,836
def clear(): """Clear cli screen :return: None """ os.system('clear' if 'posix' == os.name else 'cls')
5,336,837
def latexify(fig_width=None, fig_height=None, columns=1, tick_labelsize=8): """Set up matplotlib's RC params for LaTeX plotting. Call this before plotting a figure. Parameters ---------- fig_width : float, optional, inches fig_height : float, optional, inches columns : {1, 2} """ ...
5,336,838
def vidread(filename): """ generates images instead of storing as a 3-tensor because the videos can take up a lot of memory based on: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html """ cap = cv2.VideoCapture(filename) a...
5,336,839
def iter_ols_getters() -> Iterable[Type[Getter]]: """Iterate over OLS getters.""" for bioregistry_id in bioregistry.read_registry(): yv = make_ols_getter(bioregistry_id) if yv is not None: yield yv
5,336,840
def save_tiles(tiles, prefix='', directory=os.getcwd(), format='png'): """ Write image files to disk. Create specified folder(s) if they don't exist. Return list of :class:`Tile` instance. Args: tiles (list): List, tuple or set of :class:`Tile` objects to save. prefix (str): Filename...
5,336,841
async def save_audit(user_id: int, approved_by: int, oldpoi: POI, poi: POI): """Warning: does not do db.commit().""" db = await get_db() if oldpoi is None: query = ("insert into poi_audit (user_id, approved_by, poi_id, field, new_value) " "values (?, ?, ?, 'poi', ?)") data =...
5,336,842
def epoch_folding_search(times, frequencies, nbin=128, segment_size=5000, expocorr=False, gti=None, weights=1, fdots=0): """Performs epoch folding at trial frequencies in photon data. If no exposure correction is needed and numba is installed, it uses a fast algorithm to perform th...
5,336,843
def explain(include: InclusionChoice = "explain") -> None: """Shows the previously recorded traceback info again, with the option to specify different items to include. For example, ``explain("why")`` is equivalent to ``why()``. """ old_include = friendly_traceback.get_include() friendly_traceba...
5,336,844
def get_hs300_stocks(): """ 获取沪深300成分股 """ # 登陆系统 lg = bs.login() # 显示登陆返回信息 print('login respond error_code:' + lg.error_code) print('login respond error_msg:' + lg.error_msg) # 获取沪深300成分股 rs = bs.query_hs300_stocks() print('query_hs300 error_code:' + rs.error_code) p...
5,336,845
def dark_blue_filter(image): """Filter reduces the green making the pixels more of red and blue causing a dark bluish colour """ data = [] image_data = get_image_data(image) # setting every 'g' pixel to 0 for i in range(len(image_data)): current_tuple = list(image_data[i]) ...
5,336,846
def apply_matcher(words, offsets, dictionary, max_ngrams=5, longest_match_only=True, case_sensitive = False, split_on=None): """ TODO: cleanup! """ # covert to source char offsets text = get_t...
5,336,847
def create_and_put_metrics_and_widgets() -> dict: """For each repository, aggregates all text and metric data and creates widgets for each :returns: a dictionary mapping the dashboard name to the list of the text and metric widgets for each repository to put in the dashboard :rtype: dict ...
5,336,848
def test_truncate_default(all_terms): """Ensure that terminal.truncate functions with the default argument.""" @as_subprocess def child(kind): from blessed import Terminal term = Terminal(kind) test = "Testing " + term.red("attention ") + term.blue("please.") trunc = term.tru...
5,336,849
def boxbin(x,y,xedge,yedge,c=None,figsize=(5,5),cmap='viridis',mincnt=10,vmin=None,vmax=None,edgecolor=None,powernorm=False, ax=None,normed=False,method='mean',quantile=None,alpha=1.0,cbar=True,unconditional=False,master_count=np.array([])): """ This function will grid data for you and provide the c...
5,336,850
def testDataRate(data_rate): """ This method tests data rate for transmission """ print('Data rate = '.format(data_rate)) # toRedit(data_rate, 'DATA_RATE',pipe) if __name__ == '__main__': for i in range(60): get_color_and_depth_frames() r.set('im-shape', '720 1280'...
5,336,851
def _get_elastic_document( tasks: list[dict], symprec: float, fitting_method: str, ) -> ElasticDocument: """ Turn a list of deformation tasks into an elastic document. Parameters ---------- tasks : list of dict A list of deformation tasks. symprec : float Symmetry pr...
5,336,852
def first(filename: Union[str, Path]) -> int: """ Sort the input, prepend with 0 and append with 3 + the max. Return: (# of successive differences == 1) * (# of successive differences == 3) """ with open(filename, "rt") as infile: jolts = sorted(int(line.strip()) for line in infile)...
5,336,853
def charge_is_valid(charge_profile, capacity=6, max_charge_rate=2.5, time_unit=0.5): """ Function determining if a charge profile is valid (and fully charges the battery) """ if np.all(np.isclose(capacity/time_unit, charge_profile.groupby(charge_profile.index.date).sum())) is False: return False...
5,336,854
def create_slice_obj(start, end, step): """Create slice object""" return slice(start, end, step)
5,336,855
def send_wxnotification(message): """发送公众号提醒""" #文档字符串用三引号括起,Python使用它们来生成有关程序中函数的文档。 miao_code="tLmPyT4" text = message page = request.urlopen("http://miaotixing.com/trigger?" + parse.urlencode({"id":miao_code, "text":text, "type":"json"})) result = page.read() jsonObj = json.loa...
5,336,856
def binary_cross_entropy_error(y, t): """バイナリー交差エントロピー誤差""" #y.shape (N,C,H,W) delta = 1e-7 return -np.mean(t*np.log(y + delta) + (1-t)*np.log(1-y + delta))
5,336,857
def get_abc(): """ :return: list all the abcs as a list """ # ok return list(abcs.find({}, {'_id': False}))
5,336,858
def matching_system_code(concept: CodeableConcept, system: str) -> Optional[str]: """ Returns a code from a specified *system* contained within a given *concept*. If no code is found for the given *system*, returns None. Raises an :class:`AssertionError` if more than one encoding for a *system* is...
5,336,859
def get_pybullet(env_name): """ Returns pybullet dataset and envrironment. The dataset is provided through d4rl-pybullet. See more details including available dataset from its GitHub page. .. code-block:: python from d3rlpy.datasets import get_pybullet dataset, env = get_pybullet('ho...
5,336,860
def reverse(d: Iterable) -> Any: """Reverses the provided iterable, but also RETURNS it""" d.reverse() return d
5,336,861
def justify(words, width): """ Justify input words. :param words: list of words :type words : list :param width: width of each line :type width : int :return: list of justified words as list """ line = [] col = 0 for word in words: if line and col + len(word) > width...
5,336,862
def scalar(typename): """ Returns scalar type from ROS message data type, like "uint8" from "uint8[100]". Returns type unchanged if already a scalar. """ return typename[:typename.index("[")] if "[" in typename else typename
5,336,863
def subject(mock_messenger: AsyncMock) -> initiator.FirmwareUpdateInitiator: """The test subject.""" return initiator.FirmwareUpdateInitiator(mock_messenger)
5,336,864
def onetangent(ri, rf, ta_transb, k=0, use_alts=True, center='earth'): """Orbit transfer with one tangential burn and one nontangential burn. Must be circular or coaxially elliptic. Currently only for circular orbits. :param ri: altitude (or radius) of initial circular orbit (km) :param rf: altitu...
5,336,865
def test_user_moira_lists_anonymous(): """ Test that empty list is returned for anonymous user """ assert user_moira_lists(AnonymousUser()) == []
5,336,866
def save_keys_to_single_site_bed(keys, outfn, callBaseFormat=1, outBaseFormat=1, nonstr='.'): """ Save all keys in set of ('chr 123 123 . . +\n', etc.) to outfn. We use non-string like . in 3rd, 4th columns by BED file format. :param keys: :param outfn: :return: """ if outfn.endswit...
5,336,867
def display_matplot(images, title = None, gray=None): """[Standard display fuction used throughout testing to see the output of thhe various transforms. Displays multilpe plots at once for comparison, always in a square format.] Arguments: images {[Array]} -- [the array that contains all of ...
5,336,868
def test_step_should_set_state_to_running_before_running_step_impl(mocker): """A Step should set its State to RUNNING before it runs the Step Implementation function""" # given class WrapperForMockerSpy: def step_func(self, step): assert step.state is State.RUNNING w = WrapperForMoc...
5,336,869
def test_if_two_tables(small_table, large_table): """Test two filled tables.""" assert left_join(small_table, large_table) == [['yellow', 'blue', 'green'], ['gray', 'brown', 'pink'], ['black', 'red', 'orange'], ['cyan', 'puce', 'white']]
5,336,870
def get_version(): """ It returns the pmml version . Returns ------- version : String Returns the version of the pmml. """ version = '4.4' return version
5,336,871
def customsoftmax(inp, multihotmask): """ Custom Softmax """ soft = F.softmax(inp, dim=1) # This takes the mask * softmax ( sums it up hence summing up the classes in border # then takes of summed up version vs no summed version return torch.log( torch.max(soft, (multihotmask * (soft...
5,336,872
def mandoline( D_src: np.ndarray, D_tgt: np.ndarray, edge_list: np.ndarray, sigma: float=None, ): """ Mandoline solver. Args: D_src: (n_src x d) matrix of (example, slices) for the source distribution. D_tgt: (n_tgt x d) matrix of (example, slices) for the source distributio...
5,336,873
def service_transformer_info_get(service): # noqa: E501 """Retrieve transformer info Provides information about the transformer. # noqa: E501 :param service: Inxight_Drugs service :rtype: TransformerInfo """ return transformer[service].info
5,336,874
def create_app(config=None, app_name=None): """Create a Flask app.""" if app_name is None: app_name = DefaultConfig.PROJECT app = Flask(app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True) configure_app(app, config) configure_hook(app) configure_blueprints(app) ...
5,336,875
def read_translocations_tumors(gene_A, gene_B,\ tumor_barcodes,\ data_location=default_location): """ For a given set of tumor barcode and a gene, finds with a lookup the mutation for this particular gene on the TCGA dataset. INPUT: - gene_A (str): fi...
5,336,876
def simplify_if_constant(symbol, keep_domains=False): """ Utility function to simplify an expression tree if it evalutes to a constant scalar, vector or matrix """ if keep_domains is True: domain = symbol.domain auxiliary_domains = symbol.auxiliary_domains else: domain = ...
5,336,877
def arith_ln_sub_div( batch : int, n : int, m : int, inp : DevicePointer, # (batch, n, m) fp16 alpha : DevicePointer, # (n) fp16 beta : DevicePointer, # (n) fp16 out : DevicePointer, # (batch, n, m) fp16 stream : CUDAStream ): """ ...
5,336,878
def overall_dist(df_train, df_test, target, path): """This function takes in the train and test dataframes and plots both target distributions stacked in a histogram, It is saved to the path ---------- df_train : pandas dataframe dataframe of train set df_test : pandas dataf...
5,336,879
def is_visible(window): """ Check whether the window is visible or not. """ return lib.is_visible(window)
5,336,880
def activateMiracle(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) try: banner() islands = obtainMiraclesAvailable(session) if islands == []: print(_('There are no miracles avail...
5,336,881
def fix_mol( mol: Chem.rdchem.Mol, n_iter: int = 1, remove_singleton: bool = False, largest_only: bool = False, inplace: bool = False, ) -> Optional[Chem.rdchem.Mol]: """Fix error in molecule using a greedy approach. Args: mol: input molecule to fix n_iter: Number of valence...
5,336,882
def permutation_circuit(swaps: Iterable[List[Swap[_V]]]) -> PermutationCircuit: """Produce a circuit description of a list of swaps. With a given permutation and permuter you can compute the swaps using the permuter function then feed it into this circuit function to obtain a circuit description. ...
5,336,883
def main(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for ...
5,336,884
def create_release_branch(version, base_branch): """ checkout a new Git branch to make changes on and later tag as a release. :param bytes version: The version of Flocker to create a release branch for. :param base_branch: See :func:`git.Head`. The branch to create the release branch fr...
5,336,885
def Add(a, b): """ Adds two numbers, throws on overflow. """ c = a + b Require(c >= a) return c
5,336,886
def remap_shared_output_descriptions(output_descriptions: Dict[str, str], outputs: Dict[str, Type]) -> Dict[str, str]: """ Deals with mixed styles of return value descriptions used in docstrings. If the docstring contains a single entry of return value description, that output description is shared by each outp...
5,336,887
def dist_matrix(): """Fix dist_matrix for the next two tests.""" dist_matrix = np.array([[0, 4, 5, 6], [4, 0, 7, 8], [5, 7, 0, 9], [6, 8, 9, 0]]) return dist_matrix
5,336,888
def fitarg_rename(fitarg, ren): """Rename variable names in ``fitarg`` with rename function. :: #simple renaming fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1}, lambda pname: 'y' if pname=='x' else pname) #{'y':1, 'limit_y':1, 'fix_y':1, 'error_y':1}, #...
5,336,889
def generate_file(filename, lines, columns): """Creates and propogates a file containing random dna strings. This file can in turn be used for gss benchmarking. Args: - filename: The name of the file to the written. - lines: The number of lines to be written to the file. - column...
5,336,890
def flatten(tensor): """Flattens a given tensor such that the channel axis is first. The shapes are transformed as follows: (N, C, D, H, W) -> (C, N * D * H * W) """ C = tensor.size(1) # new axis order axis_order = (1, 0) + tuple(range(2, tensor.dim())) # Transpose: (N, C, D, H, W) ->...
5,336,891
def file_to_jsobj(src, chart_type=DFLT_CHART_TYPE, enable_playback=DFLT_ENABLE_PLAYBACK, height=DFLT_HEIGHT, params=DFLT_PARAMS, title=None, subtitle='', **kwargs ): """Ren...
5,336,892
def node_to_edge(edges, directed=True): """ From list of edges, record per node, incoming and outgoing edges """ outgoing = defaultdict(set) incoming = defaultdict(set) if directed else outgoing nodes = set() for i, edge in enumerate(edges): a, b, = edge[:2] outgoing[a].add(i...
5,336,893
def grouping_cumulative(df, col_index, col_column): """ compute histogram statistic over selected column and in addition group this histograms :param DataFrame df: rich table :param str col_index: column which will be used s index in resulting table :param str col_column: column used for computing a hi...
5,336,894
def _get_matching_stream(smap, itag): """ Return the url and signature for a stream matching itag in smap. """ for x in smap: if x['itag'] == itag and x.get("s"): return x['url'], x['s'] raise IOError("Sorry this video is not currently supported by pafy")
5,336,895
def Debounce(threshold=100): """ Simple debouncing decorator for apigpio callbacks. Example: `@Debouncer() def my_cb(gpio, level, tick) print('gpio cb: {} {} {}'.format(gpio, level, tick)) ` The threshold can be given to the decorator as an argument (in millisec). This decor...
5,336,896
def doctest_LazyDate(): """LazyDate fulfills its interface. >>> from zope.interface.verify import verifyObject >>> from cipher.lazydate import lazydate, interfaces >>> lazy = lazydate.LazyDate("now") >>> verifyObject(interfaces.ILazyDate, lazy) True String representatio...
5,336,897
def test_bad_config_section(mock_config): """Test that getting or setting a bad section gives an error.""" with pytest.raises(spack.config.ConfigSectionError): spack.config.set('foobar', 'foobar') with pytest.raises(spack.config.ConfigSectionError): spack.config.get('foobar')
5,336,898
def get_folder(default_location, title_string=None): """Dialog box to browse to a folder. Returns folder path. Usage: full_folder_name = get_folder(default_location, [title]), where "default_location" is a starting folder location, "title" is an optional message to list in the dialog box,...
5,336,899