content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def publisher(handler): """ Decorator that will publish messages to SNS Topics. This decorator looks for a 'messages' key in the result of the wrapper decorator. It expects result['messages'] to be a dict where key is Topic Name or ARN and value is the message to be sent. It will publish each message to ...
6f203909a36c48cb4c724141bebf98059550413c
3,612,000
import inspect def unwrap_obj(obj): """ Gets the actual object from a decorated or wrapped function @obj: (#object) the object to unwrap """ try: obj = obj.fget except (AttributeError, TypeError): pass try: # Cached properties if obj.func.__doc__ == obj.__do...
d158d7ed832823b66e46bea00a96c5799684bd33
3,612,001
def get_user(user_id) -> dict: """ Used only in record_to_dict and user_setting. """ user = ( db.session.query(Users.username, Users.name, Users.classnum, Users.email) .filter_by(id=user_id) .first() ) return { "username": user.username, "name": user.name,...
a25334ad1ee9abbb7f695c4e07d4cc6bcdf288cc
3,612,002
def isolines(location, **kwargs): """ :param location: an address string, or a shapely geometry the source location :param graph: NetworkX graph :param edges: geopandas GeoDataFrame :param edge_idcol: string id attribute/column name of the graph/edges GeoDataFrame (default is 'id') :para...
a809cd66e31880761f5c2c051ca9396cd037ca08
3,612,003
def delete_item(bucketlist_id, item_id): """ Deletes a bucketlist item :param bucketlist_id: :param item_id: :return: """ item = get_item(bucketlist_id, item_id) if not item or not get_bucketlist(bucketlist_id): return jsonify({ 'message': 'Bucketlist item not found....
ae30796f289fc55fae68a42b054d79703240d262
3,612,004
def predict_on_atom_efs(param): """Predict the local energy, forces, and partial stresses and predictive variances of a chemical environment.""" structure, atom, gp = param chemenv = AtomicEnvironment(structure, atom, gp.cutoffs) return gp.predict_efs(chemenv)
d16332ac72b95791e3053a450e669f6b97f0ee9f
3,612,005
def get_export_info(archive_name): """ Given a file or directory, extract it and return information that will be used in an export printout: the basename of the file, the name stripped of its extension, and our best guess (based on Slack's current naming convention) of the name of the workspace that...
7d88e13f48ee6d44d23a65abf89777d455c3d074
3,612,006
def call_var42127803hap(bamfile, cnvtag, base_db): """ Call haplotype with regard to g.42127803C>T and g.42127941G>A """ diff_haplotype = False if cnvtag == "cn2": haplotype_per_read = get_haplotypes_from_bam_single_region( bamfile, base_db, range(len(base_db.dsnp1)) ) ...
259c17e5df88e66b47f81c180499421fb97f862e
3,612,007
def closest_match(num,num_list): """ Finds the closest number to num in num_list. :num: (float) a number :num_list: (array of floats) :returns: (float) the number in num_list closest to num """ diffs = np.abs(np.subtract(num,num_list)) return num_list[np.argmin(diffs)]
37628d00de6bf1d16416a8b18c76b97e43bf0345
3,612,008
def get_workspace(repo_context): """ Construct the workspace url from the given repo context :param repo_context: Repo context from context.py :return: Workspace url for known VCS or None """ if not repo_context["repositoryUri"]: return None revision = repo_context.get("revisionId",...
ebab3b089c8267932a7a660207b8c7d4b38148f9
3,612,009
def get_wavelet(wavelet_name, dtype=tf.float32): """ Get a wavelet based on the wavelets name. Args: wavelet_name (str): Name of the wavelet ('haar', 'db1', 'db2', 'db3' or 'db4'). Returns: A wavelet object. If the wavelet name is not recognized, it returns None. """ wname = wa...
a1df3e42d0eefcde2e05fa3fa96d11185ba4088d
3,612,010
def argToBoolean(value): """ Boolean-ish arguments that are passed through demisto.args() could be type bool or type string. This command removes the guesswork and returns a value of type bool, regardless of the input value's type. It will also return True for 'yes' and False for 'no'. ...
a2b74145d98f22e6341d7b8a7a7fae6f1b1d9dd7
3,612,011
import sys def doscmd(cmd): """Execute a command.""" if flag_echo: sys.stderr.write("executing: " + cmd + "\n") if flag_dryrun: return return u.doscmd(cmd, True)
6fe812d853975fa77f9248510788f6043755e968
3,612,012
from typing import Optional def initialize_table( nrows=0, name: Optional[str] = None, subj: Optional[str] = None, set: Optional[str] = None, path: Optional[str] = None, ) -> Document: """Initializes a docx file containing the Science Bowl header row. Parameters ---------- nrows :...
04d580a9d2b2ceabb37f8abdaa89592ad09c9ddb
3,612,013
def plotlify_scatter_js(xy=None, x=None, y=None, xtag=None, ytag=None, description=""): """ Update the plot data in plotly format. :param xy: x and y in a single structure. :param description: The description of the plotly plot. :param plot_type: The type of the plotly plot. :return: A dictiona...
2ad2e33dde23ec18f162c28425380b99ae3596a6
3,612,014
from typing import Tuple from typing import Dict def get_sequence_context_to_array_index_table(motif_size: int) \ -> Tuple[Dict[str, int], Dict[str, int]]: """ Return dicts mapping sequence contexts to counter array indices Parameters ---------- motif_size: int size of motifs (e.g. 3 ...
e76116da86d07f2af3114b3337a45d32d5aa3b44
3,612,015
def make_cover_image(im): """ Make a cover image. That is, resize an image to be smaller than :py:data:`COVER_SIZE` if necessary. Parameters: im: A sanpera ``Image``. Returns: *im*, if the image is smaller than :py:data:`COVER_SIZE`. Otherwise, a new ``Image`` resized ...
64fe84f1514ecf03cb8196b94767a2b4c77ad5da
3,612,016
def uniqueCruiseIdentifier_exists(cruise_id): """ Verify cruise identifier provided does not exist. Boolean result True if exists, else False. """ try: try: # If uframe returns a value, then cruise exists, otherwise it does not. #value = uframe_get_cruise_by_subsite(cruise_id...
f1b0de22bc1ff5a3caa9bdc5263570e89042ff9e
3,612,017
def operator(openshift): """Return operator pod object.""" def select_operator(apiobject): return apiobject.get_label("app") == "apicast" and apiobject.get_label("control-plane") == "controller-manager" project_name = settings["threescale"]["gateway"]["OperatorApicast"]['openshift']['project_name'...
91e1b66086e0cd1453ff517f2be91273b4a95be8
3,612,018
import os import requests def retrieve_article(article, output_filename, clobber=False): """Download the journal article (preferred) or pre-print version of the article provided, and save the PDF to disk. Inputs ------ article : `Article` object The article to retrieve. output_filena...
d742068dd76090fb03f222194f66d66b1dc95ffe
3,612,019
def envelops(reg, target_reg): """Given a region and another target region, returns whether the region is enveloped within the target region.""" return (target_reg.start <= reg.start < target_reg.end) \ and (target_reg.start <= reg.end < target_reg.end)
716f2e905bdb852d9e0b85ff0482a70a64d325f1
3,612,020
def stats(request): """Show usage stats""" if settings.WASCH_USE_LEGACY: users_count = len(Users.select(Users.login).execute()) machines_count = len( Waschmaschinen.select(Waschmaschinen.id).execute()) appointents_count = len(Termine.select(Termine.user).execute()) else: ...
767bdb3cb4975258682b0301d99cc8b9888c7e6c
3,612,021
def get_ror_inflows(aggregation_level: str, timestamps: pd.DatetimeIndex = None) -> pd.DataFrame: """Returns ROR inflows (per unit of installed power capacity) per NUTS or country in which it exists""" return get_hydro_inflows(aggregation_level, 'ror', timestamps)
e3610b4f026b5d92d6f98826d779d14ad7f0dca4
3,612,022
import warnings def tfidf(s: pd.Series, max_features=None, min_df=1, max_df=1.0,) -> pd.DataFrame: """ Represent a text-based Pandas Series using TF-IDF. Rows of the returned DataFrame represent documents whereas columns are terms. The value in the cell document-term is the tfidf-value of the ter...
1a013287491adffa0002e434b19b57ee5555cf80
3,612,023
def get_EI(dim, sigmas, Ampl, nE, nI, alpha, **kwargs): """ wrapper function for connectivity matrix input: dim: dimensionality, 1 or 2 sigmas: list or float of standard deviation of connectivity Ampl: list or float of standard deviation of connectivity nE: size of excitatory units nI: size of inhibitory units...
a0e327f84b5a9edf1f9d5fb222e78f3281a31712
3,612,024
from typing import MutableMapping from typing import Any def include_filter( include: MutableMapping[Any, Any], target: MutableMapping[Any, Any]) -> MutableMapping[Any, Any]: """Filters target by tree structure in include. Args: include: Dict of keys from target to include. An empty dict matches all ...
f1c10ec383a430700d8e7f58e8c9f6bc5180c844
3,612,025
def _local_pca(pca, args): """Create the local PCA object """ local_pca = PCA(pca, api=args.retrieve_api_) kwargs = {} if args.max_components: kwargs.update({"max_components": args.max_components}) if args.variance_threshold: kwargs.update({"variance_threshold": args.variance_th...
ea272dcd6b1fe4fbe2d94d9deee2244ffaeb8b42
3,612,026
def create_app(config_name): """ Creates Flask instance & initialize Came from 'Use Application Factory' : http://slides.skien.cc/flask-hacks-and-best-practices/#7 :rtype: Flask """ app_ = Flask(__name__) app_.config.from_pyfile(config_name) cors.init_app(app_) jwt.init_app(app_) ...
b5c9aed6edc675d91b60df4d094634dabb932276
3,612,027
def cv(model): """ A function to perform cross-validation on a model. """ (x_train, y_train), _ = get_metadata() cv_score = cross_validate(model, x_train, y_train, cv=5, scoring="neg_mean_squared_error", return_estimator=True, return_train...
dc63f429195c1570bf23f24f6b21fe6a6929b565
3,612,028
def analyze_data(fitsfn, observables_dir="", affine2d=None, psf_offset_find_rotation = (0.0,0.0), psf_offset_ff = None, rotsearch_d=None, set_pistons=None): """ returns: affine2d (measured or input), ...
af0d32932e5cb433c36efc5ae985057bcfb51654
3,612,029
def _get_pb_likelihood(likelihood): """Convert protobuf Likelihood integer value to Likelihood enum. :type likelihood: int :param likelihood: Protobuf integer representing ``Likelihood``. :rtype: :class:`~google.cloud.vision.likelihood.Likelihood` :returns: Enum ``Likelihood`` converted from proto...
bef00bc3dbf5e31fa0f25241bce32a8b6d61b367
3,612,030
def eval_loss(original, latent, decoder, loss_func=bce_loss): """ Example of a native Keras / Tensorflow function to be used with pca_tests """ return loss_func(original, decoder.predict(latent)).numpy()
9a476197bb20cbae933f3180134401a54a52b3de
3,612,031
import os def get_key_list_images(path): """ Returns the list of the keys representing the images in the hdf/mrcs/st file. It will be converted in list of integer :param path: :return: """ print("Try to list images on", path) filename_ext = os.path.basename(path).split(".")[-1] result_...
64256ffb6d378864d7485e724abe08130626e206
3,612,032
from corehq.apps.locations.models import SQLLocation from corehq.apps.locations.views import EditLocationView def get_object_info(obj, cache=None): """ This function is intended to behave just like get_doc_info, only you call it with objects other than Couch docs (such as objects that use the Django O...
f1d80208cc9202f8c6db9fcd3e276c016bc213e8
3,612,033
def wave_bases(mother, k, scale, param=-1): """Computes the wavelet function as a function of Fourier frequency used for the CWT in Fourier space (Torrence and Compo, 1998) Arguments --------- mother: str equal to 'MORLET' or 'DOG' to choose the wavelet type k: vector of the Fourier...
aa4cb68e7d555cf8960e3d5db65fe31afb32977a
3,612,034
import os import json def load_strings(): """Inject 'strings' into the jinja2 environment so it is available everywhere """ with open(os.path.join(APP_ROOT_FOLDER, 'strings.json')) as fp: strings = json.load(fp) return dict(strings=strings)
cc8dad0b844965c33552d07a33c3b211e73f5d5b
3,612,035
import re def load_spec(filename): """Load a PIL style input specification.""" f = open(filename, "r") # Create new specification object ... spec = PIL_class.Spec() # ... and populate it with the contents of the file. for line in f: # Strip comments and whitespace line = re.sub(r"#.*\n", "", li...
62eb948fe7c2c2e0322140e6241b6f267d638dd5
3,612,036
def subgraph_from_edges(G, edge_list, ref_back=True): """ Creates a networkx graph that is a subgraph of G defined by the list of edges in edge_list. Requires G to be a networkx MultiGraph or MultiDiGraph edge_list is a list of edges in either (u,v) or (u,v,d) form where u and v are nodes compr...
31935c3319753d95ac0a60390db30f27113ab9a9
3,612,037
from typing import Type def _nptype_to_taco_type(ty: np.dtype) -> DType: """Returns the TACO type for the given numpy type.""" nptype_to_dtype = { np.int8: Type.INT8, np.int16: Type.INT16, np.int32: Type.INT32, np.int64: Type.INT64, np.float32: Type.FLOAT32, np.float64: Type.FL...
b77cda21c8b73edb988796cfd395e38047a30493
3,612,038
def search_images(request): """Function for Image searching/sourcing""" if 'image' in request.GET and request.GET['image']: search_term = request.GET.get('image') searched_images =Image.search_by_name(search_term) message = f'{search_term}' return render(request, 'search.html',...
01847fdc97647c5ba949fdbd8ed723c3a548da31
3,612,039
import struct def readRem(byteStream): """The rem - remark/comment type tokens""" commentLength = struct.unpack('bb', byteStream.read(2))[1] bytesRead = 2 comment = struct.unpack('%ds' % commentLength, byteStream.read(commentLength))[0].rstrip("\x00") bytesRead += commentLength return bytesRea...
31782ce3a8aa10b306066bd4dc388c62392cc11b
3,612,040
def linKK(f, Z, c=0.85, max_M=50, fit_type="real", add_cap=False): """A method for implementing the Lin-KK test for validating linearity [1] Parameters ---------- f: np.ndarray measured frequencies Z: np.ndarray of complex numbers measured impedances c: np.float cutoff f...
87b7ee6bdb2281117ced6826e6bc10455202e09d
3,612,041
def ERR_USERSDISABLED(sender, receipient, message): """ Error Code 446 """ return "ERROR from <" + sender + ">: " + message
2da8df2a4fd8cdb41840ca5d0929721af1354829
3,612,042
def get_route_name(route): """Returns route name.""" # split once, take last peice name = route.split("/", 1)[-1] return name
3d5c916711a7631d4eb90c5eff6f1f745c97a664
3,612,043
def get_response_ids_submitdates(resp_meta, debug=False): """ Return a dict mapping response ids to submitdates. response ids are of type int, submitdates of type str. :param resp_meta: dict mapping response ids to a dict with meta information, cf. :func:`ge...
9e04e12526302639044aae20eeb113d991ed4902
3,612,044
def singlecore(known_face_encodings, names, face_query): """ single core is impl to compare faces on one core """ tolerance, similarity_metric = configs.face_similarity_threshold, configs.metric if similarity_metric == 'euclidean': name= singlecore_euclidean(known_face_encodings, names, face...
0e3b6b0d6cd006a29052ce372793a485d5c29f39
3,612,045
def poisciPristanisce(pristanisce): """Vrne podatke o pristanišču na podlagi njegovega imena.""" cur.execute(""" SELECT id, pristanisce FROM Pristanisce WHERE pristanisce LIKE ?""", (pristanisce,)) return cur.fetchone()
b49399725fcff4ba382ba9784a1ff81aed1b859e
3,612,046
import scipy def showfreq(signal,fs,fc=0,db=False): """ return f,fft """ if fc==0: kc = int(len(signal)/2) else: kc = int(len(signal)/fs*fc) signal_fft = np.abs(scipy.fftpack.fft(signal)) f = np.linspace(0,fs/2,num=int(len(signal_fft)/2)) out_f = f[:kc] out_fft =...
29d423aa459ca64bbe910d549aa7a118f903ebb7
3,612,047
def make_input_split(filename, offset, length): """ Build a fake (i.e., not tied to a real file) :class:`~pydoop.pipes.InputSplit`\ . This is used for testing. :type filename: string :param filename: file name :type offset: int :param offset: byte offset of the split with respect to the beginning of ...
d7d49d23cff1d70f5870847a90c2409f0c7d5202
3,612,048
from typing import Sequence from typing import List from typing import Dict from typing import Any def get_info(devices: Sequence[custom_types.Device]) -> List[Dict[str, Any]]: """Returns persistent info and firmware version for each device.""" info = [] for device in devices: props = {} for device_prop...
4a464bc24e9e53b48091e62a73cf10e705006bdc
3,612,049
def get_policy_profile_by_uuid(db_session, profile_id): """ Retrieve policy profile by its UUID. :param db_session: database session :param profile_id: string representing the UUID of the policy profile :returns: policy profile object """ with db_session.begin(subtransactions=True): ...
665f7599182f982bbd6369d780218d26861b192c
3,612,050
from typing import Optional from typing import Union from typing import Literal def recall_score(y_true: np.ndarray, y_pred: np.ndarray, *, labels: Optional[np.ndarray] = None, pos_label: Union[str, int] = 1, average: Optional[Literal['micro', 'macro', 'samples', 'weighted', ...
9b22c84c0fd725dfc48541d45054eae05ffb6316
3,612,051
def evaluateIndcostt(individual, verbose=False): """ This function should take an individual,possibly an instance of Candidate class, and return a tuple where each element of the tuple is an objective. An example objective would be (error,circuitLen) where: error = |1 - < createdState | wantedStat...
2e98aa09acf81d3d8f83c3e189560fc5fbf62fb7
3,612,052
def weibull_cdf(): """ Generates a figure and table for the Weibull CDF data in the paper. """ exact = 2.4, 1.6, 0.8 t = np.array([ 1.202, 1.397, 1.537, 1.57, 1.768, 1.856, 1.87, 1.889, 1.918, 2.098, 2.212, 2.349, 2.453, 2.557, 2.596, 2.602, 2.678, 2.706, 3.089, 3.441 ]) F =...
df174f0b75458f31d7d6e71a1faef20d1cf4831a
3,612,053
def runFunction(func, pargs=None, kwargs=None, msg=DEFAULT_MSG): """ Runs the function, catching errors, and writing a message. :param Function func: :param list pargs: postional arguments :param dict kwargs: keyword arguments """ if pargs is None: pargs = [] if kwargs is None: kwargs = {}...
7d038ab3c20c06fa14cff4c689275b3c821c19ca
3,612,054
from sage.misc.prandom import randint from sage.homology.examples import simplicial_complexes def random_simplicial_complex(level=1, p=0.5): """ Return a random simplicial complex. :param level: measure of complexity: the larger this is, the more vertices and therefore the larger the possible dimen...
207b671d20b08f6f3bfc0bcb85b0e3426bfadd88
3,612,055
from aioredis.client import Redis def from_url(url, **kwargs): """ Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided. """ return Redis.from_url(url, **kwargs)
d7941027fd7b171fe5ab00d330df55b97e2e6205
3,612,056
import requests def get_remote_version(url: str) -> str: """Gets the remote file and returns it as a long string.""" response = requests.get(url) if response: #print("Getting remote version") s = response.text return s else: return "Url Not Found."
5d5ef45c5b74b326f9386214229529d9b71aca3d
3,612,057
def mesh_renderer(vertices, triangles, normals, diffuse_colors, camera_position, camera_lookat, camera_up, light_positions, light_intensities, image_width, ...
a1d83fe66b0f2e647c49840777a9fbb9ed6e49c7
3,612,058
from typing import Any def _is_optional(anno: Any) -> bool: """Is the supplied annotation an instance of the 'virtual' Optional type? Optional isn't really a type. It's an alias to Union[T, NoneType] """ return ( is_union(anno) and NoneType in anno.__args__ )
2e5225aadd48ab81b971b139d4984fab8985ca1f
3,612,059
def single_number_hashtable(nums: list[int]) -> int: """Returns the only element in `nums` that appears exactly once Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of integers s.t. every element appears twice, except for one Returns: the only elemen...
f15b06d4f4683b9604e8b5ab6f2fe9be588551a6
3,612,060
def mse_from_logits_bm(output_logits, target_logits): """Computes MSE between predictions associated with logits. Args: output_logits: A tensor of logits from the primary model. target_logits: A tensor of logits from the secondary model. Returns: The mean MSE """ alphas = t...
42634d83f7bea7d8525c29127b77d2982e68bebb
3,612,061
def get_data(input_path): """ Reading passage retrieval results into a dataframe. Parameters ---------- input_path : str Path to file containing passage retrieval results. Returns ------- data : DataFrame DataFrame containing passage retrieval results. ...
c9581d6259ee6d96b47736a316a5472f23dce80e
3,612,062
def metadata(datasets): """ Extract datasette metadata from a CLDF dataset. """ def iter_table_config(cldf): for table in cldf.tables: try: name = cldf.get_tabletype(table) except (KeyError, ValueError): name = None name = name ...
f4927cea1a5587a417e98453cd7df7bf2f75d507
3,612,063
def chunk_bboxes(shape, chunks, overlap): """Calculates the bounding box coordinates for each overlapped chunk Parameters ---------- shape : tuple overall shape chunks : tuple tuple containing the shape of each chunk overlap : int int indicating number of voxels to overl...
c4a526242390be6d395c02189a8641c96cb3ac4c
3,612,064
def DCT1e(x): """ This can act as a forward or backward transform. We use it simply as a transform. This is a very similar definition to wikipedia but with scaling 2. https://www.researchgate.net/publication/3343693_Convolution_Using_Discrete_Sine_and_Cosine_Transforms DCT1 of the input signal x...
a6d0e0099d38c20fdc2c1f2d3e702f4618b7cc76
3,612,065
from davitpy.models import igrf def get_igrf(lons,lats,alts,ephtimes): """ Highly visible getter method for acquiring Earth's magnetic field values for the provided ndarray of longitudes/latitudes/altitudes/times. Uses the IGRF model """ itype = 1 #Geodetic coordinates stp = 1. ifl ...
88a34f5eb531b1103999ebda8a37aedb912d0a85
3,612,066
def dcg_score_at_k(ground_truth, predictions, k=5, pos_label=1): """ Function to evaluate the Discounted Cumulative Gain @ k for a given ground truth vector and a list of predictions (between 0 and 1). Args: ground_truth : np.array consisting of multi-hot encoding of label ...
230a605daf6cce70d9ef97521485ae3cf83c9c65
3,612,067
def index(): """Show all the posts, most recent first.""" posts = HubPost.query\ .join(HubPost.post_content)\ .join(HubPost.effectivity)\ .join(HubPost.author)\ .filter(text("sat_post_effectivity.post_status = 'Active'")) return render_template("blog/index.html", posts=posts)
5ec84195039bc689b0bf2acd86bf8ed788e3b408
3,612,068
import os from pathlib import Path import shutil def which_executable(environment_variable, executable_name): """ Determine the path of an executable. An environment variable can be used to override the location instead of relying on searching the PATH. :param str environment_variable: The name ...
cc6cde33aacfed1626770c8ea3f5e85788d01d9e
3,612,069
def parse_card(card: str) -> tuple: """Separates the card into value and suit. Args: card (str): String representing a poker card, in the format ValueSuit, like '9D' (9 of Diamonds). Returns: tuple: Returns a tuple of the card, like (Value, Suit). Ex: '9D' -> ('9', 'D'). """ if le...
de9051906327dfcf01a3b2076acbed216ce43ced
3,612,070
import argparse def parseargs(): """ Parse the command line arguments :return: An args map with the parsed arguments """ parser = argparse.ArgumentParser(description="Download all image cube files for a given sky location") parser.add_argument("opal_username", help="You...
7c113f69a0c56d91be224d72f044147a54a3eb39
3,612,071
def reduce_mem_usage( df: pd.DataFrame, ) -> pd.DataFrame: """Function to automatically check if columns of a pandas DataFrame can be reduced to a smaller data type. Source: https://www.mikulskibartosz.name/how-to-reduce-memory-usage-in-pandas/ :param df: DataFrame to reduce memory usage on :ty...
f3559c1dfa4cff4ff5ef7e08dae7d1d000205cd0
3,612,072
def plot_po(one_survey): """Plot a diagram of PO (Porakonekairaus) with matplotlib. Parameters ---------- one_survey : hole object Returns ------- figure : matplotlib figure """ df = pd.DataFrame(one_survey.survey.data) if "Soil type" in df.columns: # pylint: disable=unsupport...
0c75f642c803501b617c396d0f6cc6330c40a051
3,612,073
import os def check_cycles(skel_img, label="default"): """ Check for cycles in a skeleton image Inputs: skel_img = Skeletonized image label = optional label parameter, modifies the variable name of observations recorded Returns: cycle_img = Image with cycles identified :par...
3cbe4178cf592299a0ae51a5373ba9ec6a0a1356
3,612,074
import requests def http_get_with_headers(url, h=False): """ executes regular HTTP GET request to url returns response body and headers """ global hd if h: hd = h resp = requests.get(url, headers=hd, allow_redirects=False) return (resp.content, resp.headers)
f5d1177b4cb281b350c0843319b311e3febdec93
3,612,075
def analysis_create(): """ Renders analysis creation page """ return flask.render_template('analysis_creation.tpl')
be8d605e8d7138b000f30c7215c466e26dafb58d
3,612,076
def create_test_engine(): """ Returns an SQLAlchemy Engine, configured for testing. :return: an SQLAlchemy Engine, configured for testing. """ engine = use_database_file(":memory:") return engine
13836447262429bba539558093fb0e45d697dd05
3,612,077
def _reformat_policy(policy): """ Policies returned from boto3 are massive, ugly, and difficult to read. This method flattens and reformats the policy. :param policy: Result from invoking describe_load_balancer_policies(...) :return: Returns a tuple containing policy_name and the reformatted policy...
4eb5372e233d53e6949a90833350831542c5bd01
3,612,078
import logging def get_log_lvl(lvl): """ get logging level via string """ lvl = lvl.lower() if lvl == 'debug': return logging.DEBUG if lvl == 'info': return logging.INFO if lvl == 'warn': return logging.WARN if lvl == 'error': return logging.ERROR
9f72dcac9aa63809c98ed9bcb50d824ec30ee5c3
3,612,079
import codecs def get_line(file_path, line_rule): """ 搜索指定文件的指定行到指定行的内容 :param file_path: 指定文件 :param line_rule: 指定行规则 :return: """ s_line = int(line_rule.split(',')[0]) e_line = int(line_rule.split(',')[1]) result = [] # with open(file_path) as file: file = codecs.open(f...
fdad31f037aa4311fb46e99623a0de0496209b2c
3,612,080
def strip_all_unbalanced_parens(s): """ Return a string where unbalanced parenthesis are replaced with a space. Strips (), <>, [] and {}. """ c = strip_unbalanced_parens(s, '()') c = strip_unbalanced_parens(c, '<>') c = strip_unbalanced_parens(c, '[]') c = strip_unbalanced_parens(c, '{}'...
7d748f79ac19866650aeadc7cf34d8859707e656
3,612,081
from typing import Optional def test_module(client: Client, first_fetch_time: Optional[int]) -> str: """ Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. :type client: ``Client`` :param client: Darktrace Client :type firs...
e2c9e6acf922e765ac1da494b42ed3606da2bfe7
3,612,082
def get_data_streams(stream_list): """ Auxiliary function to translate a list of identifier strings specified in LoggerStream.available into the corresponding DataStream classes to be used in the file logger. Args: stream_list: List of strings indicating the requested DataStreams for the file l...
92e0a78e5c84da9eee20518b334c6cdfa98c5897
3,612,083
def create_species(category_id, name): """ Create a new species for a specified category :param category_id: Category ID :param name: Species name :returns: An instance of the Species class for the created record :raises ValueError: If the species is a duplicate or has an invalid name """ ...
018bd82c86c3f57a1d72b7efad50d6b00b11c640
3,612,084
import logging import time def wait_for_new_checkpoint(checkpoint_dir, last_checkpoint=None, seconds_to_sleep=1, timeout=None): """Waits until a new checkpoint file is found. Args: checkpoint_dir: The directory in which check...
ef0cc8dfe4469501ffc0c61a24a8603d1609bc2a
3,612,085
def checksum1(data, stringlength): """ Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1 ...
504b848b651ae5e8c52c987a6a8e270259e1de44
3,612,086
def padding_function(context, length, chars=None): """ The str:padding function creates a padding string of a certain length. The second argument gives a string to be used to create the padding. This string is repeated as many times as is necessary to create a string of the length specified by the ...
baa94933b802896aaf9976172e9f651641356f4f
3,612,087
def add_gc_siepic(circuit, gc=siepic.GratingCoupler): """Add input and output gratings. Args: circuit: needs to have `o1` and `o2` pins. gc: grating coupler. """ gci = gco = gc gci["n1"].connect(gco["n1"]) gci["n2"].rename("o1") gco["n1"].rename("o2") return gci.circuit...
e41bf5654be2de1a76b1374295f851708e621674
3,612,088
def allZero(buffer): """ Tries to determine if a buffer is empty. @type buffer: str @param buffer: Buffer to test if it is empty. @rtype: bool @return: C{True} if the given buffer is empty, i.e. full of zeros, C{False} if it doesn't. """ allZero = True for byte ...
8520e57dcd09a914566622098b196965f547ac6f
3,612,089
import os def _recursive_walk(path): """ Perform os.walk() on a given path and construct the full path for each recursively found file and directory. :param path: Path of the directory to walk through :return: Tuple of all recursively found file names and directory names :rtype: tuple """...
eac74ba4345e4fb77cd3007ff0e892855bbb7764
3,612,090
def s_and(a: Floatable, b: Floatable) -> float: """ Lukasiewicz's «strong and» operator. This operator (&&) is defined by: a && b := max {0, a + b - 1} Args: a (LogicValue) b (LogicValue) Returns: LogicValue: a && b """ a = float(a) b = float(b) return max(0, a...
17d5c08855cc8e1b71e1ffe1de168fea163b251a
3,612,091
def convert_table(text): """ Convert a table in text from rst to markdown.""" lines = text.split("\n") new_lines = [] for line in lines: if _re_ignore_line_table.search(line) is not None: continue if _re_ignore_line_table1.search(line) is not None: continue ...
92dbb0a1b7073f907e901ce39fc02c40b7a18a6e
3,612,092
def negotiate_version(version, supported_versions=None): """ >>> negotiate_version(Version('0.9.0')) Version('1.0.0') >>> negotiate_version(Version('2.0.0')) Version('1.3.0') >>> negotiate_version(Version('1.1.1')) Version('1.1.1') >>> negotiate_version(Version('1.1.0')) Version('1.1...
5a8dd17788754c9fc00bd9bc43c0953627912720
3,612,093
def map_from_arrays(col1, col2): """Creates a new map from two arrays. :param col1: name of column containing a set of keys. All elements should not be null :param col2: name of column containing a set of values :rtype: Column >>> from pysparkling import Context, Row >>> from pysparkling.sql.s...
20d158ad06197b05e66d16f08e3016d1371fdfab
3,612,094
from distutils import core import os from typing import List def injection_distutils(folder: str) -> dict: """This is a bit of "dark magic", please don't do it at home. It is injecting code in the distutils.core.setup and replacing the setup function by the inner function __fake_distutils_setup. This ...
96724c1163db88444af1bb164199a3f419eec13e
3,612,095
from datetime import datetime def user_loader(session_token): """Populate user object, check expiry""" if "expires" not in session: return None expires = datetime.utcfromtimestamp(session['expires']) expires_seconds = (expires - datetime.utcnow()).total_seconds() if expires_seconds < 0: ...
5d691def8c288107be16b4f63cdcb9be0e6a05c1
3,612,096
async def complete_conversations(request: HistoryQuery = HistoryQuery(), collection: str = Depends(Authentication.authenticate_and_get_collection)): """Fetches the number of successful conversations of the bot, which had no fallback.""" conversation_count, message = HistoryProce...
ebd6d9d549e4e0703627109508b278702a380067
3,612,097
import os def get_all_labels(): """ Returns, List of labels that are in the complete state """ dbs = get_dbs(os.getcwd()) all_labels = list() for db in dbs: all_labels.extend(db.query(resultsdb.models.TuningRun.name) .filter_by(state='COMPLETE') .dis...
464932a0c32ec709cecda3e45b3ecbeb767f5d8a
3,612,098
def update_loss_accuracy_display_dash(value): """ Function that just calls the update_loss_accuracy_display function. This function is decorated by the Dash Application decorator. Such an arrangement is used as unit testing decorated functions is complex. """ display_loss, display_acc = updat...
ec85f1d4a64cc477f68acdfd2a03f038e8e1d870
3,612,099