content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_int(buffer: bytes, offset: int) -> int: """ Returns an int at the specified offset. :param buffer: The buffer to get from. :param offset: The offset to use. :return: The int """ return _int_serialiser.deserialise_from_bytes(buffer[offset:offset + 4])
2f4830cf4693178e3992a861edc1bc234f3b85d4
66,678
def load_source_table(): """ Load table of arcline sources Returns ------- sources : Table """ src_file = arclines.__path__[0]+'/data/sources/arcline_sources.ascii' # Load sources = Table.read(src_file, format='ascii.fixed_width', comment='#') # Return return sources
ec1ccbeee783f3a47d76d1546d77772d38cc385f
66,679
def clang_layer_packages(): """Packages for the clang layer.""" clang_tools = [ tool_names.binutils, tool_names.lib_cpp, ] packages = [] for tool in clang_tools: packages.extend(get_jessie_packages(jessie_tools()[tool])) return depset(packages).to_list()
4473a3038b52327d252cae4723c08d2b997b0b57
66,681
from typing import Generator def read_until( data: bytes, *, return_tail: bool = True ) -> Generator[tuple, bytes, bytes]: """ read until some bytes appear """ return (yield (Traps._read_until, data, return_tail))
277108459577218fd679b4ef44ae10ec9b009293
66,682
def clean_data(df): """Cleans the passed dataframe. Actions done while cleaning: - dropping all rows with missing location ids - dropping all rows where dropoff time is before pickup time - consider all location ids that map to the same zone as equivalent and replace them with a single value ...
f29a1d3784914c2dfcae1611c8860dbaa7f2a93c
66,684
def sort_by_scores(scores, features_list, topn=None): #实际在输入的时候scores=labels,features_list=[labels,logits],所以是按照labels进行排序 """Sorts example features according to per-example scores. Args: scores: A `Tensor` of shape [batch_size, list_size] representing the per-example scores. features_list: A list of...
3483225e319f083b23262aead39c76e6f15103fd
66,685
def _distance_sequence_from_scores(scores_1, scores_2): """ We want to compute the distance between two -local perturbation- models. To do this, we simply take the usual distance between two hmm models; the pretrained predictive model stays constant. The desired distance is the limiting value of t...
9a4488f157e8beaa9ad594467585063884800594
66,686
def polygon_clip(subjectPolygon, clipPolygon): """ Clip a polygon with another polygon. Args: subjectPolygon: a list of (x,y) 2d points, any polygon. clipPolygon: a list of (x,y) 2d points, has to be *convex* Note: **points have to be counter-clockwise ordered** Return: a list of (x,y) ...
1064e3f20c4145ac42484c8b4fc772e396032be2
66,687
def is_openbabel_molecule(obj): """Check whether an object is an `oddt.toolkits.ob.Molecule` instance. .. versionadded:: 0.6 """ return (hasattr(oddt.toolkits, 'ob') and isinstance(obj, oddt.toolkits.ob.Molecule))
1bf1cd6da46aab746f7d63d8f962c97cd5911ee0
66,689
def confirm(prompt=None, resp=False): """prompts for yes or no response from the user. Returns True for yes and False for no. 'resp' should be set to the default value assumed by the caller when user simply types ENTER. >>> confirm(prompt='Create Directory?', resp=True) Create Directory? [y]|n...
a5a6dcb89434aa7dbeac85ae1164b3912100bd4a
66,690
def streamline(mesh, field, startCoord, dLengthSteps, dataMesh=None, maxSteps=1000, verbose=False, coords=(0, 1)): """ Create a streamline from startCoord and following a vector field in up and down direction. """ xd, yd, vd = streamlineDir(mesh, field, startCoord, dLengthStep...
d01339b965c2e99c5fecd3f8df93e6025904b769
66,691
def wall_filter(gray): """ Filter walls Filter out walls from a grayscale image @Param image @Return image of walls """ ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # noise removal kernel = np.ones((3,3),np.uint8) opening = cv2.morphologyEx(thres...
31d71c640aa229efc4384140b1bd6d502544827e
66,692
from typing import Tuple def FloatRangeTupleDataclassField(N=2, default: Tuple = (0.9, 0.999), min=0, max=1): """Returns a dataclass field with marshmallow metadata enforcing a `N`-dim. tuple with all values in given range. In particular, inputs must be N-dimensional tuples of purely numeric values withi...
2166b6aad243df5e9bc9d4b1ceb071cf00e7e5e0
66,693
import htmlentitydefs import re def xss_strip_all_tags(s): """ Strips out all HTML. """ return s def fixup(m): text = m.group(0) if text[:1] == "<": return "" # ignore tags if text[:2] == "&#": try: if text[:3] == "&#x": ...
f78dc85368c63e4ed0484add6755bb9645186d02
66,694
def safe_divide(numerator, denominator, eps=1e-7): """Avoid dividing by zero by adding a small epsilon.""" safe_denominator = tf.where(denominator == 0.0, eps, denominator) return numerator / safe_denominator
551b74f9c9404882585831c316980d36e3bb3359
66,695
def sentinel2_sr_cloud_mask(input_img): """Extract cloud mask from the Sentinel 2 SR QA60 band Parameters ---------- input_img : ee.Image Image from the COPERNICUS/S2_SR collection with a QA60 band. Returns ------- ee.Image Notes ----- Output image is structured to be ...
9b456f9b130d057cb7b2a811458e1cf426365037
66,696
def get_spacegroup(cell, positions, numbers, symprec=None): """Returns Pearson symbol and intl number corresponding to the given structure""" cell = (cell, positions, numbers) sg = spglib.get_spacegroup(cell, symprec=symprec or SYMPREC).split() return sg[0], int(sg[1][1:-1])
19d6e98cfe9fe2119bbd053a81622971f018ba90
66,697
def preprocess_idl_type_and_value(idl_type, cpp_value, extended_attributes): """Returns IDL type and value, with preliminary type conversions applied.""" idl_type = idl_type.preprocessed_type if idl_type.name == 'Promise': idl_type = IdlType('ScriptValue') if idl_type.base_type in ['long long', ...
cc270ba1b811fef6992c582cdd3e28ee04554434
66,698
def start_heterogeneous_tile( tile_name, pin_assignments, sites, equivalent_sites, ): """ Returns a new tile xml definition. Input parameters are: - tile_name: name to assign to the tile - pin_assignments: location of the pins to correctly build pin locations ...
f670e3deedd396b09a2f6a497f2f223e909413fb
66,699
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
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
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 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 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
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
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