content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_cho_ccc(atoms): """ C / R-C----C-H || \ O C or H C | / R-C----C-H | \ O C or H S | / R-C----C-H | \ O S example: (5R)-5-C-Cyclohexyl-5-C-phenyl-D-xylos...
21c509b2b3c6fe1bca44b19ca6f613059c6d7baa
69,714
import json import difflib def spec_diff(request, spec1=None, spec2=None): """ Allow the user to select two specs to diff. """ specs = Spec.objects.all().order_by("name") if not spec1 or not spec2: return render(request, "specs/diff.html", {"specs": specs}) spec1 = get_object_or_404(S...
07e4c347c488db8ea87b443df775734f5b01bcbf
69,715
def is_correct_extension(filename): """Checks if a file is a required sample. Args: filename (string): path to a file Returns: bool: True if the filename ends with a known sample extension """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in EX...
54f48f8fd247f043ce74e2f84190468b67196a7b
69,717
def softmax_loss(theta, x, y, learning_rate=None): """ Categorical cross-entropy / softmax loss. The cost function for multi-class logistic regression. """ # theta = np.matrix(theta) # x = np.matrix(X) # y = np.matrix(y) first = np.multiply(-y, np.log(sigmoid_activation(x * theta.T))) ...
56065c1f2bba4dfe27379079a8e8e549dc9aa6ae
69,718
def get_formatted_el( element: str, sym_label: str, use_oxi_state: bool = True, use_sym_label: bool = True, fmt: str = "raw", ): """Formats an element string. Performs a variety of functions, including: - Changing "Sn+0" to "Sn". - Inserting the symmetry label between the element a...
87d379236b0979dc6d6680caa4f5622f3530ed1b
69,719
def bct_lattice( q_values, unitcell_param, pivot, euler_angles=(0, 0, 0), offset_indices=False, verbose=False, ): """ Calculate Bragg peaks positions for a BCT unit cell. The long axis is by default along qz (vertical up). :param q_values: tuple of 1D arrays (qx, qz, qy), q_val...
22976c3c88fcc6b818bb5ac49c0b2d179176037c
69,721
def efun(pretrained=False, **kwargs): """ eFUN """ # NOTE for train, drop_rate should be 0.2, drop_path_rate should be 0.2 model = _gen_efun( 'eFUN', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs) return model
5ba6f1de42cce50b1556df3126b2abfbc42bd589
69,723
def calc_nrmse(tar_img, ref_img, norm_type='Euclidean'): """Compute the normalized root mean-squared error (NRMSE) between two images. Parameters ---------- tar_img : sitk Test image. ref_img : sitk Ground-truth image. norm_type : {'Euclidean', 'min-max', 'mean'} Controls...
964c663c70a75216a6a842d329c2bd40512f8e53
69,725
def humansize(nbytes): """ Translates a size in bytes to a human readable size format :param int nbytes: integer of size of torrent file :return: size in bytes in a human readable format :rtype: str """ suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] i = 0 while nbytes >= 1024 and i < len(su...
98390c0f5c471b501caf2fa2bba1e593c8a17eb6
69,726
def _parser(date): """ date parser to cast a string in the format "%d/%m/%Y" to a date """ return pd.datetime.strptime(date, "%d/%m/%Y")
fbe163910d48374c34d46fda2367eded4fdaad8f
69,727
def pad_sents(sents, padding_token_index): """ Pad the sents(in word index form) into same length so they can form a matrix # 15447 >>> sents = [[1,2,3], [1,2], [1,2,3,4,5]] >>> pad_sents(sents, padding_token_index = -1) [[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]] """ ...
0063d8716f7081644e4353de662d58f0dc04e8fe
69,728
def gm_constrs(t, x_list, p): """ Form the internal CXVPY constraints to form the weighted geometric mean t <= x^p. t <= x[0]^p[0] * x[1]^p[1] * ... * x[n]^p[n] where x and t can either be scalar or matrix variables. Parameters ---------- t : cvx.Variable The epigraph variable x...
614e283beb3ad7148df78e227ff360bc6bb2080d
69,729
from typing import List def multi_gate(size: int, targets: List[int], gate: Gate, phi=0j) -> Matrix: """ Constructs a (2**size by 2**size) gate matrix that applies a specific gate to one or more specified qubits :param size int: total number of qubits in circuit :param targets List[int]: list of ...
a447968e1aa4c12dbecf02c26ec14dd2b75f2c97
69,730
def get_instances_with_configs(configs): """Create Monsoon instances from a list of dict configs. Each config should have the required key-value pair 'serial': <an integer id>. Args: configs: A list of dicts each representing the configuration of one Monsoon. Returns: A ...
a08e253daf5bb338f4530d9c71c39917c9f755f4
69,731
import hashlib def md5_md5_md5_pass(string, salt=None, **placeholder): """ Create an MD5 hash in a specific format md5(md5(md5(pass))) > :param string: string to be hashed > :return: a MD5 hash in the above format Example >>> md5_md5_md5_pass("test") 25ab3b38f7afc116f18fa...
9f91ed6abe8656292a1a1607c5c3eda377a5a4c7
69,732
def twoclass(y_true, y_pred_proba, threshold=0.5, classnames=None, normalize=False, title='', cmap=plt.cm.Blues, showfig=True, verbose=3): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ cm = confusion_matrix(y_true, y_pred_prob...
016d9cb5e6dfe1d862040adad4401c24f34575d0
69,733
def absolutify(url): """Takes a URL and prepends the SITE_URL""" site_url = getattr(settings, "SITE_URL", False) # If we don't define it explicitly if not site_url: protocol = settings.PROTOCOL hostname = settings.DOMAIN port = settings.PORT if (protocol, port) in (("htt...
160e3d272c3b38b559f2a54f27778e5f4711de77
69,735
def clamp(minimum, n, maximum): """Return the nearest value to n, that's within minimum to maximum (incl) """ return max(minimum, min(n, maximum))
a3db191a733041196b8a3e0cfc83731e839a14aa
69,737
from typing import Optional from typing import Union import ray def resume(workflow_id: str, storage: Optional[Union[str, Storage]] = None) -> ray.ObjectRef: """Resume a workflow asynchronously. See "api.resume()" for details. """ if isinstance(storage, str): store = create_storage(stor...
1be5cb24b0109858f0d106a14fedfe907d1997c8
69,738
def metadata(): """ Returns an XML with the SAML 2.0 metadata for this SP as configured in the saml2_settings.py file. """ metadata = entity_descriptor(current_app.saml2_config) response = make_response(metadata.to_string(), 200) response.headers['Content-Type'] = "text/xml; charset=utf8" ...
683db354980f57aa4f74f3cdb67db1098decde48
69,739
def boxlist_to_masklist(boxlist): """Converts a BoxList containing 'masks' into a BoxMaskList. Args: boxlist: An np_box_list.BoxList object. Returns: An BoxMaskList object. Raises: ValueError: If boxlist does not contain `masks` as a field. """ if not boxlist.has...
dd7608874ad4ae476fa9789b5c7d650bb672d4b6
69,740
from typing import List from typing import Optional def setup_optima(x: np.ndarray, optima: List[float], optima_label: str, ax: Optional[Axes] = None) -> Axes: """Set up optima. :param x: :param optima: :param optima_label: :param ax: Plot into t...
67afd52f8157fed689554de91c4cef19bb413106
69,741
import operator def normalize_data(data): """Normalizes a sequence of input data according to the heuristic laid out in the module documentation. """ data = data or [] if isinstance(data, dict): data = [{"key": key, "value": value} for key, value in data.items()] data.sort(key=oper...
d1cacf020cd8df2762f747a85a41a758e1e12ba8
69,743
def get_expression(adata, use_raw=True, use_geosketch=False, geosketch_N=10000, geosketch_transform=None): """Grab expression and put into pandas dataframe.""" if use_raw: ad = adata.raw else: ad = adata if isinstance(ad.X, csr_matrix): df = pd.DataFrame(ad.X.toarray(), index=ad...
7ba894df1eac5ccd30775162a700a7b0071b0f41
69,744
import time def get_frequency(rss: fp.util.FeedParserDict) -> int: """ Calculate the average time gap between episodes. Parameters ---------- rss : fp.util.FeedParserDict RSS feed of the podcast. Returns ------- int """ if rss is None or not rss["entries"]: re...
e3dc4daabc1a981265cf0fa649cfab2b3d4c8ffc
69,746
import typing def gen_allowed_hosts_setting() -> typing.List[str]: """ALLOWED_HOSTS setting.""" allowed_hosts = ENV.get(f"{ENV_VAR_PREFIX}_ALLOWED_HOSTS") if not allowed_hosts: return [] return [host for host in allowed_hosts.split(",") if host]
c15aac536d60dea1eb816c865d739f47b5c71ef7
69,747
def get_vehicle_mass(vehicle_info): """ Get the mass of a carla vehicle (defaults to 1500kg) :param vehicle_info: the vehicle info :type vehicle_info: carla_ros_bridge.CarlaEgoVehicleInfo :return: mass of a carla vehicle [kg] :rtype: float64 """ mass = 1500.0 if vehicle_info.mass: ...
216f109e9f963ba6de92cf168055b1a7e516d777
69,748
def has_table(table): """Return True if the given backend has a table of the given name.""" return ENGINE.has_table(table)
3ece338172776c0d73c8e82b8a1269c64e79c526
69,749
def read_instruction(fio, start_pos): """ Reads a single instruction from `fio` and returns it, or ``None`` if the stream is empty. :param fio: Any file-like object providing ``read()``. :param start_pos: The current position in the stream. """ op = fio.read(1) if not op: retur...
f7a282019507a7387ea08fc2313355513565eaaa
69,751
def attribute_conversion(word, from_pos): """ This function converts a word to a noun using the attribute method from WordNet""" # The attribute method exists for adjectives I think synsets = wn.synsets(word, from_pos) # Word not found if not synsets: return [] result =[] attribute_lis...
e49a57cdf878a2aecf2c21345d280c411c0e2414
69,752
def add_modules_to_metadata(modules, metadata): """ modules is a list of lists of otus, metadata is a dictionary of dictionaries where outer dict keys are features, inner dict keys are metadata names and values are metadata values """ for module_, otus in enumerate(modules): for otu in otus:...
b1dcd3e179a01c11d5a847094ceef4240d2b899e
69,753
def do_maximisation_step(resp_mat, data_set): """ Finds the mu, cov and pi (weights) that maximise the data log likelihood :param resp_mat: (m x K) matrix, responsibility matrix (K = num_classes, m = num of datapoints) :param data_set: (m x n) matrix, dataset with each row a single example (m = num data...
5bd5b2a7e4add811c4cfe3d5312ec710b4b3dc27
69,754
def longest_word(list_name): """Stores the number of rows. """ long_word = [0] * len(list_name) #Stores number of items in each sublist i = 0 for column in list_name: #counts words in each sublist l_word = 0 for word in column: l_word += 1 long_word[i] = l_word ...
932f250b50fc3c8161545e7c4741b255483923e5
69,755
def _get_passthru_keys(spec, zip_keys=None, extend_keys=None): """ Keys in `spec` that are not exploded and are simply carried over from the `spec` into the variants without modification. :param spec: Variants specification :type spec: dict :param zip_keys: Keys defined as 'zip_keys' (see :func...
5f57353f0fa6885e36a430c9ef13f104937bad0a
69,756
def _dataset_parser(value): """Parse a CIFAR-10 record from value.""" featdef = { 'image': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.int64), } example = tf.parse_single_example(value, featdef) image = tf.decode_raw(example['image'], tf.uint8) image.se...
b8a0acb219ee752a34f1fc373f525a601b00060b
69,757
def clone_models(d): """ Clone bokeh models in a dict. Parameters ---------- d : dict The input dict. Returns ------- d : dict A copy of the input dict with all bokeh models replaced by a clone of themselves. """ d = d.copy() for k, v in d.items(): ...
c8c225a9170e20c74912c60766a0dec230c3f0f7
69,758
from typing import Tuple def refit_reg(x_train: np.ndarray, y: np.ndarray, l1_grid_size: int, l1_exp_scale: float, max_penalty: float, interp: bool = True ) -> Tuple[np.ndarray, float, np.ndarray]: """ Final model refit with regularization Args: x_train: y: ...
9ea9fc1c223e739a116dd9c449e0126d39717560
69,759
from typing import List def parse_virus_preset_dump(msg: Message) -> List[int]: """ strips sysex header and checksum bits to return list of preset patches """ data = list(msg.data[len(VIRUS_SYSEX_HEADER): -len(VIRUS_SYSEX_CHECKSUM)]) assert len(data) == 256 return data
a42e0861f80b584910e99f307307196a07cbd9d6
69,760
def rejudge(request): """Ajax method: Rejudge a single submission `id`""" user = User.getCurrent(request) id = request.POST["id"] submission = Submission.get(id) runCode(submission, user) return JsonResponse(submission.result, safe=False)
3bf53bb2fa6b38970659a3b85612df520571704b
69,761
def get_sobel_kernels(): """ Returns the Sobel operator kernels https://en.wikipedia.org/wiki/Sobel_operator """ K_sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) K_sobel_y = np.array([[1, 2, 1], [0, 0, 0], ...
27b96f131dbff00819358336551dacd266756811
69,762
def LabelAnalyzer(): """ A analysis factory function for MeTaL. """ return analysis
8180352955157c680fbc437c0e22a93e5a721a20
69,763
def job_to_json(job): """"Convert a Job object to json via its associated ModelSchema class """ json_dict = JobSchema().dump(job).data # Sort lists # json_dict["families"] = sorted(json_dict["families"], # key=lambda p: p.get("name")) return json_dict
fe6243ab01774029c81f79ef64866fb4dd2edd13
69,764
from typing import List def get_classical_part_of_the_noise(povm: List[np.ndarray]) -> List[np.ndarray]: """ Description: From given povm get stochastic map describing classical part of the noise. Parameters: :param povm: POVM from effects of which diagonal parts shall be extracted. ...
ac49ff02b84ad903e4327132738372f2f1a58f0b
69,765
def triplet_semihard_loss_mine(labels, embeddings, margin=1.0, background=0,log_var=None): """Computes the triplet loss with semi-hard negative mining. The loss encourages the positive distances (between a pair of embeddings with the same labels) to be smaller than the minimum negative distance among which are...
15f6a9dcf15e1d855ad64ccc455fbb1436739b23
69,766
def uvm_object_value_str(v): """ Function- uvm_object_value_str Args: v (object): Object to convert to string. Returns: str: Inst ID for `UVMObject`, otherwise uses str() """ if v is None: return "<null>" res = "" if hasattr(v, 'get_inst_id'): res = "{}"....
e56bd12094923bf052b10dcb47c65a93a03142a2
69,767
def mt_mi_exam_collate(batch_list): """ Collate function for a multi-task multi-input dataset """ all_inputs = defaultdict(list) all_targets = defaultdict(list) all_info = [] for inputs, targets, info in batch_list: all_info.append(info) for name, inpt in inputs.items(): ...
3e8b0a670a71a5bf3be282dd36284b677088d923
69,768
import numpy import scipy def _compute_cumulative_statistics( samples, samples_processed_order, num_samples_used, confidence_level): """ Computes mean and error as the number of samples progresses. The output are the means, absolute and relative errors of the samples. ...
fbfc5b9bda54592e7c703392b027cac11dc2cfcf
69,770
import itertools def checkio(stones): """ Minimal possible weight difference between stone piles """ if len(stones) == 1: return stones[0] return min(set(map(best_balance, list(itertools.permutations(stones)))))
618f4d11a8d795b2b78ca50370c3f8cf112de1ce
69,771
def app(environ, start_response): """A barebones WSGI app. This is a starting point for your own Web framework """ status = "200 OK" response_headers = [("Content-Type", "text/plain")] start_response(status, response_headers) return [b"Hello world from a simple WSGI application\n"]
90f9018ccca5dca0a5437170d8a494463e5e0cc3
69,772
import tqdm import json def download_all_dicts_to_file(filename, search, mode='w'): """ Download data from elastic search server :param filename: str, name of file to save data :param search: elasticsearch search object to query :param mode, char, file write mode (w, a) :return filename, str: ...
4abea20e5cd58fa05bd498e4f7462530a2b677fe
69,773
def _initialize_sites_graphic_structure(graphic_struct: dict, scale_wedges: bool = False) -> dict: """Once the data structure has been created, it can now be initialized with plausible values.""" init_site_graphics = graphic_struct for agent_name in init_site_graphics.keys(): # identify number of we...
71a6e1750dbf966db21668b01747182ea130ca45
69,774
def get_taxa(**params) -> JsonResponse: """Search taxa .. rubric:: Notes * API reference: :v1:`GET /taxa <Taxa/get_taxa>` Example: >>> response = get_taxa(q='vespi', rank=['genus', 'family']) >>> pprint(response) [52747] Family: Vespidae (Hornets, Paper Wasps, Potter Wasps, an...
f960c4c96d42bbc4cee3a2717ee7d327ca95b056
69,775
import pathlib def findjson(basedir): """Return a list of absolute paths to json files recursively discovered by walking the directory tree rooted at basedir""" return [str(path.resolve()) for path in pathlib.Path(basedir).rglob('*.json')]
5def3388237a1e70d3801952579c7cbc51fb435b
69,776
import torchvision import torch def load_cifar10_all(data_dir='./data', val_size=0.1, shuffle=True, seed=1): """Load entire CIFAR-10 dataset into tensor""" transform = transforms.Compose([ transforms.ToTensor(), ]) trainset = torchvision.datasets.CIFAR10( root=data_dir, train=True, d...
66908b6fc6d39cd7f4812817cae6f64cce032f02
69,777
import string def create_esax(x, b, w): """ This method creates eSAX symbols for a univariate time series. :param x: numeric vector representing the univariate time series :type: pandas.Series :param b: breakpoints used for the eSAX representation :type: numpy.ndarray :param w: word size ...
44c4d465ec340c0c35742be87517a9348ee09e6b
69,780
def one_way_anova_test(df, cat_col, val_col, alpha=0.05): """ This will detect the difference of the groups of values and the value column. The return value is whether it is safe to assume there are group differences. We assume the group variance are all the "same", and that the val_col is normal. ...
2b98d30b9df19f0352424f4a718ab80afa47c786
69,781
async def get_health(request): """ Args: request: Returns: health of all registered services :Example: curl -X GET http://localhost:8081/foglamp/service """ response = get_service_records() return web.json_response(response)
185d7b37b0df2d3f1c129fb476ffa6baf5cfc13f
69,782
from typing import Sequence def batch(graphs: Sequence[gn_graph.GraphsTuple]) -> gn_graph.GraphsTuple: """Returns a batched graph given a list of graphs. This method will concatenate the ``nodes``, ``edges`` and ``globals``, ``n_node`` and ``n_edge`` of a sequence of ``GraphsTuple`` along axis 0. For ``sende...
cd227a3232fede85bb766da3bdc3cc6cee8f5104
69,783
def share_emotion_photo() -> FlaskResponse: """ XHR procedure updating the visitor log according to his emotion. Raises: 404: if the request is not POST. """ if "emotion" not in request.form: return basic_json(False, "Emotion required!") emotion = escape(request.form["emotion"])...
153535ea6d337d71e798cf207543a92e04df35e6
69,786
def encode_defunct( primitive: bytes = None, *, hexstr: str = None, text: str = None) -> SignableMessage: """ Encoded as defined here: https://github.com/ethereum/eth-account/blob/master/eth_account/messages.py Except with Helios in the message instead of Ethereum """ ...
3a2f62127b7b8cd059f3dfb647f9e9a20b4eacdc
69,787
def readfile(huc12, filename): """Make me a df please""" df = read_yld(filename) if df.empty: return None df["huc12"] = huc12 df["fpath"] = filename.split("/")[-1].split("_")[-1].split(".")[0] return df
2801cd1823309b67e0cc80e08397dd3e12a7062b
69,789
def convert_team_name_id(nickname): """ Given the team nickname, return the team id from teams table in db. :param str nickname: team nickname :return str team_id: team id :Example: >>> convert_team_name_id('Brewers') 1 """ # Open database connection db = MySQLdb.connect(hos...
29fe512821880f8e71223c854890ed8492700095
69,791
def config_vlan_range(dut, vlan_range, config="add", skip_verify=False, cli_type = ''): """ Author: sneha.mathew@broadcom.com Creates/Deletes range of VLANs given as input. :param dut: :param vlan_range: range of VLAN IDs in string format, separator space: "first-VLAN last_VLAN". ...
10570716ec2b4262c2753cf644736ad22a27ef54
69,792
def second_task(s : str) -> str: """ This function randomly reorders all the letters in a world. Parameters: s: the string to shuffle Returns: str: shuffled string Examples: >>> second_task('What can we do with the drunken sailor?') ' Tahw acn ew od hwit the un...
fc0d2c51ab0ff055d88ac4231ea2b06a1653a8d7
69,793
from typing import Tuple from typing import List def task_id_ancestors(task_id: Tuple[int]) -> List[Tuple[int]]: """ Gets the full list of tasks above the given task. """ parents = [] parent = task_id_parent(task_id) while parent is not None: parents.append(parent) parent = tas...
d25b7dce8dd878c6650f43f01040b529ac62b32e
69,794
def ReadSsconfFile(filename): """Reads an ssconf file and verifies its size. @type filename: string @param filename: Path to file @rtype: string @return: File contents without newlines at the end @raise RuntimeError: When the file size exceeds L{_MAX_SIZE} """ statcb = utils.FileStatHelper() data =...
9883de30e8b625f21092da8ce1076850a9e8e911
69,795
def auto_unmark(*args): """ auto_unmark(start, end, type) Remove range of addresses from a queue. 'start' may be higher than 'end', the kernel will swap them in this case. 'end' doesn't belong to the range. @param start (C++: ea_t) @param end (C++: ea_t) @param type (C++: atype_t) """ return _i...
c7c209c3f603367c9e4e26b719bcbc9058762d91
69,796
def _example_word(lang): """ Returns an example word for a given language :param lang: str Language abbreviation :return: A word. Should be one early in the vocab for that language """ return { "de": "mann", "es": "hombre" }.get(lang)
e9d60f31cb0c5f2b1dd397e19b60a52a43fc41d2
69,797
def lightweight_image_augment(image, strength=0.4, augment_prob=0.5, allowed_transforms='all'): """ augmentations from simclr paper :param image: [h, w, 3] -- float32 in the range of 0.0 to 1.0 :param strength: magic number from simclr. i made hue weaker :param augment_...
b676a23dd67ae4e5eec756fed26aa7bf85fac1a6
69,798
def _canonicalize(parts): """ Return a copy of 'parts' with consecutive "**"s coalesced. Raise a ValueError for unsupported uses of "**". """ res = [] prev_was_globstar = False for p in parts: if p == _GLOBSTAR: # Skip consecutive **'s if not prev_was_globst...
faf7f7da69ed4bc2624ba59820ff44ac4657c597
69,799
def load_pretrain_embed(embedding_path, max_scan_num=1000000, add_seg_vocab=False): """ 从pretrained word embedding中读取前max_scan_num的词向量 Args: embedding_path: 词向量路径 max_scan_num: 最多读多少 """ ## 如果是使用add_seg_vocab, 则全局遍历 if add_seg_vocab: max_scan_num = -1 embed_dict = di...
dadf109469c70baf922791c3b20f4a5339e1a46b
69,802
def get_object_name(object): """ Retrieves the name of object. Parameters: object (obj): Object to get name. Returns: str: Object name. """ if object.name[-5:-3] == '}.': return object.name[:-4] return object.name
fc695c8bf19817c3217bf6000358695c88de07aa
69,803
def list_functor(annotation): """Convert to List of type values""" to_type = next(iter(annotation), None) if _is_subtype(to_type, entities.AttributeV2): return partial(map, attr_v2_functor(to_type.__args__)), list return partial(map, entities.converter(to_type)), list
3e8eeec884756964a8c2287a56ed421986b6fff9
69,804
def create_nine_digit_product(num): """ Create a nine digit string resulting from the concatenation of the product from num and multipliers (1, 2, 3,).... Return 0 if string cannot be length 9. """ result = '' counter = 1 while len(result) < 9: result += str(num * counter) ...
9c6765349edfa7e03dc8d2ffe7bf6a45155f3ad0
69,805
def ReplaceValues(df, lY, iQ1, iQ2): """ Purpose: Replace all values in dataframe below i1 by i1, and all values above i2 by i2. Inputs: lY list of names of relevant columns from df df dataframe i1 first value (lower boarder) i2 second value ...
30c1199f645e2b10ffb885d543783d513818f254
69,807
def peak_indices_to_times(time, picked_peaks): """ Converts peak indices to times. Parameters ---------- time: ndarray array of time, should match the indices. picked_peaks: dict dictionary containing list of indices of peak start, center, and end. Returns ----------- ...
99aa76fbc399b2b99d4dc9c8d3e4b67e4ee2d3af
69,808
from typing import Optional from typing import List from typing import Any from typing import Tuple def _create_on_round_end_fn( file_checkpoint_manager: Optional[FileCheckpointManager] = None, metrics_managers: Optional[List[MetricsManager]] = None, validation_fn: Optional[ValidationFnType] = None): ""...
6f48db732bfb24e63cc49ce8935f3f44a7aca498
69,809
from typing import Tuple import asyncio async def read_govee() -> Tuple[float, float]: """Connects to the H5179 device and gets the lab temperature and humidity.""" h5179 = config["sensors"]["H5179"] reader, writer = await asyncio.wait_for( asyncio.open_connection(h5179["host"], h5179["port"]), ...
3489957c1a68f00731c6924606c6d15faa15a613
69,811
def init_baseline_artm( dataset, modalities_to_use, main_modality, num_topics, bcg_topics, model_params: dict = None, ): """ Creates simple artm model with standard scores. Parameters ---------- dataset : Dataset modalities_to_use : list of str ...
9aa0339316a75417e4afc756810a43d9a50a936b
69,812
def es_annotation_doc(): """ Minimal JSON document for an annotation as returned from Elasticsearch. This contains only fields which can be assumed to exist on all annotations. """ return { "_id": "annotation_id", "_source": { "authority": "hypothes.is", "tar...
085f8077d5f5cbf278a3b1be1734de081a55b769
69,813
def incmean(prevmean, n, x): """Calculate incremental mean""" newmean = prevmean + int(round((x - prevmean) / n)) return newmean
4176a07d0ad8eb96d3dd5d8b2cb46b8aecd1da20
69,814
def ccode(expr, dtype=np.float32, **settings): """Generate C++ code from an expression calling CodePrinter class :param expr: The expression :param settings: A dictionary of settings for code printing :returns: The resulting code as a string. If it fails, then it returns the expr """ return Cod...
1fdceb916a1e1c5536bf8794852d58b393f47aef
69,815
import torch def uses_placeholder_y(ds): """If ``ds`` is a ``skorch.dataset.Dataset`` or a ``skorch.dataset.Dataset`` nested inside a ``torch.utils.data.Subset`` and uses y as a placeholder, return ``True``.""" if isinstance(ds, torch.utils.data.Subset): return uses_placeholder_y(ds.datas...
1bbdfdfa644db3298a6148380155980a57183d62
69,816
def evenFibSum(limit): """Sum even Fib numbers below 'limit'""" sum = 0 a,b = 1,2 while b < limit: if b % 2 == 0: sum += b a,b = b,a+b return sum
cdf9cdb1cfb419713e794afff4d806945994692e
69,817
def copy_arrays(mapper, reverse=False): """ Build an Iteration/Expression tree performing the copy ``k = v``, or ``v = k`` if reverse=True, for each (k, v) in mapper. (k, v) are expected to be of type :class:`IndexedData`. The loop bounds are inferred from the dimensions used in ``k``. """ i...
44d346a751d8f92edb34729c9093d174ec55f499
69,818
def OneHotFromList(elements, dtype='float32', strict=True, name=None): # pylint: disable=invalid-name """A block that converts PyObject input to a one-hot encoding. Differs from `OneHot` in that the user specifies the elements covered by the one-hot encoding rather than assuming they are consecutive integers. ...
cde6231cc9701d450e6d7f5b44d630f08a657899
69,819
def _get_tfbt(output_dir, feature_cols): """Configures TF Boosted Trees estimator based on flags.""" learner_config = learner_pb2.LearnerConfig() learner_config.learning_rate_tuner.fixed.learning_rate = FLAGS.learning_rate learner_config.regularization.l1 = 0.0 # Set the regularization per instance in such a...
e5a548858850745087add9fb65bc233c880b3aa3
69,820
from datetime import datetime def dateandtime_now() -> str: """ Returns the datetime in following format as string YYYYMMDD_HHMMSS """ jetzt = datetime.datetime.now() dt = '' for time in ['year', 'month', 'day', 'hour', 'minute', 'second']: _time = str(getattr(jetzt, time)) ...
700032adc66298f98fc6687c5dbf48fe4b0706c5
69,821
def get_n_first(file_names, checksums, N_first): """ Given a list of file_names and a list of checksums, returns the 'N_first' items from both lists as a zip object. :param file_names: list of file names :param checksums: list of sha256 checksums :param N_first: int or None. If None, all items ...
13a8157dcd55fa43b0cd71eb877abddc832ff143
69,822
from typing import Tuple def singular_value_decomposition( m: np.ndarray ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Perform singular value decomposition. :param m: an input matrix M. :returns: a tuple (d, U, V), where d is a 1d matrix containing the diagonal elements of a non-ne...
b9e469f3d42b1140fc4d3303d763954d8541c69a
69,823
def get_library(gi, lib_name, lib_desc="", lib_synopsis="", create=True): """ Get the id corresponding to given library, and create it if it doesn't exist yet """ print("Looking for lib '" + lib_name + "'") libs = gi.libraries.get_libraries() found_lib = None for lib in libs: if not...
b8f9c6fff4c0162185fc71c08de9ff7b03272d4b
69,824
def state_to_index(valuation, base): """ Maps states to an decimal integers. """ factor = 1 integer = 0 for i in range(len(valuation)): integer += factor * valuation[i] factor *= base return integer
c05deefd07d0faf2749489fbc6f37576e1433c8d
69,825
def check_index_values_are_unique(data, index=None, duplicates_as_error=True): """Checks index for duplicate rows. Args: data: DataFrame to check index: optional index to use. If not specified, uses index from `data`. duplicates_as_error: If True, raises an error if duplicates are found...
cf29309022e0303c0c49b716388b2cf73909f547
69,826
def bgr2luma(im): """Converts BGR image to grayscale Luma :param im: np.ndarray BGR uint8 :returns nd.array GRAY uint8 """ im_y, _, _ = cv.split(cv.cvtColor(im, cv.COLOR_BGR2YUV)) return im_y
39f97822dea6170be74d60c357fc51f4160e1acd
69,828
def get_lock_path_from_repo(git_repo): """ >>> app_module = {'git_repo': 'git@github.com:claranet/ghost.git'} >>> get_lock_path_from_repo(app_module['git_repo']) '/ghost/.mirrors/.locks/git@github.com:claranet/ghost.git' >>> app_module = {'git_repo': ' git@github.com:claranet/spaces.git '} >>> g...
b722e69dcaa5fd6a6299ee42ddaa7f14097a25a4
69,829
def cross_entropy_with_selfnorm(input, label, name=None, coeff=1.0, softmax_selfnorm_alpha=0.1, layer_attr=None): """ A loss layer for multi class entro...
b8bda752dc9eaf1b69014481bd27be992fc4870b
69,830
def random_contrast(img, low=0.5, high=1.5): """ Randomly scales the contrast of a given RGB image. """ mean = img.mean(axis=(0,1), keepdims=True) cf = np.random.uniform(low, high, mean.shape) img -= mean img *= cf img += mean img[img > 1] = 1 img[img < 0] = 0 return img
7a3ae56c2bbf79dac312bfc176d021dc5bccc1cb
69,831
def get_movie_or_create(movie: str): """ Находит фильм в бд или создает его, возвращает id фильма. """ try: result = Movies.select().where(Movies.name==movie).get() except DoesNotExist: result = Movies.create(name=movie) return result.id
c7581ec1421d7a487fc253f3a65c544f8a3f60c6
69,833
def generalized_box_iou(boxes1, boxes2): """Compute GIoU of each pais in boxes1 and boxes2 GIoU = IoU - |A_c - U| / |A_c| where A_c is the smallest convex hull that encloses both boxes, U is the union of boxes Details illustrations can be found in https://giou.stanford.edu/ Args: boxes1: ...
671520a3967b6120d23c8944456e13e3118ef8a7
69,834
def getConstValue(stateStruct, obj): """ Evaluates the obj, in case it is a expression which can be evaluated at compile time. """ if hasattr(obj, "getConstValue"): return obj.getConstValue(stateStruct) if isinstance(obj, (CNumber,CStr,CChar)): return obj.content if isinstance(obj, CFunc...
91c1ae469ef23b91ef4f76bf35481560243cdfc7
69,835