content
stringlengths
22
815k
id
int64
0
4.91M
def add_device(overlay_id) -> Union[str, Tuple[str, int]]: """ Add device to an overlay. """ manager = get_manager() api_key = header_api_key(request) if not manager.api_key_is_valid(api_key): return jsonify(error="Not authorized"), 403 if not request.data: return jsonify(err...
18,200
def pvtol(t, x, u, params={}): """Reduced planar vertical takeoff and landing dynamics""" from math import sin, cos m = params.get('m', 4.) # kg, system mass J = params.get('J', 0.0475) # kg m^2, system inertia r = params.get('r', 0.25) # m, thrust offset g = params.get('g', 9.8) # ...
18,201
def write_bins(grp, req, buf, unit, res, chroms, bins, by_chr_bins, norm_info, show_warnings): """ Write the bins table, which has columns: chrom, start (in bp), end (in bp), and one column for each normalization type, named for the norm type. 'weight' is a reserved column for `cooler balance`. Chro...
18,202
def route( path: str, methods: List[str], **kwargs: Any ) -> Callable[[AnyCallable], AnyCallable]: """General purpose route definition. Requires you to pass an array of HTTP methods like GET, POST, PUT, etc. The remaining kwargs are exactly the same as for FastAPI's decorators like @get, @post, etc. M...
18,203
def canHaveGui(): """Return ``True`` if a display is available, ``False`` otherwise. """ # We cache this because calling the # IsDisplayAvailable function will cause the # application to steal focus under OSX! try: import wx return wx.App.IsDisplayAvailable() except ImportError:...
18,204
def test_convert_json(): """ Test converting a JSON file to Parquet """ schema = pa.schema([ pa.field("foo", pa.int32()), pa.field("bar", pa.int64()) ]) input_path = "{}/tests/fixtures/simple_json.txt".format(os.getcwd()) expected_file = "{}/tests/fixtures/simple.parquet".fo...
18,205
def syntactic_analysis(input_fd): """ Realiza análisis léxico-gráfico y sintáctico de un programa Tiger. @type input_fd: C{file} @param input_fd: Descriptor de fichero del programa Tiger al cual se le debe realizar el análisis sintáctico. @rtype: C{LanguageNode} @return: Como ...
18,206
def create_fixxation_map(eye_x, eye_y, fixxation_classifier): """ :param eye_x: an indexable datastructure with the x eye coordinates :param eye_y: an indexable datastructure with the y eye coordinates :param fixxation_classifier: a list with values which indicate ...
18,207
def with_metadata(obj: T, key: str, value: Any) -> T: """ Adds meta-data to an object. :param obj: The object to add meta-data to. :param key: The key to store the meta-data under. :param value: The meta-data value to store. :return: obj. """ # Create the meta-data map ...
18,208
def checksum(uploaded_file: 'SimpleUploadedFile', **options): """ Function to calculate checksum for file, can be used to verify downloaded file integrity """ hash_type = options['type'] if hash_type == ChecksumType.MD5: hasher = hashlib.md5() elif hash_type == ChecksumType.SHA256:...
18,209
def get_page(url): """Get source of url Keyword Arguments: url : string """ logger.debug(f'Getting source for {url}') res = requests.get(url) logger.debug(f'Status code for {url} is {res.status_code}') if res.status_code < 200 or res.status_code >= 300: raise Exception(f''' ...
18,210
def preceding_words(document: Document, position: types.Position) -> Optional[Tuple[str, str]]: """ Get the word under the cursor returning the start and end positions. """ lines = document.lines if position.line >= len(lines): return None row, col = position_from_utf16(lines, position)...
18,211
def check_gpu(gpu, *args): """Move data in *args to GPU? gpu: options.gpu (None, or 0, 1, .. gpu index) """ if gpu == None: if isinstance(args[0], dict): d = args[0] #print(d.keys()) var_dict = {} for key in d: var_dict[key] = ...
18,212
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up the SleepIQ config entry.""" conf = entry.data email = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] client_session = async_get_clientsession(hass) gateway = AsyncSleepIQ(client_session=client_session)...
18,213
def print_sonar_alert(alert, console): """Print AUnit Alert as sonar message""" def print_alert(): for line in alert.details: console.printout(escape(line)) if alert.details and alert.stack: console.printout('') for frame in alert.stack: console.pri...
18,214
def main(): # Main function for testing. """ Create binary tree. """ root = make_tree() """ All Traversals of the binary are as follows: """ print(f" In-order Traversal is {inorder(root)}") print(f" Pre-order Traversal is {preorder(root)}") print(f"Post-order Traversa...
18,215
def expansion(svsal,temp,pres,salt=None,dliq=None,dvap=None, chkvals=False,chktol=_CHKTOL,salt0=None,dliq0=None,dvap0=None, chkbnd=False,useext=False,mathargs=None): """Calculate seawater-vapour thermal expansion coefficient. Calculate the thermal expansion coefficient of a seawater-vapour parc...
18,216
def git_push(branches_to_push: list, ask: bool = True, push: bool = False): """Push all changes.""" if ask: push = input("Do you want to push changes? (y)") in ("", "y", "yes",) cmd = ["git", "push", "--tags", "origin", "master", *branches_to_push] if push: command(cmd) else: ...
18,217
def yaml_to_dict(yaml_str=None, str_or_buffer=None): """ Load YAML from a string, file, or buffer (an object with a .read method). Parameters are mutually exclusive. Parameters ---------- yaml_str : str, optional A string of YAML. str_or_buffer : str or file like, optional F...
18,218
def verify_block_arguments( net_part: str, block: Dict[str, Any], num_block: int, ) -> Tuple[int, int]: """Verify block arguments are valid. Args: net_part: Network part, either 'encoder' or 'decoder'. block: Block parameters. num_block: Block ID. Return: block_...
18,219
def _colorama(*args, **kwargs): """Temporarily enable colorama.""" colorama.init(*args, **kwargs) try: yield finally: colorama.deinit()
18,220
def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()): """ Compute the average precision, given the recall and precision curves. Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. # Arguments tp: True positives (nparray, nx1 or nx10). conf: Ob...
18,221
def frame_aligned_point_error( pred_frames: r3.Rigids, target_frames: r3.Rigids, frames_mask: paddle.Tensor, pred_positions: r3.Vecs, target_positions: r3.Vecs, positions_mask: paddle.Tensor, length_scale: float, l1_clamp_distance: Optional[float] = None, epsilon=1e-4) -> ...
18,222
def remove_app_restriction_request(machine_id, comment): """Enable execution of any application on the machine. Args: machine_id (str): Machine ID comment (str): Comment to associate with the action Notes: Machine action is a collection of actions you can apply on the machine, for ...
18,223
def fix_bond_lengths( dist_mat: torch.Tensor, bond_lengths: torch.Tensor, delim: int = None, delim_value: float = ARBITRARILY_LARGE_VALUE) -> torch.Tensor: """ Replace one-offset diagonal entries with ideal bond lengths """ mat_len = dist_mat.shape[1] bond_lengths = t...
18,224
def add_problem(report, problem, description, ack): """Add problem dict to report""" report["Problems"][problem] = {} report["Problems"][problem]["Description"] = description report["Problems"][problem]["Acknowledged"] = ack
18,225
def CommandToString(command): """Returns quoted command that can be run in bash shell.""" return ' '.join(cmd_helper.SingleQuote(c) for c in command)
18,226
def sample_trilinear(t, coords, img_h=128, img_w=128): """ Samples noise octaves in one shot :param t: noise cube [n_octaves, noise_res, noise_res, noise_res] (same noise foreach sample in batch) :param coords: octave-transformed sampling positions [bs, n_octaves, 3, img_h*img_w] :param img_h: heig...
18,227
def file_capture(pcap_files, bpf, out_file, count=0, dump=False): """ :param dump: Dump to stdout if true, does not send packets :type dump: bool :type count: int :type out_file: str :type bpf: str :type pcap_files: List[str] """ # try: # es = None # if node is not None: ...
18,228
def version(output): """ `git --version` > git version 1.8.1.1 """ output = output.rstrip() words = re.split('\s+', output, 3) if not words or words[0] != 'git' or words[1] != 'version': raise WrongOutputError() version = words[2] parts = version.split('.') try: major...
18,229
def set_up_s3_encryption_configuration(kms_arn=None): """ Use the default SSE-S3 configuration for the journal export if a KMS key ARN was not given. :type kms_arn: str :param kms_arn: The Amazon Resource Name to encrypt. :rtype: dict :return: The encryption configuration for JournalS3Export. ...
18,230
def search(dataset, node, aoi, start_date, end_date, lng, lat, dist, lower_left, upper_right, where, geojson, extended, api_key): """ Search for images. """ node = get_node(dataset, node) if aoi == "-": src = click.open_file('-') if not src.isatty(): lines = src.readline...
18,231
def _make_rnn_cell(spec: RNNSpec) -> Callable[[], tf.nn.rnn_cell.RNNCell]: """Return the graph template for creating RNN cells.""" return RNN_CELL_TYPES[spec.cell_type](spec.size)
18,232
def swap(b, h, k): """ Procedure that swaps b[h] and b[k] in b Parameter b: The list to modify Precondition: b is a mutable list, Parameter h: The first position to swap Precondition: h is an int and a valid position in the list Parameter k: The first position to swap Precondition: k ...
18,233
def run_baselines(env, seed, log_dir): """Create baselines model and training. Replace the ppo and its training with the algorithm you want to run. Args: env (gym.Env): Environment of the task. seed (int): Random seed for the trial. log_dir (str): Log dir path. Returns: ...
18,234
def dataset_str2float(dataset, column): """ Converts a dataset column's values from string to float """ for row in dataset: row[column] = float(row[column].strip())
18,235
def SolveRcpsp(problem, proto_file, params): """Parse and solve a given RCPSP problem in proto format.""" PrintProblemStatistics(problem) # Create the model. model = cp_model.CpModel() num_tasks = len(problem.tasks) num_resources = len(problem.resources) all_active_tasks = range(1, num_ta...
18,236
def load_stl(): """Loads the STL-10 dataset from config.STL10_PATH or downloads it if necessary. :return: (x_train, y_train), (x_test, y_test), min, max :rtype: tuple of numpy.ndarray), (tuple of numpy.ndarray), float, float """ from config import STL10_PATH min_, max_ = 0., 1. # Download ...
18,237
def PolyCurveCount(curve_id, segment_index=-1): """Returns the number of curve segments that make up a polycurve"""
18,238
def count_transitions(hypno): """ return the count for all possible transitions """ possible_transitions = [(0,1), (0,2), (0,4), # W -> S1, S2, REM (1,2), (1,0), (1,3), # S1 -> W, S2, REM (2,0), (2,1), (2,3), (2,4), # S2 -> W, S1, SWS, REM ...
18,239
def mu_ref_normal_sampler_tridiag(loc=0.0, scale=1.0, beta=2, size=10, random_state=None): """Implementation of the tridiagonal model to sample from .. math:: \\Delta(x_{1}, \\dots, x_{N})^{\\beta} \\prod_{n=1}^{N} \\exp(-\\frac{(x_i-\\mu)^2}{2\\sigma^2} ) dx_...
18,240
def view_request_headers(client, args): """ View the headers of the request Usage: view_request_headers <reqid(s)> """ if not args: raise CommandError("Request id is required") reqs = load_reqlist(client, args[0], headers_only=True) for req in reqs: print('-- Request id=%s --...
18,241
def get_ofi_info(hosts, supported=None, verbose=True): """Get the OFI provider information from the specified hosts. Args: hosts (NodeSet): hosts from which to gather the information supported (list, optional): list of supported providers when if provided will limit the inclusion to...
18,242
def get_pokemon(name:str) -> dict: """ Busca el pokémon dado su nombre en la base de datos y crea un diccionario con su información básica. Paramétros: name(str): Nombre del pokémon a buscar Retorna: Diccionario con la información básica del pokémon y sus evoluciones. """ try: ...
18,243
def run_and_check_command_in_hadoop(hadoop_node_config, command, cmd_work_dir=None, log_line_processor=None): """Run the given command on the Hadoop cluster. Args: hadoop_node_config - where to S...
18,244
def create_cluster(module, switch, name, node1, node2): """ Method to create a cluster between two switches. :param module: The Ansible module to fetch input parameters. :param switch: Name of the local switch. :param name: The name of the cluster to create. :param node1: First node of the clust...
18,245
def random_terminals_for_primitive( primitive_set: dict, primitive: Primitive ) -> List[Terminal]: """ Return a list with a random Terminal for each required input to Primitive. """ return [random.choice(primitive_set[term_type]) for term_type in primitive.input]
18,246
def _specie_is_intermediate_old( specie_id: str, specie_dict: dict = None, ) -> bool: """Detect is a specie should be considered as an intermediate compound. FIXME, this needs to be refined so that we don't rely on the specie ID. :param specie_id: specie ID :type: str :param specie_di...
18,247
def where_from_pos(text, pos): """ Format a textual representation of the given position in the text. """ return "%d:%d" % (line_from_pos(text, pos), col_from_pos(text, pos))
18,248
def test(ctx, unit=False, installed=False, style=False, cover=False): """run tests (unit, style)""" if not (unit or installed or style or cover): sys.exit("Test task needs --unit, --style or --cover") if unit: sys.exit(pytest_wrapper()) if style: flake8_wrapper() # exits on f...
18,249
def generateHuffmanCodes (huffsize): """ Calculate the huffman code of each length. """ huffcode = [] k = 0 code = 0 # Magic for i in range (len (huffsize)): si = huffsize[i] for k in range (si): huffcode.append ((i + 1, code)) code += 1 code <<=...
18,250
def test_ast_generation(): """ >>> test_ast_generation() """ m = load_testschema1() # Nonterminals assert issubclass(m.root, m.AST) assert issubclass(m.expr, m.AST) # Products assert issubclass(m.myproduct, m.AST) # Terminals assert issubclass(m.Ham, m.root) assert iss...
18,251
def one_hot_df(df, cat_col_list): """ Make one hot encoding on categoric columns. Returns a dataframe for the categoric columns provided. ------------------------- inputs - df: original input DataFrame - cat_col_list: list of categorical columns to encode. outputs ...
18,252
async def load_users_by_id(user_ids: List[int]) -> List[Optional[User]]: """ Batch-loads users by their IDs. """ query = select(User).filter(User.id.in_(user_ids)) async with get_session() as session: result: Result = await session.execute(query) user_map: Dict[int, User] = {user.id: use...
18,253
def create_timetravel_model(for_model): """ Returns the newly created timetravel model class for the model given. """ if for_model._meta.proxy: _tt_model = for_model._meta.concrete_model._tt_model for_model._tt_model = _tt_model for_model._meta._tt_model = _tt_model r...
18,254
def public_route_server_has_read(server_id, user_id=None): """ check if current user has read access to the given server """ user = user_id and User.query.get_or_404(user_id) or current_user server = DockerServer.query.get_or_404(server_id) if server.has_group_read(user): return Respons...
18,255
def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_check(address.encode()) valid = True except ValueError: # checksum mismatch ...
18,256
def address_print(): """ Print the working directory :return:None """ print_line(70, "*") print("Where --> " + SOURCE_DIR) print_line(70, "*")
18,257
def cost_to_go_np(cost_seq, gamma_seq): """ Calculate (discounted) cost to go for given cost sequence """ # if np.any(gamma_seq == 0): # return cost_seq cost_seq = gamma_seq * cost_seq # discounted reward sequence cost_seq = np.cumsum(cost_seq[:, ::-1], axis=-1)[:, ::-1] # cost to ...
18,258
def parse_args(): """ Parses the command line arguments. """ # Override epilog formatting OptionParser.format_epilog = lambda self, formatter: self.epilog parser = OptionParser(usage="usage: %prog -f secret.txt | --file secret.txt | --folder allmysecrets", epilog=EXAMPLES) parser.add_option("-p", "--password", ...
18,259
def x_to_ggsg(seq): """replace Xs with a Serine-Glycine linker (GGSG pattern) seq and return value are strings """ if "X" not in seq: return seq replacement = [] ggsg = _ggsg_generator() for aa in seq: if aa != "X": replacement.append(aa) # restart li...
18,260
def gini_pairwise(idadf, target=None, features=None, ignore_indexer=True): """ Compute the conditional gini coefficients between a set of features and a set of target in an IdaDataFrame. Parameters ---------- idadf : IdaDataFrame target : str or list of str, optional A co...
18,261
def init_isolated_80(): """ Real Name: b'init Isolated 80' Original Eqn: b'0' Units: b'person' Limits: (None, None) Type: constant b'' """ return 0
18,262
def xcom_api_setup(): """Instantiate api""" return XComApi(API_CLIENT)
18,263
def test_kl_normal_normal(): """Test Normal/Normal KL.""" dim = (5, 10) mu = np.zeros(dim, dtype=np.float32) std = 1.0 q = tf.distributions.Normal(mu, std) # Test 0 KL p = tf.distributions.Normal(mu, std) KL0 = kl_sum(q, p) # Test diff var std1 = 2.0 p = tf.distributions.N...
18,264
def zeros_tensor(*args, **kwargs): """Construct a tensor of a given shape with every entry equal to zero.""" labels = kwargs.pop("labels", []) dtype = kwargs.pop("dtype", np.float) base_label = kwargs.pop("base_label", "i") return Tensor(np.zeros(*args, dtype=dtype), labels=labels, ...
18,265
def reg_split_from( splitted_mappings: np.ndarray, splitted_sizes: np.ndarray, splitted_weights: np.ndarray, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ When creating the regularization matrix of a source pixelization, this function assumes each source pixel has been split into a ...
18,266
def get_initiator_IP(json_isessions): """ pull the IP from the host session """ print("-" * 20 + " get_initiator started") for session in json_isessions['sessions']: session_array[session['initiatorIP']] = session['initiatorName'] return session_array
18,267
def get_data_for_recent_jobs(recency_msec=DEFAULT_RECENCY_MSEC): """Get a list containing data about recent jobs. This list is arranged in descending order based on the time the job was enqueued. At most NUM_JOBS_IN_DASHBOARD_LIMIT job descriptions are returned. Args: - recency_secs: the thres...
18,268
def test_installroot_sdist_with_extras(project: Project) -> None: """It installs the extra.""" @nox.session def test(session: nox.sessions.Session) -> None: """Install the local package.""" nox_poetry.installroot( session, distribution_format=nox_poetry.SDIST, extras=["pygments"...
18,269
def construct_outgoing_multicast_answers(answers: _AnswerWithAdditionalsType) -> DNSOutgoing: """Add answers and additionals to a DNSOutgoing.""" out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, multicast=True) _add_answers_additionals(out, answers) return out
18,270
def load_analog_binary_v1(filename): """Load analog traces stored in the binary format by Logic 1.2.0+ The format is documented at https://support.saleae.com/faq/technical-faq/data-export-format-analog-binary Returns (data, period) where data is a numpy array of 32-bit floats of shape (nchannels, ...
18,271
def setup_phantomjs(): """Create and return a PhantomJS browser object.""" try: # Setup capabilities for the PhantomJS browser phantomjs_capabilities = DesiredCapabilities.PHANTOMJS # Some basic creds to use against an HTTP Basic Auth prompt phantomjs_capabilities['phantomjs.page...
18,272
def normal_pdf(x, mu, cov, log=True): """ Calculate the probability density of Gaussian (Normal) distribution. Parameters ---------- x : float, 1-D array_like (K, ), or 2-D array_like (K, N) The variable for calculating the probability density. mu : float or 1-D array_like, (K, ) ...
18,273
def write_log(s, *args): """ :undocumented: Writes to log.txt. """ renpy.display.log.write(s, *args)
18,274
def aws() -> Generator[Mock, None, None]: """Mock our mqtt client wrapper""" with patch("edge.edge.CloudClient", autospec=True) as mock: yield mock.return_value
18,275
def get_quiz(id, user): """Get Quiz""" conn = sqlite3.connect(DBNAME) cursor = conn.cursor() if user == 'admin' or user == 'fabioja': cursor.execute( "SELECT id, release, expire, problem, tests, results, diagnosis, numb from QUIZ where id = {0}".format(id)) else: cursor.e...
18,276
def filesystem_entry(filesystem): """ Filesystem tag {% filesystem_entry filesystem %} is used to display a single filesystem. Arguments --------- filesystem: filesystem object Returns ------- A context which maps the filesystem object to filesystem. """ return {'fi...
18,277
def haversine(lat1, lon1, lat2, lon2, units='miles'): """ Calculates arc length distance between two lat_lon points (must be in radians) lat2 & and lon2 can be numpy arrays units can be 'miles' or 'km' (kilometers) """ earth_radius = {'miles': 3959., 'km': 6371.} a = np.sq...
18,278
def OptionalDateField(description='',validators=[]): """ A custom field that makes the DateField optional """ validators.append(Optional()) field = DateField(description,validators) return field
18,279
def ShowAllPte(cmd_args=None): """ Prints out the physical address of the pte for all tasks """ head_taskp = addressof(kern.globals.tasks) taskp = Cast(head_taskp.next, 'task *') while taskp != head_taskp: procp = Cast(taskp.bsd_info, 'proc *') out_str = "task = {:#x} pte = {:#x}\t"....
18,280
def init_brats_metrics(): """Initialize dict for BraTS Dice metrics""" metrics = {} metrics['ET'] = {'labels': [3]} metrics['TC'] = {'labels': [1, 3]} metrics['WT'] = {'labels': [1, 2, 3]} for _, value in metrics.items(): value.update({'tp':0, 'tot':0}) return metrics
18,281
def add_rse(rse, issuer, vo='def', deterministic=True, volatile=False, city=None, region_code=None, country_name=None, continent=None, time_zone=None, ISP=None, staging_area=False, rse_type=None, latitude=None, longitude=None, ASN=None, availability=None): """ Creates a new R...
18,282
def multi_graph_partition(costs: Dict, probs: Dict, p_t: np.ndarray, idx2nodes: Dict, ot_hyperpara: Dict, weights: Dict = None, predefine_barycenter: bool = False) -> \ Tuple[List[Dict], List[Dict], List[Dict], Dict, np.ndarray]: ...
18,283
def TDataStd_BooleanArray_Set(*args): """ * Finds or creates an attribute with the array. :param label: :type label: TDF_Label & :param lower: :type lower: int :param upper: :type upper: int :rtype: Handle_TDataStd_BooleanArray """ return _TDataStd.TDataStd_BooleanArray_Set(*ar...
18,284
def py_list_to_tcl_list(py_list): """ Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python list. :type py_list: list :return: string representing the Tcl string equivalent to the Python list. """ py_list_str = [str(s) for s in py_list] return tcl_str(tcl_interp_g.e...
18,285
def get_post_count(user): """ Get number of posts published by the requst user. Parameters ------------ user: The request user Returns ------- count: int The number of posts published by the requst user. """ count = Post.objects.filter(publisher=user).count() return...
18,286
def init_db(): # pragma: no cover """Initializes the DB""" database.init_db()
18,287
def test_dry_run(pytest_test_inst): """ Test the dry_run() method returns the expected report skeleton. """ result = pytest_test_inst.dry_run() report = result.report assert report == pytest_expected_data.EXPECTED_DRY_RUN_REPORT
18,288
def test_connect(ccid): """Check access (udev.""" power_off = ccid.power_off()[2] assert 0x81 == power_off[0] atr = ccid.power_on() assert 0x80 == atr[0] l = atr[1] assert [0x3B, 0x8C, 0x80, 0x01] == list(atr[10 : 10 + l])
18,289
def create_new_employee(employees): """ Create a new employee record with the employees dictionary Use the employee_sections dictionary template to create a new employee record. """ subsidiary = input('Employee Subsidiary (SK, CZ):') employee_id = generate_employee_id(subsidi...
18,290
def gather_squares_triangles(p1,p2,depth): """ Draw Square and Right Triangle given 2 points, Recurse on new points args: p1,p2 (float,float) : absolute position on base vertices depth (int) : decrementing counter that terminates recursion return: squares [(float,float,float,float)...] : absolut...
18,291
def send_email(subject, sender, recipients, html_body): """Функция отправки электронных писем Принимает в качестве аргументов тему письма, отправителя, получателя, и html-шаблон письма. Создается объект thread для отправки сообщения в новом потоке. """ app = current_app._get_current_object() ...
18,292
def update_node(node_name, node_type, root=None): """ ! Node is assumed to have only one input and one output port with a maximum of one connection for each. Returns: NodegraphAPI.Node: newly created node """ new = NodegraphAPI.CreateNode(node_type, root or NodegraphAPI.GetRootNode()) ...
18,293
def dan_acf(x, axis=0, fast=False): """ Estimate the autocorrelation function of a time series using the FFT. Args: x (array): The time series. If multidimensional, set the time axis using the ``axis`` keyword argument and the function will be computed for every other axis. ...
18,294
def schedule_decision(): """最適化の実行と結果の表示を行う関数""" # トップページを表示する(GETリクエストがきた場合) if request.method == "GET": return render_template("scheduler/schedule_decision.html", solution_html=None) # POSTリクエストである「最適化を実行」ボタンが押された場合に実行 # データがアップロードされているかチェックする。適切でなければ元のページに戻る if not check_request(requ...
18,295
def process_mtl_data(sources_dir, processed_dir, date): """Processes new Sante Montreal data. Parameters ---------- sources_dir : str Absolute path to source data dir. processed_dir : str Absolute path to processed data dir. date : str Date of data to append (yyyy-mm-dd)...
18,296
def infection_rate_asymptomatic_30x40(): """ Real Name: b'infection rate asymptomatic 30x40' Original Eqn: b'contact infectivity asymptomatic 30x40*(social distancing policy SWITCH self 40*social distancing policy 40\\\\ +(1-social distancing policy SWITCH self 40))*Infected asymptomatic 30x40*Susceptible 4...
18,297
def slug(hans, style=Style.NORMAL, heteronym=False, separator='-', errors='default', strict=True): """将汉字转换为拼音,然后生成 slug 字符串. :param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ). 可以使用自己喜爱的分词模块对字符串进行分词处理, 只需将经过分词处理的字符串列表传进来就可以了。 :type hans: unicode 字符串或字符串列表 ...
18,298
def A_weight(signal, fs): """ Return the given signal after passing through an A-weighting filter signal : array_like Input signal fs : float Sampling frequency """ b, a = A_weighting(fs) return lfilter(b, a, signal)
18,299