content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional import re def extraer_numero_iniciativa(numero_evento: str) -> Optional[int]: """Algunos numeros de evento traen la iniciativa a la que pertenecen, esta función intenta extraer el ID Returns ------- int or None ID de iniciative o None si no existe un numero con...
3c1abffca75a66bfad5c9556a194b904b39422c0
39,110
def next_key(tuple_of_tuples, key): """Processes a tuple of 2-element tuples and returns the key which comes after the given key. """ for i, t in enumerate(tuple_of_tuples): if t[0] == key: try: return tuple_of_tuples[i + 1][0] except IndexError: ...
cb4cdad805049cf57db21180c390bccfb8483f45
39,111
def sort_crt(crt): """Sort df by CRT""" return (crt[1],) + get_name_sortkey(crt[0])
804d951aacd67184a6558a83812488051f4661bf
39,112
def zd_to_airmass(zd): """ conversion of zenith airmass into airmass assuming Pickering (2002). """ alt = 90. - zd # Altitude in degrees return 1. / np.sin((alt + 244. / (165. + 47. * alt**1.1)) / RAD2DEG)
634b94685c5575530585407241d4da26944f5ff7
39,114
def create_final_generator_network( Z, projection_layer, to_rgb_conv_layers, blocks, original_image_size, params): """Creates base generator network. Args: Z: tensor, latent vectors of shape [cur_batch_size, latent_size]. projection_layer: `Dense` layer for projection of noise into imag...
8f5a83a018f9d35817de92f156457b26716a4f64
39,115
def delete_redshift_cluster(config, redshift): """ Deletes the Redshift cluster specified in config Args: config: a ConfigParser object redshift: a boto3 client object for the AWS Redshift service """ try: print("Deleting Redshift Cluster: ", config['CLUSTER']['IDENTIFIER']) ...
2267eb4f017354563c9a7cf047a3a84983cd0044
39,117
def NaturalColor(C, gamma=0.8, pseudoGreen=True, night_IR=False, **kwargs): """ Natural Color RGB based on CIMSS method. Thanks Rick Kohrs! (See `Quick Guide <http://cimss.ssec.wisc.edu/goes/OCLOFactSheetPDFs/ABIQuickGuide_CIMSSRGB_v2.pdf>`__ for reference) Check out Rick Kohrs `merged GOES images <htt...
86acae6d74057771578f25a9f9aac9369a570624
39,118
def _get_adjacency_list(graph): """Convert a list of edges into an adjacency list.""" adj = {} for i, j in graph: if i in adj: ni = adj[i] else: ni = adj[i] = set() if j in adj: nj = adj[j] else: nj = adj[j] = set() ni.a...
933ba9aa28a13e145be175120520253ef53c2a88
39,119
def behavior_of(classname): """ Finds and loads the behavior class for C++ (decoded) classname or returns None if there isn't one. Behaviors do not have a required base class, and they may be used with Awkward Array's ``ak.behavior``. The search strategy for finding behavior classes is: 1...
cd0a104620cb98edacad8d822d3d64a030b0ae99
39,120
def pareto_rank(df: pd.DataFrame, objectives: list, max_rank: int = 10) -> pd.DataFrame: """ Rank solutions based on pareto dominance :param df: :param objectives: :return: DataFrame with additional column 'pareto_rank' """ df['pareto_rank'] = np.nan rank = 0 evaluating = df[objecti...
60aeaa7c52adbcfb79a71ba754c2ae8fe13a35a1
39,121
def get_domain_notes(domain): """ Combine all domain notes if there are any. """ all_notes = domain.http.notes + domain.httpwww.notes + domain.https.notes + domain.httpswww.notes all_notes = all_notes.replace(',', ';') return all_notes
f199e909184475f6c84a290ef7ac5ad9ff160a54
39,122
def add_trailing_load(axle_spacing, axle_wt, space_to_trailing_load, distributed_load, span1_begin, span2_end, pt_load_spacing=0.5): """Approximates the distributed trailing load as closely spaced point loads. The distributed trailing load is approximated as discretly spaced point loads. The point ...
3eac900cff7d5e66c399e7f846d66aeff3e7389c
39,123
def str_append(string, add): """Append add in end string. Example: str_append('hou', 'se'); Return='house'""" return string + str(add) + "\n"
efbc9a085d1e63f290af3e6c447cde13bce5f5d0
39,124
def parse_trigger_plugin(trigger_path, plugin_config, parse_only=False): """Parse plugin file and return the trigger config.""" # Open and exec plugin definitions with open(trigger_path, 'r') as f: trigger_code = f.read() trigger_vars = {} exec(trigger_code, trigger_vars) # Get trigger...
69feab8e6d109f9f5a641c3fb738710e97707e19
39,125
import json def signout(): """Signout. 退出。 """ session.pop('kb', None) session.pop('islogin', None) database.skb = '' state = { 'success' : 1, 'message' : "退出成功" } return json.dumps(state)
dfb38a2aad6f4deaf0e971c3e604ab005759a353
39,126
from .plot_utils import make_3d_axis, Arrow3D def plot_axis_angle(ax=None, a=a_id, p=p0, s=1.0, ax_s=1, **kwargs): """Plot rotation axis and angle. Parameters ---------- ax : Matplotlib 3d axis, optional (default: None) If the axis is None, a new 3d axis will be created a : array-like, s...
5a239a26eb070c0f7a4126b22ceff5f40098b0fb
39,128
from typing import Tuple from typing import List import numpy def generate_hash_rates(hash_rate_parameter: int, number_of_honest_miners: int, malicious_hash_ratio: float) -> \ Tuple[List[float], List[float]]: """ :param number_of_honest_miners: :param malicious_hash_ratio: :return: """ ...
5c02a78015c8f0d16922a37e5de163ca287932ba
39,129
def create_function(treatment_system, parameter, values): """ Creates a function based on user input """ func = str(treatment_system.loc[0, parameter]) func = func.replace(' ', '') for key, value in values.items(): func = func.replace(key, str(value)) return func
d0afaf42e50aef943b7551c60f19d180bbbeba0b
39,130
def _ResourceGraphvizNode(resource, request, resource_to_index): """Returns the node description for a given resource. Args: resource: Resource. request: RequestData associated with the resource. resource_to_index: {Resource: int}. Returns: A string describing the resource in graphviz format. ...
e3a1ba2bbe73992444cd001f44f2ac9546f256af
39,131
def unformat(combination: str) -> str: """Unformats a formatted string to it's original state""" return str(combination).replace("<", "").replace(">", "")
d017903ddaac78adf5085198d25eb508b62a78b4
39,132
def common_base(cls: type, *clss: type) -> type: """ Overview: Get common base class of the given classes. Only ``__base__`` is considered. Arguments: - cls (:obj:`type`): First class. - clss (:obj:`type`): Other classes. Returns: - base (:obj:`type`): Common ba...
40d43f9aa71537604d2a48ea7705985653f4ed8b
39,133
def get_all_configs() -> Response: """Get and return all configs by name""" return flask.jsonify(config.get_config_names())
dda1c4991129e8c5072ab06c60777d8eeece3ffb
39,134
def dewpoint(temperature, humidity, *, model='hardy', isdew=True): """Calculate the dew point. Parameters ---------- temperature : :class:`float` The temperature [degree C]. humidity : :class:`float` The humidity [%RH]. model : :class:`str` The dew point model, valid mod...
f2e2b7512a3f7a4ce5ded2fd9f7e51cb9f743408
39,135
import re def parse_list_marker(line, offset): """ Parse a list marker and return data on the marker (type, start, delimiter, bullet character, padding) or null. """ rest = line[offset:] spaces_after_marker = None data = ListData() if reHrule.search(rest): return None ...
b295d46c5c4e3ad4b6ac845f883b949c3e18b75b
39,136
def resize(img, height=800, allways=False): """Resize image to given height.""" if (img.shape[0] > height or allways): rat = height / img.shape[0] return cv.resize(img, (int(rat * img.shape[1]), height)) return img
011e42c0ef4fbc1c7e77914673a1d3d61771ff92
39,137
import re def _size_to_bytes(size): """ Parse a string with a size into a number of bytes. I.e. parses "10m", "10MB", "10 M" and other variations into the number of bytes in ten megabytes. Floating-point numbers are rounded to the nearest byte. :type size: ``str`` :param size: The size to parse, given as a stri...
833657e51bb2c54b0e86684759e263d2f8b03ffe
39,138
import torch def transform_to_tensor_per_dataset(feature, label, drug,device, basal_expression_file): """ :param feature: features like pertid, dosage, cell id, etc. will be used to transfer to tensor over here :param label: :param drug: ??? a drug dictionary mapping drug name into smile strings ...
f238ffa2a042942d5df2cf858435a5b1e5080872
39,140
def isbn_gendigit (numStr): """ (string)-->(string + 1-digit) Generates the 10th digit in a given 9-digit isbn string. Multiplies the values of individual digits within the given 9-digit string to determine the 10th digit. Prints the original string with its additional 10th digit. ('123456788')-->12...
2ceb5cb4f2f8efc2ee9625138666f7cca2c4aefb
39,141
def count_unique_sequences_per_otu(otu_ids, otu_map_file, input_seqs_file): """Counts unique sequences per-OTU for a given set of OTUs otu_ids: a set of OTU IDs otu_map_file: file-like object in the format of an OTU map input_seqs_file: FASTA containing sequences that were used to generate ...
8a50160ac14a6a6960c63a68f8b23e5fe3df043a
39,142
from typing import Tuple def fetch_add_portmapping_services() -> Tuple[UPnPServiceNames, ...]: """ :return: returns the available devices and services for which the action 'AddPortMapping' exists """ devices = upnpclient.discover() if not devices: raise NoPortMapServiceFound("No UPnP devic...
006fc914558be3afa9f8c05451c8816d6e7c0cb4
39,143
def is_valid_group(group_name, nova_creds): """ Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option. """ valid_groups = [value['SUPERNOVA_GROUP'] for key, value in nova_creds.items() if 'SUPERNOVA_GROUP' in nova_creds[key].k...
6f94e88cfcea8775bab3c05a0720ba7df11f68cc
39,144
import math def Make_scroll_bar(self, scroll_bar): """ Make a scroll_bar for a Text object. For internal use only. This function is therefore also not imported by __init__.py """ if isinstance(scroll_bar, Slider): scroll_bar.right = self.width - self.text_offset[0] scroll_bar.cente...
1cf7e94dfddb32a9ac55e72a58b41b6642a96411
39,146
def value_iteration(env, rewards): """ Computes a policy using value iteration given a list of rewards (one reward per state) """ n_states = env.observation_space.n n_actions = env.action_space.n V_states = np.zeros(n_states) theta = 1e-8 gamma = .9 maxiter = 1000 policy = np.zeros(n_sta...
29dcd90de0881986f2b08621dd0fac32c5eee305
39,147
def mktime(t): """mktime(tuple) -> floating point number Convert a time tuple in local time to seconds since the Epoch.""" tm_year = t[0] tm_mon = t[1] - 1 tm_mday = t[2] tm_hour = t[3] tm_min = t[4] tm_sec = t[5] date = JS("new Date(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hou...
e35b7a4f1367f9951201540c17aa4032113e5113
39,148
import pandas def package_matrix(request, pkg=None, arch=None): """ Generate a build matrix for one or more specs. """ # Unique package names and os options packages = ( Spec.objects.exclude(build=None).values_list("name", flat=True).distinct() ) failed_packages = ( Spec.ob...
2bcfb437062b92bc4c02140b07a9cdf5803f0995
39,149
def _PlcReady(timeout=1): """Returns True if PLC AIO node reports actuator state is 'ready'.""" t_start = time.time() while time.time() - t_start < timeout: ready = (listener.status_msg and (listener.status_msg.detwist_state == actuator_types.kActuatorStateReady)) if...
1da6241efdfe8b1bcae5e8894f35a6708a11f963
39,151
from typing import List def convert_dataframe(metrics: List[Metric]) -> pd.DataFrame: """ convert_dataframe converts list of metric to pandas DataFrame """ fields = ['date', 'point'] columns = {'date': 'ds', 'point': 'y'} return pd.DataFrame([{f: getattr(m, f) for f in fields} for m in metrics...
2bf41a0089928c6f1842dd56ff86e6ca47a7e079
39,152
def linear_shap_corr(model, data): """ Linear SHAP (corr 1000) """ return LinearExplainer(model, data, nsamples=1000).shap_values
9239b8a1083195321a766cd9894db307276ab33d
39,153
import torch def ind2sub(ind, shape, out=None): """Convert linear indices into sub indices (i, j, k). The rightmost dimension is the most rapidly changing one -> if shape == [D, H, W], the strides are therefore [H*W, W, 1] Parameters ---------- ind : tensor_like Linear indices sh...
001a88850721f8946c48a395454e6818e78a7887
39,154
import requests def get_repo_prs(r, state, base, session): """ Get all pull requests of a given repository :param r: repository name 'author/repo-name' :param state: state of the PR :param base: base branch :param session: open and authenticated session :type r: string ...
898f1937978114df673e0291a2a18f7e5f3f2d12
39,155
def register(): """Register user""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("firstname"): return apology("must provide FIR...
7799a1a7284fb311bd58fbb1f6882bf84d49b2e7
39,156
def format_sse(data: str, event=None) -> str: """Formats a string and an event name in order to follow the event stream convention. >>> format_sse(data=json.dumps({'abc': 123}), event='Jackson 5') 'event: Jackson 5\\ndata: {"abc": 123}\\n\\n' """ msg = f'data: {data}\n\n' if event is not None:...
a97cbd392b3ed087c5663fc1e874c30c20d61039
39,157
from typing import Tuple async def _unpack_message(session: Session, enc_message: bytes) -> Tuple[str, str, str]: """Decode a message using the DIDComm v1 'unpack' algorithm.""" try: wrapper = JweEnvelope.from_json(enc_message) except ValidationError: raise WalletError("Invalid packed mess...
84c96ac11a19f59a2e205c3f3a6ec8597c22e519
39,158
def minweight_match_realmxeigs(a, b, metricfn=None, pass_indices_to_metricfn=False, eps=1e-9): """ Matches the elements of `a` and `b`, whose elements are assumed to either real or one-half of a conjugate pair. Matching is performed by minimizing the weight between elements, ...
e98d7f4f5f41e9672a2863fc5d7bc2c2c8bf0c10
39,159
def _invert_aliases(): """Reverse the alias dictionary to be a lookup from command to aliases.""" out = _defaultdict(list) for alias, name in ALIASES.items(): out[name].append(alias) return out
d4b88ee5434fe989cd71ae730573cd4b6bab1562
39,160
import math def get_positive_expectation(p_samples, average=True): """Computes the positive part of a JS Divergence. Args: p_samples: Positive samples. average: Average the result over samples. Returns: th.Tensor """ log_2 = math.log(2.) Ep = log_2 - tlx.softplus(- p_sa...
db8d991ebe2bf46c58d150cb7d0fdd5122e0ccaa
39,161
def setbit(byte, offset, value): """ Set a bit in a byte to 1 if value is truthy, 0 if not. """ if value: return byte | (1 << offset) else: return byte & ~(1 << offset)
037fa6e6a14c502554a3e5ee94e2f9ed63e2f717
39,162
def insertDoubleQuote(string, index): """ Insert a double quote in the specified string at the specified index and return the string.""" return string[:index] + '\"' + string[index:]
00d16f3bc619765895408f9fcdd3a7a6e428b153
39,163
import io import base64 def title_cloud(cat, rate, year): """ Makes a word cloud of movie and TV show titles. Parameters ---------- cat: list List of genres we want to filter out from the dataframe. rate: list List of ratings we want to filter out from the dataframe. y...
af42db09486a60fab6e7da5df0dc53b5f24deefc
39,164
import torch def run_one_epoch_aae(model, x, y, num_critic=1, clip_value=0.01, train=True, optimizer=None, batch_size=None, return_loss=True, loss_weight=[1., 1., 1.], loss_fn_cls=nn.CrossEntropyLoss(), loss_fn_reg=nn.MSELoss(), loss_fn_critic=nn.L1Lo...
125d6d34eb50b5f20b6d726a90cc85040f9c571c
39,165
def And(*seq): """ Return boolean expression ``x1 and x2 and ...``. """ c = Logic.convert return Logic.And(*map(c, seq))
f6229ca92a52263d26476741c2f3ce9e495678c1
39,166
def powerlaw(x, a, b, c): """Powerlaw function used by fitting software to characterise uncertainty.""" return a * x**b + c
e67a0be2f5faaff7867b713b43caec48910bad87
39,167
def quatFromXYZW(xyzw, seq): """Convert quaternion from XYZW (pybullet convention) to arbitrary sequence.""" assert ( len(seq) == 4 and "x" in seq and "y" in seq and "z" in seq and "w" in seq ), "Quaternion sequence {} is not valid, please double check.".format(seq) inds = ["xyzw".index(axis) fo...
87d8a907fd5fc95c320df03feeffe8c185ad78e9
39,168
def readPeakList(peak_file): """ Read in list of peaks to delete from peaks_file. Comment lines (#) and blank lines are ignored. """ f = open(peak_file,'r') peak_list = f.readlines() f.close() peak_list = [l for l in peak_list if l[0] != "#" and l.strip() != ""] peak_list = [...
7c99f9fb18b36b658fe142a43adf18db7c42c7bd
39,169
import ast def parse_coordinates(raw_coordinates): """Parses cell coordinates from text.""" return {ast.literal_eval(x) for x in ast.literal_eval(raw_coordinates)}
b550709c29ba56b1dec73a94bdccda1af743c2c9
39,170
import itk def array_view_from_vector_container( container: "itkt.VectorContainer", ttype=None ) -> np.ndarray: """Get an Array view with the content of the vector container""" container_template = itk.template(container) IndexType = container_template[1][0] # Find container type if ttype is...
0f2824993eb3f5504d6985e593a4b05ee49e9271
39,171
def convert_linear_problem_to_dual(model, sloppy=False, infinity=None, maintain_standard_form=True, prefix="dual_", dual_model=None): # NOQA """ A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is a minimization problem the dual is a maximization probl...
196ff6f48cdadce1f248586485adc772f889d0a7
39,172
def snake_case(text): """Converts `text` to snake case. Args: text (str): String to convert. Returns: str: String converted to snake case. Example: >>> snake_case('This is Snake Case!') 'this_is_snake_case' .. versionadded:: 1.1.0 .. versionchanged:: 4.0.0 ...
0836bc291e01daa74287af7e3e2e52b80628344a
39,173
def chunkify(tsd, seq_len): """ Splits a TimeSeriesDataset into chunks of length seq_len Args: tsd: TimeSeriesDataset object seq_len: length of the subsequences to return Returns: numpy arrays with chunks of size seq_len """ x, y = [], [] for s in tsd: for i in ra...
a3ad94bed06cfaad05663d4898fdeb9e3e6200e3
39,174
from typing import Dict import secrets def create_survey( title: str, hide_votes: bool, is_anonymous: bool, description: str, question_author_name_field_visible: bool, limit_question_characters_enabled: bool, limit_question_characters: int, author: User)...
9ae8271c4b2f228264555bc2daa887222b270a47
39,175
def remove_batch_dimension(shape: tuple) -> tuple: """Set the batch dimension to None as it does not matter for the Network interface.""" shape = list(shape) shape[0] = None shape = tuple(shape) return shape
92b7cd7a7165338cc397e530b0b81513910b46b0
39,176
import string def load(path): """Load an image from given path. Automatically de-compresses.""" file, reason = filesystem.open(path, 'rb') if file: ## print(f'Length: {file.proxy.size(path)[0]}') readSignature = string.char(file.readString(len(OCIFSignature))) if readSignature == OC...
32843e05059a468df8c6e5e2ef282e159da6caeb
39,177
def compute_windows(numpy_image, patch_size, patch_overlap): """Create a sliding window object from a raster tile. Args: numpy_image (array): Raster object as numpy array to cut into crops Returns: windows (list): a sliding windows object """ if patch_overlap > 1: raise Valu...
d85c91ad7684c03eea25763b9fbbcf87ddf78df4
39,178
from datetime import datetime def date_to_format(value, target_format): """Convert date to specified format""" if target_format == str: if isinstance(value, datetime.date): ret = value.strftime("%d/%m/%y") elif isinstance(value, datetime.datetime): ret = value.strftime(...
dba55f49ea4c2c016803d80b6c80809629062df5
39,179
def fetch_file(file_id: str, chunk: int = None, verify: bool = False) -> FileStatus: """Fetches file information Args: file_id: The id of the file to fetch chunk: (Optional) If included, fetches a single chunk instead of the entire file. verify: (Optional) If included, fetches file vali...
67a4a67cd70c97c0f50fd13924e293650b4a198a
39,181
import string def __get_settings(file_name): """ Opens the settings file associated to a csv file and returns it. :param file_name: The path to settings file. :type file_name: str :return: The settings. :rtype: dict[str, str] """ settings = {} if not file_name.endswith('.setting')...
4da37f3f2581196446515e06a3d4a6b93d0e15f2
39,182
import torch def set_device(args, distributed=False, rank=0): """ set parameter to gpu or cpu """ if torch.cuda.is_available(): if isinstance(args, list): return (set_gpu(item, distributed, rank) for item in args) elif isinstance(args, dict): return {key:set_gpu(args[ke...
99f5c1a1214d5c52003aa87dcb44845e2452594d
39,183
def oned_const_vel_bump(g=3.5,total=10000): """ make figure for traveling bump """ dat = oned_simple.SimDat(g=g,q=0,zshift=.1,T=total) # get four bumps at four equal time intervals. use second half of sim, # use velocity to determine time intervals # Peaks of phase plot over time are at ...
880eab55b73b71874da52d453c991150c3959d81
39,184
def article_published_today(link): """ Compares the date the article was written with today's date.""" soup = lvm.soup_session(link) todays_date = (date.today() - timedelta(0)).strftime("%B %#d, %Y") # The # is platform specific date_to_check = soup.find('time', attrs={'class': 'date'}) return date_to_check ==...
bbc9b235e5cbe156e83dc103eafb1052ce99ccbb
39,186
def nearest_neighbor(left_gdf, right_gdf, k_neighbors=1, return_left_columns=True, return_right_columns=True): """ For each point in left_gdf, find closest point in right GeoDataFrame and return them. Adapted from https://stackoverflow.com/questions/62198199/k-nearest-points-from-two-dataframes-with-geopand...
52f50bf54c9b12ef1ab11eaf3c83325b27f585a8
39,188
import string import json import torch def load_sequences_from_file(path, voc_path): """ Used for reading sentences or sequences of slots. Splits input lines into lists of words and performs word to id transformation. :param path: path to txt file with data :param voc_path: path to json file with ...
f23a55f550b5ae9cd852ee1e16532c0595f21380
39,189
def lambda_handler(event, context): """ main function """ try: for region in get_regions(): stop_instances(get_untagged_instances(region), region) return { "statusCode": 200, "body": "successfully shutted down all untagged instances", } except: ...
db7e683f6e98d546b3c77749e59b1baff52e4142
39,190
from sphinx.util.inventory import InventoryFile as IFile def sphinx_load_test(): """Return function to perform 'live' Sphinx inventory load test.""" def func(path): """Perform the 'live' inventory load test.""" with path.open("rb") as f: try: IFile.load(f, "", osp....
6ab148dd821119cf8d299cc6bbecfe82a6c2966f
39,191
from operator import pos def position() -> s.SearchStrategy[pos.Position]: """Generates a random Position. Returns: A new search strategy. """ return s.builds(pos.Position)
bd85a07677a5fa34842561549a318a4a138f742f
39,192
import base64 def get_gpg_keys(conn, dns): """ Grab pgpKeyInfo records (base64 encoded gpg keys) for the key attribute entries in LDAP, returning a dict {key_attr: pgpKeyInfo} """ r = {} for dn in dns: data = get_dn_attribute(conn, dn, '(objectClass=pgpKeyInfo)', 'pgpKey') ...
5fbc0dc8e7e7c45d500f5834ca6f1431532271ff
39,193
import numpy def get_pandas_field_metadata(pandas_col_metadata, field_name): """ Fetch information for a given column. The column statistics returned will be a bit different depending on if the types in the column are a number or a string. 'NAN' values are stripped from statistics and don't even s...
cbf1a740a202c36fa7b008451d44582e195d71f8
39,194
def predict_single_image(model, image): """ Predict the bounding box quads for a single image :param model: :param image: :return: """ im_resized, (ratio_h, ratio_w) = east_utils.resize_image(image) im_resized = cv2.cvtColor( im_resized, cv2.COLOR_BGR2RGB) image_batch = np.expand_di...
f22e7788d4be372b710ac5ead9188e5bb22b97d0
39,195
def get_reduced_string( text: list[int], suffix_arr: list[int], lms_suffixes: list[int] ) -> tuple[list[int], bool]: """ >>> suffix_arr = [10, 0, 1, 2, 3, 4, 6, 8, 5, 7, 9] >>> lms_suffixes = [6, 8, 10] >>> get_reduced_string("AAAAACACAG", suffix_arr, lms_suffixes) ([1, 2, 0], False) """ ...
b6b5078ec160799912eb99a02009d65751a1347f
39,196
def gridappsdvolttron(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Gridappsdvolttron :rtype: GridAPPSDVolttron """ try:...
1656b8d877a64a8ec746196fca162165a5fb67a0
39,198
def is_valid_if_yes_definition(definition): """ Returns true if the if_yes definition is valid. str -> bool """ if definition.count(constants.QUESTION_DENOTE) < 2 or definition[0] != constants.QUESTION_DENOTE: return False # First char is white space so it needs to be removed. if_tr...
a68e8e4bce14802cf8693bd2803669743298be4f
39,199
def get_route_count(device, table, protocol, active=True, output=None): """ Get total route count for each table via 'show route target_route extensive' Args: device (`obj`): Device object table (`str`): Table name such as `inet.0`, `inet6.0` protocol (`str`): Protocol name such as ...
b152088e5d6d0c9e4e2b68e9b141181b9577b9ad
39,200
def deep_replace(arr, x, y): """ Help function for extended_euclid """ for i in range(len(arr)): element = arr[i] if type(element) == list: arr[i] = deep_replace(element, x, y) else: if element == x: arr[i] = y return arr
55ef1c7efe04d436f9ce96bda0f565a092131400
39,202
def get_imgaug_transform(cfg: DictConfig) -> iaa.Sequential: """Create simple data transform pipeline that resizes images.""" data_transform = iaa.Resize( { "height": cfg.data.image_resize_dims.height, "width": cfg.data.image_resize_dims.width, } ) return iaa.Sequ...
6a18dc04fca1d18e40a3f28ae22d6761a96dd53f
39,203
def inerIntra(groupes, centres): """Calcul de l'inertie intra-groupe d'une liste de groupes""" inerGroupeList = [] i = 0 for centre in centres: inerGroupeList.append(inerGroupe(groupes[i], centre)) i = i + 1 inersum = 0 for iner in inerGroupeList: inersum += iner retu...
0d2f39eefdcfd3f02191111e318820e1c767234f
39,204
def k_prototypes(X, n_clusters, gamma, init, n_init, max_iter, verbose): """k-prototypes algorithm""" assert len(X) == 2, "X should be a list of Xnum and Xcat arrays" # List where [0] = numerical part of centroid and # [1] = categorical part. Same for centroids. Xnum, Xcat = X # Convert to nump...
5ee8cb28ef84862fe980b1e6b70437b6893a675a
39,205
def update_password(password, value, position=None): """Update password with value :param str password: The password string :param str value: The character(s) to update with :param int position: The position in which to insert the character(s) :return: The updated password """ result = list...
19287d5fd65141de6edbd806b18419e54492e201
39,206
import yaml def run_distribute(filename, distribution, graph=None, algo=None): """ Run the distribute cli command with the given parameters """ filename = instance_path(filename) algo_opt = '' if algo is None else '-a ' + algo graph_opt = '' if graph is None else '-g ' + graph cmd = 'pydco...
395d956f922ffedf4bfbe7cbcfe6f200017543f6
39,207
def find_pmp(df): """simple function to find Pmp on an IV curve""" return df.product(axis=1).max()
5ed7c14bc58a62f6168308ccd1dfa17e56e2db89
39,208
def chebyshev_distance(v1, v2, norm=False): """ return ||v1 - v2||_oo """ v1, v2 = check_pairwise_vector(v1, v2, norm) diff = v1 - v2 K = np.abs(diff).max() return K
b65fbdfe3dee68f360ef66e0fd3c4ee5085be062
39,209
def get_distances_from_other_points(point_index: int, num_samples: int, distance_matrix: ndarray): """Get distances from point i to other points in the dataset. Args: point_index: The index of the point. num_samples: The number of points. distance_matrix: Condensed distance matrix. ...
e9610355ddc37fd58261bfb9233cc5a20ca4c2ac
39,210
def get_help_option(input_args): """Get help about option or values authorized for option.""" global cmdhelp_settings, cmdhelp_option_infolist global cmdhelp_option_infolist_fields pos = input_args.find(' ') if pos > 0: option = input_args[0:pos] else: option = input_args opt...
5436480c38a32de189ab1c2418519d5216502a46
39,212
import math from datetime import datetime def aggregate_report(): """Generate a report with total of resources in used and reserved for each aggregate.""" context = {} aggregates = Aggregates.objects.all() for aggregate in aggregates: # Add aggregate on context dict if aggregate...
134d59d1c58cb7160b88bbf596fe9f51b39e0cdb
39,213
def create_app(object_name): """ :argument object_name: the python path of the config object :return: app """ app = Flask(__name__) app.config.from_object(object_name) db.init_app(app) app.register_blueprint(main_blueprint) return app
3596a4c887326af72692189654e936bc4816308e
39,214
def fix_timestamp(dataframe): """ Convert timestamp from UTC into engine timezone and from ISO to format expected by graphs :param1 dataframe: data frame to process return: dataframe with converted timestamp column """ dataframe["timestamp"] = dataframe["timestamp"].apply(convert_from_utc, args=(__eng...
8ed075fb6afb5c5269ebf5def7c75a3632ccc7a4
39,215
def scale(data, remove_outliers=False): """ Scales the input and removes outliers """ if remove_outliers: perc_2 = np.zeros(data.shape[1]) perc_98 = np.zeros(data.shape[1]) for i in range(data.shape[1]): perc_2[i] = np.percentile(data[:, i], 2) perc_98[i] ...
1eec5537e3762f36e46eef37b36297c7b83359a8
39,217
def subpixel_values(img, pts): """ References: stackoverflow.com/uestions/12729228/simple-efficient-binlinear-interpolation-of-images-in-numpy-and-python SeeAlso: cv2.getRectSubPix(image, patchSize, center[, patch[, patchType]]) """ # Image info nChannels = get_num_channels(img)...
7778c91a320a61caecef42dec98d83861d4798a4
39,218
def loadZenMakeMetaFile(filePath): """ Load ZenMake common ConfigSet file. Return None if failed """ dbfile = db.PyDBFile(filePath, extension = '') try: data = dbfile.load(asConfigSet = True) except EnvironmentError: return None return data
5ab84701e2f18ffb397f4d22528a87c627e84041
39,219
def readable_timedelta(days): """Print the number of weeks and days in a number of days.""" #to get the number of weeks we use integer division weeks = days // 7 #to get the number of days that remain we use %, the modulus operator remainder = days % 7 return "{} week(s) and {} day(s).".format(w...
120f517939842b4e0686a57a3117221e3db63004
39,220
def create_net(in_sx, in_sy, out_sx): """ Creates a tflearn neural network with the correct architecture for learning to hear the keyword """ net = tflearn.input_data([None, in_sx, in_sy]) net = tflearn.lstm(net, lstm_size, dropout=lstm_dropout) net = tflearn.fully_connected(net, out_sx, activation='softmax') n...
686df9637496c1595fc0bed55e03a9eec550e0b9
39,221
def compute_iou(boxes1, boxes2): """ compute_iou() 函数用来计算 IOU 值,即真实检测框与预测检测框( 当然也可以是任意两个检测框)的交集面积比上 它们的并集面积,这个值越大,代表这个预测框与真实框的位置越接近 如果说得到的 IOU 值大于设置的正阈值,那么我们称这个预测框为正预测框( positive anchor)其中包含着检测目标; 如果说得到的 IOU 值小于于设置的负阈值,那么我们称这个预测框为负预测框( )negative anchor),其中包含着背景 """ le...
ba6ae63a8d15233fd18a100c6e50c2176559ecaa
39,222