content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def sin(c): """ sin(a+x)= sin(a) cos(x) + cos(a) sin(x) """ if not isinstance(c,pol): return math.sin(c) a0,p=c.separate(); lst=[math.sin(a0),math.cos(a0)] for n in range(2,c.order+1): lst.append( -lst[-2]/n/(n-1)) return phorner(lst,p)
a6ec312df4362c130343133dae9a09b377f56cf5
10,700
def _calc_metadata() -> str: """ Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. """ if not is_appveyor: ...
ccbd4912622808b5845d8e30546d6eb27e299342
10,701
import functools def authorization_required(func): """Returns 401 response if user is not logged-in when requesting URL with user ndb.Key in it or Returns 403 response if logged-in user's ndb.Key is different from ndb.Key given in requested URL. """ @functools.wraps(func) def decorated_function(*p...
12c0d645b0b26bf419e413866afaf1b4e7a19869
10,702
import torch def pad_col(input, val=0, where='end'): """Addes a column of `val` at the start of end of `input`.""" if len(input.shape) != 2: raise ValueError(f"Only works for `phi` tensor that is 2-D.") pad = torch.zeros_like(input[:, :1]) if val != 0: pad = pad + val if where == '...
77caa028bb76da922ba12492f077811d2344c2a9
10,703
from typing import List import itertools def seats_found_ignoring_floor(data: List[List[str]], row: int, col: int) -> int: """ Search each cardinal direction util we hit a wall or a seat. If a seat is hit, determine if it's occupied. """ total_seats_occupied = 0 cardinal_direction_operations ...
e5442d757df6304da42f817c975969723ad0abca
10,704
def product_design_space() -> ProductDesignSpace: """Build a ProductDesignSpace for testing.""" alpha = RealDescriptor('alpha', lower_bound=0, upper_bound=100, units="") beta = RealDescriptor('beta', lower_bound=0, upper_bound=100, units="") gamma = CategoricalDescriptor('gamma', categories=['a', 'b', '...
93468cc7aaeb6a6bf7453d2f3e974bc28dece31f
10,705
def compute_percents_of_labels(label): """ Compute the ratio/percentage size of the labels in an labeled image :param label: the labeled 2D image :type label: numpy.ndarray :return: An array of relative size of the labels in the image. Indices of the sizes in the array \ is corresponding to the...
6dfe34b7da38fa17a5aa4e42acc5c812dd126f77
10,706
def removepara(H,M,Hmin = '1/2',Hmax = 'max',output=-1,kwlc={}): """ Retrieve lineal contribution to cycle and remove it from cycle. **H** y **M** corresponds to entire cycle (two branches). I.e. **H** starts and ends at the same value (or an aproximate value). El ciclo M vs H se separa ...
1d70c60f60b3ab7b976a0ec12a3541e5a7e53426
10,707
def flush(): """ Remove all mine contents of minion. :rtype: bool :return: True on success CLI Example: .. code-block:: bash salt '*' mine.flush """ if __opts__["file_client"] == "local": return __salt__["data.update"]("mine_cache", {}) load = { "cmd": "_m...
fe7d120362393fcb4380473cdaf76e153646644a
10,708
def polygon_to_shapely_polygon_wkt_compat(polygon): """ Convert a Polygon to its Shapely Polygon representation but with WKT compatible coordinates. """ shapely_points = [] for location in polygon.locations(): shapely_points.append(location_to_shapely_point_wkt_compat(location)) ret...
54c889d2071cc8408c2bb4b739a30c3458c80f4c
10,709
import six def ccd_process(ccd, oscan=None, trim=None, error=False, masterbias=None, bad_pixel_mask=None, gain=None, rdnoise=None, oscan_median=True, oscan_model=None): """Perform basic processing on ccd data. The following steps can be included: * overscan corr...
610a53693ff84ba2e1a68662dd0a19e55228c129
10,710
def get_role_keyids(rolename): """ <Purpose> Return a list of the keyids associated with 'rolename'. Keyids are used as identifiers for keys (e.g., rsa key). A list of keyids are associated with each rolename. Signing a metadata file, such as 'root.json' (Root role), involves signing or verifyin...
4888a09740560d760bfffe9eecd50bfa67ff0613
10,711
def _DX(X): """Computes the X finite derivarite along y and x. Arguments --------- X: (m, n, l) numpy array The data to derivate. Returns ------- tuple Tuple of length 2 (Dy(X), Dx(X)). Note ---- DX[0] which is derivate along y has shape (m-1, n, l). DX[1] ...
4aff05c2c25089c9f93b762a18dad42b0142db09
10,712
def load_spectra_from_dataframe(df): """ :param df:pandas dataframe :return: """ total_flux = df.total_flux.values[0] spectrum_file = df.spectrum_filename.values[0] pink_stride = df.spectrum_stride.values[0] spec = load_spectra_file(spectrum_file, total_flux=total_flux, ...
31d1cbbee8d999dac5ee0d7f8d4c71f7f58afc3b
10,713
def included_element(include_predicates, exclude_predicates, element): """Return whether an index element should be included.""" return (not any(evaluate_predicate(element, ep) for ep in exclude_predicates) and (include_predicates == [] or any(evaluate_predicate(elem...
00e0d66db26e8bca7e3cb8505596247065422cb6
10,714
def _insertstatushints(x): """Insert hint nodes where status should be calculated (first path) This works in bottom-up way, summing up status names and inserting hint nodes at 'and' and 'or' as needed. Thus redundant hint nodes may be left. Returns (status-names, new-tree) at the given subtree, where ...
956fe03a7f5747f93034501e63cc31ff2956c2d6
10,715
def make_sine(freq: float, duration: float, sr=SAMPLE_RATE): """Return sine wave based on freq in Hz and duration in seconds""" N = int(duration * sr) # Number of samples return np.sin(np.pi*2.*freq*np.arange(N)/sr)
622b03395da5d9f8a22ac0ac30282e23d6596055
10,716
def _widget_abbrev(o): """Make widgets from abbreviations: single values, lists or tuples.""" float_or_int = (float, int) if isinstance(o, (list, tuple)): if o and all(isinstance(x, string_types) for x in o): return DropdownWidget(values=[unicode_type(k) for k in o]) elif _matche...
f5a57f2d74811ff21ea56631fd9fb22fea4ae91f
10,717
def get_conditions(): """ List of conditions """ return [ 'blinded', 'charmed', 'deafened', 'fatigued', 'frightened', 'grappled', 'incapacitated', 'invisible', 'paralyzed', 'petrified', 'poisoned', 'prone', ...
816ccb50581cafa20bdefed2a075a3370704cef4
10,718
def negative_predictive_value(y_true: np.array, y_score: np.array) -> float: """ Calculate the negative predictive value (duplicted in :func:`precision_score`). Args: y_true (array-like): An N x 1 array of ground truth values. y_score (array-like): An N x 1 array of predicted values. R...
28f1d4fce76b6201c6dbeb99ad19337ca84b74c5
10,719
def flat_list(*alist): """ Flat a tuple, list, single value or list of list to flat list e.g. >>> flat_list(1,2,3) [1, 2, 3] >>> flat_list(1) [1] >>> flat_list([1,2,3]) [1, 2, 3] >>> flat_list([None]) [] """ a = [] for x in alist: if x is None: ...
5a68495e507e9a08a9f6520b83a912cf579c6688
10,720
from typing import List def do_regression(X_cols: List[str], y_col: str, df: pd.DataFrame, solver='liblinear', penalty='l1', C=0.2) -> LogisticRegression: """ Performs regression. :param X_cols: Independent variables. :param y_col: Dependent variable. :param df: Data frame. ...
8a65d49e64e96b3fc5271545afe1761382ec1396
10,721
def gaussian_smooth(var, sigma): """Apply a filter, along the time dimension. Applies a gaussian filter to the data along the time dimension. if the time dimension is missing, raises an exception. The DataArray that is returned is shortened along the time dimension by sigma, half of sigma on ...
809ec7b135ab7d915dd62ad10baea71bfd146e34
10,722
import logging def make_ood_dataset(ood_dataset_cls: _BaseDatasetClass) -> _BaseDatasetClass: """Generate a BaseDataset with in/out distribution labels.""" class _OodBaseDataset(ood_dataset_cls): """Combine two datasets to form one with in/out of distribution labels.""" def __init__( self, ...
c1c26206e352932d3a5397f047365c8c5c8b7fa7
10,723
def _title_case(value): """ Return the title of the string but the first letter is affected. """ return value[0].upper() + value[1:]
037bce973580f69d87c2e3b4e016b626a2b76abb
10,724
import requests def zoom_api_call(user, verb, url, *args, **kwargs): """ Perform an API call to Zoom with various checks. If the call returns a token expired event, refresh the token and try the call one more time. """ if not settings.SOCIAL_AUTH_ZOOM_OAUTH2_KEY: raise DRFValidationEr...
5c359a4a7acd69a942aedcb78fc156b8218ab239
10,725
import os def copy_javascript(name): """Return the contents of javascript resource file.""" # TODO use importlib_resources to access javascript file content folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "js") with open(os.path.join(folder, name + ".js")) as fobj: content =...
927a9a87c3590f76b00f3a1085de4c6e103eeeff
10,726
def addHtmlImgTagExtension(notionPyRendererCls): """A decorator that add the image tag extension to the argument list. The decorator pattern allows us to chain multiple extensions. For example, we can create a renderer with extension A, B, C by writing: addAExtension(addBExtension(addCExtension(noti...
914d2395cdf9c5f52f94eef80e3f7469a70eb0ae
10,727
def mechaber(mechaber_name): """Route function for visualizing and exploring Mechabrim.""" mechaber = Mechaber.query.filter_by(mechaber_name=mechaber_name).first_or_404() # page = request.args.get("page", 1, type=int) # mekorot = sefer.mekorot.order_by(Makor.ref).paginate( # page, current_app.co...
56e1b0130ec3f14c389c8d1e4e31fe500cd3a5d3
10,728
def get_symmetry_projectors(character_table, conjugacy_classes, print_results=False): """ :param character_table: each row gives the characters of a different irreducible rep. Each column corresponds to a different conjugacy classes :param conjugacy_classes: List of lists of conjugacy class elements ...
8780ef1a9ebb3f6e6960d04d07677e323e7565b9
10,729
from typing import List def is_permutation_matrix(matrix: List[List[bool]]) -> bool: """Returns whether the given boolean matrix is a permutation matrix.""" return (all(sum(v) == 1 for v in matrix) and sum(any(v) for v in matrix) == len(matrix))
b53d6f4ba6e8e1ba445783350de831b614aa187e
10,730
import torch def DPT_Hybrid(pretrained=True, **kwargs): """ # This docstring shows up in hub.help() MiDaS DPT-Hybrid model for monocular depth estimation pretrained (bool): load pretrained weights into model """ model = DPTDepthModel( path=None, backbone="vitb_rn50_384", n...
0a5cb661e9e0f08daae73b8c49ba8324e0cfb3e9
10,731
def show_counts(input_dict): """Format dictionary count information into a string Args: input_dict (dictionary): input keys and their counts Return: string: formatted output string """ out_s = '' in_dict_sorted = {k: v for k, v in sorted(input_dict.items(), key=lambda item...
078d1f7599b22741f474c0e6d1b02f44edfc1f9b
10,732
def encipher_railfence(message,rails): """ Performs Railfence Encryption on plaintext and returns ciphertext Examples ======== >>> from sympy.crypto.crypto import encipher_railfence >>> message = "hello world" >>> encipher_railfence(message,3) 'horel ollwd' Parameters ========...
b1a56cdb255065b18caa4ba6da1fa11759f87152
10,733
import inspect def format_signature(name: str, signature: inspect.Signature) -> str: """Formats a function signature as if it were source code. Does not yet handle / and * markers. """ params = ', '.join( format_parameter(arg) for arg in signature.parameters.values()) if signature.return_...
a14fde11850d420d15d2f9d7f3ac4cbe9aee03cc
10,734
def extract_ratios_from_ddf(ddf): """The same as the df version, but works with dask dataframes instead.""" # we basicaly abuse map_partition's ability to expand indexes for lack of a working # groupby(level) in dask return ddf.map_partitions(extract_ratios_from_df, meta={'path': str, 'ratio': str, ...
fcb816677d3d0816b2327d458a3fdd1b820bac9e
10,735
def check_if_prime(number): """checks if number is prime Args: number (int): Raises: TypeError: if number of type float Returns: [bool]: if number prime returns ,True else returns False """ if type(number) == float: raise TypeError("TypeError: entered float ty...
0a15a4f133b12898b32b1f52a317939cf5e30d34
10,736
import inspect def get_signatures() -> {}: """ Helper method used to identify the valid arguments that can be passed to any of the pandas IO functions used by the program :return: Returns a dictionary containing the available arguments for each pandas IO method """ # Creates an empty dictionar...
243b798e1c4c57a89749fff1d33be660ab4e973b
10,737
import os import json def _load_flags(): """Load flag definitions. It will first attempt to load the file at TINYFLAGS environment variable. If that does not exist, it will then load the default flags file bundled with this library. :returns list: Flag definitions to use. """ path = os.g...
ebf3e78296c2fd8e4590f87f87bd27b9252539f8
10,738
from typing import Optional from typing import Union import os def _get_indentation_option(explicit: Optional[Union[str, int]] = None) -> Optional[str]: """Get the value for the ``indentation`` option. Args: explicit (Optional[Union[str, int]]): the value explicitly specified by user, :da...
ea1cfff674d620d879efec5490bbb13563e47bf4
10,739
from typing import List def batch_answer_same_context(questions: List[str], context: str) -> List[str]: """Answers the questions with the given context. :param questions: The questions to answer. :type questions: List[str] :param context: The context to answer the questions with. :type context: s...
b58df72f1252427ea3e58e2f8379b8e77ea55273
10,740
import torch def complex_multiplication(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Multiplies two complex-valued tensors. Assumes the tensor has a named dimension "complex". Parameters ---------- x : torch.Tensor Input data y : torch.Tensor Input data Returns ...
ed427e8f79c5bcf782da4e1c21b02528a2ccb96d
10,741
import typing def dynamic_embedding_lookup(keys: tf.Tensor, config: de_config_pb2.DynamicEmbeddingConfig, var_name: typing.Text, service_address: typing.Text = "", skip_gradient_update: bool = False, ...
c1d69548e60ff00e55ab04fe83607cae31b6558c
10,742
def register_unary_op(registered_name, operation): """Creates a `Transform` that wraps a unary tensorflow operation. If `registered_name` is specified, the `Transform` is registered as a member function of `Series`. Args: registered_name: the name of the member function of `Series` corresponding to ...
c0fb56a8e93936a4c45e199e28889ccef67d19de
10,743
def add_climatology(data, clim): """Add 12-month climatology to a data array with more times. Suppose you have anomalies data and you want to add back its climatology to it. In this sense, this function does the opposite of `get_anomalies`. Though in this case there is no way to obtain the climatol...
28845fc1455bc317d158b503ed07a7d0c1af5655
10,744
from typing import List def already_exists(statement: str, lines: List[str]) -> bool: """ Check if statement is in lines """ return any(statement in line.strip() for line in lines)
194d8c6c48609f5a2accacdb2ed0857815d48d1d
10,745
import random def uniform(lower_list, upper_list, dimensions): """Fill array """ if hasattr(lower_list, '__iter__'): return [random.uniform(lower, upper) for lower, upper in zip(lower_list, upper_list)] else: return [random.uniform(lower_list, upper_list) fo...
59bcb124f0d71fd6e5890cd1d6c200319ab5910e
10,746
import torch def prepare_data(files, voxel_size, device='cuda'): """ Loads the data and prepares the input for the pairwise registration demo. Args: files (list): paths to the point cloud files """ feats = [] xyz = [] coords = [] n_pts = [] for pc_file in files: ...
1c11444d4f6ca66396651bb49b8c655bedf6b8fa
10,747
def reshape(box, new_size): """ box: (N, 4) in y1x1y2x2 format new_size: (N, 2) stack of (h, w) """ box[:, :2] = new_size * box[:, :2] box[:, 2:] = new_size * box[:, 2:] return box
56fbeac7c785bd81c7964d7585686e11864ff034
10,748
import json def sort_actions(request): """Sorts actions after drag 'n drop. """ action_list = request.POST.get("objs", "").split('&') if len(action_list) > 0: pos = 10 for action_str in action_list: action_id = action_str.split('=')[1] action_obj = Action.object...
80f2042858f7a0ecad3663ae4bf50ad73935be3b
10,749
def fetch_file(parsed_url, config): """ Fetch a file from Github. """ if parsed_url.scheme != 'github': raise ValueError(f'URL scheme must be "github" but is "{parsed_url.github}"') ghcfg = config.get('github') if not ghcfg: raise BuildRunnerConfigurationError('Missing configur...
c688a68aeaa4efa0cda21f3b58a94075e4555004
10,750
import calendar def number_of_days(year: int, month: int) -> int: """ Gets the number of days in a given year and month :param year: :type year: :param month: :type month: :return: :rtype: """ assert isinstance(year, int) and 0 <= year assert isinstance(month, int) and 0 < ...
d585f037292eef36ecc753fbf702035577513a15
10,751
import six import sys def safe_decode(text, incoming=None, errors='strict'): """Decodes incoming str using `incoming` if they're not already unicode. :param incoming: Text's current encoding :param errors: Errors handling policy. See here for valid values http://docs.python.org/2/library/codecs.h...
8bd5a4ef516f925f7967ab50dffff0d7273f547c
10,752
from functools import reduce def medstddev(data, mask=None, medi=False, axis=0): """ This function computes the stddev of an n-dimensional ndarray with respect to the median along a given axis. Parameters: ----------- data: ndarray A n dimensional array frmo wich caculate the median s...
bbab9eede714d7c64344af271f8b6e817723d837
10,753
def load_npz(filename: FileLike) -> JaggedArray: """ Load a jagged array in numpy's `npz` format from disk. Args: filename: The file to read. See Also: save_npz """ with np.load(filename) as f: try: data = f["data"] shape = f["shape"] re...
640add32dab0b7bd12784a7a29331b59521a0f8a
10,754
import re def _egg_link_name(raw_name: str) -> str: """ Convert a Name metadata value to a .egg-link name, by applying the same substitution as pkg_resources's safe_name function. Note: we cannot use canonicalize_name because it has a different logic. """ return re.sub("[^A-Za-z0-9.]+", "-", r...
923ff815b600b95ccb5750a8c1772ee9156e53b2
10,755
def my_view(request): """Displays info details from nabuco user""" owner, c = User.objects.get_or_create(username='nabuco') # Owner of the object has full permissions, otherwise check RBAC if request.user != owner: # Get roles roles = get_user_roles(request.user, owner) # Get ...
55c3443f24d56b6ea22e02c9685d6057dfc79c7e
10,756
def handler500(request): """ Custom 500 view :param request: :return: """ return server_error(request, template_name='base/500.html')
91db9daeaac6f7f6b2207a3c8be7fa09f932b50f
10,757
def get_badpixel_mask(shape, bins): """Get the mask of bad pixels and columns. Args: shape (tuple): Shape of image. bins (tuple): CCD bins. Returns: :class:`numpy.ndarray`: 2D binary mask, where bad pixels are marked with *True*, others *False*. The bad pixels are foun...
2e636aef86d2462815683a975ef99fbcdeeaee19
10,758
def model_fn(nn_last_layer, correct_label, learning_rate, num_classes): """ Build the TensorFLow loss and optimizer operations. :param nn_last_layer: TF Tensor of the last layer in the neural network :param correct_label: TF Placeholder for the correct label image :param learning_rate: TF Placeholde...
d4883d451b749f06c718d37f1a49e4f4709d6695
10,759
import six import yaml def maybe_load_yaml(item): """Parses `item` only if it is a string. If `item` is a dictionary it is returned as-is. Args: item: Returns: A dictionary. Raises: ValueError: if unknown type of `item`. """ if isinstance(item, six.string_types): ...
9288012f0368e2b087c9ef9cd9ffaca483b4f11b
10,760
def histeq(im,nbr_bins=256): """histogram equalize an image""" #get image histogram im = np.abs(im) imhist,bins = np.histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() #cumulative distribution function cdf = 255 * cdf / cdf[-1] #normalize #use linear interpolation of cdf to ...
bbb0e758e519a7cfcc866e3193cd1ff26bf5efbc
10,761
def txgamma(v, t, gamma, H0): """ Takes in: v = values at z=0; t = list of redshifts to integrate over; gamma = interaction term. Returns a function f = [dt/dz, d(a)/dz, d(e'_m)/dz, d(e'_de)/dz, d(...
a1506ea0b54f468fd63cd2a8bd96e8a9c46a92f3
10,762
def text_pb(tag, data, description=None): """Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this summary, ...
43d652ebb9ab1d52c0514407a3c47d56816cbb65
10,763
def sanitize_input(args: dict) -> dict: """ Gets a dictionary for url params and makes sure it doesn't contain any illegal keywords. :param args: :return: """ if "mode" in args: del args["mode"] # the mode should always be detailed trans = str.maketrans(ILLEGAL_CHARS, ' ' * len(ILL...
063d314cb3800d24606b56480ce63b7dda3e8e51
10,764
def sum_to(containers, goal, values_in_goal=0): """ Find all sets of containers which sum to goal, store the number of containers used to reach the goal in the sizes variable. """ if len(containers) == 0: return 0 first = containers[0] remain = containers[1:] if first > goal: ...
db5297929332a05606dec033318ca0d7c9661b1d
10,765
def rt2add_enc_v1(rt, grid): """ :param rt: n, k, 2 | log[d, tau] for each ped (n,) to each vic (k,) modifies rt during clipping to grid :param grid: (lx, ly, dx, dy, nx, ny) lx, ly | lower bounds for x and y coordinates of the n*k (2,) in rt dx, dy | step sizes of the regular grid ...
3af0b8e15fdcc4d9bbeb604faffbd45cf013e86b
10,766
import heapq def draw_with_replacement(heap): """Return ticket drawn with replacement from given heap of tickets. Args: heap (list): an array of Tickets, arranged into a heap using heapq. Such a heap is also known as a 'priority queue'. Returns: the Ticket with the least tick...
06eb982ecf32090da51f02356a6996429773e233
10,767
import requests import platform def is_docker_reachable(docker_client): """ Checks if Docker daemon is running. :param docker_client : docker.from_env() - docker client object :returns True, if Docker is available, False otherwise. """ errors = ( docker.errors.APIError, reques...
9bea3a564d9357c5a700c9abbfaa36564f4b9adf
10,768
def get_string(entry): """ This function ... :param entry: :return: """ value = entry.split(" / ")[0].rstrip() return value
38a1dc41fd06b49aa8724cc783466b485c9017fb
10,769
from typing import Any import string import os import yaml def read_yaml_env(fname: str) -> Any: """Parse YAML file with environment variable substitution. Parameters ---------- fname : str yaml file name. Returns ------- table : Any the object returned by YAML. """ ...
5c3b929bb4b76d2c041b2db92649a62a5d91e61a
10,770
import collections def get_top_words(words): """ Получить список наиболее часто встречающихся слов, с указанием частоты :param words: список слов для анализа :return: [(слово1, количество повторений слова1), ..] """ return collections.Counter(words).most_common()
632317f57e734a93b6f3f20dfef001028b40c6b3
10,771
def get_slope(x, y, L): """ Funcao que retorna o slope da serie temporal dos dados """ try: x=np.array(x).reshape(-1, 1) y=np.array(y).reshape(-1, 1) lr=LinearRegression() lr.fit (x[:L],y[:L]) return lr.coef_[0][0] except: return 0
23f3419049ee1372d5963823e2f52b895bc766e8
10,772
from typing import Dict from typing import Any def _minimize_price(price: Dict[str, Any]) -> Price: """ Return only the keys and values of a price the end user would be interested in. """ keys = ['id', 'recurring', 'type', 'currency', 'unit_amount', 'unit_amount_decimal', 'nickname', 'prod...
7414e0f3e5ae11f55b5781a679e593294122aed2
10,773
def project(signals, q_matrix): """ Project the given signals on the given space. Parameters ---------- signals : array_like Matrix with the signals in its rows q_matrix : array_like Matrix with an orthonormal basis of the space in its rows Returns ------- proj_sig...
0d6aa780d0d424260df5f8391821c806e12c81e5
10,774
def all_movies(): """ Returns all movie in the database for Movies service """ movies = ut.get_movies() if len(movies) == 0: abort(404) return make_response(jsonify({"movies":movies}),200)
d8b2e3a66adf52830d7027953c22071449d2b29a
10,775
def format_map(mapping, st): """ Format string st with given map. """ return st.format_map(mapping)
462e0a744177d125db50739eac1f2e7a62128010
10,776
def communities_greedy_modularity(G,f): """ Adds a column to the dataframe f with the community of each node. The communitys are detected using greedy modularity. G: a networkx graph. f: a pandas dataframe. It works with networkx vesion: '2.4rc1.dev_20190610203526' """ if not(set(f.name...
cfca6ef66730f3a6ef467f1c51c66c5d46296351
10,777
import json def load_loglin_stats(infile_path): """read in data in json format""" # convert all 'stats' to pandas data frames with open(infile_path) as infile: data = json.load(infile) new_data = {} for position_set in data: try: new_key = eval(position_set) ex...
c307ff2cf4e07bbb7843971cceaf74744422276c
10,778
def _simple_logistic_regression(x,y,beta_start=None,verbose=False, CONV_THRESH=1.e-3,MAXIT=500): """ Faster than logistic_regression when there is only one predictor. """ if len(x) != len(y): raise ValueError, "x and y should be the same length!" if beta_start is ...
c37190b167e634df31127f79163aaeb56bac217e
10,779
def preemphasis(signal,coeff=0.95): """perform preemphasis on the input signal. :param signal: The signal to filter. :param coeff: The preemphasis coefficient. 0 is no filter, default is 0.95. :returns: the filtered signal. """ return np.append(signal[0],signal[1:]-coeff*signal[:-1])
c5173708e7b349decd34ac886493103eaadb023d
10,780
from sacremoses import MosesTokenizer from sacremoses import MosesPunctNormalizer def build_moses_tokenizer(tokenizer: MosesTokenizerSpans, normalizer: MosesPunctNormalizer = None) -> Callable[[str], List[Token]]: """ Wrap Spacy model to build a tokenizer for the Sentence class. ...
0dee31ab9030e387dd6907efad60c188eb0241b2
10,781
from typing import Callable from typing import Hashable from typing import Union def horizontal_block_reduce( obj: T_DataArray_or_Dataset, coarsening_factor: int, reduction_function: Callable, x_dim: Hashable = "xaxis_1", y_dim: Hashable = "yaxis_1", coord_func: Union[str, CoordFunc] = coarsen...
07fc497ae8c5cd90699bc73bfbeab705c13ed0c6
10,782
def statements_api(context, request): """List all the statements for a period.""" dbsession = request.dbsession owner = request.owner owner_id = owner.id period = context.period inc_case = case([(AccountEntry.delta > 0, AccountEntry.delta)], else_=None) dec_case = case([(AccountEntry.delta ...
87a1ec3e5fc5730eda30367a5f9f34aef6cf7339
10,783
def fp(x): """Function used in **v(a, b, th, nu, dimh, k)** for **analytic_solution_slope()** :param x: real number :type x: list :return: fp value :rtype: list """ rx = np.sqrt(x * 2 / np.pi) s_fresnel, c_fresnel = sp.fresnel(rx) return - 2 * 1j * np.sqrt(x) * np.exp(-1j * x) * np.s...
202000557fb239e589ffd4d7b9709b60678ab784
10,784
def get_truck_locations(given_address): """ Get the location of the food trucks in Boston TODAY within 1 mile of a given_address :param given_address: a pair of coordinates :return: a list of features with unique food truck locations """ formatted_address = '{x_coordinate}, {y_coordinate}'....
f1d5e290c5c46e1587a2f98c2e82edee3890fc05
10,785
import inspect import warnings def _getRelevantKwds(method, kwds): """return kwd args for the given method, and remove them from the given kwds""" argspec = inspect.getargspec(method) d = dict() for a in kwds: if a not in argspec.args: warnings.warn("Unrecognized kwd: {!r}".format(...
bca410b99e750f233a5e4476413e6bacfa52dcb9
10,786
import requests def find_overview_details(park_code): """ Find overview details from park code """ global API_KEY fields = "&fields=images,entranceFees,entrancePasses,operatingHours,exceptions" url = "https://developer.nps.gov/api/v1/parks?parkCode=" + park_code + "&api_key=" + API_KEY + fields ...
95cf281828154c45eae1e239f33d2de8bcf9e7fa
10,787
import torch def embed_nomenclature( D, embedding_dimension, loss="rank", n_steps=1000, lr=10, momentum=0.9, weight_decay=1e-4, ignore_index=None, ): """ Embed a finite metric into a target embedding space Args: D (tensor): 2D-cost matrix of the finite metric ...
1e9ca98dec0c3e42af0af483b6e9ef9efa11b225
10,788
def raw_env(): """ To support the AEC API, the raw_env() function just uses the from_parallel function to convert from a ParallelEnv to an AEC env """ env = parallel_env() env = parallel_to_aec(env) return env
dcb491c2beb50f73ba0fdab96bcd069916ce9b6d
10,789
def cmd_line(preprocessor: Preprocessor, args: str) -> str: """the line command - prints the current line number""" if args.strip() != "": preprocessor.send_warning("extra-arguments", "the line command takes no arguments") context = preprocessor.context.top pos = context.true_position(preprocessor.current_positio...
061bcf2ced6c22c77d81bb30ec00a5c1964c3624
10,790
import tempfile import zipfile import click import os def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False): """Install plugin from zipfile.""" logger.debug("%s is a file, attempting to load zip", pkgpath) pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_") try: ...
16c430ed97e1e3ee29589bec42a103f7374bf60b
10,791
from xml.dom import expatbuilder from xml.dom import pulldom def parse(file, parser=None, bufsize=None): """Parse a file into a DOM by filename or file object.""" if parser is None and not bufsize: return expatbuilder.parse(file) else: return _do_pulldom_parse(pulldom.parse, (file,), ...
0d4bc592143ecb7c093eceaf4f5fe0d18869ea9c
10,792
import hashlib def create_hash256(max_length=None): """ Generate a hash that can be used as an application secret Warning: this is not sufficiently secure for tasks like encription Currently, this is just meant to create sufficiently random tokens """ hash_object = hashlib.sha256(force_bytes(g...
4856be59c475bcfc07137b62511de4d5c7531eb3
10,793
from io import StringIO def assert_content_in_file(file_name, expected_content): """ Fabric assertion: Check if some text is in the specified file (result of installing a test product) Provision dir: PROVISION_ROOT_PATH :param file_name: File name :param expected_content: String to be found in fil...
eba68222d39c55902da1c4c4ae7055b7edc170e0
10,794
import requests import re import os def generate_substrate_fasta(df): """ gemerates fasta sequence files containing sequences of all proteins that contain phosphosites that do not have kinase annotations in PSP or Networkin. The outputs of the function will be used as input to run Networkin locally an...
7e1350444fba35331977976c19607bb34915e2f0
10,795
import math import numpy def _calculate_hwp_storage_fut( hwp_shapes, base_dataset_uri, c_hwp_uri, bio_hwp_uri, vol_hwp_uri, yr_cur, yr_fut, process_pool=None): """Calculates carbon storage, hwp biomassPerPixel and volumePerPixel due to harvested wood products in parcels on current landscape. ...
71b597c62014c120a3deb99ceea14d84612e3b19
10,796
from datetime import datetime def test_function(client: MsGraphClient, args): """ Performs basic GET request to check if the API is reachable and authentication is successful. Returns ok if successful. """ response = client.ms_client.http_request( method='GET', url_suffix='securit...
24a66cca04c9493f7c0bbe13b54e8793188e0924
10,797
import os def load(path='db'): """Recursivly load a db directory""" if not os.path.isabs(path): path = os.path.abspath(path) env["datastore"].update({ "type": "yamldir", "path": path, }) return loaddir(path)
a51ece0de411618de0bef955adb596f8ea80efe5
10,798
def wcxf2arrays_symmetrized(d): """Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. In contrast to `wcxf2arrays`, here the numpy ...
6cca03761b9799a3af7b933877ff70d6d68f7644
10,799