content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def vectorsToRotMatrix(v1,v2): """ Given two points v1 and v2 in 3D space. Suppose furthermore that v2 is generated by v1 multiplied by a rotation matrix over the origin. We will determine this rotation matrix using this method :rtype: float list :return: Rotation matrix (unhomegenized) i...
13a7348f84e69bc3337c0047e38443e839f74e33
37,827
def missing_impact(df: dd.DataFrame, bins: int) -> Intermediate: """ Calculate the data for visualizing the plot_missing(df). This contains the missing spectrum, missing bar chart and missing heatmap. """ cols = df.columns.values (nulldf,) = dask.persist(df.isnull()) nullity = nulldf.to_dask...
44869403f21416f16341671e7d870cf4d2d01815
37,828
def svn_stream_write(stream, data): """svn_stream_write(svn_stream_t * stream, char const * data) -> svn_error_t""" return _core.svn_stream_write(stream, data)
f35015ec517e77699db794ecedc93165bb5a0154
37,829
def build_word_dict(args, examples): """Return a dictionary from sentence words in provided examples. """ word_dict = Dictionary() for w in load_words(args, examples): word_dict.add(w) return word_dict
1fa9d3906f16f00f89363acb487bb8c22eb5c0b1
37,830
def train_test_split(df, index, split_by=None, stratify_by=None, test_split=0.1, seed=None): """Split pandas dataframe into train and test splits. Options to split by group (i.e. keep groups together) and stratify by label. ...
fe56f9897da4df4708b2b439ea8d2b027d01668e
37,831
def get_data_ce_duals_active_all(): """() -> list Returns a list of all of the active ce cards in the database, sorted in ascending order by start date.""" query = ( f''' SELECT active_product_nick, active_product_titles, CAST (CAST (active_product_prices AS text) AS money), active_product_...
0d9af4d17059ae53c2d0a4fa40f5e007253f07c6
37,832
from typing import Optional def _import_project_sections(nt_client, monday_client, nt_project_id, project, limits: dict): """Import monday lists as project sections""" nt_api_sections = apis.ProjectSectionsApi(nt_client) def _parse_timestamp(monday_timestamp: Optional[str]) -> Optional[models.TimestampNu...
a57a8a6a41b7ef333d45001859e9b199b3d7339a
37,833
def evaluate_wos_layer(epoch_predicts, epoch_labels, vocab, threshold=0.5, top_k=None): """ :param epoch_labels: List[List[int]], ground truth, label id :param epoch_predicts: List[List[Float]], predicted probability list :param vocab: data_modules.Vocab object :param threshold: Float, filter probab...
c3b3a47caab6d396e1c3531d7f5e4442e7e4dd33
37,834
def convert_weighted(array : np.array) : """ 3D-array to 2D-array (R^2 + G^2 + B^2) / (R+G+B) """ sqrd = array**2 sqrd = sqrd.sum(axis = -1) norm = array.sum(axis = -1) return np.nan_to_num(sqrd/norm, nan=0)
794d2fae798aec538cc6d502d86c0cd524fdf889
37,835
def empty_init(): """Returns True if trying to initialize an Interactionobseng without any arguments fails.""" try: BaseObservationEngine() return True except TypeError: return False
0d3a3f4b5e6addd818037b73edd5dc6ea37edd79
37,836
import signal def smooth_column(args): """Low-level helper function for smoothing single column Parameters ---------- args : tuple Tuple containing data to smooth in 1d array, smoothing kernel in 1d array, whether to ignore nans, and data dtype Returns ------- ...
ce3f62c01c2a6e14cf921c83b670dc08e94e2936
37,837
def check_all_H(structure): """ Parameters ---------- structure : Biopython protein structure object made with PDBParser(). Returns ------- all_ligands : dataframe of all distances between each amino acid residue and ligand from the protein structure. """ heteros = get_hetero...
db70d4d891c50ef97a3dc642e1f6d81068d8ef8e
37,838
def get_example_jwt_auth_signer(**kwargs): """ returns an example jwt_auth_signer instance. """ issuer = kwargs.get('issuer', 'egissuer') key_id = kwargs.get('key_id', '%s/a' % issuer) key = kwargs.get( 'private_key_pem', get_new_rsa_private_key_in_pem_format()) algorithm = kwargs.get('algor...
33a40801a7492c23b08570f6204cedf4d8c02eb8
37,840
async def close_trades(ctx): """Ends free agency in the identified league.""" if ctx.author.id not in admin_ids: return await ctx.send("This is an admin-only command.") for l in leagues: if l.get_channel() == ctx.channel.id: league = l break else: return a...
3219057ba9e05da4e7fa66af963c4991a55b6e3e
37,842
def generate_set_None(gen_dict, class_dict): """Generate the code for the _set_None method of the class Parameters ---------- gen_dict : dict Dict with key = class name and value = class dict (name, package, properties, methods...) class_dict : dict Dictionnary of the class to gene...
457f6588e71b9ae66b1b23a768d13a0a38be0ed0
37,843
import xml def unescape_ssml(text: str) -> str: """Unescapes XML control characters in SSML. See: https://console.bluemix.net/docs/services/text-to-speech/http.html#escape We first unescape the text in case it already contains escaped control characters. """ return xml.sax.s...
4f58510cad608fc7e18ac4ab19cf5895206adfaa
37,846
def descSetupInEipMode(): """ Setting up an EIP/ELB enabled zone with netscaler provider """ zs = cloudstackConfiguration() for l in range(1): z = zone() z.dns1 = "8.8.8.8" z.dns2 = "8.8.4.4" z.internaldns1 = "192.168.110.254" z.internaldns2 = "192.168.110.25...
a77b650532b3187085df9a19f70879addb6629b5
37,847
async def send_expr(bot: NoneBot, ctx: Context_T, expr: Expression_T, **kwargs): """Sending a expression message ignoring failure by default.""" return await send(bot, ctx, expression.render(expr, **kwargs))
0999f5d9c914c27029b0427f84089b5419432fbb
37,848
def ssd_model_build(): """create network""" ssd = ssd_inception_v2(configs=config) if config.feature_extractor_base_param != "": ssd.init_parameters_data() param_dict = load_checkpoint(config.feature_extractor_base_param) load_param_into_net(ssd, param_dict) return ssd
1a4e412d7dafcb43333cda6d0966b2fc920f6b07
37,850
def last_update_import_id(): """ For better filtering. @return: """ last_run = app.session.query(func.max(ImportLog.import_id)).filter(ImportLog.status == STATUS_FINISHED).first()[0] if last_run is None: max_import_id = -1 else: max_import_id = last_run return max_import...
e4e402a6d82e4b98d63363530c4775f50a7ee9b2
37,851
def is_valid(value, cast_fn, expected_data_type, allow_none=False): """ Checks whether a value can be converted using the cast_fn function. Args: value: Value to be considered cast_fn: Function used to determine the validity, should throw an exception if it cannot e...
ee1a2aca4ba7d437692f5025901f9bf94031434a
37,852
import re def get_kanji(seg_content: str) -> dict: """Split raw lesson content into individual character entries and process each one.""" ret = {} entries = [entry for entry in re.split(KANJI, seg_content) if entry] for kanji, desc in zip(entries[::2], entries[1::2]): ret[kanji] = parse_kanji(...
96fa6d48d3c0ac8b0e64f110987522f9656486aa
37,853
def range_transformation(value: float, input_range: list, output_range: list = [-1, 1]): """Range transformation from [input_range[0], input_range[1]] to [output_range[0], output_range[1]] Args: value (float): variable input_range (list): desired input variable range output_range (list,...
31fbddf575a896fa1ffba7c85857557c3df0337a
37,854
def get_authen_roles(): """ Get the authentication roles Returns: arr[str]: Array of associated roles """ return g.get(AUTHEN_ROLES, [])
a3ba9caa050491203626f60a273d0fa3f8f58a07
37,855
def _mkanchors(ws, hs, x_ctr, y_ctr): """ Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (h...
54e5cc05c34f970f9e725f8ecfd27043c700378c
37,856
def explode(dataframe: DataFrame, col: str, new_col: str = None) -> DataFrame: """Explode a list in a cell to many rows in the dataframe :param str col: name of the column to explode :param str new_col: name of the new column to explode to, could be exploded column """ tmp_new_col = new_col if new_...
54133354eddf42dad973c2e19a9bfc80f3763f08
37,857
def median_buffer_range(mag, magerr): """This function returns the ratio of points that are between plus or minus 10% of the amplitude value over the mean :param mag: the time-varying intensity of the lightcurve. Must be an array. :param magerr: photometric error for the intensity. Must be an array...
83b1eed561399916da58be96c2e8437a8669d2d8
37,858
def multiply(a, b): """Multiply simple numbers, vectors, and 2D matrices.""" is_a_num = is_number(a) is_b_num = is_number(b) is_a_vec = not is_a_num and is_number(a[0]) is_b_vec = not is_b_num and is_number(b[0]) is_a_mat = not is_a_num and not is_a_vec is_b_mat = not is_b_num and not is_b_...
f4c9a6e29a24bfbd9dab940510f3b6c35d09c4a7
37,859
from typing import Tuple from typing import List def two_qubit_matrix_to_diagonal_and_operations( q0: 'cirq.Qid', q1: 'cirq.Qid', mat: np.ndarray, allow_partial_czs: bool = False, atol: float = 1e-8, clean_operations: bool = True, ) -> Tuple[np.ndarray, List['cirq.Operation']]: """Decompos...
36bb1d8a31eeebf78619427e681c4c9784783d45
37,860
def log_f(theta): """log of unnormalized target probability density function""" log_var = theta[0] var = np.exp(log_var) xx = theta[1:] return -0.5*log_var**2 - (0.5/var)*np.dot(xx, xx) - 0.5*xx.size*log_var
a04ed631ae035101a04bb429c8e254f5fed0a59c
37,861
from operator import or_ def search(database, search_params=None, limit=0, order_by='last_updated desc'): """ Searches for one or more resources in the database using the specified parameters. Args: database: The current database context. limit: The maximum number of results to return. ...
d2ff639263310186e2362ce290fdeeb33d58242b
37,862
def pd_series_to_instapost(timeseries:pd.core.series.Series, pathname:str, units:str, timezone:str)->dict: """ Args: series: a pd.core.Series time series with a time stamp index pathname: pathname the data is to be stored at units: the units the data is in ...
527d20d5cfe2e6bd02199ab2713c41fd291179ea
37,863
def iou_batch(bb_test, bb_gt): """ From SORT: Computes IUO between two bboxes in the form [l,t,w,h]...
75a3eaea8aeac8c57553cc961ffcd11f25d21ac3
37,864
from typing import Callable from typing import Optional def action_interaction_additive_reward_function( context: np.ndarray, action_context: np.ndarray, action: np.ndarray, base_reward_function: Callable[[np.ndarray, np.ndarray], np.ndarray], action_interaction_weight_matrix: np.ndarray, is_c...
720b23fb2dd539dba29acf46f498ce46d7a0a77e
37,865
def butter2d_lp(shape, f, n): """ Designs a lowpass 2D Butterworth filter. Modified from Peirce JW (2009) Generating stimuli for neuroscience using PsychoPy. Front. Neuroinform. 2:10. doi:10.3389/neuro.11.010.2008. Parameters ---------- shape : tuple Size of the filter. f :...
6c4b7ccc14290b4be2e06e7c752eb2146f3023cf
37,866
def run_model(network, nodes, demand_per_person_kw_peak, mg_gen_cost_per_kw, mg_cost_per_m2, cost_wire_per_m, grid_cost_per_m2): """ """ # First calcaulte the off-grid cost for each unconnected settlement for node in nodes: if node[5] == 0: node[7] = node[4]*demand_per_person_kw_pe...
02b386363ac2b18bde7e5773da91109fd234353b
37,867
def read_circuit(file): """ Read a Revlib circuit file and create a Qiskit circuit objetc :param file: Revlib circuit file :returns a Qiskit circuit object """ with open(file, mode="r") as file: lines = [] begin = end = 0 variables = '' for index, line in enum...
b8d5c126c867a7a63843c3baf6fb321dcba9aa3a
37,868
def global_reconstruction_error( X, Y, test_idx=None, train_idx=None, scaler=None, estimator=None, ): """Computes the global reconstruction error using the source X to reconstruct the features or samples of target Y based on a minimization by linear regression: .. math:: GRE...
cebeb31aea82a5258955523bd5eeb95e492d2eea
37,869
def api_mobsfy(request): """POST - MobSFy API.""" if 'identifier' not in request.POST: return make_api_response( {'error': 'Missing Parameters'}, 422) resp = operations.mobsfy(request, True) if resp['status'] == 'ok': return make_api_response(resp, 200) return make_api_re...
306319f12e43cf57c3ab0757e964fae30cf17ed9
37,870
def numero_lista(df): """ Función destinada a obtener el número de lista de clases :parameter: dataframe :return: numero de lista de clases """ # Selecciono la columna clase del dataframe y realizo unas modificaciones df['clase'] = df['clase'].str.replace( '[', '').str.replace(']...
86523b6f9eae835de6dfc960e8930cf7659cb2a7
37,871
def Fingerprint(path, params): """Check for a Python app. Args: path: (str) Application path. params: (ext_runtime.Params) Parameters passed through to the fingerprinters. Returns: (PythonConfigurator or None) Returns a module if the path contains a python app. """ log.info('Checking f...
9fde55896fc98984ab90c6274f0f51b14d77e2a0
37,872
import numpy as np def calc_spatialCorrHeightLev(varx,vary,levs,lons,weight,levelq): """ Calculates spatial correlation from pearson correlation coefficient for grids over vertical height (17 pressure coordinate levels). Change the weighting for different level correlations Parameters --...
9645f5d92598250d75a484b0c5bf848073c3f5e8
37,874
def v_relative(v, met): """Estimates the relative air speed which combines the average air speed of the space plus the relative air speed caused by the body movement. Vag is assumed to be 0 for metabolic rates equal and lower than 1 met and otherwise equal to Vag = 0.3 (M – 1) (m/s) Parameters ...
6dceae6ec076dc800d2aa3e80d7d491d94830580
37,875
def fully_qualified_name(entry): """ Calculates the fully qualified name for an entry by walking the path to the root node. Args: entry: a BeautifulSoup Tag corresponding to an <entry ...> XML node, or a <clone ...> XML node. Raises: ValueError: if entry does not correspond to one of the ...
68119b640509cd972770f810b80ba1a2ad54f688
37,876
from pathlib import Path def lab( jupyter_lab: t.Tuple[BrowserContext, Path, int], ) -> t.Callable: """Provide function-scoped fixture leveraging longer lived fixtures.""" context, tmp, port = jupyter_lab path = tmp / f"notebook-{uuid4()}.ipynb" return lambda json_in: _lab( json_in, ...
de906a24e494ac7dd056099ca925b82ac7eeb136
37,877
def load(env_name): """Loads the train and eval environments, as well as the obs_dim.""" # pylint: disable=invalid-name kwargs = {} if env_name == 'sawyer_push': CLASS = SawyerPush max_episode_steps = 150 elif env_name == 'sawyer_drawer': CLASS = SawyerDrawer max_episode_steps = 150 elif env...
47f03f29d69f643ebd64040fa1d98607217fbb82
37,878
from typing import Iterable from typing import Dict def get_pkg_info( package_name: str, additional: Iterable[str] = ("pip", "flit", "pbr", "poetry", "setuptools", "wheel"), ) -> Dict[str, str]: """Return build and package dependencies as a dict.""" dist = distribution(package_name) dependencies =...
439b5058df1e421506ef6f23976cb64e48d555bc
37,879
def sort_tasks_by_exec_time(tasks): """ Sort tasks in descending order by the execution time Args: tasks (list(Node) Returns: list(Node) """ n = len(tasks) for i in range(n): for j in range(0, n - i - 1): if tasks[j].get_exec_time() < tasks[j+1].get_exe...
44f24408803c851ae7f1dd021ec19f99efc3feda
37,880
def csr_sort_indices(*args): """ csr_sort_indices(int n_row, int Ap, int Aj, signed char Ax) csr_sort_indices(int n_row, int Ap, int Aj, unsigned char Ax) csr_sort_indices(int n_row, int Ap, int Aj, short Ax) csr_sort_indices(int n_row, int Ap, int Aj, unsigned short Ax) csr_sort_indices(int n_r...
06bf9c3c66e30d432e43e682e87da33665439b96
37,881
def rdkit_functional_group_label_features_generator(mol: Molecule) -> np.ndarray: """ Generates functional group label for a molecule in RDKit. :param mol: A molecule (i.e. either a SMILES string or an RDKit molecule). :return: A 1D numpy array containing the RDKit 2D features. """ smiles = Che...
15ea9e0255e18674f8aeb6dc20834f1c7aee1d7f
37,882
def append(log: immutables.Map, after: model.Index, *entries: model.Entry) -> immutables.Map: """Append entries to `log` *after* the given index. :param log: Log object to append entries to. :param after: Log index after which entries will be appended. :raises AppendError: If the operation is unsucces...
c9947284f8333910e2f00703ab0da43b7c9eb2a8
37,883
def get_ids(conn, sql_class, columns, data): """ Get row ids based on data and column_names. This function returns only the first id per data point. Be careful if the columns do not ensure uniqueness. """ return [ _get_data( conn=conn, sql_class=sql_class, ...
b36be7ef815b6d2b82e340ed44881f8117490d29
37,884
import requests import re def get_special_search_qnodes(search_term): """ Searches for the search_term and returns a list of candidates from the wikidata search api """ if search_term == '': return [] url = "https://www.wikidata.org/w/api.php" params = { "action": "query", ...
fce3f0c7ebc34613e4e92162169a766e538897cf
37,885
def custom(colors, bins=None, bin_method=BinMethod.quantiles): """Create a custom scheme. Args: colors (list of str): List of hex values for styling data bins (int, optional): Number of bins to style by. If not given, the number of colors will be used. bin_method (str, optiona...
eb6f0726d3523e4937cb7615e74eb073025c144c
37,886
def convert_vdot_to_time(vdot, distance): """Given a VDOT score, returns an approx time for a given distance.""" # Get equation parameters c = VDOT_TO_TIME[VDOT_TO_TIME.Distance==distance].iloc[0].Intercept m1 = VDOT_TO_TIME[VDOT_TO_TIME.Distance==distance].iloc[0].Coef1 m2 = VDOT_TO_TIME[VDOT_TO_TI...
bb4a3071b7a94e2e1486b37baf3aeff82fcb8a2f
37,888
def exception_response(status_code, **kw): """Creates an HTTP exception based on a status code. Example:: raise exception_response(404) # raises an HTTPNotFound exception. The values passed as ``kw`` are provided to the exception's constructor. """ exc = status_map[status_code](**kw) retur...
0efc1bdd3c6febd4976210bb2759fd50c8fce9db
37,889
def _mask_iou(mask1: np.ndarray, mask2: np.ndarray) -> ScalarMetricValue: """Computes iou between two binary segmentation masks.""" return np.sum(mask1 & mask2) / np.sum(mask1 | mask2)
6f781f3f9f0702613093432de67ea91179a5cd23
37,891
import re def shorten_int_name(interface_name): """ Returns the Cisco shortened interface name from a full one. If the full interface name is invalid, this will return None """ short = None regex = "(\w{2}).*?(\d+(?:/\d+)?(?:/\d+)?)" match = re.match(regex, interface_name) ...
48a6f730c8d3d2f0abaec299385b5d558cf06a00
37,892
import re def read_version(): """Read version from the first line starting with digit """ regex = re.compile('^(?P<number>\d.*?) .*$') with open('../CHANGELOG.rst') as f: for line in f: match = regex.match(line) if match: return match.group('number')
7188470ab1a794b6e72a1fe8bcd804f7290be4a4
37,893
def version_to_semver(version): """ Convert an SDK version string to an npm compatible semver :param version: should be major[.minor] :return: "major.minor.0" """ return "{}.{}.0".format(*parse_sdk_version(version))
b1006b7dca79e6c19d3849dfef298cf08b7c7f29
37,894
def RefDefaults(): """ Returns dictionary of default values for all properties. These are used to provide defaults to fields that we do not want to automatically calculate dimensions for """ return { 'phi': { 'min':-180, 'max':180...
e6e87fd7c3b3a05f83808bebb410a6d5c687d3d3
37,895
import json def load_json(path: str): """ Load the contents of a json file into a python dictionary """ with open(path) as f: content = json.load(f) return content
b35ae26ca303347a98ea3dd3ca42370279d19a2a
37,896
def repopulate(opt: Optimizer, selected_data: pd.DataFrame, target_size: int) -> Population: """ Create new generation. """ fittest_pop = Population(selected_data, opt.population.blueprint) offspring_pop = make_new_generation(n=target_size, parent_fitness_data...
1ab2bbcee1f6f4b69aa2eba0fd4f1d48da770ba2
37,898
def DataframetolaTexTable(DF, alignment=None, fname=None,shade=False): """ Args: df: pandas dataframe alignment: python list of allignment of columns; default is ['c',..]; use ['c', 'p{4in}', 'c', 'c'] for wrapping fname: path to save latex table Returns: object: Returns...
62be7748dbdce035b70468388d314c585696e275
37,899
def getinstructorData(courseIds): """ Gets and instructor object for the course id's given. """ instructorDict = {} instructor = CourseInstructor.select().where(CourseInstructor.course << courseIds) for i in instructor: instructorDict.setdefault(i.course.id, []).append(i.user.firstName ...
845c7cbc7a0eaa41072662d2669509c2b722ceb3
37,901
def convert_farenheit_to_celcius(temp): """Convert the temperature from Farenheit to Celcius scale. :param float temp: The temperature in degrees Farenheit. :returns: The temperature in degrees Celcius. :rtype: float """ return (temp - 32) * 5 / 9
a782550aa33641a719eb6b245d894248aeaa4985
37,902
def get_frequent_item(data): """ 对于给定的字符串列表,找出其中出现次数最多的字符 参数 ---- data: list[str],字符串列表 返回 ---- re: list[str],出现次数最多的字符串 """ _hash = word_count(data) max_num = max(_hash.values()) return list(filter(lambda x: _hash[x] == max_num, _hash))
6cd1b6cd77e9855c6732614b3fbf2096ae1fcbfb
37,905
def float_coords_(coords): """\ """ return [float_recur(coord) for coord in coords]
c02fced6a0137a5bc933a81d0decc472f62faa62
37,906
def invt_sample_z(log_density, size=1, rng=None, **log_cdf_kwargs): """ Inverse transform sampling to generate "true" z values for simulation: """ if rng is None: rng = np.random.default_rng() zgrid, log_cdf = get_log_cdf(log_density, **log_cdf_kwargs) cdf = np.exp(log_cdf) interp_...
7f7e1cb86aa04dc6b00d8d35f3c8cb8028e326ab
37,909
from functools import reduce import operator def fsort(l, signed=True, reverse=False): """Sort a sequence of strings with one or more floating point number fields in using the floating point value(s) (and intervening strings are treated as normally done). Note that + and - preceding a number are included ...
75b9b465bca0e5792a128682a8b31756779173c5
37,910
import re def food_parse(db, query): """ returns a jsonable dict for the autocomplete js library we are using for a text field used to select a food item :param db: :param query: :return: """ parts = re.split("\s+", query) parts = [lemmer.lemmatize(part) for part in parts] db_...
ab55b9e1bbdf3a248c46316cdb8e69400fac9876
37,911
from typing import Union from pathlib import Path from typing import Optional from typing import Tuple import numpy from typing import Dict def read_gpop_hdf5( path: Union[Path, str], interior_path: str, dof: Optional[int] = None ) -> Union[ Tuple[numpy.ndarray, Dict[int, numpy.ndarray], Dict[int, numpy.ndarr...
286886a9866bc77b9ab5610c95ec248ceb4839d5
37,912
def invite(request): """ Simple view to send invitations to friends via mail. Making the invitation system as a view, guarantees that no invitation will be monitored or saved to the hard disk. """ if request.method == "POST": mail_addr = request.POST['email_addr'] raw_addr_list ...
14ba6ebd044710649f82c6d7b94b4b752d24bfae
37,913
def cells(): """Cells From in 'Image manipulation and processing using Numpy and Scipy' section 2.6.6 Measuring object properties <http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html> No known copyright restrictions, released into the public domain. """ np.random.s...
71a9fe2eda33585527b93710f97e76d6a9f8be10
37,915
import inspect def jsonify_arg_input(arg): """Jsonify user input (in AssemblyPipeline `append` and `insert` methods) into a standard step json.""" if isinstance(arg, RunnableArgument): return arg.to_json() # If a function object or name of a function is provided, we assume it # does not ha...
ec5f04b42a410b8aea2ed9b01b5b506f1b9629ea
37,916
def geodetic_to_ellipsoidal(lat: u.deg, lon: u.deg, height: u.m, ell): """Convert from geodetic to ellipsoidal-harmonic coordinates. Parameters ---------- lat : ~astropy.units.Quantity Geodetic latitude. lon : ~astropy.units.Quantity Geodetic longitude. height : ~astropy.units.Q...
ffaf011660c9a21908aa25e04c64e6aa9bd8d6f4
37,917
def enc_backbuffer(backbuffer): """Helper function for RLE compression, encodes a string of uncompressable data.""" compdata = [] if len(backbuffer) == 0: return compdata while len(backbuffer) > 128: compdata.append(127) compdata.extend(backbuffer[0:128]) backbuffer = bac...
75e9860cd0a8563f3e5655b998b4d0dfa1658e9c
37,918
def fourier_features(index, freq, order): """ `Reference`_: https://www.kaggle.com/ryanholbrook/seasonality Example: >>> # Compute Fourier features to the 4th order (8 new features) for a >>> # series y with daily observations and annual seasonality: >>> # fourier_features(y, freq=365.25, order...
1568aa388889ca01e47f3eb63fbf19a92bdcc0e9
37,919
def read_range(read): """Creates a Range proto from the alignment of Read. Args: read: nucleus.genomics.v1.Read. The read to calculate the range for. Returns: A nucleus.genomics.v1.Range for read. """ start = read.alignment.position.position end = start + cigar.alignment_length(read.alignment.ciga...
4a0c4519cde59484d5aae3acd72d71e870fecc60
37,920
def _get_label_members(X, labels, cluster): """ Helper function to get samples of a specified cluster. Args: X (np.ndarray): ndarray with dimensions [n_samples, n_features] data to check validity of clustering labels (np.array): clustering assignments for data X cluster ...
95c9f4e898b0636d3e7b6151f6d336137200143c
37,921
def create_balcony(bm, faces, prop): """Generate balcony geometry """ for f in faces: if not valid_ngon(f): popup_message("Balcony creation not supported for non-rectangular n-gon!", "Ngon Error") return False f.select = False normal = f.normal.copy() ...
80a1d98b8b5fd89d7f3f594edf6d51c358eb3551
37,922
def film_availability_keys(): """ FilmAvailability definition Optional keys: "id" """ return ["service", "displayName", "country", "url"]
829ec5ea5492b58c19639f0f83245a88aedb6cc8
37,924
def get_label(scores): """ Compute labels using score values. Args: scores: Score values for each detection. Returns: Label for each detection. """ return tf.math.argmax(scores, axis=1)
abcd01c989f25d574236c19ffc6cafe2eb66257d
37,925
def cm_step_summary(abf): """ Return a message displaying average stats formatted like 'Cm = 34.56 +/- 3.21 pF' """ Ihs, Rms, Ras, Cms = cm_step_valuesBySweep(abf) out = "" out += "Ih = %.02f +/- %.02f pA\n" % (np.mean(Ihs), np.std(Ihs)) out += "Rm = %.02f +/- %.02f pA\n" % (np.mean(Rms)...
e4df5d9f524dfd450c05a407b6726ff75034638c
37,926
from pathlib import Path def check_arg_input_file(input_file: str) -> bool: """Return True of the input_file exists, raise an error otherwise. :param input_file: the input file :param input_format: the expected format of the input file """ path_input_file = Path(input_file) if not path_input_...
df1f877be2afc1d37a008a551776a9adcc3f2b8a
37,927
def V_tank_Reflux(Reflux_mass, tau, rho_Reflux_20, dzeta_reserve): """ Calculates the tank for waste. Parameters ---------- Reflux_mass : float The mass flowrate of Reflux, [kg/s] tau : float The time, [s] rho_Reflux_20 : float The destiny of waste for 20 degrees celc...
3e1adc446bbe2dd936663af895c59222cd000a48
37,928
def angular_travel(angle_array): """ Takes in an array of angular change and returns the angles travelled. This is sensitive to changes in direction, The angles travelled are returned as an array of stepwise values """ travelled = [0] for a, angle in enumerate(angle_array): travelled.app...
0c9eca97614a38c7400796ae3930f18707bc948d
37,930
def IR_50(cfg): """Constructs a ir-50 model. """ input_size = cfg.INPUT.SIZE_TRAIN model = Backbone(input_size, 50,cfg.MODEL.BACKBONE.BACKBONE_OUT_CHANNELS, 'ir') return model
fef1dce13a8c4d50e669551b6b561ef1d9014007
37,932
def writeNetfile2(G, fname): """ write net file from G (networkx) Parameters ---------- G: a neteworkx object Returns ------- file """ nZones = '' nNodes = str(len(G.nodes())) nLinks = str(len(G.edges())) header = "<NUMBER OF ZONES> " + nZones + "\n<NUMBER OF NODES> " + nNodes + "\n<FIRS...
ea4b914c2169d3d3cc92a51c84ffcf89fe4bfd4e
37,933
import torch def attention_aggregator(embedding_lists, weights, embed_dim=0) -> torch.Tensor: """ Returns a weighted sum of embeddings :param embedding_lists: list of n tensors of shape (l, K) embedding tensors (l can vary) :param weights: list of n tensors of shape (l,) weights (l can...
88fe01d8baea23321593bf88fd522eb0ef379be9
37,934
def _calculate_application_risk(module): """ Function to calculate Software risk due to application type. This function uses a similar approach as RL-TR-92-52 for baseline fault density estimates. The baseline application is Process Control software. Every other application is ranked relative to ...
703aaf086aecf717be5c13694a8f1dae9f70a86c
37,935
def test(): """ Eventually this could become a convenience command for calling the other test commands quickly with just test -x. """ return test_all()
8a1bb5d89aa73f0236de0316b38c02ea17ae18cd
37,936
def RK(A,b,k=100, random_state=None): """ Function that runs k iterations of randomized Kaczmarz iterations (with uniform sampling). Parameters ---------- A : NumPy array The measurement matrix (size m x n). b : NumPy array The measurement vector (size m x 1). k : int_, opti...
375acf10f277ff7533b0b45058a836c46328deea
37,941
def run_k_means(reduced_text: str, k: int, dataframe: pd.DataFrame)->None: """ create dataframe column for k means cluster """ kmeans = KMeans(n_clusters=k, random_state=42) y_pred = kmeans.fit_predict(reduced_text) dataframe['y_pred'] = y_pred return y_pred
08fbf8cb54bc74d410f674924cc13bc82e376578
37,942
from typing import List from typing import Tuple def split_blank_line( lines: List[str], line_offset: int = 0 ) -> Tuple[List[str], List[str]]: """Split leading blank line from lines if one exists Args: lines: The lines to evaluate. line_offset (optional): The offset into the overall docu...
c70cf05111ec17c12797b5d94a547db0b4d3427c
37,943
from typing import Union import requests import json def get_page_list_by_page(base_url: str, api_token: str, page_path: str, limit:Union[int, None]=None) -> dict: """ get page list under the specified page path """ req_url = '{}{}'.format(base_url, '/_api/pages.list') limit = 1e10 if limit is Non...
dbf70ac34187748e9f6dbfc4296df738c98819b6
37,944
def erode_edges(mask, erosion_width): """Erode edge of objects to prevent them from touching Args: mask: uniquely labeled instance mask erosion_width: integer value for pixel width to erode edges Returns: mask where each instance has had the edges eroded """ if erosion_widt...
35a32f14b8ca9c54d090fe0e77e4108f02f8fe4b
37,945
import re def load_keel_file(path): """Load a keel dataset format. Parameters ---------- path : str The filepath of the keel dataset format. Returns ------- keel_dataset: KeelDataset The keel dataset format loaded. """ handle = open(path) try: ...
55849a706cdc8a3790501f694329ac73dbe1cb0d
37,946
import torch def searchsorted2d(a, b): """ Searches a sorted 2D array along the second axis. Basically performs a vectorized digitize. Solution provided here: https://stackoverflow.com/questions/40588403/vectorized-searchsorted-numpy. :param a: The array to take the elements from :type a: torch.Te...
f46cf6217e7ec85ba0a27df8474b64bebc552759
37,948
def bytesToBits(numBytes): """ Converts number of bytes to bits. :param numBytes: The n number of bytes to convert. :returns: Number of bits. """ return numBytes * 8
6dc14c9d9f5829337e826c63a7772ea8d3c6962c
37,949