content
stringlengths
22
815k
id
int64
0
4.91M
def get_variable_field_type(variable_name, field_name, error_prefix=''): """ 获取某个变量的某个字段的类型 """ schema = get_variable_schema(variable_name) result_type = schema.get(field_name) if not result_type: raise RuntimeError(utf8(error_prefix) + '变量(%s)不包含字段(%s)' % (utf8(variable_name), utf8(fie...
14,400
def test(input_test_data): """ Run test batches on trained network :return: Test accuracy [0-1] """ print('--- Execute testing ---') one_hot_label = np.zeros(10, dtype=np.uint8) correct_n = 0 total_n = 0 for batch_id, (mini_batch, label) in enumerate(input_test_data): for s...
14,401
def test(net, example): """ Args: net (FlowNet): Instance of networks.flownet.FlowNet model, only to be used for pre-processing. example (dict): Un-processed example. Returns: good (list, DMatch): List of good SIFT matches. """ net.eval() example = net.preprocess(example...
14,402
def init(skill): """ Initializes any data on the parent skill if necessary """ for component in skill.components: if component.defines('init'): component.init(skill)
14,403
def get_hashers(): """ 从settings.py中动态导入一连串hashers对象 Read list of hashers from app.settings.py """ hashers = [] # 导入报名 for hasher_path in current_app.config.get('PASSWORD_HASHERS'): hasher_cls = import_string(hasher_path) hasher = hasher_cls() hashers.append(hashers) ...
14,404
def str2range(s): """parse a samtools/tabix type region specification 'chr:start-stop' or 'chr:start..stop'""" chrom = None start = 1 stop = None tmp = s.split(':') chrom = tmp[0] if len(tmp)>1: if '-' in tmp[1]: tmp = tmp[1].split('-') else: tmp = tmp...
14,405
def check_missing_dep(): """ Check for missing dependencies """ global MISSING_PACKAGES, INSTALLED_PACKAGES, ENABLE_CUDA if ENABLE_CUDA and IS_MACOS: REQUIRED_PACKAGES.extend(MACOS_REQUIRED_PACKAGES) MISSING_PACKAGES = [] for pkg in REQUIRED_PACKAGES: key = pkg.split("==")[0] ...
14,406
def test_get_current_price(create_exchange): """ Test that we're able to get the current price and that it's not 0""" assert create_exchange.has_next_observation == True assert len(create_exchange.data_frame) != 0 # This current_price should not be 0 and should not raise and exception. assert create...
14,407
def turn_read_content(path, labelIdx, dataIdx): """ sentences: (dialog_num, turn_num, nbest_num, sentence_len) scores: (dialog_num, turn_num, nbest_num) acts: (dialog_num, turn_num, machine_act_len) labels: (dialog_num, turn_num, [label_dim]) """ sentences, scores, acts, labels = [], [], [],...
14,408
def index_page() -> dict: """Get data for Index page , interfaces, dp neighbors, arps, and hsrp""" interfaces = GetThisDataFromDevice.get_interfaces(request.json.get('ip'), request.json.get('port'), request.json.get('username'), request.json.get('password')) neighbors = GetThisDataFromDevice.get_dp_neighbo...
14,409
async def client_close(self: "dragonchain_client.Client") -> None: """ Close any aiohttp sessions associated with an instantiated async client """ await self.request.session.close()
14,410
def reverse_int_bits(n: int, n_bits: int = 10) -> int: """Reverses the bits of *n*, considering it is padded by *n_bits* first""" return int(format(n, '0' + str(n_bits) + 'b')[::-1], 2)
14,411
def generate_following_list(api): """ Generate Complete following list of Authenticated User """ print '------- Following ---------' for friend in tweepy.Cursor(api.followers).items(): print friend.screen_name
14,412
def get_conn(): """ 获取 :return: """ for name in GENERATOR_MAP: print(name) if not hasattr(g, name): setattr(g, name + '_cookies', eval('CookiesRedisClient' + '(name="' + name + '")')) setattr(g, name + '_account', eval('AccountRedisClient' + '(name="' + name +...
14,413
def get_rule_satisfaction_matrix(x, y, rules): """ Returns a matrix that shows which instances satisfy which rules Each column of the returned matrix corresponds to a rules and each row to an instance. If an instance satisfies a rule, the corresponding value will be 1, else 0. :param x: np.ndarray ...
14,414
def refactor(df, frequency = '1W'): """Refactor/rebin the data to a lower cadence The data is regrouped using pd.Grouper """ low = df.low.groupby(pd.Grouper(freq=frequency)).min() high = df.high.groupby(pd.Grouper(freq=frequency)).max() close = df.close.groupby(pd.Grouper(freq=fr...
14,415
def pendulum_derivatives(theta, omega, g=9.8, l=1): """ \dot{\theta} = \omega \dot{\omega} = -\frac{g \sin\theta}{l} :param theta: angel of the pendulum :param omega: angular velocity of the pendulum :param g: gravitational acceleration :param l: length of the pendulum :return: derivativ...
14,416
def test_nested(): """Validate result of the nested class resolving.""" # pylint: disable=no-member assert issubclass(NestedSchema, graphene.ObjectType) assert isinstance(NestedSchema.name, graphene.String) assert isinstance(NestedSchema.leaf, graphene.Field) assert str(NestedSchema.leaf.type) =...
14,417
def get_sql_filtered( source_query, python_types, db_conf_file_name, filters=[]): """ Return list of DBAPI tuples (& prefixed header row) filtered by value Keyword Parameters: source_query -- String, representing SQL definition of requested datasource python_types -- JSON encoded string representi...
14,418
def task_edit(request, pk=None): """ """ return edit(request, form_model=TaskForm, model=Task, pk=pk)
14,419
def get_intersect(pre_df, post_df, args, aoi=None): """ Computes intersection of two dataframes and reduces extent by an optional defined AOI. :param pre_df: dataframe of raster footprints :param post_df: dataframe of raster footprints :param args: arguments object :param aoi: AOI dataframe ...
14,420
def _gradient(P, T, N, A): """ Creates the gradient operator, starting from the point set P, the topology tensor T, the normal tensor N and the triangle area tensor A Parameters ---------- P : Tensor the (N,3,) point set tensor T : LongTensor the (3,M,) topology tensor N...
14,421
def breast_tissue_diagnostic_black_pen() -> Tuple[ openslide.OpenSlide, str ]: # pragma: no cover """breast_tissue_diagnostic_black_pen() -> Tuple[openslide.OpenSlide, str] Breast tissue, TCGA-BRCA dataset. Diagnostic slide with black pen marks. This image is available here https://portal.gdc.can...
14,422
def test_polyfit(): """Unit test for the polyfit function""" stations = build_station_list() # Update the water levels for all of them update_water_levels(stations) # Find which are the 5 stations with highest relative level high_risk_stations = flood.stations_highest_rel_level(stations,1) ...
14,423
def generic_plot(plot_title, xlims, ylims, xlabel, ylabel, addons, plot_fontsize=18, plot_figsize=(8,6), plot_dpi=400): """ Wrapper function for plot formatting. """ # Configurations. rcParams['font.family'] = 'serif' rcParams['font.serif'] = ['Charter'] pp_fig = plt.figure(figsize=tuple(plot_figsize)) plt.gca()...
14,424
def test_print_flashy(mock_shutil, mock_print_length, scenario, capsys): """Test print_flashy.""" mock_shutil.return_value = (scenario["mock"], 1) mock_print_length.return_value = scenario["message_length"] expected = ( f"{'>'*scenario['left']} {'a' * scenario['message_length']} " f"{'<'...
14,425
def fitcand(t,fm,p,full=False): """ Perform a non-linear fit to a putative transit. Parameters ---------- t : time fm : flux p : trial parameter (dictionary) full : Retrun tdt and fdt Returns ------- res : result dictionary. """ dtL = LDTwrap(t,fm,p) dt ...
14,426
def parse_prompt(browser): """ User enters instructions at a prompt """ i = 0 while True: line = input('webscrape> ') if line in ['break', 'exit', 'quit']: break i += 1 line = sanitize_line_input(i, line) if line is None: continue ...
14,427
def cbar_for_line_plot(axis, num_steps, discrete_ticks=True, **kwargs): """ Adds a colorbar next to a line plot axis Parameters ---------- axis : matplotlib.axes.Axes Axis with multiple line objects num_steps : uint Number of steps in the colorbar discrete_ticks : (optional)...
14,428
def get_config_based_on_config_file(path: str) -> Union[Config, None]: """ load config and check if section exist or not :param path: path to config file :return: None if section [laziest] not exist in Config object updated with params from section if exist """ cfg = load_config(path) if...
14,429
def main(): """ BST 4 2 6 1 3 5 7 """ tree = BSTwithNodes() l1 = [4, 2, 6, 1, 3, 7, 5] for i in l1: tree.insert(i) print(tree.root) print(tree.root.right) print(tree.root.right.left) print(tree.root.right.right) print(tree.root.left) print(tr...
14,430
def threadpooled( # noqa: F811 func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None, *, loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None, loop_getter_need_context: bool = False, ) -...
14,431
def prepare_solar_dps(dt, source): """ This function will prepare the day part separators for solar sources. To handle this, it will either estimate it from a diurnal pattern if provided or it will use the average hour for which there is first power generated over the past two weeks and similarly fo...
14,432
def koven_temp_atten(soiltemp, airtemp): """Define thermal attenuation ratios as in Koven et al 2013.""" # read in list of observed lats and lons from Koven paper ex_points = permafrost_koven_sites.site_points # make amplitudes airtemp_ampl = make_monthly_amp(airtemp) soiltemp_ampl = make_month...
14,433
def clipup(step_size: float, momentum: float = 0.9, max_speed: float = 0.15, fix_gradient_size: bool = True): """Construct optimizer triple for ClipUp.""" step_size = optimizers.make_schedule(step_size) def init(x0): v0 = jnp.zeros_like(x0) return x0, v0 ...
14,434
def ramsey_echo_sequence(length, target): """ Generate a gate sequence to measure dephasing time in a two-qubit chip including a flip in the middle. This echo reduce effects detrimental to the dephasing measurement. Parameters ---------- length : int Number of Identity gates. Should be ...
14,435
def gauss_elimination(matrix) -> np.array: """ This function compute Gauss elimination process :param matrix: generic matrix :return: matrix after the Gauss elimination """ import sympy return np.array(sympy.Matrix(matrix).rref()[0])
14,436
def prune(value, is_removable_function=is_removable): """ Deletes ``None`` and empty lists and dicts, recursively. """ if isinstance(value, list): for i, v in enumerate(value): if is_removable_function(value, i, v): del value[i] else: prun...
14,437
def test_clone_layer_uses_previous_config() -> None: """Tests that clone_layer uses previous layer configuration.""" units = 10 activation = "relu" use_bias = False layer = Dense(units, activation=activation, use_bias=use_bias) cloned = clone_layer(layer) assert cloned.units == units ass...
14,438
def submissions_score_set_handler(sender, **kwargs): # pylint: disable=unused-argument """ Consume the score_set signal defined in the Submissions API, and convert it to a PROBLEM_WEIGHTED_SCORE_CHANGED signal defined in this module. Converts the unicode keys for user, course and item into the standard...
14,439
def get_country_gateway_url(country): """TODO: Keep config in environment or file""" return { 'countrya': environ.get('first_gateway_url'), 'countryb': environ.get('first_gateway_url'), 'countryc': environ.get('second_gateway_url'), }.get(country.lower())
14,440
def n_permutations(n, r=None): """Number of permutations (unique by position) :param n: population length :param r: sample length :return: int """ if r is None: r = n if n < 0 or r < 0: raise ValueError("n and r must be positive") if n == 0 or r > n: return 0 ...
14,441
def parse_s3_event(event): """Decode the S3 `event` message generated by message write operations. See S3 docs: https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html See also the callers of this function. Returns bucket_name, ipppssoot """ log.verbose("S3 Ev...
14,442
def clip_2d_liang_barsky(xmin, ymin, xmax, ymax, x0, y0, x1, y1): """Clips the two-dimensional line segment by the algorithm of Liang and Barsky. Adapted from James D. Foley, ed., __Computer Graphics: Principles and Practice__ (Reading, Mass. [u.a.]: Addison-wesley, 1998), 122. Parameters --------...
14,443
def _(pattern, key_path: str, case_ignored=False) -> bool: """Called when the concerned Key is defined as a re.Pattern, and case_ignored flag is neglected.""" return re.fullmatch(pattern, key_path) is not None
14,444
def test_export(client, mock_env): # pylint: disable=unused-argument # mock_env is a fixture and creates a false positive for pylint """Test export message response""" with open('tests/mocks/export_submissions.json', 'r') as file_obj: mock_responses = json.load(file_obj) assert mock_respon...
14,445
def rotate(angle): """Make the robot rotate for a certain angle.""" move(angle, pi / 4, True)
14,446
def sophos_firewall_web_filter_update_command(client: Client, params: dict) -> CommandResults: """Update an existing object Args: client (Client): Sophos XG Firewall Client params (dict): params to update the object with Returns: CommandResults: Command results object """ r...
14,447
def transition_with_random_block(block_randomizer): """ Build a block transition with randomized data. Provide optional sub-transitions to advance some number of epochs or slots before applying the random block. """ return { "block_producer": block_randomizer, }
14,448
def vmobj_to_list(o): """Converts TVM objects returned by VM execution to Python List. Parameters ---------- o : Obj VM Object as output from VM runtime executor. Returns ------- result : list Numpy objects as list with equivalent values to the input object. """ i...
14,449
def match_histogram_with_merges(source: str, source_mask: str, reference: str, reference_mask: str, block_size: int = None): """Normalize the source image histogram with reference image. This functions implements the `skimage.exposure.match_histograms`, which consists in the manipulate the pixels of an inp...
14,450
def fetch_run(workspace: Workspace, run_recovery_id: str) -> Run: """ Finds an existing run in an experiment, based on a recovery ID that contains the experiment ID and the actual RunId. The run can be specified either in the experiment_name:run_id format, or just the run_id. :param workspace: the c...
14,451
def get_wl_band(radar_frequency): """Returns integer corresponding to radar frequency. Args: radar_frequency (float): Radar frequency (GHz). Returns: int: 0=35GHz radar, 1=94Ghz radar. """ return 0 if (30 < radar_frequency < 40) else 1
14,452
def get_topology_node(name: str, topology: ServiceTopology) -> TopologyNode: """ Fetch a topology node by name :param name: node name :param topology: service topology with all nodes :return: TopologyNode """ node = topology.__dict__.get(name) if not node: raise ValueError(f"{nam...
14,453
def place(c, project, language, appname): """copy translation(s) into <appname> plaats het gecompileerde language file zodat het gebruikt kan worden """ base = get_base_dir(project) if not base: print('unknown project') return if appname == '*': appname = os.path.basenam...
14,454
def md5hash(string): """ Return the MD5 hex digest of the given string. """ return hashlib.md5(string).hexdigest()
14,455
def test_unknown_node(): """An unknown node type should raise an error.""" with pytest.raises(UnknownNode): compose("")
14,456
def userlist(request): """Shows a user list.""" return common_userlist(request, locale=request.view_lang)
14,457
def return_heartrates(patient_id): """ access database to get heart rate history for a patient :param patient_id: integer ID of patient to get heart rates of :return: json with the heart rate list for patient, or error message """ patient_id = int(patient_id) if heart_server_helpers.valida...
14,458
def describe_vpn_connections_header(): """generate output header""" return misc.format_line(( "Account", "Region", "VpcId", "VpcCidr", "VpnName", "VpnId", "State", "CutomerGwId", "CutomerGwAddress", "Ty...
14,459
def to_numpy(a): """Convert an object to NumPy. Args: a (object): Object to convert. Returns: `np.ndarray`: `a` as NumPy. """ return convert(a, NPOrNum)
14,460
def transpose(self, perm=None, copy=True): """Return a tensor with permuted axes. Parameters ---------- perm : Union[Sequence[int], dragon.Tensor]], optional The output permutation. copy : bool, optional, default=True Return a new tensor or transpose in-place. Returns -----...
14,461
def GetInfoFromKegg(): """ """ pass
14,462
def brainrender_vis(regions, colors=None, atlas_name="allen_mouse_25um"): """Visualise regions in atlas using brainrender""" if colors is None: cm = ColorManager(num_colors=len(regions), method="rgb") colors = cm.colors def get_n_random_points_in_region(region, N): """ Gets...
14,463
def randsel(path, minlen=0, maxlen=None, unit="second"): """Randomly select a portion of audio from path. Parameters ---------- path: str File path to audio. minlen: float, optional Inclusive minimum length of selection in seconds or samples. maxlen: float, optional Excl...
14,464
def update_time_bounds_in_config(config): # {{{ """ Updates the start and end year (and associated full date) for climatologies, time series and climate indices based on the files that are actually available. Parameters ---------- config : ``MpasAnalysisConfigParser`` object contai...
14,465
def parse_datetime(splunk_uri, session_key, time_str): """ Leverage splunkd to do time parseing, :time_str: ISO8601 format, 2011-07-06T21:54:23.000-07:00 """ import splunklib if not time_str: return None scheme, host, port = tuple(splunk_uri.replace("/", "").split(":")) servi...
14,466
def _get_assessment_url(assessment): """Returns string URL for assessment view page.""" return urlparse.urljoin(utils.get_url_root(), utils.view_url_for(assessment))
14,467
def get_secret_setting_names(settings: dict) -> Set[str]: """guess the setting names that likely contain sensitive values""" return { key for key in settings.keys() if AUTOFIND_SECRET_SETTINGS.match(key) and key not in AUTOFIND_SECRET_SETTINGS_EXCLUDED } | { key for key, valu...
14,468
def main(dict): """ Function that allows to send a get request to twitter API and retrieve the last 3 tweets of a specific account name. The parameter of the account is passed by Watson Assistant throught a context variable. Args: dict (dict): containing the parameter - in our case only...
14,469
def build_classifier_model(tfhub_handle_preprocess, tfhub_handle_encoder): """Builds a simple binary classification model with BERT trunk.""" text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text') preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing') ...
14,470
def execute_sql(sql: str, param: list): """ 执行查询sql, 返回列表 :param param: 执行参数 :param sql: 执行的sql语句 :return: 结果列表 """ cursor = connection.cursor() res = cursor.execute(sql, param) return res
14,471
def slice_variable_response(DataFrame, variable, condition): """ Parameters ---------- DataFrame : pandas.DataFrame DataFrame variable : str Variable to examine the freqeuncy. condition, str, default None Filtering condition Returns ------- None ...
14,472
def enqueue_frames_from_output(_proc, _qout, scale, use_timer=None, use_tensorflow: bool = False): """ :type scale: tuple :type _proc: subprocess.Popen :type _qout: queues.Queue """ print('scale enqueue_frames_from_output', scale) timer = None if use_timer: timer = use_timer ...
14,473
def query_jwt_required(fn): """ A decorator to protect a query resolver. If you decorate an resolver with this, it will ensure that the requester has a valid access token before allowing the resolver to be called. This does not check the freshness of the access token. """ @wraps(fn) def...
14,474
def main(input_dir, output_dir): """ Runs data processing scripts to turn raw data from (../raw) into a single interim dataset (../interim), for which later features will be engineered. The main process here is *conversion* via pypandoc and external calls to unoconv. """ logger = log...
14,475
def callers_for_code(code): """ Return all users matching the code. :param code: :return: """ return db.session.query(Caller).filter(Caller.code==code).all()
14,476
def WriteJsonFile(filename, params, database): """Write database out as a .dat file. Args: filename: Name of output file to write database to. params: Parameter structure used to generate the database. database: Dictionary of ndarrays of aerodynamic coefficients and derivatives. """ def _Pr...
14,477
def headers(): """ default HTTP headers for all API calls """ return {"Content-type": "application/json"}
14,478
def preprocess_confidence(train_df, test_df=None): """ Feature creation that should be done given training data and then merged \ with test data. """ ATTRIBUTION_CATEGORIES = [ # V1 Features # ############### ['ip'], ['app'], ['device'], ['os'], ['channel'], # V2 Fea...
14,479
def ancestral_state_pair(aln,tree,pos1,pos2,\ ancestral_seqs=None,null_value=gDefaultNullValue): """ """ ancestral_seqs = ancestral_seqs or get_ancestral_seqs(aln,tree) ancestral_names_to_seqs = \ dict(zip(ancestral_seqs.Names,ancestral_seqs.ArraySeqs)) distances = tree.getDistances() ...
14,480
def get_a(i,j,k): """returns between tad coordinates""" i,j,k = np.sort([i,j,k]) ax,ay=[],[] for x_ in range(i,j+1): for y_ in range(j+1,k+1): ax.append(x_) ay.append(y_) return ax,ay
14,481
def write_dov(filename, coeffs, errors=None, header=None, header2=None, lmax=None, encoding=None): """ Write spherical harmonic coefficients to a text file formatted as [degree, order, value]. Usage ----- write_dov(filename, coeffs, [errors, header, header2, lmax, encoding]) ...
14,482
def get_mode(input_list: list): """ Get's the mode of a certain list. If there are few modes, the function returns False. This is a very slow way to accomplish this, but it gets a mode, which can only be 4 things, so it should be OK """ if len(input_list) == 0: return False distinguish...
14,483
def write_index(records_list, output_index): """Create and write a pandas df to the specified file""" # Grab the first record dict some_record = records_list[0] # Map all values to integers dtypes = {k: "int64" for k in some_record.keys()} # Except for genome id that needs to be a string dty...
14,484
def qqe(close, length=None, smooth=None, factor=None, mamode=None, drift=None, offset=None, **kwargs): """Indicator: Quantitative Qualitative Estimation (QQE)""" # Validate arguments length = int(length) if length and length > 0 else 14 smooth = int(smooth) if smooth and smooth > 0 else 5 factor = f...
14,485
async def changelog(ctx): """Shows the latest release notes of DimBot""" await ctx.reply(""" **__0.9.20 (May 20, 2021 1:58AM GMT+1)__**\n Fixes a typo in pp Updates the message of d.start to reflect latest changes WhoPing can now detect Role ghost pings. The mass ping limit for bots have been increased to 20. W...
14,486
def reference_col( tablename, nullable=False, pk_name="id", foreign_key_kwargs=None, column_kwargs=None ): """Column that adds primary key foreign key reference. Usage: :: category_id = reference_col('category') category = relationship('Category', backref='categories') """ foreign_...
14,487
def launch(directory: str = "",movie: str = "",pdfFile: str = "",webPage: str = "") -> None: """ 適切なアプリケーションを起動し、指定したドキュメント、Web ページ、またはディレクトリを開きます。 ----------------------------------------- Flags: ----------------------------------------- directory (string): ディレクトリ。 --------------...
14,488
def Ei(x, minfloat=1e-7, maxfloat=10000): """Ei integral function.""" minfloat = min(np.abs(x), minfloat) maxfloat = max(np.abs(x), maxfloat) def f(t): return np.exp(t) / t if x > 0: return (quad(f, -maxfloat, -minfloat)[0] + quad(f, minfloat, x)[0]) else: return quad(f, ...
14,489
def validate_tender_activate_with_language_criteria(request, **kwargs): """ raise error if CRITERION.OTHER.BID.LANGUAGE wasn't created for listed tenders_types and trying to change status to active """ tender = request.context data = request.validated["data"] tender_created = get_first_revis...
14,490
def _MaybeMatchCharClassEsc (text, position, include_sce=True): """Attempt to match a U{character class escape <http://www.w3.org/TR/xmlschema-2/#nt-charClassEsc>} expression. @param text: The complete text of the regular expression being translated @param position: The offset of the backslash...
14,491
def request(command, url, headers={}, data=None): """Mini-requests.""" class Dummy: pass parts = urllib.parse.urlparse(url) c = http.client.HTTPConnection(parts.hostname, parts.port) c.request( command, urllib.parse.urlunparse(parts._replace(scheme="", netloc="")), ...
14,492
def configure_hosts(hostfile): """Assuming no hostfile file exists, ask questions and create a new one""" print "Configuring `ansible_hosts` file {0}...\n".format(hostfile) print "What is the IP address of the virtual machine?" machine_address = raw_input('--> ') machine_address = machine_address...
14,493
def __ConvertOSBGToLocal(easting, northing, Eo, No, one_over_CSF): """ Convert OSBG36 Easting-Northing to local grid coordinates :param easting: easting in OSBG36 :param northing: northing in OSBG36 :param Eo: delta easting of local grid :param No: delta northing of local grid :param one_o...
14,494
def sum_of_n_2(n): """ 迭代求和,仅使用加法。 :param n: 1 到 n 的和 :return: 元组(元素的组合),第一位为值,第二位为所花时间 """ start = time.time() the_sum = 0 for i in range(1, n + 1): the_sum = the_sum + i end = time.time() return the_sum, end - start
14,495
def TSA_t_g( temperature, temperature_vegetation, vegetation_fraction): """ //Temperature of ground from Tvegetation //Based on two sources pixel split //Chen et al., 2005. IJRS 26(8):1755-1762. //Estimation of daily evapotranspiration using a two-layer remote sensing model. Ground temperature, bare soil TSA_t_g...
14,496
def get_dict_buildin(dict_obj, _type=(int, float, bool, str, list, tuple, set, dict)): """ get a dictionary from value, ignore non-buildin object """ non_buildin = {key for key in dict_obj if not isinstance(dict_obj[key], _type)} return dict_obj if not non_buildin else {key: dict_obj[key] for key in...
14,497
def onNewSceneOpened(*args): """ Called when a new scene is opened, usually through a callback. """ if store.get(pcfg.use_piper_units): loadDefaults() if store.get(pcfg.use_piper_render): loadRender()
14,498
def _generic_fix_integers(model): """ Fix the integers of a model to its solution, and removes the variables. :param model: :return: """ continuous_model = model.copy() continuous_model.name = model.name + ' - continuous' integer_variables = set() constraints_with_integer_variable...
14,499