content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import urllib def read_file(file_path): """Read file according to its file schema""" s3_schema = 's3' path_comps = urllib.parse.urlparse(file_path) scheme = path_comps.scheme return_result = None if not scheme or scheme != s3_schema: file_stream = open(file_path) return_result...
438c6286f5f29792fd7c99412bead96a11adc757
20,666
from typing import List def build_command(codemodders_list: List) -> BaseCodemodCommand: """Build a custom command with the list of visitors.""" class CustomCommand(BaseCodemodCommand): transformers = codemodders_list return CustomCommand(CodemodContext())
5aed3c94c954a8e62c7cfb23f2b338e3a017d988
20,667
def default_gen_mat(dt: float, size: int) -> np.ndarray: """Default process matrix generator. Parameters ---------- dt : float Dimension variable difference. size : int Size of the process matrix, equals to number of rows and columns. Returns ------- np.ndarray ...
fc4c19b33dae27ec412a00d20b89c25c5bc8668c
20,668
def _PrepareListOfSources(spec, generator_flags, gyp_file): """Prepare list of sources and excluded sources. Besides the sources specified directly in the spec, adds the gyp file so that a change to it will cause a re-compile. Also adds appropriate sources for actions and copies. Assumes later stage will un-ex...
a6a0d0d6d7531b8e858c8ec0d0aedee320c20d8d
20,669
def striptag(tag): """ Get the short representation of a fully qualified tag :param str tag: a (fully qualified or not) XML tag """ if tag.startswith('{'): return tag.rsplit('}')[1] return tag
f0193e3f792122ba8278e599247439a91139e72b
20,670
def dump_key(key): """ Convert key into printable form using openssl utility Used to compare keys which can be stored in different format by different OpenSSL versions """ return Popen(["openssl","pkey","-text","-noout"],stdin=PIPE,stdout=PIPE).communicate(key)[0]
71dd28876c2fd3e28a4434b926b483cef3b104c2
20,671
def download_complete(root_data_path, domain_name, start_date, end_date): """ Check that all files have been downloaded and that they contain the data in the expected date range """ missing_files = _find_missing_files( root_data_path=root_data_path, domain_name=domain_name, s...
3540632c5ec48fb0741b8173f926fd1cb5970333
20,672
from typing import Any def get_test_string(actual: Any, rtol: float, atol: float) -> str: """ Args: actual: The actual value that was produced, and that should be the desired value. rtol: The relative tolerance of the comparisons in the assertion. atol: The absolute tolerance of the co...
f017806bef4336bf187071436bd454d0ca980636
20,673
def is_type_resolved(_type): """Helper function that checks if type is already resolved.""" return _type in BASIC_TYPES or isinstance(_type, TypeDef)
9451a5dbf17aef1685122b881ede994d1a02b7a0
20,674
import types def get_extension(media): """Gets the corresponding extension for any Telegram media.""" # Photos are always compressed as .jpg by Telegram try: get_input_photo(media) return '.jpg' except TypeError: # These cases are not handled by input photo because it can't ...
cb05f122fdf03df38c6d7b7904c7ec611f09c7a0
20,675
def process_input(df, col_group, col_t, col_death_rate, return_df=True): """ Trim filter and adding extra information to the data frame. Args: df (pd.DataFrame): Provided data frame. col_group (str): Column name of group definition. col_t (str): Column name of the independent variab...
24b1e7274959c5b4befbd826c1a60ca700316b2f
20,676
def cross_entropy_loss(): """ Returns an instance to compute Cross Entropy loss """ return tf.keras.losses.BinaryCrossentropy(from_logits=True)
5fcc673d9339bd4acb84d55fe0c316bc4cf802c4
20,677
def f(x): """ Surrogate function over the error metric to be optimized """ evaluation = run_quip(cutoff = float(x[:,0]), delta = float(x[:,1]), n_sparse = float(x[:,2]), nlmax = float(x[:,3])) print("\nParam: {}, {}, {}, {} | MAE : {}, R2: {}".format(float(x[:,0]),float(x[:,1]),float(x[:,2]),f...
0663b9eb2b717f547f57a8485739165414fbbdba
20,678
def equal(* vals): """Returns True if all arguments are equal""" if len(vals) < 2: return True a = vals[0] for b in vals[1:]: if a != b: return False return True
dbd947016d2b84faaaa7fefa6f35975da0a1b5ec
20,679
def exp(x: pd.Series) -> pd.Series: """ Exponential of series :param x: timeseries :return: exponential of each element **Usage** For each element in the series, :math:`X_t`, raise :math:`e` (Euler's number) to the power of :math:`X_t`. Euler's number is the base of the natural logarithm,...
c4cb057be2dd988a152cc8f224d4bd4300f88263
20,681
def pil_paste_image(im, mask, start_point=(0, 0)): """ :param im: :param mask: :param start_point: :return: """ out = Image.fromarray(im) mask = Image.fromarray(mask) out.paste(mask, start_point, mask) return np.asarray(out)
b6393426aa5b7434e64cddc11ed598fca78a2b47
20,683
import requests def service_northwind_v2(schema_northwind_v2): """https://services.odata.org/V2/Northwind/Northwind.svc/""" return pyodata.v2.service.Service('http://not.resolvable.services.odata.org/V2/Northwind/Northwind.svc', schema_northwind_v2, requests)
a7934ff032725589bb11aab9cd84c26d9f2845c3
20,684
def make_params(params, extra_params): """ Creates URL query params by combining arbitrary params with params designated by keyword arguments and escapes them to be compatible with HTTP request URI. Raises an exception if there is a conflict between the two ways to specify a query param. ""...
f2df0c52675476c0420d40f5ef9053cd2a719194
20,686
def raw_tag(name, value): """Create a DMAP tag with raw data.""" return name.encode('utf-8') + \ len(value).to_bytes(4, byteorder='big') + \ value
9f86a5a9ebc38fcfd31eb7d76ac8bb01618f6ca7
20,687
def get_command(tool_xml): """Get command XML element from supplied XML root.""" root = tool_xml.getroot() commands = root.findall("command") command = None if len(commands) == 1: command = commands[0] return command
8d50b2675b3a6089b15b5380025ca7def9e4339e
20,688
from whoosh.reading import SegmentReader def OPTIMIZE(writer, segments): """This policy merges all existing segments. """ for seg in segments: reader = SegmentReader(writer.storage, writer.schema, seg) writer.add_reader(reader) reader.close() return []
e5985641cbe724072f37158196cdaed0600b403e
20,689
def build_features_revenue_model_q2( df_listings: pd.DataFrame, df_daily_revenue: pd.DataFrame ): """Builds the features to be used on the revenue modelling for answer question 2. Parameters ---------- df_listings : pd.DataFrame Pandas dataframe with information about listings. df_d...
16658cbc76edf66cf718b008d5fba58414df1f8c
20,690
import gzip def load_data(): """Return the MNIST data as a tuple containing the training data, the validation data, and the test data. The ``training_data`` is returned as a tuple with two entries. The first entry contains the actual training images. This is a numpy ndarray with 50,000 entries. ...
f021f1db4b0b22c6d89620f44db7e2578c516489
20,691
def get_elements(xmldoc, tag_name, attribute): """Returns a list of elements""" l = [] for item in xmldoc.getElementsByTagName(tag_name) : value = item.getAttribute(attribute) l.append( repr( value ) ) return l
2cda65802d0dc1ebbb7796f6a43fa9bacfbe852e
20,693
def test_algorithm(circuit, iterations=(1000000)): """ Tests a circuit by submitting it to both aer_simulator and PyLinalg. """ linalg = PyLinalg() qlm_circ, _ = qiskit_to_qlm(circuit, sep_measures=True) test_job = qlm_circ.to_job(nbshots=0, aggregate_data=False) expected = linalg.submit(tes...
ac11f10f9b467ab08275d55515a15d6906076191
20,694
def return_list_of_sn_host(): """ Return potential SN host names This includes: - List of object names in SIMBAD that would correspond to extra-galactic object - Unknown objects - objects with failed crossmatch In practice, this exclude galactic objects from SIMBAD. """ list_simbad_ga...
c2a536fc4b742dc0e4a4c57a582174017d6e2877
20,695
import glob import re def folder2catalog(path, granule_trunk='', granule_extension='*', add_sf=False, client=None): """ Reads a folder of granules into a STAREDataFrame catalog :param path: Path of the folder containing granules :type path: str :param granule_trunk: Granule identifier (e.g. MOD09) ...
3d1d34a3b2e85ddbfb624289126f077d1668bab4
20,696
def _check_satellite_low(xbee, is_on_hold): """ Check if satellites are low and set the is_on_hold flag. Args: xbee(xbee.Zigbee): the XBee communication interface. is_on_hold(bool): a flag telling if the thread is already on hold. Returns: bool: True if low sats, False ...
5ecfdc304a9f6aa5aa41335637f6e783a3643df1
20,697
import requests def indexof(path): """Returns list of filenames parsed off "Index of" page""" resp = requests.get(path) return [a for a, b in file_index_re.findall(resp.text) if a == b]
38b165bfd4f3dbefedff21c7ac62fb57cd8f2d97
20,698
from typing import Optional def get_oversight(xml: str) -> Optional[OversightInfo]: """ Get oversight """ if val := xml.get('oversight_info'): return OversightInfo( has_dmc=val.get('has_dmc', ''), is_fda_regulated_drug=val.get('is_fda_regulated_drug', ''), is_fda_r...
fc14da139eb350306175016a2b8d2d036d02b042
20,699
import fnmatch def get_user_id(gi,email): """ Get the user ID corresponding to a username email Arguments: gi (bioblend.galaxy.GalaxyInstance): Galaxy instance email : email address for the user Returns: String: user ID, or None if no match. """ user_id = None try: ...
89b72a4291b789ab61f276a7e4563c17c2c4e4b7
20,700
def ldns_pkt_size(*args): """LDNS buffer.""" return _ldns.ldns_pkt_size(*args)
833223ed702fdee4525f0c330f4c803bd867daa3
20,702
def getUser(userID): """ Takes a user ID as an argument and returns the user associated with that ID. Args: userID -- The ID of a user stored in the Patrons table """ user = session.query(Patrons).filter_by(id = userID).one() return user
7da06a0baaef540826fd9e902129e1a625f5bfd9
20,703
import warnings def guard_transform(transform): """Return an Affine transformation instance""" if not isinstance(transform, Affine): if tastes_like_gdal(transform): warnings.warn( "GDAL-style transforms are deprecated and will not " "be supported in Rasterio...
1c19f92331c0bb99841c86302c1c1d4c13a07649
20,704
import pandas import math def create_heatmap(piek_json, antske_json, output_path=None, verbose=0): """ """ # initialize dataframe likert_values = [1, 2, 3, 4, 5, 6, 7] df = pandas.DataFrame() default_values = [None for _ in range(len(li...
4e26331c3290d8282e98f7473cd7ee6ffbb46146
20,705
def get_classification_report(true_labels, pred_labels, labels=None, target_names=None, output_dict=False): """ true_labels = [0, 1, 2, 3, 4, 1] # Y pred_labels = [0, 1, 1, 2, 2, 1] # X target_names = ["A", "B", "C", "D", "E"] out_result = get_classification_report(true_labels, pred_labels, target...
37467891f004175ec228adac6ca1e1347c71ca15
20,706
def yx(): """ 测试印象笔记服务 :return: """ client = EvernoteClient(token=dev_token,sandbox=False) client.service_host = 'app.yinxiang.com' userStore = client.get_user_store() user = userStore.getUser() print user return "yx"
9bfdcccddfc9a99d445deea5d920256e19e0bcc5
20,708
def generate_frequency_result_for_time_precedence_query_workload(config_map, time_interval, spatial_interval): """ :param config_map: :param time_interval: :param spatial_interval: :return: """ frequency_result = {} for key in config_map.keys(): region_param_list = config_map.g...
c477acb9652ea40f498a2d92aa91840e868b1736
20,709
def delete(request): """退出登录,清除session""" request.session.flush() return redirect('/login/')
0f10480f3259c52bc1a203ccd9e9746cdf9776ed
20,710
import warnings def acovf(x, unbiased=False, demean=True, fft=None, missing='none', nlag=None): """ Autocovariance for 1D Parameters ---------- x : array Time series data. Must be 1d. unbiased : bool If True, then denominators is n-k, otherwise n demean : bool If T...
c318d80a13bcb4f87117ce84351001a8f320c6d0
20,711
import re def ParseTimeCommandResult(command_result): """Parse command result and get time elapsed. Args: command_result: The result after executing a remote time command. Returns: Time taken for the command. """ time_data = re.findall(r'real\s+(\d+)m(\d+.\d+)', command_result) time_in_seconds...
fc92d4b996716ddb2253bf4eb75ed9860c43b2d7
20,712
import requests import json def _push_aol_to_dativetop_server(aol): """Make a PUT request to the DativeTop server in order to push ``aol`` on to the server's AOL. """ try: resp = requests.put(c.DATIVETOP_SERVER_URL, json=aol) resp.raise_for_status() return resp.json(), None ...
19581efa535e4022fd844292576f56532e9b0cdd
20,714
def dual_single(lag_mul: float, val: np.ndarray, count: np.ndarray) -> float: """Weighted average minus 1 for estimate of F_0. Computes phi_n(lambda_n) - 1. Args: lag_mul: The normalized Lagrangian multiplier. Must be strictly between 0 and 1. val: Likelihood values (excluding...
699b33b824e8a0cae1b35f1290281a08a910f7ef
20,715
def _execute( repository_ctx, cmdline, error_msg = None, error_details = None, empty_stdout_fine = False, environment = {}): """Executes an arbitrary shell command. Args: repository_ctx: the repository_ctx object cmdline: list of strings, the command ...
1d1a291380ca540ab7ec34bbcec4780b695cc0d1
20,716
import warnings def parse_tagged_block(block): """ Replaces "data" attribute of a block with parsed data structure if it is known how to parse it. """ key = block.key.decode('ascii') if not TaggedBlock.is_known(key): warnings.warn("Unknown tagged block (%s)" % block.key) decoder =...
2c06fb4a20e05690a3b72b85dd09b5a2f04a6513
20,717
import numpy def floatX(arr): """Converts data to a numpy array of dtype ``theano.config.floatX``. Parameters ---------- arr : array_like The data to be converted. Returns ------- numpy ndarray The input array in the ``floatX`` dtype configured for Theano. If `arr` ...
261064f1685b4e393d493c5cc657b1ab76d5e89f
20,718
def getNumberOfPublicIp(): """Get the total number of public IP return: (long) Number of public IP """ #No need to calculate this constant everytime return 3689020672 # Real implementation: #ranges = getValidPublicIpRange() #number_of_ip = 0 #for range in ranges: # number_of_ip = number_of_ip + (r...
79221376f64d0a44da06746bc28f0bb7db808b0f
20,719
def cart2sph(x, y, z): """ Convert Cartesian coordinates x, y, z to conventional spherical coordinates r, p, a :param x: Cartesian coordinate or vector x :type x: float or np.ndarray :param y: Cartesian coordinate or vector y :type y: float or np.ndarray :param z: Cartesian coordinates ...
9487d44a8892f450a2920997f277f0f699a89e2d
20,722
def hdfs_open(server, username, path, **args): """Read a file. Returns a filelike object (specifically, an httplib response object). """ datanode_url = datanode_url(server, username, path, **args) response = _datanode_request(server, username, 'GET', datanode_url) if response.status == httplib...
6ddc83d6d571d63ce5536f7c34a00c7c3b04f1fc
20,723
def get_serv_loader(desc_file=SERVICES_FILE): """Get a ServiceLoader with service descriptions in the given file. Uses a "singleton" when the file is `SERVICES_FILE`. """ global _serv_loader if desc_file == SERVICES_FILE: if _serv_loader is None: with open(desc_file, "r") as fp:...
3693b4fd11bc2efcd394eac94e6667b84d110b34
20,724
import socket def check_reverse_lookup(): """ Check if host fqdn resolves to current host ip """ try: host_name = socket.gethostname().lower() host_ip = socket.gethostbyname(host_name) host_fqdn = socket.getfqdn().lower() fqdn_ip = socket.gethostbyname(host_fqdn) return host_ip == fqdn_ip ...
4979ba32d03782258f322ec86b2cd1c24fb4de2c
20,725
from typing import Sequence def _clean_bar_plot_data(df_in: pd.DataFrame, sweep_vars: Sequence[Text] = None) -> pd.DataFrame: """Clean the summary data for bar plot comparison of agents.""" df = df_in.copy() df['env'] = pd.Categorical( df.bsuite_env, categories=_ORDERED_EXPERIMENT...
a62feba3511dccd0d6a909531d5f50b96348e072
20,728
def file_resources(): """File Resources.""" return { 'mock_file': CustomFileResource(service=FileService()), 'mock_file_action': CustomFileActionResource(service=FileService()), }
412bdb59f04c2092c7bd77ef677cfac43bbc27ff
20,729
import pickle def prepare_data(features=None): """Prepare data for analysis Args: features (list of str): list with features Returns: X_train (np.matrix): train X X_test (np.matrix): test X y_train (np.matrix): train y y_test (np.matrix): test y """ # Rea...
b880e89c4bd5b8df80c385141f7f34e71164dc37
20,730
def choose_my_art_date(my_location, google_maps_key, mapping = False, search_range = 500, min_rating = 4.3): """ Function to select an artsy date and dinner; randomly selects local arts event from NY ArtBeat API found at https://www.nyartbeat.com/resources/doc/api, and uses the arts event data to determine...
a33ffc38c4bfb648fd4a68087844484817c8ee02
20,731
import hashlib def hash_text(message: str, hash_alg: str = 'keccak256') -> str: """get the hash of text data :param message: str :param hash_alg: str, `keccak256` or `sha256`, the default value is `keccak256` :return: hex str, digest message with `keccak256` or `sha256` """ if hash_alg == 'k...
da161ee7573ff1af9d644e04641cbb844b2311ca
20,733
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut): """ This function find the grain connected to the face set given as argument. Three nodes on a grain boundary can all be intersected by one grain in which case the grain face is on the boundary or by two grains. It is therefore su...
cb4adff2d6ffe3c32e2a1fc8058e6ad1fed9b2c9
20,734
def get_git_projects(git_worktree, args, default_all=False, use_build_deps=False, groups=None): """ Get a list of git projects to use """ git_parser = GitProjectParser(git_worktree) groups = vars(args).get("groups") if groups: use_bu...
afcb3e68d5e023937bbcdb9e86f9d50f9dc63e78
20,735
from typing import Literal def RmZ( ps: Table, r_band: Literal["9601", "9602"] = "9602", z_band: Literal["9801", "9901"] = "9901", **kw ) -> units.mag: """R-Z color. Parameters ---------- ps : astropy.table.Table need arguments for r(z)_band functions r_band: {'9601', '96...
9c659933788a36409361941f65c4d29e73ec0b9f
20,736
from typing import List def get_table_names(connection: psycop.extensions.connection) -> List[str]: """ Report the name of the tables. E.g., tables=['entities', 'events', 'stories', 'taxonomy'] """ query = """ SELECT table_name FROM information_schema.tables WHERE table_ty...
7602e998b8d4431041eb688cc5ed2450f4dc49bc
20,737
def mrpxmrp(sigmaset1, sigmaset2): """in work; returns transformation [FN] = [FB(s2)][BN(s1)] """ q1 = np.array(sigmaset1) q2 = np.array(sigmaset2) sig1_norm = norm(sigmaset1) sig2_norm = norm(sigmaset2) scalar1 = 1 - sig1_norm**2 scalar2 = 1 - sig2_norm**2 scalar3 = 2. denom = 1...
4df11a8f93c857e44fc98a59ff9a5a4325d29eef
20,738
def continuous_partition_data(data, bins='auto', n_bins=10): """Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-space...
07ab1663a4b2a4d62f2e8fce3c49d0c8c135d9e7
20,739
import csv def readInput(infile,genefile, segfile): """ Reads input files. Extended description of function. Parameters: infile (str): File containing list of genes to be analyzed genefile (str): File containing gene range definitions segfile (str): File containing cell line intervals...
225a0403c1b8875ec7f40c6511edc1c1828dd2aa
20,740
def library_name(name, suffix=SHLIB_SUFFIX, is_windows=is_windows): """ Convert a file basename `name` to a library name (no "lib" and ".so" etc.) >>> library_name("libpython3.7m.so") # doctest: +SKIP 'python3.7m' >>> library_name("libpython3.7m.so", suffix=".so", is_windows=False...
56c19da17acd6d00006e9c1e4308148ab7bc18d8
20,741
def add_light(light_type: str = 'POINT') -> str: """ Add a light of the given type to the scene, return the name key of the newly added light :param light_type: :return: The named key used to index the object """ if utils.is_new_api(): bpy.ops.object.light_add(type=light_type) el...
ac1f5e66a3baf90f2e603069e967b8ed3a76bf8d
20,742
def set_constants(ze=40, p=0.4, kc_min=0.01, kc_max=1.0, snow_alpha=0.2, snow_beta=11.0, ke_max=1.0, a_min=0.45, a_max=0.90): """ :param ze: :param p: the fraction of TAW that a crop can extract from the root zone without suffering wat...
d2c02eb49c59c203b9520b32e94aaceac611abcc
20,743
def project_poses(poses, P): """Compute projected poses x = Pp.""" assert poses.ndim == 2 and poses.shape[-1] == 3, \ 'Invalid pose dim at ext_proj {}'.format(poses.shape) assert P.shape == (3, 4), 'Invalid projection shape {}'.format(P.shape) p = np.concatenate([poses, np.ones((len(poses)...
943c935791744ec3ec6f476c16911d7c90f2024b
20,744
def argmin(x): """ Returns the index of the smallest element of the iterable `x`. If two or more elements equal the minimum value, the index of the first such element is returned. >>> argmin([1, 3, 2, 0]) 3 >>> argmin(abs(x) for x in range(-3, 4)) 3 """ argmin_ = None min_...
8d6778182bf3c18ffa6ef72093bf19a818d74911
20,745
def find_spot(entry, list): """ return index of entry in list """ for s, spot in enumerate(list): if entry==spot: return s else: raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list))
e218822e5e56a62c40f5680751c1360c56f05f4a
20,746
def parse_file(path, game=None, path_relative_to_game=True, verbose=False): """ Parse a single file and return a Tree. path, game: If game is None, path is a full path and the game is determined from that. Or game can be supplied, in which case path is a path relative to the game directory....
64673afea557ad2d74eb4cdcc56d6f6f6e2cd1f6
20,747
def svn_repos_fs_commit_txn(*args): """svn_repos_fs_commit_txn(svn_repos_t * repos, svn_fs_txn_t * txn, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_fs_commit_txn(*args)
6aebf604435485aba694b46ab58f5e4ca7d1b549
20,748
def iter_dir(temp_dir, blast_db, query_name, iteration): """ Get the work directory for the current iteration. We need to call this function in child processes so it cannot be in an object. """ name = '{}_{}_{:02d}'.format( basename(blast_db), basename(query_name), iteration) retur...
e4a8acf79fa3ef6b3822d91406cd6cf007477308
20,750
def zoomSurface(src, zoomx, zoomy, smooth): """Zooms a surface with different x & y scaling factors. This function renders to a new surface, with optional anti-aliasing. If a zoom factor is negative, the image will be flipped along that axis. If the surface is not 8-bit or 32-bit RGBA/ABGR, it will be ...
08e7ad74a4420f5b02a6924d47cdecf3dc09229b
20,751
import struct def array(*cols: Column) -> Column: """ Return column of arrays """ return (struct(*cols).apply(list)).alias(f"[{', '.join([Column.getName(c) for c in cols])}]")
65599cd0fa7b0ea5b670555656a9b615e0e68664
20,752
def prepare_inputs(boxes, digits_occurrence): """ :param boxes: 2D list of 81 gray OpenCV images (2D numpy arrays) :param digits_occurrence: 2D numpy array that contains True or False values that represent occurrence of digits :return: if no digit was found returns None; otherwise returns 4D numpy array wit...
27c97e374f9cbdb0d427acacb5645819d05a2aea
20,754
def evaluate_constants(const_arrays, expr): # pragma: no cover """Convert constant arguments to cupy arrays, and perform any possible constant contractions. """ return expr(*[to_cupy(x) for x in const_arrays], backend='cupy', evaluate_constants=True)
7a371d0cb262fb530873825dee02a8201913b2c1
20,755
def setup_family(dompc, family, create_liege=True, create_vassals=True, character=None, srank=None, region=None, liege=None, num_vassals=2): """ Creates a ruler object and either retrieves a house organization or creates it. Then we also create similar ruler objects for...
9cd1fda01685c071f79e876add49e5ffe5b23642
20,756
def normalize_line(line: dict, lang: str): """Apply normalization to a line of OCR. The normalization rules that are applied depend on the language in which the text is written. This normalization is necessary because Olive, unlike e.g. Mets, does not encode explicitly the presence/absence of whitespac...
f158d3d9811752e009a7f0aa6f94b4a67e322960
20,757
def attribute_summary(attribute_value, item_type, limit=None): """Summarizes the information in fields attributes where content is written as an array of arrays like tag_cloud, items, etc. """ if attribute_value is None: return None items = ["%s (%s)" % (item, instances) for ...
a835e985ce4f9c6d82bdaa267589a802fb865d26
20,758
import json def root(): """Base view.""" new_list = json.dumps(str(utc_value)) return new_list
7d94ea10dc944d1cef13dfea7cc12ccc5bc9f742
20,759
def plc_read_db(plc_client, db_no, entry_offset, entry_len): """ Read specified amount of bytes at offset from a DB on a PLC """ try: db_var = plc_client.db_read(db_no, entry_offset, entry_len) except Exception as err: print "[-] DB read error:", err sys.exit(1) db_val =...
324c81b1192c90c3909bf4e6cb65e590ce48f59a
20,760
def rank_adjust(t, c=None): """ Currently limited to only Mean Order Number Room to expand to: Modal Order Number, and Median Order Number Uses mean order statistic to conduct rank adjustment For further reading see: http://reliawiki.org/index.php/Parameter_Estimation Above reference...
c79d308dd333c96abe64274918fcd294d24f7d40
20,762
from datetime import datetime import requests def login_captcha(username, password, sid): """ bilibili login with captcha. depend on captcha recognize service, please do not use this as first choice. Args: username: plain text username for bilibili. password: plain text password for bi...
de0ee5d865ea11b32f155fb3a3470fff9b13202b
20,763
def ml_transitions(game, attach=True, verbose=False): """ dataframe to directional line movement arrays """ transition_classes = [] prev = [None, None] for i, row in game.iterrows(): cur = list(row[["a_ml", "h_ml"]]) transition_class = analyze.classify_transition(prev, cur) ...
3156f377f4c78b30cabe27f1dc37a277b25ebde6
20,764
def plugin_uninstall(plugin, flags=None, kvflags=None): """ Uninstall a Helm plugin. Return True if succeed, else the error message. plugin (string) The plugin to uninstall. flags (list) Flags in argument of the command without values. ex: ['help', '--help'] kvflags (d...
f162d37cb48e3cc0ebb3294ec4fe33b9fc56d8f0
20,765
def geom_to_tuple(geom): """ Takes a lat/long point (or geom) from KCMO style csvs. Returns (lat, long) tuple """ geom = geom[6:] geom = geom.replace(" ", ", ") return eval(geom)
003f25a0ebc8fd372b63453e4782aa52c0ad697c
20,766
def b_s_Poole(s, V_max, z, halo_type, bias_type): """ This function expresses Equation (2) of Poole et al (2014) and fetches the parameters needed to compute it. Args: s (numpy.ndarray) : scale values V_max (float) : halo maximum circular velocity z (float) : redshift of in...
7ee59c4e3052cab74932c9e78dfc04af92a2284e
20,767
def rasterize_polygon(poly_as_array, shape, geo_ref): """ Return a boolean numpy mask with 1 for cells within polygon. Args: poly_as_array: A polygon as returned by ogrpoly2array (list of numpy arrays / rings) shape: Shape (nrows, ncols) of output array geo_ref: GDAL style georeference ...
506fbc7b1e215e52e1ee469cb88ffc4b4d45dd89
20,770
def get_reg_part(reg_doc): """ Depending on source, the CFR part number exists in different places. Fetch it, wherever it is. """ potential_parts = [] potential_parts.extend( # FR notice node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT')) potential_parts.extend( ...
33f4c2bb9a4e2f404e7ef94a3bfe3707a3b1dd93
20,772
from pathlib import Path import json def load_configuration(module: str, configs_path=None) -> dict: """ Load the configuration and return the dict of the configuration loaded :param module: The module name to load the configuration. :type module: str :param configs_path: path where to check conf...
2a5e0a798b3c3c3dd1570ee79d1e3ce5d6eff97b
20,773
def direct(input_writer, script_str, run_dir, prog, geo, charge, mult, method, basis, **kwargs): """ Generates an input file for an electronic structure job and runs it directly. :param input_writer: elstruct writer module function for desired job :type input_writer: elstruct fun...
e14e41aac6f682d283094a4e0755dcc8949de269
20,774
def get_ids(records, key): """Utility method to extract list of Ids from Bulk API insert/query result. Args: records (:obj:`list`): List of records from a Bulk API insert or SOQL query. key (:obj:`str`): Key to extract - 'Id' for queries or 'id' for inserted data. Returns: (:obj:`l...
e1373aee926406a4a780f6c344069702350cb16d
20,775
def auto_help(func): """Automatically registers a help command for this group.""" if not isinstance(func, commands.Group): raise TypeError('Auto help can only be applied to groups.') cmd = commands.Command(_call_help, name='help', hidden=True) func.add_command(cmd) return func
bfcbd0d951dcffb43363b87b6bc4162226db1413
20,777
import itertools import operator def unique_justseen(iterable, key=None): """ List unique elements, preserving order. Remember only the element just seen. >>> [x for x in unique_justseen('AAAABBBCCDAABBB')] ['A', 'B', 'C', 'D', 'A', 'B'] >>> [x for x in unique_justseen('ABBCcAD', str.lower)] ...
97323df08e9a001b5cd81cbcb88ae3e8ae486a8b
20,778
def unique_rows(arr, thresh=0.0, metric='euclidean'): """Returns subset of rows that are unique, in terms of Euclidean distance http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array """ distances = squareform(pdist(arr, metric=metric)) idxset = {tuple(np.nonzero(v)[0]) for v in...
79afdddc50239ed1479deeb75a41ea19d2dec9ca
20,779
import json def backdoors_listing(request,option=None): """ Generate the Backdoor listing page. :param request: Django request. :type request: :class:`django.http.HttpRequest` :param option: Action to take. :type option: str of either 'jtlist', 'jtdelete', 'csv', or 'inline'. :returns: :c...
f4c8d2b2be68c40de7ec9e79a29e592618afbb44
20,780
def my_join(x): """ :param x: -> the list desired to join :return: """ return ''.join(x)
bffc33247926c2b1ebe1930700ed0ad9bcb483ec
20,781
def visualize_code_vectors(code_vectors, cmap='Paired', inter='none', origin='upper', fontsize=16, aspect='auto', colorbar=True): """ Document """ to_plot = np.array(code_vectors) # First the parameters to_plot_title = 'Code Vectors in Time...
39269d46a8ec544ccf415a363489b83f43d7fbc0
20,783
def get_displacements_and_forces(disp_dataset): """Return displacements and forces of all atoms from displacement dataset. This is used to extract displacements and forces from displacement dataset. This method is considered more-or-less as a converter when the input is in type-1. Parameters -...
998f3fd6319ad777b4dfa523b8464b45ce9bae52
20,784
from typing import Dict from datetime import datetime def GetUserAllBasicData(user_url: str) -> Dict: """获取用户的所有基础信息 Args: user_url (str): 用户个人主页 Url Returns: Dict: 用户基础信息 """ result = {} json_obj = GetUserJsonDataApi(user_url) html_obj = GetUserPCHtmlDataApi(user_url) ...
1965484ef2aa638f9084720e38c5f660d9000665
20,785