content
stringlengths
22
815k
id
int64
0
4.91M
def test_coinbase_query_balances(function_scope_coinbase): """Test that coinbase balance query works fine for the happy path""" coinbase = function_scope_coinbase def mock_coinbase_accounts(url, timeout): # pylint: disable=unused-argument response = MockResponse( 200, """ {...
5,331,700
def netoversigt(projektnavn: str, **kwargs) -> None: """Opbyg netoversigt""" er_projekt_okay(projektnavn) fire.cli.print("Så kører vi") resultater = netanalyse(projektnavn) skriv_ark(projektnavn, resultater, "-netoversigt") singulære_punkter = tuple(sorted(resultater["Singulære"]["Punkt"])) ...
5,331,701
def print_text_samples(dataset: Dataset, encoder: Encoder, indices, export_file, att_heads=None, weights=None, title=''): """Print text samples of dataset specified by indices to export_file text file.""" export_txt = export_file + '.txt' txt_file = open(export_txt, 'a') if titl...
5,331,702
def test_dataset_traverse_dirs(test_output_dirs: OutputFolderForTests, center_crop_size: Optional[TupleInt3]) -> None: """ Test dataset loading when the dataset file only contains file name stems, not full paths. """ # Copy the existing test dataset to a new folder, two levels deep. Later will initializ...
5,331,703
def do_requests_tags(self, subcmd, opts, project): """${cmd_name}: Lists requests with hashtags This command will list requests for a given project together with the list of hashtags in the request diff, so that you can use this information to group them. ${cmd_usage} ${cmd_option_list} """ api = self...
5,331,704
def process_phase_boundary(fname): """ Processes the phase boundary file, computed mean and standard deviations """ from scipy.interpolate import interp1d singlets = [] chem_pot = [] temperatures = [] with h5.File(fname, 'r') as hfile: for name in hfile.keys(): grp = ...
5,331,705
def main(): """Entry point for the check_model script. Returns ------- :class:`int` An integer suitable for passing to :func:`sys.exit`. """ from sys import argv from argparse import ArgumentParser desc = """Check actual files against the data model for validity. """ parser ...
5,331,706
def blackman_window(shape, normalization=1): """ Create a 3d Blackman window based on shape. :param shape: tuple, shape of the 3d window :param normalization: value of the integral of the backman window :return: the 3d Blackman window """ nbz, nby, nbx = shape array_z = np.blackman(nbz)...
5,331,707
def list_workflows(): """List all workflows.""" count = 0 with service() as api: doc = api.workflows().list_workflows() for wf in doc[labels.WORKFLOW_LIST]: if count != 0: click.echo() count += 1 title = 'Workflow {}'.format(count) click.echo(title) ...
5,331,708
def asset_movements_from_dictlist(given_data, start_ts, end_ts): """ Gets a list of dict asset movements, most probably read from the json files and a time period. Returns it as a list of the AssetMovement tuples that are inside the time period """ returned_movements = list() for movement in given_d...
5,331,709
def update_work(work_id): """ Route permettant de modifier les données d'une collection :param work_id: ID de l'oeuvre récupérée depuis la page oeuvre :return: redirection ou template update-work.html :rtype: template """ if request.method == "GET": updateWork = Work.query.get(...
5,331,710
def login_view(request): """Login user view""" if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, username=email, password=password) if user is not None: login(request, user) ...
5,331,711
def set_seed(seed: int) -> RandomState: """ Method to set seed across runs to ensure reproducibility. It fixes seed for single-gpu machines. Args: seed (int): Seed to fix reproducibility. It should different for each run Returns: RandomState: fixed random state to initiali...
5,331,712
def test_double_q_learning(episodes=5): """ Performs Double Q Learning (Off-policy TD0 Control) on multiple environments (separately). """ method_name = 'Double Q Learning' # Taxi: tx_env = Taxi() tx_model = TD0ControlModel(tx_env, episodes, alpha=0.4) # episodes=10000 tx_q1_table, tx_...
5,331,713
async def help_test_setup_manual_entity_from_yaml(hass, platform, config): """Help to test setup from yaml through configuration entry.""" config_structure = {mqtt.DOMAIN: {platform: config}} await async_setup_component(hass, mqtt.DOMAIN, config_structure) # Mock config entry entry = MockConfigEntr...
5,331,714
def mse(im1, im2): """Compute the Mean Squared Error. Compute the Mean Squared Error between the two images, i.e. sum of the squared difference. Args: im1 (ndarray): First array. im2 (ndarray): Second array. Returns: float: Mean Squared Error. """ im1 = np.asarray(im1)...
5,331,715
def bert_text_preparation(text, tokenizer): """Preparing the input for BERT Takes a string argument and performs pre-processing like adding special tokens, tokenization, tokens to ids, and tokens to segment ids. All tokens are mapped to seg- ment id = 1. Args: text (str): T...
5,331,716
def test_elem_q021_elem_q021_v(mode, save_output, output_format): """ TEST :3.3.2 XML Representation of Element Declaration Schema Components : Document with default=Hello andDocument contains Hello World! """ assert_bindings( schema="msData/element/elemQ021.xsd", instance="msDat...
5,331,717
def possibly_equal(first, second): """Equality comparison that propagates uncertainty. It represents uncertainty using its own function object.""" if first is possibly_equal or second is possibly_equal: return possibly_equal #Propagate the possibilities return first == second
5,331,718
def main(): """ Main routine """ # command-line arguments opt = command_line_parser() # do main task do_task(opt)
5,331,719
def get_logs(): """ Endpoint used by Slack /logs command """ req = request.values logger.info(f'Log request received: {req}') if not can_view_logs(req['user_id']): logger.info(f"{req['user_name']} attempted to view logs and was denied") return make_response("You are not authoriz...
5,331,720
def vn_test(): """Test 'vn' population model""" _, param_file = tempfile.mkstemp(suffix='.json') _, db_file = tempfile.mkstemp(suffix='.hdf5') test_params = { "files": { "reference_file": mitty.tests.test_fasta_genome_file, "dbfile": db_file }, "rng": { "master_seed": 12345 }, ...
5,331,721
def list_volumes(vg): """List logical volumes paths for given volume group. :param vg: volume group name :returns: Return a logical volume list for given volume group : Data format example : ['volume-aaa', 'volume-bbb', 'volume-ccc'] """ out, err = utils.execute('lvs', '--no...
5,331,722
def question_aligned_passage_embedding(question_lstm_outs, document_embeddings, passage_aligned_embedding_dim): """create question aligned passage embedding. Arguments: - question_lstm_outs: The dimension of output of LSTM that process ...
5,331,723
def lm_loss_fn(forward_fn, vocab_size, params, rng, data, is_training=True): """Compute the loss on data wrt params.""" logits = forward_fn(params, rng, data, is_training) targets = hk.one_hot(data['target'], vocab_size) assert logits.shape == targets.shape mask = jnp.greater(data['obs'], 0) loss = -jnp.su...
5,331,724
def ParseArguments(): """Parse command line arguments, validate them, and return them. Returns: A dict of: {'args': argparse arguments, see below, 'cur_ip': the ip address of the target, as packed binary, 'cur_node_index': the current node index of the target, 'cur_node_name': the cu...
5,331,725
def chroms_from_build(build): """ Get list of chromosomes from a particular genome build Args: build str Returns: chrom_list list """ chroms = {'grch37': [str(i) for i in range(1, 23)], 'hg19': ['chr{}'.format(i) for i in range(1, 23)] ...
5,331,726
def get_ready_count_string(room: str) -> str: """Returns a string representing how many players in a room are ready. Args: room (str): The room code of the players. Returns: str: A string representing how many players in a room are ready in the format '[ready]/[not ready]'. """ pla...
5,331,727
def add_object_to_session(object, session): """Explicitly add object to the session.""" if session and object: session.add(object)
5,331,728
def switches(topology: 'Topology') -> List['Node']: """ @param topology: @return: """ return filter_nodes(topology, type=DeviceType.SWITCH)
5,331,729
def geometric_progression(init, ratio): """ Generate a geometric progression start form 'init' and multiplying 'ratio'. """ return _iterate(lambda x: x * ratio, init)
5,331,730
def resolve(marathon_lb_url): """Return the individual URLs for all available Marathon-LB instances given a single URL to a DNS-balanced Marathon-LB cluster. Marathon-LB typically uses DNS for load balancing between instances and so the address provided by the user may actually be multiple load-balance...
5,331,731
def save_data(data, filename, save_path): """Saves the dataset in a given file path""" if not os.path.exists(save_path): os.mkdir(save_path) np.save(os.path.join(save_path, filename), data)
5,331,732
def copy_masked(src, dst, srcval=None, srcmask=None, dstmask=None): """ Copies masked elements from the :samp:`src` array into the :samp:`dst` array. If the arrays are different layouts/shapes then the :samp:`src` array will be copied to an array of the same layout/shape as the :samp:`dst` array. By...
5,331,733
def _parse_bluetooth_info(data): """ """ # Combine the bytes as a char string and then strip off extra bytes. name = ''.join(chr(i) for i in data[:16]).partition('\0')[0] return BluetoothInfo(name, ''.join(chr(i) for i in data[16:28]), ''.join(chr(i)...
5,331,734
async def get_reverse_objects_topranked_for_lst(entities): """ get pairs that point to the given entity as the primary property primary properties are those with the highest rank per property """ # run the query res = await runQuerySingleKey(cacheReverseObjectTop, entities, """ SELECT ?ba...
5,331,735
def LU_razcep(A): """ Vrne razcep A kot ``[L\\U]`` """ # eliminacija for p, pivot_vrsta in enumerate(A[:-1]): for i, vrsta in enumerate(A[p + 1:]): if pivot_vrsta[p]: m = vrsta[p] / pivot_vrsta[p] vrsta[p:] = vrsta[p:] - pivot_vrsta[p:] * m ...
5,331,736
def jni_request_identifiers_for_type(field_type, field_reference_name, field_name, object_name="request"): """ Generates jni code that defines C variable corresponding to field of java object (dto or custom type). To be used in request message handlers. :param field_type: type of the field to be initial...
5,331,737
def _ValidateDuration(arg_internal_name, arg_value): """Validates an argument which should have a Duration value.""" try: if isinstance(arg_value, basestring): return TIMEOUT_PARSER(arg_value) elif isinstance(arg_value, int): return TIMEOUT_PARSER(str(arg_value)) except arg_parsers.ArgumentTyp...
5,331,738
def get_jaccard_dist1(y_true, y_pred, smooth=default_smooth): """Helper to get Jaccard distance (for loss functions). Note: This mirrors what others in the ML community have been using even for non-binary vectors.""" return 1 - get_jaccard_index1(y_true, y_pred, smooth)
5,331,739
def deduplicate_obi_codes(fname: Path) -> None: """ Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance. When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inserts the identifier.type code for http://terminology.hl7.org/CodeSystem/v2-0...
5,331,740
def fold_conv_bns(onnx_file: str) -> onnx.ModelProto: """ When a batch norm op is the only child operator of a conv op, this function will fold the batch norm into the conv and return the processed graph :param onnx_file: file path to ONNX model to process :return: A loaded ONNX model with BatchNor...
5,331,741
def numdays(year, month): """ numdays returns the number of days in the given month of the given year. Args: year month Returns: ndays: number of days in month """ NDAYS = list([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]) assert(year >= 0) assert(1 <=...
5,331,742
def normalise_diversity_year_df(y_div_df): """Normalises a dataframe with diversity information by year and parametre set""" yearly_results_norm = [] # For each possible diversity metric it pivots over parametre sets # and calculates the zscore for the series for x in set(y_div_df["diversity_metric...
5,331,743
def usage(parser): """Help""" parser.print_help() print("Example:") print("\t" + sys.argv[0] + " --bridgeip 192.168.1.23 --lights Light1,Light2") sys.exit()
5,331,744
def test_contains_valid_chars(): """ Test that _contains_valid_chars works """ test_names = { "metric_name tag-key.str": False, u"&*)": False, "abc.abc-abc/abc_abc": True, " ": False, u'日本語.abc': True, u'abc.日本語': True } for test_string, expected_n...
5,331,745
def allowed_file(filename): """Does filename have the right extension?""" return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
5,331,746
def validate_fetch_params(max_fetch: int, max_events_fetch: int, fetch_events: bool, first_fetch: str, event_types: List[str]) -> None: """ Validates the parameters for fetch incident command. Args: max_fetch: (int): The maximum number of incidents for one fetch. m...
5,331,747
def render( template: str, context: Dict, serializer: Optional[CallableType[[Any], str]] = None, partials: Optional[Dict] = None, missing_variable_handler: Optional[CallableType[[str, str], str]] = None, missing_partial_handler: Optional[CallableType[[str, str], str]] = None, cache_tokens: b...
5,331,748
def preprocess_observations(input_observation, prev_processed_observation, input_dimensions): """ convert the 210x160x3 uint8 frame into a 6400 float vector """ processed_observation = input_observation[35:195] # crop processed_observation = downsample(processed_observation) processed_observation = remo...
5,331,749
def expand_configuration(configuration): """Fill up backups with defaults.""" for backup in configuration['backups']: for field in _FIELDS: if field not in backup or backup[field] is None: if field not in configuration: backup[field] = None ...
5,331,750
def create_feature_extractor(input_shape: tuple, dropout:float=0.3, kernel_size:tuple=(3,3,3)) -> tf.keras.Sequential: """ Create feature extracting model :param input_shape: shape of input Z, X, Y, channels :return: feature extracting model """ model = Sequential() model.add(Conv3D(filters...
5,331,751
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Set up the component.""" hass.data.setdefault(DOMAIN, {}) async_add_defaults(hass, config_entry) router = KeeneticRouter(hass, config_entry) await router.async_setup() undo_listener = config_entry.add_updat...
5,331,752
def log_set_level(client, level): """Set log level. Args: level: log level we want to set. (for example "DEBUG") """ params = {'level': level} return client.call('log_set_level', params)
5,331,753
def exec_local_command(cmd): """ Executes a command for the local bash shell and return stdout as a string. Raise CalledProcessError in case of non-zero return code. Args: cmd: command as a string Return: STDOUT """ proc = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess...
5,331,754
def OGH(p0, p1, v0, v1, t0, t1, t): """Optimized geometric Hermite curve.""" s = (t-t0)/(t1-t0) a0 = (6*np.dot((p1-p0).T,v0)*np.dot(v1.T,v1) - 3*np.dot((p1-p0).T,v1)*np.dot(v0.T,v1)) / ((4*np.dot(v0.T,v0)*np.dot(v1.T,v1) - np.dot(v0.T,v1)*np.dot(v0.T,v1))*(t1-t0)) a1 = (3*np.dot((p1-p0).T,v0)*np.dot(v0....
5,331,755
def permutation_test(v1, v2, iter=1000): """ Conduct Permutation test Parameters ---------- v1 : array Vector 1. v2 : array Vector 2. iter : int. Default is 1000. The times for iteration. Returns ------- p : float The permutation test result, p-...
5,331,756
def registered_paths(): """Return paths added via registration ..note:: This returns a copy of the registered paths and can therefore not be modified directly. """ return list(_registered_paths)
5,331,757
def second_pass_organizing_files(qc_path): """Second Pass at organizing qc txt files. Parameters ---------- qc_path : string existing path of qc_html directory Returns ------- None Notes ----- Combines files with same strategy. combines files for derivative falff ,...
5,331,758
def nms_dynamic(ctx, g, boxes: Tensor, scores: Tensor, max_output_boxes_per_class: int, iou_threshold: float, score_threshold: float): """Rewrite symbolic function for default backend. Support max_output_boxes_per_class, iou_threshold, score_threshold of constant Tensor, whi...
5,331,759
def api_timestamp_to_datetime(api_dt: Union[str, dict]): """Convertes the datetime string returned by the API to python datetime object""" """ Somehow this string is formatted with 7 digits for 'microsecond' resolution, so crop the last digit (and trailing Z) The cropped string will be written into api...
5,331,760
def calc_mutation(offsprings: List[List[List[int]]], mut_rate: float, genes_num: int) -> List[List[List[int]]]: """ Not necessary, however when provided and returns value other than None, the simulator is going to use this one instead of the given ones by default, if you are not intending to use it leave i...
5,331,761
def compute_targets(ex_rois, gt_rois, weights=(1.0, 1.0, 1.0, 1.0)): """Compute bounding-box regression targets for an image.""" return box_utils.bbox_transform_inv(ex_rois, gt_rois, weights).astype( np.float32, copy=False )
5,331,762
def dmp_gf_sqf_list(f, u, K, all=False): """Compute square-free decomposition of ``f`` in ``GF(p)[X]``. """ raise NotImplementedError('multivariate polynomials over finite fields')
5,331,763
def _args_filter(args): """ zenith db api only accept list of tuple arguments for bind execute, that is ungainly so we should make all kind of arguments to list of tuple arguments """ if isinstance(args, (GeneratorType, )): args = list(args) if len(args) <= 0: return [] if ...
5,331,764
def test_in_range_above(): """One page above current should be displayed.""" test_page = 5 current_page = 4 result = within_filter(test_page, current_page) assert result
5,331,765
def getAreaDF(spark): """ Returns a Spark DF containing the BLOCK geocodes and the Land and Water area columns Parameters ========== spark : SparkSession Returns ======= a Spark DF Notes ===== - Converts the AREALAND and AREAWATER columns from square meters to square miles...
5,331,766
def test_SteepCBPCTL(): """Test STEEP effect on a circumbinary planet (Fleming et al., 2018, ApJ, 858, 86), but with the CTL model (Graham et al., in prep).""" # Remove old log file subprocess.run(['rm', 'STEEP_CTL.log'], cwd=cwd) # Run vplanet subprocess.run(['vplanet', 'vpl.in', '-q'], cwd=cwd...
5,331,767
def run_command(command, filename=None, repeat=1, silent=False): """ Run `command` with `filename` positional argument in the directory of the `filename`. If `filename` is not given, run only the command. """ if filename is not None: fdir = os.path.dirname(os.path.abspath(filename)) ...
5,331,768
def how_many(): """Check current number of issues waiting in SQS.""" if not is_request_valid(request): abort(400) lapdog_instance = Lapdog() lapdog_instance.how_many() return jsonify( response_type="in_channel", text="There are 4 issues waiting to be handled", )
5,331,769
def read_sbd(filepath): """Reads an .sbd file containing spectra in either profile or centroid mode Returns: list:List of spectra """ with open(filepath, 'rb') as in_file: header = struct.unpack("<BQB", in_file.read(10)) meta_size = header[1] * 20 # sizeof(QLfHH)...
5,331,770
def dct2(X, blksize): """Calculate DCT transform of a 2D array, X In order for this work, we have to split X into blksize chunks""" dctm = dct_mat(blksize) #try: #blks = [sp.vsplit(x, X.shape[1]/blksize) for x in sp.hsplit(X, X.shape[0]/blksize)] #except: # print "Some error occurred" ...
5,331,771
def print_filtering(dataset, filter_vec, threshold, meta_name): """Function to select the filtering_names(names of those batches or cell types with less proportion of cells than threshold), and print an informative table with: batches/cell types, absolute_n_cells, relative_n_cells, Exluded or not. """ ...
5,331,772
def attempt_input_load(input_path): """Attempts to load the file at the provided path and return it as an array of lines. If the file does not exist we will exit the program since nothing useful can be done.""" if not os.path.isfile(input_path): print("Input file does not exist: %s" % input_path...
5,331,773
def get_chunk_tags(chunks: Dict, attrs: str): """ Get tags for :param chunks: :param attrs: :return: """ tags = [] for chunk in chunks: resource_type = chunk['resource_type'] original_url = chunk['url'] parse_result = urlparse(original_url) path = parse_r...
5,331,774
def __discount_PF(i, n): """ Present worth factor Factor: (P/F, i, N) Formula: P = F(1+i)^N :param i: :param n: :return: Cash Flow: F | | -------------- | P """ return (1 + i) ** (-n)
5,331,775
def update(upd_time): """ Send the notification to the users """ now = datetime.datetime.now() curr_time = {now.time().hour, now.time().minute} # Supper or lunch have_to_send = "" # Error message err_msg = "Si è verificato un *errore* all'interno di @UnicamEatBot, contro...
5,331,776
def step_impl(context): """ :type context: behave.runner.Context """ logger.info(f"The car has a max speed of {context.formule1.max_speed}")
5,331,777
def pw2dense(pw, maxd): """Make a pairwise distance matrix dense assuming -1 is used to encode D = 0""" pw = np.asarray(pw.todense()) pw[pw == 0] = maxd + 1 # pw[np.diag_indices_from(pw)] = 0 pw[pw == -1] = 0 return pw
5,331,778
def run_simulation(sim: td.Simulation) -> Awaitable[td.Simulation]: """Returns a simulation with simulation results Only submits simulation if results not found locally or remotely. First tries to load simulation results from disk. Then it tries to load them from the server storage. Finally, only ...
5,331,779
def calculate_ucm_friction_factor_annular( ctx: "void*", ff_wG: "double*", ff_wL: "double*", ff_i: "double*" ) -> "int": """ **c++ signature** : ``HOOK_CALCULATE_UCM_FRICTION_FACTOR_ANNULAR(void* ctx, double* ff_wG, double* ff_wL, double* ff_i)`` Internal unit cell model `hook` to calculate the wal...
5,331,780
def get_cursor_position(fd=1): """Gets the current cursor position as an (x, y) tuple.""" csbi = get_console_screen_buffer_info(fd=fd) coord = csbi.dwCursorPosition return (coord.X, coord.Y)
5,331,781
def _held_karp(dists: np.ndarray) -> Tuple[float, np.ndarray]: """ Held-Karp algorithm solves the Traveling Salesman Problem. This algorithm uses dynamic programming with memoization. Parameters ---------- dists Distance matrix. Returns ------- The cost and the path. "...
5,331,782
def process_log_data(spark, input_data, output_data): """Process the event log data storing users, time and songplay dimension tables. Arguments: spark -- SparkSession object input_data -- path to the raw event log data files output_data -- path to write out the resulting dimesion tables...
5,331,783
def import_from_pickle(manager, folder, files, database): """Import folder with pickles into database. :param pathme_viewer.manager.Manager manager: PathMe manager :param str folder: folder to be imported :param iter[str] files: iterator with file names :param str database: resource name """ ...
5,331,784
def dl_files(go_directory): """function to download latest ontologies and associations files from geneontology.org specify the directory to download the files to""" # change to go directory os.chdir(go_directory) # Get http://geneontology.org/ontology/go-basic.obo obo_fname = download_go_basic...
5,331,785
def NS(s,o): """ Nash Sutcliffe efficiency coefficient Adapated to use in alarconpy by Albenis Pérez Alarcón contact: apalarcon1991@gmail.com Parameters -------------------------- input: s: simulated o: observed output: ns: Nash Sutcliffe efficient ...
5,331,786
def UTArgs(v): """ tag UTArgs """ tag = SyntaxTag.TagUTArgs() tag.AddV(v) return tag
5,331,787
def rules_check(rulesengine_db, filename, output_path, query_start, query_end): """check if any rules match""" from src.praxxis.sqlite import sqlite_rulesengine rulesets = sqlite_rulesengine.get_active_rulesets(rulesengine_db, query_start, query_end) rulesmatch = [] hit = set() predictions = [...
5,331,788
def delete_shelf(shelf_name): """ Deletes shelf with given name :param shelf_name: str """ raise NotImplementedError()
5,331,789
def query( params, remote, query, level, query_res, since, before, local, out_format, assume_yes, no_progress, ): """Perform a query against a network node""" if level is not None: level = level.upper() for q_lvl in QueryLevel: if q_lvl.nam...
5,331,790
def shortstr(s,max_len=144,replace={'\n':';'}): """ Obtain a shorter string """ s = str(s) for k,v in replace.items(): s = s.replace(k,v) if max_len>0 and len(s) > max_len: s = s[:max_len-4]+' ...' return s
5,331,791
def update_gms_stats_collection( self, application: bool = None, dns: bool = None, drc: bool = None, drops: bool = None, dscp: bool = None, flow: bool = None, interface: bool = None, jitter: bool = None, port: bool = None, shaper: bool = None, top_talkers: bool = None, ...
5,331,792
def test_process_fields(cbcsdk_mock): """Testing AsyncProcessQuery.set_fields().""" api = cbcsdk_mock.api guid = 'WNEXFKQ7-0002b226-000015bd-00000000-1d6225bbba74c00' # use the update methods process = api.select(Process).where("event_type:modload").add_criteria("device_id", [1234]).add_exclusions("...
5,331,793
def _get_nearby_factories(latitude, longitude, radius): """Return nearby factories based on position and search range.""" # ref: https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula distance = 6371 * ACos( Cos(Radians(latitude)) * Cos(Radians("lat")) * Cos(Radian...
5,331,794
def add_register(request): """ 处理注册提交的数据,保存到数据库 :param request: :return: """ form = forms.RegisterForm(request.POST) if form.is_valid(): data = form.cleaned_data #清洗数据 data.pop("re_password") data['password'] = hash_pwd.has_password(data.get('password')) #添加必要数据 data['is_active'] = 1 #格式化储存 model...
5,331,795
def confidence_interval(data, alpha=0.1): """ Calculate the confidence interval for each column in a pandas dataframe. @param data: A pandas dataframe with one or several columns. @param alpha: The confidence level, by default the 90% confidence interval is calculated. @return: A series where each e...
5,331,796
def test_datasets_str(): """Test that datasets are printed as expected.""" url = ('http://thredds.ucar.edu/thredds/catalog/grib/NCEP/NAM/' 'CONUS_20km/noaaport/catalog.xml') cat = TDSCatalog(url) assert str(cat.datasets) == ("['Full Collection (Reference / Forecast Time) Dataset', " ...
5,331,797
def RunInTransactionOptions(options, function, *args, **kwargs): """Runs a function inside a datastore transaction. Runs the user-provided function inside a full-featured, ACID datastore transaction. Every Put, Get, and Delete call in the function is made within the transaction. All entities involved in these ...
5,331,798
def notify(message, key, target_object=None, url=None, filter_exclude={}): """ Notify subscribing users of a new event. Key can be any kind of string, just make sure to reuse it where applicable! Object_id is some identifier of an object, for instance if a user subscribes to a specific comment thread, ...
5,331,799