content
stringlengths
22
815k
id
int64
0
4.91M
def lift(cra, crb): """Returns the relative uplift in conversion rate. Parameters ---------- cra: float Conversion rate of Group A crb: float Conversion rate of Group B Returns ------- float Relative uplift in conversion rate """ return ((crb - cra) / cra)...
79,100
def get_asso_words(txt, stopwords, w, window=2, t=2, s=0.5, m=10): """Main method for getting keywords Keyword arguments: txt -- txt-file address stopwords -- stopwords-file address word -- the keyword to query window -- adjacent window words in a senten...
79,101
def convert_object_to_float(x): """ Convert input object to float :param x: input series/signal as datatype not a float :return: same series/signal with datatype float. """ if isinstance(x, str): x = x.strip('\'') try: return float(x) except ValueError: ...
79,102
def _get_pressures(sounding_dict): """Returns pressure levels in soundings. :param sounding_dict: Dictionary created by `_convert_interp_table_to_soundings` or `_pressure_to_height_coords`. :return: pressure_matrix_pascals: N-by-P numpy array of pressures. """ if PRESSURE_LEVELS_WITH_SFC_K...
79,103
def test53(): """ test crud ops on pod templates """ res = PodTemplateList.listNamespacedPodTemplate(e2e_namespace) before_len = len(res.obj.items) pt = PodTemplate( metadata=ObjectMeta(name='test-53'), template=PodTemplateSpec( metadata=ObjectMeta(labels={'name': ''}...
79,104
def load(symbol_id: str) -> ast.Name: """Returns an AST Name node that loads a variable.""" return ast.Name(id=symbol_id, ctx=ast.Load())
79,105
async def subprocess() -> tests.helpers.Subprocess: """Return an asynchronous executor for testing subprocesses.""" return tests.helpers.Subprocess()
79,106
def controller_encryption_key_id_generate(handle, controller_type, controller_slot, server_id=1): """ Generates a random key id for the given controller Args: handle (ImcHandle) controller_type (str): Controller type '...
79,107
def is_videoid_in_db(videoid): """Return True if the video is in the database, else False""" if videoid.mediatype == common.VideoId.MOVIE: return G.SHARED_DB.movie_id_exists(videoid.value) if videoid.mediatype == common.VideoId.SHOW: return G.SHARED_DB.tvshow_id_exists(videoid.value) if ...
79,108
def image_frame_to_camera_frame(image_frame, camera_intrinsics): """Un-project points that are in image frame to the camera fame. Given a camera intrinsics matrix K, and a set of 2d points in image frame, this functions returns the 3D points at unit depth. Currently this function only supports a linear camera...
79,109
def dump_configs(conf): """Json dumps wrapper to printy print dicts to the console Arguments: configs (dict): The dictionary to log with indendation Note: This will only print in the CONFIGS namespace """ try: formatted = dumps(conf, sort_keys=True, indent=4) color...
79,110
def descent(X, targets, thetas, hypothesis, calc_cost, **kwargs): """Gradient descent""" MAX_ITS = kwargs.pop('max_its', DEF_MAX_ITERATIONS) LRN_RT = kwargs.pop('lrn_rt', DEF_LEARNING_RATE) REG_P = kwargs.pop('reg_p', DEF_REG_P) MIN_DELTA = kwargs.pop('min_delta', DEF_MIN_DELTA) m = len(targets) cost_his...
79,111
def sharpe(returns, rfr=0, expanding=0): """ returns: periodic return string rfr: risk free rate expanding: bool """ if expanding: excess = excess_returns(returns, rfr) return pd.expanding_mean(excess) / pd.expanding_std(returns) else: return excess_returns(returns, r...
79,112
def build_config(path: str, module: bool) -> None: """ build config via template """ global __ydoc with Path(f'{__rootdir__}/templates/config.yaml').open('r', encoding='utf8') as f: loader = yaml.load_all(f) next(loader) # discard first document (used for comment) __ydoc = next(load...
79,113
def _NegGrad(_, grad): """Returns -grad.""" return -grad
79,114
def utilize_ListOf(schema, data, **kwargs): """ Validate a list with arbitrary length. Validate each value from `data` against `schema.schema`. `schema` is a `ListOf` instance. """ schema_list = [schema.schema for item in data] return utilize_list(schema=schema_list, data=data, **kwargs)
79,115
def init_vec(f, names, data): """Initialize resizable 1d arrays to hold the outputs.""" # Iterate over 'names' and columns of 'data' dset = [ (name, f.create_dataset(name, data=d, maxshape=(None,))) for name, d in zip(names, data.T) ] # -> list return OrderedDict(dset)
79,116
def generate_nmt_data(): """Runs the data generation script which creates the data required for the NMT tests.""" subprocess.run( ["./generate_data.sh"], universal_newlines=True, cwd=DATA_GEN_SCRIPT_PATH ) if not test_util.check_data_exists( DATA_PATH, FILES_TO_G...
79,117
def powershell( cmd, cwd=None, stdin=None, runas=None, shell="powershell", env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel="debug", hide_output=False, timeout=None, reset_system_locale=True, ignore_r...
79,118
def play_one_file(idx, filename, folder, title, playlist_size): """Play one file, reacting to user input""" board.DISPLAY.auto_refresh = False playback_display.set_bitmap([ filename.rsplit('.', 1)[0] + ".bmp", filename.rsplit('/', 1)[0] + ".bmp", filename.rsplit('/', 1)[0] + "/cover...
79,119
def open_file(fileName): """用浏览器打开指定文件 :param fileName: 文件名 """ webbrowser.open('file:' + fileName)
79,120
def main(): """as per book""" rec1 = Person("Bob", ["dev", "mgr"], 40.5) rec2 = Person("Sue", ["dev", "cto"]) print(rec1.name, rec2.info())
79,121
def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. Not...
79,122
def clean_url(url): """ Reformat a URL with all querystrings stripped :param url: The URL :return: A clean URL """ return url[:url.find('?')]
79,123
def get_camera_bouma(df, fieldfile='../data/camera_boresights_SNE-shifted.csv'): """ Like get_camera, only better """ camdf = get_camera_coords(fieldfile) observed = np.zeros((df.shape[0], camdf.shape[0]), dtype='int') for ix, row in tqdm(camdf.iterrows(), total=camdf.shape[0]): cam_dir...
79,124
def animal_categories(): """Return list of strings""" categories = open(CATEGORIES_ANIMAL_PATH).readlines() categories = [c.strip() for c in categories] return categories
79,125
def p_createTable_u(t): """createTableList : createTable"""
79,126
def read_json(path: str) -> dict: """ This method reads the file specified in :param path: resource path :return: json object """ with open(path) as f: data = json.load(f) return data
79,127
def rmseff(x, c=0.68): """Compute half-width of the shortest interval containing a fraction 'c' of items in a 1D array. """ x = np.sort(x, kind="mergesort") m = int(c * len(x)) + 1 return np.min(x_sorted[m:] - x_sorted[:-m]) / 2.0
79,128
def test_md020_good_almost_missing_end_spacing(): """ Test to make sure we get the expected behavior after scanning a good file from the test/resources/rules/md020 directory that has a closed atx heading that is almost missing end spacing, except that the hashes are followed by something else, making ...
79,129
def small_movies_json_file(): """ Runs once per session. Provides the content of small_movies.json from read. """ with open('./datasets/small_movies.json', 'r', encoding='utf-8') as movie_json_file: return movie_json_file.read().encode('utf-8')
79,130
def get_router_connection(deploy_config: dict) -> paramiko.SSHClient: """ Opens a connection to the configured router Can throw: - ValueError - BadHostKeyException - AuthenticationException - SSHException - socket.error """ router_config = deploy_config["rout...
79,131
def isValid(text): """ Returns True if the input is related to the meaning of life. Arguments: text -- user-input, typically transcribed speech """ return bool( re.search( r'email', text, re.IGNORECASE)) or bool( re.search( ...
79,132
def _has_abstract_methods(node): """Determine if the given `node` has abstract methods. The methods should be made abstract by decorating them with `abc` decorators. """ return len(utils.unimplemented_abstract_methods(node)) > 0
79,133
def run_de(game): """ DIFFERENTIAL EVOLUTION """ diff_evolution_parameters = DifferentialEvolutionParameters( pop_size=10, ngen=350, game_batch_size=1, hof_size=5, cr=0.25, f=1) # mlp = MLP(hidden_layers=[200, 200], activation="relu") esn = EchoSt...
79,134
def simplify_tags(tags): """ >>> simplify_tags([set([('defined(world)', True), ('defined(hello)', True)]), ... set([('defined(world)', False), ('defined(hello)', True)])]) [set([('defined(hello)', True)])] >>> simplify_tags([set([('defined(LIBEV_EMBED)', True), ('defined(_WIN32)', Tru...
79,135
def substitute_parameters(layout, parameter_dictionary): """ <Purpose> This function is a transitionary measure for parameter substitution (or any other solution defined by the in-toto team). As of now, it acts as a very simple replacement layer for python-like parameters <Arguments> layout: ...
79,136
def mol_to_graph_data_obj_simple( mol, partial_charge=False, substruct_input=False, pattern_path=None, mask=False, hops=5, pooling_indicator=False, ): """ Converts rdkit mol object to graph Data object required by the pytorch geometric package. NB: Uses simplified atom and bond f...
79,137
def level_is_rtl(lev): """ Return True if `lev' is a Right-to-Left level, False otherwise. """ return lev & 1
79,138
def test_in_thread3(): """ Test hotswapping the loop to another thread. """ res = [] class MyComp1(event.Component): foo = event.IntProp(0, settable=True) @event.reaction('foo') def on_foo(self, *events): for ev in events: res.append(ev.new_value) ...
79,139
def bpcalc(request): """Calculate blueprint production details for X number of days""" # Get a valid number of days try: days = max(1, int(request.GET.get('days', '7'))) except ValueError: days = 7 # Initialise variabls bpis = [] bpi_totals = { 'input_m3': Decimal('0...
79,140
def calc_E_E_L_d_t(n_p, A_A, A_MR, A_OR, L): """1 時間当たりの照明設備の消費電力量(kWh/h) Args: n_p(float): 仮想居住人数 A_A(float): 床面積の合計[m^2] A_MR(float): 主たる居室の床面積[m^2] A_OR(float): その他の居室の床面積[m^2] L(dict): 照明設備仕様辞書 Returns: ndarray: E_E_L_d_t 日付dの時刻tにおける 1 時間当たりの照明設備の消費電力量[kWh/h] "...
79,141
def safe_divide(numerator, denominator, ones=False): """Divide ignoring div by zero warnings""" if isinstance(numerator, pd.Series): numerator = numerator.values if isinstance(denominator, pd.Series): denominator = denominator.values numerator = numerator.astype(float) denominator ...
79,142
def fgt_set_sensorRegulation(sensor_index, pressure_index, setpoint): """Sets the flow rate on the specified flow rate channel, using the specified pressure channel as an actuator""" c_error = c_ubyte(lib.fgt_set_sensorRegulation(c_uint(sensor_index), c_uint(pressure_index), c_f...
79,143
def main(): """ TODO think about better data structure, list of tuples might be better, perhaps a class for a self-sorting tuple manager, essentially a DB """ input_file = sys.argv[1] output_file_top10occupations = sys.argv[2] output_file_top10states = sys.argv[3] occupation_aggregate, stat...
79,144
def test_different_reuse_distances(): """ tests the calculation of alpha values using different reuse distances""" # init default AlphaTree a = AlphaTree() reuseDist = 0 memAddr = 0b111111111 a.ProcessAccess(memAddr, reuseDist) sol = np.zeros((3, 7, 2), dtype = np.flo...
79,145
def _read_solvr(f): """Read SOLVR block data.""" fmt = block_to_format["SOLVR"] solvr = {} line = next(f) data = read_record(line, fmt) solvr["solver"] = { "method": data[0], "z_precond": data[2], "o_precond": data[4], "rel_iter_max": data[5], "eps": data...
79,146
def resetPowerOverDrive(deviceList, autoRespond): """ Reset Power OverDrive to the default value @param deviceList: List of DRM devices (can be a single-item list) """ setPowerOverDrive(deviceList, 0, autoRespond)
79,147
def populate_sample_paths(sample, schema, check_exist=False): """ Populate path-like Sample attributes with other object attributes based on a defined template, e.g. '/Users/x/test_{name}/{genome}_file.txt' :param peppy.Sample sample: sample to populate paths in :param Iterable[dict] schema: schema...
79,148
def handle_run(configuration): """usage: cosmic-ray run [options] [--dist] [--exclude-modules=P ...] (--timeout=T | --baseline=M) <session-name> <top-module> [-- <test-args> ...] This simply runs the "init" command followed by the "exec" command. It's important to remember that "init" clears the session database,...
79,149
def main(): """Main function""" # parser input arguments args = parseargs() # create file writer dataset_writer = dataset_factory.get_writer(args.datasetname) writer = dataset_writer() # retrieve list of data datalst = writer.generate_data_lst_from_split(args.splitlist) # decide w...
79,150
def main() -> int: """ Runs the program :returns: an exit code for the script """ global TO_COOKIE, TO_LOGIN, TO_URL, LOG_LEVELS, MODE, needInstall, DISTRO, TS_ROOT, FMT # I have no idea why, but the old ORT script does this on every run. print(datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y")) ...
79,151
def default_states_preprocessor(states): """ Convert list of states into the form suitable for model. By default we assume Variable :param states: list of numpy arrays with states :return: Variable Obtained from https://github.com/Shmuma/ptan/blob/master/ptan/agent.py """ if not is...
79,152
def get_candidates_for_bid(bid_id: str) -> List[helpling_schema.DecoratedPotentialCandidateEdge]: """ Query the API for all (i.e. the first 1000) candidates for a given bid. The bid must have been parametrized already. Note that not all fields are actually requested from the backend. :param bid_id: Id o...
79,153
def arc_svg_to_parametric(src, dst, rx, ry, x_axis_rot, large_flag, sweep_flag): """Convert arc from SVG arguments to parametric curve This code mostly comes from arc implementation notes from svg sepc (Arc to Parametric)[https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes] Returns arc para...
79,154
def GroupBuilder(size, builderFunc, indAttr): """size - the number of members of the group indAttr - a list of [size, possList, probList] for IndividualBuilder file - the csv file to rebuild an existing group from""" individualSize = indAttr[0] possList = indAttr[1] probList = indAttr[2] ...
79,155
def detect_number_of_cores(): """ Detects the number of cores on a system. Cribbed from pp. """ # Linux, Unix and MacOS: if hasattr(os, "sysconf"): if "SC_NPROCESSORS_ONLN" in os.sysconf_names: # Linux & Unix: ncpus = os.sysconf("SC_NPROCESSORS_ONLN") if i...
79,156
def _read_timestamp(file): """Get start and end time from timestamp csv file.""" try: with open(file, 'r') as f: rows = f.readlines() starttime, endtime = float(rows[0].split(",")[0]), float(rows[-1].split(",")[0]) starttime, endtime = starttime / (10**3), endtime / (10**...
79,157
def _refine_resourcedetails(response: Dict, Translator: DataFields) -> ResourceDetails: """Parse the resource details response. Args: response: Ganttic API response Translator: Description of fields Returns: task Details Pydantic. """ res = response.copy() # custom parsing ...
79,158
def rerun(): """ Rerun last example code block with specified version of Python. """ from commandlib import Command version = _personal_settings().data["params"]["python version"] Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))( DIR.gen.joinpath("working", "examplepy...
79,159
def plot_sim_matrix(clusterings, scoring): """ Plot a similarity matrix between a list of clusterings, using the provided scoring function. :param clusterings: list of clusterings to compare :param scoring: the scoring function to use :return: a ClusterGrid instance Example: >>> from cdli...
79,160
def examples(manager: Manager, debug: bool): """Load examples to the database.""" level = logging.DEBUG if debug else logging.INFO logging.basicConfig(level=level) logging.getLogger('pybel').setLevel(level) for graph in (sialic_acid_graph, statin_graph, homology_graph, braf_graph, egf_graph): ...
79,161
def _copy_attachments(syn: Synapse, entity_wiki: Wiki) -> list: """Copy wiki attachments Args: syn: Synapse connection entity_wiki: Wiki you are copying Returns: Synapse Attachment filehandleids """ # All attachments must be updated if entity_wiki["attachmentFileHandle...
79,162
def generic_actor(name=None, health=None, r=None, g=None, b=None, y=None, x=None, m=None, h=None, c=None): """Simple factory to keep tests focused.""" base = (50, 100) health = health or base r = r or base g = g or base b = b or base y = y or base x = ...
79,163
def error_not_found(message, redirect): """ Shows an error message that a page couldn't be found. """ return error('Not found: {}'.format(message), redirect)
79,164
def Rz(angle:float, use_degrees:bool=False) -> np.ndarray: """Rotation matrix, for a rotation about the z-axis. Args: angle (float): Counter-clockwise angle of rotation as viewed looking back along the postive direction of the rotation axis. use_degrees (bool): Handle input and out...
79,165
def __folha(soup): """ Gets the most read news from the Folha de Sao Paulo page :param soup: the BeautifulSoup object :return: a list with the most read news from the Folha de Sao Paulo Page """ news = [] anchors = soup.find('ol', class_='c-most-read__list').find_all('a') for a in anc...
79,166
def get_table_cols_w_type(table, conn_handler=None): """Returns the column headers and its type Parameters ---------- table : str The table name conn_handler : SQLConnectionHandler, optional The connection handler object connected to the db Returns ------- list of tuple...
79,167
def _require_auth( handler: Callable[[web.Request, "User"], Awaitable], *, redirect: bool = True, admin: bool = False, ) -> Callable[[web.Request], Awaitable]: """This does the heavy lifting for the authorization check""" @wraps(handler) async def wrapped(request: web.Request) -> web.Respon...
79,168
def generate_padding_mask(x: torch.Tensor, length: torch.Tensor) -> torch.Tensor: """ Args: x: tensor of shape [batch_size, length] length: tensor of shape [batch_size] Returns: float tensor of shape [batch_size, length] """ assert x.dim() == 2 assert length.dim() == 1 ...
79,169
def track_command(func): """ Decorator to track execution of a command. This method executes the function, gathers all relevant metrics, reports the metrics and returns. If you have a Click command, you can track as follows: .. code:: python @click.command(...) @click.options(...) ...
79,170
def change_events_timegenerated(): """ :return: True if successfully changed the TimeGenerated configuration """ collect_to_create = "s|'Timestamp' => OMS::Common::fast_utc_to_iso8601_format(Time.now.utc),|'Timestamp' =>" \ " OMS::Common::fast_utc_to_iso8601_format(Time.at(time)....
79,171
def slow_down(_func=None, *, rate=1): """Sleep given amount of seconds before calling the function""" def decorator_slow_down(func): @functools.wraps(func) def wrapper_slow_down(*args, **kwargs): time.sleep(rate) return func(*args, **kwargs) return wrapper_slow_do...
79,172
def RegularStrandCurvature(**kwargs): """ Returns angle and dihedral constraints strings that dictate the curvature of strands without bulges. Given a strand, place curvature and twist constraints every 2*level positions. Angle constraints, for curvature, are placed on CA atoms. Dihedral...
79,173
def test_get_save_file(mocker, tmp_path): """ test get_save_file """ def mock_user_data_dir(appname, appauthor, version): return tmp_path / appname / appauthor / version mocker.patch.object(resources.appdirs, "user_data_dir", mock_user_data_dir) mocker.patch.objec...
79,174
def _compose_tfms(args): """Create a composite transform from inputs.""" in_file, in_xform, ifargs, index, newpath = args out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index, newpath=newpath, use_ext=True) xfm = ants.ApplyTransforms( input_image=in_fi...
79,175
async def changelog() -> HTMLResponse: """ Display the changelog for this API """ return HTMLResponse(content=_get_changelog_html())
79,176
def set_level(world_number, char): # used for changing to a new level and reloading level """ Changes the level and soft-resets the character state. The total gold collected is stored, while current gold is reset. The character's position is also set to the new world's start position. If not all t...
79,177
def switch(ranker, key1, key2): """ Switch the rankers given by the two keys """ r = ranker[key1] ranker[key1] = ranker[key2] ranker[key2] = r
79,178
def extract_times(UV, ra, dt): """Extracts data from specified times from an already open UVData instance. This is an alternative to opening the file with the times specified using pyuvdata.UVData.open(). Parameters ---------- UV : pyuvdata.UVData() instance The UVData instance from wh...
79,179
def apply(df, target_func, n_cpus=None): """ Apply row-wise a user-defined target function to the file index. Each row is passed as input to the function. The call for each row is done in parallel. Parameters ---------- - df: a DataFrame with the file index. - target_func: a user-defined f...
79,180
def load_mnist() -> Dataset: """Loads the MNIST dataset using OpenML. OpenML dataset link: https://www.openml.org/d/554 """ mnist_openml = openml.datasets.get_dataset(554) Xy, _, _, _ = mnist_openml.get_data(dataset_format="array") X = Xy[:, :-1] # the last column contains labels y = Xy[:, ...
79,181
def gen_save_best_models_by_val_score( save_handler: Union[Callable, BaseSaveHandler], evaluator: Engine, models: Union[torch.nn.Module, Dict[str, torch.nn.Module]], metric_name: str, n_saved: int = 3, trainer: Optional[Engine] = None, tag: str = "val", **kwargs: Any ): """Method add...
79,182
def favicon(): """ Returns the favicon when working in dev. """ return flask.send_from_directory('static/images', 'favicon.ico')
79,183
def load_np(filename, control=False): """ Load the raw data from h5 files :param filename: [string] filename to be read in :return: 4 x [np array[float64]] leads, [np array[int]] time vector, [np array[int]] heartrate vector from machine, [np array[float64]] abs pos sum ECG signal """ pr...
79,184
def get_ent(s): """ Return 1 if there is no enantiomer and 2 if there is based on @ sign appearing in the smiles """ sites = 0 xyz = get_xyz(s) s2 = get_smiles(xyz) frags = s2.split('[') for frag in frags: if '@' in frag: sites += 1 ent = 2.**sites retu...
79,185
def run(varname: str): """ getenv print PHP environment variables. """ res = send(get_php(varname)) result = "None" if not res.r_text else res.r_text if (not res): return print(f"\n{varname}:{result}\n")
79,186
def read_pkg_info(path: Union[bytes, str, PathLike]) -> Message: """Read a PKG-INFO or METADATA file.""" with open(path, encoding="utf-8") as headers: return Parser().parse(headers)
79,187
def isdefined(obj, force_import=False, namespace=None): """Return True if object is defined in namespace If namespace is None --> namespace = locals()""" if namespace is None: namespace = locals() attr_list = obj.split('.') base = attr_list.pop(0) if len(base) == 0: retur...
79,188
def deserialize_namedtuple( obj: Dict[str, Any], to: Type[NT], attr_deserializers: Optional[Dict[str, Callable[[PrimitiveType], T]]] = None, type_deserializers: Optional[Dict[Type, Callable[[PrimitiveType], T]]] = None, ) -> NT: """ Deserializes a Dict loaded from JSON into a NamedTuple object ...
79,189
def delayed_stream(iterable, delay_seconds=0): """Iterable wrapper that delayed consumption by delay_seconds.""" q = mp.Queue() producer = mp.Process(target=_producer, args=(iterable, q)) p = mp.Process(target=_producer, args=(iterable, q)) p.start() while True: timestamp, item = q.get()...
79,190
def infer_reader(file_path, word_dict): """ Reader interface for prediction :param data_dir: data directory :type data_dir: str :param word_dict: path of word dictionary, the dictionary must has a "UNK" in it. :type word_dict: Python dict """ def reader(): UNK_ID = word...
79,191
def test_robots_txt(client): """Make sure we have a robots.txt file.""" response = client.get('/robots.txt') assert response.status_code == 200
79,192
def object_func(x, A, b): """ Objective function for the optimization for L-BFGS-B """ y = A * x - b return 0.5 * y.dot(y)
79,193
def create_wallet(request): """Create wallet from the form data.""" if request.method == "POST": form = CreateWalletForm(request.POST) if form.is_valid(): wallet_id = add_wallet( form.cleaned_data["name"], form.cleaned_data["password"] ) if ...
79,194
def random_binomial(shape, p=0.0, dtype=None, seed=None): """Returns a tensor with random binomial distribution of values. # Arguments shape: A tuple of integers, the shape of tensor to create. p: A float, `0. <= p <= 1`, probability of binomial distribution. dtype: String, dtype of ret...
79,195
def generate_user_data(count=1): """ generate a list of dictionaries containing data necessary to create a User object :param count: :return: """ return [{'username': 'user_{:03}'.format(i)} for i in range(1, count + 1)]
79,196
def start_cloudcmd(request): """ Start Cloudcmd :param request: Ajax request :return: """ cmd = "node node_modules/cloudcmd/bin/cloudcmd --one-panel-mode --port " with open("settings.json") as some_settings: new_settings = json.loads(some_settings.read()) some_settings.close...
79,197
def sanity_check(state): """ Check invariants that must hold. """ # if a transfer is paid we must know the secret all_transfers_states = itertools.chain( (pair.payee_state for pair in state.transfers_pair), (pair.payer_state for pair in state.transfers_pair), ) if any(state in STATE...
79,198
async def test_user_input_unexpected_error(hass, mock_scan): """Test that unexpected error yields an error message.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) mock_scan.side_effect = Exception result2 = await hass.config_e...
79,199