content
stringlengths
22
815k
id
int64
0
4.91M
def perturb_box(box, min_iou=0.5, sigma_factor=0.1): """ Perturb the input box by adding gaussian noise to the co-ordinates args: box - input box min_iou - minimum IoU overlap between input box and the perturbed box sigma_factor - amount of perturbation, relative to the box size. Can b...
43,800
def coverageCalc(coverageList,minCov): """Function parsing coverageList for :param coverageList: List of pacbam coverage information :param minCov: Int of minimum passing coverage :return: covCount: Int of bases with coverage minCovCount: Int of bases w...
43,801
def truncate_top_k_2(x, k): """Keep top_k highest values elements for each row of a numpy array Args: x (np.Array): numpy array k (int): number of elements to keep for each row Returns: np.Array: processed array """ s = x.shape # ind = np.argsort(x)[:, : s[1] - k] i...
43,802
def run(): """ read pipeline and do infer """ args = parse_args() # input_ids file list, every file content a tensor[1,128] file_list = glob.glob(os.path.join(os.path.realpath(args.data_dir), "10_data", "*.txt")) cwq_lists = [] for i in range(len(file_list)): b = os.path.split(fi...
43,803
def permute_dimensions(x, pattern): """Permutes axes in a tensor. # Arguments pattern: should be a tuple of dimension indices, e.g. (0, 2, 1). # Returns A tensor. """ return KerasSymbol(mx.sym.transpose(x.symbol, axes=pattern))
43,804
def main(): """Main function.""" print(f"Using root path {ROOT}") print() add_headers('*.py', 'HEADER_PY') add_headers('*.tex', 'HEADER_TEX') add_headers('*.yml', 'HEADER_YML')
43,805
def relaxStructure(s, operation): """ Performs a gulp relaxation (either relaxation of unit cell parameters only, or both unit cell and atomic positions. s: structure_class operation: string Specifies the gulp calculation to execute. Returns ------- s : structure_class ...
43,806
def dos_gaussian_shift(energies, dos_total, projections, nGridpoints, smearing): """ Produces a single gaussian function then shifts the gaussian around the grid Advantages: + Very fast compared to other methods Disadvantages: - Produces an edge effect, energy range should be larger than required - Very reliable...
43,807
def temp_h5_file(tmpdir_factory): """ a fixture that fetches a temporary output dir/file for a test file that we want to read or write (so it doesn't clutter up the test directory when the automated tests are run)""" return str(tmpdir_factory.mktemp('data').join('test.h5'))
43,808
def test_examples(shapes_file, test_file, assertion): """Test validity or invalidity of data against a SHACL shape Args: :param shapes_file: file where the SHACL shape is :param test_file: the data file to validate :param assertion: specify what to test validity or invalidity """ ...
43,809
def get_day_name(date): """ returns the day name for a give date @param date datatime @return month name .. faqref:: :tag: python :title: Récupérer le nom du jour à partir d'une date .. runpython:: :showcode: import date...
43,810
def os_ubuntu20_subiquity_tuple(os_ubuntu20, subiquity_cmdline_template): """ Ubuntu 20 with subiquity installer complete definition """ template_content = '' # use template from ubuntu18 for legacy installer with open(TEMPLATES_DIR + 'ubuntu20-subiquity.jinja', "r") as template_file: te...
43,811
def __replicate_test_method(cls, original_test, new_test_name): """ *Private* method that **clones** a test method, names it and inserts it in the test class """ # Create a new test from the old test new_test = FunctionType(original_test.func_code, original_test.func_globals, name=new_test_name) ...
43,812
def get_samples(n_samples, data, labels=None, use_random_transpose=False): """Return some random samples of the training data.""" indices = np.random.choice(len(data), n_samples, False) if np.issubdtype(data.dtype, np.bool_): sample_data = data[indices] * 2. - 1. else: sample_data = data...
43,813
def apply_to_tensor( x: Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes], func: Callable ) -> Union[torch.Tensor, collections.Sequence, collections.Mapping, str, bytes]: """Apply a function on a tensor or mapping, or sequence of tensors. Args: x: input tensor or mapping...
43,814
def test_sub_account_futures_asset_transfer_without_amount(): """Tests the API endpoint to transfer futures asset without amount""" param["amount"] = "" client = Client(key, secret) client.sub_account_futures_asset_transfer.when.called_with(**param).should.throw( ParameterRequiredError )
43,815
def status(): """ Returns a page showing the number of unprocessed certficate-requests. """ result = db.session.query(Request).filter(Request.generation_date == None).count() return render_template('status.html', requests=result)
43,816
def test_available_plugins_trainer(): """ Test that available plugins return the correct list in the trainer. """ plugins = Trainer.available_plugins() expected_plugins = [e.name for e in LightningCustomPlugins] assert plugins == expected_plugins
43,817
def weak_connect(sender, signal, connector, attr, idle=False, after=False): """ Function to connect some GObject with weak callback """ wc = WeakCallback(connector, attr, idle) if after: wc.gobject_token = sender.connect_after(signal, wc) else: wc.gobject_token = sender.conn...
43,818
def load_user(id): """ Provides login_manager with a method to load a user """ return User.get_by_id(int(id))
43,819
def _compute_min_dfc(fnrs, fprs, thresholds, p_target, c_miss, c_fa): """ Computes the minimum of the detection cost function. The comments refer to equations in Section 3 of the NIST 2016 Speaker Recognition Evaluation Plan. :param fnrs: the list of false negative rates :param fprs: the list of fa...
43,820
def send_message_to_slack(text, channel, token, username) : """Sends message to slack text - text to be send channel - channel name at slack. example: #general token - bot token for posting messages username - bot name """ #http post request to slack service to post message t...
43,821
def events_run(lock, qPasswordEvents): """ Process the user after approval """ logger.info("Worker password events starting") dbconnection = connect() while True: try: event = Event(qPasswordEvents.get()) except Exception as e: logger.error("Problem ...
43,822
def parse_rsync_url(location): """Parse a rsync-style URL.""" if ':' in location and '@' not in location: # SSH with no user@, zero or one leading slash. (host, path) = location.split(':', 1) user = None elif ':' in location: # SSH with user@host:foo. user_host, path ...
43,823
def ThetaE(tempk, pres, e): """Calculate Equivalent Potential Temperature for lowest model level (or surface) INPUTS: tempk: Temperature [K] pres: Pressure [Pa] e: Water vapour partial pressure [Pa] OUTPUTS: theta_e: equivalent potential temperature...
43,824
def generate_address_street(): """Concatenate number, street, and street sufix.""" number = random.randint(1, 9999) street = last_names[random.randint(0, len(last_names) - 1)] suffix = address_street_suffix[random.randint(0, len(address_street_suffix) - 1)] return "{0} {1} {2}".format(number, street...
43,825
def try_all_eliza_transformations(doc): """ Try to do eliza transformation for all the functions and add the transformed string to the responses list """ responses = [] question = ask_do_you_like_to(doc) if question: responses.append(question) question = rephrase_question(doc) ...
43,826
def get_jwt_subject(): """Returns a the subject from a valid access tokekn""" token = get_token_auth_header() payload = verify_decode_jwt(token) if "sub" not in payload: abort(401) return payload["sub"]
43,827
def shutdown(event): """Shuts down the remote server""" elements.REMOTE_SERVER.shutdown() disconnect(None)
43,828
def sleep_relative(delta): """Sleep for a period of time. :Parameters: - `delta`: The number of seconds to sleep. """ time.sleep(delta)
43,829
def api(function): """ Decorator of API functions that protects user code from unknown exceptions raised by gRPC or internal API errors. It will catch all exceptions and throw InternalError. :param function: function to be decorated :return: decorated function """ @functools.wraps(func...
43,830
def strfmt(): """ >>> name = 'Jon' >>> 'Hi, %s!' % name 'Hi, Jon!' >>> 'Hi, {0}!'.format(name) 'Hi, Jon!' >>> '%s' % 'hi' 'hi' >>> '%r' % 'hi' "'hi'" >>> str('hi') 'hi' >>> repr('hi') "'hi'" >>> '%d' % 100.0 '100' >>> '%03d' % 10 '010' >>> '%f' % 1 '1.000000' >>> '%.3f' % 1 '1.000' >>> 'Hi, %s!' % ('Jon',) 'Hi, ...
43,831
def mock_signal_receiver(signal, wraps=None, **kwargs): """ Taken from mock_django as importing mock_django created issues with Django 1.9+ Temporarily attaches a receiver to the provided ``signal`` within the scope of the context manager. The mocked receiver is returned as the ``as`` target o...
43,832
def download_google_drive_file(service, blob, destination_file_name=None): """ Download a selected file from Google Drive to local storage in the current working directory. """ local_path = os.path.normpath(f'{os.getcwd()}/{destination_file_name}') name = blob['name'] path = local_path.rspli...
43,833
def get_annotations(template): """ This utility prints all the annotations in the provided template. template: A path to the template that you would like to get annotations for. Example usage from the base directory: python ./bin/get_annotations.py dear_petition/static/templates/AOC-CR-287.pdf ...
43,834
def is_valid_cover(cover_metadata): """Fetch all sizes of cover from url and evaluate if they are valid.""" syndetics_urls = build_syndetic_cover_urls(cover_metadata) if syndetics_urls is None: return False try: for size in ["small", "medium", "large"]: resp = urllib.request...
43,835
def setup_go_func(func, arg_types=None, res_type=None): """ Set up Go function, so it know what types it should take and return. :param func: Specify Go function from library. :param arg_types: List containing file types that function is taking. Default: None. :param res_type: File type that functio...
43,836
def retire(*list_of_channelEnds): """ retire(C1, [C2, .. , CN]) Retire channel ends When a channel end is retired, the channel is signaled that a channel end has now left the channel. When the set of all reading or writing channel ends is set to none, then the channel enters a retired state wherea...
43,837
def compress_cubic(G): """Calculate the matricized cubic operator that operates on the compact cubic Kronecker product. Parameters ---------- G : (r,r**3) ndarray The matricized cubic tensor that operates on the full cubic Kronecker product. This should be a symmetric operator in th...
43,838
def xonly_pubkey_tweak_add( xonly_pubkey: Secp256k1XonlyPubkey, tweak32: bytes ) -> Secp256k1Pubkey: """ Tweak an x-only public key by adding the generator multiplied with tweak32 to it. Note that the resulting point can not in general be represented by an x-only pubkey because it may have an o...
43,839
def get_organisms_df(url: Optional[str] = None) -> pd.DataFrame: """Convert tab separated txt files to pandas Dataframe. :param url: url from KEGG tab separated file :return: dataframe of the file :rtype: pandas.DataFrame """ df = pd.read_csv( url or ensure_path(MODULE_NAME, KEGG_ORGANI...
43,840
def plot_histogram(): """ plot entropy histogram """ save = True fig = plt.figure(figsize=(8, 5)) for count, name in enumerate(names): plot_label, shade, ls, _ = get_label_by_language(name) plt.hist( entropy_dict["mean_" + name], bins=200, ...
43,841
def positive_int(val): """ ArgumentParse positive int check """ try: ival = int(val) assert ival > 0 return ival except (ValueError, AssertionError): raise argparse.ArgumentTypeError("'%s' is not a valid positive int" % val)
43,842
def split(dataset: Dataset, count: int, shuffle=False): """Datasetを指定個数に分割する。""" dataset_size = len(dataset) sub_size = dataset_size // count assert sub_size > 0 indices = np.arange(dataset_size) if shuffle: random.shuffle(indices) return [ dataset.slice(indices[o : o + sub_s...
43,843
def init(dispatcher: Dispatcher): """Provide handlers initialization.""" dispatcher.add_handler(CommandHandler('menu', menu)) dispatcher.add_handler(CallbackQueryHandler(callback))
43,844
def test__basic_model__init_on_access_flag(): """ Example: on_access flag is used to autocreate value for field using its type. For custom constructors use default param with provided factory method """ from dictmodel import DictModel, DictField class MyModel(DictModel): int_field: int ...
43,845
def lex(source_text): """ Tokenizes a Python source text. source_text: Assumes bytes already decoded per any encoding declaration. """ indent_stack = [('', 0)] # text, value char_pos = 0 for logical_line in logical_lines(source_text): num_tokens = len(logical_line) ...
43,846
def load_fixture(filename): """Load a fixture.""" return ( pathlib.Path(__file__) .parent.joinpath("fixtures", filename) .read_text(encoding="utf8") )
43,847
def natural_sort(l): """ From http://stackoverflow.com/a/4836734 """ def convert(text): return int(text) if text.isdigit() else text.lower() def alphanum_key(key): return [convert(c) for c in re.split('([0-9]+)', key)] return sorted(l, key=alphanum_key)
43,848
def is_verifier(cls): """Determine if a class is a Verifier that can be instantiated""" return inspect.isclass(cls) and issubclass(cls, Verifier) and \ not inspect.isabstract(cls)
43,849
def test_shell_cmd_inputspec_outputspec_2a(): """ customised input_spec and output_spec, output_spec uses input_spec fields in the requires filed """ cmd = ["touch", "newfile_tmp.txt"] my_input_spec = SpecInfo( name="Input", fields=[ ( "file1", ...
43,850
def get_config(): """Parse the aliases and configuration.""" if pyversion("3"): import configparser else: import ConfigParser as configparser config = configparser.ConfigParser() import os rcfiles = [ "/etc/weatherrc", "/etc/weather/weatherrc", os.path.expanduser("~/.weat...
43,851
def go_sequence(scf: Crazyflie, data: Dict): """ This is the go sequence. It commands the trajectory to start and runs the lighting. """ try: cf = scf.cf # type: Crazyflie commander = cf.high_level_commander # type: cflib.HighLevelCOmmander commander.start_trajectory( ...
43,852
def test_StrictCharField_null_no_cleaning(): """ No validation happens on Nones because of Django doing setattr(None) """ CharFieldModel(field=None)
43,853
def test_p_methods_1_value_dataframe_false_signficance(): """ Testing 1 values dataframe with false signficance. """ d = {"Test": ["test 1"], "p_value": [0.1]} df = pd.DataFrame(data=d) ad = {"Test": ["test 1"], "p_value": [0.1], "bonf_value": [0.05], "bonf_significant": [False], "bh_value": [0...
43,854
def get_framework_sample(project_id: str, framework: str, sample: str): """ Route for getting sample code for an ML framework for optimization of the projects model :param project_id: the project_id to get the available frameworks for :param framework: the ML framework to get available sample code ...
43,855
def merge(ref, gtfs_str, outdir=''): """Merges all stringtie output files """ stringtie_merge_outfile = os.path.join(outdir, 'stringtie_merge.gtf') print('Running Stringtie --merge') #cmd = ['./stringtie_merge.sh'] + [ref, stringtie_merge_outfile, gtfs_str] cmd = 'stringtie --merge -G {} -o {} ...
43,856
def get_bleu_score(references, hypothesis): """ Args: references: list(list(list(str))) # examples: list(examples) hypothesis: list(list(list(str))) # hypotheses: list(list(str)) """ hypothesis = [hyp[0][0] for hyp in hypothesis] return 100.0 * bleu_score.corpus_ble...
43,857
def GetLicenseTypesFromEbuild(ebuild_path): """Returns a list of license types from the ebuild file. This function does not always return the correct list, but it is faster than using portageq for not having to access chroot. It is intended to be used for tasks such as presubmission checks. Args: ebuild...
43,858
def load_json_link_index(out_dir, link): """check for an existing link archive in the given directory, and load+merge it into the given link dict """ link = { **parse_json_link_index(out_dir), **link, } link.update({ 'history': link.get('history') or {}, }) c...
43,859
def relative_phase(input_phase: float, output_phase: float) -> float: """ Calculates the relative phase between two phases. :param input_phase: the input phase. :param output_phase: the output phase. :return: the relative phase. """ phi = output_phase - input_phase if phi < -np.pi: ...
43,860
def get_process_state(*args): """ get_process_state() -> int Return the state of the currently debugged process. \sq{Type, Synchronous function, Notification, none (synchronous function)} @return: one of Debugged process states """ return _ida_dbg.get_process_state(*args)
43,861
def jaccard_similarity(x, y): """ Returns the Jaccard Similarity Coefficient (Jarccard Index) between two lists. From http://en.wikipedia.org/wiki/Jaccard_index: The Jaccard coefficient measures similarity between finite sample sets, as is defined as the size of the intersection divided by th...
43,862
def save_points_as_csv(**kwargs): """Saves a list of points into a CSV file. Args: - points - Nx(3x1 numpy array) list to be saved. - save_path - string path to save to. - delim - delimiter to use for the CSV format. """ points = kwargs.pop('points') save_path = kwargs.pop('save_path') ...
43,863
def align_address_to_size(address, align): """Align the address to the given size.""" return address + ((align - (address % align)) % align)
43,864
def tokenizer_word(text_string, keep_phrases=False): """ Tokenizer that tokenizes a string of text on spaces and new lines (regardless of however many of each.) :param text_string: Python string object to be tokenized. :param keep_phrases: Booalean will not split "quoted" text :return: Array of str...
43,865
def test_meta(ncbi, pdp1): """Test NCBI source metadata.""" response = ncbi.search('PDP1') assert response.source_meta_.data_license == 'custom' assert response.source_meta_.data_license_url == \ 'https://www.ncbi.nlm.nih.gov/home/about/policies/' assert datetime.strptime(response.source_met...
43,866
def getiso(): """Get iso level of sensor..""" global camera maxtint = 4 iso = float(camera.analog_gain) # get current ambient brightness 0..8 iso = (iso * maxtint) # adjust buy max tint level iso = (256 - (maxtint * 8)) + iso # clear - max tint + ISO tint return int(iso)
43,867
def _get_credentials(rse, endpoint): """ Pass an endpoint and return its credentials. :param endpoint: URL endpoint string. :param rse: RSE name. :returns: Dictionary of credentials. """ key = '%s_%s' % (rse, endpoint) result = REGION.get(key) if type(res...
43,868
def get_manual_comparisons(db: cosem_db.MongoCosemDB, cropno: Union[None, str, int, Sequence[Union[str, int]]] = None, mode: str = "across_setups") -> \ List[Union[Dict[str, str], Dict[str, Union[str, Sequence[str]]]]]: """ Read best configurations o...
43,869
def draw_circle(center_x:float, center_y:float, radius:float = 0.3, segments:int = 360, fill:bool=False): """ Returns an Object2D class that draws a circle Arguments: center_x : float : The x cord for the center of the circle. center_y : float : The y cord for the center of the circle. radius ...
43,870
def weighted_mean(values, weights): """Calculate the weighted mean. :param values: Array of values :type values: numpy.ndarray :param weights: Array of weights :type weights: numpy.ndarray :rtype: float """ weighted_mean = (values * weights).sum() / weights.sum() return weighted_me...
43,871
def shared_cluster(): """Create a shared cluster""" global _shared_cluster if _shared_cluster is None: cluster = PseudoHdfs4() atexit.register(cluster.stop) try: cluster.start() except Exception, ex: LOG.exception("Failed to fully bring up test cluster: %s" % (ex,)) # Fix config t...
43,872
def sync_database(gdax, db=None, interval=60): """ Updates a GdaxDatabase with pricing information on a regular basis. :param gdax: (gdax.api.Gdax) The api object :param db: (gdax.db.GdaxDatabase) The database to load updates into. :param interval: (int, default 60) The ...
43,873
def test_ner(params, extractor): """ :type params: dict :type trigger_extractor: nlplingo.nn.extractor.Extractor :type argument_extractor: nlplingo.nn.extractor.Extractor :type docs: list[nlplingo.text.text_theory.Document] """ docs = prepare_docs(params['data']['test']['filelist'], dict(), ...
43,874
def _format_args(args): """Format function arguments. Special case for a single parameter: ('hello',) is formatted as ('hello'). """ # use reprlib to limit the length of the output args_repr = reprlib.repr(args) if len(args) == 1 and args_repr.endswith(',)'): args_repr = args_repr[:-2] ...
43,875
def request(config, url_params={}): """Wrapper for sending GET to Facebook. Args: config: YAML object of config file. url_params: Dictionary of parameters to add to GET. Returns: HTTP response or error. """ host = HOST + f"/{config['user_id']}/" params = {"fields": "id,name", "...
43,876
def setup(hass, config): """Register a port mapping for Home Assistant via UPnP.""" import miniupnpc upnp = miniupnpc.UPnP() hass.data[DATA_UPNP] = upnp upnp.discoverdelay = 200 upnp.discover() try: upnp.selectigd() except Exception: _LOGGER.exception("Error when attemp...
43,877
def load_formatted_objects_json(fp): """A function to load formatted object data data. The function assumes the input json is of the form: [ { id: <number>, regions : [ { x: <number>, ...
43,878
def _event_last_observed(event: EventsV1Event) -> datetime.datetime: """ Returns the last time an event was observed """ if event.series: series_data: EventsV1EventSeries = event.series return series_data.last_observed_time if event.event_time: return event.event_time ...
43,879
def bytes(length): """Returns random bytes. .. seealso:: :func:`numpy.random.bytes` """ return numpy.bytes(length)
43,880
def test_input_int(): """test `input_int` function""" print(input_int('Enter an integer: ')) print(input_int('Enter an integer (default=0): ', default=0)) print(input_int('Enter an integer (>= 3): ', minimum=3)) print(input_int('Enter an integer (<= 9): ', maximum=9)) print(input_int( 'E...
43,881
def init_json(): """ This function init the JSON dict. Return : Dictionnary """ data_json = {} data_json['login'] = "" data_json['hash'] = "" data_json['duration'] = 0 data_json['nbFiles'] = 0 data_json['nbVirus'] = 0 data_json['nbErrors'] = 0 data_json['uuidUsb'] = "" ...
43,882
def load_skeds(year, teams): """ Loads the game schedules for teams for a given year. Defaults to all teams where updated = True, but can be passed in a selection of teams. >>> teams = College.objects.filter(id__in=(123,345,435)) >>> load_skeds(2009, teams) """ if not teams: teams = ...
43,883
def path_gen(env_id, seed: int, *wrappers, policy=None, preproc=None, collect=None, limit=None, env_kwargs=None, **config): """ :env_id: str the gym environment id :*wrappers: positional arguments for the wrapper :policy: a policy function that takes in policy(*obs[k] for k in obs_keys) ...
43,884
def django_popup_view_field_javascript(): """ Return HTML for django_popup_view_field JavaScript. Adjust url in settings. **Tag name**:: django_popup_view_field_javascript **Usage**:: {% django_popup_view_field_javascript %} """ temp = loader.get_template('django_popup_view...
43,885
def get_version(verbose=0): """ Extract version information from source code """ matcher = re.compile('[\t ]*#define[\t ]+OPENQL_VERSION_STRING[\t ]+"(.*)"') version = None with open(os.path.join(inc_dir, 'ql', 'version.h'), 'r') as f: for ln in f: m = matcher.match(ln) ...
43,886
def apply_filters(row): """Applies filters to the input data and returns transformed row.""" return {k: COLUMN_FILTERS.get(k, lambda x: x)(v) for k,v in row.items()}
43,887
def save_convergence_statistics( inputs, results, dmf=None, display=True, json_path=None, report_path=None ): """ """ s = Stats(inputs, results) if display: s.report() if report_path: with open(report_path, "w") as f: s.report(f) if json_path is not None: with...
43,888
def _backported_all_estimators(type_filter=None): """ Backported from scikit-learn 0.23.2: https://github.com/scikit-learn/scikit-learn/blob/0.23.2/sklearn/utils/__init__.py#L1146 Use this backported `all_estimators` in old versions of sklearn because: 1. An inferior version of `all_estimators` tha...
43,889
def test_coordinate_map_get_coordinates(coordinate_map): """ Test that the list of coordinates are returned that form a circle around the center point. """ expected = [(0, 3), (0, 4), (1, 4), (1, 5), (2, 5), (3, 5), (4, 5), (4, 4), (5, 4), (5, 3), (5, 2), (5, 1), (4, 1), (4, 0), (3, ...
43,890
def max_size(resize_info): """ リサイズ情報から結合先として必要な画像サイズを計算して返す :param resize_info: リサイズ情報 :return: width, height """ max_w, max_h = 0, 0 for name, info in resize_info.items(): pos = info['pos'] size = info['size'] max_w = max(max_w, pos[0] + size[0]) max_h = max...
43,891
def get_thru(path, specs=range(10), cameras='brz'): """Calculate the throughput in each camera for a single exposure. See https://github.com/desihub/desispec/blob/master/bin/desi_average_flux_calibration and DESI-6043. The result includes the instrument throughput as well as the fiber acceptance los...
43,892
def frame_csv(data_frame: DataFrame, file: str, **kwargs): """ store pandas.DataFrame to csv, with default options """ ensure_dir_exist(file) data_frame.to_csv(file, encoding='utf-8', **{**dict(header=True, index=False), **kwargs})
43,893
def lights(converted: str) -> None: """Controller for smart lights. Args: converted: Takes the voice recognized statement as argument. """ def light_switch(): """Says a message if the physical switch is toggled off.""" speaker.say("I guess your light switch is turned off sir! I...
43,894
def quicksort(lyst): """This is a quicksort """ def partition_helper(lyst, first, last): pivot = lyst[first] left = (first + 1) right = last done = False while not done: while left <= right and lyst[left] <= pivot: left += 1 whi...
43,895
def status_parameter_error(): """Returns the value returned by the function calls to the library in case of parameter error. """ r = call_c_function(petlink32_c.status_parameter_error, [{'name': 'return_value', 'type': 'int', 'value': None}]) return r.return_value
43,896
def df_to_dict(df: DataFrame) -> list[dict]: """DataFrame 转 dict""" # 拿到表头,转换为字典结构 head_list = list(df.columns) list_dic = [] for i in df.values: a_line = dict(zip(head_list, i)) list_dic.append(a_line) return list_dic
43,897
def parse_describeprocess(html_response): """Parse WPS DescribeProcess response. Parameters ---------- html_response : string xml document from a DescribeProcess WPS request. Returns ------- out : list of dict 'identifier' : ProcessDescription -> ows:Identifier 'inp...
43,898
def variational_implicit_step(system, dt, p, x, z, t): """ For Lagrangian functions of the form L(j) = 1/(2h^2) (x_{j+1} - x_j)^2 - 1/2 (V(x_j) + V(x_{j+1})) - 1/2 (F(z_j) + F(z_{j+1})) """ tnew = t + dt xnew = ( x + (dt - 0.5 * dt ** 2 * system.Fz(z, t)) * p - 0.5 * dt ** 2 * system.Vq...
43,899