content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import subprocess def system_call(command): """Run a command and return stdout. :param str command: command to run :returns: output of the command :rtype: str Would be better to use subprocess.check_output, but this works on 2.6, which is still the system Python on CentOS 7. """ p = subprocess.Popen...
e7481a3c7a8c6510f643c64f58782c483d2108d6
66,700
def midpoint(pair1, pair2): """find and return the midpoint between the two given points""" x = (pair1[0] + pair2[0])/2 y = (pair1[1] + pair2[1])/2 return x, y
760aca99b1dad002fb8b6f483515f222dee77160
66,701
from re import T from typing import Tuple def _to_tuple(x: T, n: int = 2) -> Tuple[T, T]: """Convert to n-tuple if not already an n-tuple.""" if isinstance(x, tuple): if len(x) != n: raise ValueError() return x return tuple([x] * n)
5deb4f3e4fe9b8021b3bf35d834e5de9e9639282
66,702
def totalistic_ca(k, rule): """ The totalistic rule as described in NKS. The average color is mapped to a whole number in [0, k - 1]. The rule number is in base 10, but interpreted in base k. For a 1-dimensional cellular automaton, there are 3k - 2 possible average colors in the 3-cell neighbourhood. Th...
470902207495fd54a05e1d31eac339382870e156
66,703
def _load_properties(filepath, sep='=', comment_char='#'): """ Read the file passed as parameter as a properties file. @see https://stackoverflow.com/a/31852401 """ props = {} with open(filepath, "rt") as f: for line in f: line = line.strip() if line and not line...
4795ea5e7c30c8820e3035d09fef3a71452e3ce8
66,704
def vcat( *relations ): """ Concatenate relations vertically. All relations must have the same attribute set (names and types). The order of columns is determined by the first relation in the input list. The input relations are **not** consumed immediately. """ return csvq.structure.VCat( *relations )
6b646f7ac1a5b1710203eddaaf103e01e345eb36
66,705
import numpy def power2(f1, f2=None, boxsize=1.0, k = None): """ Calculate power spectrum given density field in real space & boxsize Do not divide by mean, but the field should have 0 mean """ # f1 = f1[::2, ::2, ::2] c1 = numpy...
da7fa71e20071e85ea195c28b7fa4932782179d0
66,706
def send_email(email_message): """ Send email using Mandrill API :param email_message: Mandrill API message dict to send :return: result from Mandrill API """ result = None try: api_key = _get_mandrill_api_key() mandrill_client = mandrill.Mandrill(api_key) result = m...
35238add778dc519dda8edab759de6a974e9e6a3
66,707
def separate_answers(albert_text, cls='[CLS]', sep='[SEP]'): """ Separates the sentences of sequence classification used for bert :param bert_text: list of bert word tokens :param cls: string of cls token :param sep: string of sep token :return: separated strings """ # Fix SPIECE_underli...
66a9b1e5bcd2c096187db12f31b6e66336552f22
66,708
def today_datetime(): """Today is two months after default timestamp""" return dtvals.format_date(pd.Timestamp(2019, 3, 1, 1))
3f809a5d71341ecdef255444d816374d9baa9b35
66,709
def get_partition_vec(rank,n,cluster,closeRange=False): """ get the partition vector from clusters returned by partition algorithms rank: If the bins are sorted, give the rank of each item in the input list. Used by AHP partition. Set rank = None if not used. n: Length of vector in origi...
69c4e7bcbc3cad1442f65693cfa574f3619567fd
66,710
def concat_map_upstream_databases(*arg): """ Concatenates all of the upstream databases given as args. Then all of the emissions in the combined database are mapped to the federal elementary flows list in preparation for being turned into openLCA processes and combined with the generation emissions....
5804e6a87ae7ddd550c09d62797d653b14429d02
66,711
def mail_addr_test(str): """Tests for a bracketed mailing address""" testcase = str start = str.find('<') end = str.find('>') if start==-1 or end==-1: return False else: testcase2 = testcase[start+1:end] if testcase2.find('<') != -1 or testcase2.find('>') != -1: return False elif testcase2.find(' ') !...
2a814da46f7596ba6931d109270327a36cb56aed
66,712
def get_doc_title(request, doc, value = None): """ проверяем что есть поле title или name или value и что оно не равно 32 и в нем нет цыфр это для того чтоб не попадало _id в выпадающий список """ title = '' if 'title' in doc['doc']: title = ct(request, doc['doc']['title']) elif 'name' in doc['doc']: tit...
ba760b2e9539a39eb641d4459a3c6e0efb842c36
66,713
import random def random_with_bias(messages: list, word: str): """ Go through all the messages and try to choose the ones where the given word is not at the end of the string. """ last_word_messages = [] non_last_word_messages = [] for m in messages: words = m.split() if words[-1]....
74579e4216af2a2c1023aa9a2130301c4ec04e6b
66,714
def group_table(df, valuefield): """Group the table by -valuefield- Args: df (dataframe): dataframe valuefield ([type]): [description] Returns: [type]: [description] """ df = df[df["Agegroup"] != "0-19"] df_grouped = df.groupby([df[valuefield]], sort=True).sum().reset...
a55f601cda65d032dce90828d2a293c0976ef3a7
66,715
import os def filename_parser(filename, is_in_valid_container=None): """Extract information from Syncopy file and folder names Parameters ---------- filename: str Syncopy data file (\*.<dataclass>.info), Syncopy info file (\*.<dataclass>) or Syncopy container folder (\*.sp...
1eb7e97f0f1ef3b0f64a877f4a055609755d3894
66,716
def find_allowed_size(nx_size): """ Finds the next largest "allowed size" for the Fried Phase Screen method Parameters: nx_size (int): Requested size Returns: int: Next allowed size """ n = 0 while (2 ** n + 1) < nx_size: n += 1 nx_size = 2 ** n + 1 ...
b7d53ba805ed3c4f543bbb3ff0a94056b76f9738
66,717
def remove_field(meta, field_id): """Delete field and any descendants.""" field_ids = [] if meta.has_field(field_id): field_ids = meta.remove_field(field_id) meta.plot = { key: value for key, value in meta.plot.items() if value not in field_ids } return field_ids
c8bdc810448bf5d722587776377228391a820e60
66,718
def plot_binned_stat(x, y, statistic='mean', bins=20, errorbar=False, percentile=68.27, line=True, ax=None, **kwargs): """ Plot statistics on the quantity y binned following the quantity x. The statistic can be given by a string ('mean', 'sum', 'max'...) or a function. See `scipy.stats....
90c6f7667ca10cd4314037783cb7394177212efa
66,719
def compute_likelihood(da_logical, dim='ensemble'): """ Returns array of likelihoods computed along dim from logical event data Notes ----- See http://www.cawcr.gov.au/projects/verification/ """ if dim == None: likelihood = da_logical else: ...
7387b7720aa4619c5bee27fedcd4e0e8401eb4ce
66,720
from .wlts_qgis import WltsQgis def classFactory(iface): # pylint: disable=invalid-name """Load WltsQgis class from file WltsQgis. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return WltsQgis(iface)
8ecfc8f9f413a8a3c027b1fcec6dadc105a0f513
66,721
from typing import Optional def process_snapshot( serialized_snapshot: bytes, detokenizer: Optional[pw_tokenizer.Detokenizer] = None, elf_matcher: Optional[ElfMatcher] = None, symbolizer_matcher: Optional[SymbolizerMatcher] = None) -> str: """Processes a single snapshot.""" ou...
8ba45a916c4e37f800b2ced2210f5e52e39dcd65
66,722
import re import urllib def parse_ssid_value(ssid_value): """ Parse ssid value to a list. """ val_re = r"'([^']*)'" ssid = [] ssid_items = re.findall(val_re, ssid_value) for ssid_item in ssid_items: ssid.append(urllib.parse.unquote(ssid_item)) return ssid
67fa10d42c255ac8f93e4f9dfbea65e73d288cdd
66,723
def traverse_list_rev(tail): """Prints all elements from tail to head in reverse direction""" if tail is None: return -1 curr = tail arr = [] while curr.prev != tail: arr.append(curr.data) curr = curr.prev arr.append(curr.data) return " ".join(map(str, arr))
ae337027eef66ba81447db8b9ced404b9606f25d
66,724
def bioes_to_bio(tags): """ BIOES->BIO :param tags: :return: """ new_tags = [] for i, tag in enumerate(tags): if tag.split('-')[0] == "B": new_tags.append(tag) elif tag.split('-')[0] == "I": new_tags.append(tag) elif tag.split('-')[0] == "S": ...
10632bbadf9cacd96d2253ed1ac9eaf4d927c532
66,725
import numpy def normalize_slices(shape,index): """ returns index with slice expressions normalized, i.e. simplified using actual length, replace ellipsis, extend where necessary """ if isinstance(index,EllipsisType): index=(Ellipsis,) if isinstance(index, tuple): if is_all_int(ind...
6a690e4275a5ce44cbc0c934836bc81ced4d6adf
66,726
def get_iocs(sample_id, all_artifacts): """ Args: sample_id (str): Returns: dict: response """ suffix = 'sample/{}/iocs'.format(sample_id) if all_artifacts: suffix += '?all_artifacts=true' response = http_request('GET', suffix) return response
52156cfbbc30e787fef889ec7e66b93ebc29df0a
66,727
def euler_step(u, delta_t, t, du): """ Implementation of Euler's method for coupled pair of ODEs for a single step Parameters: ----------- u: array-like vector of initial conditions delta_t: float time step size t: float current time d...
d78940e87ed472f772c73555e38d5950bc5367e1
66,728
from typing import Any def update( *, user_id: int, user_in: UserUpdate, current_user: UsersTable = Depends(deps.get_current_active_superuser), ) -> Any: """ Update a user. """ user = user_crud.get(id=user_id) if not user: raise HTTPException( status_code=404, ...
da3bb335bbf08f0ecc0b3f10913a91d65cf6775d
66,729
def exception(msg, *args, **kwargs): """ Logs a message with level ERROR inside exception handler """ return get_outer_logger().exception(msg, *args, **kwargs)
86bcce59e8bd374f9643fad6f6abac76c9cbd7da
66,730
def get_taxonomy_columns(rank: str) -> list: """ Gets a list of columns for a specific rank along with all the inferior taxonomic ranks. Parameters ---------- rank : str Taxonomic rank. Returns ------- list List with columns names for the taxonomic ranks. """ ...
960ca36f7a978de042c43466f5744dcd71d5bb49
66,731
def write_n_line_file_to_gcs(project, temp_location, n): """Write an n-line file to the temp_location in Google Cloud Storage. Args: temp_location: A string specifying a GCS location to write to. n: An integer specifying the number of lines to write to a file. """ # Prepare to write gcs ...
ea57065ac013b9939ed183e200b0d4ac83964c17
66,732
def format_module_group_selection(form_data): """ """ if not key_in_dict_not_empty('group_selection', form_data): return None return form_data['group_selection']
7ec360a953b73863c1c3e92add531136f56dac40
66,733
import os def subset_image_by_shapefile(imagefile,shapefile,bkeepmidfile=True, overwrite=False, format='GTiff', save_path=None ): """ subset an image by polygons contained in the shapefile the shapefile and imagefile may have different projections, the gdalwarp can handle Args: imagefile:input...
87c589cc85ba4ca743983a7154c915ab2676ed3d
66,734
def mask_to_shapely_polygon(mask: np.ndarray) -> MultiPolygon: """Generates shapely polygon from a single instance binary mask Parameters ---------- mask : binary masks representing single object Returns ------- mp : shapely.geometry.MultiPolygon Geo polygon as shapely object "...
70557f9f6d8ef6b1aadd18818493c4fcfea0b99a
66,735
def get_data_peaks(list_dataset): """Returned Dataset with peaks data from 'hitfinder/peakinfo'. Parameters ---------- list_dataset : list List with dataset from h5py. Returns ------- dataset : The class 'h5py._hl.dataset.Dataset' Dataset with peaks data. """ # we...
af5174fd5a9b5bbb3113f1e6481bbe1102732b15
66,736
def _dress_up_yvals(y): """Reshape temperature array to be per hex side Parameters ---------- y : numpy.ndarray Y-values to be interpolated """ ym = y.copy().reshape(6, -1) tmp = np.zeros((6, ym.shape[1] + 1)) tmp[:, 1:] = ym tmp[0, 0] = ym[-1, -1] tmp[1:, 0] = ym[:-1, ...
ae264d05f2144f3c56d692b3e7d2d5592b01e0ac
66,737
import types def pd_range_index_getiter(context, builder, sig, args): """ Returns a new iterator object for RangeIndexType by delegating to range.__iter__ """ (value,) = args range_index = cgutils.create_struct_proxy(sig.args[0])(context, builder, value) res = call_getiter(context, builder, types.rang...
10b2529aa3b030b566511b46b836d52cb24adf27
66,738
from pathlib import Path from typing import Set def expand_globbed_path(path: Path, config_directory: Path) -> Set[Path]: """ Expand globs, i.e. * and **, of path object. This function is actually not used at the moment, but I have left it here in case we would want to support globbed paths in the fu...
70f132e18f72084336a4a15f1bc367c3b6c5f518
66,739
def msg_obs_st(myjson, privacy = False, raw = False): """ Process JSON Packet from WeatherFlow Hub - obs_st """ text = {} wf_type = False if 'type' in myjson: if myjson['type'] == 'obs_st': if 'obs' in myjson: try: obs_list = myjson['obs'][0] ...
1429cded22a7adae238625e604bfbd203464b6be
66,740
from typing import Generator from unittest.mock import patch import time def client_fixture() -> Generator[None, MagicMock, None]: """Mock balboa.""" with patch( "homeassistant.components.balboa.BalboaSpaWifi", autospec=True ) as mock_balboa: # common attributes client = mock_balbo...
26f3614df512f1f3f06b254b7456cb5de13b828d
66,741
def iou_ddd_distance(atracks, btracks, frame_id=0, use_prediction=True): """ Compute cost based on IoU :type atracks: list[STrack] :type btracks: list[STrack] :rtype cost_matrix np.ndarray """ if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) or ( len(btracks) > 0 and isi...
27a5cebdbb3efb4114a08574939a18834a8c606e
66,742
def normalize_column(tag): """Delete extra spaces from data""" if type(tag) == list: return list(set( [' '.join(item.split()) for item in tag] )) elif type(tag) == str: return [tag, ] else: return []
1267a62933974cd688fe8945a2cc3b407ba7f0a6
66,743
import re def number_of_rsp(ctx): """ Determine the number of RSP's in the chassis :param ctx: :return: the number of RSP's """ platforms = ['ASR-902', 'ASR-920'] count = 0 valid_count = ['1', '2'] if ctx._connection.platform in platforms: count = 1 return count ...
47a068c790e487b7259b1aef4e48a932d2a4f9d5
66,744
def isCompliant(quote): """Checks a few compliant parameters to filter bad quotes.""" if quote == '': return False elif len(quote) < 30: return False else: return True
db7bf215b28b8add0c01118c2ad7e043d5b34048
66,745
def unpad_tensors(sequence, other): """Unpad both sequence and other tensor based on the batch padding in sequence. This relies on the fact that the sequence tensor ONLY has pad characters to represent batch-level padding, not missing residues. This pad character can be used to identify the correct bat...
546ce7cbb648c852c9dadf76b0d3150328f8e713
66,746
def expandRectangle(rect, xfactor=3, yfactor=3): """ Takes a (x,y,w,h) rectangle tuple and returns a new bounding rectangle that is centered on the center of the origin rectangle, but has a width/height that is larger by a given factor. The returned coordinates are rounded to integers """ x...
dbc37c87f7fe69c846a3089ab0543e4810ee3c21
66,747
def wrap_init(f, params={}): """Wraps function `f` as a `WrappedFun`, suitable for transformation.""" return WrappedFun(f, (), (), tuple(sorted(params.items())))
fe80752b0a97784e5831292b7bb714ea438dfa36
66,748
import re def baby_names_table_rows_from_babyfile_string(babyfile_string): """ babyfile_string sample excerpt with lines of html <tr align="right"><td>1</td><td>Michael</td><td>Jessica</td> <tr align="right"><td>2</td><td>Christopher</td><td>Ashley</td> <tr align="right"><td>3</td><td>Matthew</td>...
a0bb831ee908e9fae0c125b2452977afc23058ce
66,749
def get_folders(request): """ all the folders :param request :return: json """ res = joplin.get_folders() json_data = sorted(res.json(), key=lambda k: k['title']) data = nb_notes_by_folder(json_data) logger.debug(data) return JsonResponse(data, safe=False)
48fd663ef4eec9aaeb507893e4c32489ee90367f
66,750
def findColor(frame, DISPLAY, MOTOR, motor, cmdDict): """initial function, create HSV range+mask and passes to 'findPurpleDems'""" #make array for final values HSVLOW=np.array([hul,sal,val]) HSVHIGH=np.array([huh,sah,vah]) # it is common to apply a blur to the frame frame=cv2.GaussianBlur(frame...
833d0915ec69424739eb185183a49e5efb547118
66,751
import re def strong_to_b(value): """ Replaces enclosing <strong> and </strong>s with <p><b>s """ value = re.sub(r'^<p><strong>(.+?)</strong></p>$', u'<p><b>\\1</b></p>', value) return value
06e0f531160e4e5bf23feba3723aaf85971e606b
66,752
from typing import Dict from typing import Union import gc def compute_site_source_distances( stations: np.ndarray, faults: Dict[str, Union[nhm.NHMFault, dict]], calculate_directivity: bool = True, n_procs: int = 1, ): """ Computes the site-source distances for the given stations and faults ...
8d2003297e7c127800ece20b7146380e999b4f7c
66,753
def add_ice_partial_one_arguments(parser): """Add arguments for assigning nfl reads of a given input fasta to unpolished isoforms.""" parser.add_input_file_type(FileTypes.DS_CONTIG, "input_fasta", name="ContigSet", description="ContigSet of non-f...
560793aa551d217c24f12205ab2c2133f9b942a2
66,754
def LoadPemGeneric(s, header, footer, skip_info=True): """Load a generic pem format string. Args: s: str, item in pem format header: str, header type to look for, e.g. "BEGIN CERTIFICATE" footer: str, footer type to look for, e.g. "END CERTIFICATE" skip_info: bool, default True, skip info lines lik...
fedda89f9d0aa023cfbc69c37f747077f390c39e
66,755
def generate_notes_from_corpus(corpus_files,starting_note=None, ending_note=None, length:int=32, width:int=4, save_to_file=None): """ Generate note sequence of defined length from corpus text files @param corpus_files: List of corpus file paths that contain sequence of notes @param starting_note: Starti...
0f0395cdfc0a6e95f75bb1c7f43d2a8fcda57f13
66,756
def net(): """Generate proteingraph from 2VUI.pdb.""" return generate_network()
8e14f72a4023255a69b62eef9664ab85364627c9
66,757
from typing import Dict from typing import Any def podcast_obj(podcast_data: Dict[str, Any]) -> Podcast: """Get a Podcast object.""" return Podcast(**podcast_data)
144cf8e315caa8b4c2b6f96eac2abab20f540600
66,758
import typing def get_baggage( name: str, context: typing.Optional[Context] = None ) -> typing.Optional[object]: """Provides access to the value for a name/value pair in the Baggage Args: name: The name of the value to retrieve context: The Context to use. If not set, uses current Con...
500467a0955af37459762d8431b7f2a6c6139975
66,759
def safe_execution(func): """run a function in safe mode""" def inner_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: print("An exception occcurred, details:{}".format(e)) return inner_func
2423332a5a71e2858eb82496176c110a0be738cf
66,760
def verify_password(plain_text_password, hashed_password) -> bool: """ :rtype: bool that is true if an appropriate password was passed """ return bcrypt.verify(plain_text_password, hashed_password)
f8faa6612eb95218ba9ceb1c61f6b1e2d89bd355
66,761
def product(var_x, var_y): """This is a test!""" return var_x * var_y
bd71b40841a39f9df1b796975782c238c20ec3a3
66,762
def SingletonDecorator(cls): """ Decorator to setup any class as Singleton. Args: cls (class): decorated class Returns: cls instance Warning: Some subclass or decorated inside methods may lost docstring. Not recommended use this decorator with documented class. ...
37c330af4c12b12c338fe56c6882d0a9c937e105
66,763
def empty_list_production(service, create_cmd): """Fixture for empty list command for production""" return toolbox.run_cmd(create_cmd(service, 'list', 'production'))['stdout']
70bc2ed800ffcb8043cb0c6e05435a843e534a56
66,764
def open_localhost_vnc_vterm(adapter, lpar_uuid, force=False): """Opens a VNC vTerm to a given LPAR. Always binds to localhost. :param adapter: The adapter to drive the PowerVM API :param lpar_uuid: Partition UUID. :param force: (Optional, Default: False) If set to true will force the ...
ca463c9a39582c8d9e53950907e330a8d9e4d4b7
66,765
def obscure(item, start=3, end=3): """ Replaces middle of string with * :param item: string - to be obscured string :param start: int - how many letters to leave from start :return: obscured string - how many letters to leave from end """ # ignore None if item is None: return Non...
c5f181e83806d4027bb3e8dd19e94701dda1f4f4
66,766
from typing import List def MishWindowEncoder( width: int, window_size: int, depth: int ) -> Model[List[Floats2d], List[Floats2d]]: """Encode context using convolutions with mish activation, layer normalization and residual connections. width (int): The input and output width. These are required to b...
a583b5bbfad61d068aa3f8669b9aeb85c1ac3db0
66,767
from onnx.helper import make_node import logging def convert_contrib_box_nms(node, **kwargs): """Map MXNet's _contrib_box_nms operator to ONNX """ name, input_nodes, attrs = get_inputs(node, kwargs) input_dtypes = get_input_dtypes(node, kwargs) dtype = input_dtypes[0] #dtype_t = onnx.mapping....
da4fe22efd731aa20af2fed5e12f8749c52e63e3
66,768
from datetime import datetime def str2dt(timestr: str, /, *args, **kwargs) -> datetime: """Return datetime from string Args: timestr: string describing a datetime *args, **kwargs : @see `dateutil.parser.parse` """ return parse(timestr, *args, **kwargs)
c9b965743986609237e3c2b4f5c4229f8b56139c
66,769
def _check_stacking_layer(stacking_layer: dict, estimator_type: str) -> dict: """Chooses the the first and second stacking layer estimators. Parameters ---------- stacking_layer : dict Specify the estimator(s) in the first stacking layer, and the final estimator in the second stacking l...
f23b1999f65d0e620f686db3197e1ee22d810a63
66,770
import os def is_tingbot(): """ Return True if running as a tingbot. """ # TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps. return 'TB_RUN_ON_LCD' in os.environ
192d951e01c15450b69b7329fe802effbc895eef
66,771
def english_to_french(english_text): """ translate english to french""" #write the code here translation_response = language_translator.translate(text=english_text, model_id='en-fr') translation=translation_response.get_result() french_text =translation['translations'][0]['translation'] retur...
18f5a386d46d5337ca8dd65e2ca2e913f5a80a94
66,772
import requests def set_zip_info(zip_code=None): """given a zip code, it returns a json dictionary object with nested data""" if zip_code is None: print("Function takes zip_code as a string") return None if AUTH_ID is None or AUTH_TOKEN is None: return -1 resp = requests.get(...
188b10b2a64213489257c49787229b391b5220eb
66,773
import inspect def t_sne( dimension="both", text_corpus=None, num_topics=10, remove_3d_outliers=False, fig_size=(20, 10), save_file=False, **kwargs, ): """ Returns the outputs of an LDA model plotted using t-SNE (t-distributed Stochastic Neighbor Embedding). Notes ----- ...
a5206a47b7d97a16b484d35b43b9cc51c4d503ac
66,774
from functools import reduce def combination(n: int, r: int) -> int: """ Calculate combination Args: n (int): integer of number of elements r (int): integer of size of combinations Returns: int: An integer of number of combinations """ r = min(r, n - r) nu...
e95805032107f78f93687240c4eba0a9c666b977
66,775
def decode_as_text(encoded, encoding='utf-8'): """Decode a Base64 encoded string. Decode the Base64 string and then decode the result from *encoding* (UTF-8 by default). :param encoded: bytes or text Base64 encoded string to be decoded :returns: decoded text string (bytes) Use decode_as_bytes...
16037e4aeb4151dfdbb529f294c2c8112a2f3ac9
66,776
from pandas.tseries import converter def heatmap(*args, classes=None, cmap=DEFAULT_DISCRETE_CMAP, **kws): """j24.visualization.heatmap wrapper for sounding data""" # This is needed because of a bug in pandas 0.21 converter.register() fig, ax = vis.heatmap(*args, cmap='jet', **kws) fmt_m2km(ax.yaxi...
274f6936902c094e0281c2217c864aaf8037cae1
66,777
import glob import os import sys import warnings def getImageSetDirectories(data_dir='data/chips', labels_filename='data/labels.csv', band_list=['img_ndwi'], test_size=0.1, plot_coords=True, plot_class_imbalance=True, seed=123): """ Return list of list of paths to filenames for training...
df86812d838b1d4dc3489bdfc28054abf13d327d
66,778
from typing import Set from typing import Dict from pathlib import Path async def _compute_protocol_sources( expected_protocol_ids: Set[str], protocols_directory: AsyncPath, protocol_reader: ProtocolReader, ) -> Dict[str, ProtocolSource]: """Compute `ProtocolSource` objects from protocol source files....
215142a0e91f3505b9138b408a41477011e7b3d9
66,779
def get_byte_command(cmd, crc_function): """ Generates a byte command including CRC and CR """ log.debug('Generate full byte command for %s', cmd) # Encode ASCII string to bytes byte_cmd = bytes(cmd, 'utf-8') # calculate the CRC crc_high, crc_low = crc_function(byte_cmd) if crc_high:...
6576de3cc3d1f97be75fbc3f239a5a21dfd33b10
66,780
def test_token(): """Retrieve a token used for testing.""" _ = dotdb.find_one_organization('it_doesnt_exist') result = dotdb.login('test', 'test') return result.token
e9bb34419158377a97e12949c2bfd12c1c93760a
66,781
def scale_rows(A, v): """Scale each row of A by the corresponding entry of v and return the result.""" return sparse.spdiags(v, 0, len(v), len(v)) @ A
361afdb855de4f2dbd982951e8966ba213003687
66,782
from typing import Tuple def biggest_labelizer_balance(metrics: dict, *args, **kwargs) -> Tuple[str, float]: """Given dict of metrics result, returns (key, metrics[key]) whose value is maximal.""" metric_values = list(metrics.values()) metric_keys = list(metrics.keys()) big = metric_values[0] draw...
6d17c971c8bcb0333a91bdc3add6a6883845a6ef
66,783
def valid_snap_channel(channel): """ Validate snap channel exists :raises InvalidSnapChannel: When channel does not exist :return: Boolean """ if channel.lower() in SNAP_CHANNELS: return True else: raise InvalidSnapChannel("Invalid Snap Channel: {}".format(channel))
4d4e86614522e2585cddcd0463027a3d6f30f877
66,784
from typing import List from re import A def center_crop(height: int, width: int, **kwargs) -> List[BasicTransform]: """ Wrapper for albumentations center crop. For every patch a crop a is extracted from the center, p=1.0. Args: ---------- height (int): height of the output image ...
d00cb20f07de44788994169d38e487cb44bd3df9
66,785
import json def error_response(title, status='500'): """Generates an error response to return to API Gateway Parameters ---------- title: string The title description of the error. status: string Thes http status code. Returns ------- dict: An response bac...
16a62ec46396bee5fe3b240febe4bd0ac2cf9de9
66,786
def make_spacy_tokenizer(model_name): """ Make a spacy tokenizer """ model = spacy.load(model_name) def spacy_tokenizer(string): """spacy tokenbizer""" return [t.text for t in model.tokenizer(string)] return spacy_tokenizer
33ba92db24fd5783426f1b9efe9b94a11f7c4e35
66,787
def get_srcpath(): """ Get the sourcepath where the inspection is conducted """ try: return jsonify({"SOURCEPATH": inspsettings.get_sourcepath()}) except (ComprehensionError, InvalidRequestError) as error: return jsonify(error.to_dict()), error.status_code
124af9183d02b5940ce7338b41fbf11828631395
66,788
def add_affinity_others(image, weight, weight_val, bbox_1, bbox_2): """ Add gaussian heatmap for affinity bbox to the image and also generate weighted map for weak-supervision :param image: 2-d array containing affinity heatmap :param weight: 2-d array containing weight heatmap :param weight_val: weight to be...
5219528bbe467ee2d3a02e2a150bfc3d63e96b66
66,789
def calculate_ssim(img1, img2): """calculate SSIM the same outputs as MATLAB's img1, img2: [0, 255] """ if not img1.shape == img2.shape: raise ValueError('Input images must have the same dimensions.') if img1.ndim == 2: return ssim(img1, img2) elif img1.ndim == 3: if ...
0cffee7069e887601b3e544eedc8bc9e34a27c6a
66,790
import requests def get_resource_from_manager(resource_path, base_url=None, base_urls=None): """Get resource from the manager file server. :param resource_path: path to resource on the file server :param base_url: The base URL to manager file se...
72fdd1ede9c0182f02d4ea4621831777a43ff797
66,791
def reindex_like(self, other, **kwargs): """ reindex_like : re-index like another dimarray / axes instance Applies reindex_axis on each axis to match another DimArray Parameters ---------- other : DimArray or Axes instance **kwargs : Returns ------- DimArray Notes ----- ...
16dceb6dadf4b7ce6b8d6311b26c773fd15b1588
66,792
def create_plotly_blob(data_list, xlabel, ylabel, title): """ Create plotly line plot object, useful for jupyter plots or generation of interactive html plots E.G. import plotly.graph_objects as go blob = create_plotly_blob([(xdata1, ydata1, label1, True), (xdata2, ydata2, label2, False)], 'x', ...
a19ece2ba0a1fc6a1db6a167b266d1b3099927c1
66,793
import socket def get_internal_ipv4_address(host="8.8.8.8", port=80) -> IPv4Address | None: """Find local IPv4 address.""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect((host, port)) ip_address = IPv4Address(s.getsockname()[0]) except Exception as e: base_...
a18c5959ada6bb506f2af57b8d8ed2924df6df1e
66,794
from bolero.optimizer import fmin def fmin_cma(objective_function, x0, xL, xU, sigma0=0.01, maxfun=1000): """ Minimize objective function in hypercube using CMA-ES. This function optimizes an objective function in a search space bounded by a hypercube. One corner of the hypercube is given by xL and the o...
1dce18400c3f784ae544d7c8d8bd9b55a215aaf7
66,795
from typing import Any def get_init_value(attr: XmlAttr, node_globals: InheritedDict) -> Any: """Evaluates attribute value and returns it""" stripped_value = attr.value.strip() if attr.value else '' if is_expression(stripped_value): body = parse_expression(stripped_value)[1] parameters = n...
ed7247af31b5a5d4d3f15746a6287471cf8c4188
66,796
def set_bmc_use_attack_path_axioms(ctx, engine, source, target): """ set_bmc_use_attack_path_axioms(Int_ctx ctx, Int_engine_bmc engine, Int_net source, Int_net target) Parameters ---------- ctx: Int_ctx engine: Int_engine_bmc source: Int_net target: Int_net """ return _api.set_...
13e456bcc536920a26be3e7f344972353f42d5c3
66,797
def not_found_error(error): """ 404 error route :param error: error description :return: redirect to page route for 404 """ return page('excludes/404'), 404
0874682a09fc1cba4ca217358d8f8049b50f2a16
66,798
import glob import os def get_spcandidates(versionnum, directory, header_id=None): """Return single pulse candidates to common DB. Inputs: versionnum: A combination of the githash values from PRESTO, the pipeline, and psrfits_utils. directory: The director...
8343a9abfd188feef53f2736b63f63738a4fa8e4
66,799