content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_exploration_summary_from_model(exp_summary_model): """Returns an ExplorationSummary domain object. Args: exp_summary_model: ExplorationSummary. An ExplorationSummary model instance. Returns: ExplorationSummary. The summary domain object correspoding to the given...
c6561670f976e28a3869eb89c4be3ba884808da0
13,616
def get_service(api_name, api_version, scope, key_file_location, service_account_email): """Get a service that communicates to a Google API. Args: api_name: The name of the api to connect to. api_version: The api version to connect to. scope: A list auth scopes to authorize for the appl...
6c333f43c5feb5b44128b8f592586804eba68e1e
13,617
from IsabelaFunctions.langlais_coeff import glm as g from IsabelaFunctions.langlais_coeff import hlm as h import tqdm def model_map(lon, lat, alt, comp, binsize = 0.1, nmax = 134, a = 3393.5): """ Calculates a map of one component of the crustal magnetic field field model, for a given altitude. Param...
9a49e4a1f31180cd7a26f2028c5e45d077103346
13,618
def parse_command(incoming_text): """ incoming_text: A text string to parse for docker commands returns: a fully validated docker command """ docker_action = '' parse1 = re.compile(r"(?<=\bdocker\s)(\w+)") match_obj = parse1.search(incoming_text) if match_obj: docker_ac...
abe82ae2fe29014b3441889c973a412a536b78f1
13,619
def angle_connectivity(ibonds): """Given the bonds, get the indices of the atoms defining all the bond angles A 'bond angle' is defined as any set of 3 atoms, `i`, `j`, `k` such that atom `i` is bonded to `j` and `j` is bonded to `k` Parameters ---------- ibonds : np.ndarray, shape=[n_bond...
86c992a1a8ac2d3c6b1fbc5a137ef0734a3079ed
13,621
def BOPDS_PassKeyMapHasher_IsEqual(*args): """ :param aPKey1: :type aPKey1: BOPDS_PassKey & :param aPKey2: :type aPKey2: BOPDS_PassKey & :rtype: bool """ return _BOPDS.BOPDS_PassKeyMapHasher_IsEqual(*args)
8da04f1755e3d2f7d10ad3ecf5ec6b0d00ca5fcb
13,622
def dms2dd(s): """convert lat and long to decimal degrees""" direction = s[-1] degrees = s[0:4] dd = float(degrees) if direction in ('S','W'): dd*= -1 return dd
cb76efbf8c3b6a75bcc26593fab81a8ef3e16bbf
13,624
def setna(self, value, na=np.nan, inplace=False): """ set a value as missing Parameters ---------- value : the values to set to na na : the replacement value (default np.nan) Examples -------- >>> from dimarray import DimArray >>> a = DimArray([1,2,-99]) >>> a.setna(-99) di...
6ada601dee346d5440a64ffdbf8d2642873bdb08
13,625
def hbox(*items, **config): """ Create a DeferredConstraints object composed of horizontal abutments for a given sequence of items. """ return LinearBoxHelper('horizontal', *items, **config)
cdfe16a35c73a2f8406207a0262b4210ce86146f
13,626
def find_columns(clause): """locate Column objects within the given expression.""" cols = util.column_set() visitors.traverse(clause, {}, {'column':cols.add}) return cols
86b4c866a8fbe20ab1d4b0a34e4940155df00744
13,627
def _preprocess_data(smiles, labels, batchsize = 100): """ prepares all input batches to train/test the GDNN fingerprints implementation """ N = len(smiles) batches = [] num_bond_features = 6 for i in range(int(np.ceil(N*1./batchsize))): array_rep = utils.array_rep_from_smi...
3456fe2059e386088d359ec0c2d54dff2d7fac25
13,628
def linear_activation_forward(A_prev, W, b, activation, keep_prob=1): """ Implement the forward propagation for the LINEAR->ACTIVATION layer Arguments: A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples) W -- weights matrix: numpy array of shape (...
0e4d12142224bfb46af0afb547abe3dde0aa6811
13,629
def load_image(image_path, size): """ Load an image as a Numpy array. :param image_path: Path of the image :param size: Target size :return Image array, normalized between 0 and 1 """ image = img_to_array(load_img(image_path, target_size=size)) / 255. return image
3d9a790b762f800a222c26578dc0572587b091fb
13,631
import signal def _signal_exit_code(signum: signal.Signals) -> int: """ Return the exit code corresponding to a received signal. Conventionally, when a program exits due to a signal its exit code is 128 plus the signal number. """ return 128 + int(signum)
050eee98632216fddcbd71e4eb6b0c973f6d4144
13,632
import csv def make_template_matrix(msigdb_file, blacklist, checkblacklist=True): """ Retrieve all genes and pathways from given msigdb .gmt file Output: sorted gene by pathways pandas dataframe. Entries indicate membership """ all_db_pathways = [] all_db_genes = [] # Get a set o...
b8068089279dfbe3b3cfc8b16dee016cc0994746
13,633
def unwrap_key( security_control: SecurityControlField, wrapping_key: bytes, wrapped_key: bytes ): """ Simple function to unwrap a key received. """ validate_key(security_control.security_suite, wrapping_key) validate_key(security_control.security_suite, wrapped_key) unwrapped_key = aes_key_...
7720ad8905f6818b1a3fa4132b040560a9ae0dfa
13,634
def checkOwnership(obj, login_session): """ This function helps to check if the current logged in user is the creator of the given category or a given item. This function return True if the current user owns the category, otherwise, it will return False. """ # the user has logged in at ...
851d2dafae633ed92698af525b1c717091edb2b7
13,635
import logging def transform_file_name(original_file_name): """ Now, this is just whatever I felt like. Whee. So in this function I could have just used 0 and 1 as my indices directly when I look at the different parts of the file name, but it's generally better to name these sorts of things, so peop...
daa5b3be0ae7a40c9d20ac4a8aa37c51dec89c89
13,637
import pandas def remove_overlapping_cells(graph): """ Takes in a graph in which each node is a cell and edges connect cells that overlap eachother in space. Removes overlapping cells, preferentially eliminating the cell that overlaps the most cells (i.e. if cell A overlaps cells B, C, and D, wher...
bd133c5ddd59f950d34ba16fb7bc3ff0215f0cf2
13,638
def main_page(request) : """Renders main page and gets the n (matrix demension number)""" if request.method != 'POST' : form = InputForm() else : form = InputForm(data=request.POST) if form.is_valid() : return redirect('calculator:set_demensions') context ...
a6131ea837c8d9b986e8579a40ada1f7a0a3bb64
13,639
def int2fin_reference(n): """Calculates a checksum for a Finnish national reference number""" checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10) return "%s%s" % (n, checksum)
f21e66cb917631797d62ecc8ba2728b18d36ae1c
13,640
def COLSTR(str, tag): """ Utility function to create a colored line @param str: The string @param tag: Color tag constant. One of SCOLOR_XXXX """ return SCOLOR_ON + tag + str + SCOLOR_OFF + tag
abe3d9111a30ebb678d1f1a2011d3b8a3ad39a75
13,641
def get_instance_pricing(instance_types): """ Get the spot and on demand price of an instance type in all the regions at current instant :param instance_types: EC2 instance type :return: a pandas DataFrame with columns as region, spot price and on demand price """ all_regions = ...
62dba0e3c3f46ac460178da0bc4d615869819f83
13,642
import itertools async def get_user_groups(request): """Returns the groups that the user in this request has access to. This function gets the user id from the auth.get_auth function, and passes it to the ACL callback function to get the groups. Args: request: aiohttp Request object Ret...
9fd62d6f971c871ce290700f3abb7eb467692533
13,643
def plot_bivariate_correlations(df, path=None, dpi=150): """ Plots heatmaps of 2-variable correlations to the Target function The bivariate correlations are assmebled using both the arithmatic and geometric means for two subplots in the figure. Parameters ---------- df: dataframe path: ...
d5dc7da98228aa7b7865510bd4dcd6531e7049bc
13,644
from torch.utils.data import DataLoader def create_datastream(dataset_path, **kwargs): """ create data_loader to stream images 1 by 1 """ if osp.isfile(osp.join(dataset_path, 'calibration.txt')): db = ETH3DStream(dataset_path, **kwargs) elif osp.isdir(osp.join(dataset_path, 'image_left')): ...
145f8c44e8e718fea9a9bdabf5e1f9497a00241a
13,645
def is_contained(target, keys): """Check is the target json object contained specified keys :param target: target json object :param keys: keys :return: True if all of keys contained or False if anyone is not contained Invalid parameters is always return False. """ if not target or not key...
948196d4b470788199506bd7768e03554fa67b40
13,646
def map(x, in_min, in_max, out_min, out_max): """ Map a value from one range to another :param in_min: minimum of input range :param in_max: maximum of input range :param out_min: minimum of output range :param out_max: maximum of output range :return: The value scaled ...
4117af35b0061df1fd271306accf198692442dac
13,647
import requests def get_points(sess: requests.Session, console: Console, status: Status, projectID: int): """ Get all exisiting points in a project """ base_url = f"https://mapitfast.agterra.com/api/Points" resp = sess.get(base_url, params={"projectId": projectID}) points_obj_list = list() ...
c5f1fce542b06d1680637750f51c3bd7a6e6ebc4
13,648
def calculate_discounted_returns(rewards): """ Calculate discounted reward and then normalize it (see Sutton book for definition) Params: rewards: list of rewards for every episode """ returns = np.zeros(len(rewards)) next_return = 0 # 0 because we start at the last timestep for...
538c3d5636bc6105ddf603f0928e4e891fea774c
13,649
def parse_binskim_old(bin_an_dic, output): """Parse old version of binskim.""" current_run = output['runs'][0] if 'results' in current_run: rules = output['runs'][0]['rules'] for res in current_run['results']: if res['level'] != 'pass': if len(res['formattedRuleMe...
bd927aa972148b1171dcf2d5c60aa219cf4527b6
13,651
import operator def binary_elementwise_compute( ifm: te.Tensor, ifm2: te.Tensor, lut: te.Tensor, operator_type: str, ifm_scale: float, ifm_zero_point: int, ifm2_scale: float, ifm2_zero_point: int, ofm_scale: float, ofm_zero_point: int, ifm_channels: int, ifm2_channels: ...
2bbac91e8606512180b6a652538eeac23e369c7c
13,652
def x_power_dependence(n, dep_keys, ctfs=list(), force_zero=None, **kwargs): """Returns a fit function that allows x^n depdendence on the constants associated with each of the dep_keys y(x) = (a0 * b0 + a1 * b1 + ...) * x^n where each of the a's are fit parameters and each of the b's are either ...
49b1a605001003b52f38f7f469a7c7bfafd43d6b
13,653
from typing import Iterable def get_subseqs(s, ops): """Returns a list of sequences given when applying the list of (ops) on them, until a constant one is found, thus: new[0] = next seq of s with ops[0] new[i] = next seq of new[i-1] with op[i] If 'ops' is not a list, then the s...
3ad7a955c7b55596f327ae52d34368451ef79737
13,654
def update_s(C,k): """ Args: C: 2d array k: 1d array Return: 1d array """ if np.shape(C)[0]==0: s = np.array([1]) else: temp = np.dot(C,k) s = np.append(temp,1) return s
ce4604d71b05d328d6b8b60bea9f611d8d12f6eb
13,656
def test_handler_callback_failure(): """Test failure mode for inappropriate handlers.""" class BadHandler(object): def handler(self, one): return 'too many' ob = EventTest() handler = BadHandler() with pytest.raises(TypeError): ob.PublicEvent += handler.handler ...
c5d8daf4cca81ef8dee8ba5a10b9e572899bd23e
13,657
def get_chord_type(chord): """'Parses' input for a chord and returns the type of chord from it""" cleaned_chord = chord[1:] cleaned_chord = cleaned_chord.replace('b', '') cleaned_chord = cleaned_chord.replace('#', '') mapping = { '7': 'seven', '9': 'nine', 'm7': 'minor7', ...
4a753eb31f1e33340a7aa4df6942c4752b208fdd
13,658
from typing import Union def transpile(model: Union[SympyOpt, Model]) -> SympyOpt: """Transpile optimization problem into SympyOpt model Only accepts SympyOpt or Docplex model. :param model: model to be transpiled :raises ValueError: if the argument is of inappropriate type :return: transpiled m...
f2b4895cb980e535166d9749eb93925722981828
13,660
def definition(): """View of the finances with subtotals generated.""" return sql.format(source=source)
c0b9add49b9c7403328449b8989e29739be267a9
13,661
import math def random_mini_batches(X, Y, mini_batch_size = 32, seed = 0): """ Creates a list of random minibatches from (X, Y) Arguments: X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci) Y -- true "label" vector (containing 0 if control, 1 if case), of shape (1, number ...
8baa63be638a1706c49176a51013524594a59452
13,662
def file_base_features(path, record_type): """Return values for BASE_SCHEMA features.""" base_feature_dict = { "record_id": path, "record_type": record_type, # "utc_last_access": os.stat(path).st_atime, "utc_last_access": 1600000000.0, } return base_feature_dict
12f16684002892d7af59a1e26e8a40501098ca4f
13,663
def split_ref(ref): """ セル参照をセル文字と1ベース行番号文字に分割する。 Params: ref(str): Returns: Tuple[str, str]: 列、行 """ m = re_cellref.match(ref) if m: return m.group(1), m.group(2) return None, None
1ae8e058a47ad0410b7131d4b89061dea822ed68
13,664
def table_definition(dataset): """print an azure synapse table definition for a kartothek dataset""" index_col = list(dataset.dataset_metadata.index_columns)[ 0 ] ##works only with one index column cols = synapse_columns( dataset.dataset_metadata.table_meta[dataset.table], index_col ...
75a2f55fa31025899e9adb05e20dbc89ae8dabd4
13,665
import itertools def node_extractor(dataframe, *columns): """ Extracts the set of nodes from a given dataframe. :param dataframe: dataframe from which to extract the node list :param columns: list of column names that contain nodes :return: list of all unique nodes that appear in the provided data...
7a4ab889257a0f2c5ddfe18e65d0a7f5f35d8d98
13,667
def _get_bag(environ, bag_name): """ Get the named bag out of the store. """ store = environ['tiddlyweb.store'] bag = Bag(bag_name) try: bag = store.get(bag) except NoBagError as exc: raise HTTP404('%s not found, %s' % (bag.name, exc)) return bag
db4e2425f6c4d839fa091c08b524ea8ecd3c7c27
13,668
def missing_values_operation(files): """Will take iterable file objects and eliminate features or samples with missing values or inputing missing values if necessary""" for i in files: with open(i,'rw') as f: if missing_values(f)==True: file_data=load_data(i) ...
df5a6f6809605107db9b008b877fa913a3dc686d
13,669
def _object_id(value): """Return the object_id of the device value. The object_id contains node_id and value instance id to not collide with other entity_ids. """ object_id = "{}_{}".format(slugify(_value_name(value)), value.node.node_id) # Add the instance id if...
34c21de533a99ffdabfdabf21540492f7ce33b7f
13,670
def _apply_attention_constraint( e, last_attended_idx, backward_window=1, forward_window=3 ): """Apply monotonic attention constraint. **Note** This function is copied from espnet.nets.pytorch_backend.rnn.attention.py """ if e.size(0) != 1: raise NotImplementedError( "Batch atten...
213ef514a9cff31134185e38c57d46921eba763a
13,671
from bs4 import BeautifulSoup import re def parse_reolink(email): """Parse Reolink tracking numbers.""" tracking_numbers = [] soup = BeautifulSoup(email[EMAIL_ATTR_BODY], 'html.parser') links = [link.get('href') for link in soup.find_all('a')] for link in links: if not link: c...
cc96d35edb2ace40d83464f4cc3bed1c91480f0f
13,673
def HMF(state, Delta, N): """Computes the result of the MF hamiltonian acting on a given state.""" #kinetic term: sum_i(eps(i)*(n_i,up + n_i,down)) kinetic_state = dict_list_sum( [dict_prod(eps(i, N), dict_sum(number_op(state, i, 0, N), number_op(state, i, 1, N))) for i in range(N)]) #interaction term: sum_i( ...
3c608d42a328e05fd59c55cbaeded3b6d0b4970b
13,674
def calculate_probability_of_multicoincidence(ambient_size: int = 0, set_sizes: tuple = (), intersection_size: int = 0): """ Calculates the probability that subsets of a set of a given size, themselves of prescribed ...
1d9deb083f0a0397b067f6efa989a94d68d11b69
13,675
def check_date(option, opt, value): """check a file value return the filepath """ try: return DateTime.strptime(value, "%Y/%m/%d") except DateTime.Error : raise OptionValueError( "expected format of %s is yyyy/mm/dd" % opt)
3f817bf2286b459b11ded67abba33b654b090caf
13,676
def no_cloud_fixture(): """Multi-realization cloud data cube with no cloud present.""" cloud_area_fraction = np.zeros((3, 10, 10), dtype=np.float32) thresholds = [0.265, 0.415, 0.8125] return cloud_probability_cube(cloud_area_fraction, thresholds)
5128c40485fdbc9c8646bec25d1949aac4cddb58
13,677
from typing import Iterable def make_slicer_query( database: Database, base_table: Table, joins: Iterable[Join] = (), dimensions: Iterable[Field] = (), metrics: Iterable[Field] = (), filters: Iterable[Filter] = (), orders: Iterable = (), ): """ Creates a pypika/SQL query from a lis...
31821bdbb0ab94c8971a70d35c1165f5245d90fb
13,678
def build_grid_generator(cfg, input_shape): """ Built an grid generator from `cfg.MODEL.GRID_GENERATOR.NAME`. """ grid_generator = cfg.MODEL.GRID_GENERATOR.NAME return GRID_GENERATOR_REGISTRY.get(grid_generator)(cfg, input_shape)
5f6edbaeece026fc56068aec0fc75549a71ce4a8
13,679
def main_page(request): """ This function is used to display the main page of programme_curriculum @param: request - contains metadata about the requested page """ return render(request, 'programme_curriculum/mainpage.html')
fdee3342d369112abb2560c4ecfda17a8dfe01e4
13,680
def _write_detailed_dot(graph, dotfilename): """Create a dot file with connection info digraph structs { node [shape=record]; struct1 [label="<f0> left|<f1> mid\ dle|<f2> right"]; struct2 [label="<f0> one|<f1> two"]; struct3 [label="hello\nworld |{ b |{c|<here> d|e}| f}| g | h"]; struct1:f1...
793983b56b8fff32fde4e9dc5379a93e4edcb16e
13,681
import functools def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True, bn=False): """ resample: None, 'down', or 'up' """ if resample=='down': conv_shortcut = MeanPoolConv conv_1 = functools.partial(lib.ops.conv2d.Conv2D, input_dim=inpu...
8871553f11975edef2a1b0bbf96aff8c54417adf
13,682
def timer(func): """Logging elapsed time of funciton (decorator).""" @wraps(func) def wrapper(*args, **kwargs): with timing(func.__name__): return func(*args, **kwargs) return wrapper
eb38d9856f59328188ac24e66f3bb4f9356ebe89
13,684
def peak_ana(x, y, nb=3, plotpoints_axis=None): """ nb = number of point (on each side) to use as background""" ## get background xb = np.hstack((x[0:nb], x[-(nb):])) yb = np.hstack((y[0:nb], y[-(nb):])) a = np.polyfit(xb, yb, 1) b = np.polyval(a, x) yf = y - b yd = np.diff(yf) ## d...
1f9ea444b09684ac7764ced8ba5ca3fdbd3e8593
13,685
from jams.distributions import sep_fs_mean, sep_fs_std def sample_sep01(nn, xi=1., beta=0.): """ Samples from the skew exponential power distribution with location zero and scale one. Definition ---------- def sample_sep01(nn, xi=1., beta=0.): Input ----- ...
dbeda8efa38db5d55b688c4bfc30350262c39f32
13,687
def pandas_from_feather(file: str = None) -> pd.DataFrame: """ Load a feather file to a pandas DataFrame. Uses pyarrow to load a csv file into a [pyarrow.Table](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html) and convert to pandas format. Args: file (str): the feathe...
2bd7679581690095865d9f9d2cae85cf9d736f8d
13,688
def email_coas(): """ Email certificates of analysis to their recipients. """ # Get the certificate data. # Email links (optional attachments) to the contacts. return NotImplementedError
b09c6650c498618b77a5e0beab0caf63a2cbf99d
13,690
import random def dropout(x, key, keep_rate): """Implement a dropout layer. Arguments: x: np array to be dropped out key: random.PRNGKey for random bits keep_rate: dropout rate Returns: np array of dropped out x """ # The shenanigans with np.where are to avoid having to re-jit if # keep ...
f9686e64a11e17ca35eefacaa8f0b356cc0f065e
13,691
def band_spd_spin_polarized( folder, output='band_spd_sp.png', scale_factor=2, order=['s', 'p', 'd'], color_dict=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, fontsize=7, annotations=['$\\uparrow$ ', '$\\d...
4cd0ef74a2ad4ce46d28aad296a9156ec91dc301
13,692
def initial_queries(bo): """ script which explores the initial query points of a BayesianOptimization instance, reports errors to Slack Input: instance of a BayesianOptimization """ # loop to try a second time in case of error errcount = 0 for i in range(2): try: bo.m...
3419cd89724a23296688f321469a68c8209d2a25
13,693
def cell2AB(cell): """Computes orthogonalization matrix from unit cell constants :param tuple cell: a,b,c, alpha, beta, gamma (degrees) :returns: tuple of two 3x3 numpy arrays (A,B) A for crystal(x) to Cartesian(X) transformations A*x = np.inner(A,x) =X B (= inverse of A) for Cartesian to c...
970acf484a701efcdb024e7cad5981ded314209e
13,695
def sendMessage(qry): """ Message sending handling, either update if the query suggests it otherwise send the message. :param qry: current query :return: Status of Message sending. """ try: getUserName() except: return _skypeError() if(qry == "skype update"): _writeFriends() ...
c13e187170015d3e9a786ceb7cb9a364928fa8c0
13,697
def scrape_detail_page(response): """ get detail page info as dict type """ root = lxml.html.fromstring(response.content) ebook = { 'url': response.url, 'title': root.cssselect('#bookTitle')[0].text_content(), 'price': root.cssselect('.buy')[0].text, 'content': [h3.te...
5c3b7e743cd109fe2d05e0cc261e46884c673421
13,698
import tqdm from pathlib import Path import torch def reload_from_numpy(device, metadata, reload_dir): """Reload the output of voice conversion model.""" conv_mels = [] for pair in tqdm(metadata["pairs"]): file_path = Path(reload_dir) / pair["mel_path"] conv_mel = torch.load(file_path) ...
7cf5b2c1f12886f8fcded9072a86c53384b93760
13,699
def jaccard_similarity_coefficient(A, B, no_positives=1.0): """Returns the jaccard index/similarity coefficient between A and B. This should work for arrays of any dimensions. J = len(intersection(A,B)) / len(union(A,B)) To extend to probabilistic input, to compute the intersection, use ...
fe408565827f61323513d7d3b562bd79a23e47ec
13,700
def get_argument_from_call(call_node: astroid.Call, position: int = None, keyword: str = None) -> astroid.Name: """Returns the specified argument from a function call. :param astroid.Call call_node: Node representing a function call to check. :param int...
e4b7e054c4728f5b74bcbbe1678816a910f64bda
13,701
def snake_string(ls): """ Question 7.11: Write a string sinusoidally """ result = [] strlen = len(ls) for idx in xrange(1, strlen, 4): result.append(ls[idx]) for idx in xrange(0, strlen, 2): result.append(ls[idx]) for idx in xrange(3, strlen, 4): result.append(l...
391f7cef4289c5746f77598501aeaa7ae93d31bc
13,702
def _prepare_memoization_key(args, kwargs): """ Make a tuple of arguments which can be used as a key for a memoized function's lookup_table. If some object can't be hashed then used its __repr__ instead. """ key_list = [] for arg in args: try: hash(arg) key_li...
c83e08c42886ba0e7f6e4defe5bc8f53f5682657
13,703
def kl_divergence_with_logits(p_logits = None, q_logits = None, temperature = 1.): """Compute the KL between two categorical distributions from their logits. Args: p_logits: [..., dim] array with logits for the first distribution. q_logits: [..., ...
1950dea9e5c6d040ce464e0861b09469742810c4
13,704
from typing import Any from datetime import datetime def convert_bosch_datetime(dt: Any = None) -> datetime: """Create a datetime object from the string (or give back the datetime object) from Bosch. Checks if a valid number of milliseconds is sent.""" if dt: if isinstance(dt, str): if dt....
845e9de019b700b2ab37ebb4a1b577d0bd068638
13,705
def day_log_add_id(day_log): """ その日のログにID(day_id)を割り振る :param day_log: :return: """ for v in range(len(day_log)): day_log[v]['day_id'] = v + 1 return day_log
c4608b07e86c074a11cf78d171490ec152092eeb
13,706
def cisco_ios_l3_acl_parsed(): """Cisco IOS L3 Interface with ip address, acl, description and vlan.""" vlan = Vlan(id="300", encapsulation="dot1Q") ipv4 = IPv4(address="10.3.3.13", mask="255.255.255.128") acl_in = ACL(name="Common_Client_IN", direction="in") acl_out = ACL(name="TEST_ACL_03", direct...
25c7ad34695499bb6426ff71a9893c233b54a925
13,707
def brillance(p, g, m = 255): """ p < 0 : diminution de la brillance p > 0 : augmentation de la brillance """ if (p + g < m + 1) and (p + g > 0): return int(p + g) elif p + g <= 0: return 0 else: return m
b40169e487521c146c4c0777517492205951cf16
13,708
def payback(request): """ 微信支付回调函数 :param request: :return: """ return HttpResponse('payback')
e178abe0effe6359a664dca434e181390c1a56c1
13,710
from datetime import datetime def get_index_shares(name, end_date=None): """获取某一交易日的指数成分股列表 symbols = get_index_shares("上证50", "2019-01-01 09:30:00") """ if not end_date: end_date = datetime.now().strftime(date_fmt) else: end_date = pd.to_datetime(end_date).strftime(date_fmt) ...
7a9e2890d0508b00d15da4688980736776199cfa
13,711
def erfcx(x): """Elementwise scaled complementary error function. .. note:: Forward computation in CPU cannot be done if `SciPy <https://www.scipy.org/>`_ is not available. Args: x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable. Returns: ~chainer.Variable...
60f1655a6e390ca935f80d33e0d9156879b56c41
13,712
def fetch_data_async(blob, start_index, end_index, rpc=None): """Asynchronously fetches data for a blob. Fetches a fragment of a blob up to `MAX_BLOB_FETCH_SIZE` in length. Attempting to fetch a fragment that extends beyond the boundaries of the blob will return the amount of data from `start_index` until the ...
518f1ef45c19b8a7be55940d9abdeaf0fe014835
13,713
def get_legal_moves(color, size, board): """ Get Legal Moves """ legal_moves = {} for y in range(size): for x in range(size): reversibles = get_reversibles(color, size, board, x, y) if reversibles: legal_moves[(x, y)] = reversibles return legal_...
eaab0b7fededbe660b02974f675877b97e3327f4
13,714
def edition(self, key, value): """Translates edition indicator field.""" sub_a = clean_val("a", value, str) if sub_a: return sub_a.replace("ed.", "") raise IgnoreKey("edition")
715724dffb4ef6d72c173afbf8186acfdf9f20e3
13,715
from typing import Dict from typing import Set import itertools def get_site_data(hostname: str) -> SiteData: """Get metadata about a site from the API""" url = f"https://{hostname}/w/api.php" data = dict( action="query", meta="siteinfo", siprop="|".join( [ ...
83ca853c6fb2ebadf6473b8f5da0008b145717b0
13,716
def clear_monitor(nodenet_uid, monitor_uid): """Leaves the monitor intact, but deletes the current list of stored values.""" micropsi_core.runtime.get_nodenet(nodenet_uid).get_monitor(monitor_uid).clear() return True
ad39c344f41fcf307f85d09add71eeeac66b30c1
13,717
def loadGrammarFrom(filename, data=None): """Return the text of a grammar file loaded from the disk""" with open(filename, 'r') as f: text = f.read() lookup = mako.lookup.TemplateLookup(directories=[relativePath('grammars')]) template = mako.template.Template(text, lookup=lookup) # base_...
0a0bbd0f2af5db4c673d7dbd31259a3977adb9cf
13,718
def create_generator_selfatt(generator_inputs, generator_outputs_channels, flag_I=True): """ Add Conditional Self-Attention Modual to the U-Net Generator. By default, 256x256 => 256x256 Args: generator_inputs: a tensor of input images, [b, h, w, n], with each pixel value [-1, 1]. generator_...
bfcc81955c7849e84053c45ea7a593570059bf28
13,719
def by_tag(articles_by_tag, tag): """ Filter a list of (tag, articles) to list of articles by tag""" for a in articles_by_tag: if a[0].slug == tag: return a[1]
642472a89cb624ed02a6e8ec488b72856ac231a9
13,720
def experiment(dataset='SUPPORT', quantiles=(0.25, 0.5, 0.75), prot_att='race', groups=('black', 'white'), model='dcm', adj='KM', cv_folds=5, seed=100, hyperparams=None, plot=True, store=False): """Top level interface to train and evaluate proposed survival models. This is the top le...
79ec44d4d62a42dea4f7e612cd4291ce8fbc5585
13,721
def ldns_str2rdf_type(*args): """LDNS buffer.""" return _ldns.ldns_str2rdf_type(*args)
d121f8534c64b7597d775e5443b706c962ec738a
13,722
import hashlib import _crypt def scramble(password, message): """scramble message with password""" scramble_length = 20 sha_new = partial(hashlib.new, 'sha1') if not password: return b'' stage1 = sha_new(password).digest() stage2 = sha_new(stage1).digest() buf = sha_new() buf....
9ad006a5626d7b4ca3f8220dc4cbdd719a3cbac8
13,723
def dp_port_id(switch: str, port: str) -> str: """ Return a unique id of a DP switch port based on switch name and port name :param switch: :param port: :return: """ return 'port+' + switch + ':' + port
479891e41b51114744dcbb2b177180c19cd1bfd5
13,724
import requests def request_item(zip_code, only_return_po_boxes=False, spatial_reference='4326'): """ Request data for a single ZIP code, either routes or PO boxes. Note that the spatial reference '4326' returns latitudes and longitudes of results. """ url = BASE_URL.format( zip_code=str(...
956a2a86f0960a888046bfd5a8e3c2d7c56bc9dc
13,725
def smoothen_histogram(hist: np.array) -> np.array: """ Smoothens a histogram with an average filter. The filter as defined as multiple convolutions with a three-tap box filter [1, 1, 1] / 3. See AOS section 4.1.B. Args: hist: A histogram containing gradient orientation counts. ...
bdcc5de3df5aa2aad33653cce237f7f07d825b9d
13,726
from typing import Tuple def end_point(min_radius: float, max_radius: float) -> Tuple[int, int]: """ Generate a random goal that is reachable by the robot arm """ # Ensure theta is not 0 theta = (np.random.random() + np.finfo(float).eps) * 2 * np.pi # Ensure point is reachable r = np.rando...
8d6a79195108e8354fad986f93da5f089b6df0d7
13,727
def expand_tile(value, size): """Add a new axis of given size.""" value = tf.convert_to_tensor(value=value, name='value') ndims = value.shape.ndims return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
50adf652fff47418d1f8f1250a2a6d01f712da76
13,728
from typing import Mapping from typing import Any def parse_header( info: Mapping[str, Any], field_meta_data: Mapping[str, FieldMetaData], component_meta_data: Mapping[str, ComponentMetaData] ) -> Mapping[str, MessageMemberMetaData]: """Parse the header. Args: info (Mapping[st...
a8043c62070c540712074c60e01e3c9c3ebfe99b
13,729
def amina_choo(update, context): #3.2.1 """Show new choice of buttons""" query = update.callback_query bot = context.bot keyboard = [ [InlineKeyboardButton("Yes", callback_data='0'), InlineKeyboardButton("No", callback_data='00')], [InlineKeyboardButton("Back",callback_data='3....
b43d2e6d63e111b9a2f70fd71e5da765ef923746
13,730