content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Callable from typing import Tuple def metropolis_hastings( proposal: Proposal, state: State, step_size: float, ns: int, unif: float, inverse_transform: Callable ) -> Tuple[State, Info, np.ndarray, bool]: """Computes the Metropolis-Hastings accept-...
b5390d8a420ebb3d62c700fe246127935b658b6c
3,642,133
from datetime import datetime def Now(): """Returns a datetime.datetime instance representing the current time. This is just a wrapper to ease testing against the datetime module. Returns: An instance of datetime.datetime. """ return datetime.datetime.now()
9a0657011e10b47eb755a575216944a786218f2e
3,642,135
def ndvi_list_hdf(hdf_dir, satellite=None): """ List all the available HDF files, grouped by tile Args: hdf_dir: directory containing one subdirectory per year which contains HDF files satellite: None to select both Tera and Aqua, 'mod13q1' for MODIS, 'myd...
068062bdef503b6652c62c142a1cf80d830fc8db
3,642,136
def create_provisioned_product_name(account_name: str) -> str: """ Replaces all space characters in an Account Name with hyphens, also removes all trailing and leading whitespace """ return account_name.strip().replace(" ", "-")
743e7438f421d5d42c071d27d1b0fa2a816a9b4d
3,642,138
def case34(): """ Create the IEEE 34 bus from IEEE PES Test Feeders: "https://site.ieee.org/pes-testfeeders/resources/”. OUTPUT: **net** - The pandapower format network. """ net = pp.create_empty_network() # Linedata # CF-300 line_data = {'c_nf_per_km': 3.8250977, 'r_ohm_pe...
8e04a125df0e0a64008724d419bafe19481f5ac1
3,642,139
def _hack_namedtuple(cls): """Make class generated by namedtuple picklable.""" name = cls.__name__ fields = cls._fields def reduce(self): return (_restore, (name, fields, tuple(self))) cls.__reduce__ = reduce cls._is_namedtuple_ = True return cls
89468f0ffb5506ef0c9a33fec0d390576638e659
3,642,140
import tokenize def build_model(): """ Returns built and tuned model using pipeline Parameters: No arguments Returns: cv (estimator): tuned model """ pipeline = Pipeline([ ('Features', FeatureUnion([ ('text_pipeline', Pipeline([ ...
94bc0ad8a3eb48531cb6229972099369a9b9cf61
3,642,142
def INPUT_BTN(**attributes): """ Utility function to create a styled button """ return SPAN(INPUT(_class = "button-right", **attributes), _class = "button-left")
6c6610626367795518ca737b53950d3687ae4d91
3,642,143
def load_annotations(file_path): """Loads a file containing annotations for multiple documents. The file should contain lines with the following format: <DOCUMENT ID> <LINES> <SPAN START POSITIONS> <SPAN LENGTHS> <SEVERITY> Fields are separated by tabs; LINE, SPAN START POSITIONS and SPAN LENGTHS ...
0c674142ae0d99670e63959c3c00ed0ca2c8fac1
3,642,144
import re def search(request, template_name='blog/post_search.html'): """ Search for blog posts. This template will allow you to setup a simple search form that will try to return results based on given search strings. The queries will be put through a stop words filter to remove words like 'the'...
fdb72279b6ed5fe5e87c888b7a10c8a3ed8f94d0
3,642,145
import math def orient_data (data, header, header_out=None, MLBG_rot90_flip=False, log=None, tel=None): """Function to remap [data] from the CD matrix defined in [header] to the CD matrix taken from [header_out]. If the latter is not provided the output orientation will be North up, Eas...
6ef27074692f46de56e5decd7d6b315e11c4d686
3,642,146
def _batchnorm_to_groupnorm(module: nn.modules.batchnorm._BatchNorm) -> nn.Module: """ Converts a BatchNorm ``module`` to GroupNorm module. This is a helper function. Args: module: BatchNorm module to be replaced Returns: GroupNorm module that can replace the BatchNorm module provi...
1b923a28a4727b72768acf0fc00d93d9012c5349
3,642,147
def _compute_bic( data: np.array, n_clusters: int ) -> BICResult: """Compute the BIC statistic. Parameters ---------- data: np.array The data to cluster. n_clusters: int Number of clusters to test. Returns ------- results: BICResult The results as a BICR...
3eb1a759a60f834f4e4fb7e364c9bce4ffb61230
3,642,148
def release_branch_name(config): """ build expected release branch name from current config """ branch_name = "{0}{1}".format( config.gitflow_release_prefix(), config.package_version() ) return branch_name
0d97c515aca8412882c8b260405a63d20b4b0f63
3,642,149
def torch2numpy(data): """ Transfer data from the torch tensor (on CPU) to the numpy array (on CPU). """ return data.numpy()
c7ca4123743c4f054d809f0e307a4de079b0af10
3,642,150
def new_schema(name, public_name, is_active=True, **options): """ This function adds a schema in schema model and creates physical schema. """ try: schema = Schema(name=name, public_name=public_name, is_active=is_active) schema.save() except IntegrityError: raise Exception('...
efd6ed2737c6a25e8beeaef9f7fffebdb9592f10
3,642,151
def find_appropriate_timestep(simulation_factory, equilibrium_samples, M, midpoint_operator, temperature, timestep_range, DeltaF_neq_thresho...
94000a07cfc8cf00e3440ff242c63da5c8be5d00
3,642,152
def critical_bands(): """ Compute the Critical bands as defined in the book: Psychoacoustics by Zwicker and Fastl. Table 6.1 p. 159 """ # center frequencies fc = [ 50, 150, 250, 350, 450, 570, 700, 840, 1000, 1170, ...
6301a6ee86d0ea3fb588213aa8b9453b14fb7036
3,642,153
def repackage(r, amo_id, amo_file, target_version=None, sdk_dir=None): """Pull amo_id/amo_file.xpi, schedule xpi creation, return hashtag """ # validate entries # prepare data hashtag = get_random_string(10) sdk = SDK.objects.all()[0] # if (when?) choosing sdk_dir will be possible # sdk ...
9527f2fbe6077e25eee72a570f2e9702cbf3b510
3,642,154
def edges_to_adj_list(edges): """ Transforms a set of edges in an adjacency list (represented as a dictiornary) For UNDIRECTED graphs, i.e. if v2 in adj_list[v1], then v1 in adj_list[v2] INPUT: - edges : a set or list of edges OUTPUT: - adj_list: a dictionary with the vertices as ...
683f10e9a0a9b8a29d63b276b2e550ebe8287a05
3,642,155
from typing import Optional def _get_lookups( name: str, project: interface.Project, base: Optional[str] = None) -> list[str]: """[summary] Args: name (str): [description] design (Optional[str]): [description] kind (Optional[str]): [description] Returns: list...
c8f700a19bbae0167c8474f033d625a763743db8
3,642,156
def unwrap(value): """ Unwraps the given Document or DocumentList as applicable. """ if isinstance(value, Document): return value.to_dict() elif isinstance(value, DocumentList): return value.to_list() else: return value
7e25c2935ff0a467e51097c4291e8d5f751c34db
3,642,157
def home_all(): """Home page view. On this page a summary campaign manager view will shown with all campaigns. """ context = dict( oauth_consumer_key=OAUTH_CONSUMER_KEY, oauth_secret=OAUTH_SECRET, all=True, map_provider=map_provider() ) # noinspection PyUnresol...
d987486f30cc5a8f6e697d9ccb92741b2d2067e4
3,642,158
import math def _sqrt(x): """_sqrt.""" isnumpy = isinstance(x, np.ndarray) isscalar = np.isscalar(x) return np.sqrt(x) if isnumpy else math.sqrt(x) if isscalar else x.sqrt()
16f566493deeaaf35841548e6db89408ca686bfe
3,642,159
def update_subnet(context, id, subnet): """Update values of a subnet. : param context: neutron api request context : param id: UUID representing the subnet to update. : param subnet: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow_put'...
f1ac159f612d3b8a5459ee3b70c440cf7cf84cd5
3,642,160
def validate_params(): """@rtype bool""" def validate_single_param(param_name, required_type): """@rtype bool""" inner_result = True if not rospy.has_param(param_name): rospy.logfatal('Parameter {} is not defined but needed'.format(param_name)) inner_result = Fal...
8734d9db7e29b8b6c30dc8a3ae72b0cf18c85310
3,642,161
def user_exists(username): """Return True if the username exists, or False if it doesn't.""" try: adobe_api.AdobeAPIObject(username) except adobe_api.AdobeAPINoUserException: return False return True
3767bec38c8058e7bd193e5532e4150ca501a96a
3,642,163
def bags_containing_bag(bag: str, rules: dict[str, list]) -> int: """Returns the bags that have bag in their rules.""" return {r_bag for r_bag, r_rule in rules.items() for _, r_color in r_rule if bag in r_color}
f9e67a4ade4dd9bdf25e05669741c71270007215
3,642,164
def default_mutable_arguments(): """Explore default mutable arguments, which are a dangerous game in themselves. Why do mutable default arguments suffer from this apparent problem? A function's default values are evaluated at the point of function definition in the defining scope. In particular, we can ...
a58a8c2807e29af68d501aa5ad4b33ad1aa80252
3,642,165
def is_text_file(file_): """ detect if file is of type text :param file_: file to be tested :returns: `bool` of whether the file is text """ with open(file_, 'rb') as ff: data = ff.read(1024) return not is_binary_string(data)
d064b51ea239f34ed97d47416b1f411650ce8a1a
3,642,166
from typing import Union from datetime import datetime from typing import List import pytz def soft_update_datetime_field( model_inst: models.Model, field_name: str, warehouse_field_value: Union[datetime, None], ) -> List[str]: """ Uses Django ORM to update DateTime field of model instance if the ...
33034a548ee572706cd1e6e696d5a9249ad0b528
3,642,167
import itertools def plot_confusion_matrix( y_true, y_pred, normalize=False, cmap=plt.cm.Blues, label_list = None, visible=True, savepath=None): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normali...
f15d2170ba0e869cb47e554ea374f93b05dbcab8
3,642,168
def _test_pressure_reconstruction(self, g, recon_p, point_val, point_coo): """ Testing pressure reconstruction. This function uses the reconstructed pressure local polynomial and perform an evaluation at the Lagrangian points, and checks if the those values are equal to the point_val array. Param...
b70b202cc21ba632f18af2f5fcf72f7b6d509e91
3,642,169
def logout(): """Logout :return: Function used to log out the current user """ logout_user() return redirect(url_for('index'))
f5e2ef30b47c645ba5671395a115eb6d6c9425f1
3,642,170
def get_user_messages(user, index=0, number=0): """ 返回指定user按时间倒序的从index索引开始的number个message """ if not user or user.is_anonymous or index < 0 or number < 0: return tuple() # noinspection PyBroadException try: if index == 0 and number == 0: all_message = user.messa...
bb0c499e5ca8ec650d2ebca12852d2345733e882
3,642,172
def third_party_apps_default_dc_modules_and_settings(klass): """ Decorator for DefaultDcSettingsSerializer class. Updates modules and settings fields defined in installed third party apps. """ logger.info('Loading third party apps DEFAULT DC modules and settings.') for third_party_app, app_dc_...
59be03a271e60352b429d45ecff647100388f9ab
3,642,173
from typing import Union from pathlib import Path def split_lvis( n_experiences: int, train_transform=None, eval_transform=None, shuffle=True, root_path: Union[str, Path] = None, ): """ Creates the example Split LVIS benchmark. This is a toy benchmark created only to show how a detect...
efece586ec6bfbc45911ed9f4f2ad5ead2cfd88b
3,642,174
def compute_log_ksi_normalized(log_edge_pot, #'(t-1,t)', log_node_pot, # '(t, label)', T, n_labels, log_alpha, log_beta, temp_array_1, temp_array_2): """ to obtain the two-slice posteri...
e4e6ea464851ba64d640e14fd7c88e9c52f28f50
3,642,175
from typing import Any from typing import Type def _deserialize_union(x: Any, field_type: Type) -> Any: """Deserialize values for Union typed fields Args: x (Any): value to be deserialized. field_type (Type): field type. Returns: [Any]: desrialized value. """ for arg in f...
01793983a0a82fc16c03adbe57f52de9be5c81ea
3,642,177
def read_simplest_expandable(expparams, config): """ Read expandable parameters from config file of the type `param_1`. Parameters ---------- expparams : dict, dict.keys, set, or alike The parameter names that should be considered as expandable. Usually, this is a module subdictiona...
4e2068e4a6cbca050da6a33a24b5fb0d2477e4e3
3,642,178
from typing import Callable from typing import Iterable from typing import Any def rec_map_reduce_array_container( reduce_func: Callable[[Iterable[Any]], Any], map_func: Callable[[Any], Any], ary: ArrayOrContainerT) -> "DeviceArray": """Perform a map-reduce over array containers recursivel...
885862371ece1e1f041a44693704300945d8d4a0
3,642,179
import json def load_augmentations_config( placeholder_params: dict, path_to_config: str = "configs/augmentations.json" ) -> dict: """Load the json config with params of all transforms Args: placeholder_params (dict): dict with values of placeholders path_to_config (str): path to the json ...
49f3170033411418e7e5468aecdcdc612a677e66
3,642,181
import numpy def simplify_mask(mask, r_ids, r_p_zip, replace=True): """Simplify the mask by replacing all `region_ids` with their `root_parent_id` The `region_ids` and `parent_ids` are paired from which a tree is inferred. The root of this tree is value `0`. `region_ids` that have a corresponding `p...
b8344a893319ad7a26f931b2edbc6ef452b82c24
3,642,182
def getStops(ll): """ getStops Returns a list of stops based off of a lat long pair :param: ll { lat : float, lng : float } :return: list """ if not ll: return None url = "%sstops?appID=%s&ll=%s,%s" % (BASE_URI, APP_ID, ll['lat'], ll['lng']) try: f = u...
eedfc49a02ab6c2ccf45e241262236804007a156
3,642,183
import warnings import six def rws(log_joint, observed, latent, axis=None): """ Implements Reweighted Wake-sleep from (Bornschein, 2015). This works for both continuous and discrete latent `StochasticTensor` s. :param log_joint: A function that accepts a dictionary argument of ``(string, Tens...
eb6278919dd484884b3110681680e67d3ee17d2f
3,642,184
def fit_svr(X, y, kernel: str = 'rbf') -> LinearSVR: """ Fit support vector regression for the given input X and expected labes y. :param X: Feature data :param y: Labels that should be correctly computed :param kernel: type of kernel used by the SVR {‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed...
10a38fca990c4ab058d582fbe38bd05df7456660
3,642,185
import typing def process_get_namespaces_from_accounts( status: int, json: list, network_type: models.NetworkType, ) -> typing.Sequence[models.NamespaceInfo]: """ Process the "/account/namespaces" HTTP response. :param status: Status code for HTTP response. :param json: JSON data for resp...
748bdca72db0640e75f8a0c063f7968ea9583e94
3,642,186
def _hexsplit(string): """ Split a hex string into 8-bit/2-hex-character groupings separated by spaces""" return ' '.join([string[i:i+2] for i in range(0, len(string), 2)])
672e475edeaafaa08254845e620b0a771b294fa8
3,642,188
def get_analysis_id(analysis_id): """ Get the new analysis id :param analysis_id: analysis_index DataFrame :return: new analysis_id """ if analysis_id.size == 0: analysis_id = 0 else: analysis_id = np.nanmax(analysis_id.values) + 1 return int(analysis_id)
3318764daadca6c1e1921847f623fcac169e2cb5
3,642,189
from typing import Union def get_station_pqr(station_name: str, rcu_mode: Union[str, int], db): """ Get PQR coordinates for the relevant subset of antennas in a station. Args: station_name: Station name, e.g. 'DE603LBA' or 'DE603' rcu_mode: RCU mode (0 - 6, can be string) db: inst...
d796639866421876bc58a7621d37bbe7239da6df
3,642,190
from typing import List def hello_world(cities: List[str] = ["Berlin", "Paris"]) -> bool: """ Hello world function. Arguments: - cities: List of cities in which 'hello world' is posted. Return: - success: Whether or not function completed successfully. """ try: [print("Hello...
a24f0f47c9b44c97f46524d354fff0ed9a735fe3
3,642,191
import random def random_samples(traj_obs, expert, num_sample): """Randomly sample a subset of states to collect expert feedback. Args: traj_obs: observations from a list of trajectories. expert: an expert policy. num_sample: the number of samples to collect. Returns: new expert data. """ ...
55aa4312c095ce97b8cf2840ff9ca61e393dff63
3,642,193
def get_p2_vector(img): """ Returns a p2 vector. We calculate the p2 vector by taking the radial mean of the autocorrelation of the input image. """ radvars = [] dimX = img.shape[0] dimY = img.shape[1] fftimage = np.fft.fft2(img) final_image = np.fft.ifft2(fftimage*np.conj(fftim...
7544751bf268d6eea432e21efe3d3a7703b16c1b
3,642,195
def multiplex(n, q, **kwargs): """ Convert one queue into several equivalent Queues >>> q1, q2, q3 = multiplex(3, in_q) """ out_queues = [Queue(**kwargs) for i in range(n)] def f(): while True: x = q.get() for out_q in out_queues: out_q.put(x) t...
4de6fa4fd495c2b320c4cdf28aa56df4411b7aa9
3,642,197
def stack(arrays, axis=0): """ Join a sequence of arrays along a new axis. The `axis` parameter specifies the index of the new axis in the dimensions of the result. For example, if ``axis=0`` it will be the first dimension and if ``axis=-1`` it will be the last dimension. .. versionadded:: 1.1...
ba8a2b514c32a1dc7a15215e5e26a90f2ace9a26
3,642,198
def verifica_cc(numero): """verifica_cc(numero): int -> tuple Funcao que verifica o numero do cartao, indicando a categoria e a rede emissora""" numero_final = str(numero) if luhn_verifica(numero_final) == True: categor = categoria(numero_final) rede_cartao = valida_iin(numero_final) ...
f6d3501b8154c05058006575f8aa33c228b9ade6
3,642,200
def create_security_group(stack, name, rules=()): """Add EC2 Security Group Resource.""" ingress_rules = [] for rule in rules: ingress_rules.append( SecurityGroupRule( "{0}".format(rule['name']), CidrIp=rule['cidr'], FromPort=rule['from_por...
e4d2b81fc1c3b0b3231725aa8757ea644d2efdf6
3,642,201
from typing import List import tqdm def features_targets_and_externals( df: pd.DataFrame, region_ordering: List[str], id_col: str, time_col: str, time_encoder: OneHotEncoder, weather: Weather_container, time_interval: str, latitude: str, longitude: str, ): """ Function that...
c9fc9fc210407ec596facda1bc43952ce9c6b98a
3,642,202
def transform_child_joint_frame_to_parent_inertial_frame(child_body): """Return the homogeneous transform from the child joint frame to the parent inertial frame.""" parent_joint = child_body.parent_joint parent = child_body.parent_body if parent_joint is not None and parent.inertial is not None: ...
0ab8761ef40101368fb3f2b657c329cd8cf5cf2b
3,642,204
def team_to_repos(api, no_repos, organization): """Create a team_to_repos mapping for use in _add_repos_to_teams, anc create each team and repo. Return the team_to_repos mapping. """ num_teams = 10 # arrange team_names = ["team-{}".format(i) for i in range(num_teams)] repo_names = ["some-rep...
390da146c3f96c554f9194f8551a066eec535533
3,642,205
def box_minus(plus_transform: pin.SE3, minus_transform: pin.SE3) -> np.ndarray: """ Compute the box minus between two transforms: .. math:: T_1 \\boxminus T_2 = \\log(T_1 \\cdot T_2^{-1}) This operator allows us to think about orientation "differences" as similarly as possible to position...
838f5e8b4f91450c311c72d4526e4c8fd3c9d6f7
3,642,206
import struct def padandsplit(message): """ returns a two-dimensional array X[i][j] of 32-bit integers, where j ranges from 0 to 16. First pads the message to length in bytes is congruent to 56 (mod 64), by first adding a byte 0x80, and then padding with 0x00 bytes until the message length is ...
ea06a3fc91e19ed0dbea6ddcc2ee6d554fb5a40f
3,642,207
import requests def base_put(url_path, content): """ Do a PUT to the REST API """ response = requests.put(url=settings.URL_API + url_path, json=content) return response
dde94c1dba0d8a931a0eae0e8f5ce63d1f5a62a1
3,642,208
def inverse_rotation(theta: float) -> np.ndarray: """ Compute inverse of the 2d rotation matrix that rotates a given vector by theta without use of numpy.linalg.inv and numpy.linalg.solve. Arguments: theta: rotation angle Return: Inverse of the rotation matrix """ rotation_matri...
732183f7577969a1ecbbd0ee5ed86342c65991fc
3,642,209
import functools def _config_validation_decorator(func): """A decorator used to easily run validations on configs loaded into dicts. Add this decorator to any method that returns the config as a dict. Raises: ValueError: If the configuration fails validation """ @functools.wraps(func) ...
1a63254e43c2920d6952105d9860138c395cbf2b
3,642,210
import functools def image_transpose_exif(im): """ https://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image Apply Image.transpose to ensure 0th row of pixels is at the visual top of the image, and 0th column is the visual left-hand side. Return the original image if unable to...
4f166ea59c097e4306bd43db7165e56e8d289b6a
3,642,211
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs): """Return optimised pore diameter and it's COM.""" args = elements, coordinates if com is not None: pass else: com = center_of_mass(elements, coordinates) if bounds is None: pore_r = pore_diameter(...
f75a7c4246bc2ad096de309795d61afea78f7c3e
3,642,213
def animate_operators(operators, date): """Main.""" results = [] failures = [] length = len(operators) count = 1 for i in operators: try: i = i.encode('utf-8') except: i = unicode(i, 'utf-8') i = i.encode('utf-8') print(i, count, "/",...
d8dd6afdd4a13ab62a4c821bb43050af07fdc455
3,642,214
def add_stocks(letter, page, get_last_page=False): """ goes through each row in table and adds to df if it is a stock returns the appended df """ df = pd.DataFrame() res = req.get(BASE_LINK.format(letter, page)) soup = bs(res.content, 'lxml') table = soup.find('table', {'id': 'Companyli...
ce86ef68a107fbae8d0028486bef8567dc24c43e
3,642,217
def available_parent_amount_rule(model, pr): """ Each parent has a limited resource budget; it cannot allocate more than that. :param ConcreteModel model: :param int pr: parent resource :return: boolean indicating whether pr is staying within budget """ if model.parent_possible_allocations[...
e1ccc7e9ad4941bfffebefd34217cd58c5bc18e5
3,642,218
def extract_coords(filename): """Extract J2000 coordinates from filename or filepath Parameters ---------- filename : str name or path of file Returns ------- str J2000 coordinates """ # in case path is entered as argument filename = filename.split("/")[-1] if ...
57f0ca79223116caa770a1dbea2eda84df146855
3,642,219
def exponential(mantissa, base, power, left, right): """Return the exponential signal. The signal's value will be `mantissa * base ^ (power * time)`. Parameters: mantissa: The mantissa, i.e. the scale of the signal base: The exponential base power: The exponential power left: Left bound of...
a2fbd76b6426f600d19eb9caeb4edac88dea9a9c
3,642,220
def get_features(features, featurestore=None, featuregroups_version_dict={}, join_key=None, online=False): """ Gets a list of features (columns) from the featurestore. If no featuregroup is specified it will query hopsworks metastore to find where the features are stored. It will try to construct the query ...
03cfc250bd921b291ac38fce5beddac3144e65ba
3,642,221
def get_flex_bounds(x, samples, nsig=1): """ Here, we wish to report the distribution of the subchunks 'sample' along with the value of the full sample 'x' So this function will return x, x_lower_bound, x_upper_bound, where the range of the lower and upper bound expresses the standard deviation ...
0fb4120307f61aafce902e92a32c66fd9aad91bf
3,642,222
def _parse_multi_header(headers): """ Parse out and return the data necessary for generating ZipkinAttrs. Returns a dict with the following keys: 'trace_id': str or None 'span_id': str or None 'parent_span_id': str or None 'sampled_str': ...
2ac3d0cbee196385e970bcc85827c1a467b5bb3b
3,642,223
import numpy def get_tgimg(img): """ 处理提示图片,提取提示字符 :param img: 提示图片 :type img: :return: 返回原图描边,提示图片按顺序用不同颜色框,字符特征图片列表 :rtype: img 原图, out 特征图片列表(每个字), templets 角度变换后的图 """ imgBW = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) h, w = imgBW.shape _, imgBW = cv2.threshold(imgBW, 0, 255, ...
5f48e2b639dd3027e6463b1a99a8b7c13c043f88
3,642,224
def brand_profitsharing_order_query(self, transaction_id, out_order_no, sub_mchid): """查询连锁品牌分账结果 :param transaction_id: 微信支付订单号,示例值:'4208450740201411110007820472' :param out_order_no: 商户分账单号,只能是数字、大小写字母_-|*@,示例值:'P20150806125346' :param sub_mchid: 子商户的商户号,由微信支付生成并下发。示例值:'1900000109' """ if sub_...
cb1af072f2b4f94f632817baff6cdfea66110873
3,642,225
def get_controller_from_module(module, cname): """ Extract classes that inherit from BaseController """ if hasattr(module, '__controller__'): controller_classname = module.__controller__ else: controller_classname = cname[0].upper() + cname[1:].lower() + 'Controller' controller_c...
b450105f6ec38a03fe461c5d9c07c4652da0efd3
3,642,226
def exp(d: D) -> NumDict: """Compute the base-e exponential of d.""" return d.exp()
a4d5baf6bdfadb48add80096bb4d167f01572b69
3,642,227
def Main(operation, args): """Supports 2 operations 1. Consulting the existing data (get) > get ["{address}"] 2. Inserting data about someone else (certify) > certify ["{address}","{hash}"] """ if len(args) == 0: Log('You need to provide at least 1 parameter - [address]')...
0dac2ddb4dc3d259e30f5a3c100a39ff8d7b940d
3,642,228
def get_latest_file_list_orig1(input_list, start_time, num_files): """ Return a list of file names, trying to get one from each index file in input_list. The starting time is start_time and the number of days to investigate is num_days. """ out = [] for rind in input_list: # Create time...
744b5392d136129a1135cea3ad577817798ef582
3,642,229
def get_ogheader(blob, url=None): """extract Open Graph markup into a dict The OG header section is delimited by a line of only `---`. Note that the page title is not provided as Open Graph metadata if the image metadata is not specified. """ found = False ogheader = dict() for line in...
4edd7c5545ddef241ee2bfd5e316e47a336aaa3f
3,642,230
def list_ingredient(): """List all ingredients currently in the database""" ingredients = IngredientCollection() ingredients.load_all() return jsonify(ingredients=[x.to_dict() for x in ingredients.models])
d3275dba18922b9f4558f23eedda3ae25d8a25d9
3,642,231
import re def ParseSavedQueries(cnxn, post_data, project_service, prefix=''): """Parse form data for the Saved Queries part of an admin form.""" saved_queries = [] for i in xrange(1, MAX_QUERIES + 1): if ('%ssavedquery_name_%s' % (prefix, i)) not in post_data: continue # skip any entries that are bla...
5db4ecdf22eb61c1c43914f00042862142664590
3,642,232
def label_anchors(anchors, anchor_is_untruncated, gt_classes, gt_bboxes, background_id, iou_low_threshold=0.41, iou_high_threshold=0.61): """ Get the labels of the anchors. Each anchor can be labeled as positive (1), negative (0) or ambiguous (-1). Truncated anchors are always labeled as ambiguous. """ n = anch...
39dc4d29f5a2491c2f818e7af2c01e1824afff56
3,642,233
import hashlib def make_hash_md5(obj): """make_hash_md5 Args: obj (any): anything that can be hashed. Returns: hash (str): hash from object. """ hasher = hashlib.md5() hasher.update(repr(make_hashable(obj)).encode()) return hasher.hexdigest()
c8c0f0202f171e2557eba6a3824ac2f9a07dada9
3,642,234
def fbx_data_bindpose_element(root, me_obj, me, scene_data, arm_obj=None, mat_world_arm=None, bones=[]): """ Helper, since bindpose are used by both meshes shape keys and armature bones... """ if arm_obj is None: arm_obj = me_obj # We assume bind pose for our bones are their "Editmode" pose....
9d205cd3c7a0242dbfaad42d1e7f0b9b3b81eb75
3,642,235
def partitioned_rml_estimator(y, sigma2i, iterations=50): """ Implementation of the robust maximum likelihood estimator. Parameters ---------- y : :py:class:`~numpy.ndarray`, (n_replicates, n_variants) The variant scores matrix sigma2i : :py:class:`~numpy.ndarray`, (n_replicates, n_vari...
b4ec6ad8af85cdf29470fa132d7f6008617b3a66
3,642,236
import math def inv_kinema_cal_3(JOINT_ANGLE_OFFSET, L, H, position_to_move): """逆運動学を解析的に解く関数. 指先のなす角がηになるようなジョイント角度拘束条件を追加して逆運動学問題を解析的に解く 引数1:リンク長さの配列.nd.array(6).単位は[m] 引数2:リンク高さの配列.nd.array(1).単位は[m] 引数3:目標位置(直交座標系)行列.nd.array((3, 1)).単位は[m] 戻り値(成功したとき):ジョイント角度配列.nd.array((6)).単位は[°] ...
4368c847b9918f3682e2ca0336008af49f0823cf
3,642,237
from django.contrib.auth import authenticate, login def http_basic_auth(func): """ Attempts to login user with u/p provided in HTTP_AUTHORIZATION header. If successful, returns the view, otherwise returns a 401. If PING_BASIC_AUTH is False, then just return the view function Modified code by...
fd99ce1464acb88bd9f68b6b85233dd44cb81bfd
3,642,241
def stats_to_df(stats_data): """ Transform Statistical API response into a pandas.DataFrame """ df_data = [] for single_data in stats_data['data']: df_entry = {} is_valid_entry = True df_entry['interval_from'] = parse_time( single_data['interval']['from']).date() ...
d77d3ee46c68c737ce8274458d8564256f8121a7
3,642,242
def make_risk_metrics( stocks, weights, start_date, end_date ): """ Parameters: stocks: List of tickers compatiable with the yfinance module weights: List of weights, probably going to be evenly distributed """ if mlfinlabExists: Var, VaR, CVaR, CD...
8a24d542a8b7475a66c0c914866ee4225564b8ed
3,642,243
def decrypt(bin_k, bin_cipher): """decrypt w/ DES""" return Crypto.Cipher.DES.new(bin_k).decrypt(bin_cipher)
fa8331b792ae4003c2fc14fd84b2ac82306bc7b2
3,642,244
from ucscsdk.mometa.vnic.VnicIScsiLCP import VnicIScsiLCP from ucscsdk.mometa.vnic.VnicVlan import VnicVlan def lcp_iscsi_vnic_add(handle, name, parent_dn, addr="derived", admin_host_port="ANY", admin_vcon="any", stats_policy_name="global-default", ...
6d87f8f3adebaa56850dfb14137fe049ff6e01ee
3,642,246
def fixture_ecomax_with_data(ecomax: EcoMAX) -> EcoMAX: """Return ecoMAX instance with test data.""" ecomax.product = ProductInfo(model="test_model") ecomax.set_data(_test_data) ecomax.set_parameters(_test_parameters) return ecomax
4f496342d461eb39e4689ed266471b11bdf3f1f5
3,642,247
async def request_get_stub(url: str, stub_for: str, status_code: int = 200): """Returns an object with stub response. Args: url (str): A request URL. stub_for (str): Type of stub required. Returns: StubResponse: A StubResponse object. """ return StubResponse(stub_for=stub_f...
f4c4f9a0610e8d95f920ddee76c4264e23c08283
3,642,249
import torch def single_gpu_test(model, data_loader, rescale=True, show=False, out_dir=None): """Test with single GPU. Args: model (nn.Module): Model to be tested. data_loader (nn.Dataloader): Pytorch data loader. show (bool): Whether show results during infernece. Default: False. ...
0e548186e5909b1a7b72d6fd6ed16c80e233e0b6
3,642,250
def readAllCarts(): """ This function responds to a request for /api/people with the complete lists of people :return: json string of list of people """ # Create the list of people from our data return[CART[key] for key in sorted(CART.keys())]
7ec9b25b36c238a6bfae3963482d610ed09d1d75
3,642,251
import random import logging def build_encapsulated_packet(select_test_interface, ptfadapter, tor, tunnel_traffic_monitor): """Build the encapsulated packet sent from T1 to ToR.""" _, server_ipv4 = select_test_interface config_facts = tor.get_running_config_facts() try: peer_ipv4_address = [_[...
e7776a602eeb0dbe9bcd8707b71dacfe4ac36338
3,642,252
def index(): """ Renders the index page. """ return render_template("index.html")
cc7630c3bbaf32c3be705a7205df715f959a5683
3,642,253