content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data parallel callback.""" import logging import vega from vega.common import ClassFactory, ClassType from .callback import Callback logger = logging.getLogger(__name__)
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 357, 34, 8, 12131, 13, 43208, 21852, 1766, 1539, 12052, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, ...
3.660714
224
# _*_ coding:utf-8 _*_ import logging import re import app_config from bs4 import BeautifulSoup from shortcode import process_shortcode logging.basicConfig(format=app_config.LOG_FORMAT) logger = logging.getLogger(__name__) logger.setLevel(app_config.LOG_LEVEL) end_doc_regex = re.compile(ur'^\s*[Ee][Nn][Dd]\s*$', re.UNICODE) new_section_marker_regex = re.compile(ur'^\s*\+{50,}\s*$', re.UNICODE) section_end_marker_regex = re.compile(ur'^\s*-{50,}\s*$', re.UNICODE) frontmatter_marker_regex = re.compile(ur'^\s*-{3}\s*$', re.UNICODE) extract_metadata_regex = re.compile(ur'^(.*?):(.*)$', re.UNICODE) shortcode_regex = re.compile(ur'^\s*\[%\s*.*\s*%\]\s*$', re.UNICODE) def is_section_marker(tag): """ Checks for the beginning of a new section """ text = tag.get_text() m = new_section_marker_regex.match(text) if m: return True else: return False def is_section_end_marker(tag): """ Checks for the beginning of a new section """ text = tag.get_text() m = section_end_marker_regex.match(text) if m: return True else: return False def process_section_contents(contents): """ Process episode copy content In particular parse and generate HTML from shortcodes """ logger.debug('--process_post_contents start--') parsed = [] for tag in contents: text = tag.get_text() m = shortcode_regex.match(text) if m: parsed.append(process_shortcode(tag)) else: parsed.append(unicode(tag)) episode_contents = ''.join(parsed) return episode_contents def parse_raw_sections(raw_sections): """ parse raw episodes into an array of section objects """ # Divide each episode into its subparts # - Headline # - FrontMatter # - Contents sections = [] for raw_section in raw_sections: section = {} marker_counter = 0 section_raw_headline = [] section_raw_metadata = [] section_raw_contents = [] for tag in raw_section: text = tag.get_text() m = frontmatter_marker_regex.match(text) if m: marker_counter += 1 else: if (marker_counter == 0): section_raw_headline.append(tag) elif (marker_counter == 1): section_raw_metadata.append(tag) else: section_raw_contents.append(tag) section[u'headline'] = process_headline(section_raw_headline) metadata = process_metadata(section_raw_metadata) for k, v in metadata.iteritems(): section[k] = v section[u'contents'] = process_section_contents(section_raw_contents) sections.append(section) return sections def split_sections(doc): """ split the raw document into an array of raw sections """ logger.debug('--split_sections start--') raw_sections = [] raw_episode_contents = [] ignore_orphan_text = True body = doc.soup.body for child in body.children: if is_section_marker(child): # Detected first post stop ignoring orphan text if ignore_orphan_text: ignore_orphan_text = False else: if ignore_orphan_text: continue elif is_section_end_marker(child): ignore_orphan_text = True raw_sections.append(raw_episode_contents) raw_episode_contents = [] else: raw_episode_contents.append(child) return raw_sections def find_section_id(sections, id): """ Find the section with a given id """ for idx, section in enumerate(sections): try: if section['id'] == id: return idx except KeyError: continue return None def process_extracted_contents(inline_intro): """ Remove html markup """ return inline_intro['contents'] def parse(doc): """ parse google doc files and extract markup """ try: parsed_document = {} logger.info('-------------start------------') raw_sections = split_sections(doc) sections = parse_raw_sections(raw_sections) logger.info('Number of sections: %s' % len(sections)) parsed_document['sections'] = sections finally: logger.info('-------------end------------') return parsed_document
[ 2, 4808, 9, 62, 19617, 25, 40477, 12, 23, 4808, 9, 62, 198, 11748, 18931, 198, 11748, 302, 198, 11748, 598, 62, 11250, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 6738, 1790, 8189, 1330, 1429, 62, 19509, 8189, 198, 198, 6...
2.127553
2,203
""" Abdur-Rahmaan Janhangeer Skeleton of https://github.com/pyhoneybot/honeybot/ """ import time import os import socket directory = "irc" if not os.path.exists(directory): os.makedirs(directory) target = open(os.path.join(directory, "log.txt"), "w") BOT_IRC_SERVER = "chat.freenode.net" BOT_IRC_CHANNEL = "##bottestingmu" # BOT_IRC_CHANNEL = "#python" BOT_IRC_PORT = 6667 BOT_NICKNAME = "appinventormuBot" # BOT_PASSWORD = '' irc = socket.socket() irc.connect((BOT_IRC_SERVER, BOT_IRC_PORT)) irc.recv(4096) irc.send(bytes("NICK " + BOT_NICKNAME + "\r\n", "utf8")) ping_checker(irc.recv(4096)) irc.send( bytes( "USER appinventormuBot appinventormuBot appinventormuBot : appinventormuBot IRC\r\n", "utf8", ) ) ping_checker(irc.recv(4096)) # irc.send(bytes('msg NickServ identify ' + BOT_PASSWORD + " \r\n" ,'utf8') ) # ping_checker(irc.recv(4096)) # irc.send(bytes('NICKSERV identify ' + BOT_NICKNAME+' '+BOT_PASSWORD+ '\r\n','utf8' ) ) # ping_checker(irc.recv(4096)) time.sleep(3) irc.send(bytes("JOIN " + BOT_IRC_CHANNEL + "\r\n", "utf8")) while 1: pass line = irc.recv(4096) print(line) ping_checker(line) if ( line.find(bytes("PRIVMSG", "utf8")) != -1 or line.find(bytes("NOTICE", "utf8")) != -1 ): message_checker(line) target.write(str(line)) target.flush()
[ 37811, 198, 4826, 67, 333, 12, 47135, 2611, 272, 2365, 71, 858, 263, 198, 50, 38800, 286, 3740, 1378, 12567, 13, 785, 14, 9078, 71, 1419, 13645, 14, 71, 1419, 13645, 14, 198, 37811, 198, 198, 11748, 640, 198, 11748, 28686, 198, 1174...
2.126935
646
# coding: utf-8 """ Xenia Python Client Library Python Client Library to interact with the Xenia API. # noqa: E501 The version of the OpenAPI document: v2.1 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from xenia_python_client_library.configuration import Configuration def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AttachmentsList): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, AttachmentsList): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 21173, 544, 11361, 20985, 10074, 628, 220, 220, 220, 11361, 20985, 10074, 284, 9427, 351, 262, 21173, 544, 7824, 13, 220, 1303, 645, 20402, 25, 412, 33548, 628, 22...
2.603675
381
################################################################################ # Create a Registration with the UI for a Role. # Each module's aushadha.py is screened for this # # Each Class is registered for a Role in UI # These can be used to generate Role based UI elements later. # # As of now string base role assignement is done. # This can be later extended to class based role ################################################################################ from .models import Chapter, Section,Diagnosis from AuShadha.apps.ui.ui import ui as UI UI.register('RegistryApp',Chapter ) UI.register('DiseaseCodes',Chapter) UI.register('ReferenceApp',Chapter)
[ 29113, 29113, 14468, 198, 2, 13610, 257, 24610, 351, 262, 12454, 329, 257, 20934, 13, 220, 198, 2, 5501, 8265, 338, 257, 1530, 324, 3099, 13, 9078, 318, 32862, 329, 428, 198, 2, 220, 198, 2, 5501, 5016, 318, 6823, 329, 257, 20934, ...
4.226415
159
from turtle import *
[ 6738, 28699, 1330, 1635, 198 ]
4.2
5
""" Define the Movie model """ from . import db from .abc import BaseModel, MetaBaseModel
[ 37811, 198, 7469, 500, 262, 15875, 2746, 198, 37811, 198, 6738, 764, 1330, 20613, 198, 6738, 764, 39305, 1330, 7308, 17633, 11, 30277, 14881, 17633, 628 ]
3.5
26
f""" Shell script tho reproduce results for BERTScores in data from WMT18/19 Metrics Shared task. """ import argparse import hashlib import logging import os import sys from typing import Any, Dict, Iterator, List import numpy as np import pandas as pd import sentencepiece as spm import torch from tqdm import tqdm from fairseq import utils from fairseq import checkpoint_utils from fairseq.data import LanguagePairDataset #!/usr/bin/env python3 logger = logging.getLogger('prism') logger.setLevel(logging.INFO) MODELS = { '8412b2044da4b9b2c0a8ce87b305d0d1': { 'name': 'm39v1', 'path': 'todo', 'date': '2020-04-30', 'description': 'model released with arXiv paper April 2020', 'langs': ['ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'eo', 'fi', 'fr', 'he', 'hr', 'hu', 'id', 'it', 'ja', 'kk', 'lt', 'lv', 'mk', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sv', 'tr', 'uk', 'vi', 'zh'], } } """ Copy of https://github.com/pytorch/fairseq/blob/master/fairseq/sequence_scorer.py with softmax temperature control added """ def compute_kendall( hyp1_scores: list, hyp2_scores: list, dataframe: pd.DataFrame ) -> (int, list): """ Computes the official WMT19 shared task Kendall correlation score. """ assert len(hyp1_scores) == len(hyp2_scores) == len(data) conc, disc = 0, 0 for i, row in tqdm(data.iterrows(), total=len(data), desc="Kendall eval..."): if hyp1_scores[i] > hyp2_scores[i]: conc += 1 else: disc += 1 return (conc - disc) / (conc + disc) def run_prism(mt: list, ref: list, language=False, temperature=1.0) -> list: prism = Prism(model_dir="m39v1", lang=language, temperature=temperature) scores = prism.score(cand=mt, ref=ref, segment_scores=True) return list(scores) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Evaluates BERTScores against relative preferences." ) parser.add_argument( "--test_path", default="wmt-metrics/wmt19/de-en/relative-ranks.csv", help="Path to the test dataframe with relative preferences.", type=str, ) parser.add_argument( "--language", default="en", help="Target language of the testset.", type=str, ) parser.add_argument( '--temperature', type=float, default=1.0, help='Softmax temperature: values >1.0 produce more uniform samples and values <1.0 produce sharper samples') parser.add_argument( "--run_wmt18", default=False, help="Runs entire WMT18 evaluation.", action="store_true", ) parser.add_argument( "--run_wmt19", default=False, help="Runs entire WMT19 evaluation.", action="store_true", ) args = parser.parse_args() if args.run_wmt18: lps = [ "en-cs", "en-de", "en-et", "en-fi", "en-ru", "en-tr", "en-zh", "cs-en", "de-en", "et-en", "fi-en", "ru-en", "tr-en", "zh-en", ] kendall_scores = {} for lp in lps: data = pd.read_csv(f"wmt-metrics/wmt18/{lp}/relative-ranks.csv") hyp1_scores = run_prism([str(s) for s in data.hyp1], list(data.ref), language=lp.split('-')[1], temperature=args.temperature) hyp2_scores = run_prism([str(s) for s in data.hyp2], list(data.ref), language=lp.split('-')[1], temperature=args.temperature) #hyp1_scores = run_prism([str(s) for s in data.hyp1], list(data.ref), list(data.src), language=lp.split('-')[1]) #hyp2_scores = run_prism([str(s) for s in data.hyp2], list(data.ref), list(data.src), language=lp.split('-')[1]) kendall = compute_kendall(hyp1_scores, hyp2_scores, data) print("Results for {}: {}".format(lp, kendall)) kendall_scores[lp] = kendall print(kendall_scores) elif args.run_wmt19: lps = [ "en-cs", "en-de", "en-fi", "en-gu", "en-kk", "en-lt", "en-ru", "en-zh", "de-en", "fi-en", "gu-en", "kk-en", "lt-en", "ru-en", "zh-en", "de-cs", "de-fr", "fr-de", ] kendall_scores = {} for lp in lps: data = pd.read_csv(f"wmt-metrics/wmt19/{lp}/relative-ranks.csv") hyp1_scores = run_prism([str(s) for s in data.hyp1], list(data.ref), language=lp.split('-')[1], temperature=args.temperature) hyp2_scores = run_prism([str(s) for s in data.hyp2], list(data.ref), language=lp.split('-')[1], temperature=args.temperature) kendall = compute_kendall(hyp1_scores, hyp2_scores, data) print("Results for {}: {}".format(lp, kendall)) kendall_scores[lp] = kendall print(kendall_scores) else: data = pd.read_csv(args.test_path) kendall_scores = {} hyp1_scores = run_prism([str(s) for s in data.hyp1], list(data.ref), language=lp.split('-')[1], temperature=args.temperature) hyp2_scores = run_prism([str(s) for s in data.hyp2], list(data.ref), language=lp.split('-')[1], temperature=args.temperature) kendall = compute_kendall(hyp1_scores, hyp2_scores, data) print("Results for {}: {}".format(args.test_path, kendall)) kendall_scores[lp] = kendall print(kendall_scores)
[ 69, 37811, 198, 23248, 4226, 42796, 22919, 2482, 329, 347, 17395, 3351, 2850, 287, 1366, 422, 370, 13752, 1507, 14, 1129, 3395, 10466, 39403, 4876, 13, 198, 37811, 198, 11748, 1822, 29572, 198, 11748, 12234, 8019, 198, 11748, 18931, 198, ...
2.026016
2,806
import os os.makedirs('./img/', exist_ok=True) IMAGE_URL = "https://mofanpy.com/static/img/description/learning_step_flowchart.png" urllib_download() print('download image1') request_download() print('download image2') chunk_download() print('download image3')
[ 11748, 28686, 198, 418, 13, 76, 4335, 17062, 7, 4458, 14, 9600, 14, 3256, 2152, 62, 482, 28, 17821, 8, 198, 198, 3955, 11879, 62, 21886, 796, 366, 5450, 1378, 76, 1659, 272, 9078, 13, 785, 14, 12708, 14, 9600, 14, 11213, 14, 40684...
2.821053
95
from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout import tensorflow.keras as keras import os import cv2 import numpy as np from sklearn.model_selection import train_test_split def data_prep(path, img_rows, img_cols, color): """ A function to preprocess the input data for a CNN. The images are resized, normalised to have pixel values between 0-1, converted into greyscale if required and put into a numpy array. Each class label is turned into a one hot pixel array and added to an ordered numpy array such that the order for the labels is the same as the images. The data is shuffled to make sure each batch is representative of the overall data during training which will reduce overfitting to each batch. This function requires that the images for each class are in a seperate directory. param: - path, a string of the path to the directory containing the images - img_rows, an integer for the number of rows the resized image should have - img_cols, an integer for the number of columns the resized image should have - color, a boolean that is set to true if the image should be in RGB colour space or false for greyscale return: - images, a numpy array of images with pixel values normalised to be between 0 and 1. numpy array dimensions are [number of images, number of rows, number of columns, number of chanels] - labels, a numpy array of labels associated with each image (labels are a one hot pixel numpy array [1, 0, 0, ...] or [0, 1, 0, ...], etc) """ images = [] labels = [] for image_class in os.listdir(path): print('image_class =', image_class) path_to_class_directory = os.path.join(path, image_class) for img_name in os.listdir(path_to_class_directory): true_path = os.path.join(path_to_class_directory, img_name) if color: images.append(cv2.imread(true_path, 1)/255.0) else: images.append(cv2.imread(true_path, 0)/255.0) # greyscale labels.append(os.listdir(path).index(image_class)) data = list(zip(images, labels)) np.random.shuffle(data) images, labels = zip(*data) images = [cv2.resize(img, (img_rows, img_cols), cv2.INTER_AREA) for img in images] # resize images to all be the same if color: images = np.array(images).reshape(len(images), img_rows, img_cols, 3) else: images = np.array(images).reshape(len(images), img_rows, img_cols, 1) labels = keras.utils.to_categorical(labels, num_classes=len(os.listdir(path))) return images, labels def decode_labels(coded, class_names): """ A funtion to get the name of the class by decoding a one hot pixel array. Uses a list comprehension and boolean indexing. The list comprehension returns the index of the variable with the highest value in each one hot pixel array. That list is then used for boolean indexing with a numpy array to get a list of class_names for each label in coded. Param: - coded, a numpy array of coded labels - class_names, a list of the class_names in the same order they were coded (alphabetical) Return: - numpy array of class names for each label in coded """ return np.array(class_names)[[np.argmax(example) for example in coded]] def calc_accuracy(pred, real): """ A function to calculate the accuracy of a CNN when given a list of predicted classes and a list of the real classes Param: - pred, a numpy array of predicted classes - real, a numpy array of the real classes Return: - Accuracy as a decimal """ return sum(pred==real) / len(pred) if __name__ == '__main__': path = 'data' img_rows = 150 img_cols = 150 is_color = True model_filename = 'flare_cnn' print('\nloading training data\n') num_classes = len(os.listdir(path)) x, y = data_prep(path, img_rows, img_cols, color=is_color) x_train, x_test, y_train, y_test = train_test_split(x, y) print('\nbuilding model\n') cnn = build_CNN(img_rows, img_cols, color=is_color) print('\ntraining model\n') cnn.fit(x_train, y_train, batch_size=50, epochs=1, validation_split=0.2) print('\nsaving model\n') if is_color: model_filename = model_filename + '_RGB' + '.h5' else: model_filename = model_filename + '_grey' + '.h5' cnn.save(model_filename) print('\nsaved model to file {}\n'.format(model_filename)) print('\nloading model\n') loaded_cnn = keras.models.load_model(model_filename) print('\ngenerating predictions\n') predictions = loaded_cnn.predict(x_test) dec_preds = decode_labels(predictions, os.listdir(path)) dec_ytest = decode_labels(y_test, os.listdir(path)) # F1 score would probably be a better metric due to skew of training expample (num B > num C) print('\naccuracy =', calc_accuracy(dec_preds, dec_ytest))
[ 6738, 11192, 273, 11125, 13, 6122, 292, 1330, 24604, 1843, 198, 6738, 11192, 273, 11125, 13, 6122, 292, 13, 75, 6962, 1330, 34872, 17, 35, 11, 1610, 41769, 11, 360, 1072, 11, 14258, 448, 198, 11748, 11192, 273, 11125, 13, 6122, 292, ...
2.669456
1,912
""" Oracle library """ import lib_common from lib_properties import pc # Ambiguity with tables, oracle or normal users.
[ 37811, 198, 48625, 5888, 198, 37811, 198, 198, 11748, 9195, 62, 11321, 198, 6738, 9195, 62, 48310, 1330, 40653, 628, 198, 2, 12457, 328, 14834, 351, 8893, 11, 393, 6008, 393, 3487, 2985, 13, 198 ]
3.514286
35
"""Training method""" import argparse import json import os import pathlib from typing import Union import numpy as np import torch from torch.backends import cudnn import pytorch_lightning as pl import dgmvae.models as dvm from experiment import VAEUpdater def export_model(model: Union[torch.nn.Module, torch.jit.ScriptModule], path: Union[str, pathlib.Path], input_shape: tuple = (1, 3, 64, 64), use_script_module: bool = True ) -> Union[str, pathlib.Path]: """Exports model. Args: model (torch.nn.Module or torch.jit.ScriptModule): Saved model. path (str or pathlib.Path): Path to file. input_shape (tuple, optional): Tuple of input data shape. use_script_module (bool, optional): Boolean flag for using script module. Returns: path (str or pathlib.Path): Path to saved file. """ model = model.cpu().eval() if isinstance(model, torch.jit.ScriptModule): assert use_script_module, \ "Provided model is a ScriptModule, set use_script_module to True." if use_script_module: if not isinstance(model, torch.jit.ScriptModule): assert input_shape is not None traced_model = torch.jit.trace(model, torch.zeros(*input_shape)) else: traced_model = model torch.jit.save(traced_model, path) else: torch.save(model, path) # saves model as a nn.Module return path if __name__ == "__main__": main()
[ 198, 37811, 44357, 2446, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 3108, 8019, 198, 6738, 19720, 1330, 4479, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 18...
2.418097
641
from myhdl import Signal, intbv, block, always_comb, ConcatSignal import myhdl from collections import OrderedDict import keyword def _is_valid_name(ident: str) -> bool: '''Determine if ident is a valid register or bitfield name. ''' if not isinstance(ident, str): raise TypeError("expected str, but got {!r}".format(type(ident))) if not ident.isidentifier(): return False if keyword.iskeyword(ident): return False return True
[ 6738, 616, 71, 25404, 1330, 26484, 11, 493, 65, 85, 11, 2512, 11, 1464, 62, 24011, 11, 1482, 9246, 11712, 282, 198, 11748, 616, 71, 25404, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 11748, 21179, 198, 198, 4299, 4808, 2...
2.770115
174
import random
[ 11748, 4738, 628, 628, 220, 220, 220, 220 ]
2.625
8
"""Advanced Tensor slicing ========================== Utilities for advanced tensor slicing and batching operations. Reference --------- """ import tensorflow as tf def slice_within_stride(x, stride, si=0, ei=None, keepdims=True): """Select ``x[..., (i * stride + si):(i * stride + ei)]`` for each i. The tensor returned will have the last dimension shrunk by a factor of ``(ei-si)/stride``. As a natural special case, ``tb.multiple_within_stride(x, N)`` is equivalent to adding a dimension of ``N`` at the end, as in ``tf.expand_dims(x, (..., -1, N))``. Example: When predicting anchor positions in SSD, ``num_classes + num_offsets`` are predicted for each anchor. To get only the class confidence, this would be used:: logits = model(input) class_logits = tb.slice_within_stride( logits, 0, num_classes, num_classes + num_offsets) loss = softmax_cross_entropy_with_logits( class_preds, class_logits) Args: x (tf.Tensor): value to modify stride (int): stride for the last dimension si (int): starting index within stride. Negative indices are supported. Defaults to 0. ei (int): end index (1 element after the last) within stride. Negative indices are supported. Defaults to ``None``, which means "until the last element". keepdims (bool): if False, adds another dimension that iterates over each stride. This dimension will be of size ``ei-si``. Defaults to True. Returns: tf.Tensor: modified ``x`` with the last dimension sliced. """ step1 = tf.reshape(x, (-1, stride)) step2 = step1[..., si:ei] new_shape = list(x.shape) new_shape[-1] = -1 if not keepdims: if ei is None: ei = stride # Calculate the size of the slice. This is O(stride) which is # small. last_dim_len = len(list(range(stride)[si:ei])) new_shape.append(last_dim_len) print("NS: {}".format(new_shape)) step3 = tf.reshape(step2, new_shape) return step3
[ 37811, 28809, 309, 22854, 49289, 198, 4770, 2559, 855, 198, 198, 18274, 2410, 329, 6190, 11192, 273, 49289, 290, 15458, 278, 4560, 13, 628, 198, 26687, 198, 45537, 198, 37811, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 4299, 1...
2.36859
936
# Copyright (c) 2014 Simplistix Ltd # See license.txt for license details. from decimal import Decimal from testfixtures import RoundComparison as R, compare, ShouldRaise from unittest import TestCase from ..compat import PY2, PY3
[ 2, 15069, 357, 66, 8, 1946, 45157, 396, 844, 12052, 198, 2, 4091, 5964, 13, 14116, 329, 5964, 3307, 13, 198, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 1332, 69, 25506, 1330, 10485, 50249, 1653, 355, 371, 11, 8996, 11, 10358, 21...
3.492537
67
"""***************************************************************************** * Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" currentQSizeRead = 1 currentQSizeWrite = 1 currentQSizeSerialStateNotification = 1 cdcInterfacesNumber = 2 cdcDescriptorSize = 58 cdcEndpointsPic32 = 2 cdcEndpointsSAM = 3 indexFunction = None configValue = None startInterfaceNumber = None numberOfInterfaces = None useIad = None epNumberInterrupt = None epNumberBulkOut = None epNumberBulkIn = None cdcEndpointNumber = None # This function is called when user modifies the CDC Queue Size.
[ 37811, 17174, 17174, 4557, 35625, 198, 9, 15069, 357, 34, 8, 13130, 4527, 35902, 8987, 3457, 13, 290, 663, 34943, 13, 198, 9, 198, 9, 15540, 284, 534, 11846, 351, 777, 2846, 11, 345, 743, 779, 4527, 35902, 3788, 198, 9, 290, 597, ...
3.581489
497
""" quant_test ~~~~~~ The quant_test package - a Python package template project that is intended to be used as a cookie-cutter for developing new Python packages. """
[ 37811, 198, 40972, 62, 9288, 198, 8728, 4907, 198, 198, 464, 5554, 62, 9288, 5301, 532, 257, 11361, 5301, 11055, 1628, 326, 318, 5292, 198, 1462, 307, 973, 355, 257, 19751, 12, 8968, 353, 329, 5922, 649, 11361, 10392, 13, 198, 37811, ...
3.930233
43
import re from django.utils.html import escape from django.utils.safestring import mark_safe from ..utils import Parameter
[ 11748, 302, 198, 6738, 42625, 14208, 13, 26791, 13, 6494, 1330, 6654, 198, 6738, 42625, 14208, 13, 26791, 13, 49585, 395, 1806, 1330, 1317, 62, 21230, 198, 198, 6738, 11485, 26791, 1330, 25139, 2357, 198 ]
3.542857
35
# -*- coding=utf-8 -*- # author: dongrixinyu # contact: dongrixinyu.89@163.com # blog: https://github.com/dongrixinyu/ # file: bare_embedding.py # time: 2020-06-12 11:27 import os import pdb import logging from typing import Union, Optional, Dict, Any, Tuple import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from jiotc.embeddings.base_embedding import BaseEmbedding from .base_model import BaseModel # Bidirectional LSTM neural network (many-to-one)
[ 2, 532, 9, 12, 19617, 28, 40477, 12, 23, 532, 9, 12, 198, 198, 2, 1772, 25, 288, 506, 8609, 3541, 84, 198, 2, 2800, 25, 288, 506, 8609, 3541, 84, 13, 4531, 31, 24136, 13, 785, 198, 2, 4130, 25, 3740, 1378, 12567, 13, 785, 14...
2.786096
187
import numpy as np from psyneulink import PredictionErrorDeltaFunction np.set_printoptions(suppress=True)
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 17331, 710, 377, 676, 1330, 46690, 12331, 42430, 22203, 198, 198, 37659, 13, 2617, 62, 4798, 25811, 7, 18608, 601, 28, 17821, 8, 198 ]
3.375
32
from datetime import datetime as dt from django.utils import timezone import uuid from django.contrib.auth import get_user_model from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view from company.utils import get_or_create_company from position.utils import get_or_insert_position from utils import utils from utils.error_codes import ResponseCodes from utils.generic_json_creator import create_response from .models import JobApplication, Contact, ApplicationStatus, StatusHistory from .models import JobApplicationNote, JobApplicationFile from .models import Source from alumni.serializers import AlumniSerializer from .serializers import ApplicationStatusSerializer from .serializers import JobApplicationNoteSerializer, JobApplicationFileSerializer from .serializers import JobApplicationSerializer, ContactSerializer from .serializers import SourceSerializer from .serializers import StatusHistorySerializer User = get_user_model()
[ 6738, 4818, 8079, 1330, 4818, 8079, 355, 288, 83, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 11748, 334, 27112, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, ...
4
257
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python x=5 print x reassign(x) print x
[ 2, 48443, 23377, 14, 42026, 14, 37906, 13, 30604, 14, 45150, 14, 17, 13, 22, 14, 8800, 14, 29412, 198, 198, 87, 28, 20, 198, 4798, 2124, 198, 260, 562, 570, 7, 87, 8, 198, 4798, 2124, 198 ]
2.526316
38
from collections import namedtuple from dagster import check from dagster.config.config_type import ConfigType, ConfigTypeKind from dagster.config.field import Field from dagster.core.serdes import whitelist_for_serdes # This function is used by the recursive descent # through all the inner types. This does *not* # recursively descend through the type parameters # of generic types. It just gets the next level of # types. Either the direct type parameters of a # generic type. Or the type refs of all the fields # if it is a type with fields. def _get_next_level_refs(ref): # if a generic type, get type params # if a type with fields, get refs of the fields if ConfigTypeKind.is_closed_generic(ref.kind): return ref.type_param_refs elif ( ConfigTypeKind.has_fields(ref.kind) and ref.fields ): # still check fields because permissive return [field_meta.type_ref for field_meta in ref.fields] # A type reference in these serializable data structures are one of two things # 1) A closed generic type (e.g. List[Int] of Optional[Set[str]]) # 2) Or a reference to a non-generic type, such as Dict, Selector, or a Scalar. # Upon deserialization and when hydrated back to the graphql query, it will # be the responsibility of that module to maintain a dictionary of the # non-generic types and then do lookups into the dictionary in order to # to explode the entire type hierarchy requested by the client TypeRef = (ConfigTypeMeta, NonGenericTypeRefMeta) def meta_from_field(name, field): check.str_param(name, 'name') check.inst_param(field, 'field', Field) return ConfigFieldMeta( name=name, type_ref=type_ref_of(field.config_type), is_required=field.is_required, default_provided=field.default_provided, default_value_as_str=field.default_value_as_str if field.default_provided else None, description=field.description, ) def type_ref_of(config_type): check.inst_param(config_type, 'config_type', ConfigType) if ConfigTypeKind.is_closed_generic(config_type.kind): return meta_from_config_type(config_type) else: return NonGenericTypeRefMeta(key=config_type.key) def type_refs_of(type_list): return list(map(type_ref_of, type_list)) if type_list is not None else None def meta_from_config_type(config_type): check.inst_param(config_type, 'config_type', ConfigType) return ConfigTypeMeta( key=config_type.key, given_name=config_type.given_name, kind=config_type.kind, description=config_type.description, type_param_refs=type_refs_of(config_type.type_params), enum_values=[ ConfigEnumValueMeta(ev.config_value, ev.description) for ev in config_type.enum_values ] if config_type.kind == ConfigTypeKind.ENUM else None, fields=[meta_from_field(name, field) for name, field in config_type.fields.items()] if ConfigTypeKind.has_fields(config_type.kind) else None, )
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 6738, 48924, 1706, 1330, 2198, 198, 6738, 48924, 1706, 13, 11250, 13, 11250, 62, 4906, 1330, 17056, 6030, 11, 17056, 6030, 35854, 198, 6738, 48924, 1706, 13, 11250, 13, 3245, 1330, 7663, 198...
2.826977
1,075
from orator.migrations import Migration
[ 6738, 393, 1352, 13, 76, 3692, 602, 1330, 36991, 628 ]
4.1
10
from configparser import ConfigParser import os import json obj = {} config = ConfigParser() config.read(os.path.join(os.getenv("HOME"), ".aws", "credentials")) obj["MY_ACCESS_KEY"] = config.get("default", "aws_access_key_id", fallback="") obj["MY_SECRET_KEY"] = config.get("default", "aws_secret_access_key", fallback="") with open("config.json", "w") as out: json.dump(obj, out)
[ 6738, 4566, 48610, 1330, 17056, 46677, 198, 11748, 28686, 198, 11748, 33918, 198, 198, 26801, 796, 23884, 198, 11250, 796, 17056, 46677, 3419, 198, 11250, 13, 961, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 1136, 24330, 7203, 39069, 12340...
2.824818
137
######################################################### # 1 ######################################################### import sys import math # 4 if len(sys.argv[1:]) != 4: error_usage() n1,p1,n2,p2 = map(float, sys.argv[1:]) p = ((n1*p1) + (n2*p2))/(n1+n2) # n30 if (n1 < 30) or (n2 < 30): error_usage() # 01 if not (0 <= p1 <= 1) or not (0 <= p2 <= 1): error_usage() T = math.fabs(p1 - p2) / math.sqrt((p * (1-p)) * ((1/n1) + (1/n2))) if T >= 2.58: print("1% (:" + str(T) + "") elif T >= 1.96: print("5% (:" + str(T) + "") elif T >= 1.65: print("10% (:" + str(T) + "") else: print(" (:" + str(T) + "")
[ 29113, 14468, 7804, 2, 198, 2, 352, 198, 29113, 14468, 7804, 2, 198, 198, 11748, 25064, 198, 11748, 10688, 198, 198, 2, 604, 198, 361, 18896, 7, 17597, 13, 853, 85, 58, 16, 25, 12962, 14512, 604, 25, 198, 220, 220, 220, 4049, 62, ...
2.129568
301
# coding=utf-8 import functools from flask import Flask, session from flask import redirect from flask import request, make_response from flask import render_template from flask import url_for from flask_bootstrap import Bootstrap # from db import * # json import json # app app = Flask(__name__, instance_relative_config=True) bootstrap=Bootstrap(app) app.secret_key = 'lab3' # app # # urlhost/table # # # # # # # # # # html # URLhtml page # if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
[ 2, 19617, 28, 40477, 12, 23, 201, 198, 11748, 1257, 310, 10141, 201, 198, 201, 198, 6738, 42903, 1330, 46947, 11, 6246, 201, 198, 6738, 42903, 1330, 18941, 201, 198, 6738, 42903, 1330, 2581, 11, 787, 62, 26209, 201, 198, 6738, 42903, ...
2.18705
278
# Licensed under the MIT License from mymusichere import env
[ 2, 49962, 739, 262, 17168, 13789, 198, 198, 6738, 616, 28965, 1456, 1330, 17365, 628 ]
4.2
15
# STL imports import random import logging import string import time import datetime import random import struct import sys from functools import wraps # Third party imports import numpy as np import faker from faker.providers import BaseProvider logging.getLogger('faker').setLevel(logging.ERROR) sys.path.append('.') # grpc from milvus.grpc_gen import milvus_pb2 fake = faker.Faker() fake.add_provider(FakerProvider)
[ 2, 37269, 17944, 198, 11748, 4738, 198, 11748, 18931, 198, 11748, 4731, 198, 11748, 640, 198, 11748, 4818, 8079, 198, 11748, 4738, 198, 11748, 2878, 198, 11748, 25064, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 2, 10467, 2151, ...
3.083916
143
import math import os import random import re import sys first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) m = int(first_multiple_input[1]) matrix = [] if (n>0 and m>0 and n<100 and m< 100): for _ in range(n): matrix_item = input() matrix.append(matrix_item) for _ in range(m): string = "" for cols in range (m): for rows in range (n): string += matrix[rows][cols] output = re.sub(r"\b[!@#$%& ]+\b"," ", string) print(output)
[ 11748, 10688, 198, 11748, 28686, 198, 11748, 4738, 198, 11748, 302, 198, 11748, 25064, 628, 198, 11085, 62, 48101, 62, 15414, 796, 5128, 22446, 81, 36311, 22446, 35312, 3419, 198, 77, 796, 493, 7, 11085, 62, 48101, 62, 15414, 58, 15, ...
2.298246
228
# pylint: disable=C0111,R0902,R0904,R0912,R0913,R0915,E1101 # Smartsheet Python SDK. # # Copyright 2016 Smartsheet.com, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"): you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from .criteria import Criteria from ..types import TypedList from ..util import prep from datetime import datetime import json import logging import six
[ 2, 279, 2645, 600, 25, 15560, 28, 34, 486, 1157, 11, 49, 2931, 2999, 11, 49, 2931, 3023, 11, 49, 2931, 1065, 11, 49, 2931, 1485, 11, 49, 2931, 1314, 11, 36, 1157, 486, 198, 2, 2439, 5889, 25473, 11361, 26144, 13, 198, 2, 198, ...
3.483871
248
import torch import torch.nn.functional as F import os.path as osp import json from torch_geometric.utils import precision, recall from torch_geometric.utils import f1_score, accuracy from torch.utils.tensorboard import SummaryWriter
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 33918, 198, 198, 6738, 28034, 62, 469, 16996, 13, 26791, 1330, 15440, 11, 10014, 198, 6738, 28034, 62, 469, 16996,...
3.71875
64
# nuScenes dev-kit. # Code written by Holger Caesar, 2020. import argparse import gc import os import random from typing import List from collections import defaultdict import cv2 import tqdm from nuimages.nuimages import NuImages def render_images(nuim: NuImages, mode: str = 'all', cam_name: str = None, log_name: str = None, sample_limit: int = 50, filter_categories: List[str] = None, out_type: str = 'image', out_dir: str = '~/Downloads/nuImages', cleanup: bool = True) -> None: """ Render a random selection of images and save them to disk. Note: The images rendered here are keyframes only. :param nuim: NuImages instance. :param mode: What to render: "image" for the image without annotations, "annotated" for the image with annotations, "trajectory" for a rendering of the trajectory of the vehice, "all" to render all of the above separately. :param cam_name: Only render images from a particular camera, e.g. "CAM_BACK'. :param log_name: Only render images from a particular log, e.g. "n013-2018-09-04-13-30-50+0800". :param sample_limit: Maximum number of samples (images) to render. Note that the mini split only includes 50 images. :param filter_categories: Specify a list of object_ann category names. Every sample that is rendered must contain annotations of any of those categories. :param out_type: The output type as one of the following: 'image': Renders a single image for the image keyframe of each sample. 'video': Renders a video for all images/pcls in the clip associated with each sample. :param out_dir: Folder to render the images to. :param cleanup: Whether to delete images after rendering the video. Not relevant for out_type == 'image'. """ # Check and convert inputs. assert out_type in ['image', 'video'], ' Error: Unknown out_type %s!' % out_type all_modes = ['image', 'annotated', 'trajectory'] assert mode in all_modes + ['all'], 'Error: Unknown mode %s!' % mode assert not (out_type == 'video' and mode == 'trajectory'), 'Error: Cannot render "trajectory" for videos!' if mode == 'all': if out_type == 'image': modes = all_modes elif out_type == 'video': modes = [m for m in all_modes if m not in ['annotated', 'trajectory']] else: raise Exception('Error" Unknown mode %s!' % mode) else: modes = [mode] if filter_categories is not None: category_names = [c['name'] for c in nuim.category] for category_name in filter_categories: assert category_name in category_names, 'Error: Invalid object_ann category %s!' % category_name # Create output folder. out_dir = os.path.expanduser(out_dir) if not os.path.isdir(out_dir): os.makedirs(out_dir) # Filter by camera. sample_tokens = [s['token'] for s in nuim.sample] if cam_name is not None: sample_tokens_cam = [] for sample_token in sample_tokens: sample = nuim.get('sample', sample_token) key_camera_token = sample['key_camera_token'] sensor = nuim.shortcut('sample_data', 'sensor', key_camera_token) if sensor['channel'] == cam_name: sample_tokens_cam.append(sample_token) sample_tokens = sample_tokens_cam # Filter by log. if log_name is not None: sample_tokens_cleaned = [] for sample_token in sample_tokens: sample = nuim.get('sample', sample_token) log = nuim.get('log', sample['log_token']) if log['logfile'] == log_name: sample_tokens_cleaned.append(sample_token) sample_tokens = sample_tokens_cleaned # Filter samples by category. if filter_categories is not None: # Get categories in each sample. sd_to_object_cat_names = defaultdict(lambda: set()) for object_ann in nuim.object_ann: category = nuim.get('category', object_ann['category_token']) sd_to_object_cat_names[object_ann['sample_data_token']].add(category['name']) # Filter samples. sample_tokens_cleaned = [] for sample_token in sample_tokens: sample = nuim.get('sample', sample_token) key_camera_token = sample['key_camera_token'] category_names = sd_to_object_cat_names[key_camera_token] if any([c in category_names for c in filter_categories]): sample_tokens_cleaned.append(sample_token) sample_tokens = sample_tokens_cleaned # Get a random selection of samples. random.shuffle(sample_tokens) # Limit number of samples. sample_tokens = sample_tokens[:sample_limit] print('Rendering %s for mode %s to folder %s...' % (out_type, mode, out_dir)) for sample_token in tqdm.tqdm(sample_tokens): sample = nuim.get('sample', sample_token) log = nuim.get('log', sample['log_token']) log_name = log['logfile'] key_camera_token = sample['key_camera_token'] sensor = nuim.shortcut('sample_data', 'sensor', key_camera_token) sample_cam_name = sensor['channel'] sd_tokens = nuim.get_sample_content(sample_token) # We cannot render a video if there are missing camera sample_datas. if len(sd_tokens) < 13 and out_type == 'video': print('Warning: Skipping video for sample token %s, as not all 13 frames exist!' % sample_token) continue for mode in modes: out_path_prefix = os.path.join(out_dir, '%s_%s_%s_%s' % (log_name, sample_token, sample_cam_name, mode)) if out_type == 'image': write_image(nuim, key_camera_token, mode, '%s.jpg' % out_path_prefix) elif out_type == 'video': write_video(nuim, sd_tokens, mode, out_path_prefix, cleanup=cleanup) def write_video(nuim: NuImages, sd_tokens: List[str], mode: str, out_path_prefix: str, cleanup: bool = True) -> None: """ Render a video by combining all the images of type mode for each sample_data. :param nuim: NuImages instance. :param sd_tokens: All sample_data tokens in chronological order. :param mode: The mode - see render_images(). :param out_path_prefix: The file prefix used for the images and video. :param cleanup: Whether to delete images after rendering the video. """ # Loop through each frame to create the video. out_paths = [] for i, sd_token in enumerate(sd_tokens): out_path = '%s_%d.jpg' % (out_path_prefix, i) out_paths.append(out_path) write_image(nuim, sd_token, mode, out_path) # Create video. first_im = cv2.imread(out_paths[0]) freq = 2 # Display frequency (Hz). fourcc = cv2.VideoWriter_fourcc(*'MJPG') video_path = '%s.avi' % out_path_prefix out = cv2.VideoWriter(video_path, fourcc, freq, first_im.shape[1::-1]) # Load each image and add to the video. for out_path in out_paths: im = cv2.imread(out_path) out.write(im) # Delete temporary image if requested. if cleanup: os.remove(out_path) # Finalize video. out.release() def write_image(nuim: NuImages, sd_token: str, mode: str, out_path: str) -> None: """ Render a single image of type mode for the given sample_data. :param nuim: NuImages instance. :param sd_token: The sample_data token. :param mode: The mode - see render_images(). :param out_path: The file to write the image to. """ if mode == 'annotated': nuim.render_image(sd_token, annotation_type='all', out_path=out_path) elif mode == 'image': nuim.render_image(sd_token, annotation_type='none', out_path=out_path) elif mode == 'trajectory': sample_data = nuim.get('sample_data', sd_token) nuim.render_trajectory(sample_data['sample_token'], out_path=out_path) else: raise Exception('Error: Unknown mode %s!' % mode) # Trigger garbage collection to avoid memory overflow from the render functions. gc.collect() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Render a random selection of images and save them to disk.') parser.add_argument('--seed', type=int, default=42) # Set to 0 to disable. parser.add_argument('--version', type=str, default='v1.0-mini') parser.add_argument('--dataroot', type=str, default='/data/sets/nuimages') parser.add_argument('--verbose', type=int, default=1) parser.add_argument('--mode', type=str, default='all') parser.add_argument('--cam_name', type=str, default=None) parser.add_argument('--log_name', type=str, default=None) parser.add_argument('--sample_limit', type=int, default=50) parser.add_argument('--filter_categories', action='append') parser.add_argument('--out_type', type=str, default='image') parser.add_argument('--out_dir', type=str, default='~/Downloads/nuImages') args = parser.parse_args() # Set random seed for reproducible image selection. if args.seed != 0: random.seed(args.seed) # Initialize NuImages class. nuim_ = NuImages(version=args.version, dataroot=args.dataroot, verbose=bool(args.verbose), lazy=False) # Render images. render_images(nuim_, mode=args.mode, cam_name=args.cam_name, log_name=args.log_name, sample_limit=args.sample_limit, filter_categories=args.filter_categories, out_type=args.out_type, out_dir=args.out_dir)
[ 2, 14364, 3351, 18719, 1614, 12, 15813, 13, 198, 2, 6127, 3194, 416, 6479, 1362, 24088, 11, 12131, 13, 198, 198, 11748, 1822, 29572, 198, 11748, 308, 66, 198, 11748, 28686, 198, 11748, 4738, 198, 6738, 19720, 1330, 7343, 198, 6738, 17...
2.465364
3,941
import re from configparser import ConfigParser from constants import PROJECT_FOLDER, RELEASE_LEVEL_DICT from release_type import ReleaseLevel, ReleaseType, value_from_key if __name__ == '__main__': # Test Script index = 0 version_info = VersionInfo(1, 0, 0, 0, ReleaseLevel.public, None, ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.bugfix) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.bugfix) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.hotfix) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.minor) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.beta, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.release_candidate, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.major) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.hotfix) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.public, release_type=ReleaseType.hotfix) print(index, version_info) index += 1 version_info.increment(ReleaseLevel.alpha, release_type=ReleaseType.minor) print(index, version_info) index += 1 _version = version_info.convert_to_godot_format() print(_version) _pattern: re.Pattern = re.compile(r"(\d)\.(\d)\.?(\d)?\.?(\d)?\.?([a-z]{1,2})?(\d{1,3})?") _match: re.Match = _pattern.match(_version.replace('"', '')) print(index, VersionInfo(*_match.groups()))
[ 11748, 302, 198, 6738, 4566, 48610, 1330, 17056, 46677, 198, 198, 6738, 38491, 1330, 21965, 23680, 62, 37, 3535, 14418, 11, 46492, 62, 2538, 18697, 62, 35, 18379, 198, 6738, 2650, 62, 4906, 1330, 13868, 4971, 11, 13868, 6030, 11, 1988, ...
2.801912
1,883
# test_create_json_items_from_embark_xml.py 2/18/19 sm """ test create_json_items_from_embark_xml.py """ import sys import json import unittest import csv from xml.etree.ElementTree import ElementTree, tostring # add parent directory to path import os import inspect CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) PARENTDIR = os.path.dirname(CURRENTDIR) sys.path.insert(0, PARENTDIR) import create_json_items_from_embark_xml def suite(): """ define test suite """ return unittest.TestLoader().loadTestsFromTestCase(Test) if __name__ == '__main__': suite() unittest.main()
[ 2, 1332, 62, 17953, 62, 17752, 62, 23814, 62, 6738, 62, 24419, 668, 62, 19875, 13, 9078, 362, 14, 1507, 14, 1129, 895, 198, 37811, 1332, 2251, 62, 17752, 62, 23814, 62, 6738, 62, 24419, 668, 62, 19875, 13, 9078, 37227, 198, 198, 1...
2.789474
228
import os import sys cwd = os.getcwd() sys.path.append(cwd) import pickle import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from plot.helper import plot_task, plot_weights, plot_rf_z_max, plot_rf_quad, plot_vector_traj tasks = [ 'com_pos', 'com_vel', 'chassis_quat', 'chassis_ang_vel', 'toeFL_pos', 'toeFL_vel', 'toeFR_pos', 'toeFR_vel', 'toeRR_pos', 'toeRR_vel', 'toeRL_pos', 'toeRL_vel' ] weights = [ 'w_com', 'w_chassis_ori', 'w_toeFL', 'w_toeFR', 'w_toeRR', 'w_toeRL' ] rf_z = ['rf_z_max_toeFL', 'rf_z_max_toeFR', 'rf_z_max_toeRR', 'rf_z_max_toeRL'] time = [] phase = [] rf_cmd = [] des, act = dict(), dict() for topic in tasks: des[topic] = [] act[topic] = [] w = dict() for topic in weights: w[topic] = [] rf_z_max = dict() for topic in rf_z: rf_z_max[topic] = [] with open('data/pnc.pkl', 'rb') as file: while True: try: d = pickle.load(file) time.append(d['time']) phase.append(d['phase']) for topic in tasks: des[topic].append(d[topic + '_des']) act[topic].append(d[topic]) for topic in weights: w[topic].append(d[topic]) for topic in rf_z: rf_z_max[topic].append(d[topic]) rf_cmd.append(d['rf_cmd']) except EOFError: break for k, v in des.items(): des[k] = np.stack(v, axis=0) for k, v in act.items(): act[k] = np.stack(v, axis=0) rf_cmd = np.stack(rf_cmd, axis=0) phase = np.stack(phase, axis=0) ## ============================================================================= ## Plot Task ## ============================================================================= plot_task(time, des['com_pos'], act['com_pos'], des['com_vel'], act['com_vel'], phase, 'com lin') plot_task(time, des['chassis_quat'], act['chassis_quat'], des['chassis_ang_vel'], act['chassis_ang_vel'], phase, 'pelvis ori') plot_task(time, des['toeFL_pos'], act['toeFL_pos'], des['toeFL_vel'], act['toeFL_vel'], phase, 'left foot lin') plot_task(time, des['toeFR_pos'], act['toeFR_pos'], des['toeFR_vel'], act['toeFR_vel'], phase, 'left foot ori') plot_task(time, des['toeRR_pos'], act['toeRR_pos'], des['toeRR_vel'], act['toeRR_vel'], phase, 'right foot lin') plot_task(time, des['toeRL_pos'], act['toeRL_pos'], des['toeRL_vel'], act['toeRL_vel'], phase, 'right foot ori') ## ============================================================================= ## Plot WBC Solutions ## ============================================================================= plot_rf_quad(time, rf_cmd, phase) ## ============================================================================= ## Plot Weights and Max Reaction Force Z ## ============================================================================= plot_weights(time, w, phase) plot_rf_z_max(time, rf_z_max, phase) plt.show()
[ 11748, 28686, 198, 11748, 25064, 198, 66, 16993, 796, 28686, 13, 1136, 66, 16993, 3419, 198, 17597, 13, 6978, 13, 33295, 7, 66, 16993, 8, 198, 11748, 2298, 293, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 1...
2.405774
1,247
from pyramid.httpexceptions import HTTPConflict from h.auth.util import client_authority from h.presenters import TrustedUserJSONPresenter from h.schemas import ValidationError from h.schemas.api.user import CreateUserAPISchema, UpdateUserAPISchema from h.services.user_unique import DuplicateUserError from h.views.api.config import api_config from h.views.api.exceptions import PayloadError def _json_payload(request): try: return request.json_body except ValueError as err: raise PayloadError() from err
[ 6738, 27944, 13, 2804, 24900, 11755, 1330, 14626, 18546, 13758, 198, 198, 6738, 289, 13, 18439, 13, 22602, 1330, 5456, 62, 9800, 414, 198, 6738, 289, 13, 25579, 364, 1330, 833, 8459, 12982, 40386, 34695, 263, 198, 6738, 289, 13, 1416, ...
3.122093
172
from kivy.logger import Logger from kivy.utils import platform __version__ = "2.3.2" _log_message = "KivyAuth:" + f" {__version__}" + f' (installed at "{__file__}")' __all__ = ("login_providers", "auto_login") Logger.info(_log_message)
[ 6738, 479, 452, 88, 13, 6404, 1362, 1330, 5972, 1362, 198, 6738, 479, 452, 88, 13, 26791, 1330, 3859, 198, 198, 834, 9641, 834, 796, 366, 17, 13, 18, 13, 17, 1, 198, 62, 6404, 62, 20500, 796, 366, 42, 452, 88, 30515, 11097, 1343...
2.542553
94
from .user import *
[ 6738, 764, 7220, 1330, 1635, 220 ]
3.333333
6
import tornado.web import os import sys import pathlib from baselayer.app.config import Config from . import models from baselayer.app import model_util # This provides `login`, `complete`, and `disconnect` endpoints from social_tornado.routes import SOCIAL_AUTH_ROUTES from .handlers import ( ProjectHandler, DatasetHandler, FeatureHandler, PrecomputedFeaturesHandler, ModelHandler, PredictionHandler, FeatureListHandler, SklearnModelsHandler, PlotFeaturesHandler, PredictRawDataHandler ) def make_app(cfg, baselayer_handlers, baselayer_settings): """Create and return a `tornado.web.Application` object with specified handlers and settings. Parameters ---------- cfg : Config Loaded configuration. Can be specified with '--config' (multiple uses allowed). baselayer_handlers : list Tornado handlers needed for baselayer to function. baselayer_settings : cfg Settings needed for baselayer to function. """ if baselayer_settings['cookie_secret'] == 'abc01234': print('!' * 80) print(' Your server is insecure. Please update the secret string ') print(' in the configuration file!') print('!' * 80) for path_name, path in cfg['paths'].items(): if not os.path.exists(path): print("Creating %s" % path) try: os.makedirs(path) except Exception as e: print(e) handlers = baselayer_handlers + [ (r'/project(/.*)?', ProjectHandler), (r'/dataset(/.*)?', DatasetHandler), (r'/features(/[0-9]+)?', FeatureHandler), (r'/features/([0-9]+)/(download)', FeatureHandler), (r'/precomputed_features(/.*)?', PrecomputedFeaturesHandler), (r'/models(/[0-9]+)?', ModelHandler), (r'/models/([0-9]+)/(download)', ModelHandler), (r'/predictions(/[0-9]+)?', PredictionHandler), (r'/predictions/([0-9]+)/(download)', PredictionHandler), (r'/predict_raw_data', PredictRawDataHandler), (r'/features_list', FeatureListHandler), (r'/sklearn_models', SklearnModelsHandler), (r'/plot_features/(.*)', PlotFeaturesHandler) ] settings = baselayer_settings # settings.update({}) # Specify additional settings here app = tornado.web.Application(handlers, **settings) models.init_db(**cfg['database']) model_util.create_tables() return app
[ 11748, 33718, 13, 12384, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 3108, 8019, 198, 198, 6738, 1615, 417, 2794, 13, 1324, 13, 11250, 1330, 17056, 198, 6738, 764, 1330, 4981, 198, 6738, 1615, 417, 2794, 13, 1324, 1330, 2746,...
2.546296
972
# # Copyright (c) 2016 Michael Conroy # from elevator.building import ( Building, Floor, DEFAULT_FLOOR_QTY, DEFAULT_ELEVATOR_QTY, ) from elevator.elevator import Elevator
[ 2, 198, 2, 15069, 357, 66, 8, 1584, 3899, 1482, 3287, 198, 2, 628, 198, 6738, 20932, 13, 16894, 1330, 357, 198, 220, 220, 220, 11819, 11, 198, 220, 220, 220, 22343, 11, 198, 220, 220, 220, 5550, 38865, 62, 3697, 46, 1581, 62, 48...
2.533333
75
import tkinter as tk from presentacion.formulario import FormularioPersona try: ventana=tk.Tk() centrar_ventana(ventana) ventana.title("Formulario") form = FormularioPersona(ventana) ventana.mainloop() except Exception as e: print("Existe un error : ", e)
[ 11748, 256, 74, 3849, 355, 256, 74, 198, 6738, 220, 1944, 49443, 13, 687, 934, 952, 1330, 5178, 934, 952, 15439, 64, 198, 198, 28311, 25, 220, 220, 220, 220, 198, 220, 220, 220, 7435, 2271, 28, 30488, 13, 51, 74, 3419, 198, 220, ...
2.02994
167
from django.urls import path from .views import teams_all, team_vote urlpatterns = [ path('teams/all', teams_all, name="teams_all"), path('teams/<int:pk>', team_vote, name="team_vote"), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 33571, 1330, 3466, 62, 439, 11, 1074, 62, 27257, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 660, 4105, 14, 439, 3256, 3466, 62, 439, 11, 1438, ...
2.545455
77
from Dataset import * from Network import * from Functions import * import os from fastai.distributed import * import argparse import torch try: #from apex.parallel import DistributedDataParallel as DDP from apex.fp16_utils import * from apex import amp, optimizers from apex.multi_tensor_apply import multi_tensor_applier except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to run this example.") from tqdm import tqdm opts=get_args() #set up gpu os.environ["CUDA_VISIBLE_DEVICES"] = opts.gpu_id device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') os.system('mkdir models') os.system('mkdir logs') #dice = Dice_th_pred(np.arange(0.2,0.7,0.01)) #datasets and dataloaders dataset = HuBMAPDataset(path=opts.path, fold=opts.fold, nfolds=opts.nfolds, train=True, tfms=get_aug()) val_dataset = HuBMAPDataset(path=opts.path, fold=opts.fold, nfolds=opts.nfolds, train=False) dataloader = DataLoader(dataset, batch_size=opts.batch_size, shuffle=True, num_workers=opts.workers, drop_last=True) val_dataloader = DataLoader(val_dataset, batch_size=opts.batch_size, shuffle=False, num_workers=opts.workers, drop_last=True) #model and optimizer model = UneXt50().cuda() #optimizer = Ranger(model.parameters(), lr=opts.lr, weight_decay=opts.weight_decay) optimizer = torch.optim.Adam(model.parameters(), lr=opts.lr, weight_decay=opts.weight_decay) # scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, pct_start=0.1, div_factor=1e3, # max_lr=1e-3, epochs=opts.epochs, steps_per_epoch=len(dataloader)) criterion=nn.BCEWithLogitsLoss() opt_level = 'O1' model, optimizer = amp.initialize(model, optimizer, opt_level=opt_level) model = nn.DataParallel(model) ####### Transfer learning ####### if opts.transfer == 1: best_model_path = "models_scratch/fold4.pth" state_dict = torch.load(best_model_path) model.load_state_dict(state_dict) #some more things logger=CSVLogger(['epoch','train_loss','val_loss','dice_coef'],f"logs/log_fold{opts.fold}.csv") metric=Dice_soft() best_metric=0 #training scheduler=torch.optim.lr_scheduler.OneCycleLR(optimizer=optimizer, pct_start=0.2, div_factor=1e2, max_lr=1e-4, epochs=opts.epochs, steps_per_epoch=len(dataloader)) for epoch in range(opts.epochs): train_loss=0 model.train(True) for data in tqdm(dataloader): img=data['img'].to(device) mask=data['mask'].to(device) img=cutout(img) output=model(img) loss=criterion(output,mask) with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1) #if step%opts.gradient_accumulation_steps==0: optimizer.step() scheduler.step() optimizer.zero_grad() train_loss+=loss.item() #break train_loss/=len(dataloader) print(f"### validating for epoch {epoch} ###") val_loss=0 model.eval() metric.reset() with torch.no_grad(): for data in tqdm(val_dataloader): if img.shape[0]%2!=0: img=img[:-1] mask=mask[:-1] img=data['img'].to(device) mask=data['mask'].to(device) shape=img.shape output=model(img)[:,:,opts.expansion//2:-opts.expansion//2,opts.expansion//2:-opts.expansion//2] output[output != output] = 0 mask=mask[:,:,opts.expansion//2:-opts.expansion//2,opts.expansion//2:-opts.expansion//2] metric.accumulate(output.detach(), mask) loss=criterion(output,mask) val_loss+=loss.item() val_loss/=len(val_dataloader) metric_this_epoch=metric.value # metric_this_epoch=val_loss logger.log([epoch+1,train_loss,val_loss,metric_this_epoch]) if metric_this_epoch>best_metric: torch.save(model.state_dict(),f'models/fold{opts.fold}.pth') best_metric=metric_this_epoch
[ 6738, 16092, 292, 316, 1330, 1635, 198, 6738, 7311, 1330, 1635, 198, 6738, 40480, 1330, 1635, 198, 11748, 28686, 198, 6738, 3049, 1872, 13, 17080, 6169, 1330, 1635, 198, 11748, 1822, 29572, 198, 11748, 28034, 198, 28311, 25, 198, 220, 2...
2.233817
1,792
""" NODE model definition and experiment setup. Neural Oblivious Decision Ensembles for Deep Learning on Tabular Data https://arxiv.org/abs/1909.06312 Model details: https://pytorch-tabular.readthedocs.io/en/latest/models/#nodemodel """ import logging import os.path import shutil from sklearn.metrics import classification_report from omegaconf import OmegaConf import optuna from optuna.samplers import TPESampler from pytorch_tabular import TabularModel from pytorch_tabular.models import NodeConfig from pytorch_tabular.config import ( DataConfig, OptimizerConfig, TrainerConfig, ExperimentConfig) from pytorch_tabular.utils import get_class_weighted_cross_entropy from optuna_utils import OptunaExperiments, run_experiments LOGGER = logging.getLogger(__name__) LABEL_COL = "retweet_label" # updated by train.py before running config = OmegaConf.create( {"max_epochs": 50, "lr_exp_min": -4, "lr_exp_max": -3, "alpha_exp_min": -4, "alpha_exp_max": -3, "batch_exp_min": 7, "batch_exp_max": 8, "num_trees_min": 512, "num_trees_max": 2560, "num_trees_step": 512, "depth_min": 4, "depth_max": 6, "categorical_cols": [ "entities.urls", "entities.media", "user_in_net", "has_covid_keyword", "user.followers_isna", "users_mention_isna", "following_users_isna", "users_reply_isna"], "exp_log_freq": 100, "seed": 1, "num_workers": 24, "embed_categorical": True} )
[ 37811, 198, 45, 16820, 2746, 6770, 290, 6306, 9058, 13, 198, 198, 8199, 1523, 1835, 35260, 26423, 2039, 4428, 829, 329, 10766, 18252, 319, 16904, 934, 6060, 198, 5450, 1378, 283, 87, 452, 13, 2398, 14, 8937, 14, 1129, 2931, 13, 3312, ...
2.449918
609
from django.db import models from django.core.urlresolvers import reverse from djnfusion import server, key from django.conf import settings from jsonfield import JSONField # TODO: change to this. Currently doesnt work. may have something to do with # the server not in __init__ # from packages.providers.infusionsoft import server, key from .managers import InfusionsoftTagManager, PackagePurchaseManager from packages.managers import PackageManager
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 6738, 42625, 77, 69, 4241, 1330, 4382, 11, 1994, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 33...
3.889831
118
import numpy as np import matplotlib.pyplot as plt from tqdm import trange def get_result(e): bandits = [bandit(np.random.randn(),CFG.variance) for i in range(CFG.n)] res = [] global cnt for _ in range(CFG.t): if (np.random.random()<e): choose = np.random.choice(CFG.n) else: choose = np.argmax([ban.mean for ban in bandits]) val = bandits[choose].get_reward() res.append(val) bandits[choose].update(val) # print(res) return res plt.figure(figsize=(20, 10)) for e in CFG.esp: res = np.zeros(CFG.t) for tr in trange(CFG.n_try): res += get_result(e) print(res.shape) res /= CFG.n_try # print(res) plt.plot(res, label = e) print(f'done {e}') plt.xlabel('step') plt.ylabel('average reward') plt.legend() plt.savefig('figure_2_1.png') plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 256, 80, 36020, 1330, 491, 858, 628, 220, 220, 220, 220, 198, 198, 4299, 651, 62, 20274, 7, 68, 2599, 198, 220, 220, 220, 44149,...
2.009029
443
# -*- coding: utf-8 -*- import io import os from setuptools import setup, find_packages # Package metadata # ---------------- SHORT_NAME = 'databricks_client' NAME = 'jetavator_databricks_client' DESCRIPTION = ( 'Databricks support for the Jetavator engine ' 'to be installed on the client system' ) URL = 'https://github.com/jetavator/jetavator' EMAIL = 'joetaylorconsulting@gmail.com' AUTHOR = 'Joe Taylor' REQUIRES_PYTHON = '>=3.7.0' VERSION = None # What packages are required for this module to be executed? REQUIRED = [ 'jetavator>=0.1.5', 'lazy-property>=0.0.1,<1', 'databricks-cli>=0.14.1,<0.15', 'nbformat>=5.0.8>,<6', 'azure-storage-queue>=12.1.5,<13', 'azure-storage-blob>=12.7.1,<13' ] # What packages are optional? EXTRAS = { # 'some-feature': ['requirement'], } # Package setup # ------------- # Import the README and use it as the long description here = os.path.abspath(os.path.dirname(__file__)) try: with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = '\n' + f.read() except FileNotFoundError: long_description = DESCRIPTION # Import the LICENSE with open(os.path.join(here, 'LICENSE')) as f: license_text = f.read() # Load the package's __version__.py module as a dictionary about = {} if not VERSION: with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) else: about['__version__'] = VERSION setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(exclude=('tests', 'docs')), install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license=license_text, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7' ], entry_points={'jetavator.plugins': f'{SHORT_NAME} = {NAME}'} )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 33245, 198, 11748, 28686, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 2, 15717, 20150, 198, 2, 34400, 198, 198, 9693, 9863,...
2.45283
848
from dataclasses import dataclass from .base import _MiscOptionBase from application.src.misc.sampling import PurposesOfSampling
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 764, 8692, 1330, 4808, 44, 2304, 19722, 14881, 198, 6738, 3586, 13, 10677, 13, 44374, 13, 37687, 11347, 1330, 9330, 4832, 5189, 16305, 11347, 628, 198 ]
3.638889
36
import sdp.scripts.load_nstx_exp_ref as nstx_exp #import sdp.scripts.FWR2D_NSTX_139047_Postprocess as fwrpp import pickle import numpy as np with open('/p/gkp/lshi/XGC1_NSTX_Case/FullF_XGC_ti191_output/ref_pos.pck','r') as f: ref_pos = pickle.load(f) channel = 9 nt = 50 llim = 1e-7 ulim = 1e-4 time_array = np.linspace(llim,ulim,nt) cs_mean = np.zeros((nt)) cs_median = np.zeros((nt)) cs_std = np.zeros((nt))
[ 11748, 264, 26059, 13, 46521, 13, 2220, 62, 77, 301, 87, 62, 11201, 62, 5420, 355, 299, 301, 87, 62, 11201, 198, 2, 11748, 264, 26059, 13, 46521, 13, 37, 18564, 17, 35, 62, 45, 2257, 55, 62, 1485, 3829, 2857, 62, 6307, 14681, 35...
2.038462
208
# -*- coding: utf-8 -*- # # Copyright 2017-2020 AVSystem <avsystem@avsystem.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from framework.lwm2m_test import *
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 2177, 12, 42334, 14661, 11964, 1279, 615, 10057, 31, 615, 10057, 13, 785, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15...
3.531915
188
import sys, os import numpy as np import scarlet import sep from astropy.io import ascii import astropy.io.fits as fits import matplotlib import matplotlib.pyplot as plt from matplotlib.patches import Ellipse from astropy.wcs import WCS def write_scarlet_results(datas, observation, starlet_sources, model_frame, catalog_deblended, segmentation_masks, dirpath, filters, s): """ Saves images in each channel, with headers for each source in image, such that the number of headers = number of sources detected in image. Parameters ---------- datas: array array of Data objects observation: scarlet function Scarlet observation objects starlet_sources: list List of ScarletSource objects model_frame: scarlet function Image frame of source model catalog_deblended: list Deblended source detection catalog segmentation_masks: list List of segmentation mask of each object in image dirpath : str Path to HSC image file directory filters : list A list of filters for your images. Default is ['g', 'r', 'i']. s : str File basename string Returns ------- filename : dict dictionary of all paths to the saved scarlet files for the particular dataset. Saved image and model files for each filter, and one total segmentation mask file for all filters. """ def _make_hdr(starlet_source, cat): """ Helper function to make FITS header and insert metadata. Parameters ---------- starlet_source: starlet_source starlet_source object for source k cat: dict catalog data for source k Returns ------- model_hdr : Astropy fits.Header FITS header for source k with catalog metadata """ # For each header, assign descriptive data about each source # (x0, y0, w, h) in absolute floating pixel coordinates bbox_h = starlet_source.bbox.shape[1] bbox_w = starlet_source.bbox.shape[2] bbox_y = starlet_source.bbox.origin[1] + int(np.floor(bbox_w/2)) # y-coord of the source's center bbox_x = starlet_source.bbox.origin[2] + int(np.floor(bbox_w/2)) # x-coord of the source's center # Ellipse parameters (a, b, theta) from deblend catalog e_a, e_b, e_theta = cat['a'], cat['b'], cat['theta'] ell_parm = np.concatenate((cat['a'], cat['b'], cat['theta'])) # Add info to header model_hdr = fits.Header() model_hdr['bbox'] = ','.join(map(str, [bbox_x, bbox_y, bbox_w, bbox_h])) model_hdr['area'] = bbox_w * bbox_h model_hdr['ell_parm'] = ','.join(map(str, list(ell_parm))) model_hdr['cat_id'] = 1 # Category ID #TODO: set categor_id based on if the source is extended or not return model_hdr # Create dict for all saved filenames segmask_hdul = [] model_hdul = [] filenames = {} # Filter loop for i, f in enumerate(filters): # datas is HSC data array with dimensions [filters, N, N] f = f.upper() # Primary HDU is full image img_hdu = fits.PrimaryHDU(data=datas[i]) # Create header entry for each scarlet source for k, (src, cat) in enumerate(zip(starlet_sources, catalog_deblended)): # Get each model, make into image model = starlet_sources[k].get_model(frame=model_frame) model = observation.render(model) model = src.bbox.extract_from(model) model_hdr = _make_hdr(starlet_sources[k], cat) model_hdu = fits.ImageHDU(data=model[i], header=model_hdr) model_primary = fits.PrimaryHDU() model_hdul.append(model_hdu) # Write final fits file to specified location # Save full image and then headers per source w/ descriptive info save_img_hdul = fits.HDUList([img_hdu]) save_model_hdul = fits.HDUList([model_primary, *model_hdul]) # Save list of filenames in dict for each band filenames[f'img_{f}'] = os.path.join(dirpath, f'{f}-{s}_scarlet_img.fits') save_img_hdul.writeto(filenames[f'img_{f}'], overwrite=True) filenames[f'model_{f}'] = os.path.join(dirpath, f'{f}-{s}_scarlet_model.fits') save_model_hdul.writeto(filenames[f'model_{f}'], overwrite=True) # If we have segmentation mask data, save them as a separate fits file if segmentation_masks is not None: # Create header entry for each scarlet source for k, (src, cat) in enumerate(zip(starlet_sources, catalog_deblended)): segmask_hdr = _make_hdr(starlet_sources[k], cat) # Save each model source k in the image segmask_hdu = fits.ImageHDU(data=segmentation_masks[k], header=segmask_hdr) segmask_primary = fits.PrimaryHDU() segmask_hdul.append(segmask_hdu) save_segmask_hdul = fits.HDUList([segmask_primary, *segmask_hdul]) # Save list of filenames in dict for each band filenames['segmask'] = os.path.join(dirpath, f'{f}-{s}_scarlet_segmask.fits') save_segmask_hdul.writeto(filenames['segmask'], overwrite=True) return filenames def plot_stretch_Q(datas, stretches=[0.01,0.1,0.5,1], Qs=[1,10,5,100]): """ Plots different normalizations of your image using the stretch, Q parameters. Parameters ---------- stretches : array List of stretch params you want to permutate through to find optimal image normalization. Default is [0.01, 0.1, 0.5, 1] Qs : array List of Q params you want to permutate through to find optimal image normalization. Default is [1, 10, 5, 100] Code adapted from: https://pmelchior.github.io/scarlet/tutorials/display.html Returns ------- fig : Figure object """ fig, ax = plt.subplots(len(stretches), len(Qs), figsize=(9,9)) for i, stretch in enumerate(stretches): for j, Q in enumerate(Qs): asinh = scarlet.display.AsinhMapping(minimum=0, stretch=stretch, Q=Q) # Scale the RGB channels for the image img_rgb = scarlet.display.img_to_rgb(datas, norm=asinh) ax[i][j].imshow(img_rgb) ax[i][j].set_title("Stretch {}, Q {}".format(stretch, Q)) ax[i][j].axis('off') return fig def make_catalog(datas, lvl=4, wave=True, segmentation_map=False, maskthresh=10.0, object_limit=100000): """ Creates a detection catalog by combining low and high resolution data Parameters ---------- datas: array array of Data objects lvl: int detection lvl wave: Bool set to True to use wavelet decomposition of images before combination subtract_background : Bool if you want to subtract the background and retrieve an estimate, change to True. But default is False because HSC images are already background subtracted. segmentation_map : Bool Whether to run sep segmentation map maskthresh : float Mask threshold for sep segmentation object_limit : int Limit on number of objects to detect in image Code adapted from https://pmelchior.github.io/scarlet/tutorials/wavelet_model.html Returns ------- catalog: sextractor catalog catalog of detected sources (use 'catalog.dtype.names' for info) bg_rms: array background level for each data set (set to None if subtract_background is False) """ if type(datas) is np.ndarray: hr_images = datas / np.sum(datas, axis=(1, 2))[:, None, None] # Detection image as the sum over all images detect_image = np.sum(hr_images, axis=0) else: data_lr, data_hr = datas # Create observations for each image # Interpolate low resolution to high resolution interp = interpolate(data_lr, data_hr) # Normalization of the interpolate low res images interp = interp / np.sum(interp, axis=(1, 2))[:, None, None] # Normalisation of the high res data hr_images = data_hr.images / np.sum(data_hr.images, axis=(1, 2))[:, None, None] # Detection image as the sum over all images detect_image = np.sum(interp, axis=0) + np.sum(hr_images, axis=0) detect_image *= np.sum(data_hr.images) if np.size(detect_image.shape) == 4: if wave: # Wavelet detection in the first three levels wave_detect = scarlet.Starlet(detect_image.mean(axis=0), lvl=5).coefficients wave_detect[:, -1, :, :] = 0 detect = scarlet.Starlet(coefficients=wave_detect).image else: # Direct detection detect = detect_image.mean(axis=0) else: if wave: wave_detect = scarlet.Starlet(detect_image).coefficients detect = wave_detect[0][0] + wave_detect[0][1] + wave_detect[0][2] else: detect = detect_image bkg = sep.Background(detect) # Set the limit on the number of sub-objects when deblending. sep.set_sub_object_limit(object_limit) # Extract detection catalog with segmentation maps! # Can use this to retrieve ellipse params catalog = sep.extract(detect, lvl, err=bkg.globalrms, segmentation_map=segmentation_map, maskthresh=maskthresh) # Estimate background if type(datas) is np.ndarray: bkg_rms = scarlet.wavelet.mad_wavelet(datas) else: bkg_rms = [] for data in datas: bkg_rms.append(scarlet.wavelet.mad_wavelet(data.images)) return catalog, bkg_rms def fit_scarlet_blend(starlet_sources, observation, max_iters=15, e_rel=1e-4, plot_likelihood=True): """ Creates a detection catalog by combining low and high resolution data Parameters ---------- datas: array array of Data objects Will end early if likelihood and constraints converge Returns ------- """ # Create and fit Blend model. Go for 200 iterations, # but will end early if likelihood and constraints converge print(f"Fitting Blend model.") try: starlet_blend = scarlet.Blend(starlet_sources, observation) it, logL = starlet_blend.fit(max_iters, e_rel=e_rel) print(f"Scarlet ran for {it} iterations to logL = {logL}") # Catch any exceptions like no detections except AssertionError as e1: print(f"Length of detection catalog is {len(catalog)}.") if plot_likelihood == True: scarlet.display.show_likelihood(starlet_blend) plt.show() return starlet_blend, logL def _plot_wavelet(datas): """ Helper function to plot wavelet transformation diagnostic figures with scarlet Parameters ---------- datas: array array of Data objects Returns ------- """ # Declare a starlet object (and performs the transform) Sw = scarlet.Starlet(datas, lvl=5, direct=True) # This is the starlet transform as an array w = Sw.coefficients # The inverse starlet transform of w (new object otherwise, the tranform is not used) iw = Sw.image # TODO: Clean this code up using plt.subplots() # The wavelet transform of the first slice of images in pictures lvl = w.shape[1] plt.figure(figsize=(lvl*5+5,5)) plt.suptitle('Wavelet coefficients') for i in range(lvl): plt.subplot(1, lvl, i+1) plt.title('scale' + str(i+1)) plt.imshow(w[0,i], cmap='inferno') plt.colorbar() plt.show() # Making sure we recover the original image plt.figure(figsize=(30,10)) plt.subplot(131) plt.title('Original image', fontsize=20) plt.imshow(datas[0], cmap='inferno') plt.colorbar() plt.subplot(132) plt.title('Starlet-reconstructed image', fontsize=20) plt.imshow(iw[0], cmap='inferno') plt.colorbar() plt.subplot(133) plt.title('Absolute difference', fontsize=20) plt.imshow((np.abs(iw[0]-datas[0])), cmap='inferno') plt.colorbar() plt.show() return def _plot_scene(starlet_sources, observation, norm, catalog, show_model=True, show_rendered=True, show_observed=True, show_residual=True, add_labels=True, add_boxes=True, add_ellipses=True): """ Helper function to plot scene with scarlet Parameters ---------- starlet_sources: List List of ScarletSource objects observation: Scarlet observation objects norm: Scarlet normalization for plotting catalog: list Source detection catalog show_model: bool Whether to show model show_rendered: bool Whether to show rendered model show_observed: bool Whether to show observed show_residual: bool Whether to show residual add_labels: bool Whether to add labels add_boxes: bool Whether to add bounding boxes to each panel add_ellipses: bool Whether to add ellipses to each panel Returns ------- fig : matplotlib Figure Figure object """ fig = scarlet.display.show_scene(starlet_sources, observation=observation, norm=norm, show_model=show_model, show_rendered=show_rendered, show_observed=show_observed, show_residual=show_residual, add_labels=add_labels, add_boxes=add_boxes) for ax in fig.axes: # Plot sep ellipse around all sources from the detection catalog if add_ellipses == True: for k, src in enumerate(catalog): # See https://sextractor.readthedocs.io/en/latest/Position.html e = Ellipse(xy=(src['x'], src['y']), width=6*src['a'], height=6*src['b'], angle=np.rad2deg(src['theta'])) e.set_facecolor('none') e.set_edgecolor('white') ax.add_artist(e) ax.axis('off') fig.subplots_adjust(wspace=0.01) plt.show() return fig def run_scarlet(datas, filters, stretch=0.1, Q=5, sigma_model=1, sigma_obs=5, subtract_background=False, max_chi2=5000, max_iters=15, morph_thresh=0.1, starlet_thresh=0.1, lvl=5, lvl_segmask=2, maskthresh=0.025, segmentation_map=True, plot_wavelet=False, plot_likelihood=True, plot_scene=False, plot_sources=False, add_ellipses=True, add_labels=False, add_boxes=False): """ Run P. Melchior's scarlet (https://github.com/pmelchior/scarlet) implementation for source separation. This function will create diagnostic plots, a source detection catalog, and fit a model for all sources in the observation scene (image). Parameters ---------- subtract_background : boolean Whether or not to estimate and subtract the background (often background is already subtracted) Detault is False plot_wavelet_transform : boolean Plot starlet wavelet transform and inverse transform at different scales. NOTE: Not really useful at large image sizes (> ~few hundred pixels length/height) Default is False plot_detections : boolean Plot detection catalog results. Default is False plot_likelihood : boolean Plot likelihood as function of iterations from Blend fit function. Default is True plot_full_scene : boolean Plot full scene with the model, rendered model, observation, and residual. Default is False. plot_all_sources : boolean Plot the model, rendered model, observation, and spectrum across channels for each object. WARNING: dumb to do this with a large image with many sources! Default is False plot_first_isolated_comp : boolean Plot the subtracted and isolated first (or any) starlet component. Recommended for finding a bright component. Default is False. Return ------- FITS file with... TODO: fill this out once I get the exact fits file output generated to Colin's liking """ norm = scarlet.display.AsinhMapping(minimum=0, stretch=stretch, Q=Q) # Generate source catalog using wavelets catalog, bg_rms_hsc = make_catalog(datas, lvl, wave=True) # If image is already background subtracted, weights are set to 1 if subtract_background: weights = np.ones_like(datas) / (bg_rms_hsc**2)[:, None, None] else: weights = np.ones_like(datas) print("Source catalog found ", len(catalog), "objects") # Plot wavelet transform at different scales if plot_wavelet == True: _plot_wavelet(datas) # Define model frame and observations: model_psf = scarlet.GaussianPSF(sigma=sigma_model) #, boxsize=100) model_frame = scarlet.Frame(datas.shape, psf=model_psf, channels=filters) observation_psf = scarlet.GaussianPSF(sigma=sigma_obs) observation = scarlet.Observation(datas, psf=observation_psf, weights=weights, channels=filters).match(model_frame) # Initialize starlet sources to be fit. Assume extended sources for all because # we are not looking at all detections in each image # TODO: Plot chi2 vs. binned size and mag. Implement conidition if chi2 > xxx then # add another component until larger sources are modeled well print("Initializing starlet sources to be fit.") # Compute radii and spread of sources Rs = np.sqrt(catalog['a']**2 + catalog['b']**2) spread = Rs/sigma_obs # Array of chi^2 residuals computed after fit on each model chi2s = np.zeros(len(catalog)) # Loop through detections in catalog starlet_sources = [] for k, src in enumerate(catalog): # Is the source compact relative to the PSF? if spread[k] < 1: compact = True else: compact = False # Try modeling each source as a single ExtendedSource first new_source = scarlet.ExtendedSource(model_frame, (src['y'], src['x']), observation, K=1, thresh=morph_thresh, compact=compact) starlet_sources.append(new_source) # Fit scarlet blend starlet_blend, logL = fit_scarlet_blend(starlet_sources, observation, max_iters=max_iters, plot_likelihood=plot_likelihood) print("Computing residuals.") # Compute reduced chi^2 for each rendered sources for k, src in enumerate(starlet_sources): model = src.get_model(frame=model_frame) model = observation.render(model) res = datas - model # Compute in bbox only res = src.bbox.extract_from(res) chi2s[k] = np.sum(res**2) # Replace models with poor fits with StarletSource models if chi2s[k] > max_chi2: starlet_sources[k] = scarlet.StarletSource(model_frame, (catalog["y"][k], catalog["x"][k]), observation, thresh=morph_thresh, starlet_thresh=starlet_thresh, full=False) # If any chi2 residuals are flagged, re-fit the blend with a more complex model if np.any(chi2s > max_chi2): print("Re-fitting with Starlet models for poorly-fit sources.") starlet_blend, logL = fit_scarlet_blend(starlet_sources, observation, max_iters=max_iters, plot_likelihood=plot_likelihood) # Extract the deblended catalog and update the chi2 residuals print('Extracting deblended catalog.') catalog_deblended = [] segmentation_masks = [] for k, src in enumerate(starlet_sources): model = src.get_model(frame=model_frame) model = observation.render(model) # Compute in bbox only model = src.bbox.extract_from(model) # Run sep try: cat, _ = make_catalog(model, lvl_segmask, wave=False, segmentation_map=False, maskthresh=maskthresh) except: print(f'Exception with source {k}') cat = [] #if segmentation_map == True: # cat, mask = cat # If more than 1 source is detected for some reason (e.g. artifacts) if len(cat) > 1: # keep the brightest idx = np.argmax([c['cflux'] for c in cat]) cat = cat[idx] # if segmentation_map == True: # mask = mask[idx] # If failed to detect model source if len(cat) == 0: # Fill with nan cat = [np.full(catalog[0].shape, np.nan, dtype=catalog.dtype)] # Append to full catalog if segmentation_map == True: # For some reason sep doesn't like these images, so do the segmask ourselves for now model_det = np.array(model[0,:,:]) mask = np.zeros_like(model_det) mask[model_det>maskthresh] = 1 segmentation_masks.append(mask) #plt.imshow(mask) #plt.show() catalog_deblended.append(cat) # Combine catalog named array catalog_deblended = np.vstack(catalog_deblended) # Plot scene: rendered model, observations, and residuals if plot_scene == True: _plot_scene(starlet_sources, observation, norm, catalog, show_model=False, show_rendered=True, show_observed=True, show_residual=True, add_labels=add_labels, add_boxes=add_boxes, add_ellipses=add_ellipses) # Plot each for each source if plot_sources == True: scarlet.display.show_sources(starlet_sources, observation, norm=norm, show_rendered=True, show_observed=True, add_boxes=add_boxes) plt.show() return observation, starlet_sources, model_frame, catalog, catalog_deblended, segmentation_masks
[ 11748, 25064, 11, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 10153, 1616, 198, 11748, 41767, 198, 198, 6738, 6468, 28338, 13, 952, 1330, 355, 979, 72, 198, 11748, 6468, 28338, 13, 952, 13, 21013, 355, 11414, 198, 198, ...
2.304231
9,713
from application import bootstrap bootstrap() if __name__=='__main__': import cherrypy cherrypy.engine.signals.subscribe() cherrypy.engine.start() cherrypy.engine.block()
[ 6738, 3586, 1330, 6297, 26418, 198, 198, 18769, 26418, 3419, 198, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 10354, 198, 220, 220, 220, 1330, 23612, 9078, 198, 220, 220, 220, 23612, 9078, 13, 18392, 13, 12683, 874, 13, 7266,...
2.71831
71
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Interface Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.smarttags import typing from abc import abstractmethod from ..lang.x_initialization import XInitialization as XInitialization_d46c0cca if typing.TYPE_CHECKING: from ..frame.x_controller import XController as XController_b00e0b8f from .smart_tag_recognizer_mode import SmartTagRecognizerMode as SmartTagRecognizerMode_9179119e from ..text.x_text_markup import XTextMarkup as XTextMarkup_a5d60b3a from ..text.x_text_range import XTextRange as XTextRange_9a910ab7 __all__ = ['XRangeBasedSmartTagRecognizer']
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 198, 2, 15069, 33160, 1058, 33, 6532, 12, 22405, 12, 12041, 25, 19935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 4943, 198, 2, 345, 743,...
3.281984
383
from rest_framework import status from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from apprest.plugins.icat.helpers.complex_encoder import JsonResponse from apprest.plugins.icat.services.ICAT import ICATService
[ 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 41299, 3299, 1330, 23575, 47649, 3299, 11, 14392, 47649, 3299, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 1148, 47649, 3474, 198, 6738, 1334, 62, 30604, 13, 33571,...
4.023256
86
import unittest from table_tests.utils import BaseTestNoFlushTable from evaluator.hashtable8 import NO_FLUSH_8 if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 3084, 62, 41989, 13, 26791, 1330, 7308, 14402, 2949, 7414, 1530, 10962, 198, 6738, 5418, 84, 1352, 13, 17831, 11487, 23, 1330, 8005, 62, 3697, 27143, 62, 23, 198, 198, 361, 11593, 3672, 834, 6624,...
2.821429
56
#zadanie 1 i=1 j=1 k=1 ciag=[1,1] while len(ciag)<50: k=i+j j=i i=k ciag.append(k) print(ciag) #zadanie 2 wpisane=str(input("Prosz wpisa dowolne sowa po przecinku ")) zmienne=wpisane.split(",") def funkcja(*args): '''Funkcja sprawdza dugo sw i usuwa te, ktre s za krtkie''' lista=[] lista2=[] wartosc = int(input("Prosz wpisa jak warto ")) for arg in args: lista.append(arg) dlugosc=len(arg) if len(arg)>wartosc: lista2.append(arg) procenty=(len(lista2)/len(lista))*100 return procenty,lista,lista2 print(funkcja(zmienne)) #zadanie 3 liczby=list(input("Prosz wpisa liczby po przecinku: ")) unikalna_lista=[] n=1 a=liczby[n] unikalna_lista.append(liczby[0]) while n<len(liczby): if liczby[n]!=unikalna_lista[n-1]: unikalna_lista.append(a) n+=1
[ 2, 89, 29157, 494, 352, 201, 198, 201, 198, 72, 28, 16, 201, 198, 73, 28, 16, 201, 198, 74, 28, 16, 201, 198, 979, 363, 41888, 16, 11, 16, 60, 201, 198, 201, 198, 4514, 18896, 7, 979, 363, 8, 27, 1120, 25, 201, 198, 220, 2...
1.714829
526
from linePathSegment import LinePathSegment from lineSegmentFinder import LineSegmentFinder
[ 6738, 1627, 15235, 41030, 434, 1330, 6910, 15235, 41030, 434, 198, 6738, 1627, 41030, 434, 37, 5540, 1330, 6910, 41030, 434, 37, 5540 ]
3.956522
23
from helpers import inputs
[ 6738, 49385, 1330, 17311, 628 ]
5.6
5
from unicon.eal.dialogs import Statement from .service_patterns import NxosN5kReloadPatterns from unicon.plugins.nxos.service_statements import (login_stmt, password_stmt, enable_vdc, admin_password) from unicon.plugins.generic.service_statements import (save_env, auto_provision, auto_install_dialog, setup_dialog, confirm_reset, press_enter, confirm_config, module_reload, save_module_cfg, secure_passwd_std, ) # for nxos n5k single rp reload pat = NxosN5kReloadPatterns() reload_confirm_nxos = Statement(pattern=pat.reload_confirm_nxos, action='sendline(y)', loop_continue=True, continue_timer=False) # reload statement list for nxos n5k single-rp nxos_reload_statement_list = [save_env, confirm_reset, reload_confirm_nxos, press_enter, login_stmt, password_stmt, confirm_config, setup_dialog, auto_install_dialog, module_reload, save_module_cfg, secure_passwd_std, admin_password, auto_provision, enable_vdc]
[ 6738, 555, 4749, 13, 2287, 13, 38969, 18463, 1330, 21983, 198, 6738, 764, 15271, 62, 33279, 82, 1330, 399, 87, 418, 45, 20, 74, 6892, 1170, 47546, 82, 198, 198, 6738, 555, 4749, 13, 37390, 13, 77, 87, 418, 13, 15271, 62, 14269, 31...
2.025685
584
#!/usr/bin/env python3 from clic import nodes import time import os import logging as loggingmod logging = loggingmod.getLogger('cloud') logging.setLevel(loggingmod.WARNING) def main(): import argparse parser = argparse.ArgumentParser(description='Execute cloud API commands') from clic import version parser.add_argument('-v', '--version', action='version', version=version.__version__) image = parser.add_argument_group() image.add_argument('--image', metavar='NAME', nargs=1, help='Create an image from NAME') image.add_argument('--recreate', action='store_true', help='Recreate NAME after creating an image') args = parser.parse_args() if args.image: getCloud().makeImage(args.image[0], args.recreate)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 537, 291, 1330, 13760, 198, 11748, 640, 198, 11748, 28686, 198, 11748, 18931, 355, 18931, 4666, 198, 6404, 2667, 796, 18931, 4666, 13, 1136, 11187, 1362, 10786, 17721, 11537, 1...
3.028112
249
import numpy as np import pandas as pd import ipywidgets as widgets import matplotlib.pyplot as plt from skimage.measure import label, regionprops, regionprops_table from skimage.color import label2rgb def Wav_2_Im(im, wn): ''' Input a 3-D datacube and outputs a normalized slice at one wavenumber. Parameters ---------- im : array-like image. Input data. wn : integer. Integer index value. Returns ---------- slice : ndarray. An image the same size as the input, but with one slice in wavenumber space. ''' normalized = [] # storage for each normalized slice img_norm = np.empty(im.shape, dtype=np.float32) for i in np.linspace(0, im.shape[2]-1, im.shape[2]-1).astype(np.int): image = im[:,:,i] normalized.append((image - np.min(image))/(np.amax(image) - np.min(image))) for i in np.linspace(0, im.shape[2]-1, im.shape[2]-1).astype(np.int): img_norm[:,:,i] = normalized[i-1] im_slice = img_norm[:,:,wn-750] return im_slice def AreaFraction(im, norm_im, image_size): ''' Input test image, normalized NMF coefficients image, and image size. Outputs a dictionary of computed properties for regions of interest, a multidimensional array containing threshold masks, and a list of computed area fractions for the areas of interest in each threshold mask. Parameters ---------- im : array-like image. Image slice to measure. norm_im : multidimensional array-like image Image of normalized NMF coefficients. image_size : integer. Size of the image. Returns --------- regions : dict. Dictionary of regions of interest and their computed properties. mask : multidimensional array-like image. Multidimensional array with each threshold mask image. area_frac : list. List of computed area fractions of DPPDTT. ''' # Set up threshold masks percents = np.round(np.arange(0.5, 1.0, 0.05),2) # array of thresholds mask = np.zeros((norm_im.shape[0], norm_im.shape[1], 10)) # ten tested thresholds for h in range(mask.shape[2]): for i in range(mask.shape[0]): for j in range(mask.shape[1]): if norm_im[i][j] >= percents[h]: mask[i][j][h] = 1 else: mask[i][j][h] = 0 # Compute region properties of labeled images regions = {} props = ('area', 'major_axis_length', 'minor_axis_length', 'mean_intensity') for i in range(mask.shape[2]): labels = label(mask[:,:,i]) regions[i] = pd.DataFrame(regionprops_table(labels, im, props)) # Compute the area fractions area_frac = [] for i in range(len(regions.keys())): area_frac.append(regions[i]['area'].values / image_size**2) return regions, mask, area_frac def interactive_hyperimage(image, w=(750,1877,1)): ''' input: image: 3D Hyperspectral image w: wavenumbers, which is desired interval format is (starting wavenumber, ending wavenumber, step). Default is full spectrum, which is (750,1128,1) output: interactive 2D image of hyperspectral image at desired wavenumber ''' return widgets.interact(update, a=w)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 20966, 88, 28029, 11407, 355, 40803, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 1341, 9060, 13, 1326, 5015, 1330, 6167, ...
2.835849
1,060
import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline as interpolate from scipy.misc import derivative import inspect def loginterp(x, y, yint = None, side = "both", lorder = 9, rorder = 9, lp = 1, rp = -2, ldx = 1e-6, rdx = 1e-6,\ interp_min = -12, interp_max = 12, Nint = 10**5, verbose=False, option='B'): ''' Extrapolate function by evaluating a log-index of left & right side. From Chirag Modi's CLEFT code at https://github.com/modichirag/CLEFT/blob/master/qfuncpool.py The warning for divergent power laws on both ends is turned off. To turn back on uncomment lines 26-33. ''' if yint is None: yint = interpolate(x, y, k = 5) if side == "both": side = "lr" # Make sure there is no zero crossing between the edge points # If so assume there can't be another crossing nearby if np.sign(y[lp]) == np.sign(y[lp-1]) and np.sign(y[lp]) == np.sign(y[lp+1]): l = lp else: l = lp + 2 if np.sign(y[rp]) == np.sign(y[rp-1]) and np.sign(y[rp]) == np.sign(y[rp+1]): r = rp else: r = rp - 2 lneff = derivative(yint, x[l], dx = x[l]*ldx, order = lorder)*x[l]/y[l] rneff = derivative(yint, x[r], dx = x[r]*rdx, order = rorder)*x[r]/y[r] #print(lneff, rneff) # uncomment if you like warnings. #if verbose: # if lneff < 0: # print( 'In function - ', inspect.getouterframes( inspect.currentframe() )[2][3]) # print('WARNING: Runaway index on left side, bad interpolation. Left index = %0.3e at %0.3e'%(lneff, x[l])) # if rneff > 0: # print( 'In function - ', inspect.getouterframes( inspect.currentframe() )[2][3]) # print('WARNING: Runaway index on right side, bad interpolation. Reft index = %0.3e at %0.3e'%(rneff, x[r])) if option == 'A': xl = np.logspace(interp_min, np.log10(x[l]), Nint) xr = np.logspace(np.log10(x[r]), interp_max, Nint) yl = y[l]*(xl/x[l])**lneff yr = y[r]*(xr/x[r])**rneff #print(xr/x[r]) xint = x[l+1:r].copy() yint = y[l+1:r].copy() if side.find("l") > -1: xint = np.concatenate((xl, xint)) yint = np.concatenate((yl, yint)) if side.find("r") > -1: xint = np.concatenate((xint, xr)) yint = np.concatenate((yint, yr)) yint2 = interpolate(xint, yint, k = 5, ext=3) else: yint2 = lambda xx: (xx <= x[l]) * y[l]*(xx/x[l])**lneff \ + (xx >= x[r]) * y[r]*(xx/x[r])**rneff \ + (xx > x[l]) * (xx < x[r]) * interpolate(x, y, k = 5, ext=3)(xx) return yint2
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 3849, 16104, 378, 1330, 4225, 16104, 515, 3118, 42524, 26568, 500, 355, 39555, 378, 198, 6738, 629, 541, 88, 13, 44374, 1330, 27255, 198, 11748, 10104, 198, 198, 4299, 2604, ...
1.939522
1,422
from typing import Tuple import dataclasses import numpy as np import torch from pathlib import Path from l5kit.data import LocalDataManager, ChunkedDataset import sys import os from tqdm import tqdm sys.path.append(os.pardir) sys.path.append(os.path.join(os.pardir, os.pardir)) from lib.evaluation.mask import load_mask_chopped from lib.rasterization.rasterizer_builder import build_custom_rasterizer from lib.dataset.faster_agent_dataset import FasterAgentDataset from lib.utils.yaml_utils import save_yaml, load_yaml from modeling.load_flag import load_flags, Flags if __name__ == '__main__': mode = "" flags: Flags = load_flags(mode=mode) flags_dict = dataclasses.asdict(flags) cfg = load_yaml(flags.cfg_filepath) out_dir = Path(flags.out_dir) print(f"cfg {cfg}") os.makedirs(str(out_dir), exist_ok=True) print(f"flags: {flags_dict}") save_yaml(out_dir / 'flags.yaml', flags_dict) save_yaml(out_dir / 'cfg.yaml', cfg) debug = flags.debug # set env variable for data os.environ["L5KIT_DATA_FOLDER"] = flags.l5kit_data_folder dm = LocalDataManager(None) print("init dataset") train_cfg = cfg["train_data_loader"] valid_cfg = cfg["valid_data_loader"] # Build StubRasterizer for fast dataset access cfg["raster_params"]["map_type"] = "stub_debug" rasterizer = build_custom_rasterizer(cfg, dm) print("rasterizer", rasterizer) train_path = "scenes/sample.zarr" if debug else train_cfg["key"] train_agents_mask = None if flags.validation_chopped: # Use chopped dataset to calc statistics... num_frames_to_chop = 100 th_agent_prob = cfg["raster_params"]["filter_agents_threshold"] min_frame_future = 1 num_frames_to_copy = num_frames_to_chop train_agents_mask = load_mask_chopped( dm.require(train_path), th_agent_prob, num_frames_to_copy, min_frame_future) print("train_path", train_path, "train_agents_mask", train_agents_mask.shape) train_zarr = ChunkedDataset(dm.require(train_path)).open(cached=False) print("train_zarr", type(train_zarr)) print(f"Open Dataset {flags.pred_mode}...") train_agent_dataset = FasterAgentDataset( cfg, train_zarr, rasterizer, min_frame_history=flags.min_frame_history, min_frame_future=flags.min_frame_future, agents_mask=train_agents_mask ) print("train_agent_dataset", len(train_agent_dataset)) n_sample = 1_000_000 # Take 1M sample. target_scale_abs_mean, target_scale_abs_max, target_scale_std = calc_target_scale(train_agent_dataset, n_sample) chopped_str = "_chopped" if flags.validation_chopped else "" agent_prob = cfg["raster_params"]["filter_agents_threshold"] filename = f"target_scale_abs_mean_{agent_prob}_{flags.min_frame_history}_{flags.min_frame_future}{chopped_str}.npz" cache_path = Path(train_zarr.path) / filename np.savez_compressed(cache_path, target_scale=target_scale_abs_mean) print("Saving to ", cache_path) filename = f"target_scale_abs_max_{agent_prob}_{flags.min_frame_history}_{flags.min_frame_future}{chopped_str}.npz" cache_path = Path(train_zarr.path) / filename np.savez_compressed(cache_path, target_scale=target_scale_abs_max) print("Saving to ", cache_path) filename = f"target_scale_std_{agent_prob}_{flags.min_frame_history}_{flags.min_frame_future}{chopped_str}.npz" cache_path = Path(train_zarr.path) / filename np.savez_compressed(cache_path, target_scale=target_scale_std) print("Saving to ", cache_path) print("target_scale_abs_mean", target_scale_abs_mean) print("target_scale_abs_max", target_scale_abs_max) print("target_scale_std", target_scale_std) import IPython; IPython.embed()
[ 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 4818, 330, 28958, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 300, 20, 15813, 13, 7890, 1330, 10714, 6601, 13511, 11, 609, 29...
2.52381
1,491
import numpy as np import scipy as sp import scipy.sparse import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.path plt.ion() import pybie2d """o solve an interior Modified Helmholtz problem On a complicated domain using a global quadr Demonstrate how to use the pybie2d package tature This example demonstrates how to do this entirely using low-level routines, To demonstrate both how to use these low level routines And to give you an idea what is going on under the hood in the higher level routines """ NG = 1000 h_max = 0.01 # extract some functions for easy calling squish = pybie2d.misc.curve_descriptions.squished_circle PPB = pybie2d.boundaries.panel_polygon_boundary.panel_polygon_boundary.Panel_Polygon_Boundary Grid = pybie2d.grid.Grid PointSet = pybie2d.point_set.PointSet Laplace_Layer_Form = pybie2d.kernels.high_level.laplace.Laplace_Layer_Form Laplace_Layer_Singular_Form = pybie2d.kernels.high_level.laplace.Laplace_Layer_Singular_Form Laplace_Layer_Apply = pybie2d.kernels.high_level.laplace.Laplace_Layer_Apply ################################################################################ # define problem # boundary boundary = PPB([0,1,1,0], [0,0,1,1], [h_max]*4, [True]*4, dyadic_levels=20, dyadic_base=3) # solution solution_func = lambda x, y: 2*x + y bc = solution_func(boundary.x, boundary.y) bcx = lambda x, y: 2.0*np.ones_like(x) bcy = lambda x, y: 1.0*np.ones_like(x) bcn = lambda x, y, nx, ny: bcx(x, y)*nx + bcy(x, y)*ny ################################################################################ ##### solve problem the hard way ############################################### ################################################################################ ################################################################################ # find physical region # (this implements a fast way to tell if points are in or out of the boundary) # (and of course, for the squish boundary, we could easily figure out something # faster, but this illustrates a general purpose routine) gridp = Grid([0,1], NG, [0,1], NG, x_endpoints=[False,False], y_endpoints=[False,False]) ################################################################################ # solve for the density DLP = Laplace_Layer_Singular_Form(boundary, ifdipole=True) SLPp = (DLP/boundary.weights).T*boundary.weights A = 0.5*np.eye(boundary.N) + SLPp tau = np.linalg.solve(A, bcn(boundary.x, boundary.y, boundary.normal_x, boundary.normal_y)) # fix the mean target = PointSet(x=np.array((0.5)),y=np.array((0.5))) good_eval = Laplace_Layer_Apply(boundary, target=target, charge=tau) correction = (2*0.5 + 0.5) - good_eval ################################################################################ # naive evaluation u = Laplace_Layer_Apply(boundary, gridp, charge=tau) u = gridp.reshape(u) u += correction err_plot(u) ################################################################################ # oversampled hmax = gridp.xg[1,0] - gridp.xg[0,0] fbdy, IMAT = boundary.prepare_oversampling(hmax/6.0) IMAT = sp.sparse.csr_matrix(IMAT) ftau = IMAT.dot(tau) u = Laplace_Layer_Apply(fbdy, gridp, charge=ftau) u = gridp.reshape(u) u += correction err_plot(u) ua = 2*gridp.xg + gridp.yg
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 355, 599, 198, 11748, 629, 541, 88, 13, 82, 29572, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, ...
3.127413
1,036
from math import ceil from referee.consts import MATCH_TIME, TIME_STEP from referee.referee import RCJSoccerReferee referee = RCJSoccerReferee( match_time=MATCH_TIME, progress_check_steps=ceil(15/(TIME_STEP/1000.0)), progress_check_threshold=0.5, ball_progress_check_steps=ceil(10/(TIME_STEP/1000.0)), ball_progress_check_threshold=0.5, ) while referee.step(TIME_STEP) != -1: referee.emit_positions() if not referee.tick(): break # When end of match, pause simulator immediately referee.simulationSetMode(referee.SIMULATION_MODE_PAUSE)
[ 6738, 10688, 1330, 2906, 346, 198, 6738, 22957, 13, 1102, 6448, 1330, 337, 11417, 62, 34694, 11, 20460, 62, 42135, 198, 6738, 22957, 13, 5420, 45316, 1330, 13987, 20120, 420, 2189, 8134, 45316, 198, 198, 5420, 45316, 796, 13987, 20120, ...
2.630137
219
from flask import Flask, request import os from subprocess import Popen, PIPE import json from prof_file_util import load_source, load_line_profile, load_graph_profile from linewise_barchart import linewise_barchart from valgrind import extract_valgrind_result from mem_issue_visualize import mem_issue_visualize app = Flask(__name__)
[ 6738, 42903, 1330, 46947, 11, 2581, 198, 11748, 28686, 198, 6738, 850, 14681, 1330, 8099, 268, 11, 350, 4061, 36, 198, 11748, 33918, 198, 198, 6738, 1534, 62, 7753, 62, 22602, 1330, 3440, 62, 10459, 11, 3440, 62, 1370, 62, 13317, 11, ...
3.175926
108
''' Leetcode problem No 862 Shortest Subarray with Sum at Least K Solution written by Xuqiang Fang on 1 July, 2018 ''' import collections main()
[ 7061, 6, 198, 3123, 316, 8189, 1917, 1400, 807, 5237, 10073, 395, 3834, 18747, 351, 5060, 379, 1004, 459, 509, 198, 46344, 3194, 416, 33591, 80, 15483, 24468, 319, 352, 2901, 11, 2864, 198, 7061, 6, 198, 11748, 17268, 198, 12417, 3419...
3.372093
43
import time from ckeditor.fields import RichTextField from django.db import models from django.utils.translation import ugettext_lazy as _ from requests import ConnectionError from djangocms_baseplugins.baseplugin.models import AbstractBasePlugin from djangocms_baseplugins.baseplugin.utils import check_migration_modules_needed check_migration_modules_needed('contact')
[ 11748, 640, 198, 198, 6738, 269, 9091, 2072, 13, 25747, 1330, 3998, 8206, 15878, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 6738, ...
3.696078
102
#1. for (len(absolutes)), if signs[i] is true: answer += absolutes[i], else: answer -= absolutes[i] #2. sum(absolutes)
[ 198, 198, 2, 16, 13, 329, 357, 11925, 7, 8937, 349, 1769, 36911, 611, 5895, 58, 72, 60, 318, 2081, 25, 3280, 15853, 2352, 349, 1769, 58, 72, 4357, 2073, 25, 3280, 48185, 2352, 349, 1769, 58, 72, 60, 198, 2, 17, 13, 2160, 7, 89...
2.44898
49
""" pyexcel ~~~~~~~~~~~~~~~~~~~ **pyexcel** is a wrapper library to read, manipulate and write data in different excel formats: csv, ods, xls, xlsx and xlsm. It does not support formulas, styles and charts. :copyright: (c) 2014-2017 by Onni Software Ltd. :license: New BSD License, see LICENSE for more details """ # flake8: noqa from .cookbook import ( merge_csv_to_a_book, merge_all_to_a_book, split_a_book, extract_a_sheet_from_a_book, ) from .core import ( get_array, iget_array, get_dict, get_records, iget_records, get_book_dict, get_sheet, get_book, iget_book, save_as, isave_as, save_book_as, isave_book_as, ) from .book import Book from .sheet import Sheet from .internal.garbagecollector import free_resources from .deprecated import ( load_book, load_book_from_memory, load, load_from_memory, load_from_dict, load_from_records, Reader, SeriesReader, ColumnSeriesReader, BookReader, ) from .__version__ import __version__, __author__
[ 37811, 198, 220, 220, 220, 12972, 1069, 5276, 198, 220, 220, 220, 220, 27156, 4907, 93, 628, 220, 220, 220, 12429, 9078, 1069, 5276, 1174, 318, 257, 29908, 5888, 284, 1100, 11, 18510, 290, 198, 220, 220, 220, 3551, 1366, 287, 1180, ...
2.426009
446
# coding=utf-8 import logging import random import string import sys import unittest from time import time, sleep import apiritif import os import re from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import Select from selenium.webdriver.support import expected_conditions as econd from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.keys import Keys from bzt.resources.selenium_extras import waiter, get_locator
[ 2, 19617, 28, 40477, 12, 23, 198, 198, 11748, 18931, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 25064, 198, 11748, 555, 715, 395, 198, 6738, 640, 1330, 640, 11, 3993, 198, 198, 11748, 2471, 3276, 361, 198, 198, 11748, 28686, 198,...
3.537634
186
from elasticsearch_dsl import Search as BaseSearch from elasticsearch_dsl.response import Hit as BaseHit from elasticsearch_dsl.response import Response as BaseResponse def explanation_value(explanation, text): """ Gets the value from the explanation for descriptions starting with the given text. """ if explanation.description.startswith(text): return { 'description': explanation.description, 'value': explanation.value } for detail in getattr(explanation, 'details', []): result = explanation_value(detail, text) if result: return result
[ 6738, 27468, 12947, 62, 67, 6649, 1330, 11140, 355, 7308, 18243, 198, 6738, 27468, 12947, 62, 67, 6649, 13, 26209, 1330, 7286, 355, 7308, 17889, 198, 6738, 27468, 12947, 62, 67, 6649, 13, 26209, 1330, 18261, 355, 7308, 31077, 628, 628, ...
2.962963
216
from SocketServer import BaseRequestHandler, TCPServer from DistributedStorageBenchmarkTool.StampyMcGetTheLog import StampyMcGetTheLog # from sets import Set import re if __name__ == '__main__': serv = TCPServer(('', 20000), EchoHandler) serv.serve_forever()
[ 6738, 47068, 10697, 1330, 7308, 18453, 25060, 11, 17283, 3705, 18497, 198, 6738, 4307, 6169, 31425, 44199, 4102, 25391, 13, 1273, 696, 88, 9742, 3855, 464, 11187, 1330, 40694, 88, 9742, 3855, 464, 11187, 198, 2, 422, 5621, 1330, 5345, 1...
3.141176
85
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2010 Edgewall Software # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://bitten.edgewall.org/wiki/License. """Implements the scheduling of builds for a project. This module provides the functionality for scheduling builds for a specific Trac environment. It is used by both the build master and the web interface to get the list of required builds (revisions not built yet). Furthermore, the `BuildQueue` class is used by the build master to determine the next pending build, and to match build slaves against configured target platforms. """ from itertools import ifilter import re import time from trac.util.datefmt import to_timestamp from trac.util import pretty_timedelta, format_datetime from trac.attachment import Attachment from bitten.model import BuildConfig, TargetPlatform, Build, BuildStep from bitten.util.repository import get_repos __docformat__ = 'restructuredtext en'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 4343, 12, 10333, 1717, 39909, 439, 10442, 198, 2, 15069, 357, 34, 8, 5075, 12, 12726, 12803, 12592, 89, 1279, 66, 4029, 19471, 31, 70, ...
3.678457
311
from typing import List
[ 6738, 19720, 1330, 7343, 628 ]
5
5
# -*- coding: utf-8 -*- from __future__ import unicode_literals from copy import deepcopy from functools import wraps from itertools import chain from lxml import etree from six.moves.html_parser import HTMLParser from regparser.tree.priority_stack import PriorityStack def prepend_parts(parts_prefix, n): """ Recursively preprend parts_prefix to the parts of the node n. Parts is a list of markers that indicates where you are in the regulation text. """ n.label = parts_prefix + n.label for c in n.children: prepend_parts(parts_prefix, c) return n def split_text(text, tokens): """ Given a body of text that contains tokens, splice the text along those tokens. """ starts = [text.find(t) for t in tokens] if not starts or starts[0] != 0: starts.insert(0, 0) slices = zip(starts, starts[1:]) texts = [text[i[0]:i[1]] for i in slices] + [text[starts[-1]:]] return texts def _combine_with_space(prev_text, next_text, add_space_if_needed): """Logic to determine where to add spaces to XML. Generally this is just as matter of checking for space characters, but there are some outliers""" prev_text, next_text = prev_text or "", next_text or "" prev_char, next_char = prev_text[-1:], next_text[:1] needs_space = (not prev_char.isspace() and not next_char.isspace() and next_char and prev_char not in u'([/<-' and next_char not in u').;,]>/-') if add_space_if_needed and needs_space: return prev_text + " " + next_text else: return prev_text + next_text def replace_xml_node_with_text(node, text): """There are some complications w/ lxml when determining where to add the replacement text. Account for all of that here.""" parent, prev = node.getparent(), node.getprevious() if prev is not None: prev.tail = (prev.tail or '') + text else: parent.text = (parent.text or '') + text parent.remove(node) def replace_xpath(xpath): """Decorator to convert all elements matching the provided xpath in to plain text. This'll convert the wrapped function into a new function which will search for the provided xpath and replace all matches""" return decorator def get_node_text(node, add_spaces=False): """ Extract all the text from an XML node (including the text of it's children). """ node = deepcopy(node) subscript_to_plaintext(node, add_spaces) superscript_to_plaintext(node, add_spaces) footnotes_to_plaintext(node, add_spaces) parts = [node.text] + list( chain(*([c.text, c.tail] for c in node.getchildren()))) final_text = '' for part in filter(bool, parts): final_text = _combine_with_space(final_text, part, add_spaces) return final_text.strip() _tag_black_list = ('PRTPAGE', ) def get_node_text_tags_preserved(xml_node): """Get the body of an XML node as a string, avoiding a specific blacklist of bad tags.""" xml_node = deepcopy(xml_node) etree.strip_tags(xml_node, *_tag_black_list) # Remove the wrapping tag node_text = xml_node.text or '' node_text += ''.join(etree.tounicode(child) for child in xml_node) node_text = HTMLParser().unescape(node_text) return node_text
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 340, 861, 10141, ...
2.643307
1,270
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """Backend query implementation classes""" from __future__ import division from __future__ import print_function from __future__ import absolute_import import abc import six from aiida.common import exceptions from aiida.common.lang import abstractclassmethod, type_check from aiida.common.exceptions import InputValidationError __all__ = ('BackendQueryBuilder',)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 7804, 21017, 198, 2, 15069, 357, 66, 828, 383, 317, 4178, 5631, 1074, 13, 1439, 2489, 10395, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.790503
358
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wildcard-import,unused-wildcard-import """Common utilities for Qiskit.""" # Deprecated: for backwards compatibility to be removed in a future release from qiskit.utils import *
[ 2, 770, 2438, 318, 636, 286, 1195, 1984, 270, 13, 198, 2, 198, 2, 357, 34, 8, 15069, 19764, 2177, 13, 198, 2, 198, 2, 770, 2438, 318, 11971, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 13, 921, 743, 198, 2, 7330, 257, 4866...
3.648649
185
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Plot Milky Way spiral arm models. """ import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from gammapy.astro.population.spatial import ValleeSpiral, FaucherSpiral vallee_spiral = ValleeSpiral() faucher_spiral = FaucherSpiral() #theta = np.arange(0, 720) radius = np.arange(2.1, 20, 0.1) for spiralarm_index in range(4): # Plot Vallee spiral x, y = vallee_spiral.xy_position(radius=radius, spiralarm_index=spiralarm_index) name = vallee_spiral.spiralarms[spiralarm_index] plt.plot(x, y, label=name) # Plot Faucher spiral x, y = faucher_spiral.xy_position(radius=radius, spiralarm_index=spiralarm_index) name = faucher_spiral.spiralarms[spiralarm_index] plt.plot(x, y, ls='-.', label='Faucher ' + name) plt.plot(vallee_spiral.bar['x'], vallee_spiral.bar['y']) plt.xlim(-10, 10) plt.ylim(-10, 10) plt.legend(ncol=2) filename = 'valee_spiral.pdf' print('Writing {0}'.format(filename)) plt.savefig(filename)
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 37811, 198, 43328, 34822, 6378, 23642, 3211, 4981, 13, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8...
2.405963
436
__description__ = \ """ Fitter subclass for performing bayesian (MCMC) fits. """ __author__ = "Michael J. Harms" __date__ = "2017-05-10" from .base import Fitter import emcee, corner import numpy as np import scipy.optimize as optimize import multiprocessing
[ 834, 11213, 834, 796, 3467, 198, 37811, 198, 37, 1967, 47611, 329, 9489, 15489, 35610, 357, 9655, 9655, 8, 11414, 13, 198, 37811, 198, 834, 9800, 834, 796, 366, 13256, 449, 13, 2113, 907, 1, 198, 834, 4475, 834, 796, 366, 5539, 12, ...
3
88
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628 ]
3.75
8
from inspect import isclass, isabstract, getmembers import autos
[ 6738, 10104, 1330, 318, 4871, 11, 318, 397, 8709, 11, 651, 30814, 198, 11748, 44619, 628, 198 ]
3.941176
17
# -*- coding: utf-8 -*- # We must always import the relevant libraries for our problem at hand. NumPy and TensorFlow are required for this example. # https://www.kaggle.com/c/costa-rican-household-poverty-prediction/data#_=_ import numpy as np np.set_printoptions(threshold='nan') import matplotlib.pyplot as plt import tensorflow as tf import pandas as pd costa_rica_household = pd.read_csv('data/train.csv') #x1 = costa_rica_household.describe() #x1["v2a1"] costa_rica_household.head() list(costa_rica_household.dtypes) #costa_rica_household = costa_rica_household.fillna(0) costa_rica_household = costa_rica_household.fillna(costa_rica_household.mean()) #costa_rica_household["idhogar"] = costa_rica_household["idhogar"].apply(lambda x: int(x, 16)) #costa_rica_household["dependency"] = costa_rica_household["dependency"].apply(lambda x: toInt(x)) #costa_rica_household["edjefe"] = costa_rica_household["edjefe"].apply(lambda x: toInt(x))//edjefa #costa_rica_household.loc[costa_rica_household['dependency'] == "'<='"] #v1 = costa_rica_household[costa_rica_household['dependency'].apply(lambda x: type(x) == str)]['dependency'] #col_name = costa_rica_household.columns #print(list(col_name)) #costa_rica_household[["age", "SQBage", "agesq", "r4h1", "r4h2"]] cols_to_norm = ['v2a1', 'hacdor', 'rooms', 'hacapo', 'v14a', 'refrig', 'v18q', 'v18q1', 'tamhog', 'tamviv', 'escolari', 'rez_esc', 'hhsize', 'paredblolad', 'paredzocalo', 'paredpreb', 'pareddes', 'paredmad', 'paredzinc', 'paredfibras', 'paredother', 'pisomoscer', 'pisocemento', 'pisoother', 'pisonatur', 'pisonotiene', 'pisomadera', 'techozinc', 'techoentrepiso', 'techocane', 'techootro', 'cielorazo', 'abastaguadentro', 'abastaguafuera', 'abastaguano', 'public', 'planpri', 'noelec', 'coopele', 'sanitario1', 'sanitario2', 'sanitario3', 'sanitario5', 'sanitario6', 'energcocinar1', 'energcocinar2', 'energcocinar3', 'energcocinar4', 'elimbasu1', 'elimbasu2', 'elimbasu3', 'elimbasu4', 'elimbasu5', 'elimbasu6', 'epared1', 'epared2', 'epared3', 'etecho1', 'etecho2', 'etecho3', 'eviv1', 'eviv2', 'eviv3', 'dis', 'male', 'female', 'estadocivil1', 'estadocivil2', 'estadocivil3', 'estadocivil4', 'estadocivil5', 'estadocivil6', 'estadocivil7', 'parentesco1', 'parentesco2', 'parentesco3', 'parentesco4', 'parentesco5', 'parentesco6', 'parentesco7', 'parentesco8', 'parentesco9', 'parentesco10', 'parentesco11', 'parentesco12', 'hogar_nin', 'hogar_adul', 'hogar_mayor', 'hogar_total', 'meaneduc', 'instlevel1', 'instlevel2', 'instlevel3', 'instlevel4', 'instlevel5', 'instlevel6', 'instlevel7', 'instlevel8', 'instlevel9', 'bedrooms', 'overcrowding', 'tipovivi1', 'tipovivi2', 'tipovivi3', 'tipovivi4', 'tipovivi5', 'computer', 'television', 'mobilephone', 'qmobilephone', 'lugar1', 'lugar2', 'lugar3', 'lugar4', 'lugar5', 'lugar6', 'area1', 'area2', 'SQBescolari', 'SQBhogar_total', 'SQBedjefe', 'SQBhogar_nin', 'SQBovercrowding', 'SQBdependency', 'SQBmeaned', 'agesq'] cat_cols_to_norm = ['r4h1', 'r4h2', 'r4h3', 'r4m1', 'r4m2', 'r4m3', 'r4t1', 'r4t2', 'r4t3'] cols_of_interest = ['v2a1', 'hacdor', 'rooms', 'hacapo', 'v14a', 'refrig', 'v18q', 'v18q1', 'r4h1', 'r4h2', 'r4h3', 'r4m1', 'r4m2', 'r4m3', 'r4t1', 'r4t2', 'r4t3', 'tamhog', 'tamviv', 'escolari', 'rez_esc', 'hhsize', 'paredblolad', 'paredzocalo', 'paredpreb', 'pareddes', 'paredmad', 'paredzinc', 'paredfibras', 'paredother', 'pisomoscer', 'pisocemento', 'pisoother', 'pisonatur', 'pisonotiene', 'pisomadera', 'techozinc', 'techoentrepiso', 'techocane', 'techootro', 'cielorazo', 'abastaguadentro', 'abastaguafuera', 'abastaguano', 'public', 'planpri', 'noelec', 'coopele', 'sanitario1', 'sanitario2', 'sanitario3', 'sanitario5', 'sanitario6', 'energcocinar1', 'energcocinar2', 'energcocinar3', 'energcocinar4', 'elimbasu1', 'elimbasu2', 'elimbasu3', 'elimbasu4', 'elimbasu5', 'elimbasu6', 'epared1', 'epared2', 'epared3', 'etecho1', 'etecho2', 'etecho3', 'eviv1', 'eviv2', 'eviv3', 'dis', 'male', 'female', 'estadocivil1', 'estadocivil2', 'estadocivil3', 'estadocivil4', 'estadocivil5', 'estadocivil6', 'estadocivil7', 'parentesco1', 'parentesco2', 'parentesco3', 'parentesco4', 'parentesco5', 'parentesco6', 'parentesco7', 'parentesco8', 'parentesco9', 'parentesco10', 'parentesco11', 'parentesco12', 'hogar_nin', 'hogar_adul', 'hogar_mayor', 'hogar_total', 'meaneduc', 'instlevel1', 'instlevel2', 'instlevel3', 'instlevel4', 'instlevel5', 'instlevel6', 'instlevel7', 'instlevel8', 'instlevel9', 'bedrooms', 'overcrowding', 'tipovivi1', 'tipovivi2', 'tipovivi3', 'tipovivi4', 'tipovivi5', 'computer', 'television', 'mobilephone', 'qmobilephone', 'lugar1', 'lugar2', 'lugar3', 'lugar4', 'lugar5', 'lugar6', 'area1', 'area2', 'SQBescolari', 'SQBhogar_total', 'SQBedjefe', 'SQBhogar_nin', 'SQBovercrowding', 'SQBdependency', 'SQBmeaned', 'agesq'] #costa_rica_household[cols_to_norm] = costa_rica_household[cols_to_norm].apply(lambda x: (x - x.min())/(x.max() - x.min())) #costa_rica_household[cat_cols_to_norm] = costa_rica_household[cat_cols_to_norm].apply(lambda x: (x - x.min())/(x.max() - x.min())) costa_rica_household[cols_of_interest] = costa_rica_household[cols_of_interest].apply(lambda x: (x - x.min())/(x.max() - x.min())) feat_cols = [] for col_name in cols_to_norm: col_name = tf.feature_column.numeric_column(col_name) feat_cols.append(col_name) age_range_count = [1,2,3,4,5,7] r4h1_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4h1'), boundaries=age_range_count) r4h2_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4h2'), boundaries=age_range_count) r4h3_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4h3'), boundaries=age_range_count) crossed_r4h = tf.feature_column.crossed_column([r4h1_bucket, r4h2_bucket, r4h3_bucket], 100) #fc = [r4h1_bucket, r4h2_bucket, r4h3_bucket, crossed_r4h] r4m1_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4m1'), boundaries=age_range_count) r4m2_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4m2'), boundaries=age_range_count) r4m3_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4m3'), boundaries=age_range_count) crossed_r4m = tf.feature_column.crossed_column([r4m1_bucket, r4m2_bucket, r4m3_bucket], 100) r4t1_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4t1'), boundaries=age_range_count) r4t2_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4t2'), boundaries=age_range_count) r4t3_bucket = tf.feature_column.bucketized_column(tf.feature_column.numeric_column('r4t3'), boundaries=age_range_count) crossed_r4t = tf.feature_column.crossed_column([r4t1_bucket, r4t2_bucket, r4t3_bucket], 100) feat_cols.extend([r4h1_bucket, r4h2_bucket, r4h3_bucket, crossed_r4h, r4m1_bucket, r4m2_bucket, r4m3_bucket, crossed_r4m, r4t1_bucket, r4t2_bucket, r4t3_bucket, crossed_r4t]) len(feat_cols) feat_cols[138] estimator = tf.estimator.LinearClassifier(feature_columns=feat_cols, n_classes=4) #costa_rica_household[(costa_rica_household.Target == 4)] x_data = costa_rica_household.drop('Id', axis=1).drop('edjefa', axis=1).drop('idhogar', axis=1).drop('dependency', axis=1).drop('Target', axis=1) #x_data['idhogar'] #x_data.describe() #x_data.head() labels = costa_rica_household['Target'] labels.head() from sklearn.model_selection import train_test_split X_train, X_eval, y_train, y_eval = train_test_split(x_data, labels, test_size=0.3, random_state=101) print(X_train.shape, y_eval.shape) input_func = tf.estimator.inputs.pandas_input_fn(x=X_train, y=y_train, batch_size=10, num_epochs=100, shuffle=True) estimator.train(input_fn=input_func,steps=1000) eval_input_func = tf.estimator.inputs.pandas_input_fn(x=X_eval, y=y_eval, batch_size=10, num_epochs=1, shuffle=False) eval_metrics = estimator.evaluate(input_fn=eval_input_func) print('Eval metrics') print(eval_metrics) pred_input_func = tf.estimator.inputs.pandas_input_fn(x=X_eval, shuffle=False) predictions = [] for predict in estimator.predict(input_fn=pred_input_func): predictions.append(predict) predictions #categorical_columun_voc = tf.feature_column.embedding_column(categorical_columun_voc, 4) dnn_classifier = tf.estimator.DNNClassifier(hidden_units=[10, 10, 10], feature_columns=feat_cols, n_classes=2) dnn_classifier.train(input_fn=input_func,steps=1000) dnn_eval_metrics = dnn_classifier.evaluate(input_fn=eval_input_func) dnn_eval_metrics
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 1303, 775, 1276, 1464, 1330, 262, 5981, 12782, 329, 674, 1917, 379, 1021, 13, 31835, 20519, 290, 309, 22854, 37535, 389, 2672, 329, 428, 1672, 13, 198, 2, 3740, 1378, ...
2.207205
4,025
import os import time import unittest from DTL.api import * def main(): unittest.main(verbosity=2) if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 640, 198, 11748, 555, 715, 395, 198, 198, 6738, 360, 14990, 13, 15042, 1330, 1635, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 628, 220, 220, 220, 220, 220, 2...
2.047619
84
#!/usr/bin/env python import numpy as np import cv2 import math import rospy from cv_bridge import CvBridge, CvBridgeError from std_msgs.msg import Bool from sensor_msgs.msg import Image from geometry_msgs.msg import Twist bridge = CvBridge() laser_scan_on = True if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 10688, 198, 11748, 686, 2777, 88, 198, 6738, 269, 85, 62, 9458, 1330, 327, 85, 37385, 11, 327, 85, 37385, 123...
2.756757
111
"""JSON implementations of authentication queries.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package json package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification from .. import utilities from ..osid import queries as osid_queries from ..primitives import Id from ..utilities import get_registry from dlkit.abstract_osid.authentication import queries as abc_authentication_queries from dlkit.abstract_osid.osid import errors
[ 37811, 40386, 25504, 286, 18239, 20743, 526, 15931, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 3919, 12, 15003, 198, 2, 220, 220, 220, 220, 45261, 6097, 836, 470, 2421, 11593, 15003, 834, 13, 198, 2, 279, 2645, 600, 25, 15560, 28, ...
3.421569
204
import requests import dateutil.parser import pytz from Git.dao.git_dao import GitOwnerRepo
[ 11748, 7007, 198, 11748, 3128, 22602, 13, 48610, 198, 11748, 12972, 22877, 198, 198, 6738, 15151, 13, 67, 5488, 13, 18300, 62, 67, 5488, 1330, 15151, 42419, 6207, 78, 628 ]
3.133333
30
import os import os.path import requests import time from pathlib import Path from talon import ctrl, ui, Module, Context, actions, clip import tempfile # Courtesy of https://github.com/anonfunc/talon-user/blob/master/apps/jetbrains.py extendCommands = [] # Each IDE gets its own port, as otherwise you wouldn't be able # to run two at the same time and switch between them. # Note that MPS and IntelliJ ultimate will conflict... port_mapping = { "com.google.android.studio": 8652, "com.jetbrains.AppCode": 8655, "com.jetbrains.CLion": 8657, "com.jetbrains.datagrip": 8664, "com.jetbrains.goland-EAP": 8659, "com.jetbrains.goland": 8659, "com.jetbrains.intellij-EAP": 8653, "com.jetbrains.intellij.ce": 8654, "com.jetbrains.intellij": 8653, "com.jetbrains.PhpStorm": 8662, "com.jetbrains.pycharm": 8658, "com.jetbrains.rider": 8660, "com.jetbrains.rubymine": 8661, "com.jetbrains.WebStorm": 8663, "google-android-studio": 8652, "idea64.exe": 8653, "IntelliJ IDEA": 8653, "jetbrains-appcode": 8655, "jetbrains-clion": 8657, "jetbrains-datagrip": 8664, "jetbrains-goland-eap": 8659, "jetbrains-goland": 8659, "jetbrains-idea-ce": 8654, "jetbrains-idea-eap": 8653, "jetbrains-idea": 8653, "jetbrains-phpstorm": 8662, "jetbrains-pycharm-ce": 8658, "jetbrains-pycharm": 8658, "jetbrains-rider": 8660, "jetbrains-rubymine": 8661, "jetbrains-studio": 8652, "jetbrains-webstorm": 8663, "PyCharm": 8658, "pycharm64.exe": 8658, "webstorm64.exe": 8663, } select_verbs_map = { "clear": ["action EditorBackSpace"], "collapse": ["action CollapseRegion"], "comment": ["action CommentByLineComment"], "copy": ["action EditorCopy"], "cut": ["action EditorCut"], "drag down": ["action MoveLineDown"], "drag up": ["action MoveLineUp"], "expand": ["action ExpandRegion"], "indent": ["action EditorIndentLineOrSelection"], "refactor": ["action Refactorings.QuickListPopupAction"], "rename": ["action RenameElement"], "replace": ["action EditorPaste"], "select": [], "unindent": ["action EditorUnindentSelection"], } movement_verbs_map = { "fix": ["action ShowIntentionActions"], "go": [], "paste": ["action EditorPaste"], } ctx = Context() mod = Module() mod.list("select_verbs", desc="Verbs for selecting in the IDE") mod.list("movement_verbs", desc="Verbs for navigating the IDE") ctx.matches = r""" app: /jetbrains/ app: IntelliJ IDEA app: idea64.exe app: PyCharm app: PyCharm64.exe app: pycharm64.exe app: webstorm64.exe """ ctx.lists["user.selection_verbs"] = select_verbs_map.keys() ctx.lists["user.navigation_verbs"] = movement_verbs_map.keys()
[ 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 7007, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 3305, 261, 1330, 269, 14859, 11, 334, 72, 11, 19937, 11, 30532, 11, 4028, 11, 10651, 198, 11748, 20218, 7753, ...
2.441593
1,130
from be.table.user import User from be.table.user_store import User_Store from be.table.store import Store
[ 6738, 307, 13, 11487, 13, 7220, 1330, 11787, 198, 6738, 307, 13, 11487, 13, 7220, 62, 8095, 1330, 11787, 62, 22658, 198, 6738, 307, 13, 11487, 13, 8095, 1330, 9363, 628 ]
3.483871
31
# Adapted by Ji Zhang, 2019 # # Based on Detectron.pytorch/lib/roi_data/fast_rcnn.py # Original license text: # -------------------------------------------------------- # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## """Construct minibatches for Fast R-CNN training. Handles the minibatch blobs that are specific to Fast R-CNN. Other blobs that are generic to RPN, etc. are handled by their respecitive roi_data modules. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import numpy.random as npr import logging from core.config import cfg import utils_rel.boxes_rel as box_utils_rel import utils.blob as blob_utils import utils.fpn as fpn_utils logger = logging.getLogger(__name__) def add_rel_blobs(blobs, im_scales, roidb): """Add blobs needed for training Fast R-CNN style models.""" # Sample training RoIs from each image and append them to the blob lists for im_i, entry in enumerate(roidb): frcn_blobs = _sample_pairs(entry, im_scales[im_i], im_i) for k, v in frcn_blobs.items(): blobs[k].append(v) # Concat the training blob lists into tensors for k, v in blobs.items(): if isinstance(v, list) and len(v) > 0: blobs[k] = np.concatenate(v) if cfg.FPN.FPN_ON and cfg.FPN.MULTILEVEL_ROIS: _add_rel_multilevel_rois(blobs) return True def _sample_pairs(roidb, im_scale, batch_idx): """Generate a random sample of RoIs comprising foreground and background examples. """ fg_pairs_per_image = cfg.TRAIN.FG_REL_SIZE_PER_IM pairs_per_image = int(cfg.TRAIN.FG_REL_SIZE_PER_IM / cfg.TRAIN.FG_REL_FRACTION) # need much more pairs since it's quadratic max_pair_overlaps = roidb['max_pair_overlaps'] if cfg.MODEL.MULTI_RELATION: prd_gt_overlaps = roidb['prd_gt_overlaps'].toarray() prd_class_num = prd_gt_overlaps.shape[1] gt_pair_inds, gt_pair_class = np.where(prd_gt_overlaps > 1.0 - 1e-4) fg_pair_inds, fg_pair_class = np.where((prd_gt_overlaps >= cfg.TRAIN.FG_THRESH) & (prd_gt_overlaps <= 1.0 - 1e-4)) hash_gt_pair_inds = prd_class_num * gt_pair_inds + gt_pair_class hash_fg_pair_inds = prd_class_num * fg_pair_inds + fg_pair_class fg_pairs_per_this_image = np.minimum(fg_pairs_per_image, hash_gt_pair_inds.size + hash_fg_pair_inds.size) if hash_fg_pair_inds.size > 0 and fg_pairs_per_this_image > hash_gt_pair_inds.size: hash_fg_pair_inds = npr.choice( hash_fg_pair_inds, size=(fg_pairs_per_this_image - hash_gt_pair_inds.size), replace=False) hash_fg_pair_inds = np.append(hash_fg_pair_inds, hash_gt_pair_inds) elif fg_pairs_per_this_image <= hash_gt_pair_inds.size: hash_gt_pair_inds = npr.choice( hash_gt_pair_inds, size=fg_pairs_per_this_image, replace=False) hash_fg_pair_inds = hash_gt_pair_inds else: hash_fg_pair_inds = hash_gt_pair_inds blob_dict = {} if cfg.MODEL.USE_BG: bg_pair_inds, bg_pair_class_inds = np.where((prd_gt_overlaps < cfg.TRAIN.BG_THRESH_HI)) hash_bg_pair_inds = prd_class_num * bg_pair_inds + bg_pair_class_inds bg_pairs_per_this_image = pairs_per_image - fg_pairs_per_this_image bg_pairs_per_this_image = np.minimum(bg_pairs_per_this_image, hash_bg_pair_inds.size) if hash_bg_pair_inds.size > 0: hash_bg_pair_inds = npr.choice( hash_bg_pair_inds, size=bg_pairs_per_this_image, replace=False) hash_keep_pair_inds = np.append(hash_fg_pair_inds, hash_bg_pair_inds) multi_prd_labels = np.zeros(hash_keep_pair_inds.size, dtype=np.int32) multi_prd_labels[:hash_fg_pair_inds.size] = 1.0 #fg_multi_prd_labels keep_pair_inds = np.append(hash_fg_pair_inds // prd_class_num, hash_bg_pair_inds // prd_class_num) keep_pair_class = np.append(hash_fg_pair_inds % prd_class_num, hash_bg_pair_inds % prd_class_num) else: multi_prd_labels = np.ones(fg_multi_prd_labels.size, dtype=np.int32) #fg_multi_prd_labels keep_pair_inds = np.append(hash_fg_pair_inds // prd_class_num) keep_pair_class = np.append(hash_fg_pair_inds % prd_class_num) blob_dict['multi_prd_labels_int32'] = multi_prd_labels.astype(np.int32, copy=False) blob_dict['keep_pair_class_int32'] = keep_pair_class.astype(np.int32, copy=False) blob_dict['fg_size'] = np.array([hash_fg_pair_inds.size], dtype=np.int32) else: gt_pair_inds = np.where(max_pair_overlaps > 1.0 - 1e-4)[0] fg_pair_inds = np.where((max_pair_overlaps >= cfg.TRAIN.FG_THRESH) & (max_pair_overlaps <= 1.0 - 1e-4))[0] fg_pairs_per_this_image = np.minimum(fg_pairs_per_image, gt_pair_inds.size + fg_pair_inds.size) # Sample foreground regions without replacement if fg_pair_inds.size > 0 and fg_pairs_per_this_image > gt_pair_inds.size: fg_pair_inds = npr.choice( fg_pair_inds, size=(fg_pairs_per_this_image - gt_pair_inds.size), replace=False) fg_pair_inds = np.append(fg_pair_inds, gt_pair_inds) elif fg_pairs_per_this_image <= gt_pair_inds.size: gt_pair_inds = npr.choice( gt_pair_inds, size=fg_pairs_per_this_image, replace=False) fg_pair_inds = gt_pair_inds else: fg_pair_inds = gt_pair_inds # Label is the class each RoI has max overlap with fg_prd_labels = roidb['max_prd_classes'][fg_pair_inds] blob_dict = dict( fg_prd_labels_int32=fg_prd_labels.astype(np.int32, copy=False)) if cfg.MODEL.USE_BG: bg_pair_inds = np.where((max_pair_overlaps < cfg.TRAIN.BG_THRESH_HI))[0] # Compute number of background RoIs to take from this image (guarding # against there being fewer than desired) bg_pairs_per_this_image = pairs_per_image - fg_pairs_per_this_image bg_pairs_per_this_image = np.minimum(bg_pairs_per_this_image, bg_pair_inds.size) # Sample foreground regions without replacement if bg_pair_inds.size > 0: bg_pair_inds = npr.choice( bg_pair_inds, size=bg_pairs_per_this_image, replace=False) # logger.info('{} : {}'.format(fg_pair_inds.size, bg_pair_inds.size)) keep_pair_inds = np.append(fg_pair_inds, bg_pair_inds) all_prd_labels = np.zeros(keep_pair_inds.size, dtype=np.int32) all_prd_labels[:fg_pair_inds.size] = fg_prd_labels + 1 # class should start from 1 else: keep_pair_inds = fg_pair_inds all_prd_labels = fg_prd_labels blob_dict['all_prd_labels_int32'] = all_prd_labels.astype(np.int32, copy=False) blob_dict['fg_size'] = np.array([fg_pair_inds.size], dtype=np.int32) # this is used to check if there is at least one fg to learn sampled_sbj_boxes = roidb['sbj_boxes'][keep_pair_inds] sampled_obj_boxes = roidb['obj_boxes'][keep_pair_inds] sampled_all_boxes = roidb['all_boxes'] det_labels = roidb['det_labels'] sampled_sbj_inds = roidb['sbj_id'][keep_pair_inds] sampled_obj_inds = roidb['obj_id'][keep_pair_inds] # Scale rois and format as (batch_idx, x1, y1, x2, y2) sampled_sbj_rois = sampled_sbj_boxes * im_scale sampled_obj_rois = sampled_obj_boxes * im_scale sampled_all_rois = sampled_all_boxes * im_scale repeated_batch_idx = batch_idx * blob_utils.ones((keep_pair_inds.shape[0], 1)) all_boxes_repeated_batch_idx = batch_idx * blob_utils.ones((sampled_all_boxes.shape[0], 1)) sampled_sbj_rois = np.hstack((repeated_batch_idx, sampled_sbj_rois)) sampled_obj_rois = np.hstack((repeated_batch_idx, sampled_obj_rois)) sampled_all_rois = np.hstack((all_boxes_repeated_batch_idx, sampled_all_rois)) int_repeated_batch_idx = batch_idx * np.ones((keep_pair_inds.shape[0], 1), dtype=np.int) blob_dict['sbj_inds'] = np.hstack((repeated_batch_idx, sampled_sbj_inds.reshape(-1, 1))) blob_dict['obj_inds'] = np.hstack((repeated_batch_idx, sampled_obj_inds.reshape(-1, 1))) blob_dict['sbj_rois'] = sampled_sbj_rois blob_dict['obj_rois'] = sampled_obj_rois blob_dict['det_rois'] = sampled_all_rois blob_dict['det_labels'] = det_labels sampled_rel_rois = box_utils_rel.rois_union(sampled_sbj_rois, sampled_obj_rois) blob_dict['rel_rois'] = sampled_rel_rois if cfg.MODEL.USE_SPATIAL_FEAT: sampled_spt_feat = box_utils_rel.get_spt_features( sampled_sbj_boxes, sampled_obj_boxes, roidb['width'], roidb['height']) blob_dict['spt_feat'] = sampled_spt_feat if cfg.MODEL.USE_FREQ_BIAS: sbj_labels = roidb['max_sbj_classes'][keep_pair_inds] obj_labels = roidb['max_obj_classes'][keep_pair_inds] blob_dict['all_sbj_labels_int32'] = sbj_labels.astype(np.int32, copy=False) blob_dict['all_obj_labels_int32'] = obj_labels.astype(np.int32, copy=False) if cfg.MODEL.USE_NODE_CONTRASTIVE_LOSS or cfg.MODEL.USE_NODE_CONTRASTIVE_SO_AWARE_LOSS or cfg.MODEL.USE_NODE_CONTRASTIVE_P_AWARE_LOSS: nodes_per_image = cfg.MODEL.NODE_SAMPLE_SIZE max_sbj_overlaps = roidb['max_sbj_overlaps'] max_obj_overlaps = roidb['max_obj_overlaps'] # sbj # Here a naturally existing assumption is, each positive sbj should have at least one positive obj sbj_pos_pair_pos_inds = np.where((max_pair_overlaps >= cfg.TRAIN.FG_THRESH))[0] sbj_pos_obj_pos_pair_neg_inds = np.where((max_sbj_overlaps >= cfg.TRAIN.FG_THRESH) & (max_obj_overlaps >= cfg.TRAIN.FG_THRESH) & (max_pair_overlaps < cfg.TRAIN.BG_THRESH_HI))[0] sbj_pos_obj_neg_pair_neg_inds = np.where((max_sbj_overlaps >= cfg.TRAIN.FG_THRESH) & (max_obj_overlaps < cfg.TRAIN.FG_THRESH) & (max_pair_overlaps < cfg.TRAIN.BG_THRESH_HI))[0] if sbj_pos_pair_pos_inds.size > 0: sbj_pos_pair_pos_inds = npr.choice( sbj_pos_pair_pos_inds, size=int(min(nodes_per_image, sbj_pos_pair_pos_inds.size)), replace=False) if sbj_pos_obj_pos_pair_neg_inds.size > 0: sbj_pos_obj_pos_pair_neg_inds = npr.choice( sbj_pos_obj_pos_pair_neg_inds, size=int(min(nodes_per_image, sbj_pos_obj_pos_pair_neg_inds.size)), replace=False) sbj_pos_pair_neg_inds = sbj_pos_obj_pos_pair_neg_inds if nodes_per_image - sbj_pos_obj_pos_pair_neg_inds.size > 0 and sbj_pos_obj_neg_pair_neg_inds.size > 0: sbj_pos_obj_neg_pair_neg_inds = npr.choice( sbj_pos_obj_neg_pair_neg_inds, size=int(min(nodes_per_image - sbj_pos_obj_pos_pair_neg_inds.size, sbj_pos_obj_neg_pair_neg_inds.size)), replace=False) sbj_pos_pair_neg_inds = np.append(sbj_pos_pair_neg_inds, sbj_pos_obj_neg_pair_neg_inds) sbj_pos_inds = np.append(sbj_pos_pair_pos_inds, sbj_pos_pair_neg_inds) binary_labels_sbj_pos = np.zeros(sbj_pos_inds.size, dtype=np.int32) binary_labels_sbj_pos[:sbj_pos_pair_pos_inds.size] = 1 blob_dict['binary_labels_sbj_pos_int32'] = binary_labels_sbj_pos.astype(np.int32, copy=False) prd_pos_labels_sbj_pos = roidb['max_prd_classes'][sbj_pos_pair_pos_inds] prd_labels_sbj_pos = np.zeros(sbj_pos_inds.size, dtype=np.int32) prd_labels_sbj_pos[:sbj_pos_pair_pos_inds.size] = prd_pos_labels_sbj_pos + 1 blob_dict['prd_labels_sbj_pos_int32'] = prd_labels_sbj_pos.astype(np.int32, copy=False) sbj_labels_sbj_pos = roidb['max_sbj_classes'][sbj_pos_inds] + 1 # 1. set all obj labels > 0 obj_labels_sbj_pos = roidb['max_obj_classes'][sbj_pos_inds] + 1 # 2. find those negative obj max_obj_overlaps_sbj_pos = roidb['max_obj_overlaps'][sbj_pos_inds] obj_neg_inds_sbj_pos = np.where(max_obj_overlaps_sbj_pos < cfg.TRAIN.FG_THRESH)[0] obj_labels_sbj_pos[obj_neg_inds_sbj_pos] = 0 blob_dict['sbj_labels_sbj_pos_int32'] = sbj_labels_sbj_pos.astype(np.int32, copy=False) blob_dict['obj_labels_sbj_pos_int32'] = obj_labels_sbj_pos.astype(np.int32, copy=False) # this is for freq bias in RelDN blob_dict['sbj_labels_sbj_pos_fg_int32'] = roidb['max_sbj_classes'][sbj_pos_inds].astype(np.int32, copy=False) blob_dict['obj_labels_sbj_pos_fg_int32'] = roidb['max_obj_classes'][sbj_pos_inds].astype(np.int32, copy=False) sampled_sbj_boxes_sbj_pos = roidb['sbj_boxes'][sbj_pos_inds] sampled_obj_boxes_sbj_pos = roidb['obj_boxes'][sbj_pos_inds] # Scale rois and format as (batch_idx, x1, y1, x2, y2) sampled_sbj_rois_sbj_pos = sampled_sbj_boxes_sbj_pos * im_scale sampled_obj_rois_sbj_pos = sampled_obj_boxes_sbj_pos * im_scale repeated_batch_idx = batch_idx * blob_utils.ones((sbj_pos_inds.shape[0], 1)) sampled_sbj_rois_sbj_pos = np.hstack((repeated_batch_idx, sampled_sbj_rois_sbj_pos)) sampled_obj_rois_sbj_pos = np.hstack((repeated_batch_idx, sampled_obj_rois_sbj_pos)) blob_dict['sbj_rois_sbj_pos'] = sampled_sbj_rois_sbj_pos blob_dict['obj_rois_sbj_pos'] = sampled_obj_rois_sbj_pos sampled_rel_rois_sbj_pos = box_utils_rel.rois_union(sampled_sbj_rois_sbj_pos, sampled_obj_rois_sbj_pos) blob_dict['rel_rois_sbj_pos'] = sampled_rel_rois_sbj_pos _, inds_unique_sbj_pos, inds_reverse_sbj_pos = np.unique( sampled_sbj_rois_sbj_pos, return_index=True, return_inverse=True, axis=0) assert inds_reverse_sbj_pos.shape[0] == sampled_sbj_rois_sbj_pos.shape[0] blob_dict['inds_unique_sbj_pos'] = inds_unique_sbj_pos blob_dict['inds_reverse_sbj_pos'] = inds_reverse_sbj_pos if cfg.MODEL.USE_SPATIAL_FEAT: sampled_spt_feat_sbj_pos = box_utils_rel.get_spt_features( sampled_sbj_boxes_sbj_pos, sampled_obj_boxes_sbj_pos, roidb['width'], roidb['height']) blob_dict['spt_feat_sbj_pos'] = sampled_spt_feat_sbj_pos # obj # Here a naturally existing assumption is, each positive obj should have at least one positive sbj obj_pos_pair_pos_inds = np.where((max_pair_overlaps >= cfg.TRAIN.FG_THRESH))[0] obj_pos_sbj_pos_pair_neg_inds = np.where((max_obj_overlaps >= cfg.TRAIN.FG_THRESH) & (max_sbj_overlaps >= cfg.TRAIN.FG_THRESH) & (max_pair_overlaps < cfg.TRAIN.BG_THRESH_HI))[0] obj_pos_sbj_neg_pair_neg_inds = np.where((max_obj_overlaps >= cfg.TRAIN.FG_THRESH) & (max_sbj_overlaps < cfg.TRAIN.FG_THRESH) & (max_pair_overlaps < cfg.TRAIN.BG_THRESH_HI))[0] if obj_pos_pair_pos_inds.size > 0: obj_pos_pair_pos_inds = npr.choice( obj_pos_pair_pos_inds, size=int(min(nodes_per_image, obj_pos_pair_pos_inds.size)), replace=False) if obj_pos_sbj_pos_pair_neg_inds.size > 0: obj_pos_sbj_pos_pair_neg_inds = npr.choice( obj_pos_sbj_pos_pair_neg_inds, size=int(min(nodes_per_image, obj_pos_sbj_pos_pair_neg_inds.size)), replace=False) obj_pos_pair_neg_inds = obj_pos_sbj_pos_pair_neg_inds if nodes_per_image - obj_pos_sbj_pos_pair_neg_inds.size > 0 and obj_pos_sbj_neg_pair_neg_inds.size: obj_pos_sbj_neg_pair_neg_inds = npr.choice( obj_pos_sbj_neg_pair_neg_inds, size=int(min(nodes_per_image - obj_pos_sbj_pos_pair_neg_inds.size, obj_pos_sbj_neg_pair_neg_inds.size)), replace=False) obj_pos_pair_neg_inds = np.append(obj_pos_pair_neg_inds, obj_pos_sbj_neg_pair_neg_inds) obj_pos_inds = np.append(obj_pos_pair_pos_inds, obj_pos_pair_neg_inds) binary_labels_obj_pos = np.zeros(obj_pos_inds.size, dtype=np.int32) binary_labels_obj_pos[:obj_pos_pair_pos_inds.size] = 1 blob_dict['binary_labels_obj_pos_int32'] = binary_labels_obj_pos.astype(np.int32, copy=False) prd_pos_labels_obj_pos = roidb['max_prd_classes'][obj_pos_pair_pos_inds] prd_labels_obj_pos = np.zeros(obj_pos_inds.size, dtype=np.int32) prd_labels_obj_pos[:obj_pos_pair_pos_inds.size] = prd_pos_labels_obj_pos + 1 blob_dict['prd_labels_obj_pos_int32'] = prd_labels_obj_pos.astype(np.int32, copy=False) obj_labels_obj_pos = roidb['max_obj_classes'][obj_pos_inds] + 1 # 1. set all sbj labels > 0 sbj_labels_obj_pos = roidb['max_sbj_classes'][obj_pos_inds] + 1 # 2. find those negative sbj max_sbj_overlaps_obj_pos = roidb['max_sbj_overlaps'][obj_pos_inds] sbj_neg_inds_obj_pos = np.where(max_sbj_overlaps_obj_pos < cfg.TRAIN.FG_THRESH)[0] sbj_labels_obj_pos[sbj_neg_inds_obj_pos] = 0 blob_dict['sbj_labels_obj_pos_int32'] = sbj_labels_obj_pos.astype(np.int32, copy=False) blob_dict['obj_labels_obj_pos_int32'] = obj_labels_obj_pos.astype(np.int32, copy=False) # this is for freq bias in RelDN blob_dict['sbj_labels_obj_pos_fg_int32'] = roidb['max_sbj_classes'][obj_pos_inds].astype(np.int32, copy=False) blob_dict['obj_labels_obj_pos_fg_int32'] = roidb['max_obj_classes'][obj_pos_inds].astype(np.int32, copy=False) sampled_sbj_boxes_obj_pos = roidb['sbj_boxes'][obj_pos_inds] sampled_obj_boxes_obj_pos = roidb['obj_boxes'][obj_pos_inds] # Scale rois and format as (batch_idx, x1, y1, x2, y2) sampled_sbj_rois_obj_pos = sampled_sbj_boxes_obj_pos * im_scale sampled_obj_rois_obj_pos = sampled_obj_boxes_obj_pos * im_scale repeated_batch_idx = batch_idx * blob_utils.ones((obj_pos_inds.shape[0], 1)) sampled_sbj_rois_obj_pos = np.hstack((repeated_batch_idx, sampled_sbj_rois_obj_pos)) sampled_obj_rois_obj_pos = np.hstack((repeated_batch_idx, sampled_obj_rois_obj_pos)) blob_dict['sbj_rois_obj_pos'] = sampled_sbj_rois_obj_pos blob_dict['obj_rois_obj_pos'] = sampled_obj_rois_obj_pos sampled_rel_rois_obj_pos = box_utils_rel.rois_union(sampled_sbj_rois_obj_pos, sampled_obj_rois_obj_pos) blob_dict['rel_rois_obj_pos'] = sampled_rel_rois_obj_pos _, inds_unique_obj_pos, inds_reverse_obj_pos = np.unique( sampled_obj_rois_obj_pos, return_index=True, return_inverse=True, axis=0) assert inds_reverse_obj_pos.shape[0] == sampled_obj_rois_obj_pos.shape[0] blob_dict['inds_unique_obj_pos'] = inds_unique_obj_pos blob_dict['inds_reverse_obj_pos'] = inds_reverse_obj_pos if cfg.MODEL.USE_SPATIAL_FEAT: sampled_spt_feat_obj_pos = box_utils_rel.get_spt_features( sampled_sbj_boxes_obj_pos, sampled_obj_boxes_obj_pos, roidb['width'], roidb['height']) blob_dict['spt_feat_obj_pos'] = sampled_spt_feat_obj_pos return blob_dict def _add_rel_multilevel_rois(blobs): """By default training RoIs are added for a single feature map level only. When using FPN, the RoIs must be distributed over different FPN levels according the level assignment heuristic (see: modeling.FPN. map_rois_to_fpn_levels). """ lvl_min = cfg.FPN.ROI_MIN_LEVEL lvl_max = cfg.FPN.ROI_MAX_LEVEL def _distribute_rois_over_fpn_levels(rois_blob_names): """Distribute rois over the different FPN levels.""" # Get target level for each roi # Recall blob rois are in (batch_idx, x1, y1, x2, y2) format, hence take # the box coordinates from columns 1:5 lowest_target_lvls = None for rois_blob_name in rois_blob_names: target_lvls = fpn_utils.map_rois_to_fpn_levels( blobs[rois_blob_name][:, 1:5], lvl_min, lvl_max) if lowest_target_lvls is None: lowest_target_lvls = target_lvls else: lowest_target_lvls = np.minimum(lowest_target_lvls, target_lvls) for rois_blob_name in rois_blob_names: # Add per FPN level roi blobs named like: <rois_blob_name>_fpn<lvl> fpn_utils.add_multilevel_roi_blobs( blobs, rois_blob_name, blobs[rois_blob_name], lowest_target_lvls, lvl_min, lvl_max) _distribute_rois_over_fpn_levels(['sbj_rois']) _distribute_rois_over_fpn_levels(['obj_rois']) _distribute_rois_over_fpn_levels(['rel_rois']) _distribute_rois_over_fpn_levels(['det_rois']) if cfg.MODEL.USE_NODE_CONTRASTIVE_LOSS or cfg.MODEL.USE_NODE_CONTRASTIVE_SO_AWARE_LOSS or cfg.MODEL.USE_NODE_CONTRASTIVE_P_AWARE_LOSS: _distribute_rois_over_fpn_levels(['sbj_rois_sbj_pos']) _distribute_rois_over_fpn_levels(['obj_rois_sbj_pos']) _distribute_rois_over_fpn_levels(['rel_rois_sbj_pos']) _distribute_rois_over_fpn_levels(['sbj_rois_obj_pos']) _distribute_rois_over_fpn_levels(['obj_rois_obj_pos']) _distribute_rois_over_fpn_levels(['rel_rois_obj_pos'])
[ 2, 30019, 276, 416, 29380, 19439, 11, 13130, 198, 2, 198, 2, 13403, 319, 35874, 1313, 13, 9078, 13165, 354, 14, 8019, 14, 305, 72, 62, 7890, 14, 7217, 62, 6015, 20471, 13, 9078, 198, 2, 13745, 5964, 2420, 25, 198, 2, 20368, 22369,...
1.957749
11,408
import time import re from src.core.tables import Table, MigrationTable from src.core.constraints import Index def get_column_definition(self, column_name): '''Get the sql column definition Selects the column type, and YES or NO from the column, IS NULLABLE. That's enough information to re-create the column. ''' sql = self.commands.column_definition(self.db.name, self.name, column_name) ans = self.execute(sql)[0] if ans[1] == 'NO': return '{} NOT NULL'.format(ans[0]) else: return ans[0] def rename_column(self, old_name, new_name): '''Rename a column''' self.execute(self.commands.rename_column( self.name, old_name, new_name, self.get_column_definition(old_name)) )
[ 11748, 640, 198, 11748, 302, 198, 6738, 12351, 13, 7295, 13, 83, 2977, 1330, 8655, 11, 36991, 10962, 198, 6738, 12351, 13, 7295, 13, 1102, 2536, 6003, 1330, 12901, 628, 198, 220, 220, 220, 825, 651, 62, 28665, 62, 46758, 7, 944, 11,...
2.21875
384
import cv2 import numpy as np from time import sleep import random length_min = 80 # Minimum length of retangle height_min = 80 # Minimum height of the angle offset = 6 #Error allowed between pixel pos_linha = 550 delay = 60 #FPS of video detect = [] cars = 0 cap = cv2.VideoCapture ("DRONE-SURVEILLANCE-CONTEST-VIDEO.mp4") cap.set (3,500) cap.set (4,500) subtractor = cv2.bgsegm.createBackgroundSubtractorMOG () while True: ret, frame1 = cap.read () time = float(1 / delay) sleep(time) gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3,3), 10) img_sub = subtractor.apply(blur) dilate = cv2.dilate(img_sub, np.ones ((5,5))) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) dilated = cv2.morphologyEx(dilate, cv2. MORPH_CLOSE, kernel) dilated = cv2.morphologyEx(dilated, cv2. MORPH_CLOSE, kernel) contour, h = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.line(frame1, (25, pos_linha), (1900, pos_linha), (255,0,0), 3) for (i, c) in enumerate(contour): (x, y, w, h) = cv2.boundingRect(c) validate_contour = (w >= length_min) and (h >= height_min) if not validate_contour: continue cv2.rectangle(frame1, (x, y), (x + w, y + h), (0,255,0), 2) center = paste_center (x, y, w, h) detect.append(center) cv2.circle(frame1, center, 4, (0, 0.255), -1) cv2.putText(frame1,str(random.randint(1,200)),(x,y),cv2.FONT_HERSHEY_SIMPLEX, 1,(0,0,255),2) for (x, y) in detect: if y <(pos_linha + offset) and y> (pos_linha-offset): cars += 1 cv2.line(frame1, (25, pos_linha), (1200, pos_linha), (0,127,255), 3) cv2.putText(frame1, str (random.randint (1,200)), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2) detect.remove((x, y)) print("car is detected:" + str (cars)) cv2.putText(frame1, "Moran 11", (850, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 5) cv2.putText(frame1, str(cars), (1700, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 5) cv2.imshow("Surveillance Video", frame1) if cv2.waitKey (10) == 27: break cv2.destroyAllWindows () cap.release ()
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 640, 1330, 3993, 198, 11748, 4738, 198, 198, 13664, 62, 1084, 796, 4019, 1303, 26265, 4129, 286, 1005, 9248, 198, 17015, 62, 1084, 796, 4019, 1303, 26265, 6001, 286, 2...
2.006999
1,143
# -*- coding: utf-8 -*- import os.path from distutils.core import setup setup( name='django-db-prefix', version='1.0', keywords='django database', author=u'Ben Slavin <benjamin.slavin@gmail.com>, Denilson S <denilsonsa@gmail.com>', packages=['django_db_prefix'], url='https://github.com/denilsonsa/django-db-prefix', license='BSD licence, see LICENCE', description='Allow specification of a global, per-app or per-model database table name prefix.', long_description=read('README.md'), requires=[ 'Django', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Database', ] )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 13, 6978, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 628, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 28241, 14208, 12, 9945, 12, 40290, 3256, ...
2.567123
365
# -*- coding: utf-8 -*- from numpy import arcsin, arctan, cos, exp, array, angle, pi from numpy import imag as np_imag from scipy.optimize import fsolve from ....Classes.Segment import Segment from ....Classes.SurfLine import SurfLine from ....Classes.Arc1 import Arc1 from ....Methods import ParentMissingError from ....Functions.labels import HOLEV_LAB, HOLEM_LAB def build_geometry(self, alpha=0, delta=0, is_simplified=False): """Compute the curve (Segment) needed to plot the Hole. The ending point of a curve is the starting point of the next curve in the list Parameters ---------- self : HoleUD A HoleUD object alpha : float Angle to rotate the slot (Default value = 0) [rad] delta : complex Complex to translate the slot (Default value = 0) is_simplified : bool True to avoid line superposition (not used) Returns ------- surf_list: list List of SurfLine needed to draw the Hole """ surf_list = self.surf_list # Get correct label for surfaces lam_label = self.parent.get_label() R_id, surf_type = self.get_R_id() vent_label = lam_label + "_" + surf_type + "_R" + str(R_id) + "-T" mag_label = lam_label + "_" + HOLEM_LAB + "_R" + str(R_id) + "-T" # Update surface labels hole_id = 0 mag_id = 0 for surf in surf_list: if HOLEM_LAB in surf.label: key = "magnet_" + str(mag_id) if key in self.magnet_dict and self.magnet_dict[key] is not None: surf.label = mag_label + str(mag_id) + "-S0" mag_id += 1 else: # Magnet disabled or not defined surf.label = vent_label + str(hole_id) + "-S0" hole_id += 1 elif HOLEV_LAB in surf.label: surf.label = vent_label + str(hole_id) + "-S0" hole_id += 1 # Apply the transformations return_list = list() for surf in surf_list: return_list.append(surf.copy()) return_list[-1].rotate(alpha) return_list[-1].translate(delta) return return_list
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 299, 32152, 1330, 44606, 259, 11, 610, 310, 272, 11, 8615, 11, 1033, 11, 7177, 11, 9848, 11, 31028, 198, 6738, 299, 32152, 1330, 3590, 355, 45941, 62, 48466...
2.369369
888
''' Local DB Authentication module. .. moduleauthor:: Gerson Galang <gerson.galang@versi.edu.au> ''' import logging from django.contrib.auth.models import User, Group from django.contrib.auth.backends import ModelBackend from tardis.tardis_portal.auth.interfaces import AuthProvider, GroupProvider, UserProvider logger = logging.getLogger(__name__) auth_key = u'localdb' auth_display_name = u'Local DB' _modelBackend = ModelBackend() django_user = DjangoUserProvider.name django_group = DjangoGroupProvider.name
[ 7061, 6, 198, 14565, 20137, 48191, 8265, 13, 198, 198, 492, 8265, 9800, 3712, 402, 882, 5027, 648, 1279, 70, 882, 13, 13528, 648, 31, 690, 72, 13, 15532, 13, 559, 29, 198, 7061, 6, 198, 198, 11748, 18931, 198, 198, 6738, 42625, 14...
3.028736
174
import os import time from pathlib import Path from flask import Flask, jsonify, abort, request, Response, Request import concurrent.futures import threading import requests import logging import ast from urllib.parse import urlparse from flask import current_app as app from urllib3.exceptions import InsecureRequestWarning from yaml import safe_load # Local modules from elasticsearch.indexer import Indexer from libs.assay_type import AssayType # HuBMAP commons from hubmap_commons.hm_auth import AuthHelper # Set logging fromat and level (default is warning) # All the API logging is forwarded to the uWSGI server and gets written into the log file `uwsgo-entity-api.log` # Log rotation is handled via logrotate on the host system with a configuration file # Do NOT handle log file and rotation via the Python logging to avoid issues with multi-worker processes logging.basicConfig(format='[%(asctime)s] %(levelname)s in %(module)s:%(lineno)d: %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S') logger = logging.getLogger(__name__) # Specify the absolute path of the instance folder and use the config file relative to the instance path app = Flask(__name__, instance_path=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'instance'), instance_relative_config=True) app.config.from_pyfile('app.cfg') # load the index configurations and set the default INDICES = safe_load((Path(__file__).absolute().parent / 'instance/search-config.yaml').read_text()) DEFAULT_INDEX_WITHOUT_PREFIX = INDICES['default_index'] logger.debug("############ INDICES config LOADED") logger.debug(INDICES) # Remove trailing slash / from URL base to avoid "//" caused by config with trailing slash DEFAULT_ELASTICSEARCH_URL = INDICES['indices'][DEFAULT_INDEX_WITHOUT_PREFIX]['elasticsearch']['url'].strip('/') DEFAULT_ENTITY_API_URL = INDICES['indices'][DEFAULT_INDEX_WITHOUT_PREFIX]['document_source_endpoint'].strip('/') # Suppress InsecureRequestWarning warning when requesting status on https with ssl cert verify disabled requests.packages.urllib3.disable_warnings(category = InsecureRequestWarning) #################################################################################################### ## Register error handlers #################################################################################################### # Error handler for 400 Bad Request with custom error message # Error handler for 401 Unauthorized with custom error message # Error handler for 403 Forbidden with custom error message # Error handler for 500 Internal Server Error with custom error message #################################################################################################### ## AuthHelper initialization #################################################################################################### # Initialize AuthHelper class and ensure singleton try: if AuthHelper.isInitialized() == False: auth_helper_instance = AuthHelper.create(app.config['APP_CLIENT_ID'], app.config['APP_CLIENT_SECRET']) logger.info("Initialized AuthHelper class successfully :)") else: auth_helper_instance = AuthHelper.instance() except Exception: msg = "Failed to initialize the AuthHelper class" # Log the full stack trace, prepend a line with our message logger.exception(msg) #################################################################################################### ## Default route #################################################################################################### #################################################################################################### ## Assay type API #################################################################################################### #################################################################################################### ## API #################################################################################################### # Both HTTP GET and HTTP POST can be used to execute search with body against ElasticSearch REST API. # general search uses the DEFAULT_INDEX # Both HTTP GET and HTTP POST can be used to execute search with body against ElasticSearch REST API. # Note: the index in URL is not he real index in Elasticsearch, it's that index without prefix # HTTP GET can be used to execute search with body against ElasticSearch REST API. # HTTP GET can be used to execute search with body against ElasticSearch REST API. # Note: the index in URL is not he real index in Elasticsearch, it's that index without prefix # Get a list of indices # Get the status of Elasticsearch cluster by calling the health API # This shows the connection status and the cluster health status (if connected) # This reindex function will also reindex Collection and Upload # in addition to the Dataset, Donor, Sample entities # Live reindex without first deleting and recreating the indices # This just deletes the old document and add the latest document of each entity (if still available) #################################################################################################### ## Internal Functions Used By API #################################################################################################### # Throws error for 400 Bad Reqeust with message def bad_request_error(err_msg): abort(400, description = err_msg) # Throws error for 401 Unauthorized with message def unauthorized_error(err_msg): abort(401, description = err_msg) # Throws error for 403 Forbidden with message # Throws error for 500 Internal Server Error with message # Get user infomation dict based on the http request(headers) # `group_required` is a boolean, when True, 'hmgroupids' is in the output """ Parase the token from Authorization header Parameters ---------- request_headers: request.headers The http request headers admin_access_required : bool If the token is required to belong to the HuBMAP-Data-Admin group, default to False Returns ------- str The token string if valid """ """ Check if the user with token belongs to the HuBMAP-Data-Admin group Parameters ---------- request : falsk.request The flask http request object that containing the Authorization header with a valid Globus nexus token for checking group information Returns ------- bool True if the user belongs to HuBMAP-Data-Admin group, otherwise False """ """ Get user infomation dict based on the http request(headers) The result will be used by the trigger methods Parameters ---------- request : Flask request object The Flask request passed from the API endpoint Returns ------- dict A dict containing all the user info { "scope": "urn:globus:auth:scope:nexus.api.globus.org:groups", "name": "First Last", "iss": "https://auth.globus.org", "client_id": "21f293b0-5fa5-4ee1-9e0e-3cf88bd70114", "active": True, "nbf": 1603761442, "token_type": "Bearer", "aud": ["nexus.api.globus.org", "21f293b0-5fa5-4ee1-9e0e-3cf88bd70114"], "iat": 1603761442, "dependent_tokens_cache_id": "af2d5979090a97536619e8fbad1ebd0afa875c880a0d8058cddf510fc288555c", "exp": 1603934242, "sub": "c0f8907a-ec78-48a7-9c85-7da995b05446", "email": "email@pitt.edu", "username": "username@pitt.edu", "hmscopes": ["urn:globus:auth:scope:nexus.api.globus.org:groups"], } """ # Always expect a json body # We'll need to verify the requested index in URL is valid # Determine the target real index in Elasticsearch bases on the request header and given index (without prefix) # The Authorization header with globus token is optional # Case #1: Authorization header is missing, default to use the `hm_public_<index_without_prefix>`. # Case #2: Authorization header with valid token, but the member doesn't belong to the HuBMAP-Read group, direct the call to `hm_public_<index_without_prefix>`. # Case #3: Authorization header presents but with invalid or expired token, return 401 (if someone is sending a token, they might be expecting more than public stuff). # Case #4: Authorization header presents with a valid token that has the group access, direct the call to `hm_consortium_<index_without_prefix>`. # Make a call to Elasticsearch # Get the query string from orignal request # Get a list of entity uuids via entity-api for a given entity type: # Collection, Donor, Sample, Dataset, Submission. Case-insensitive. # Create a dict with HTTP Authorization header with Bearer token # Gets a list of actually public and private indice names # Get a list of filtered Elasticsearch indices to expose to end users without the prefix # For local development/testing if __name__ == "__main__": try: app.run(host='0.0.0.0', port="5005") except Exception as e: print("Error during starting debug server.") print(str(e)) logger.error(e, exc_info=True) print("Error during startup check the log file for further information")
[ 11748, 28686, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 15614, 11, 2581, 11, 18261, 11, 19390, 198, 11748, 24580, 13, 69, 315, 942, 198, 11748, 4704, 278, 198, 11748, 7007, ...
3.631056
2,518
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198 ]
3.777778
9
# -*- coding: utf-8 -*- # Copyright 2018 ukasz Wojniowicz <lukasz.wojnilowicz@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. import info from Package.AutoToolsPackageBase import * from Package.VirtualPackageBase import * if not CraftCore.compiler.isMSVC(): else:
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 2864, 334, 42749, 89, 370, 13210, 8461, 47982, 1279, 2290, 42749, 89, 13, 86, 13210, 45991, 47982, 31, 14816, 13, 785, 29, 198, 2, 198, 2, 2297, 396, 3890, ...
3.382883
444