content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_education_degrees(education_counts, educations): """ Gets a map count of the formal educations that was provided in the survey """ education_degrees = defaultdict(int) for e in educations: for idx in education_counts.index: if idx in educations[e]: educati...
c9f4948fd19de12ab08f988472e5892e7406b92a
69,951
import re def getNormform(synonym): """ """ a = re.sub("[^a-z0-9]", "", synonym[0:255].lower()) return " ".join(a.split())
36d60ad20ff8adee5e4d6f009119026db8a1b874
69,952
from typing import Union import json async def session_remove_all( handle: SessionHandle, category: str, tag_filter: Union[str, dict] = None, ) -> int: """Remove all matching rows in the Store.""" category = encode_str(category) if isinstance(tag_filter, dict): tag_filter = json.dumps(...
3a5a02328ac40273b3efaa27c7091af0fd07bab9
69,953
def tarjans(complexes, products): """ Tarjans algorithm to find strongly connected components. Dirctly from the peppercornenumerator project. """ stack, SCCs = [], [] def strongconnect(at, index): stack.append(at) at.index = index at.llink = index index += 1 ...
1f81bb8734ad0383dc7aa60e116ac1ac0c20da78
69,954
def conjugate_gradient_ok(f_ax, b_vec, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10): """ conjugate gradient calculation (Ax = b), bases on https://epubs.siam.org/doi/book/10.1137/1.9781611971446 Demmel p 312 :param f_ax: (function) The function describing the Matrix A dot the vector x...
c8815023562b58214584f7f13fd8efe91835f00e
69,956
def parse_grid(rb): """ Parse grid location :param _RawBinaryData rb: Binary data describing the location :returns: Grid location :rtype: GridLocation """ assert rb.location_type == LocationType.GRID bl = _parse_absolute_coordinates(rb) if rb.num_bytes == LARGE_GRID_SIZ...
8c1d047e50d47ebed33ebf891ee690c36afff5e9
69,957
from typing import Sequence from typing import MutableMapping from typing import List def _parse_cell( source: Sequence[str], cell_number: int, temporary_lines: MutableMapping[int, Sequence[NewMagicHandler]], command: str, ) -> str: """ Parse cell, replacing line magics with python code as pla...
f5cb8ba019852db89608e50de34415ff6acdc55a
69,958
def draw_prediction_on_image( image, keypoints_with_scores, crop_region=None, close_figure=False, output_image_height=None): """Draws the keypoint predictions on image. Args: image: A numpy array with shape [height, width, channel] representing the pixel values of the input image....
e295c8ae1d44b854fba4d8dd19bc85c9b0195c97
69,959
def process_spectrum(spectrum: MsmsSpectrum, is_library: bool) -> MsmsSpectrum: """ Process the peaks of the MS/MS spectrum according to the config. Parameters ---------- spectrum : MsmsSpectrum The spectrum that will be processed. is_library : bool Flag specifying whether the s...
ebad54e42ff763d7e27a1e7dd84e8e8e8abce766
69,960
def generate_sensors(k = 7, d = 2): """ Generate sensor locations. Input: k: The number of sensors. d: The spatial dimension. Output: sensor_loc: k * d numpy array. """ sensor_loc = 100*np.random.randn(k,d) return sensor_loc
c7e3d71e565b2d7fd1462f5cdeef69a6cb665910
69,961
import cmd import re def parse_csr (csr): """parse the CSR to find all domains""" out = cmd(["openssl", "req", "-in", csr, "-noout", "-text"], err=f"error loading {csr}") domains = set([]) # Find Common Name in CSR cn = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode("utf-8")) if cn...
deb8035c3f4b8fa2929ccae1aa09f01789afc6cb
69,962
import functools def return_as_coroutine(return_value=None): """Creates a function that behaves like an asyncio coroutine and returns the given value. Typically used as a side effect of a mocked coroutine like this: # in module mymod: async def my_coro_under_test(): await asyncio...
92011e2fd12e85cd8afc4bc3a1f98d23e2d38160
69,963
import torch def unscale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor: """ Denormalizes a given input tensor from range of [-1, 1] to (lower, upper). @note It uses pytorch broadcasting functionality to deal with batched input. Args: x: Input tensor of ...
86aa3a1ac0e15b9f19f5970ece2388de2de3f54d
69,964
def save( name: str, model: "xgb.core.Booster", *, booster_params: t.Optional[t.Dict[str, t.Union[str, int]]] = None, metadata: t.Optional[t.Dict[str, t.Any]] = None, model_store: "ModelStore" = Provide[BentoMLContainer.model_store], ) -> Tag: """ Save a model instance to BentoML modelst...
8f60a8c00345c997262955e87693cba8c5f949e4
69,965
def defaultformatter(default_factory): """The default factory is called without arguments to produce a new value when a field value is not present. All remaining field are treated the same as if they were passed to the str.format, including keyword arguments. """ return DefaultFormatter(default...
800244382025a84583b2cdac6454eb18a105d2ea
69,966
def sigmoid_derivative(x): """ Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments: x -- A scalar or numpy array ...
0dbc00a502a3eea4d99739a98c541af28264ea76
69,967
def hidden_digits(time_string): """ converts time with unknown digits to max time with respect to hours and minutes given starting digits Args: time_string (str): a string representing an unknown time Returns: max_time_string (str): a string with filled in missing digits for max time """...
15fdefb340ab5fe66b562f0fa642210db138c590
69,968
def find_tuple_with_max_vl(base, T, key): """ Scan through the whole table T, and find the i-th tuple that maximizes VL(base, i). Returns ------- :return best: int Unique Id of the found tuple """ max_vl = 0 best = None for k in T.keys(): if k != key: v...
89b0a2b9334c9faeef6065e9e1d92854e6f221e2
69,970
def classification_signature_fn(examples, unused_features, predictions): """Creates classification signature from given examples and predictions. Args: examples: `Output`. unused_features: `dict` of `Output`s. predictions: `Output` or dict of tensors that contains the classes tensor as in {'class...
54802e9846d8604729e7ec134c05b5a07da3d182
69,971
def action(method): """ Marks an agent instance method to be registered as an action :param method: :return: """ method._register_action = True return method
15f32f6acd7e31e50ef3b61d0de04e029e65249a
69,973
import pandas import urllib def get_sensor_data( aranet_conf, sensor_id, from_time, to_time, timezone="0000", metrics=list(DEFAULT_METRICS_DICT.keys()), **kwargs) -> pandas.DataFrame: """Get the data for a given sensor from the Aranet Cloud. Args: aranet_conf: Object of the Ar...
a5254e3936a2d47c3bd40807cda7547e29dab4db
69,974
def OutputVector(r, name, mode="python", initial_tabs=3, max_index=30, replace_indices=True, assignment_op="="): """ This method converts into text the RHS vector Keyword arguments: rhs -- The RHS vector name -- The name of the variables mode -- The mode of output initial_tabs -- The number of ...
4043f2d1166a1ebc65ae3120156eb3ebe4402eba
69,976
def create_connection(url, timeout=None, **options): """ connect to url and return websocket object. Connect to url and return the WebSocket object. Passing optional timeout parameter will set the timeout on the socket. If no timeout is supplied, the global default timeout setting returned by g...
2faaa073de7231d3446bcce505c46df9bfcb58db
69,977
def _has_basal(morph_path): """Check if neuron has basal dendrites.""" _morph = Morphology(morph_path) for root in _morph.root_sections: if root.type == SectionType.basal_dendrite: return True return False
799230bd4f16be92e559cb1d199f9626cae25a97
69,978
import re def filter_illegal_chars(dirty, repl=''): """Remove character which allow to inject code which would be run by displaying on the page """ illegal_chars_re = re.compile('[<>="]') return illegal_chars_re.sub(repl, dirty)
d389df644959850ccd4de6dd7ab22f0276b47435
69,979
def get_congress_search( congress=None, chamber=None, versions=None, text=None, page=None, page_size=None ) -> BillSearchList: # noqa: E501 """Your GET endpoint Search for the different bills # noqa: E501 :param congress: Comma separated list of sessions to filter by :type congress: str :para...
5420907bfbf5c02691f0328be0cdbd2cec2c99f0
69,980
def ParseXMLString(raw_xml): """Parses raw_xml and returns an ElementTree node that includes comments.""" return ET.fromstring(raw_xml, _CommentedXMLParser())
84f76b8ef5d1ed57a83c4e1bdf27571db3ea7890
69,981
from typing import OrderedDict def _flatten_obs(obs, space): """ Flatten observations, depending on the observation space. :param obs: (list<X> or tuple<X> where X is dict<ndarray>, tuple<ndarray> or ndarray) observations. A list or tuple of observations, one per environment. ...
1eb81c79f284226887a82a4b7cd7b7a748c4fa00
69,982
from typing import Optional def generate_captcha(seed: Optional[int] = None, length: int = 4, format: str = "png"): """生成验证码(先生成字符,再生成图片)""" code = generate_captcha_code(seed, length) capthca_key = uuid4() # 理论上有碰撞的可能,但验证码嘛,换一个就是了。 key = current_config.CAPTC...
e005603263a5f81cbc901c55c3e1c12065cd80ca
69,983
import re import logging import functools def match(func=None, regex=None, thread=False): """ this decorator is used to create a command the bot will respond to. """ def decorator(func): func.__brutal_event = True func.__brutal_event_type = 'message' func.__brutal_trigger = Non...
8fb06014196ffb1b499ebf172cf4c88f247c100b
69,984
def gen_task2() -> np.ndarray: """Task 2: head of random sequence.""" seq = rand_syms() return np.concatenate(([2], seq, [seq[0]]))
fe98dbf30be0933f58c06f8914dc8835bcaf12ed
69,986
def download_page(cluster_id): """Handle download of the SSH private key """ cluster = Cluster.query.filter_by(id=cluster_id).first() if cluster and cluster.ssh_private_key: return Response( cluster.ssh_private_key, mimetype="text/json", headers={"Content-disp...
65636f137234c633e9a23d63c667f3bd4365e1b7
69,987
from establishment.errors.errors import BaseError def login_required_ajax(function=None): """ Just make sure the user is authenticated to access a certain ajax view """ def _decorator(view_func): def _wrapped_view(request, *args, **kwargs): if not request.is_ajax(): ...
238e764b855c8766165d105f9094be10ffee75ff
69,988
def analyze_SENTINEL_temperature(sen_directory, sen_shape_path, daytime_S3): """ returns the temperature value for each pixel of each station for each SENTINEL scene prints an array for the scenes according to the stations :return: returns three arrays (1st array displayed for each station is the te...
c270a6176170a73c1cbda728096a010af76e919f
69,989
def exp_np_array_list(lst, power): """ Raise elements of a list (of np.arrays - elementwise) to power @param lst: list of np.arrays @param power: scalar, to which power the elements should be raised @rtype list of np.arrays """ result = [] for nparr in lst: result.append(nparr **...
8c8b80c217f4a381e8514c7fff06dc98114087d9
69,990
def max_layout_dimensions(dimensions): """ Take the maximum of a list of :class:`.LayoutDimension` instances. """ min_ = max([d.min for d in dimensions if d.min is not None]) max_ = max([d.max for d in dimensions if d.max is not None]) preferred = max([d.preferred for d in dimensions]) retu...
67e309465f400334dcd68ff8c8197b5cd641b205
69,991
def split_dataset(dataset: Dataset, val_split: float = 0.1, seed: int = 17): """Splits dataset into train and validation ones and transform them into dataloaders. Parameters ---------- dataset : Dataset Dataset to split. val_split : float Ratio used in spliting. seed : int ...
5b69ae352c96511546045ecba18a09ced6b1e15a
69,993
def check_if_significant(data, thresh=1e-5): """ trim data based on threshold. Args: pandas DataFrame: data needs to be trimmed. threshold (float): a constant. Default = 1e-5. Returns: pandas DataFrame: data after trimming. pandas DataFrame: corrsponding index of data....
62494c97559632f2d8d3e542320cb72f3da90eab
69,994
import math def _cosine_anneal(x: float, min_y: float = 0.0, max_y: float = 1.0) -> float: """Implements a cosine decay curve. Curve is cos(x) on domain [0, pi], stretched to the domain [0, 1] and range [min_y, max_y]. Additionally, param x is clipped to the interval [0, 1] """ x = min(max(x, 0.0...
ea3b6dfb8158c12d447d1a23cb472f0be5ef46d9
69,995
def log_rebin_pix(lamRange, n, oversample=None, velscale=None, log10=False, newRange=None): """ Determine the number of new pixels and their coordinate step when rebinning a spectrum in geometrically stepped bins. The input spectrum must be sampled linearly in wavelength. This is primarily a support routine for ...
09d46e09cfba6e0fe00c2645ab55446e4cfe6e03
69,996
def is_image_file(filename): """Checks if a file is an image. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known image extension """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in IMG_EXTENSI...
d87f4d48737292d619f7641f320b32f0ce760581
69,997
import csv def from_line_file(filename, filter_negative=True): """ Loads file from directory ** needs input to be a fully qualified file path. Returns a new list of tuples (x,y) containing points, where x = wavenums and y = intensities. """ spectra = [] # Read in files row by row w...
8ada4018ef0ce4ff874c548f6d12b611dd2ec59d
69,998
from typing import Any def _convert_v_0_1_imported_options(config: dict[str, Any]) -> Any: """Convert a key from the imported configuration.""" code: str | int | None = config.get("code") force_bypass: LegacyArmingOptions | None = config.get("force_bypass") no_entry_delay: LegacyArmingOptions | None ...
8811cee6b9366b9f690f0727ca7a36dae6483859
69,999
import itk def range(imageOrFilter): """Return the range of values in a image of in the output image of a filter The minimum and maximum values are returned in a tuple: (min, max) range() take care of updating the pipeline """ img = output(imageOrFilter) img.UpdateOutputInformation() img....
5c3ec056208b0829cc081dc88faca28b59760481
70,001
def encodeTime(t): """ Calls the time2integer function by unpacking the list or tuple provided Args: date (tuple): year, month, day Returns: int: the number of seconds since the start of the epoch 1st January 1970 """ return time2integer(t[0],t[1],t[2])
4318f52a65d4ec360e58918cb93177a330610252
70,002
def create_model(config, num_classes=2): """Create a model, starting with a pre-trained checkpoint.""" model_kwargs = dict( config=config.model, n_classes=num_classes, ) model_def = modeling.BertForSequenceClassification.partial(**model_kwargs) if config.init_checkpoint: initial_params = impor...
bac802fc18655260b62cbeec22c059be266f0b00
70,003
def tango_to_katcp_text(text): """Convert Tango description text to KATCP compatible text. Description strings from Tango devices have latin-1 encoding, but KATCP expects utf-8. This is only in Python 2, not Python 3. """ if future.utils.PY2: decoded = text.decode(encoding='latin-1') ...
b5a316534e5f91e24414f103fd7b28a923ec5ffa
70,004
from typing import Optional from datetime import datetime from typing import Union def validate_datetime( value: object, allow_null: bool = False, minimum: Optional[datetime.datetime] = None, maximum: Optional[datetime.datetime] = None, extra_error_msg: str = None, ) -> Union[datetime.datetime, No...
86d5e7db54338cc3f2372e275e6d0490aea14400
70,005
def get_volume_type(ctxt, id, expected_fields=None): """Retrieves single volume type by id.""" if id is None: msg = _("id cannot be None") raise exception.InvalidVolumeType(reason=msg) if ctxt is None: ctxt = context.get_admin_context() return db.volume_type_get(ctxt, id, expec...
10449cc5cf852237be5d7dda9c7d3c324e212178
70,007
def diag(v): """ @param v: the vector to put in the diagonal @type v: cvxopt dense matrix @return: diagonal matrix @rtype: cvxopt dense matrix """ result = co.matrix(0.0, (v.size[0], v.size[0])) for i, x in enumerate(v): result[i, i] = x return result
649962a4dff2c9722ed0b8b088d143d0b9238a41
70,008
def calculate_unitary(programs, symbol_names, symbol_values): """Calculate the unitary matrix for the given circuits. >>> qubit = cirq.GridQubit(0, 0) >>> symbol = sympy.Symbol('alpha') >>> my_circuit = cirq.Circuit(cirq.H(qubit) ** symbol) >>> tensor_circuit = tfq.convert_to_tensor([my_circuit]) ...
bd4d65e94e79d33d3cc06e1a28af284cc6b82afa
70,009
def parse_args(args): """Parse command line arguments. Returns list of (data) files that need to be processed -- /unless/ the -A (--generate-all) option is passed, in which case superfluous data files are ignored... """ global add_legend, output_file, title_str, type, verbose global generate_all prog = args[...
7e080b1f5c0ed894099b1354ea0498470663a0bd
70,013
def get_enrichment_plots(enrichment_results, identifier, args): """ This function generates a scatter plot with enriched terms (y-axis) and their adjusted pvalues (x-axis) :param dataframe enrichment_results: dataframe with the enrichment data to plot (see enrichment functions for format) :param str id...
b918217c10a5dc91e675e5e236d173682f13a4a8
70,014
import io def load_img(img_path): """This Function loads the image, corrects the channels (in case if it is not a 4D image file) and returns the dimensions of the file with a boolean of whether it is a RGB file""" img = io.imread(img_path) img, use_RGB = correct_channels(img) if img.shape[-1]==3: ...
7cff625728bfe4d02da46637439bce773ae7ebe5
70,015
from typing import Union from typing import List def _validate_batch_seed_values( batch: Batch, seed_values: Union[dict, List[dict]] ) -> Union[str, List[str]]: """Validate that seed values line up with the first N columns in a batch. Also construct an appropiate seed string based on the values in the bat...
491e93a081af22924fb787ee1e7af875386ea6c0
70,017
from skimage.external import tifffile def pts_to_img(pts, shape, path): """Saves a set of points into a binary image Parameters ---------- pts: an (N, D) array with N D-dimensional points shape: a tuple describing the overall shape of the image path: path to save the output tiff image Re...
a5f06bbd9c54d653398235c9e6f863694faa8340
70,018
def create_network_settings(neutron, network): """ Returns a NetworkSettings object :param neutron: the neutron client :param network: a SNAPS-OO Network domain object :return: """ return NetworkSettings( name=network.name, network_type=network.type, subnet_settings=create_su...
142ab27fc9dea838796434ded990f6db5c5e02e5
70,019
def add_sensorgroup_filter_by_sensor(query, value): """Adds an sensorgroup-specific filter to a query. Filters results by sensor id if supplied value is an integer. Filters results by sensor UUID if supplied value is a UUID. Otherwise attempts to filter results by name :param query: Initial query ...
9aa9bc6a42cb58c98c15de66b3ce1a29432865fd
70,020
def user_feedback_articles(users): """API-endpoint for requesting user_feedback for articles, 'user_id' must be one or more ids separated by comma.""" return jsonify(db.get_user_feedback_articles(users))
af9b762f59ed85fa7fdd9a9bb09757eb11abd5d4
70,021
def encode_frame(frame): """ Encodes an APRS frame-as-dict as a KISS frame. :param frame: APRS frame-as-dict to encode. :type frame: dict :return: KISS-encoded APRS frame. :rtype: str """ enc_frame = ''.join([ encode_callsign(create_callsign(frame['destination'])), enco...
8431abe37cad2650043793519bea6ac9b86cdfeb
70,022
import re def sanitize(text, new_value=''): """ Removes HTML tags that can be executed, used to download from or link to external resources. """ # if input type is anything but string, return as-is # not enforcing type in parameters since we don't want this to fail with a non string type if n...
e3fda4b348a4e32fb6a5cd3f82c44555f374d264
70,023
import glob def png2fea(dir_name): """ Loads all *.png images from directory dir_name into a dictionary. Keys are the file names and values and 2D numpy arrays with corresponding grayscale images """ features = {} for f in glob(dir_name + '/*.png'): print('Processing file: ', f) ...
885406384ed810a6677c400e956eb1ce1947c2a0
70,024
import datetime import calendar def getWeekday(year, month, day): """ input: integers year, month, day output: name of the weekday on that date as a string """ date = datetime.date(year, month, day) return calendar.day_name[date.weekday()]
ca5164b6d7243033f57c3a803301ff3c3ec13d29
70,026
def delete(event, context): """ Delete a given scheduled scrape. """ cloudwatch_events = boto3.client("events") rule_name = event["pathParameters"]["rule_name"] rules = cloudwatch_events.list_rules(NamePrefix=rule_name)["Rules"] if len(rules) != 1: if len(rules) == 0: res...
4425e5d9f0be50eaf4b7d915b88c0838c9056d99
70,027
def main(args=None): """Console script for osna.""" return 0
09202d5e071798d90800122cc0ba5f1e55dd81f5
70,028
def load_velodyne_points(filename): """Load 3D point cloud from KITTI file format (adapted from https://github.com/hunse/kitti) """ points = np.fromfile(filename, dtype=np.float32).reshape(-1, 4) points[:, 3] = 1.0 # homogeneous return points
2114e7db090fb5d2d14dd5ac5402b8fef1139c12
70,029
def rivers_with_station(stations): """Creates a list of rivers with at least 1 station""" rivers = [] for i in stations: if i.name != None: if i.river not in rivers: rivers.append(i.river) return rivers
f935e97dca96a94d7d3e839b9b5178b701799e08
70,030
def tree_leaves(root, follow=is_seqcont, children=iter): """Lists tree leaves.""" return list(itree_leaves(root, follow, children))
cd5046bc3fd4e6a5f073cfdaa39e9c47b703065f
70,031
def build_joint_test_es_senseval_gloss_corpus(_basepath,verbose=True): """ Given filepath to base folder of semseval 3 spanish corpus containing the xml.gz files Parses corpus and generates joint context-gloss pairs from wordnet glosses """ _dict_fileref = find_files(_basepath,'MiniDir.xml') _tes...
201d3dade2cdc6364a0f2f5854ce751ae54ac111
70,032
def get_download_cache_dir() -> str: """Returns full path to download cache directory.""" if cache_dir: return cache_dir return join(config_dir, 'cache')
d85624369189d43c8c22eedac81c6d0d289b8057
70,033
def _extract_script_class(module): """Return the subclass of decu.Script found in module.""" for obj in module.__dict__.values(): if isinstance(obj, type) and decu.Script in obj.__bases__: return obj
3e186880531cc6ecc8787ad420edfb65b2faefd1
70,034
import random def create_person_json() -> dict: """ This method returns a new person in JSON format. The age and gender are chosen randomly. The name is created using a third-party lib, based on the person gender. """ age = random.randint(18, 90) gender = "female" if random.choice([True, F...
4956e2c13099b34854ec1190879eae4e96436362
70,035
def weightsP1D(k, m, dx): """ Computes the m+1 weights of P Arguments: k (int): Order of accuracy m (int): Number of cells dx (float): Step size Returns: :obj:`ndarray` containing weights of P """ G = grad1D(k, m, dx) b = np.append(np.insert(np.zeros((m, 1)), ...
11fc31d536c61c946df897071e71d3d6e3960785
70,036
def mutation_remove_audioobject_exampleofwork(audioobject_identifier: str, work_identifier: str): """Returns a mutation for removing that a AudioObject is an example of a work (https://schema.org/exampleOfWork). Arguments: audio_object_identifier: The unique identifier of the AudioObject. w...
006383e8a2e9d95554a3b68c433d13403f479806
70,037
def init_data(rand: bool = False) -> list: """Prepare the training data. Return the training data as a list with the last element in each sample being that sample's label. """ if not rand: result = [ [0.5, 0.4, 0], [0.8, 0.3, 0], [0.3, 0.8, 0], ...
23eb0089c9e4daf468171ad07fc33fb73befcbd0
70,038
def second_half(dayinput): """ second half solver: """ lines = dayinput.split('\n') result = None return result
e90ff0be6170541c2cbfb1727cc86d4ef2855474
70,039
def config_section_data(): """Produce the default configuration section for app.config, when called by `resilient-circuits config [-c|-u]` """ config_data = u"""[fn_create_webex_meeting] # this may also be the conference id for the developer sandbox webex_email= webex_password= webex_site= webex_site...
5e5a1ca7e3402ab177c5805404beb8baed318aaf
70,040
def generate_token() -> str: """Generate an random, secure, URL-safe token.""" return token_urlsafe()
ab6c99786ad42126c3b5299f13c24f03d449fe31
70,041
from typing import List import inspect def get_function_parameters_list(func) -> List[str]: """ Get parameter list of function `func`. Parameters ---------- func : Callable A function to get parameter list. Returns ------- List[str] Parameter list Examples --...
bff2ec37a5564b87e48abf964d0d42a55f809a16
70,043
def lazylist(fn): """A decorator to wrap function return values in `LazyList`""" def wrapped(*args, **kwargs): return LazyList(fn(*args, **kwargs)) return wrapped
acc3d464d23eaedea049b4c59615e414c6877c9d
70,044
def are_compatible_imgs(one_img, another_img): """Return true if one_img and another_img have the same shape. False otherwise. If both are nibabel.Nifti1Image will also check for affine matrices. Parameters ---------- one_img: nibabel.Nifti1Image or np.ndarray another_img: nibabel.Nifti1Im...
100b2101a46547d802b8567c361fa828f5a94787
70,045
import json def generate_api_queries(input_container_sas_url,file_list_sas_urls,request_name_base, caller,additional_args={},image_path_prefixes=None): """ Generate .json-formatted API input from input parameters. file_list_sas_urls is a list of SAS URLs to individual file lists ...
fc8bb3d6a2e93b003c6d9330b93d19f2d4f27c4a
70,046
def get_mesh_from_vertex(vertex): """ Returns corresponding mesh of the given vertex :param vertex: str :return: str """ return get_shape_from_component(vertex, 'vtx')
bee7c1223b9df1349b7fd1bcde7c77e8fd387f7f
70,047
def checkout_counter(request): """Expose the number of items in checkout.""" checkout = get_checkout_from_request(request) return {'checkout_counter': checkout.quantity}
d23f1b3cbd76c81d8b070c0a16073ad018d3e5a0
70,048
def get_vrt_driver(): """ Convenience function to get the VRT driver. """ return gdal.GetDriverByName("VRT")
f7cfeb6d5a71aa6f40ab30573049208b15e31646
70,049
def getSectionText(cd, sectionLabel=None ): """ """ markups = cd.getSectionMarkups(sectionLabel, returnSentenceNumbers=False) txt = " ".join([m.getText() for m in markups]) return txt
d4bcaa109f5774bd3f5a9abb5a11829061b0ca8f
70,050
def preprocessor(url, published): """ Given a url(a web url or a file object), the preprocessor identifies the type of the url and generates news article data and/or twitter data. :returns: Returns newsObject, tweeter object and error object """ news, tweet, error = None, None, None ...
7a6f8cfa84a2c2b2d2a9bbafa6954a6d8b2d2e50
70,051
def execute_device_action_command(client: MobileIronCoreClient, action: str) -> str: """ Returns results for a MobileIron Device Action :type client: ``MobileIronCoreClient`` :param client: MobileIron client to use :type action: ``str`` :pa...
b397c6b1f3a32ff364e2e19e09615836e4ca4e18
70,053
def search(coordinates): """Search for closest known locations to these coordinates. :param coordinates: A list of tuples of (latitude, longitude) coordinates. :type coordinates: list[tuple] """ gd = GeocodeData() return gd.query(coordinates)
c8c8883913b369b41cebd311331bc960befc8d93
70,054
def sfl_trhph_chloride(V_R1, V_R2, V_R3, T): """ Description: OOI Level 2 Vent Fluid Chloride Concentration TRHPHCC data product, which is calculated using data from the Temperature Resistivity Probe (TRHPH) instrument. Implemented by: 2013-05-01: Christopher Wingard. Init...
4c8f1ddcc9b99b1bf7d3e95f7dd929a267db145d
70,055
def retention_policy_get( database, name, user=None, password=None, host=None, port=None ): """ Get an existing retention policy. database The database to operate on. name Name of the policy to modify. CLI Example: .. code-block:: bash salt '*' influxdb08.retenti...
0c4e1ad31831d54d23a6860be7e3b4f0b1bbaf38
70,056
import torch def run_episode(env, Q, n_action): """ Run a episode given Q-values @param env: OpenAI Gym environment @param Q: Q-values @param n_action: action space @return: resulting states, actions and rewards for the entire episode """ state = env.reset() rewards = [] action...
0ab96c3d2c768befccebab5bc1af6b37f976594c
70,058
def json(value): """Safe jsonify filter.""" uncleaned = jsonlib.dumps(value) clean = bleach.clean(uncleaned) return mark_safe(clean)
56c5fafc2b33fa1f19f741b1c45a8405f05bf427
70,059
def resampleImage(image,resamplingfactor,conserve=True): """Resample an image by `resamplingfactor`. Parameters ---------- image : 2D array The 2D image array to be resampled. npix must be odd-valued. resamplingfactor : float The factor by which the the image sampling (number of p...
0d997c9a98ebc4e71d17a550d3e8b825b581271e
70,060
def _create_export_movie_task(videoid, movie, nfo_settings): """Create a task for a movie""" # Reset NFO export to false if we never want movies nfo name = '{title} ({year})'.format(title=movie['title'], year=movie['year']) return [_create_export_item_task(name, FOLDER_MOVIES, videoid, name, name, ...
45aa37affbc28ce068862c7af373f687d0a01543
70,061
import importlib def load_attr(name): """Load an attribute in format path.to.module:attribute.""" module_name, attr_name = name.split(":") module = importlib.import_module(module_name) attr = getattr(module, attr_name) return attr
90d7ecbf35a52d1b1ee3e9aeeb1e4263baf055a2
70,062
import html def layout(): """Main layout for the open requests tab.""" if is_logged_in(): user = get_current_user() else: return html.Div([html.Br(), html.H1("You must be logged in to do this")]) requests = user.get_requests_as_mentee() # type: List[Request] if not requests: ...
ae105868377cf4bb626e6ce8214c74289c2b0e09
70,063
def iou3d_7dof_box_pairwise(boxes1_length, boxes1_height, boxes1_width, boxes1_center, boxes1_rotation_z_radians, boxes2_length, boxes2_height, boxes2_width, boxes2_center, boxes2_rotation_z_radians): """Computes pairwise intersection...
285d2846835bd489c5f85c778177245b1765c465
70,065
def load(as_pandas=None): """ Load the Longley data and return a Dataset class. Parameters ---------- as_pandas : bool Flag indicating whether to return pandas DataFrames and Series or numpy recarrays and arrays. If True, returns pandas. Returns ------- Dataset instanc...
3e4781ba7c33d9588758e298db81690803228bae
70,066
def margin_of_error(samples): """Computes the margin of error for a set of samples. """ return critical_value(samples) * mean_standard_error(samples)
578cc66e482e5b7878ea2c38d4e792553aefc872
70,067