content
stringlengths
22
815k
id
int64
0
4.91M
def balanced_decomp_unsafe(sequence, open_to_close): """ Same as :func:`balanced_decomp` but assumes that ``sequence`` is valid balanced sequence in order to execute faster. """ gen = generate_balance_unsafe(sequence, open_to_close) bal_curr, tok_curr = next(gen) pop_open = sequence[0:1] ...
61,900
def _cast_keys_as_lists(dictionary): """Converts dictionary with values that are ints or numpy arrays to lists. :param dict dictionary: dictionary with values that are ints or numpy arrays :return: (*dict*) -- the same dictionary where the values are lists """ for key, value in dictionary.items(): ...
61,901
def parse(args: list = None) -> dict: """ Parses the command line arguments and returns a dictionary containing the results. :param args: The command line arguments to parse. If None, the system command line arguments will be used instead. """ parser = ArgumentParser(description...
61,902
def GetPlayerNames(player_ids): """Loads player_ids into Steam Account cache. This will take in a list of account ids and load the Steam Accounts into db cache from the Steam API. Args: player_ids (list): List of SteamID64s to lookup. Returns: dict. Returns dict of player_i...
61,903
def check_mrtrix(version_requirements=None): """Check MRtrix software.""" from colorama import Fore from clinica.utils.exceptions import ClinicaMissingDependencyError check_environment_variable('MRTRIX_HOME', 'MRtrix') list_binaries = ['transformconvert', 'mrtransform', 'dwi2response', 'tckgen'] ...
61,904
def _verify_node(cmd): """Verify that the node command exists and is at least the minimum supported version of node. Parameters ---------- cmd : string Node command to verify (i.e 'node').""" try: out, err, return_code = get_output_error_code([cmd, '--version']) except OSErr...
61,905
def main(args=None): """ The main method for parsing command-line arguments and running the application. :param args: the commandline arguments, uses sys.argv if not supplied :type args: list """ parser = argparse.ArgumentParser() parser.add_argument("--text", help="the text to output", req...
61,906
def get_all_devices( client: happi.Client = None, ) -> Generator[ophyd.Device, None, None]: """ Get all devices from a given happi client. Parameters ---------- client : happi.Client, optional The happi client to use. Defaults to using one from the environment configuration. ...
61,907
async def test_invalid_token_format(hass): """Test an error is shown for invalid token formats.""" flow = SmartThingsFlowHandler() flow.hass = hass result = await flow.async_step_user({'access_token': '123456789'}) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['step_id...
61,908
def random_crop_info(h, w, border_ratio): """ :return: random cropsize 原尺寸 * random scale [0.9, 1.0, 1.1] random center 设置 border 随机取中心 """ # h,w: ori image size if np.random.random() < 1.0: # random scale random_scale = np.random.choice(np.arange(0.8, 1.2, 0...
61,909
def test_veri_chips_vals(veri): """ Test that VeriDataset chips have the correct values. """ instantiated_class = veri[0] FILE_NAMES = veri[1] # Check that the correct chips exist for filepath, car_id, cam_id, time, misc in FILE_NAMES: chip = instantiated_class.chips[filepath] asser...
61,910
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: entry_data = hass.data[DOMAIN].pop(entry.entry_id) vlc = entry_data[DATA_VLC] awa...
61,911
def finalize(): """ Finalize the module """ global TPL if TPL: TPL = None
61,912
def _create_pem_projected_volume(cert_secret_name): """ Create volume for pem certificate """ items = [client.V1KeyToPath(key="tls.crt", path="keystore.pem"), client.V1KeyToPath(key="ca.crt", path="truststore.pem"), client.V1KeyToPath(key="tls.key", path="key.pem")] sec_pro...
61,913
def assign_random(scores, vector_quotas=None, pi_init=None, sigma_init=None, envy_init=None): """ Assigns refugee at random Inputs: assignment: A NxM matrix describing assignment scores: The scoring matrix describing refugee-locality integration scores refugee: The index of the refuge...
61,914
def get_alerts(alert_id=None, filt=None): """In short: Get one or many alerts. The client uses the get_alerts command to get alert information. If the command sent by the client was valid, the connector will reply with a list of alerts to the client. """ root = etree.Element("get_alerts") i...
61,915
def similar(app_id, detailed=False, hl="en", gl="us"): """Sends a GET request, follows the redirect, and retrieves a list of applications similar to the specified app. :param app_id: the app to retrieve details from, e.g. 'com.nintendo.zaaa' :param detailed: if True, sends request per app for its full ...
61,916
def gcd(x, y): """ greatest common divisor """ while y != 0: (x, y) = (y, x % y) return x
61,917
def parse_agent_req_file(contents): """ Returns a dictionary mapping {check-package-name --> pinned_version} from the given file contents. We can assume lines are in the form: datadog-active-directory==1.1.1; sys_platform == 'win32' """ catalog = {} for line in contents.splitlines(): ...
61,918
def evaluate_metrics_stopping(model_list, metric_name, bigger_is_better, search_criteria, possible_model_number): """ This function given a list of dict that contains the value of metric_name will manually go through the early stopping condition and see if the randomized grid search will give us the correct...
61,919
def svn_wc_external_item2_create(*args): """svn_wc_external_item2_create(apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_external_item2_create(*args)
61,920
def PHeaderDict (dict): """ Print the contents of a descriptor as python dict * dict = Python ImageDesc to print as python dict """ ################################################################ print("Object: %8s Origin: %8s" % \ (dict["object"], dict["origin"])) #"date origin ...
61,921
def __get_recruiter_hamburger_menu_items(): """ allows multiple templates to pull the same menu list items from one source of truth Returns(str): html5 list elements for the hamburger menu """ return \ "<li><a href='/jobs'><span class='glyphicon glyphicon-briefcase'></span> &nbsp; Jobs</a...
61,922
def test_block_swap() -> None: """Test Block.swap. - vertical (test in game) - horizontal (test in game) - block can't be swapped """ block = Block((50, 50), 100, (0, 0, 0), 0, 2) assert block.swap(0) is False assert block.swap(1) is False
61,923
def test_maxwell_magnetic_field_sphere( default_parameters, helpers, device_interface, precision ): """Test Maxwell magnetic field on sphere.""" from bempp.api import function_space from bempp.api.operators.boundary.maxwell import magnetic_field grid = helpers.load_grid("sphere") space1 = func...
61,924
def SampleSum(dists, n): """Draws a sample of sums from a list of distributions. dists: sequence of Pmf or Cdf objects n: sample size returns: new Pmf of sums """ pmf = Pmf(RandomSum(dists) for i in range(n)) return pmf
61,925
def transform(shape, from_crs, to_crs): """Transform a shape from one crs to another.""" project = partial(pyproj.transform, from_crs, to_crs) return s_transform(project, shape)
61,926
def optimum_policy2D(): """ This algorithm keeps track of all the paths through the grid. It always expands the least expensive path, thus avoiding unnecessary work on paths that are too expensive to follow. A path starts at the initial position. Each time a new position is found, a Cell object...
61,927
def coral(source_data, target_data, assay, feat_key: str, nthreads: int): """ Applies CORAL error correction to the input data. Args: source_data (): target_data (): assay (): feat_key (): nthreads (): """ from .writers import dask_to_zarr from .utils imp...
61,928
def make_etag(hasher): """Build etag function based on `hasher` algorithm.""" def etag(buf): h = hasher() for chunk in buf: h.update(chunk) return '"' + h.hexdigest() + '"' return etag
61,929
def print_options(options): """ print options """ print "--------------------------------------------------" print " " keys = options.keys() for k in keys: print k, ':', options[k] print "--------------------------------------------------"
61,930
def Siamese(vocab_size=41699, d_model=128, mode='train'): """Returns a Siamese model. Args: vocab_size (int, optional): Length of the vocabulary. Defaults to len(vocab). d_model (int, optional): Depth of the model. Defaults to 128. mode (str, optional): 'train', 'eval' or 'predict', pre...
61,931
def indexof(ilist, item): """ returns the index of item in the list """ i = 0 for list_item in ilist: list_item = list_item.strip() if list_item == item: return i i += 1 print("ERROR failed to parse config, can't find item:", item) exit(-4)
61,932
def paginate_query(db_name, model_class, q_expression, annotate=None, query_size=5000, values=None, load_source=None): """ Runs a query on the given database in small chunks and produces a generator with the results. Iteration logic adopted from https://djangosnippets.org/snippets/19...
61,933
def remove_xml_dir(path): """ Remove doxygen xml folder """ if os.path.exists(path): shutil.rmtree(path, ignore_errors=True)
61,934
def im(data): """ imshow puts eta (first axis) on y-axis inverts the y-axis resulting in a plot like W | | eta | | E v --------> N xi S So flipping brings us to W | | eta | | E v --------> S xi N And rotation to N | | xi | | S v --------> E xi W """ retur...
61,935
def update_loc_dict(new_file_name, file_name="loc_dict"): """ Updates loc_dict with locations new file and saves it as python object. :param new_file_name: string, name of file with new data :param file_name: string, name of file to update, default "loc_dict" :return loc_dict: dictionary, keys - loc...
61,936
def make_1397(pc, target_list, skill_id, skill_lv, damage_list, color_list): """スキル使用結果通知(対象:自分)""" if not target_list: target_list = () damage_list = () color_list = () else: assert len(target_list) == len(damage_list) assert len(damage_list) == len(color_list) i = len(target_list) result = pa...
61,937
def _contains(shape, x, y): """ Try to use the shape's contains method directly on XY. Does not currently work on anything. """ raise NotImplementedError() return shape.contains((x, y))
61,938
def _api_tier_validator(value: str) -> Optional[str]: """ Determines if input value is a valid API tier """ try: KrakenAPITier(value.upper()) except ValueError: return "No such Kraken API Tier."
61,939
def cli_inventory(): """ Various commands for working with the inventory format """ pass
61,940
def ecdf(x): """ Generate empirical CDF """ n = len(x) xs = np.sort(x) ys = np.arange(1, n+1)/n return xs, ys
61,941
def _get_pyramid(img, num_scales, pooling_fn=tf.nn.avg_pool2d): """Generates a pyramid from the input image/tensor at different scales. This function behaves similarly to `tfg.image.pyramid.split()`. Instead of using an image resize operation, it uses average pooling to give each input pixel equal weight in c...
61,942
def get_partner_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(AAPartner, *args, **kwargs)
61,943
def test_component_html_repr(): """check the HTML repr for Jupyter notebooks""" comp = ExampleComponent() html = comp._repr_html_() assert len(html) > 10
61,944
def random_val(matrix,mean,std): """Function to apply normally distributed random noise to the matrix that represents sarcomeres as voxels.""" mat = np.random.normal(mean,std,matrix.shape) matrix += mat return matrix
61,945
def verificacion(autor): """ Se utiliza el metodo de la clase Contribucion para obtener la cantidad de objetos instanciados. Se inicialista una lista de calificaciones como lista vacia por cada contribucion se realiza el llamado al metodo del autor para verificar calificaci...
61,946
def load_mnist_labels(file_name, onehot, num_classes=10): """Load MNIST image labels.""" with gzip.open(file_name, 'rb') as mnist_file: _, num_labels = struct.unpack( ">II", mnist_file.read(8)) buf = mnist_file.read(num_labels) labels = np.frombuffer(buf, dtype=np.uint8) ...
61,947
def preprocess(instr, cpp_path='cpp', cpp_args='', include_paths=[], defines=[]): """ Preprocess a a string using cpp. instr: c code to preprocess. cpp_path: cpp_args: Refer to the documentation of parse_file for the meaning of these arguments. Whe...
61,948
def sinr( received_signal_dbm: float, received_interference_dbm: float, noise_floor_dbm: float, ): """ Calculate the Signal Interference Noise Ratio in decibels. That means that $10^{sinr/10} . (noise+interference) = signal$ Should always hold. """ # We need to convert to watts...
61,949
def load_services(config, bus, path=None): """Load builtin services as well as service plugins The builtin service folder is scanned (or a folder indicated by the path parameter) for services and plugins registered with the "mycroft.plugin.audioservice" entrypoint group. Args: config: conf...
61,950
def generateInput_v4(fout=False): """ Generate complete observation matrix """ des, X = generate_corina_features('ca') pvt = X[:,2] # poverty index of each CA popul = X[:,0].reshape(X.shape[0],1) # poi_cnt = getFourSquareCount() # poi_cnt = np.divide(poi_cnt, popul) * 10000 ...
61,951
def validate_gwdevice_list(data, valid_values=None): """Validate the list of devices.""" if not data: # Devices must be provided msg = _("Cannot create a gateway with an empty device list") return msg try: for device in data: interface_data = device.get(constants....
61,952
def load_log2seq(conf): """Return parser object log2seq.LogParser . Amulog accepts following additional keys extracted by log2seq. - host: device hostname, mandatory - lid: Log message identifier, optional The configuration is described in a python script file. The file is specified in databas...
61,953
def deflate_spans( spans: List[Tuple[int, int, int]] ) -> List[List[Tuple[int, int]]]: """[summary] Args: spans (List[Tuple[int, int, int]]): [description] Returns: List[List[Tuple[int, int]]]: [description] """ # assuming last element in the tuple is the step id spans = so...
61,954
def correlation_coeff(score, gold_data): """ It will take the list of similarity score and calculates pearson correlation and spearman correlation. Finally, it returns the score as per competition standard. """ a = spearmanr(score, gold_data)[0] b = pearsonr(score, gold_data)[0] return (2*a...
61,955
def operate_status_template(open_now: bool) -> tuple: """Flex Message 餐廳營業狀況 Args: open_now (bool): 營業中 Returns: tuple: (營業狀況, 營業文字顏色) """ if open_now: operate_status = { "type": "text", "text": "營業中", "size": "xs", "color": "...
61,956
def install(version, **_): # type: (str, Any) -> None """Install the specified <version> of Terraform (e.g. 0.12.0). If no version is specified, Runway will attempt to find and read a ".terraform-version" file in the current directory. If this file doesn't exist, nothing will be installed. """...
61,957
def paramset_to_rootnames(paramset): """ Generates parameter names for parameters in the set as ROOT would do. Args: paramset (:obj:`pyhf.paramsets.paramset`): The parameter set. Returns: :obj:`List[str]` or :obj:`str`: The generated parameter names (for the non-scalar/scalar c...
61,958
def create_access_token(token): # type: (str) -> azure.core.credentials.AccessToken """Creates an instance of azure.core.credentials.AccessToken from a string token. The input string is jwt token in the following form: <token_header>.<token_payload>.<token_signature> This method looks into the token...
61,959
def get_resolution(token): """Parse a <resolution> token in ddpx.""" if token.type == 'dimension': factor = RESOLUTION_TO_DPPX.get(token.unit) if factor is not None: return token.value * factor
61,960
def build_expr(query_items, entity_name, max_length=16000): """Builds and yields OR expressions for MAG from a list of items. Strings and integer items are formatted quoted and unquoted respectively, as per the MAG query specification. The maximum accepted query length for the api appears to be around ...
61,961
def test_fiedler_vector_tracemin_unknown(): """Test that "tracemin_unknown" raises an exception.""" pytest.importorskip("scipy") G = nx.barbell_graph(5, 4) L = nx.laplacian_matrix(G) X = np.asarray(np.random.normal(size=(1, L.shape[0]))).T with pytest.raises(nx.NetworkXError, match="Unknown line...
61,962
def format_date(date_string, date_format): """ """ formatted_date = datetime.datetime.strptime(date_string, date_format) year_directives = ['%y', '%Y', '%c', '%x'] contains_year = any(directive in date_format for directive in year_directives) if not contains_year: utc_now = datetime.d...
61,963
def check_backend(backend): """Check backend.""" if backend not in ["tensorflow", "caffe", "onnx", "mindspore"]: raise ValueError("The backend only support tensorflow, caffe, onnx and mindspore.")
61,964
def progress_bar(i, size): """ Function that prints progress bar to terminal. """ sys.stdout.write('\r') x = float(i)/float(size) * 100.0 + 1.0 sys.stdout.write("[%-50s] %3d%%" % ('=' * int(x * 0.5), x)) sys.stdout.flush()
61,965
def query_neo_nodes(port, pwd): """ 查询所有的节点 Args: port: pwd: Returns: """ graph = Graph(f"bolt://{NEO_HOST}:" + port, password=pwd) nodes_matcher = NodeMatcher(graph) nodes = list(nodes_matcher.match()) return {node.identity: node["s_name"] for node in nodes}
61,966
def __select_constraints_pairwise(data, labels, samples, samples_labels, n_neighbors): """select constraints of the form x-y where x,y have different labels""" constraints = [] # nearest neighbors are selected from the entire set neighbors = {} data_by_label = {} smallest_norm = np.inf for i...
61,967
def read_and_store(infile: str, host: str, username: str, database: str, password: str): """ Reads a data file in the SBB data format and exports it into an SQL database. :param infile: Path to input file. :param host: Hostname of SQL server. :param username: Username to use for...
61,968
def func_type(): """ type(object) or type(name, bases, dict) return type of an object or if 3 arguments are given return new class. Examples: type('abc'), type('MyClass', (object, Parent), {'attr': None}) """ print '555 = {}'.format(type(555)) print '"Class", object, {{attr: 5}} = {}'.format...
61,969
def take_while(predicate: Callable, iterable: Iterable) -> Tuple: """ Constructs a iterable list by taking elements from ``iterable`` while ``predicate`` is true, Stop taking after the first element falsifies the predicate. >>> take_while(is_even, [2,4,6,7,8,9,10]) (2,4,6) # Notice that it does no...
61,970
def comprobar_restricciones_check(parameters, check): """Comprueba las restricciones CHECK :param parameters: tipo de dato Number: ["Number", nombre_col, precision, escala] tipo de dato String: ["String", nombre_col, varying, max_size] :param check: campo check de la sent...
61,971
async def check_response_route( uid: int = Query.i(description="user id", gt=10, lt=1000), email: Optional[str] = Query.i(default="example@xxx.com", description="user email"), user_name: str = Query.i(description="user name", min_length=2, max_length=4), age: int = Query.i(description="age", gt=1, lt=10...
61,972
def test_fileno(): """Test fileno.""" files = [tempfile.NamedTemporaryFile(mode="a+") for i in range(128)] w = Writer(files) assert w.fileno()
61,973
def cpu_count(): """:return:number of CPUs in the system :note: inspired by multiprocessing""" num = 0 try: if sys.platform == 'win32': num = int(os.environ['NUMBER_OF_PROCESSORS']) elif 'bsd' in sys.platform or sys.platform == 'darwin': num = int(os.popen('sysctl...
61,974
def _n_dist(v, n, randomize=False): """ Creates grouping factor with distributed excess elements """ len_v = float(len(v)) divisor = len_v / n # Create range the length of v (+1 because it starts at 0) # Divide each element and get everything but the first element (0) v_divided = ...
61,975
def test_signed_payload(mocker, has_coupon, has_company, is_program_product, user_ip): """ A valid payload should be signed appropriately """ line1 = LineFactory.create( product_version__product__content_object=ProgramFactory.create() if is_program_product else CourseRunFactory.c...
61,976
def a2l_variable_section_write(symbol_info): """ This function writes the variable section in a2l file :param symbol_info: information of the symbols :return: None """ extracted_symbol_info = info_extract(symbol_info) sym_type = 'NO_TYPE' sym_conversion_method = 'NO_COMPU_METHOD' sym_standard_limits_lower = '0...
61,977
def forward_sensitivity_model(t, s, args): """ This solves a system of (P+1)*N differential equations (needs to solve the original ODE in conjunction) """ y = s.reshape((2, 5))[:, 0] sensitivities = s.reshape((2, 5))[:, 1:] del_f__del_u = jax.jacobian(model, argnums=1)(t, y, args) del_f...
61,978
def create_code_index(model, **kwargs): """ Creates an value/id index of the model args: model: datatstore class, babel datastore table kwargs: dict, filters to be applied to query returns: idx: dict, {column value: datastore id} """ idx = {} with session_scope() as s...
61,979
def get_exploration_recommendations(exp_id): """Gets a list of ids of at most 10 recommended explorations to play after completing the exploration keyed by exp_id. Args: exp_id: str. The ID of the exploration for which to get the recommendations. Returns: list(str). List of...
61,980
def BNNoReLU(x, name=None): """ A shorthand of BatchNormalization. """ if name is None: x = BatchNorm('bn', x) else: x = BatchNorm(name, x) return x
61,981
def symPT(x, Ps, Ts, window_half): """ Measure of asymmetry between oscillatory peaks and troughs Parameters ---------- x : array-like 1d voltage time series Ps : array-like 1d time points of oscillatory peaks Ts : array-like 1d time points of oscillatory troughs ...
61,982
def get_items_serial_number(prefix, obj): """获取物品唯一货号""" date_str = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) # 生成一个固定6位数的流水号 objmodel = obj.objects.last() serial_number = objmodel.id if objmodel else 0 serial_number = "{0:06d}".format(serial_number + 1) return "{}{}{}".form...
61,983
def display_tensor_shapes( sess, tensor_input, tensor_keep_prob, tensor_layer3, tensor_layer4, tensor_layer7, tensor_output, tensor_correct_label, tensor_learning_rate, tensor_logits, get_batches_fn): """for debugging""" graph = tf.get_default_graph() printed_tensors = [ te...
61,984
def tmtuple(tmsecs=None): """ Return a time tuple. This is currently an alias for gmtime(), but allows later tweaking. """ # avoid problems due to timezones etc. - especially a underflow if -86400 <= tmsecs <= 86400: # if we are around 0, we maybe had tmsecs = 0 # 0 initi...
61,985
def make_gaussian_prf(size): """Generate various pRFs based on 2d Gaussian kernel with different parameters. Return a pRF matrixs which shape is (size, size, size*size*fwhm#) """ fwhm_num = 10 fwhms = np.arange(1, fwhm_num+1) prfs = np.zeros((size, size, size*size*fwhm_num)) for k in r...
61,986
def set_summary_output(f): """ Takes a filename and will write the execution summary there """ global _summary_output_file _summary_output_file = _maybe_open_file(f)
61,987
def split(array, nrows, ncols): """Split a matrix into sub-matrices.""" r, h = array.shape return (array.reshape(h // nrows, nrows, -1, ncols) .swapaxes(1, 2) .reshape(-1, nrows, ncols))
61,988
def write_patches_data_to_file(patches_data_file, patch_shape, data_file, patch_overlap=0, indices=None): """ write all the patches (data, GT, indices, and normalization factors (mean, std)) to a file, using multiple processes executing 'write_patches_data_to_file' function on...
61,989
def enumerate_blobs_to_file( output_file: str, account_name: str, container_name: str, sas_token: Optional[str] = None, blob_prefix: Optional[str] = None, blob_suffix: Optional[Union[str, Tuple[str]]] = None, rsearch: Optional[str] = None, limit: Optional[...
61,990
async def test_auth_create(hass, simple_mock_auth): """Mock AsyncAuth to execute get_auth.""" config = { const.HMIPC_HAPID: HAPID, const.HMIPC_PIN: HAPPIN, const.HMIPC_NAME: "hmip", } hmip_auth = HomematicipAuth(hass, config) assert hmip_auth with patch( "homeass...
61,991
def origin_trial_enabled_function_name(definition_or_member): """Returns the name of the OriginTrials enabled function. An exception is raised if both the OriginTrialEnabled and RuntimeEnabled extended attributes are applied to the same IDL member. Only one of the two attributes can be applied to any m...
61,992
def test_version_scm0(monkeypatch): """Retrieve the version via setuptools_scm.""" class _version: __version__ = "10.0.0" monkeypatch.setitem(sys.modules, "sdcflows._version", _version) reload(sdcflows) assert sdcflows.__version__ == "10.0.0"
61,993
def _UpdateSymbolNamesFromNm(raw_symbols, names_by_address): """Updates raw_symbols names with extra information from nm.""" logging.debug('Update symbol names') # linker_map_parser extracts '** outlined function' without knowing how many # such symbols exist at each address. nm has this information, and stores...
61,994
def validate_yn(answer): """Validate y/n prompts :param answer: User response to y/n prompt. If a boolean value is passed (e.g. if a prompt received parsed_input=True), it is treated as a y/n answer and considered valid input :return: True if user answered yes, False if user answered no ...
61,995
def _read_web_config(): """ This function reads *web_config_file* and storing paths to other configuration files (auth.cfg, label.cfg and secret.cfg) and reading secret token value from the appropriate file. """ global conf conf.read(web_config_file) global secret_file secret_file =...
61,996
def wget(URL): """Upload a file across the network using HTTP protocol data: content of the file to upload. URL: e.g. "http://id14timing3.cars.aps.anl.gov/tmp/test.txt" """ URL = URL.replace("http://","") ip_address = URL.split("/")[0] script = "/"+"/".join(URL.split("/")[1:]) if not ip_...
61,997
def other_document(database, document): """ Returns: Document: Copy of 'document' fixture, but with an additional revision. """ other_document = Document(database, document.doc_id) other_document.retrieve() other_document.data['more'] = 'stuff' other_document.create_update() retu...
61,998
def trial_division_5(n): """试除法,境界5层""" prime_number_list = [] for i in range(2, n): for j in prime_number_list: # if j > int(i**0.5)+1: # break if i % j == 0 and j < int(i**0.5)+1: break else: prime_number_list.append(i) ...
61,999