content
stringlengths
22
815k
id
int64
0
4.91M
def train10(): """ CIFAR-10 training set creator. It returns a reader creator, each sample in the reader is image pixels in [0, 1] and label in [0, 9]. :return: Training reader creator :rtype: callable """ return reader_creator( paddle.dataset.common.download(CIFAR10_URL, 'cifar'...
28,400
def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets): """Verifies if the fleet is in a border and the updates the position of all aliens in the fleet""" check_fleet_edges(ai_settings, aliens) aliens.update() #Verifies if a collision between aliens and the spaceship has occured i...
28,401
def _generate_one_direction_LSTM(transformer, X, W, R, B, initial_h, initial_c, P, clip, act, dtype, hidden_size, batch_size): """Generate subgraph for one direction of unrolled LSTM layer Args: transformer (_ModelTransformerHelper): helper for model generation X...
28,402
def FindTerms(Filename, NumTerms): """Reorders the first NumTerms of the output of Todd program to find omega breakpoints""" f = open(Filename, 'r') # Get the value of omega Omega = int(f.readline().split()[1]) print "Omega =", Omega # Skip these lines for i in range(3): f.readline() Terms = [] for line i...
28,403
def hessian_power(h): """ Power in the hessian filter band Frobenius norm squared """ if len(h) == 2: p = np.abs(h[0])**2 + 2*np.abs(h[1])**2 + np.abs(h[2])**2 elif len(h) == 6: p = np.abs(h[0])**2 + 2*np.abs(h[1])**2 + 2*np.abs(h[2])**2 + np.abs(h[3])**2 + 2*np.abs(h[4])**2 + np...
28,404
def read_table(source, columns=None, memory_map=True): """ Read a pyarrow.Table from Feather format Parameters ---------- source : str file path, or file-like object columns : sequence, optional Only read a specific set of columns. If not provided, all columns are read. memo...
28,405
def save_classnames_in_image_maxcardinality( rgb_img, label_img, id_to_class_name_map, font_color=(0, 0, 0), save_to_disk: bool = False, save_fpath: str = "" ) -> np.ndarray: """ Args: rgb_img label_img id_to_class_name_map: Mapping[int,str] Returns: rgb_img """ ...
28,406
def yolo2lite_mobilenet_body(inputs, num_anchors, num_classes, alpha=1.0): """Create YOLO_V2 Lite MobileNet model CNN body in Keras.""" mobilenet = MobileNet(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha) print('backbone layers number: {}'.format(len(mobilenet.layers))) # inpu...
28,407
def test_init_no_resume_file(flow_sampler, tmp_path, resume): """Test the init method when there is no run to resume from""" model = MagicMock() output = tmp_path / 'init' output.mkdir() output = str(output) resume = resume exit_code = 131 max_threads = 2 resume_file = 'test.pkl' ...
28,408
def from_pandas( X: pd.DataFrame, max_iter: int = 100, h_tol: float = 1e-8, w_threshold: float = 0.0, tabu_edges: List[Tuple[str, str]] = None, tabu_parent_nodes: List[str] = None, tabu_child_nodes: List[str] = None, ) -> StructureModel: """ Learn the `StructureModel`, the graph stru...
28,409
def conv_seq_to_sent_symbols(seq, excl_symbols=None, end_symbol='.', remove_end_symbol=True): """ Converts sequences of tokens/ids into a list of sentences (tokens/ids). :param seq: list of tokens/ids. :param excl_symbols: tokens/ids which should be excluded from the final ...
28,410
def emphasize_match(seq, line, fmt='__{}__'): """ Emphasize the matched portion of string. """ indices = substr_ind(seq.lower(), line.lower(), skip_spaces=True) if indices: matched = line[indices[0]:indices[1]] line = line.replace(matched, fmt.format(matched)) return line
28,411
def param_value(memory, position, mode): """Get the value of a param according to its mode""" if mode == 0: # position mode return memory[memory[position]] elif mode == 1: # immediate mode return memory[position] else: raise ValueError("Unknown mode : ", mode)
28,412
def check_array_shape(inp: np.ndarray, dims: tuple, shape_m1: int, msg: str): """check if inp shape is allowed inp: test object dims: list, list of allowed dims shape_m1: shape of lowest level, if 'any' allow any shape msg: str, error msg """ if inp.ndim in dims: if inp.shape[-1] == ...
28,413
def Implies(p, q, simplify=True, factor=False): """Factory function for Boolean implication expression.""" p = Expression.box(p) q = Expression.box(q) expr = ExprImplies(p, q) if factor: expr = expr.factor() elif simplify: expr = expr.simplify() return expr
28,414
def install_local_rpm(rpm_file, logger): """ install a local rpm file :param rpm_file: path to the file :param logger: rs log obj :return: """ if check_local_rpm(rpm_file, logger): logger.trace("{} RPM already installed. Do nothing.", rpm_file) else: command = "yum -y install {}".format(rpm_file) logger....
28,415
def r_power(r_amp): """Return the fraction of reflected power. Parameters ---------- r_amp : float The net reflection amplitude after calculating the transfer matrix. Returns ------- R : numpy array The model reflectance """ return np.abs(r_amp)**2
28,416
def wrap_get_server(layer_name, func): """ Wrapper for memcache._get_server, to read remote host on all ops. This relies on the module internals, and just sends an info event when this function is called. """ @wraps(func) # XXX Not Python2.4-friendly def wrapper(*f_args, **f_kwargs): re...
28,417
def shape(batch) -> (int, int): """Get count of machine/tasks of a batch""" return len(batch), len(batch[0])
28,418
def uniprot_mappings(query: Union[str, List[str]], map_from: str = 'ID', map_to: str = 'PDB_ID', ) -> pd.DataFrame: """Map identifiers using the UniProt identifier mapping tool. :param query: list or space delimited string of identifiers :param...
28,419
def build_property_filter_spec(client_factory, property_specs, object_specs): """Builds the property filter spec. :param client_factory: factory to get API input specs :param property_specs: property specs to be collected for filtered objects :param object_specs: object specs to identify objects to be ...
28,420
def get_user_name_from_token(): """Extract user name and groups from ID token returns: a tuple of username and groups """ curl = _Curl() token_info = curl.get_token_info() try: return token_info['name'], token_info['groups'], token_info['preferred_username'] except Exce...
28,421
def write_gro(filename: str, positions: np.array, simulation_cell: np.array): """ Write out one frame in a GROMACS trajectory. residue number (5 positions, integer) residue name (5 characters) atom name (5 characters) atom number (5 positions, integer) position (in nm, x y z in 3 columns, e...
28,422
def plotPanel(ax,image,units='',extent=None,colorbar=False,cblabel=None,title='',cmap=plt.cm.viridis,contours=None,interpolation='bicubic',**kwargs): """Plot a single panel. To be called from :func:`multiplot() (see docstring there).` """ # what kind of animal is 'image'? cls = None try: ...
28,423
def prob17(limit=1000): """ If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do n...
28,424
def mask_orbit_start_and_end(time, flux, orbitgap=1, expected_norbits=2, orbitpadding=6/(24), raise_error=True): """ Ignore the times near the edges of orbits. args: time, flux returns: time, flux: with `orbitpadding` days trimmed out """ norbits, gr...
28,425
def cast_args(args): """The numbers are stored as strings via doctopt. Convert them to numbers.""" for key, val in args.items(): if key.startswith('--') and isinstance(val, str): args[key] = _string_to_num(val)
28,426
def to_cnf(expr): """ Convert a propositional logical sentence s to conjunctive normal form. That is, of the form ((A | ~B | ...) & (B | C | ...) & ...) Examples ======== >>> from sympy.logic.boolalg import to_cnf >>> from sympy.abc import A, B, D >>> to_cnf(~(A | B) | D) And(Or(D,...
28,427
def plot_contours_for_all_classes(sample: Sample, segmentation: np.ndarray, foreground_class_names: List[str], result_folder: Path, result_prefix: str = "", ...
28,428
def match_gadgets_phasepoly(g: BaseGraph[VT,ET]) -> List[MatchPhasePolyType[VT]]: """Finds groups of phase-gadgets that act on the same set of 4 vertices in order to apply a rewrite based on rule R_13 of the paper *A Finite Presentation of CNOT-Dihedral Operators*.""" targets: Dict[VT,Set[FrozenSet[VT]]] =...
28,429
def get_replaceid(fragment): """get replace id for shared content""" replaceid=re.findall(r":[A-z]+:\s(.+)", fragment)[0] return replaceid
28,430
def _tower_fn(is_training, weight_decay, feature, label, data_format, num_layers, batch_norm_decay, batch_norm_epsilon): """Build computation tower (Resnet). Args: is_training: true if is training graph. weight_decay: weight regularization strength, a float. feature: a Tensor. ...
28,431
def DiscRate(t, dur): """Discount rates for the outer projection""" return scen.DiscRate(dur) + DiscRateAdj(t)
28,432
def outlierDivergence(dist1, dist2, alpha): """Defines difference between how distributions classify outliers. Choose uniformly from Distribution 1 and Distribution 2, and then choose an outlier point according to the induced probability distribution. Returns the probability that said point would ...
28,433
def load_data(root_path, data_path): """ :param root_path: root path of data :param data_path: name of data :return: datas, labels: arrays which are normalized label_dict """ path = os.path.join(root_path, data_path) f = open(path, 'r') label_dict = {} labels = [] d...
28,434
def getCP2KBasisFromPlatoOrbitalGauPolyBasisExpansion(gauPolyBasisObjs, angMomVals, eleName, basisNames=None, shareExp=True, nVals=None): """ Gets a BasisSetCP2K object, with coefficients normalised, from an iter of GauPolyBasis objects in plato format Args: gauPolyBasisObjs: (iter plato_pylib GauPolyBasis object...
28,435
def longitude_to_utm_epsg(longitude): """ Return Proj4 EPSG for a given longitude in degrees """ zone = int(math.floor((longitude + 180) / 6) + 1) epsg = '+init=EPSG:326%02d' % (zone) return epsg
28,436
def updateBarDone(outputlabel): """ Overwrite the previous message in stdout with the tag "Done" and a new message. Parameters: outputlabel - Required: Message to be printed (str) progressbar - Optional: Set True if the previous message was the progress bar (bool) """ print(("[ "+...
28,437
def SupportVectorRegression(X_train, X_test, y_train, y_test, search, save=False): """ Support Vector Regression. Can run a grid search to look for the best parameters (search=True) and save the model to a file (save=True). """ if search: # parameter values over which we will se...
28,438
def conv_relu_pool(X, conv_params, pool_params): """ Initializes weights and biases and does a 2d conv-relu-pool """ # Initialize weights W = tf.Variable( tf.truncated_normal(conv_params, stddev=0.1) ) b = tf.constant(0.1, shape=conv_params['shape']) conv = tf.nn.conv2d(X, W,...
28,439
def compute_node_depths(tree): """Returns a dictionary of node depths for each node with a label.""" res = {} for leaf in tree.leaf_node_iter(): cnt = 0 for anc in leaf.ancestor_iter(): if anc.label: cnt += 1 res[leaf.taxon.label] = cnt return res
28,440
def create_device(hostname, address, username="root", password=""): """Create and return a DeviceInfo struct.""" return DeviceInfo(hostname, address, username, password)
28,441
def max_box(box1, box2): """ return the maximum of two bounding boxes """ ext = lambda values: min(values) if sum(values) <= 0 else max(values) return tuple(tuple(ext(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2))
28,442
def homogenize(a, w=1.0): """ Example: a=[ [a00, a01], [a10, a11], [a20, a21] ], w=1 -> result=[ [a00, a01, w], [a10, a11, w], [a20, a21, w] ] """ return np.hstack([a, np.full((len(a), 1), w,...
28,443
def find_similar_term(term, dictionary): """ Returns a list of terms similar to the given one according to the Damerau-Levenshtein distance https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance """ return list(filter(lambda t: textdistance.damerau_levenshtein.distance(t, term) <= 2, di...
28,444
def check_fields(cls, model, opts, label, fields): """ Checks that fields listed on fields refers to valid model fields on model parameter """ model_fields = [f.name for f in opts.fields] for field in fields: if not field in model_fields: raise ImproperlyConfigured('"%s.%s" refers to...
28,445
def calc_sign(string): """str/any->str return MD5. From: Biligrab, https://github.com/cnbeining/Biligrab MIT License""" return str(hashlib.md5(str(string).encode('utf-8')).hexdigest())
28,446
def compile_circuit( circuit: cirq.Circuit, *, device: cirq.google.xmon_device.XmonDevice, compiler: Callable[[cirq.Circuit], cirq.Circuit] = None, routing_algo_name: Optional[str] = None, router: Optional[Callable[..., ccr.SwapNetwork]] = None, ) -> Tuple[cirq.Circuit, D...
28,447
def remove_prefix(utt, prefix): """ Check that utt begins with prefix+" ", and then remove. Inputs: utt: string prefix: string Returns: new utt: utt with the prefix+" " removed. """ try: assert utt[: len(prefix) + 1] == prefix + " " except AssertionError as e: ...
28,448
def table(command): """ Creates a report with a heading and a line of output showing the average, maximum, and minimum temperatures for EACH period within the period specfied in the command. """ #format of print from instruction pdf print("{:>12} {:>5} {:>5} {:>5}".format('Period', 'Avg', ...
28,449
def format_ucx(name, idx): """ Formats a name and index as a collider """ # one digit of zero padding idxstr = str(idx).zfill(2) return "UCX_%s_%s" % (name, idxstr)
28,450
def get_connection(): """ Return a connection to the database and cache it on the `g` object. Generally speaking, each app context has its own connection to the database; these are destroyed when the app context goes away (ie, when the server is done handling that request). """ if 'db_conne...
28,451
def first_location_of_minimum(x): """ Returns the first location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: pandas.Series :return: the value of this feature :return type: float """ x...
28,452
def _positive_int(integer_string, strict=False, cutoff=None): """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret == -1: return -1 if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: return min(ret, cutoff) return ...
28,453
def x1_0_mult(guess, slip): """ Compute x1_0 element-wise :param guess: (np.array) [odds] :param slip: (np.array) [odds] :return: np.array """ return ((1.0+guess)/(guess*(1.0+slip)))/x0_mult(guess,slip)
28,454
def compute_bootstrap_distribution(exp): """ Computes bootstrap distributions for alpha and beta band power for all three stimulation conditions. For each condition, it loads that condition's raw tfr and pre-computed bootstrap sampled indices. It then runs through each re-sampled index and computes...
28,455
def get_xblock_app_config(): """ Get whichever of the above AppConfig subclasses is active. """ return apps.get_app_config(XBlockAppConfig.label)
28,456
def remove_experiment_requirement(request, object_id, object_type): """Removes the requirement from the experiment, expects requirement_id (PK of req object) to be present in request.POST""" if request.POST: assert 'requirement_id' in request.POST requirement_id = request.POST['requirement_i...
28,457
def _k_hot_from_label_names(labels: List[str], symbols: List[str]) -> List[int]: """Converts text labels into symbol list index as k-hot.""" k_hot = [0] * len(symbols) for label in labels: try: k_hot[symbols.index(label)] = 1 except IndexError: raise ValueError( 'Label %s did not app...
28,458
def upload(training_dir, algorithm_id=None, writeup=None, api_key=None, ignore_open_monitors=False): """Upload the results of training (as automatically recorded by your env's monitor) to OpenAI Gym. Args: training_dir (Optional[str]): A directory containing the results of a training run. a...
28,459
def partition_analysis(analysis: str) -> Tuple[List[FSTTag], FSTLemma, List[FSTTag]]: """ :return: the tags before the lemma, the lemma itself, the tags after the lemma :raise ValueError: when the analysis is not parsable. >>> partition_analysis('PV/e+fakeword+N+I') (['PV/e'], 'fakeword', ['N', 'I'...
28,460
def test_world_extent_mixed_flipped(): """Test world extent after adding data with a flip.""" # Flipped data results in a negative scale value which should be # made positive when taking into consideration for the step size # calculation np.random.seed(0) layers = LayerList() layer = Image(...
28,461
def add_representer(data_type, representer, Dumper=Dumper): """ Add a representer for the given type. Representer is a function accepting a Dumper instance and an instance of the given data type and producing the corresponding representation node. """ Dumper.add_representer(data_type, representer)
28,462
def dummy_dictionary( dummy_tokens=3, additional_token_list=None, dictionary_cls=pytorch_translate_dictionary.Dictionary, ): """First adds the amount of dummy_tokens that you specify, then finally the additional_token_list, which is a list of string token values""" d = dictionary_cls() for i...
28,463
def lies_in_epsilon(x: Num, c: Num, e: Num) -> bool: """ Функция проверки значения x на принадлежность отрезку выда [c - e, c + e]. :param x: значение :param c: значение попадание в epsilon-окрестность которого необходимо проверить :param e: epsilon-окрестность вокруг значения c :return: True - ...
28,464
def decimal_to_digits(decimal, min_digits=None): """ Return the number of digits to the first nonzero decimal. Parameters ----------- decimal: float min_digits: int, minimum number of digits to return Returns ----------- digits: int, number of digits to the first nonzero decima...
28,465
def test_remove_identity_key_with_valid_application_input(): """ Given: - Dictionary with three nested objects which the creator type is "application" When - When Parsing outputs to context Then - Dictionary to remove to first key and add it as an item in the dictionary """ ...
28,466
def lcs(a, b): """ Compute the length of the longest common subsequence between two sequences. Time complexity: O(len(a) * len(b)) Space complexity: O(min(len(a), len(b))) """ # This is an adaptation of the standard LCS dynamic programming algorithm # tweaked for lower memory consumpt...
28,467
def sync_blocks(rpc_connections, *, wait=1, timeout=60, logger=None): """ Wait until everybody has the same tip. sync_blocks needs to be called with an rpc_connections set that has least one node already synced to the latest, stable tip, otherwise there's a chance it might return before all nodes a...
28,468
def paginate_years(year): """Return a list of years for pagination""" START_YEAR = 2020 # first year that budgets were submitted using this system y = int(year) return (START_YEAR, False, y-1, y, y+1, False, settings.CURRENT_YEAR)
28,469
def gene_rooflines_old(): """Obsolete. Based on Kai's Jupyter notebook timings and estimated values, before having measured results from NCU.""" labels = ['dgdxy ij_deriv', 'dgdxy update_rhs', 'dgdxy fused', 'dzv'] time = [1.04e-3, 1.287e-3, 1.091e-3, 1.258e-3] flops = [396361728, 132120576, 52...
28,470
def create(self, node=None): """Test the RBAC functionality of the `CREATE LIVE VIEW` command.""" Scenario( run=create_without_create_view_privilege, setup=instrument_clickhouse_server_log ) Scenario( run=create_with_create_view_privilege_granted_directly_or_via_role, setup=instr...
28,471
def wait_for_service_tasks_state( service_name, expected_task_count, expected_task_states, timeout_sec=120 ): """ Returns once the service has at least N tasks in one of the specified state(s) :param service_name: the service name :type service_name: str :par...
28,472
def eval_add(lst): """Evaluate an addition expression. For addition rules, the parser will return [number, [[op, number], [op, number], ...]] To evaluate that, we start with the first element of the list as result value, and then we iterate over the pairs that make up the rest of the list, adding or subtracti...
28,473
def run_cmd(cmdStr): """ 用shell运行命令,并检查命令返回值。 仔细检查cmdStr,以避免可能存在的安全问题。 """ cmdProc = subprocess.Popen( cmdStr, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = cmdProc.communicate() # check command return if (0 != cmdProc.re...
28,474
def is_password_valid(plaintextpw: str, storedhash: str) -> bool: """ Checks if a plaintext password matches a stored hash. Uses ``bcrypt``. The stored hash includes its own incorporated salt. """ # Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the # VARCHAR was retrieved as U...
28,475
def find_item(item_to_find, items_list): """ Returns True if an item is found in the item list. :param item_to_find: item to be found :param items_list: list of items to search in :return boolean """ is_found = False for item in items_list: if (item[1] == item_to_find[1]) and m...
28,476
def init_output_masks_in_graph(graph: NNCFGraph, nodes: List): """ Initialize masks in groph for mask propagation algorithm :param graph: NNCFNetwork :param nodes: list with pruned nodes """ for node in graph.get_all_nodes(): node.data.pop('input_masks', None) node.data.pop('out...
28,477
def set_cron_job_schedule(cron_tpl: Dict[str, Any], schedule: str) -> NoReturn: """ Set the cron job schedule, if specifed, otherwise leaves default schedule """ if not schedule: return cron_spec = cron_tpl.setdefault("spec", {}) cron_spec["schedule"] = schedule
28,478
def validate_target_types(target_type): """ Target types validation rule. Property: SecretTargetAttachment.TargetType """ VALID_TARGET_TYPES = ( "AWS::RDS::DBInstance", "AWS::RDS::DBCluster", "AWS::Redshift::Cluster", "AWS::DocDB::DBInstance", "AWS::DocDB::DB...
28,479
def find_prefixed(root, prefix): """finds all elements in root that begin with the prefix, case insensitive""" l_prefix = prefix.lower() for x in root.iterdir(): if x.name.lower().startswith(l_prefix): yield x
28,480
def cprint(*objects, **kwargs): """Apply Color formatting to output in terminal. Same as builtin print function with added 'color' keyword argument. eg: cprint("data to print", color="red", sep="|") available colors: black red green yellow blue pink cyan white no-colo...
28,481
def handle_authbuf(tsuite, ssh, res_type): """Deals with the transfer of authbuf keys. Returns True if the authbuf key needs to be pulled after lauching this object Args: tsuite: tsuite runtime. ssh: remote server connection res_type: slash2 resource type.""" if not hasattr(tsuite, "authbuf_ob...
28,482
def clean(tokens: List[str]) -> List[str]: """ Returns a list of unique tokens without any stopwords. Input(s): 1) tokens - List containing all tokens. Output(s): 1) unique_tokens - List of unique tokens with all stopwords removed. """ # handle alphanumeric stri...
28,483
def current_sessions(macfile): """ Show currently open sessions """ state, mac_to_name = read_state(macfile) data = [] for mac in state['macs']: try: name = mac_to_name[mac] except KeyError: name = '-' # (unknown) info = state['macs'][mac][-1] ...
28,484
def validate_file_submission(): """Validate the uploaded file, returning the file if so.""" if "sourceFile" not in flask.request.files: raise util.APIError(400, message="file not provided (must " "provide as uploadFile).") # Save to GCloud uploaded_file ...
28,485
def oauth_redirect(request, consumer_key=None, secret_key=None, request_token_url=None, access_token_url=None, authorization_url=None, callback_url=None, parameters=None): """ View to handle the OAuth based authentication redirect to the service provider """ request.session['next'] = get_login_r...
28,486
def get_service_url(): """Return the root URL of this service.""" if 'SERVICE_URL' in os.environ: return os.environ['SERVICE_URL'] # the default location for each service is /api/<service> return '/api/{}'.format(get_service_name())
28,487
def read_stats(stats): """ Read rsync stats and print a summary :param stats: String :return: """ if system.config['verbose']: print(f'{output.Subject.DEBUG}{output.CliFormat.BLACK}{stats}{output.CliFormat.ENDC}') _file_number = parse_string(stats, r'Number of regular files transfer...
28,488
def to_hdf(data_dict, tgt, attrs=None, overwrite=True, warn=True): """Store a (possibly nested) dictionary to an HDF5 file or branch node within an HDF5 file (an h5py Group). This creates hardlinks for duplicate non-trivial leaf nodes (h5py Datasets) to minimize storage space required for redundant dat...
28,489
def render_template(content, context): """Render templates in content.""" # Fix None issues if context.last_release_object is not None: prerelease = context.last_release_object.prerelease else: prerelease = False # Render the template try: render = Template(content) ...
28,490
def isJacobianOnS256Curve(x, y, z): """ isJacobianOnS256Curve returns boolean if the point (x,y,z) is on the secp256k1 curve. Elliptic curve equation for secp256k1 is: y^2 = x^3 + 7 In Jacobian coordinates, Y = y/z^3 and X = x/z^2 Thus: (y/z^3)^2 = (x/z^2)^3 + 7 y^2/z^6 = x^3/z^6 + 7 y^2 = x^3 + 7*z^6 """ fv...
28,491
def decode_base85(encoded_str): """Decodes a base85 string. The input string length must be a multiple of 5, and the resultant binary length is always a multiple of 4. """ if len(encoded_str) % 5 != 0: raise ValueError('Input string length is not a multiple of 5; ' + ...
28,492
def process_doc(doc: PDFDocument): """Process PDF Document, return info and metadata. Some PDF store infomations such as title in field info, some newer PDF sotre them in field metadata. The processor read raw XMP data and convert to dictionary. Parameters ---------- doc : PDFDocument ...
28,493
def are_expected_items_in_list(test_case, actual_list, *expected_items): """ Checks whether the expected items are in the given list and only those are in the list. Parameters ---------- test_case : unittest.TestCase The test case that provides assert methods. actual_list : list of obje...
28,494
def main(): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger = logging.getLogger(__name__) logger.info('making final data set from raw data') c = Config() url = c.read('DATA', 'url') urls = get_...
28,495
def score_lin_reg(est, X, y, sample_weight=None, level=1): """ Scores a fitted linear regression model. Parameters ----------- est: The fitted estimator. X: array-like, shape (n_samples, n_features) The test X data. y_true: array-like, shape (n_samples, ) The true ...
28,496
def test_write_log_file(): """Test writing to a log file """ sample_target = { 'new_val': { 'Location': '192.168.1.3', 'Optional': { 'init': '' }, 'PluginName': 'Harness', 'Port': '9800', 'id': '059ed5fc-0263-42b0-962d-7258003fd53a' }, 'old_val': None, 'ts': 15 } sample_job = { 'new...
28,497
def listen(): """ Connect to Twitter and listen tweets with PrintingListener """ api = get_api() listener = PrintingListener(api) stream = tweepy.Stream(auth=api.auth, listener=listener, tweet_mode='extended') print("Listening to Twitter API.. (to stop press Ctrl-C)") stream.filter(track=liste...
28,498
def test_help(): """Passing -h or --help => print help text.""" assert run(["rm", "-h"]).stdout.split(" ")[0] == "Usage:" assert run(["rm", "--help"]).stdout.split(" ")[0] == "Usage:" assert run(["rm", "-h"]).returncode > 0 assert run(["rm", "--help"]).returncode > 0
28,499