content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# # Copyright (c) 2020, Neptune Labs Sp. z o.o. # # 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. # import os import neptune __all__ = [ 'log_audio', ] def log_audio(path_to_file, audio_name=None, experiment=None): """Logs audio file to 'artifacts/audio' with player. Logs audio file to the 'artifacts/audio' in the experiment, where you can play it directly from the browser. You can also download raw audio file to the local machine. Just use "three vertical dots" located to the right from the player. Args: path_to_file (:obj:`str`): Path to audio file. audio_name (:obj:`str`, optional, default is ``None``): Name to be displayed in artifacts/audio. | If `None`, file name is used. experiment (:obj:`neptune.experiments.Experiment`, optional, default is ``None``): | For advanced users only. Pass Neptune `Experiment <https://docs.neptune.ai/neptune-client/docs/experiment.html#neptune.experiments.Experiment>`_ object if you want to control to which experiment data is logged. | If ``None``, log to currently active, and most recent experiment. Example: .. code:: python3 log_audio('audio-file.wav') log_audio('/full/path/to/some/other/audio/file.mp3') log_audio('/full/path/to/some/other/audio/file.mp3', 'my_audio') Note: Check out how the logged audio file looks in Neptune: `here <https://ui.neptune.ai/o/shared/org/showroom/e/SHOW-1485/artifacts?path=audio%2F>`_. """ import base64 from io import StringIO _exp = experiment if experiment else neptune name, file_ext = os.path.split(path_to_file)[1].split('.') if audio_name is None: audio_name = name else: assert isinstance(audio_name, str), 'audio_name must be string, got {}'.format(type(audio_name)) encoded_sound = base64.b64encode(open(path_to_file, 'rb').read()) html = """<!DOCTYPE html> <html> <body> <audio controls> <source src='data:audio/{};base64,{}'> </audio> </body> </html>""".format(file_ext, encoded_sound.decode()) buffer = StringIO(html) buffer.seek(0) _exp.log_artifact(buffer, 'audio/{}.html'.format(audio_name))
[ 2, 198, 2, 15069, 357, 66, 8, 12131, 11, 26461, 23500, 1338, 13, 1976, 267, 13, 78, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, ...
2.647225
1,063
from pydantic import BaseModel
[ 6738, 279, 5173, 5109, 1330, 7308, 17633, 628 ]
4
8
#This code and description is written by Hoplin #This code is written with API version 1.0.0(Rewirte-V) #No matter to use it as non-commercial. import discord import asyncio import os from discord.ext import commands import urllib from urllib.request import URLError from urllib.request import HTTPError from urllib.request import urlopen from urllib.request import Request, urlopen from bs4 import BeautifulSoup from urllib.parse import quote import re # Regex for youtube link import warnings import requests import unicodedata import json import time token = '' client = discord.Client() @client.event # Use these decorator to register an event. @client.event client.run(token)
[ 2, 1212, 2438, 290, 6764, 318, 3194, 416, 9996, 2815, 198, 2, 1212, 2438, 318, 3194, 351, 7824, 2196, 352, 13, 15, 13, 15, 7, 30003, 343, 660, 12, 53, 8, 198, 2, 2949, 2300, 284, 779, 340, 355, 1729, 12, 36313, 13, 198, 198, 1...
3.48731
197
""" Created on Dec 8, 2017 @author: nhan.nguyen Verify that user can close a reopened pool ledger. """ from indy import pool from utilities import utils from utilities import common, constant from test_scripts.functional_tests.pool.pool_test_base import PoolTestBase import pytest
[ 37811, 198, 41972, 319, 4280, 807, 11, 2177, 198, 198, 31, 9800, 25, 299, 7637, 13, 782, 4669, 268, 198, 13414, 1958, 326, 2836, 460, 1969, 257, 37415, 5933, 37208, 13, 198, 37811, 198, 198, 6738, 773, 88, 1330, 5933, 198, 6738, 200...
3.594937
79
from keras.engine.topology import Layer from keras import backend as K import tensorflow as tf import numpy as np import random import math import ComplexTensor as ct # This layer represets a power series # a_0*I+a_1*X+a_2*X^2+...+a_n*X^n # Where X is a complex input matrix, and the coefficients a_n are complex. # The optimized weights of this layer are the coefficients. # Input shape: [?(batch_size), 2(0=real\1=imag), n, n] (n is the size of input matrices) # Output shape: same as input MPS = MatrixPowerSeriesLayer # This layer represets a power series # A_0*I + A_1*X + A_2*X^2 + ... + A_n*X^n # Where X is a complex input matrix, and the coefficients A_n are complex matrices. # The optimized weights of this layer are the coefficients MMPS = MatrixMPowerSeriesLayer # This layer represets a power series # A_0*I*B_0 + A_1*X*B_1 + A_2*X^2*B_2 + ... + A_n*X^n*B_n # Where X is a complex input matrix, and the coefficients A_n, B_n are complex matrices. # The optimized weights of this layer are the coefficients MM2PS = MatrixM2PowerSeriesLayer # This is the same as MatrixPowerSeriesLayer, only for multiple channels of input and output. # Input shape: [?(batch_size), k(input channels), 2(0=real\1=imag), n, n] # Output shape: [?(batch_size), j(output channel), k(input channels), 2(0=real\1=imag), n, n] # Calculates the same computations for every input channel in parallel MchMPS = MultichannelMatrixPowerSeriesLayer # This is the same as MatrixMPowerSeriesLayer, only for multiple channels of input and output MchMMPS = MultichannelMatrixMPowerSeriesLayer # This is the same as MatrixM2PowerSeriesLayer, only for multiple channels of input and output MchMM2PS = MultichannelMatrixM2PowerSeriesLayer
[ 198, 6738, 41927, 292, 13, 18392, 13, 4852, 1435, 1330, 34398, 198, 6738, 41927, 292, 1330, 30203, 355, 509, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 11748, 10688, 198, 198, 1...
3.096601
559
# @author Tasuku Miura # @brief Training for controller to output steering and throttle commands given # an image taken from a monocular camera. (Assumes CUDA enabled) # python train.py --root-dir /home/ubuntu/ws/amr_core/model_sandbox/model_nn_controller_service/data # put images and pickle file in ./data # TODO: save model and reload model, test with ROS package # http://pytorch.org/docs/master/notes/serialization.html#recommend-saving-models import os import pickle import argparse from skimage import io, transform import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader, ConcatDataset from torch.utils.data.sampler import SubsetRandomSampler from torchvision import transforms, utils from data_loader import * from transforms import * import models import utils # used for logging to TensorBoard from tensorboard_logger import configure, log_value if __name__ == "__main__": parser = argparse.ArgumentParser(description='NN Controller') parser.add_argument('--root-dir', type=str, default='.', help='path to root') parser.add_argument('--ckpt-file-name', type=str, default='checkpoint.pth.tar', help='name of checkpoint file') parser.add_argument('--train-data', type=str, default='predictions.pickle', help='filename containing train data') parser.add_argument('--train-valid-split', type=float, default='0.2', help='x% valid split') parser.add_argument('--batch-size', type=int, default=32, metavar='N', help='input batch size for training (default: 32)') parser.add_argument('--valid-batch-size', type=int, default=32, metavar='N', help='input batch size for validation (default: 32)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=0, metavar='S', help='random seed (default: 0)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') args = parser.parse_args() main(args)
[ 2, 2488, 9800, 24932, 33263, 13756, 5330, 198, 2, 2488, 65, 3796, 13614, 329, 10444, 284, 5072, 19702, 290, 29976, 9729, 1813, 198, 2, 281, 2939, 2077, 422, 257, 937, 37320, 4676, 13, 357, 8021, 8139, 29369, 5631, 9343, 8, 198, 2, 2...
2.646751
954
class SynthError(Exception): """ Generic error raised by library. """ pass class SynthValidationError(SynthError): """ Raised on attribute validation failure. """ pass
[ 4871, 16065, 400, 12331, 7, 16922, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 42044, 4049, 4376, 416, 5888, 13, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1208, 628, 198, 4871, 16065, 400, 7762, 24765, 12331, 7, 29934, ...
2.805556
72
__all__ = ['observing_bands'] import astropy.units as u observing_bands = { 'U' : (365*u.nm, 66*u.nm), 'B' : (445*u.nm, 94*u.nm), 'G' : (464*u.nm, 128*u.nm), 'V' : (551*u.nm, 88*u.nm), 'R' : (658*u.nm, 138*u.nm), 'I' : (806*u.nm, 149*u.nm), 'Y' : (1020*u.nm, 120*u.nm), 'J' : (1220*u.nm, 213*u.nm), 'H' : (1630*u.nm, 307*u.nm), 'K' : (2190*u.nm, 390*u.nm), 'L' : (3450*u.nm, 472*u.nm), }
[ 834, 439, 834, 796, 37250, 672, 31293, 62, 21397, 20520, 198, 198, 11748, 6468, 28338, 13, 41667, 355, 334, 198, 198, 672, 31293, 62, 21397, 796, 1391, 198, 220, 220, 220, 705, 52, 6, 1058, 357, 24760, 9, 84, 13, 21533, 11, 7930, ...
1.625468
267
import GlobalVariables import Character, Enemies, Encounters import AdventureMap import Actions import gui import NPCs import tkinter import Conditions # Will change to initialize to 'None' after more testing and whatnot is done # GlobalVariables.PC = Character.Rogue() # GlobalVariables.Enemy = Enemies.Chimera() # Resets the game # Each .py file should have a reset function that gets called here if (__name__ == "__main__"): main()
[ 11748, 8060, 23907, 2977, 201, 198, 11748, 15684, 11, 24364, 11, 14711, 15044, 201, 198, 11748, 9553, 13912, 201, 198, 11748, 24439, 201, 198, 11748, 11774, 201, 198, 11748, 28167, 201, 198, 201, 198, 11748, 256, 74, 3849, 201, 198, 117...
3.253521
142
from .providers import load_world, load_vehicle
[ 6738, 764, 15234, 4157, 1330, 3440, 62, 6894, 11, 3440, 62, 33892, 1548, 198 ]
3.428571
14
""" Sense manipulations following the framework of the STARLING package. """ # import networkx as nx from pysem.data import SENSE from collections import defaultdict
[ 37811, 198, 41166, 7704, 5768, 1708, 262, 9355, 286, 262, 25424, 43, 2751, 5301, 13, 198, 37811, 198, 2, 1330, 3127, 87, 355, 299, 87, 198, 6738, 12972, 43616, 13, 7890, 1330, 311, 24290, 198, 6738, 17268, 1330, 4277, 11600, 628 ]
4.073171
41
from tkinter import Frame, Label from tkinter import StringVar from tkinter import N, Y, SW, SE from widgetclasses.MyLabelFrame import MyLabelFrame from widgetclasses.MyOptionMenu import MyOptionMenu from widgetclasses.MyButton import MyButton from widgetclasses.MyLabel import MyLabel from widgetclasses.DoubleScrolledFrame import DoubleScrolledFrame from widgetclasses.MyEntry import MyEntry from helpermodules.MyFonts import FONTS import pages.ProcessVariables as ProcessVariables import pages.PreviewVariables as PreviewVariables import JSON_Test_Case_Generator
[ 6738, 256, 74, 3849, 1330, 25184, 11, 36052, 198, 6738, 256, 74, 3849, 1330, 10903, 19852, 198, 6738, 256, 74, 3849, 1330, 399, 11, 575, 11, 12672, 11, 7946, 628, 198, 6738, 26295, 37724, 13, 3666, 33986, 19778, 1330, 2011, 33986, 197...
3.748387
155
n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) m = (n1 + n2)/2 print('A média do aluno é {:.2f}'.format(m))
[ 77, 16, 796, 12178, 7, 15414, 10786, 3673, 64, 352, 25, 705, 4008, 198, 77, 17, 796, 12178, 7, 15414, 10786, 3673, 64, 362, 25, 705, 4008, 198, 76, 796, 357, 77, 16, 1343, 299, 17, 20679, 17, 198, 4798, 10786, 32, 285, 2634, 67,...
2
60
import argparse import os import torch from torch.utils.data import DataLoader import torch.nn as nn import torch.nn.functional as F from dataset import ASVspoof2019 from evaluate_tDCF_asvspoof19 import compute_eer_and_tdcf from tqdm import tqdm import eval_metrics as em import numpy as np if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-m', '--model_dir', type=str, help="path to the trained model", default="./models/ocsoftmax") parser.add_argument('-l', '--loss', type=str, default="ocsoftmax", choices=["softmax", 'amsoftmax', 'ocsoftmax'], help="loss function") parser.add_argument("--gpu", type=str, help="GPU index", default="0") args = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu args.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") test(args.model_dir, args.loss, args.device) # eer_cm_lst, min_tDCF_lst = test_individual_attacks(os.path.join(args.model_dir, 'checkpoint_cm_score.txt')) # print(eer_cm_lst) # print(min_tDCF_lst)
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 27039, 1330, 7...
2.600939
426
# utilities to generate molecules with this repo. # v1. Dec 2020, F. Grisoni
[ 2, 20081, 284, 7716, 17745, 351, 428, 29924, 13, 198, 2, 410, 16, 13, 4280, 12131, 11, 376, 13, 1902, 1653, 72, 628 ]
3.391304
23
import base64 import json import logging import base58 from forge_sdk import protos as forge_protos from forge_sdk import utils as forge_utils logger = logging.getLogger('model-mobile')
[ 11748, 2779, 2414, 198, 11748, 33918, 198, 11748, 18931, 198, 198, 11748, 2779, 3365, 198, 6738, 28325, 62, 21282, 74, 1330, 1237, 418, 355, 28325, 62, 11235, 418, 198, 198, 6738, 28325, 62, 21282, 74, 1330, 3384, 4487, 355, 28325, 62, ...
3.275862
58
# coding: utf-8 import os from os.path import join, dirname from sympy import Symbol, Lambda, Function, Dummy from sympy import Tuple, IndexedBase from sympy.core.function import AppliedUndef from sympy.core.function import UndefinedFunction from sympy import Integer, Float from sympy import sympify from sympy import FunctionClass from pyccel.codegen.utilities import random_string from pyccel.ast.utilities import build_types_decorator from pyccel.ast.datatypes import Int, Real, Complex, Bool from pyccel.ast.core import Slice from pyccel.ast.core import Variable, FunctionDef, Assign, AugAssign from pyccel.ast.core import Return from pyccel.ast.basic import Basic from .datatypes import assign_type, BasicTypeVariable from .datatypes import TypeVariable, TypeTuple, TypeList, TypeFunction from .lexeme import _internal_map_functors from .lexeme import _internal_functors from .lexeme import _internal_zip_functions from .lexeme import _internal_product_functions from .lexeme import _internal_applications from .lexeme import _elemental_math_functions from .lexeme import _math_vector_functions from .lexeme import _math_matrix_functions from .lexeme import _math_functions from .ast import Map, ProductMap, TensorMap, Zip, Product from .ast import BasicReduce, AddReduce, MulReduce from .ast import BasicMap from .ast import PartialFunction from .ast import LampyLambda from .ast import FunctionSymbol #========================================================================= #========================================================================= # TODO add some verifications before starting annotating L
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 11, 26672, 3672, 198, 198, 6738, 10558, 88, 1330, 38357, 11, 21114, 6814, 11, 15553, 11, 360, 13513, 198, 6738, 10558, 88, 1330, 309, 29...
3.353175
504
import pytest
[ 11748, 12972, 9288, 628 ]
3.75
4
import argparse import os from multiprocessing.pool import ThreadPool from utils.backend import HikeDBClient, update_db from utils.combine_gpx import CombineGpx from utils.gpx_import import GpxImport from utils.plotting import plot_elevation, plot_coordinates, plot_heart_rate from utils.report import render_html GPX = "GPX" if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 28686, 198, 6738, 18540, 305, 919, 278, 13, 7742, 1330, 14122, 27201, 198, 198, 6738, 3384, 4487, 13, 1891, 437, 1330, 367, 522, 11012, 11792, 11, 4296, 62, 9945, 198, 6738, 3384, 4487, 13, 24011, 500, ...
2.991935
124
from .augmentation_factory import * from .blur import Blur, RandomBlur, RandomGaussianBlur from .mirror import Mirror, RandomMirror from .crop import RandomCrop, CentreCrop from .normalize import Normalize, NormalizeDpn, NormalizeLe, NormalizeTorchvision from .colour import RandomBrightnessContrast, RandomSaturation from .shift import RandomShift from .affine import Affine
[ 6738, 764, 559, 5154, 341, 62, 69, 9548, 1330, 1635, 198, 6738, 764, 2436, 333, 1330, 1086, 333, 11, 14534, 3629, 333, 11, 14534, 35389, 31562, 3629, 333, 198, 6738, 764, 10793, 1472, 1330, 17918, 11, 14534, 27453, 1472, 198, 6738, 76...
3.640777
103
from abc import abstractmethod from enum import Enum from typing import List, Type from tales.components import Component from tales.entities.entity import Entity from tales.world import World
[ 6738, 450, 66, 1330, 12531, 24396, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 7343, 11, 5994, 198, 198, 6738, 19490, 13, 5589, 3906, 1330, 35100, 198, 6738, 19490, 13, 298, 871, 13, 26858, 1330, 20885, 198, 6738, 19490, ...
4.170213
47
import unittest class AggregateTestCase(unittest.TestCase): """Tests for class ``Aggregate``. """ @classmethod def setUpClass(cls): """Set up the class fixture. """ from ugentaggregates.aggregates import Aggregate cls.Aggregate = Aggregate def setUp(self): """Set up the fixture. """ self.aggr1 = self.Aggregate() def tearDown(self): """Tear down the fixture. """ self.aggr1 = None def test_creation(self): """Test for creating an ``Aggregate`` object. """ self.assertTrue(isinstance(self.aggr1, self.Aggregate)) def test_callable(self): """Test for calling an ``Aggregate`` object. """ with self.assertRaises(NotImplementedError): self.aggr1("field1", []) class FirstAggregateTestCase(unittest.TestCase): """Tests for class ``FirstAggregate``. """ @classmethod def setUpClass(cls): """Set up the class fixture. """ from ugentaggregates.aggregates import Aggregate from ugentaggregates.aggregates import FirstAggregate from ugentaggregates.aggregates import NO_DEFAULT cls.Aggregate = Aggregate cls.FirstAggregate = FirstAggregate cls.NO_DEFAULT = NO_DEFAULT def test_creation(self): """Test for creating a ``FirstAggregate`` object. """ aggr1 = self.FirstAggregate() self.assertTrue(isinstance(aggr1, self.FirstAggregate)) def test_inheritance(self): """Test for the inheritance of class ``FirstAggregate``. """ self.assertTrue(issubclass(self.FirstAggregate, self.Aggregate)) def test_callable(self): """Test for calling a ``FirstAggregate`` object. """ aggr1 = self.FirstAggregate() self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 2}]), 1) self.assertEqual(aggr1("field1", [{"field2": 1}, {"field1": 2}]), 2) def test_missing(self): """Test for calling a ``FirstAggregate`` object for a missing attribute. """ aggr1 = self.FirstAggregate() with self.assertRaises(AttributeError): aggr1("field1", [{"field2": 1}, {"field2": 2}]) def test_empty(self): """Test for calling a ``FirstAggregate`` object with an empty list. """ aggr1 = self.FirstAggregate() with self.assertRaises(AttributeError): aggr1("field1", []) def test_name(self): """Test for the attribute ``name`. """ aggr1 = self.FirstAggregate(name="field1") self.assertEqual(aggr1.name, "field1") self.assertEqual(aggr1("field2", [{"field1": 1, "field2": 2}]), 1) def test_valid(self): """Test for the attribute ``valid``. """ is_even = lambda i: i % 2 == 0 aggr1 = self.FirstAggregate(valid=is_even) self.assertEqual(aggr1.valid, is_even) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 2}]), 2) self.assertEqual(aggr1("field1", [{"field1": 2}, {"field1": 4}]), 2) def test_format(self): """Test for the attribute ``format``. """ double = lambda i: i * 2 aggr1 = self.FirstAggregate(format=double) self.assertEqual(aggr1.format, double) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 2}]), 2) def test_default(self): """Test for the attribute ``default``. """ # Without default. aggr1 = self.FirstAggregate() self.assertEqual(aggr1.default, self.NO_DEFAULT) # With default. aggr2 = self.FirstAggregate(default=-1) self.assertEqual(aggr2.default, -1) self.assertEqual(aggr2("field1", []), -1) self.assertEqual(aggr2("field1", [{"field2": 1}, {"field2": 2}]), -1) def test_callable_value(self): """Test for callable values. """ aggr1 = self.FirstAggregate() self.assertEqual(aggr1("field1", [{"field1": lambda: 1}, {"field1": 2}]), 1) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": lambda: 2}]), 1) class AllAggregateTestCase(unittest.TestCase): """Tests for class ``AllAggregate``. """ @classmethod def setUpClass(cls): """Set up the class fixture. """ from ugentaggregates.aggregates import Aggregate from ugentaggregates.aggregates import AllAggregate cls.Aggregate = Aggregate cls.AllAggregate = AllAggregate def test_creation(self): """Test for creating a ``AllAggregate`` object. """ aggr1 = self.AllAggregate() self.assertTrue(isinstance(aggr1, self.AllAggregate)) def test_inheritance(self): """Test for the inheritance of class ``AllAggregate``. """ self.assertTrue(issubclass(self.AllAggregate, self.Aggregate)) def test_callable(self): """Test for calling an ``AllAggregate`` object. """ aggr1 = self.AllAggregate() self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 2}]), [1, 2]) self.assertEqual(aggr1("field1", [{"field2": 1}, {"field1": 2}]), [2]) def test_list(self): """Test for calling an ``AllAggregate`` object with list attributes. """ aggr1 = self.AllAggregate() self.assertEqual(aggr1("field1", [{"field1": [1, 2]}, {"field1": [3, 4]}]), [1, 2, 3, 4]) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": [2, 3]}]), [1, 2, 3]) self.assertEqual(aggr1("field1", [{"field1": [1, 2]}, {"field1": 3}]), [1, 2, 3]) def test_missing(self): """Test for calling an ``AllAggregate`` object for a missing attribute. """ aggr1 = self.AllAggregate() self.assertEqual(aggr1("field1", [{"field2": 1}, {"field2": 2}]), []) def test_empty(self): """Test for calling an ``AllAggregate`` object with an empty list. """ aggr1 = self.AllAggregate() self.assertEqual(aggr1("field1", []), []) def test_name(self): """Test for the attribute ``name`. """ aggr1 = self.AllAggregate(name="field1") self.assertEqual(aggr1.name, "field1") self.assertEqual(aggr1("field2", [{"field1": 1, "field2": 2}, {"field1": 3, "field2": 4}]), [1, 3]) def test_valid(self): """Test for the attribute ``valid``. """ is_even = lambda i: i % 2 == 0 aggr1 = self.AllAggregate(valid=is_even) self.assertEqual(aggr1.valid, is_even) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 2}]), [2]) self.assertEqual(aggr1("field1", [{"field1": 2}, {"field1": 4}]), [2, 4]) def test_format(self): """Test for the attribute ``format``. """ double = lambda i: i * 2 aggr1 = self.AllAggregate(format=double) self.assertEqual(aggr1.format, double) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 2}]), [2, 4]) def test_unique(self): """Test for the attribute ``unique``. """ # Unique is false. aggr1 = self.AllAggregate() self.assertEqual(aggr1.unique, False) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": 1}]), [1, 1]) # Unique is true. aggr2 = self.AllAggregate(unique=True) self.assertEqual(aggr2.unique, True) self.assertEqual(aggr2("field1", [{"field1": 1}, {"field1": 1}]), [1]) def test_callable_value(self): """Test for callable values. """ aggr1 = self.AllAggregate() self.assertEqual(aggr1("field1", [{"field1": lambda: 1}, {"field1": 2}]), [1, 2]) self.assertEqual(aggr1("field1", [{"field1": 1}, {"field1": lambda: 2}]), [1, 2])
[ 11748, 555, 715, 395, 628, 198, 4871, 19015, 49373, 14402, 20448, 7, 403, 715, 395, 13, 14402, 20448, 2599, 198, 220, 220, 220, 37227, 51, 3558, 329, 1398, 7559, 46384, 49373, 15506, 13, 198, 220, 220, 220, 37227, 628, 220, 220, 220, ...
1.837051
5,155
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.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. # This module is combined from the following sources: # https://github.com/paramiko/paramiko/blob/master/demos/interactive.py@c091e756084ce017d8d872ffeaf95422f79140f1 # https://github.com/sirosen/paramiko-shell/blob/master/interactive_shell.py@5a743a4e1eccff2d88b273aa108d0d1bb7268771 # Corresponding license notices are available in the respective repositories from __future__ import print_function import paramiko import sys import os import re import select import socket import shutil from paramiko.py3compat import u DEFAULT_TERMINAL_COLUMNS = 100 DEFAULT_TERMINAL_LINES = 30 PYTHON3 = sys.version_info.major == 3 try: import termios import tty has_termios = True except ImportError: has_termios = False # Python < 3.4 does not have shutil.get_terminal_size # If it's the case - use stty in posix and a fallback in Windows
[ 2, 15069, 2177, 12, 23344, 14724, 2390, 11998, 11, 3457, 13, 357, 5450, 1378, 2503, 13, 538, 321, 13, 785, 34729, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 74...
3.162338
462
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from cgxsh_lib.file_crypto import edit_config_file if __name__ == '__main__': sys.exit(edit_config_file())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 25064, 198, 198, 6738, 269, 70, 87, 1477, 62, 8019, 13, 7753, 62, 29609, 78, 1330, 4370, 62, 11250, 62, ...
2.342466
73
# Generated by Django 2.1.4 on 2019-01-23 20:41 from django.conf import settings from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 19, 319, 13130, 12, 486, 12, 1954, 1160, 25, 3901, 201, 198, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 201, ...
2.804348
46
""" Configurables for Transformer """ from transformer_2.utils.config_system import ConfigSystem __all__ = ['make_config'] _C = ConfigSystem(validate_config_fn=validate_config) # --------------------------------------------------------------------------- # # Start of configs # --------------------------------------------------------------------------- # # Required # The vocab size of the encoder language # Should be the number of tokens including <bos> <pad> <eos> <unk> _C.encoder_vocab_size = None # Required # The index of the padding token _C.encoder_padding_idx = None # The size of the token/positional embeddings for the encoder _C.encoder_embed_dim = 512 # The size of the hidden states embeddings in the encoder _C.encoder_hidden_dim = 512 # The size of the hidden states in the encoder transistor _C.encoder_transistor_dim = 1024 # The number of multi-head attention layers _C.encoder_num_layers = 6 # The number of heads in multi-head attention _C.encoder_num_heads = 4 # Should bias be used in the encoder _C.encoder_use_bias = True # The number of positional embeddings to use _C.encoder_max_positions = 1024 # Should positional embeddings not be used? _C.encoder_no_pos_embeds = False # Should positional embeddings be learned? Default uses sinusoidal _C.encoder_learned_pos_embeds = False # Required # The vocab size of the decoder language # Should be the number of tokens including <bos> <pad> <eos> <unk> _C.decoder_vocab_size = None # Required # The index of the padding token _C.decoder_padding_idx = None # The size of the token/positional embeddings for the encoder _C.decoder_embed_dim = 512 # The size of the hidden states embeddings in the decoder _C.decoder_hidden_dim = 512 # The size of the hidden states in the decoder transistor _C.decoder_transistor_dim = 1024 # The number of multi-head attention layers _C.decoder_num_layers = 6 # The number of heads in multi-head attention _C.decoder_num_heads = 4 # Should bias be used in the decoder _C.decoder_use_bias = True # The number of positional embeddings to use _C.decoder_max_positions = 1024 # Should positional embeddings not be used? _C.decoder_no_pos_embeds = False # Should positional embeddings be learned? Default uses sinusoidal _C.decoder_learned_pos_embeds = False # Should the decoder not attend to the encoder? Default the # decoder will attend to the encoder. _C.decoder_no_encoder_attn = False # Dropout probability _C.dropout = 0.0 # Dropout probability for attention weights _C.attn_dropout = 0.0 # Dropout probability after attention in transistor _C.activation_dropout = 0.0 # Activation function to use in transistor _C.activation_fn = 'relu' # Should layer norm be applied before multi-headed attention? # Default is before _C.normalize_before = True # Should encoder input embeddings, decoder input embeddings and decoder output # embeddings be the same tensor? _C.share_all_embeddings = False # Should decoder input and output embeddings be the same tensor? _C.share_decoder_input_output_embed = True # --------------------------------------------------------------------------- # # End of configs # --------------------------------------------------------------------------- # _C.immutable(True) make_config = _C.make_config
[ 37811, 198, 16934, 333, 2977, 329, 3602, 16354, 198, 37811, 198, 198, 6738, 47385, 62, 17, 13, 26791, 13, 11250, 62, 10057, 1330, 17056, 11964, 198, 198, 834, 439, 834, 796, 37250, 15883, 62, 11250, 20520, 628, 198, 198, 62, 34, 796, ...
3.349385
976
from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django import forms from django.utils.safestring import mark_safe from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from .models import User, Category, Auction, Bid, Comment, Watchlist from .forms import CreateForm, CommentForm, BidForm, SearchForm @login_required(redirect_field_name='') @login_required(redirect_field_name='') @login_required(redirect_field_name='') @login_required(redirect_field_name='') @login_required(redirect_field_name='') @login_required(redirect_field_name='') @login_required(redirect_field_name='') @login_required(redirect_field_name='')
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 8323, 5344, 11, 17594, 11, 2604, 448, 198, 6738, 42625, 14208, 13, 9945, 1330, 39348, 12331, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 11, 367, 29281, 31077, 7738, 10...
3.019417
309
number1 = 10 number2 = 20 number4 = 40 number3 = 30
[ 17618, 16, 796, 838, 198, 17618, 17, 796, 1160, 198, 198, 17618, 19, 796, 2319, 198, 198, 17618, 18, 796, 1542, 628 ]
2.5
22
#!/usr/bin/env python3 import rospy import math from arduinobot_controller.srv import AnglesConverter, AnglesConverterResponse """ arduinobot - angles_converter This script implements two services on the topics - radians_to_degrees - degrees_to_radians Both of them receives a request with the format: float64 base float64 shoulder float64 elbow float64 gripper and sends a response in the same format to the client The first service (radians_to_degrees) receives the angles in radians and convert those in degrees according to the boundaries defined inthe URDF file The second service (degrees_to_radians) receives the angles in degrees and convert those in radians according to the boundaries defined inthe URDF file This conversion is needed for the control of the real robot in order to convert the radians angle of each joint as used in ROS in degrees angles as used in Arduino for the actuation of the Servo motors Copyright (c) 2021 Antonio Brandi. All right reserved. """ if __name__ == "__main__": # Inizialize a ROS node called angles_converter rospy.init_node('angles_converter') # Inizialize two services for the angle conversions radians_to_degrees = rospy.Service('radians_to_degrees', AnglesConverter, convert_radians_to_degrees) degrees_to_radians = rospy.Service('degrees_to_radians', AnglesConverter, convert_degrees_to_radians) # keeps the node up and running rospy.spin()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 686, 2777, 88, 198, 11748, 10688, 198, 6738, 50065, 259, 672, 313, 62, 36500, 13, 27891, 85, 1330, 2895, 829, 3103, 332, 353, 11, 2895, 829, 3103, 332, 353, 31077, 198, 19...
3.269316
453
from primitiv import optimizers as O from primitiv import Optimizer, Parameter, Device, Graph, Shape from primitiv import initializers as I from primitiv import devices as D from primitiv import functions as F from primitiv import tensor_functions as tF import unittest import tempfile import numpy as np
[ 6738, 2684, 270, 452, 1330, 6436, 11341, 355, 440, 198, 6738, 2684, 270, 452, 1330, 30011, 7509, 11, 25139, 2357, 11, 16232, 11, 29681, 11, 25959, 198, 6738, 2684, 270, 452, 1330, 4238, 11341, 355, 314, 198, 6738, 2684, 270, 452, 1330...
3.516854
89
import gym from gym.envs.box2d import CarRacing from stable_baselines.common.policies import CnnPolicy from stable_baselines.common.vec_env import DummyVecEnv from stable_baselines import PPO2 if __name__ == '__main__': env = lambda : CarRacing( grayscale=1, show_info_panel=0, discretize_actions="hard", frames_per_state=4, num_lanes=1, num_tracks=1, ) env = DummyVecEnv([env]) model = PPO2('MlpPolicy', env, verbose=1, tensorboard_log='tensor_logs/ppo') model.learn(total_timesteps=200000) model.save('learned_models/car_racing_weights_200k')
[ 11748, 11550, 198, 6738, 11550, 13, 268, 14259, 13, 3524, 17, 67, 1330, 1879, 49, 4092, 198, 198, 6738, 8245, 62, 12093, 20655, 13, 11321, 13, 79, 4160, 444, 1330, 327, 20471, 36727, 198, 6738, 8245, 62, 12093, 20655, 13, 11321, 13, ...
2.234043
282
from rest_framework import permissions from rest_framework.permissions import BasePermission
[ 6738, 1334, 62, 30604, 1330, 21627, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 7308, 5990, 3411, 628 ]
4.947368
19
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development 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. # ============================================================================== """The model write audio sample to wav file.""" import tensorflow as tf from athena.utils.hparam import HParams from athena.transform.feats.base_frontend import BaseFrontend class WriteWav(BaseFrontend): """ Encode audio data (input) using sample rate (input), return a write wav opration. """ @classmethod def params(cls, config=None): """ Set params. :param config: contains one optional parameters:sample_rate(int, default=16000). :return: An object of class HParams, which is a set of hyperparameters as name-value pairs. """ sample_rate = 16000 hparams = HParams(cls=cls) hparams.add_hparam('sample_rate', sample_rate) if config is not None: hparams.override_from_dict(config) return hparams def call(self, filename, audio_data, sample_rate): """ Write wav using audio_data[tensor]. :param filename: filepath of wav. :param audio_data: a tensor containing data of a wav. :param sample_rate: the samplerate of the signal we working with. :return: write wav opration. """ filename = tf.constant(filename) with tf.name_scope('writewav'): audio_data = tf.cast(audio_data, dtype=tf.float32) contents = tf.audio.encode_wav( tf.expand_dims(audio_data, 1), tf.cast(sample_rate, dtype=tf.int32)) w_op = tf.io.write_file(filename, contents) return w_op
[ 2, 15069, 357, 34, 8, 2177, 11618, 7731, 72, 22385, 8987, 290, 7712, 1766, 1539, 43, 8671, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198...
2.993017
716
# # A template class representing the interactions that the end-user has # with the filesystem in a z-machine. # # Third-party programs are expected to subclass ZFilesystem and # override all the methods, then pass an instance of their class to be # driven by the main z-machine engine. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZFilesystem(object): """Encapsulates the interactions that the end-user has with the filesystem.""" def save_game(self, data, suggested_filename=None): """Prompt for a filename (possibly using suggested_filename), and attempt to write DATA as a saved-game file. Return True on success, False on failure. Note that file-handling errors such as 'disc corrupt' and 'disc full' should be reported directly to the player by the method in question method, and they should also cause this function to return False. If the user clicks 'cancel' or its equivalent, this function should return False.""" raise NotImplementedError() def restore_game(self): """Prompt for a filename, and return file's contents. (Presumably the interpreter will attempt to use those contents to restore a saved game.) Returns None on failure. Note that file-handling errors such as 'disc corrupt' and 'disc full' should be reported directly to the player by the method in question method, and they should also cause this function to return None. The error 'file not found' should cause this function to return None. If the user clicks 'cancel' or its equivalent, this function should return None.""" raise NotImplementedError() def open_transcript_file_for_writing(self): """Prompt for a filename in which to save either a full game transcript or just a list of the user's commands. Return standard python file object that can be written to. If an error occurs, or if the user clicks 'cancel' or its equivalent, return None.""" raise NotImplementedError() def open_transcript_file_for_reading(self): """Prompt for a filename contain user commands, which can be used to drive the interpreter. Return standard python file object that can be read from. If an error occurs, or if the user clicks 'cancel' or its equivalent, return None.""" raise NotImplementedError()
[ 2, 198, 2, 317, 11055, 1398, 10200, 262, 12213, 326, 262, 886, 12, 7220, 468, 198, 2, 351, 262, 29905, 287, 257, 1976, 12, 30243, 13, 198, 2, 198, 2, 10467, 12, 10608, 4056, 389, 2938, 284, 47611, 1168, 25876, 6781, 290, 198, 2, ...
3.598201
667
#!/usr/bin/python import sys import os.path from functools import wraps from flask import Flask, g, render_template, redirect, request from flask_login import login_required, current_user, login_user, logout_user from flask_bcrypt import Bcrypt from util.database import * # 5000 seems a bit... basic. Feel free to change later to something more # interesting. SITE_PORT = 5000 # If testing on localhost, set to True # Otherwise if running on server, set to False SERVER_LOCAL = True # Init app app = Flask(__name__) # Setup bcrypt bcrypt = Bcrypt(app) # Initialize SQL database app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database.db" db.init_app(app) # Setup login manage login_manager.init_app(app) ##### Other constants RESPONSE_SUCCESS = "success" # Run before first request: We cannot create all inline # (unless we do db = SQLAlchemy(app) ) @app.before_first_request @app.route("/") @app.route("/home") @app.route("/scout") @login_required # Checks for login @app.route("/login", methods=["POST"]) @app.route("/logout") @login_required # Registers user @app.route("/register", methods=["POST"]) # Login page @app.route("/login", methods=["GET"]) # Register page @app.route("/register", methods=["GET"]) # Context Processor, automatically passing data to EVERY template # Makes sure we don't have to manually pass data every time we render @app.context_processor # Login wrapper. If no user exists, redirect to '/login' # Gets and sets the secret key from a file if __name__ == "__main__": if SERVER_LOCAL: host = "127.0.0.1" else: host = "0.0.0.0" set_secret_key("secret/secretkey") app.run(host = host, port = SITE_PORT, debug = True )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 25064, 198, 11748, 28686, 13, 6978, 198, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 6738, 42903, 1330, 46947, 11, 308, 11, 8543, 62, 28243, 11, 18941, 11, 2581, 198, 6738...
2.739938
646
#!/usr/bin/env python from mudparser.matches import (IPv4Match, IPv6Match, TCPMatch, UDPMatch, EthMatch, MUDMatch) __all__ = ['AccessListEntry']
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 17492, 48610, 13, 6759, 2052, 1330, 357, 4061, 85, 19, 23850, 11, 25961, 21, 23850, 11, 17283, 5868, 963, 11, 43700, 5868, 963, 11, 9956, 23850, 11, 337, 8322, 23850, 8, 1...
2.727273
55
""" Tests for the stow stub command """ # pylint: disable=missing-docstring # disable lint errors for function names longer that 30 characters # pylint: disable=invalid-name import os import pytest import dploy from dploy import error from tests import utils SUBCMD = "stow"
[ 37811, 198, 51, 3558, 329, 262, 336, 322, 17071, 3141, 198, 37811, 198, 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 15390, 8841, 198, 2, 15560, 300, 600, 8563, 329, 2163, 3891, 2392, 326, 1542, 3435, 198, 2, 279, 2645, 600, 25, 1...
3.135417
96
import pydeck as pdk from pydeck_carto import register_carto_layer
[ 11748, 12972, 35875, 355, 279, 34388, 198, 6738, 12972, 35875, 62, 26674, 78, 1330, 7881, 62, 26674, 78, 62, 29289, 628 ]
3.238095
21
#!/usr/bin/env python3 # Imports import bpy class BlenderNC_NT_preloader(bpy.types.Node): # === Basics === # Description string """A datacube node""" # Optional identifier string. If not explicitly defined, # the python class name is used. bl_idname = "datacubePreloadNode" # Label for nice name display bl_label = "Load datacube" # Icon identifier bl_icon = "SOUND" blb_type = "NETCDF" # TODO: This node will receive a datacube as # input and store all the images in disk for easier import and animation. # === Optional Functions === # Initialization function, called when a new node is created. # This is the most common place to create the sockets for a node, # as shown below. # Copy function to initialize a copied node from an existing one. # Free function to clean up on removal. # Additional buttons displayed on the node. # Detail buttons in the sidebar. # If this function is not defined, # the draw_buttons function is used instead # Optional: custom label # Explicit user label overrides this, # but here we can define a label dynamically
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 1846, 3742, 198, 11748, 275, 9078, 628, 198, 4871, 1086, 2194, 7792, 62, 11251, 62, 3866, 29356, 7, 65, 9078, 13, 19199, 13, 19667, 2599, 198, 220, 220, 220, 1303, 24844, 4588...
3.180328
366
# Echo server implemented using socket server and # a ThredoMixIn class. This class replaces the normal # socket with one that can be cancelled. Also uses spawn() # internally to launch threads. from thredo.socket import * import thredo import socketserver import signal thredo.run(main)
[ 2, 21455, 4382, 9177, 1262, 17802, 4382, 290, 220, 198, 2, 257, 536, 48454, 35608, 818, 1398, 13, 220, 220, 770, 1398, 24020, 262, 3487, 198, 2, 17802, 351, 530, 326, 460, 307, 16769, 13, 220, 4418, 3544, 10922, 3419, 198, 2, 20947,...
3.658537
82
from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from tutors.models import StudentRequest, TutorStudents from users.models import User from users.serializers import UserSerializer
[ 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 6738, 9732, 669, 13, 27530, 1330, 13613, 18453, 11, 22792, 273, 28239, 198, 198, ...
3.932203
59
"""Shared math functions.""" def math_sum(num1, num2): """Returns the sum of two parameters.""" return num1 + num2
[ 37811, 2484, 1144, 10688, 5499, 526, 15931, 628, 198, 4299, 10688, 62, 16345, 7, 22510, 16, 11, 997, 17, 2599, 198, 220, 220, 220, 37227, 35561, 262, 2160, 286, 734, 10007, 526, 15931, 198, 220, 220, 220, 1441, 997, 16, 1343, 997, 1...
2.840909
44
# Copyright (c) 2013, Minda Sai Pvt LTd and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ import math from calendar import monthrange from datetime import datetime,timedelta,date from dateutil.rrule import * # def get_conditions(filters): # conditions = "" # # if filters.get("employee"):conditions += "AND att.employee = '%s'" % filters["employee"] # if filters.get("from_date"): conditions += "and c.date_of_skill_evaluatation >= %(from_date)s" # if filters.get("to_date"): conditions += " and c.date_of_skill_evaluatation <= %(to_date)s" # return conditions, filters
[ 2, 15069, 357, 66, 8, 2211, 11, 10175, 64, 25251, 18367, 83, 34146, 67, 290, 20420, 198, 2, 1114, 5964, 1321, 11, 3387, 766, 5964, 13, 14116, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 5306, 27...
2.877049
244
import unittest from models.dqn.dqnalgorithm import DqnAlgorithm import random import roomai import roomai.sevenking from models.dqn.dqnalgorithm import DqnPlayer from models.dqn.sevenking import SevenKingModel_ThreePlayers import roomai.common
[ 198, 11748, 555, 715, 395, 198, 6738, 4981, 13, 49506, 77, 13, 49506, 77, 282, 42289, 1330, 360, 80, 77, 2348, 42289, 198, 11748, 4738, 198, 11748, 2119, 1872, 198, 11748, 2119, 1872, 13, 26548, 3364, 198, 6738, 4981, 13, 49506, 77, ...
3.233766
77
""" File: my_drawing Name: LEE HSUAN HSUAN ---------------------- TODO: """ from campy.graphics.gobjects import GOval, GRect, GArc, GPolygon ,GLabel from campy.graphics.gwindow import GWindow def main(): """ Sometimes little things in daily life that bring us happiness. Hope everyone can enjoy every moment of your life:) """ window = GWindow(500,500, title='The little things') tail = GOval(50,30,x=140,y=380) tail.filled = True tail.fill_color = 'lightgray' tail.color = 'lightgray' window.add(tail) tail_2 = GOval(80,35,x=130,y=365) tail_2.filled = True tail_2.fill_color = 'white' tail_2.color = 'white' window.add(tail_2) body_2 = GPolygon() body_2.add_vertex((180,425)) body_2.add_vertex((300,425)) body_2.add_vertex((230,320)) body_2.filled = True body_2.fill_color = 'lightgrey' body_2.color = 'lightgrey' window.add(body_2) body = GPolygon() body.add_vertex((170,440)) body.add_vertex((270,440)) body.add_vertex((200,290)) body.filled = True body.fill_color = 'lightgrey' body.color = 'lightgrey' window.add(body) ear_2 = GOval(100,120,x=120,y=175) ear_2.filled = True ear_2.fill_color = 'lightgray' ear_2.color = 'lightgray' window.add(ear_2) ear_1 = GOval(110,100,x=110,y=240) ear_1.filled = True ear_1.fill_color = 'lightgrey' ear_1.color = 'lightgrey' window.add(ear_1) nose_1 = GOval(80,110,x=260,y=190) nose_1.filled = True nose_1.fill_color = 'lightgrey' nose_1.color = 'lightgrey' window.add(nose_1) nose_2 = GOval(60,90,x=260,y=175) nose_2.filled = True nose_2.fill_color = 'white' nose_2.color = 'white' window.add(nose_2) head = GOval(150,150,x=150,y=190) head.filled = True head.fill_color = 'lightgrey' head.color = 'lightgrey' window.add(head) eye = GOval(30,30,x=233,y=240) eye.filled = True eye.fill_color = 'darkgray' eye.color = 'darkgray' window.add(eye) eye_2 = GOval(10,10,x=248,y=242) eye_2.filled = True eye_2.fill_color = 'white' eye_2.color = 'white' window.add(eye_2) mouth = GArc(30,50,180,180,x=248,y=289) mouth.filled = True mouth.fill_color = 'darkgray' mouth.color = 'darkgray' window.add(mouth) mouth_2 = GOval(32,12,x=247,y=297) mouth_2.filled = True mouth_2.fill_color = 'lightgrey' mouth_2.color = 'lightgrey' window.add(mouth_2) bubble = GOval(90,90,x=285,y=138) bubble.filled = True bubble.fill_color = 'skyblue' bubble.color = 'skyblue' window.add(bubble) bubble = GOval(10,25,x=295,y=160) bubble.filled = True bubble.fill_color = 'snow' bubble.color = 'snow' window.add(bubble) bubble_2 = GOval(10,10,x=295,y=193) bubble_2.filled = True bubble_2.fill_color = 'snow' bubble_2.color = 'snow' window.add(bubble_2) word = GLabel('"What makes you happy?"') word.color = "slategray" word.font = "Times New Roman-18-bold" window.add(word,125,80) word_2 = GLabel('"Blowing bubbles."') word_2.color = "slategray" word_2.font = "Times New Roman-18-bold" window.add(word_2,150,110) word_3 = GLabel('"The little things."') word_3.color = "slategray" word_3.font = "Times-14-bold-italic" window.add(word_3,350,445) if __name__ == '__main__': main()
[ 37811, 198, 8979, 25, 616, 62, 19334, 278, 198, 5376, 25, 406, 6500, 367, 12564, 1565, 367, 12564, 1565, 198, 19351, 438, 198, 51, 3727, 46, 25, 198, 37811, 198, 198, 6738, 1413, 88, 13, 70, 11549, 13, 70, 48205, 1330, 10351, 2100, ...
2.181529
1,570
symbol_table = { '00000000': 'A', '00000001': 'B', '00000010': 'C', '00000011': 'D', '00000100': 'E', '00000101': 'F', '00000110': 'G', '00000111': 'H', '00001000': 'I', '00001001': 'J', '00001010': 'K', '00001011': 'L', '00001100': 'M', '00001101': 'N', '00001110': 'O', '00001111': 'P', '00010000': 'Q', '00010001': 'R', '00010010': 'S', '00010011': 'T', '00010100': 'U', '00010101': 'V', '00010110': 'W', '00010111': 'X', '00011000': 'Y', '00011001': 'Z', '00011010': 'a', '00011011': 'b', '00011100': 'c', '00011101': 'd', '00011110': 'e', '00011111': 'f', '00100000': 'g', '00100001': 'h', '00100010': 'i', '01011100': 'j', '00100011': 'k', '00100100': 'l', '00100101': 'm', '00100110': 'n', '00100111': 'o', '00101000': 'p', '00101001': 'q', '00101010': 'r', '00101011': 's', '00101100': 't', '01011101': 'u', '00101101': 'v', '00101110': 'w', '00101111': 'x', '00110000': 'y', '00110001': 'z', '00110010': '0', '00110011': '1', '00110100': '2', '00110101': '3', '00110110': '4', '00110111': '5', '00111000': '6', '00111001': '7', '00111010': '8', '00111011': '9', '00111100': ';', '00111101': ':', '00111110': "'", '00111111': '"', '01000000': '/', '01000001': '\\', '01000010': '?', '01000011': '.', '01000100': ',', '01000101': '<', '01000110': '>', '01000111': '|', '01001000': ']', '01001001': '[', '01001010': '(', '01001011': ')', '01001100': '{', '01001101': '}', '01001110': '=', '01001111': '+', '01010000': '-', '01010001': '_', '01010010': '*', '01010011': '^', '01010100': '&', '01010101': '%', '01010110': '$', '01010111': '#', '01011000': '@', '01011001': '!', '01011010': '~', '01011011': '`', '01011100': ' ', '01011101': '', '01011110': '' }
[ 1837, 23650, 62, 11487, 796, 1391, 198, 220, 220, 220, 705, 8269, 10354, 705, 32, 3256, 198, 220, 220, 220, 705, 10535, 486, 10354, 705, 33, 3256, 198, 220, 220, 220, 705, 10535, 940, 10354, 705, 34, 3256, 198, 220, 220, 220, 705, ...
1.781629
1,154
# Copyright (C) 2010 The MITRE Corporation. See the toplevel # file LICENSE for license terms. # This file contains utilities which may be used either by # build_tarball.py, install.py, or any of the dist.py files in # the individual tasks. # THIS FILE DOES NOT RELY ON THE MAT PYTHON MODULE. import subprocess import os # We want to be able to save out task-specific config files. import ConfigParser # We're going to introduce the possibility of having multiple # versions, if we have an additional search path. import re # # Better, more integrated version of the executable chooser. # # The candidates are considered first, then the name in the usual path, # then the name in the extra dirs. If there's a version checker, the # argument of any acceptability test is the checker and the version, and # the choice function is the newest acceptable version. Otherwise, the # argument of the acceptability test is the full pathname, and # the choice function gets all the paths. If there's no choice function, # the first acceptable one is chosen. If there's no acceptability # test, the first element that exists and is a file is returned. import sys
[ 2, 15069, 357, 34, 8, 3050, 383, 17168, 2200, 10501, 13, 4091, 262, 284, 1154, 626, 198, 2, 2393, 38559, 24290, 329, 5964, 2846, 13, 198, 198, 2, 770, 2393, 4909, 20081, 543, 743, 307, 973, 2035, 416, 198, 2, 1382, 62, 18870, 1894...
3.902685
298
import os import requests from file_handler import download_image, get_filename if __name__ == "__main__": main()
[ 11748, 28686, 198, 11748, 7007, 198, 6738, 2393, 62, 30281, 1330, 4321, 62, 9060, 11, 651, 62, 34345, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
3.210526
38
snippet_normalize (cr, width, height) cr.set_line_width (0.16) cr.move_to (0.3, 0.33) cr.rel_line_to (0.2, -0.2) cr.rel_line_to (0.2, 0.2) cr.set_line_join (cairo.LINE_JOIN_MITER) #/* default */ cr.stroke () cr.move_to (0.3, 0.63) cr.rel_line_to (0.2, -0.2) cr.rel_line_to (0.2, 0.2) cr.set_line_join (cairo.LINE_JOIN_BEVEL) cr.stroke () cr.move_to (0.3, 0.93) cr.rel_line_to (0.2, -0.2) cr.rel_line_to (0.2, 0.2) cr.set_line_join (cairo.LINE_JOIN_ROUND) cr.stroke ()
[ 16184, 3974, 316, 62, 11265, 1096, 357, 6098, 11, 9647, 11, 6001, 8, 198, 6098, 13, 2617, 62, 1370, 62, 10394, 357, 15, 13, 1433, 8, 198, 6098, 13, 21084, 62, 1462, 357, 15, 13, 18, 11, 657, 13, 2091, 8, 198, 6098, 13, 2411, 6...
1.822394
259
from typing import Tuple from item_engine.constants import * from item_engine.lin_lin_network import Model as LL_Model from item_engine.textbase import make_characters, Char, Token if __name__ == '__main__': calls_to = {} @memorize def function(token: Token, char) -> Tuple[ACTION, STATE]: """ parser for : VAR = 'abcdefghijklmnopqrstuvwxyz'+ NUM = '0123456789'+ VAR_NUM = 'abcdefghijklmnopqrstuvwxyz'+ '0123456789'+ EQUAL = '=' PLUS = '+' PLUS_EQUAL = '+=' PLUS_PLUS = '++' LP = '(' RP = ')' """ if token.value == 0: if char.value == '=': return INCLUDE, 'EQUAL' elif char.value == '+': return INCLUDE, 7 elif char.value == '(': return INCLUDE, 'LP' elif char.value == ')': return INCLUDE, 'RP' elif char.value == '/': return INCLUDE, 'SLASH' elif char.value == '-': return INCLUDE, 'DASH' elif char.value == ' ': return INCLUDE, 6 elif char.value in 'abcefghijklmnopqrstuvwxyz': return INCLUDE, 1 elif char.value in 'd': return INCLUDE, 3 elif char.value in '0123456789': return INCLUDE, 8 else: return EXCLUDE, '!' elif token.value == 1: if char.value in 'abcdefghijklmnopqrstuvwxyz': return INCLUDE, 1 elif char.value in '0123456789': return INCLUDE, 2 else: return EXCLUDE, 'VAR' elif token.value == 2: if char.value in '0123456789': return INCLUDE, 2 else: return EXCLUDE, 'VAR_NUM' elif token.value == 3: if char.value == 'e': return INCLUDE, 4 elif char.value in 'abcdfghijklmnopqrstuvwxyz': return INCLUDE, 1 elif char.value in '0123456789': return INCLUDE, 2 else: return EXCLUDE, 'VAR' elif token.value == 4: if char.value == 'f': return INCLUDE, 5 elif char.value in 'abcdeghijklmnopqrstuvwxyz': return INCLUDE, 1 elif char.value in '0123456789': return INCLUDE, 2 else: return EXCLUDE, 'VAR' elif token.value == 5: if char.value in 'abcdefghijklmnopqrstuvwxyz': return INCLUDE, 1 elif char.value in '0123456789': return INCLUDE, 2 else: return EXCLUDE, 'KW_DEF' elif token.value == 6: if char.value == ' ': return INCLUDE, 6 else: return EXCLUDE, 'SPACE' elif token.value == 7: if char.value == '+': return INCLUDE, 'PLUS_PLUS' elif char.value == '=': return INCLUDE, 'PLUS_EQUAL' else: return EXCLUDE, 'PLUS' elif token.value == 8: if char.value in '0123456789': return INCLUDE, 8 else: return EXCLUDE, 'NUM' else: raise Exception(f"invalid value : {token.value!r}") net = LL_Model( input_cls=Char, output_cls=Token, function=function, skips=["SPACE"] ) alphabet = "abcdefghijklmnopqrstuvwxyz0123456789+/=() " import time import random size = 10_000 text = ''.join(random.choice(alphabet) for _ in range(size)) t = time.time() try: tokens = net.generate(make_characters(text)) d = time.time() - t print(f"{round((1e6 * d) / len(text))} μs/char [{len(text)} chars]") print(f"{round((1e6 * d) / len(tokens))} μs/token [{len(tokens)} tokens]") print(f"total time : {round(d, 3)} seconds") print() except SyntaxError as e: print(repr(text)) print('|' + ''.join('^' if e.args[0].start == index else ' ' for index in range(len(text))) + '|') raise e len_keys = len(calls_to.keys()) max_call = max(calls_to.values()) sum_call = sum(calls_to.values()) print(f"memorize\n" f"number of cases : {len_keys}\n" f"maximum calls to a single case : {max_call}\n" f"mean calls to a single case : {sum_call / max_call if max_call != 0 else '?'}") for key, val in calls_to.items(): if val >= 0.75 * max_call: print(f"{key} occured {val} times") text = "abcdef12345 = (x / 120)" from tools37 import ReprTable print(ReprTable.from_items(items=net.generate(make_characters(text)), config=dict( span=lambda token: f"{token.start} → {token.end}", type=lambda token: token.value, content=lambda token: token.content )))
[ 6738, 19720, 1330, 309, 29291, 198, 198, 6738, 2378, 62, 18392, 13, 9979, 1187, 1330, 1635, 198, 6738, 2378, 62, 18392, 13, 2815, 62, 2815, 62, 27349, 1330, 9104, 355, 27140, 62, 17633, 198, 6738, 2378, 62, 18392, 13, 5239, 8692, 1330...
1.793701
2,826
""" Author: Vinícius Jardim Email: viniciuspjardim@gmail.com Date: 3/2016 """ import math import random import re import wave import matplotlib.pyplot as plt import numpy as np import pyaudio as pa from scipy.io.wavfile import write from scipy import signal from src.musics import * class Notes: """Musical notes represents sounds with definite pitches (sound frequency). Definite pitches come from instruments like piano, guitar, vocals, etc. Notes often come from the chromatic scale, with 12 pitches, each a semitone above or below another. The notes are: `C, C#, D, D#, E, F, F#, G, G#, A, A#, B` In this class each of this notes is represented by a number from 0 (C note) to 11 (B note). This 12 notes represents an octave. Each octave ends in a B note, then a new octave starts (C note). For example: as we said, the the note number 11 is a B so the number 12 will be another C. This C will be one octave higher the other C. So we can call the first C, C0, the second C will be C1 and so on. The letter is the note name and the number is the octave. Each note in this class can be represented as a number or by the note name followed by the octave number. Example: | Note | Name | Frequency (Hz) | Wavelength (m)| |:----:|:----:|---------------:|--------------:| | 0 | C0 | 16.351597 | 21.098855 | | 1 | C#0 | 17.323914 | 19.914667 | | 2 | D0 | 18.354047 | 18.796943 | |... | | | | | 12 | C1 | 32.703195 | 10.549427 | | 13 | C#1 | 34.647828 | 9.957333 | |... | | | | We can see that the C1 is twice C0 frequency. Although C1 is more acute, it produces a harmonic sound to C0. C2 will be twice the frequency of C1, and it keeps doubling. The human ear can listen to frequencies from 20 to 20000 Hz. """ names = [ # 0 1 2 3 4 5 6 7 8 9 10 11 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] """Notes names""" notes_dict = { 'C': 0, 'C#': 1, 'D': 2, 'D#': 3, 'E': 4, 'F': 5, 'F#': 6, 'G': 7, 'G#': 8, 'A': 9, 'A#': 10, 'B': 11} """Notes name dictionary. We can get the number of the note by passing the note name """ scales = [ { 'name': 'Major Diatonic', 'notes': [0, 2, 4, 5, 7, 9, 11]}, { 'name': 'Minor Diatonic', 'notes': [0, 2, 3, 5, 7, 8, 10]}, { 'name': 'Major Pentatonic', 'notes': [0, 2, 4, 7, 9]}, { 'name': 'Minor Pentatonic', 'notes': [0, 3, 5, 7, 10]}, { 'name': 'Major Hexatonic', 'notes': [0, 2, 3, 4, 7, 9], 'blue_note': 3}, { 'name': 'Minor Hexatonic', 'notes': [0, 3, 5, 6, 7, 10], 'blue_note': 6} ] """A list of scales with C as the tonic note. Each scale is a dictionary itself, with name, notes and blue note when applicable. """ note_rgx = re.compile(r"^([CDEFGAB]{1}[#]?)([0-9]*)$") """Matches a string note like C, G#, B4, D#3 More about regex can be found on https://docs.python.org/3/library/re.html """ @staticmethod @staticmethod @staticmethod @staticmethod @staticmethod @staticmethod @staticmethod def frequency(self, note_num): """Returns the note frequency of the note represented by note num. The math formula is T * 2 ^((N -15/12)), where T is the A4 default tune (usually 440 Hz) and N is the number of the note (starting from C0 = 0). """ if note_num is None: return 0 return self.a4Tune * 2 ** ((note_num - 57) / 12) if __name__ == "__main__": main()
[ 37811, 198, 13838, 25, 11820, 8836, 28599, 449, 446, 320, 198, 15333, 25, 410, 47277, 3754, 79, 73, 446, 320, 31, 14816, 13, 785, 198, 10430, 25, 513, 14, 5304, 198, 37811, 198, 198, 11748, 10688, 198, 11748, 4738, 198, 11748, 302, ...
2.189369
1,806
from __future__ import (absolute_import, division, print_function, unicode_literals) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from zope.sqlalchemy import ZopeTransactionExtension __all__ = ['Base', 'Session'] Session = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base(cls=_Base)
[ 6738, 11593, 37443, 834, 1330, 357, 48546, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 28000, 1098, 62, 17201...
2.910959
146
from typing import ( Protocol, Awaitable, TypeVar, Callable, Union, runtime_checkable, Dict, TypedDict, Generic, Type, TYPE_CHECKING, ) from typing_extensions import ParamSpec if TYPE_CHECKING: from .object import Object T = TypeVar("T", covariant=True) A = TypeVar("A", bound="Object") P = ParamSpec("P") @runtime_checkable MaybeAwaitable = Union[Awaitable[T], T] MaybeCoroutine = Callable[P, MaybeAwaitable[T]] CommandSchema = Dict[str, CommandArgument[A]]
[ 6738, 19720, 1330, 357, 201, 198, 220, 220, 220, 20497, 11, 201, 198, 220, 220, 220, 5851, 4548, 540, 11, 201, 198, 220, 220, 220, 5994, 19852, 11, 201, 198, 220, 220, 220, 4889, 540, 11, 201, 198, 220, 220, 220, 4479, 11, 201, ...
2.284519
239
import json import subprocess import re import sys from nittymcpick.cls.comment import Comment
[ 11748, 33918, 198, 11748, 850, 14681, 198, 11748, 302, 198, 11748, 25064, 198, 198, 6738, 299, 715, 4948, 13155, 624, 13, 565, 82, 13, 23893, 1330, 18957, 628 ]
3.464286
28
""" Copyright 2017 Google 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. """ import json import pandas as pd from collections import defaultdict import csv import numpy as np folder = 'last_comments' with open('/scratch/wiki_dumps/expr_with_matching/%s/mapping.json'%(folder)) as f: mapping = json.load(f) history_toxicity = {} for ind in range(13): with open('/scratch/wiki_dumps/toxicity_scores/toxicity_scored_0%02d.csv'%(ind)) as f: df = pd.read_csv(f, encoding = 'utf-8', index_col=None, quoting=csv.QUOTE_ALL) print(ind, len(df)) for index, row in df.iterrows(): conv_id, user = mapping[str(row['id'])] if not(conv_id in history_toxicity): history_toxicity[conv_id] = defaultdict(list) history_toxicity[conv_id][user].append(row['TOXICITY']) print(ind, 'finished') output = [] for conv_id, conv in history_toxicity.items(): out = {} for user, toxicity in conv.items(): out[user] = np.mean(toxicity) output.append((conv_id, out)) with open('/scratch/wiki_dumps/expr_with_matching/user_features/history_toxicity.json', 'w') as w: json.dump(output, w)
[ 37811, 198, 15269, 2177, 3012, 3457, 13, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 1639, 743, 7330...
2.780612
588
import os import numpy as np import math import scipy import pickle TRAIN_DATA_PATH = "/Users/evanradcliffe/Senior Design/webserver/app/asl-alphabet/asl_alphabet_train" split_arr = lambda arr: arr[int(len(arr)/7):] def read_hand3d(): """read data from files (run setup_asl.py to generate)""" images = pickle.load( open("./pickle/images.pickle","rb") ) labels = pickle.load( open("./pickle/labels.pickle","rb") ) classes = pickle.load( open("./pickle/classes.pickle","rb") ) return np.array(images), np.array(labels), classes def read_data(): """read data from files""" print("loading data...",end="") ret_images = [] ret_labels = [] ret_class_names = [] count = 0 for label in list(os.walk(TRAIN_DATA_PATH)): # walk directory full_path, image_list = label[0], label[2] letter = full_path[len(TRAIN_DATA_PATH)+1:] # get letter class if len(letter) > 0: # get list of file paths to each image image_path_list = [TRAIN_DATA_PATH+"/"+letter+"/"+file for file in image_list] ret_class_names.append(letter) # print(letter, count) print(".",end="") if len(image_path_list) > 0: # iterate each image for i in range(len(image_path_list)): # add image, letter to ret array image = scipy.misc.imread(image_path_list[i]) image = scipy.misc.imresize(image, (28, 28)) image = rgb2gray(image) # image = np.expand_dims((image.astype('float') / 255.0) - 0.5, 0) ret_images.append(image) ret_labels.append(count) count += 1 print() return np.array(ret_images), np.array(ret_labels), ret_class_names def split_data(images, labels): """split training and testing data""" train_percent = 0.7 count = math.floor(len(images)*train_percent) images, labels = unison_shuffled_copies(images, labels) train_images, test_images = images[:count], images[count:] train_labels, test_labels = labels[:count], labels[count:] return (train_images, train_labels), (test_images, test_labels)
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 629, 541, 88, 198, 11748, 2298, 293, 198, 198, 51, 3861, 1268, 62, 26947, 62, 34219, 796, 12813, 14490, 14, 1990, 272, 6335, 33783, 14, 31224, 8495, 14, ...
2.221116
1,004
from .insn import * from .variant import RV64I,Extensions @isa("lui", 0x37) class InstructionLUI(InstructionUType): """ The Load Upper Immediate (LUI) instruction loads the given immediate (unsigned 20 bit) to the upper 20 bit of the destination register. The lower bits are set to zero in the destination register. This instruction can be used to efficiently form constants, as a sequence of LUI and ORI for example. """ @isa("auipc", 0x17) @isa("jal", 0x6F) @isa("jalr", 0x67, 0) @isa("beq", 0x63, 0) @isa("bne", 0x63, 1) @isa("blt", 0x63, 4) @isa("bge", 0x63, 5) @isa("bltu", 0x63, 6) @isa("bgeu", 0x63, 7) @isa("lb", 0x03, 0) @isa("lh", 0x03, 1) @isa("lw", 0x03, 2) @isa("lbu", 0x03, 4) @isa("lhu", 0x03, 5) @isa("sb", 0x23, 0) @isa("sh", 0x23, 1) @isa("sw", 0x23, 2) @isa("addi", 0x13, 0) @isa("slti", 0x13, 2) @isa("sltiu", 0x13, 3) @isa("xori", 0x13, 4) @isa("ori", 0x13, 6) @isa("andi", 0x13, 7) @isa("slli", 0x13, 1, 0x00) @isa("srli", 0x13, 5, 0x00) @isa("srai", 0x13, 5, 0x20) @isa("add", 0x33, 0, 0x00) @isa("sub", 0x33, 0, 0x20) @isa("sll", 0x33, 1, 0x00) @isa("slt", 0x33, 2, 0x00) @isa("sltu", 0x33, 3, 0x00) @isa("xor", 0x33, 4, 0x00) @isa("srl", 0x33, 5, 0x00) @isa("sra", 0x33, 5, 0x20) @isa("or", 0x33, 6, 0x00) @isa("and", 0x33, 7, 0x00) @isa("fence", 0xF, 0, 0x00) @isa("fence.i", 0xF, 1, 0x00) @isa("ecall", 0x73, 0) @isa("ebreak", 0x73, 0) @isa("csrrw", 0x73, 1) @isa("csrrs", 0x73, 2) @isa("csrrc", 0x73, 3) @isa("csrrwi", 0x73, 5) @isa("csrrsi", 0x73, 6) @isa("csrrci", 0x73, 7) @isa("lwu", 0x3, 6, variant=RV64I) @isa("ld", 0x3, 3, variant=RV64I) @isa("sd", 0x23, 3, variant=RV64I) @isa_pseudo() @isaC("c.addi", 1, funct3=0) @isaC("c.andi", 1, funct3=4) @isaC("c.swsp", 2, funct3=6) @isaC("c.li", 1, funct3=2) @isaC("c.mv", 2, funct4=8)
[ 6738, 764, 1040, 77, 1330, 1635, 198, 6738, 764, 25641, 415, 1330, 31367, 2414, 40, 11, 11627, 5736, 628, 198, 31, 9160, 7203, 2290, 72, 1600, 657, 87, 2718, 8, 198, 4871, 46486, 43, 10080, 7, 6310, 2762, 3843, 2981, 2599, 198, 220,...
1.898696
997
import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from .learnable import Scale, Balance from .softmax import SpatialSoftmax2d from .spectral import SpectralConv2d from ImageFunctions.utility.torch import get_valid_padding from .registry import register from . import create as create_layer @register("spatial_attn") @register("cat_pool_spatial_attn") @register("soft_wave_spatial_attn")
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 1330, 309, 22854, 198, 6738, 764, 35720, 540, 1330, 21589, 11, 22924, 198, 6738, 764, 4215, 9806, 1330, 1338,...
3.182482
137
""" -*- test-case-name: PyHouse/src/Modules/Utilities/coordinate_tools.py -*- @name: PyHouse/src/Modules/Utilities/coordinate_tools.py @author: D. Brian Kimmel @contact: d.briankimmel@gmail.com @copyright: 2016-2016 by D. Brian Kimmel @date: Created on Jun 21, 2016 @licencse: MIT License @summary: Handle X,Y,Z coordinates """ # Import system type stuff import xml.etree.ElementTree as ET import datetime # Import PyMh files from Modules.Core.data_objects import CoordinateData class Coords(object): """ """ @staticmethod def _get_coords(p_coords): """ get CordinateData() from JSON data returned from the browser @param p_str: Json returns a list of X, Y and Z values. It should look like >> [ 1, 2.2, 33.44 ] but it could be deformed by the user. @return: a CoordinateData() object filled in. """ l_ret = CoordinateData() if isinstance(p_coords, list): l_list = p_coords else: l_list = p_coords.strip('\[\]') l_list = l_list.split(',') try: l_ret.X_Easting = float(l_list[0]) l_ret.Y_Northing = float(l_list[1]) l_ret.Z_Height = float(l_list[2]) except Exception as e_err: print('Error {}'.format(e_err)) l_ret.X_Easting = 0.0 l_ret.Y_Northing = 0.0 l_ret.Z_Height = 0.0 return l_ret # ## END DBK
[ 37811, 198, 12, 9, 12, 1332, 12, 7442, 12, 3672, 25, 220, 9485, 18102, 14, 10677, 14, 5841, 5028, 14, 18274, 2410, 14, 37652, 4559, 62, 31391, 13, 9078, 220, 532, 9, 12, 198, 198, 31, 3672, 25, 220, 220, 220, 220, 220, 220, 9485...
2.099432
704
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
# the pre compiled functions would be written here # only the algocryption module can access these complied functions
[ 2, 262, 662, 14102, 5499, 561, 307, 3194, 994, 198, 2, 691, 262, 435, 70, 420, 13168, 8265, 460, 1895, 777, 35413, 5499, 198 ]
4.916667
24
import os, sys sys.path.append(os.path.abspath(os.getcwd())) from pymongo import MongoClient API = 'http://localhost:4200' # frontend api PRIMEIROAPP_API_DEV = os.environ.get('PRIMEIROAPP_API_DEV') PRIMEIROAPP_API_PROD = os.environ.get('PRIMEIROAPP_API_PROD') conn = MongoClient(host=PRIMEIROAPP_API_DEV, port=27017) # conn = MongoClient(host=PRIMEIROAPP_API_PROD, port=27017) # client = MongoClient("mongodb+srv://beto:beto1234@cluster0.rt58f.mongodb.net/primeiroapp?retryWrites=true&w=majority") # client = MongoClient("mongodb://beto:beto123@cluster0-shard-00-00.rt58f.mongodb.net:27017,cluster0-shard-00-01.rt58f.mongodb.net:27017,cluster0-shard-00-02.rt58f.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-xu6lpq-shard-0&authSource=admin&retryWrites=true&w=majority") # db = client.test # print(client.list_database_names()) db = conn['primeiroapp']
[ 11748, 28686, 11, 25064, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 1136, 66, 16993, 3419, 4008, 198, 198, 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 198, 17614, 796, 705, 4023, 137...
2.376022
367
import re import nltk import gensim import logging from pymystem3 import Mystem from string import punctuation from nltk.corpus import stopwords log = logging.getLogger(__name__)
[ 11748, 302, 198, 11748, 299, 2528, 74, 198, 11748, 308, 641, 320, 198, 11748, 18931, 198, 198, 6738, 12972, 1820, 927, 18, 1330, 2011, 927, 198, 6738, 4731, 1330, 21025, 2288, 198, 6738, 299, 2528, 74, 13, 10215, 79, 385, 1330, 2245, ...
3.081967
61
# Copyright 2013 Google Inc. All Rights Reserved. """Provide commands for managing SSL certificates of Cloud SQL instances.""" from googlecloudsdk.calliope import base class SslCerts(base.Group): """Provide commands for managing SSL certificates of Cloud SQL instances. Provide commands for managing SSL certificates of Cloud SQL instances, including creating, deleting, listing, and getting information about certificates. """ @staticmethod def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use it to add arguments that go on the command line after this command. Positional arguments are allowed. """ parser.add_argument( '--instance', '-i', required=True, help='Cloud SQL instance ID.')
[ 2, 15069, 2211, 3012, 3457, 13, 1439, 6923, 33876, 13, 198, 198, 37811, 15946, 485, 9729, 329, 11149, 25952, 20835, 286, 10130, 16363, 10245, 526, 15931, 628, 198, 6738, 23645, 17721, 21282, 74, 13, 13345, 72, 3008, 1330, 2779, 628, 198...
3.30916
262
import unicodedata from pyglet.window import key from pyglet.libs.darwin.cocoapy import * NSArray = ObjCClass('NSArray') NSApplication = ObjCClass('NSApplication') # This custom NSTextView subclass is used for capturing all of the # on_text, on_text_motion, and on_text_motion_select events. PygletTextView = ObjCClass('PygletTextView')
[ 11748, 28000, 9043, 1045, 198, 198, 6738, 12972, 70, 1616, 13, 17497, 1330, 1994, 198, 198, 6738, 12972, 70, 1616, 13, 8019, 82, 13, 27455, 5404, 13, 66, 25634, 12826, 1330, 1635, 198, 198, 8035, 19182, 796, 38764, 34, 9487, 10786, 80...
2.982609
115
#!/usr/bin/env python from BaseHTTPServer import HTTPServer from threading import Thread from webserver.context import RequestHandler if __name__ == "__main__": from sys import argv if len(argv) == 2: run(port=int(argv[1])) else: run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 7308, 6535, 28820, 18497, 1330, 38288, 18497, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 2639, 18497, 13, 22866, 1330, 19390, 25060, 628, 198, 361, 11593, 3672, 834, 6624, 366, ...
2.561905
105
from state import State from mystack import Stack from myqueue import Queue """ Define the number of stones can capstones for each board size. """ STONES = { 3: (10,0), 4: (15,0), 5: (21,1), 6: (30,1), 8: (50,2) } """ Define constants representing flat stones, standing stones and cap stones. """ FLAT_STONE = 0 STANDING_STONE = 1 CAP_STONE = 2 TYPES = ['-', '|', '*'] """ Define the four directions. """ UP = (-1, 0) DOWN = (1, 0) LEFT = (0, -1) RIGHT = (0, 1) DIR = [ UP, DOWN, LEFT, RIGHT ] """ Class representing the Tak state """ class TakState(State): """ Return a deep copy of this state. """ """ Return the size of the board. """ """ Return true if and only if the game is over. """ """ Returns a pair (over, winner) where over is true iff the game is over and winner is equal to the winner (0, 1 or -1 is the game is not over) """ """ Return the number of board position contolled by each player. """ """ Get the winning path if it exists. It retuns an empty path otherwise. """ """ Check whether there is a horizontal winnning path for a given player. """ """ Check whether there is a vertical winning path for a given player. """ """ Check whether there is a path controlled by the given player connecting the cells in S to the cells in T. Used to check winning paths. """ """ Check whether cell (r, c) is controlled by the given player. """ """ Return the index of the current player. """ """ Get all the actions that the current player can perform. """ """ Get all possible move actions from the current player. """ """ Auxiliary function to generate move actions. """ """ Get all place actions for the current player. """ """ Applies a given action to this state. It assume that the actions is valid. This must be checked with is_action_valid. """ """ Return the scores of each players. """ """ Get the winner of the game. Call only if the game is over. """ """ Check whether postition (r, c) is empty. """ """ Check whether the current player still has pieces (stones or capstones). """ """ Get the top piece at position (r, c). Returns None if the stack is empty. """ """ Checks whether it is possible to move k the pieces on top of the stack at (r_orig, c_orig) to (r_dest, c_dest). Also checks whether the positions are adjacent. """ """ Move the top k pieces of stack (r_orig, c_orig) to (r_dest, c_dest). It assumes that there are enough pieces at origin and enough space at destination. """ """ Return a string representation of the board. """ """ Get a representation of this state that can be loaded in the GUI. """ ########################################################################## # YOU SHOULD NOT USE THESE FUNCTION, THEY ARE ONLY USED IN THE INTERFACE # ########################################################################## """ Add a piece of type piece_type for the given player at position (r, c). This should not be used by your code, it is just a function used in the interface. It does not change the current player nor checks whether the game is over. """ """ Add a piece of type piece_type for the current player at position (r, c). This should not be used by your code, it is just a function used in the interface. It does not change the current player nor checks whether the game is over. """ """ Replace the top of the stack at position (r, c) by a piece of type piece_type for the given player. This should not be used by your code, it is just a function used in the interface. It does not change the current player nor checks whether the game is over. """ """ Replace the top of the stack at position (r, c) by a piece of type piece_type for the current player. This should not be used by your code, it is just a function used in the interface. It does not change the current player nor checks whether the game is over. """ """ Get a representation of this state that can be loaded in the GUI. """
[ 6738, 1181, 1330, 1812, 198, 6738, 21619, 441, 1330, 23881, 198, 6738, 616, 36560, 1330, 4670, 518, 198, 198, 37811, 198, 7469, 500, 262, 1271, 286, 14966, 460, 1451, 28750, 329, 1123, 3096, 2546, 13, 198, 37811, 198, 2257, 39677, 796, ...
3.355412
1,238
import concurrent.futures import logging import os import sys import boto3 import log_return from job_requester import JobRequester LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.DEBUG) LOGGER.addHandler(logging.StreamHandler(sys.stdout)) TEST_IMAGE = "763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-training:2.2.0-gpu-py37-cu101-ubuntu18.04" SAMPLE_XML_MESSAGE = "<note><to>Sample</to><from>XML</from><heading>Report</heading><body>Hello World!</body></note>" SAMPLE_CB_ARN = "arn:aws:codebuild:us-west-2:754106851545:build/DLCTestJobExecutor:894c9690-f6dc-4a15-b4b8-b9f2ddc51ea9" def test_requester(): """ Tests the send_request and receive_logs functions of the Job Requester package. How tests are executed: - create one Job Requester object, and multiple threads. Perform send_request with the Job Requester object in each of these threads. - send messages to the SQS queue that the Job Requester object created, to imitate the response logs received back from the Job Executor. - In each of the threads, perform receive_logs to receive the log correspond to the send_request earlier. """ threads = 10 request_object = JobRequester() identifiers_list = [] input_list = [] # creating unique image names and build_context strings for _ in range(threads): input_list.append((TEST_IMAGE, "PR", 3)) # sending requests with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as executor: futures = [executor.submit(request_object.send_request, x, y, z) for (x, y, z) in input_list] print("Created tickets......") for future in futures: res = future.result() print(res) identifiers_list.append(res) print("\n") # create sample xml report files image_tag = TEST_IMAGE.split(":")[-1] report_path = os.path.join(os.getcwd(), f"{image_tag}.xml") with open(report_path, "w") as report: report.write(SAMPLE_XML_MESSAGE) os.environ["CODEBUILD_BUILD_ARN"] = SAMPLE_CB_ARN for identifier in identifiers_list: os.environ["TICKET_KEY"] = f"folder/{identifier.ticket_name}" log_return.update_pool("completed", identifier.instance_type, 3, identifier.job_type, report_path) # receiving logs with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as executor: logs = [executor.submit(request_object.receive_logs, identifier) for identifier in identifiers_list] LOGGER.info("Receiving logs...") for log in logs: assert "XML_REPORT" in log.result(), f"XML Report not found as part of the returned log message." # clean up test artifacts S3 = boto3.client("s3") ticket_names = [item.ticket_name for item in identifiers_list] for name in ticket_names: S3.delete_object(Bucket=request_object.s3_ticket_bucket, Key=name) LOGGER.info("Tests passed.") if __name__ == "__main__": test_requester()
[ 11748, 24580, 13, 69, 315, 942, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 628, 198, 11748, 275, 2069, 18, 198, 198, 11748, 2604, 62, 7783, 198, 198, 6738, 1693, 62, 8897, 7834, 1330, 15768, 16844, 7834, 628, 198, 25294, ...
2.693285
1,102
from django.shortcuts import render from django.views.generic import ListView from pdn.models import *
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 198, 198, 6738, 279, 32656, 13, 27530, 1330, 1635, 628 ]
3.62069
29
from dotenv import load_dotenv import os from psycopg2 import connect, OperationalError load_dotenv()
[ 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 11748, 28686, 198, 6738, 17331, 22163, 70, 17, 1330, 2018, 11, 6564, 864, 12331, 198, 2220, 62, 26518, 24330, 3419, 628 ]
3.433333
30
import os import sys import logging import time import argparse import re import pymysql.cursors import pymysql.err from prometheus_client import CollectorRegistry, Gauge, Counter, push_to_gateway FORMAT = '%(asctime)s [%(process)d] [%(levelname)s] [%(name)s] %(message)s' TABLE_DEF = """ CREATE TABLE `alembic_version` ( `version_num` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=UTF8MB4 COLLATE=utf8mb4_bin; """ PROM_LABEL_PREFIX = 'DBA_OP_LABEL_' logger = logging.getLogger(__name__) if __name__ == '__main__': logging.basicConfig(format=FORMAT, level=logging.DEBUG) check_vars = [ 'DBA_OP_PROMETHEUS_PUSH_GATEWAY_ADDR', 'DBA_OP_JOB_ID', 'DBA_OP_CONNECTION_STRING', ] for env_var_name in check_vars: if not env_var_name in os.environ: logger.error('Must provide the environment variable %s', env_var_name) sys.exit(1) logger = logging.getLogger(os.environ['DBA_OP_JOB_ID']) parser = argparse.ArgumentParser( description='Run a fake migration container.', ) parser.add_argument( '--seconds', default=30, type=int, help='Number of seconds for which to run', ) parser.add_argument( '--fail_after', default=sys.maxsize, type=int, help='Number of seconds after which to fail (default: succeed)', ) parser.add_argument( '--write_version', required=True, type=str, help='Database version to set after completion', ) args = parser.parse_args() # Parse the env to find labels that we need to add labels = {_process_label_key(k): v for k, v in os.environ.items() if k.startswith(PROM_LABEL_PREFIX)} run( os.environ['DBA_OP_CONNECTION_STRING'], os.environ['DBA_OP_PROMETHEUS_PUSH_GATEWAY_ADDR'], os.environ['DBA_OP_JOB_ID'], labels, args.write_version, args.seconds, args.fail_after, )
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 11748, 302, 198, 198, 11748, 279, 4948, 893, 13976, 13, 66, 1834, 669, 198, 11748, 279, 4948, 893, 13976, 13, 8056, 198, 198, 6738, 1552,...
2.162191
931
#!/usr/bin/env python import json import os ''' The whitelist object is for reading the standard minecraft whitelist.json, and also maintaining a blacklist.json. '''
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 33918, 198, 11748, 28686, 198, 198, 7061, 6, 198, 464, 20542, 46331, 2134, 318, 329, 3555, 262, 3210, 6164, 3323, 198, 1929, 270, 46331, 13, 17752, 11, 290, 635, 10941, 257, 388...
3.408163
49
__author__ = 'dimitris' """ URLS for the Advanced Builder """ from django.conf.urls import patterns, include, url from builder_advanced import views urlpatterns = patterns('', # Basic pages url(r'^$', views.index, name='advanced-builder-index'), # API calls url(r'^api/active_classes/(?P<dt_name>[\w-]+)/$', views.active_classes), url(r'^api/object_properties/(?P<dt_name>[\w-]+)/$', views.object_properties), url(r'^api/active_class_properties/(?P<dt_name>[\w-]+)/$', views.active_class_properties), url(r'^api/get_property_type/(?P<dt_name>[\w-]+)/$', views.get_property_type), )
[ 834, 9800, 834, 796, 705, 27740, 270, 2442, 6, 198, 198, 37811, 198, 4261, 6561, 329, 262, 13435, 35869, 198, 37811, 198, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 7572, 11, 2291, 11, 19016, 198, 6738, 27098, 62, 32225, ...
1.925558
403
from rest_framework import serializers from django.contrib.auth.models import User from coffee_book.models import User, Coffee, BrewMethod, Review, Region
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 6891, 62, 2070, 13, 27530, 1330, 11787, 11, 19443, 11, 9702, 17410, 11, 6602, 11, 17718, 198 ]
3.974359
39
import sys import cStringIO import urllib2 from img_utils import prepare_image from PIL import Image from wintria.wintria.settings import PROJECT_ROOT thumbnail_size = 100, 100 dest_thumb_url = PROJECT_ROOT + 'wintria/wintria/logo_static/logo_thumbs/' dest_gen_url = PROJECT_ROOT + 'wintria/wintria/logo_static/logobank/' if __name__ == '__main__': new_url, domain = sys.argv[1], sys.argv[2] upload_gen = dest_gen_url+domain+'.png' upload_thumb = dest_thumb_url+domain+'.png' _file = cStringIO.StringIO(urllib2.urlopen(new_url, timeout=4).read()) img = Image.open(_file) img.save(dest_gen_url) new_img = prepare_image(img) new_img.save(upload_thumb)
[ 11748, 25064, 198, 11748, 269, 10100, 9399, 198, 11748, 2956, 297, 571, 17, 198, 198, 6738, 33705, 62, 26791, 1330, 8335, 62, 9060, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 266, 600, 7496, 13, 86, 600, 7496, 13, 33692, 1330, 21965...
2.391003
289
# -*- coding: utf-8 -*- """ Sahana Eden Population Outreach Models @copyright: 2015-2021 (c) Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __all__ = ("OutreachAreaModel", "OutreachHouseholdModel", "OutreachReferralModel", "po_rheader", "po_organisation_onaccept", "po_due_followups", ) from ..s3 import * from s3layouts import S3PopupLink from gluon import IS_NOT_EMPTY, IS_INT_IN_RANGE # ============================================================================= class OutreachAreaModel(S3Model): """ Model representing a mesh area for outreach work """ names = ("po_area", "po_area_id", ) # ------------------------------------------------------------------------- @staticmethod def defaults(): """ Safe defaults for names in case the module is disabled """ dummy = S3ReusableField("dummy_id", "integer", readable = False, writable = False, ) return {"po_area_id": lambda **attr: dummy("area_id"), } # ------------------------------------------------------------------------- @classmethod def area_onaccept(cls, form): """ Onaccept actions for po_area """ try: record_id = form.vars.id except AttributeError: return cls.area_update_affiliations(record_id) # ------------------------------------------------------------------------- @classmethod def area_ondelete(cls, row): """ Ondelete actions for po_area """ try: record_id = row.id except AttributeError: return cls.area_update_affiliations(record_id) # ------------------------------------------------------------------------- @staticmethod def area_update_affiliations(record_id): """ Update affiliations for an area @param record: the area record """ ROLE = "Areas" db = current.db s3db = current.s3db table = s3db.po_area row = db(table.id == record_id).select(table.pe_id, table.deleted, table.deleted_fk, table.organisation_id, limitby=(0, 1), ).first() if not row: return area_pe_id = row.pe_id if not area_pe_id: return # Get the organisation_id if row.deleted: try: fk = json.loads(row.deleted_fk) except ValueError: organisation_id = None else: organisation_id = fk.get("organisation_id") else: organisation_id = row.organisation_id # Get the PE ids organisation_pe_id = s3db.pr_get_pe_id("org_organisation", organisation_id, ) # Remove obsolete affiliations rtable = s3db.pr_role atable = s3db.pr_affiliation query = (atable.pe_id == row.pe_id) & \ (atable.deleted != True) & \ (atable.role_id == rtable.id) & \ (rtable.role == ROLE) & \ (rtable.pe_id != organisation_pe_id) rows = db(query).select(rtable.pe_id) for row in rows: s3db.pr_remove_affiliation(row.pe_id, area_pe_id, role=ROLE) # Add current affiliation from .pr import OU s3db.pr_add_affiliation(organisation_pe_id, area_pe_id, role=ROLE, role_type=OU) # ============================================================================= # ============================================================================= class OutreachReferralModel(S3Model): """ Model to track referrals of households to organisations """ names = ("po_referral_organisation", "po_organisation_area", "po_organisation_household", ) # ============================================================================= # ============================================================================= # ============================================================================= def po_organisation_onaccept(form): """ 1. Set the owned_by_group to PO_ADMIN so that they can see these agencies in the household referrals dropdown 2. Create a po_referral_organisation record onaccept of an org_organisation to link it to this module. @param form: the form """ try: organisation_id = form.vars["id"] except AttributeError: return db = current.db s3db = current.s3db otable = s3db.org_organisation record = db(otable.id == organisation_id).select(otable.id, otable.owned_by_group, limitby=(0, 1) ).first() if record: gtable = db.auth_group role = db(gtable.uuid == "PO_AGENCIES").select(gtable.id, limitby = (0, 1) ).first() try: PO_AGENCIES = role.id except AttributeError: # No PO_AGENCIES role prepopped pass else: if record.owned_by_group != PO_AGENCIES: record.update_record(owned_by_group = PO_AGENCIES) rtable = s3db.po_referral_organisation query = (rtable.organisation_id == organisation_id) & \ (rtable.deleted != True) exists = db(query).select(rtable.id, limitby=(0, 1)).first() if not exists: rtable.insert(organisation_id=organisation_id) # ============================================================================= def po_due_followups(): """ Number of due follow-ups """ query = (FS("followup_date") <= datetime.datetime.utcnow().date()) & \ (FS("completed") != True) resource = current.s3db.resource("po_household_followup", filter=query) return resource.count() # END =========================================================================
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 22982, 2271, 23369, 20133, 3806, 16250, 32329, 628, 220, 220, 220, 2488, 22163, 4766, 25, 1853, 12, 1238, 2481, 357, 66, 8, 22982, 2271, 10442, 5693, 198, 22...
2.285929
3,333
from fastapi import APIRouter from pydantic import UUID4 from models.cv.cv import CVModel, CV_Pydantic from models.cv.details import DetailsModel cv_router = APIRouter() @cv_router.get("/{cv_id}") @cv_router.get("/") @cv_router.post("/{user_id}")
[ 6738, 3049, 15042, 1330, 3486, 4663, 39605, 198, 6738, 279, 5173, 5109, 1330, 471, 27586, 19, 198, 6738, 4981, 13, 33967, 13, 33967, 1330, 26196, 17633, 11, 26196, 62, 47, 5173, 5109, 198, 6738, 4981, 13, 33967, 13, 36604, 1330, 14890, ...
2.544554
101
from typing import Dict import pandas as pd import datetime as dt from src.typeDefs.freqVoltConfig import IFreqVoltConfig from src.typeDefs.voltRecord import IVoltDataRecord from typing import List
[ 6738, 19720, 1330, 360, 713, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4818, 8079, 355, 288, 83, 198, 6738, 12351, 13, 4906, 7469, 82, 13, 19503, 80, 53, 5978, 16934, 1330, 16876, 42180, 53, 5978, 16934, 198, 6738, 12351, 13, ...
3.372881
59
#!/usr/bin/env python #coding:utf-8 # Purpose: whitespace processing # Created: 06.01.2011 # Copyright (C) 2011, Manfred Moitzi # License: MIT from __future__ import unicode_literals, print_function, division __author__ = "mozman <mozman@gmx.at>" from .compatibility import tostr from .xmlns import register_class, CN from .base import GenericWrapper @register_class @register_class @register_class @register_class WhitespaceEncoder = _WhitespaceEncoder()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 2, 66, 7656, 25, 40477, 12, 23, 201, 198, 2, 32039, 25, 13216, 10223, 7587, 201, 198, 2, 15622, 25, 9130, 13, 486, 13, 9804, 201, 198, 2, 15069, 357, 34, 8, 2813, 11, 1869, ...
2.781609
174
import pandas as pd df = pd.read_csv('data_banknote_authentication.txt') outliers(1.5, df) outliers(2.5, df) print() authentic = df[df['class'] == 0] # class 0 fake = df[df['class'] == 1] # class 1 outliers(1.5, authentic) outliers(2.0, authentic) outliers(2.5, authentic) print() outliers(1.5, fake) outliers(2.0, fake) outliers(2.5, fake)
[ 11748, 19798, 292, 355, 279, 67, 198, 7568, 796, 279, 67, 13, 961, 62, 40664, 10786, 7890, 62, 17796, 11295, 62, 41299, 3299, 13, 14116, 11537, 628, 198, 198, 448, 75, 3183, 7, 16, 13, 20, 11, 47764, 8, 198, 448, 75, 3183, 7, 17...
2.194969
159
from api.base_datastream_api import UAICensorBaseDatastreamApi from api.utils import gen_async_video_censor_url
[ 6738, 40391, 13, 8692, 62, 19608, 459, 1476, 62, 15042, 1330, 46164, 2149, 22854, 14881, 27354, 459, 1476, 32, 14415, 198, 6738, 40391, 13, 26791, 1330, 2429, 62, 292, 13361, 62, 15588, 62, 66, 22854, 62, 6371, 198 ]
2.947368
38
import math import numpy.linalg import numpy as np def shrink(X, tau): """ Apply the shrinkage operator the the elements of X. Returns V such that V[i,j] = max(abs(X[i,j]) - tau,0). """ V = np.copy(X).reshape(X.size) for i in range(V.size): V[i] = math.copysign(max(abs(V[i]) - tau, 0), V[i]) if V[i] == -0: V[i] = 0 return V.reshape(X.shape) def frobeniusNorm(X): """ Evaluate the Frobenius norm of X Returns sqrt(sum_i sum_j X[i,j] ^ 2) """ accum = 0 V = np.reshape(X,X.size) for i in range(V.size): accum += abs(V[i] ** 2) return math.sqrt(accum) def L1Norm(X): """ Evaluate the L1 norm of X Returns the max over the sum of each column of X """ return max(np.sum(X,axis=0)) def converged(Y,W,X,E): """ A simple test of convergence based on accuracy of matrix reconstruction from sparse and low rank parts """ error = frobeniusNorm(Y - np.dot(W,X) - E) / frobeniusNorm(Y) print("error =", error) return error <= 5*10e-5 def run(X_list,Y_list): """ """ Y = Y_list[0] X = X_list[0] L = np.zeros(Y.shape) W = np.zeros([3,3]) E = np.zeros(X.shape) mu = (Y.shape[0] * Y.shape[1]) / (4.0 * L1Norm(Y)) lamb = max(Y.shape) ** -0.5 print(mu) i = 1 while not converged(Y,W,X,E): Y = Y_list[i] X = X_list[i] tmp = Y - E + L*(mu**-1) # print(tmp) W = np.dot(np.dot(tmp,np.transpose(X)),np.linalg.inv(np.dot(X,np.transpose(X)))) W = -W #print(np.dot(Y,np.linalg.det(X))) #print(W) E = shrink(Y-np.dot(W,X) + (mu**-1) * L, (mu)*lamb) #mu = max(mu * 0.98,mu*0.1) #print(mu) L = L - 1 * (Y - np.dot(W,X) - E) #print(mu) i = (i+1) % X_list.__len__() return W,E if __name__ == '__main__': x_list = [] y_list = [] W = np.random.randint(0,10,size=[3,3]) / 255.0 for i in range(10): x = np.random.randint(0, 255, size=[3, 1000])/255.0 x_list.append(x) E = GaussieNoisy(x,0.1) y = np.dot(W,x) + E y_list.append(y) W_res, E_res = run(x_list,y_list) print(W) print(W_res) print(E_res)
[ 11748, 10688, 198, 11748, 299, 32152, 13, 75, 1292, 70, 198, 11748, 299, 32152, 355, 45941, 198, 198, 4299, 22085, 7, 55, 11, 256, 559, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 27967, 262, 22085, 496, 10088, 262, 262, 48...
1.88401
1,207
__author__ = 'wkerzend'
[ 834, 9800, 834, 796, 705, 86, 6122, 89, 437, 6, 198 ]
2.181818
11
#!/usr/bin/env python """ Test each connector's standalone CLI cache tool """ import os import json import sqlite3 try: import StringIO as io except ImportError: import io import datetime import pandas import nose try: import elasticsearch.exceptions _HAVE_ELASTICSEARCH = True except ImportError: _HAVE_ELASTICSEARCH = False try: from requests.exceptions import Timeout, ConnectionError, HTTPError _HAVE_REQUESTS = True except ImportError: _HAVE_REQUESTS = False import tokiotest import tokio.cli.cache_collectdes import tokio.cli.cache_darshan import tokio.cli.cache_esnet_snmp import tokio.cli.cache_isdct import tokio.cli.cache_lfsstatus import tokio.cli.cache_lmtdb import tokio.cli.cache_mmperfmon import tokio.cli.cache_nersc_globuslogs import tokio.cli.cache_nersc_jobsdb import tokio.cli.cache_slurm import tokio.cli.cache_topology @nose.tools.with_setup(tokiotest.create_tempfile, tokiotest.delete_tempfile) def verify_sqlite(output_str): """ Ensure that the database contains at least one table, and that table contains at least one row. """ ### Try to find the caching file name from the application's stdout output_file = None for line in output_str.splitlines(): if line.startswith('Caching to'): output_file = line.strip().split(None, 3)[-1] break if output_file is None: print("Could not find cache file name in output:") print(output_str) assert output_file is not None print("Using output_file [%s]" % output_file) assert os.path.isfile(output_file) tmpdb = sqlite3.connect(output_file) cursor = tmpdb.cursor() ## Count number of tables cursor.execute("SELECT name FROM sqlite_master WHERE type = 'table'") tables = cursor.fetchall() print("Found %d tables in %s" % (len(tables), output_file)) assert len(tables) > 0 for table in [x[0] for x in tables]: cursor.execute('SELECT count(*) FROM %s' % table) rows = cursor.fetchall() num_rows = rows[0][0] print("Found %d rows in %s" % (num_rows, table)) assert len(rows) > 0 def verify_json_zero_ok(json_str): """Ensure that json is loadable Args: json_str (str): string containing json text """ data = json.loads(json_str) assert data is not None def verify_json(json_str): """Ensure that json is loadable and contains something Args: json_str (str): string containing json text """ data = json.loads(json_str) assert len(data) > 0 def verify_csv(csv_str): """ Ensure that csv is loadable by Pandas """ data = pandas.read_csv(io.StringIO(csv_str)) assert len(data) > 0 def verify_sacct(csv_str): """ Ensure that native format is vaguely valid (treat it as a |-separated csv) """ data = pandas.read_csv(io.StringIO(csv_str), sep="|") assert len(data) > 0 def run_connector(binary, argv): """Default cache_connector run function Args: binary (module): tokio.cli module that contains a main() function argv (list of str): list of CLI arguments to pass to connector Returns: Stdout of cache connector script as a string """ return tokiotest.run_bin(binary, argv) def run_elasticsearch(binary, argv): """Run function that traps connection errors from ElasticSearch Args: binary (module): tokio.cli module that contains a main() function argv (list of str): list of CLI arguments to pass to connector Returns: Stdout of cache connector script as a string """ if not _HAVE_ELASTICSEARCH: raise nose.SkipTest("elasticsearch module not available") try: return tokiotest.run_bin(binary, argv) except elasticsearch.exceptions.ConnectionError as error: raise nose.SkipTest(error) def run_requests(binary, argv): """Run function that traps connection errors from REST Args: binary (module): tokio.cli module that contains a main() function argv (list of str): list of CLI arguments to pass to connector Returns: Stdout of cache connector script as a string """ if not _HAVE_REQUESTS: raise nose.SkipTest("requests module not available") try: return tokiotest.run_bin(binary, argv) except (ConnectionError, Timeout, HTTPError) as error: raise nose.SkipTest(error) @nose.tools.raises(ValueError) @nose.tools.raises(SystemExit) CACHE_CONNECTOR_CONFIGS = [ { 'name': 'cli.cache_mmperfmon', 'description': 'cli.cache_mmperfmon, gzipped text input', 'binary': tokio.cli.cache_mmperfmon, 'args': [tokiotest.SAMPLE_MMPERFMON_USAGE_INPUT], 'validators': [verify_json,], }, { 'name': 'cli.cache_mmperfmon', 'description': 'cli.cache_mmperfmon --csv --metric, gzipped text input', 'binary': tokio.cli.cache_mmperfmon, 'args': ['--csv', '--metric', tokiotest.SAMPLE_MMPERFMON_METRICS[0], tokiotest.SAMPLE_MMPERFMON_USAGE_INPUT], 'validators': [verify_csv,], }, { 'name': 'cli.cache_mmperfmon', 'description': 'cli.cache_mmperfmon --csv --host, gzipped text input', 'binary': tokio.cli.cache_mmperfmon, 'args': ['--csv', '--host', tokiotest.SAMPLE_MMPERFMON_HOSTS[0], tokiotest.SAMPLE_MMPERFMON_USAGE_INPUT], 'validators': [verify_csv,], }, { 'name': 'cli.cache_mmperfmon', 'description': 'cli.cache_mmperfmon --csv without --host/--metric', 'binary': tokio.cli.cache_mmperfmon, 'runfunction': run_raises_systemexit, 'args': ['--csv', tokiotest.SAMPLE_MMPERFMON_USAGE_INPUT], }, { 'name': 'cli.cache_mmperfmon', 'description': 'cli.cache_mmperfmon, tarfile input', 'binary': tokio.cli.cache_mmperfmon, 'args': [tokiotest.SAMPLE_MMPERFMON_TGZ_INPUT], 'validators': [verify_json,], }, { 'name': 'cli.cache_mmperfmon', 'description': 'cli.cache_mmperfmon, multiple inputs', 'binary': tokio.cli.cache_mmperfmon, 'args': [tokiotest.SAMPLE_MMPERFMON_USAGE_INPUT, tokiotest.SAMPLE_MMPERFMON_USAGE_INPUT], 'validators': [verify_json,], }, { 'name': 'cli.cache_nersc_globuslogs', 'description': 'cli.cache_nersc_globuslogs, cached input', 'binary': tokio.cli.cache_nersc_globuslogs, 'args': ['--input', tokiotest.SAMPLE_GLOBUSLOGS, tokiotest.SAMPLE_TIMESTAMP_START_NOW, tokiotest.SAMPLE_TIMESTAMP_END_NOW], 'validators': [verify_json,], }, { 'name': 'cli.cache_nersc_globuslogs', 'description': 'cli.cache_nersc_globuslogs, remote connection', 'binary': tokio.cli.cache_nersc_globuslogs, 'args': ['--input', tokiotest.SAMPLE_GLOBUSLOGS, tokiotest.SAMPLE_TIMESTAMP_START_NOW, tokiotest.SAMPLE_TIMESTAMP_END_NOW], 'runfunction': run_elasticsearch, 'validators': [verify_json_zero_ok,], }, { 'name': 'cli.cache_nersc_globuslogs', 'description': 'cli.cache_nersc_globuslogs --csv', 'binary': tokio.cli.cache_nersc_globuslogs, 'args': ['--input', tokiotest.SAMPLE_GLOBUSLOGS, '--csv', tokiotest.SAMPLE_TIMESTAMP_START_NOW, tokiotest.SAMPLE_TIMESTAMP_END_NOW], 'validators': [verify_csv,], }, { 'name': 'cli.cache_isdct', 'binary': tokio.cli.cache_isdct, 'args': ['--json', tokiotest.SAMPLE_NERSCISDCT_FILE], 'validators': [verify_json,], }, { 'name': 'cli.cache_isdct', 'binary': tokio.cli.cache_isdct, 'args': ['--csv', tokiotest.SAMPLE_NERSCISDCT_FILE], 'validators': [verify_csv,], }, { 'name': 'cli.cache_collectdes', 'description': 'cli.cache_collectdes, cached input', 'binary': tokio.cli.cache_collectdes, 'args': ['--input', tokiotest.SAMPLE_COLLECTDES_FILE, tokiotest.SAMPLE_COLLECTDES_START, tokiotest.SAMPLE_COLLECTDES_END], 'validators': [verify_json,], }, { 'name': 'cli.cache_collectdes', 'description': 'cli.cache_collectdes, remote connection', 'binary': tokio.cli.cache_collectdes, 'args': [tokiotest.SAMPLE_TIMESTAMP_START_NOW, tokiotest.SAMPLE_TIMESTAMP_END_NOW], 'runfunction': run_elasticsearch, 'validators': [verify_json_zero_ok,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--base', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--perf', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--total', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--base', '--perf', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--base', '--total', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--perf', '--total', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_darshan', 'binary': tokio.cli.cache_darshan, 'args': ['--base', '--perf', '--total', tokiotest.SAMPLE_DARSHAN_LOG], 'validators': [verify_json,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp default args', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--timeout", "5", "nersc"], 'runfunction': run_requests, 'validators': [verify_json,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp --json, remote connection', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--timeout", "5", "--json", "nersc"], 'runfunction': run_requests, 'validators': [verify_json,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp --csv, remote connection', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--timeout", "5", "--csv", "nersc"], 'runfunction': run_requests, 'validators': [verify_csv,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp --json, cached input', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "--json", "nersc"], 'validators': [verify_json,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp --csv, cached input', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "--csv", "nersc"], 'validators': [verify_csv,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp, explicit endpoint:interface', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "blah0:interf0"], 'validators': [verify_json,], }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp, invalid endpoint:interface', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "blah"], 'runfunction': run_raises_valueerror, }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp, invalid --start format', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "--start", "invalid", "nersc"], 'runfunction': run_raises_valueerror, }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp, --end without --start', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "--end", "2019-01-01T00:00:00", "nersc"], 'runfunction': run_raises_systemexit, }, { 'name': 'cli.cache_esnet_snmp', 'description': 'cli.cache_esnet_snmp, --start > --end', 'binary': tokio.cli.cache_esnet_snmp, 'args': ["--input", tokiotest.SAMPLE_ESNET_SNMP_FILE, "--start", "2019-01-02T00:00:00", "--end", "2019-01-01T00:00:00", "nersc"], 'runfunction': run_raises_valueerror, }, { 'name': 'cli.cache_slurm', 'binary': tokio.cli.cache_slurm, 'args': ['--json', tokiotest.SAMPLE_SLURM_CACHE_FILE], 'validators': [verify_json,], }, { 'name': 'cli.cache_slurm', 'binary': tokio.cli.cache_slurm, 'args': ['--csv', tokiotest.SAMPLE_SLURM_CACHE_FILE], 'validators': [verify_csv,], }, { 'name': 'cli.cache_slurm', 'binary': tokio.cli.cache_slurm, 'args': ['--native', tokiotest.SAMPLE_SLURM_CACHE_FILE], 'validators': [verify_sacct,], }, { 'name': 'cli.cache_topology', 'description': 'cli.cache_topology', 'binary': tokio.cli.cache_topology, 'args': [ '--nodemap-cache', tokiotest.SAMPLE_XTDB2PROC_FILE, '--jobinfo-cache', tokiotest.SAMPLE_SLURM_CACHE_FILE, ], 'validators': [verify_json,], }, { 'description': 'cli.cache_lfsstatus --fullness, no cache', 'binary': tokio.cli.cache_lfsstatus, 'args': [ '--fullness', '--', tokiotest.SAMPLE_DARSHAN_SONEXION_ID, tokiotest.SAMPLE_DARSHAN_START_TIME.replace(' ', 'T'), ], 'validators': [verify_json,], }, { 'description': 'cli.cache_lfsstatus --fullness, explicit cache', 'binary': tokio.cli.cache_lfsstatus, 'args': [ '--fullness', tokiotest.SAMPLE_OSTFULLNESS_FILE, tokiotest.SAMPLE_DARSHAN_SONEXION_ID, tokiotest.SAMPLE_DARSHAN_START_TIME.replace(' ', 'T'), ], 'validators': [verify_json,], }, { 'description': 'cli.cache_lfsstatus --failure, no cache', 'binary': tokio.cli.cache_lfsstatus, 'args': [ '--failure', '--', tokiotest.SAMPLE_DARSHAN_SONEXION_ID, tokiotest.SAMPLE_DARSHAN_START_TIME.replace(' ', 'T'), ], 'validators': [verify_json,], }, { 'description': 'cli.cache_lfsstatus --failure, explicit cache', 'binary': tokio.cli.cache_lfsstatus, 'args': [ '--failure', tokiotest.SAMPLE_OSTMAP_FILE, tokiotest.SAMPLE_DARSHAN_SONEXION_ID, tokiotest.SAMPLE_DARSHAN_START_TIME.replace(' ', 'T'), ], 'validators': [verify_json,], }, { 'description': 'cli.cache_nersc_jobsdb', 'binary': tokio.cli.cache_nersc_jobsdb, 'args': [ '-i', tokiotest.SAMPLE_NERSCJOBSDB_FILE, datetime.datetime.fromtimestamp( tokiotest.SAMPLE_NERSCJOBSDB_START).strftime("%Y-%m-%dT%H:%M:%S"), datetime.datetime.fromtimestamp( tokiotest.SAMPLE_NERSCJOBSDB_END).strftime("%Y-%m-%dT%H:%M:%S"), 'edison', ], 'validators': [verify_sqlite,], 'to_file': [True], 'validate_contents': False, }, { 'description': 'cli.cache_lmtdb', 'binary': tokio.cli.cache_lmtdb, 'args': [ '-i', tokiotest.SAMPLE_LMTDB_FILE, datetime.datetime.fromtimestamp( tokiotest.SAMPLE_LMTDB_START).strftime("%Y-%m-%dT%H:%M:%S"), datetime.datetime.fromtimestamp( tokiotest.SAMPLE_LMTDB_END).strftime("%Y-%m-%dT%H:%M:%S"), ], 'validators': [verify_sqlite,], 'to_file': [True], 'validate_contents': False, }, { 'description': 'cli.cache_lmtdb --limit', 'binary': tokio.cli.cache_lmtdb, 'args': [ '--limit', '2', '-i', tokiotest.SAMPLE_LMTDB_FILE, datetime.datetime.fromtimestamp( tokiotest.SAMPLE_LMTDB_START).strftime("%Y-%m-%dT%H:%M:%S"), datetime.datetime.fromtimestamp( tokiotest.SAMPLE_LMTDB_END).strftime("%Y-%m-%dT%H:%M:%S"), ], 'validators': [verify_sqlite,], 'to_file': [True], 'validate_contents': False, }, ] @nose.tools.with_setup(tokiotest.create_tempfile, tokiotest.delete_tempfile) def run_cache_connector(config, to_file=False): """ Test a connector cache (cache_*.py) CLI interface """ if config['binary'] == tokio.cli.cache_darshan: tokiotest.check_darshan() runfunction = config.get('runfunction', run_connector) if to_file: argv = ['-o', tokiotest.TEMP_FILE.name] + config['args'] print("Caching to %s" % tokiotest.TEMP_FILE.name) print("Executing: %s" % ' '.join(argv)) output_str = runfunction(config['binary'], argv) # (validate_contents == True) means the associated validator function # expects the contents of the output file rather than the name of the # output file if config.get('validate_contents', True): output_str = tokiotest.TEMP_FILE.read() else: argv = config['args'] print("Caching to stdout") print("Executing: %s" % ' '.join(argv)) output_str = runfunction(config['binary'], argv) for validator in config.get('validators', []): if isinstance(output_str, bytes): validator(output_str.decode()) else: validator(output_str) def craft_description(config, suffix): """ Take a cache_*.py command invocation and craft a clever test description """ if 'description' in config: result = "%s %s" % (config['description'], suffix) elif 'name' in config: result = "%s %s %s" % ( config['name'], ' '.join(config['args'][0:-1]), suffix) else: result = "%s %s %s" % ( config['binary'], ' '.join(config['args'][0:-1]), suffix) return result @tokiotest.needs_darshan def test(): """ Test all connector cache scripts """ for config in CACHE_CONNECTOR_CONFIGS: func = run_cache_connector for to_file in config.get('to_file', [True, False]): if to_file: func.description = craft_description(config, '(to file)') else: func.description = craft_description(config, '(to stdout)') yield func, config, to_file
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 14402, 1123, 21716, 338, 27669, 43749, 12940, 2891, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 44161, 578, 18, 198, 28311, 25, 198, 220, 220, 220, 133...
1.984591
10,059
import accimage import numpy as np import imageio import os ACCIMAGE_SAVE = os.environ.get('ACCIMAGE_SAVE', '') if len(ACCIMAGE_SAVE) and ACCIMAGE_SAVE.lower() not in {'0', 'false', 'no'}: SAVE_IMAGES = True else: SAVE_IMAGES = False def image_to_np(image): """ Returns: np.ndarray: Image converted to array with shape (width, height, channels) """ image_np = np.empty([image.channels, image.height, image.width], dtype=np.uint8) image.copyto(image_np) image_np = np.transpose(image_np, (1, 2, 0)) return image_np
[ 11748, 697, 9060, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2939, 952, 198, 11748, 28686, 198, 198, 26861, 3955, 11879, 62, 4090, 6089, 796, 28686, 13, 268, 2268, 13, 1136, 10786, 26861, 3955, 11879, 62, 4090, 6089, 3256, 10148, 8...
2.410256
234
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair. MIT Licensed. Contact at www.sinclair.bio """ # Built-in modules # # Internal modules # # First party modules # ############################################################################### class NonRedundant(object): """ The NR database from NCBI. NR contains non-redundant sequences from GenBank translations (i.e. GenPept) together with sequences from other databanks (Refseq, PDB, SwissProt, PIR and PRF). """
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 25354, 416, 15257, 34927, 13, 198, 36393, 49962, 13, 198, 17829, 379, 7324, 13, 31369, 27659, 13, ...
3.195122
164
#!/usr/bin/env python3 # # Copyright 2020 IBM # 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.IBM Confidential # # coding: utf-8 from __future__ import absolute_import from unittest import mock from swagger_server.models.capabilities import Capabilities # noqa: E501 from swagger_server.models.capability import Capability # noqa: E501 from swagger_server.models.server_info import ServerInfo # noqa: E501 from swagger_server.test import BaseTestCase from swagger_server.controllers.info_controller import get_capabilities, get_info class TestStatusController(BaseTestCase): """StatusController integration test stubs""" # GET CAPABILITIES def test_get_capabilities(self): """Test case for get_capabilities Get Server Capabilities """ expected = "{'capabilities': ['" + Capability.INFO + "', '" + Capability.DISCOVER + "', '" + Capability.RUN + "']}" response = get_capabilities() assert isinstance(response, Capabilities) assert str(response) == expected, 'response is not matching expected response' # GET STATUS @mock.patch("swagger_server.controllers.info_controller.boto3.client") def test_get_info(self, mock_boto_client): """Test case for get_info Get Server Status """ expected = "{'error': None,\n" +\ " 'info': {'description': 'Open Prediction Service for Amazon Sagemaker based '\n" + \ " 'on OPSv2 API'},\n" + \ " 'status': 'ok'}" response = get_info() assert isinstance(response, ServerInfo) assert str(response) == expected, 'response is not matching expected response' mock_boto_client.assert_called_once_with('sagemaker') @mock.patch("swagger_server.controllers.info_controller.boto3.client") def test_get_info_error(self, mock_boto_client): """Test case for get_info Get Server Status """ mock_boto_client.side_effect = KeyError('foo') expected = '{\'error\': "<class \'KeyError\'>",\n' + \ ' \'info\': {\'description\': \'Open Prediction Service for Amazon Sagemaker based \'\n' + \ ' \'on OPSv2 API\'},\n' + \ ' \'status\': \'error\'}' response = get_info() assert isinstance(response, ServerInfo) assert str(response) == expected, 'response is not matching expected response' mock_boto_client.assert_called_once_with('sagemaker') if __name__ == '__main__': import unittest unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 15069, 12131, 19764, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 1...
2.651657
1,177
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
'''https://leetcode.com/problems/operations-on-tree/ 1993. Operations on Tree Medium 152 34 Add to List Share You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked. Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user. Upgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true: The node is unlocked, It has at least one locked descendant (by any user), and It does not have any locked ancestors. Implement the LockingTree class: LockingTree(int[] parent) initializes the data structure with the parent array. lock(int num, int user) returns true if it is possible for the user with id user to lock the node num, or false otherwise. If it is possible, the node num will become locked by the user with id user. unlock(int num, int user) returns true if it is possible for the user with id user to unlock the node num, or false otherwise. If it is possible, the node num will become unlocked. upgrade(int num, int user) returns true if it is possible for the user with id user to upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded. Example 1: Input ["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"] [[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]] Output [null, true, false, true, true, true, false] Explanation LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]); lockingTree.lock(2, 2); // return true because node 2 is unlocked. // Node 2 will now be locked by user 2. lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2. lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2. // Node 2 will now be unlocked. lockingTree.lock(4, 5); // return true because node 4 is unlocked. // Node 4 will now be locked by user 5. lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4). // Node 0 will now be locked by user 1 and node 4 will now be unlocked. lockingTree.lock(0, 1); // return false because node 0 is already locked. Constraints: n == parent.length 2 <= n <= 2000 0 <= parent[i] <= n - 1 for i != 0 parent[0] == -1 0 <= num <= n - 1 1 <= user <= 104 parent represents a valid tree. At most 2000 calls in total will be made to lock, unlock, and upgrade.''' # Time: ctor: O(n) # lock: O(1) # unlock: O(1) # upgrade: O(n) # Space: O(n)
[ 7061, 6, 5450, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 3575, 602, 12, 261, 12, 21048, 14, 198, 24465, 13, 16205, 319, 12200, 198, 31205, 198, 198, 17827, 198, 198, 2682, 198, 198, 4550, 284, 7343, 198, 198, 11649, 198, ...
3.114644
1,038
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from .xaml_build_controller_reference import XamlBuildControllerReference class BuildController(XamlBuildControllerReference): """BuildController. :param id: Id of the resource :type id: int :param name: Name of the linked resource (definition name, controller name, etc.) :type name: str :param url: Full http link to the resource :type url: str :param _links: :type _links: :class:`ReferenceLinks <build.v4_0.models.ReferenceLinks>` :param created_date: The date the controller was created. :type created_date: datetime :param description: The description of the controller. :type description: str :param enabled: Indicates whether the controller is enabled. :type enabled: bool :param status: The status of the controller. :type status: object :param updated_date: The date the controller was last updated. :type updated_date: datetime :param uri: The controller's URI. :type uri: str """ _attribute_map = { 'id': {'key': 'id', 'type': 'int'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}, '_links': {'key': '_links', 'type': 'ReferenceLinks'}, 'created_date': {'key': 'createdDate', 'type': 'iso-8601'}, 'description': {'key': 'description', 'type': 'str'}, 'enabled': {'key': 'enabled', 'type': 'bool'}, 'status': {'key': 'status', 'type': 'object'}, 'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'}, 'uri': {'key': 'uri', 'type': 'str'} }
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
3.190977
665
_base_ = [ '../_base_/models/cascade_rcnn_r50_fpn.py', './my_voc.py', './my_runtime.py' ] model = dict( pretrained='open-mmlab://resnext101_32x4d', backbone=dict( type='ResNeXt', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict( type='BN', requires_grad=True), norm_eval=True, style='pytorch', groups=32, base_width=4), roi_head=dict( bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=13, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=13, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=13, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ])) # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=dict(max_norm=35)) # learning policy # actual epoch = lr_config = dict(policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[5, 8, 10], gamma=0.2) # runtime settings 0.01 0.002 0.0004 0.00008 total_epochs = 12 # actual epoch = 12 * 2 = 24
[ 62, 8692, 62, 796, 685, 198, 220, 220, 220, 705, 40720, 62, 8692, 62, 14, 27530, 14, 66, 28966, 62, 6015, 20471, 62, 81, 1120, 62, 69, 21999, 13, 9078, 3256, 198, 220, 220, 220, 705, 19571, 1820, 62, 18893, 13, 9078, 3256, 198, ...
1.575378
1,917
import setuptools with open("README.md") as readme: long_description = readme.read() setuptools.setup( name="simpleparser", version="0.1.3", author="NamorNiradnug", author_email="roma57linux@gmail.com", packages=["simpleparser"], tests_require=["test.py"], description="Simple library with simple parser which parses simple expressions.", long_description=long_description, long_description_content_type="text/markdown", license="MIT", url="https://github.com/NamorNiradnug/SimpleParser", project_urls={ "Bug Tracker": "https://github.com/NamorNiradnug/SimpleParser/issues", "Source": "https://github.com/NamorNiradnug/SimpleParser", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires=">=3.7" )
[ 11748, 900, 37623, 10141, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 4943, 355, 1100, 1326, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 1100, 1326, 13, 961, 3419, 198, 198, 2617, 37623, 10141, 13, 40406, 7, 198, 220, 220, ...
2.597143
350
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2142, 286, 10529, 2238, 13, 4091, 38559, 24290, 2393, 329, 1336, 6634, 290, 15665, 3307, 13, 198, 198, 6738, 16298, 2238, 1330, 40391, 11, 7032, 11, 4981, 628 ]
3.209302
43
import os from flask import Flask from flask_mail import Mail from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_assets import Environment from flask_wtf import CsrfProtect from flask_compress import Compress from flask_rq import RQ from flask_oauthlib.provider import OAuth2Provider from flask_wtf import CsrfProtect from flask_restful import Api from config import config from .assets import app_css, app_js, vendor_css, vendor_js basedir = os.path.abspath(os.path.dirname(__file__)) mail = Mail() db = SQLAlchemy() csrf = CsrfProtect() compress = Compress() csrf = CsrfProtect() oauth = OAuth2Provider() # Set up Flask-Login login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'account.login'
[ 11748, 28686, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 4529, 1330, 11099, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 42903, 62, 38235, 1330, 23093, 13511, 198, 6738, 42903, 62, 19668, 1330, 9...
3.229508
244
# coding: utf-8 """ Binary Heap https://en.wikipedia.org/wiki/Binary_heap https://en.wikipedia.org/wiki/Heap_(data_structure) A binary heap is a special binary tree which satisfies following properties: - The tree is complete. - The parent's value is less than or equal to children's values. - The root's value would be the minimum of the tree. A binary heap is typically represented as a compact array since it's a complete binary search tree: - array[0] is the root node. - array[floor((i - 1) / 2)] is the parent node of array[i]. - array[(i * 2) + 1] is the left child node of array[i]. - array[(i * 2) + 2] is the right child node of array[i]. Applications: - K-way merges (merging k sorted arrays into a single sorted array). - Priority queues. """ # This is a min heap. # O(log n) # O(log n) # O(1)
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 37811, 198, 33, 3219, 679, 499, 198, 5450, 1378, 268, 13, 31266, 13, 2398, 14, 15466, 14, 33, 3219, 62, 258, 499, 198, 5450, 1378, 268, 13, 31266, 13, 2398, 14, 15466, 14, 1544, 499, 41052, 7...
3.08209
268
from django.template.loader import render_to_string from jinja2 import Environment, PackageLoader, select_autoescape from ..templatetags.dtt_filters import to_snake_case
[ 6738, 42625, 14208, 13, 28243, 13, 29356, 1330, 8543, 62, 1462, 62, 8841, 198, 6738, 474, 259, 6592, 17, 1330, 9344, 11, 15717, 17401, 11, 2922, 62, 2306, 3028, 36435, 198, 198, 6738, 11485, 11498, 489, 265, 316, 3775, 13, 67, 926, ...
3.222222
54
from path import Path as path import pixabay as python_pixabay import tempfile from sklearn.externals import joblib import os import time import warnings import json import requests import numpy as np import re cache_filename = "pixabay_cache.pkl" api_key = None cache_update_interval = 3600 cache_expiry = 24*3600 cache = {} try: cache = joblib.load(cache_path()) if isinstance(cache, dict) == False: cache = create_cache() except IOError: cache = create_cache() update_api_key() def download_google_file(google_file, folder = "./"): """ Do a Google image search limited to pixabay.com and get the download file using these instructions: https://github.com/fastai/course-v3/blob/master/nbs/dl1/lesson2-download.ipynb Then use this script to grab the higher res photos. """ f = open(google_file,'r') urls = f.read().split("\n") f.close() [download(cdn_to_larger(url), folder) for url in urls]
[ 6738, 3108, 1330, 10644, 355, 3108, 198, 11748, 279, 844, 397, 323, 355, 21015, 62, 79, 844, 397, 323, 198, 11748, 20218, 7753, 198, 6738, 1341, 35720, 13, 1069, 759, 874, 1330, 1693, 8019, 198, 11748, 28686, 198, 11748, 640, 198, 117...
2.70339
354
""" pydeptree file.py -- contains functions to parses .py file -- extract function names, class names -- find what other functions a given function rely on @By Seth (Xiaohui) Wang @email: sethwang199418@gmail.com """ ''' class pyfile: def __init__(self, file_dir): self.file_dir = file_dir # find what other funcs the given func depends on def find_depend_funcs(self, func_name, file_funcs, result): moduleNames = [] with open(self.file_dir) as fp: for line in fp: if line.match("from .* import"): #def find_func_class(self, file_funcs): '''
[ 37811, 198, 9078, 2934, 457, 631, 198, 7753, 13, 9078, 198, 438, 4909, 5499, 284, 13544, 274, 764, 9078, 2393, 198, 438, 7925, 2163, 3891, 11, 1398, 3891, 198, 438, 1064, 644, 584, 5499, 257, 1813, 2163, 8814, 319, 198, 31, 3886, 20...
2.475806
248
"""Base test case support for tools. Version Added: 3.0 """ from __future__ import unicode_literals import os import tempfile from copy import deepcopy from functools import wraps from unittest import SkipTest import kgb import six from reviewbot.config import config from reviewbot.repositories import GitRepository from reviewbot.testing import TestCase from reviewbot.utils.process import execute class ToolTestCaseMetaclass(type): """Metaclass for tool tests. This is required for all subclasses of :py:class:`BaseToolTestCase`. This will split any test methods that are marked as a simulation and/or integration test into individual tests, set up by the subclass's :py:meth:`~BaseToolTestCase.setup_simulation_test` or :py:meth:`~BaseToolTestCase.setup_integration_test` method. Version Added: 3.0 """ def __new__(meta, name, bases, d): """Construct a new class. Args: name (str): The name of the class. bases (tuple of str): The parent classes/mixins. d (dict): The class dictionary. Returns: type: The new class. """ tool_class = d.get('tool_class') assert tool_class, '%s must set base_tool_class' % name if tool_class.exe_dependencies: assert d.get('tool_exe_config_key'), \ '%s must set tool_exe_config_key' % name assert d.get('tool_exe_path'), '%s must set tool_exe_path' % name for func_name, func in six.iteritems(d.copy()): if callable(func): added = False if hasattr(func, 'integration_setup_kwargs'): new_name = meta.tag_func_name(func_name, 'integration') d[new_name] = meta.make_integration_test_func(func, new_name) added = True if hasattr(func, 'simulation_setup_kwargs'): new_name = meta.tag_func_name(func_name, 'simulation') d[new_name] = meta.make_simulation_test_func(func, new_name) added = True if added: del d[func_name] return super(ToolTestCaseMetaclass, meta).__new__(meta, name, bases, d) @classmethod def tag_func_name(meta, func_name, tag): """Return a function name tagged with an identifier. This will convert a ``test_*` function name into a :samp:`test_{tag}_*`. Args: func_name (str): The original name of the function. tag (unicode): The tag to add. Returns: str: The resulting function name. """ assert func_name.startswith('test_') return str('test_%s_%s' % (tag, func_name[5:])) @classmethod def make_integration_test_func(meta, func, func_name): """Return a new function for an integration test. The function will wrap the original function from the class, and set up the state for an integration test. Args: func (callable): The function to wrap. func_name (str): The name of the function. Returns: callable: The new integration test function. """ @wraps(func) _wrapper.__name__ = func_name _wrapper.__doc__ = '%s [integration test]' % _wrapper.__doc__ return _wrapper @classmethod def make_simulation_test_func(meta, func, func_name): """Return a new function for a simulation test. The function will wrap the original function from the class, and set up the state for a simulation test. Args: func (callable): The function to wrap. func_name (str): The name of the function. Returns: callable: The new simulation test function. """ @wraps(func) _wrapper.__name__ = func_name _wrapper.__doc__ = '%s [simulation test]' % _wrapper.__doc__ return _wrapper class BaseToolTestCase(kgb.SpyAgency, TestCase): """Base class for Tool test cases. Version Added: 3.0 """ #: The tool class to test. #: #: This is required. #: #: Type: #: type tool_class = None #: The key in the configuration identifying the executable of the tool. #: #: This is required. #: #: Type: #: unicode tool_exe_config_key = None #: The path to the executable for running the tool. #: #: This will generally be a fake path for simulated tool runs, but a #: real one for integration tests. It can be set on the class or during #: test/test suite setup. #: #: Type: #: unicode tool_exe_path = None def run_get_can_handle_file(self, filename, file_contents=b'', tool_settings={}): """Run get_can_handle_file with the given file and settings. This will create the review objects, set up a repository (if needed by the tool), apply any configuration, and run :py:meth:`~reviewbot.tools.base.BaseTool.get_can_handle_file`. Args: filename (unicode): The filename of the file being reviewed. file_contents (bytes, optional): File content to review. tool_settings (dict, optional): The settings to pass to the tool constructor. Returns: bool: ``True`` if the file can be handled. ``False`` if it cannot. """ review = self.create_review() review_file = self.create_review_file( review, source_file=filename, dest_file=filename, diff_data=self.create_diff_data(chunks=[{ 'change': 'insert', 'lines': file_contents.splitlines(), 'new_linenum': 1, }]), patched_content=file_contents) tool = self.tool_class(settings=tool_settings) return tool.get_can_handle_file(review_file) def run_tool_execute(self, filename, file_contents, checkout_dir=None, tool_settings={}, other_files={}): """Run execute with the given file and settings. This will create the review objects, set up a repository (if needed by the tool), apply any configuration, and run :py:meth:`~reviewbot.tools.base.BaseTool.execute`. Args: filename (unicode): The filename of the file being reviewed. file_contents (bytes): File content to review. checkout_dir (unicode, optional): An explicit directory to use as the checkout directory, for tools that require full-repository checkouts. tool_settings (dict, optional): The settings to pass to the tool constructor. other_files (dict, optional): Other files to write to the tree. Each will result in a new file added to the review. The dictionary is a map of file paths (relative to the checkout directory) to byte strings. Returns: tuple: A 2-tuple containing: 1. The review (:py:class:`reviewbot.processing.review.Review)` 2. The file entry corresponding to ``filename`` (:py:class:`reviewbot.processing.review.File`) If ``other_files`` is specified, the second tuple item will instead be a dictionary of keys from ``other_files`` (along with ``filename``) to :py:class:`reviewbot.processing.review.File` instances. """ if self.tool_class.working_directory_required: repository = GitRepository(name='MyRepo', clone_path='git://example.com/repo') self.spy_on(repository.sync, call_original=False) @self.spy_for(repository.checkout) else: repository = None review = self.create_review() review_file = self.create_review_file( review, source_file=filename, dest_file=filename, diff_data=self.create_diff_data(chunks=[{ 'change': 'insert', 'lines': file_contents.splitlines(), 'new_linenum': 1, }]), patched_content=file_contents) review_files = {} if other_files: review_files[filename] = review_file for other_filename, other_contents in six.iteritems(other_files): review_files[other_filename] = self.create_review_file( review, source_file=other_filename, dest_file=other_filename, diff_data=self.create_diff_data(chunks=[{ 'change': 'insert', 'lines': other_contents.splitlines(), 'new_linenum': 1, }]), patched_content=other_contents) worker_config = deepcopy(self.config) worker_config.setdefault('exe_paths', {}).update({ self.tool_exe_config_key: self.tool_exe_path, }) with self.override_config(worker_config): tool = self.tool_class(settings=tool_settings) tool.execute(review, repository=repository) if other_files: return review, review_files return review, review_file def setup_integration_test(self, **kwargs): """Set up an integration test. Args: **kwargs (dict): Keyword arguments passed to :py:func:`~reviewbot.tools.testing.testcases.integration_test`. """ pass def setup_simulation_test(self, **kwargs): """Set up a simulation test. Args: **kwargs (dict): Keyword arguments passed to :py:func:`~reviewbot.tools.testing.testcases.simulation_test`. """ pass
[ 37811, 14881, 1332, 1339, 1104, 329, 4899, 13, 198, 198, 14815, 10687, 25, 198, 220, 220, 220, 513, 13, 15, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 28686, 198, 11748, 20218, 7...
2.11042
4,981
"""Interfaces defined in the state chart model. The interfaces defined in the state chart model are represented as separate classes. """ class SCI_Interface: """Implementation of scope sci_interface. """
[ 37811, 9492, 32186, 5447, 287, 262, 1181, 8262, 2746, 13, 198, 198, 464, 20314, 5447, 287, 262, 1181, 8262, 2746, 389, 7997, 198, 292, 4553, 6097, 13, 198, 198, 37811, 198, 198, 4871, 6374, 40, 62, 39317, 25, 628, 197, 37811, 3546, ...
3.633333
60