code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CVRF_Syntax(object): <NEW_LINE> <INDENT> NAMESPACES = {x.upper(): "{http://www.icasi.org/CVRF/schema/%s/1.1}" % x for x in ("cvrf", "vuln", "prod")} <NEW_LINE> CVRF_ARGS = ["all", "DocumentTitle", "DocumentType", "DocumentPublisher", "DocumentTracking", "DocumentNotes", "DocumentDistribution", "AggregateSeverity", "DocumentReferences", "Acknowledgments"] <NEW_LINE> VULN_ARGS = ["all", "Title", "ID", "Notes", "DiscoveryDate", "ReleaseDate", "Involvements", "CVE", "CWE", "ProductStatuses", "Threats", "CVSSScoreSets", "Remediations", "References", "Acknowledgments"] <NEW_LINE> PROD_ARGS = ["all", "Branch", "FullProductName", "Relationship", "ProductGroups"] <NEW_LINE> CVRF_SCHEMA = "http://www.icasi.org/CVRF/schema/cvrf/1.1/cvrf.xsd" <NEW_LINE> CVRF_CATALOG = "./cvrfparse/schemata/catalog.xml"
All of the CVRF Elements and Namespaces are kept here. As CVRF evolves, make appropriate changes here.
62598fc3656771135c489905
class Algorithm(CaomObject): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> caom_util.type_check(name, six.text_type, 'name', override=False) <NEW_LINE> self._name = str(name) <NEW_LINE> <DEDENT> def _key(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def __ne__(self, y): <NEW_LINE> <INDENT> return not self.__eq__(y) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name
The concept of Algorithm is to provide a way for users to find all composite observation sets that have been built using a particular grouping algorithm (eg. the MegaPipe stacks). For simple observations the algorithm is 'exposure'.
62598fc3283ffb24f3cf3b1a
class VersionAction(argparse.Action): <NEW_LINE> <INDENT> def __init__(self, option_strings, dest=argparse.SUPPRESS): <NEW_LINE> <INDENT> super(VersionAction, self).__init__( option_strings=option_strings, dest=dest, nargs=0, help="show program's version information and exit" ) <NEW_LINE> <DEDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> print('{prog} {0}'.format(__version__, prog=parser.prog)) <NEW_LINE> print('+ Python {0}.{1}.{2}'.format(*sys.version_info)) <NEW_LINE> from . import gamera_support as gs <NEW_LINE> print('+ Gamera {0}'.format(gs.gamera.__version__)) <NEW_LINE> pil_name = 'Pillow' <NEW_LINE> try: <NEW_LINE> <INDENT> pil_version = gs.PIL.PILLOW_VERSION <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pil_version = gs.PIL.__version__ <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pil_name = 'PIL' <NEW_LINE> pil_version = gs.PIL.VERSION <NEW_LINE> <DEDENT> <DEDENT> print('+ {PIL} {0}'.format(pil_version, PIL=pil_name)) <NEW_LINE> parser.exit()
argparse --version action
62598fc350812a4eaa620d30
class ChatClient(object): <NEW_LINE> <INDENT> def __init__(self, name, port, host=SERVER_HOST): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.connected = False <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.prompt= '[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> ' <NEW_LINE> try: <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self.sock.connect((host, self.port)) <NEW_LINE> print("Now connected to chat server@ port {0}".format(self.port)) <NEW_LINE> self.connected = True <NEW_LINE> send(self.sock, 'NAME: '+self.name) <NEW_LINE> data = receive(self.sock) <NEW_LINE> addr = data.split('CLIENT: ')[1] <NEW_LINE> self.prompt = '[' + '@'.join((self.name, addr)) +'>' <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> print("Failed to connect to chat server @ port {0}".format(self.port)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> while self.connected: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sys.stdout.write(self.prompt) <NEW_LINE> sys.stdout.flush() <NEW_LINE> readable, writeable, exceptional = select.select([0, self.sock], [], []) <NEW_LINE> for sock in readable: <NEW_LINE> <INDENT> if sock == 0: <NEW_LINE> <INDENT> data = sys.stdin.readline().strip() <NEW_LINE> if data: <NEW_LINE> <INDENT> send(self.sock, data) <NEW_LINE> <DEDENT> <DEDENT> elif sock == self.sock: <NEW_LINE> <INDENT> data = receive(self.sock) <NEW_LINE> if not data: <NEW_LINE> <INDENT> print("Client shutting down...") <NEW_LINE> self.connected = False <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.stdout.write(data+'\n') <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> print("Client interrupted.") <NEW_LINE> with open('./temp.txt', 'w') as f: <NEW_LINE> <INDENT> f.write("I was excuted!") <NEW_LINE> <DEDENT> self.sock.close() <NEW_LINE> break
a command lin chat client using select
62598fc3bf627c535bcb173d
class BANKMAILRQ(Aggregate): <NEW_LINE> <INDENT> bankacctfrom = SubAggregate(BANKACCTFROM) <NEW_LINE> ccacctfrom = SubAggregate(CCACCTFROM) <NEW_LINE> mail = SubAggregate(MAIL, required=True) <NEW_LINE> requiredMutexes = [["bankacctfrom", "ccacctfrom"]]
OFX section 11.11.1.1
62598fc3796e427e5384ea2c
class Exercise(NamedTuple): <NEW_LINE> <INDENT> fitid: str <NEW_LINE> dttrade: datetime.datetime <NEW_LINE> memo: str <NEW_LINE> uniqueidtype: str <NEW_LINE> uniqueid: str <NEW_LINE> units: decimal.Decimal <NEW_LINE> currency: str <NEW_LINE> total: decimal.Decimal <NEW_LINE> uniqueidtypeFrom: str <NEW_LINE> uniqueidFrom: str <NEW_LINE> unitsfrom: decimal.Decimal <NEW_LINE> reportdate: datetime.datetime <NEW_LINE> notes: Tuple[ibflex.enums.Code, ...]
Synthetic data type implementing OFX CLOSUREOPT interface.
62598fc3be7bc26dc9251fa7
class DateHourParameter(Parameter): <NEW_LINE> <INDENT> date_format = '%Y-%m-%dT%H' <NEW_LINE> def parse(self, s): <NEW_LINE> <INDENT> return datetime.datetime.strptime(s, self.date_format) <NEW_LINE> <DEDENT> def serialize(self, dt): <NEW_LINE> <INDENT> if dt is None: <NEW_LINE> <INDENT> return str(dt) <NEW_LINE> <DEDENT> return dt.strftime(self.date_format)
Parameter whose value is a :py:class:`~datetime.datetime` specified to the hour. A DateHourParameter is a `ISO 8601 <http://en.wikipedia.org/wiki/ISO_8601>`_ formatted date and time specified to the hour. For example, ``2013-07-10T19`` specifies July 10, 2013 at 19:00.
62598fc3091ae35668704ebe
class ConfigData: <NEW_LINE> <INDENT> def __init__( self, setup_dir ): <NEW_LINE> <INDENT> if not ( isinstance( setup_dir, str ) or isinstance( setup_dir, pathlib.Path ) ): <NEW_LINE> <INDENT> raise TypeError( 'Parameter \'setup_dir\' must be of type \'str\' or \'pathlib.Path\'' ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> setup_dir_path = pathlib.Path( setup_dir ).resolve( strict = True ) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> raise RuntimeError( 'not a valid directory: {}\n{}'.format( setup_dir, err ) ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.__sim_setup_file_path = pathlib.Path( setup_dir_path, CONFIG_FILE_NAME ).resolve( strict = True ) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> raise RuntimeError( 'not a valid simulation setup: {}\n{}'.format( setup_dir_path, err ) ) <NEW_LINE> <DEDENT> with open( self.__sim_setup_file_path ) as sim_setup_file: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__config_data = json.load( sim_setup_file ) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> raise Exception( 'Invalid JSON format: {}\n{}'.format( self.__sim_setup_file_path, str( err ) ) ) <NEW_LINE> <DEDENT> <DEDENT> self.__recursive_del_empty_str_from_lists( self.__config_data ) <NEW_LINE> <DEDENT> def __setitem__( self, index, value ): <NEW_LINE> <INDENT> self.__config_data[index] = value <NEW_LINE> <DEDENT> def __getitem__( self, index ): <NEW_LINE> <INDENT> return self.__config_data[index] <NEW_LINE> <DEDENT> def __contains__( self, item ): <NEW_LINE> <INDENT> return item in self.__config_data <NEW_LINE> <DEDENT> def write( self ): <NEW_LINE> <INDENT> with open( self.path, 'w' ) as sim_setup_file: <NEW_LINE> <INDENT> json.dump( self.__config_data, sim_setup_file, indent = 2, separators = ( ',', ': ' ) ) <NEW_LINE> sim_setup_file.write( '\n' ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def path( self ): <NEW_LINE> <INDENT> return self.__sim_setup_file_path <NEW_LINE> <DEDENT> @property <NEW_LINE> def data( self ): <NEW_LINE> <INDENT> return self.__config_data <NEW_LINE> <DEDENT> def __recursive_del_empty_str_from_lists( self, obj ): <NEW_LINE> <INDENT> for k,v in obj.items(): <NEW_LINE> <INDENT> if isinstance( v, list ): <NEW_LINE> <INDENT> if '' in v: <NEW_LINE> <INDENT> v.remove( '' ) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance( v, dict ): <NEW_LINE> <INDENT> self.__recursive_del_empty_str_from_lists( v )
This class handles access to simulation setup configuration data.
62598fc3cc40096d6161a324
class Meta: <NEW_LINE> <INDENT> verbose_name = 'Despesa e Receita' <NEW_LINE> verbose_name_plural = 'Despesas e Receitas'
Meta definition for ExpenseAndReceive.
62598fc3283ffb24f3cf3b1c
class Trips(Uri): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Uri.__init__(self, is_collection, "trips", output_type_serializer=api.TripsSerializer) <NEW_LINE> self.collections = get_collections(self.collection) <NEW_LINE> self.get_decorators.insert(1, get_obj_serializer(self))
Retrieves trips
62598fc35fc7496912d483c7
class Controller(object): <NEW_LINE> <INDENT> def __init__(self, program_id=DEFAULT_PROGRAM): <NEW_LINE> <INDENT> self.messages = Queue() <NEW_LINE> self.program_id = program_id <NEW_LINE> self.program = PROGRAMS[program_id]() <NEW_LINE> self.green = None <NEW_LINE> self.can_reset = False <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.green = Greenlet(self.main_loop) <NEW_LINE> self.green.start_later(START_DELAY) <NEW_LINE> self.program.start() <NEW_LINE> self.can_reset = True <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.program.stop() <NEW_LINE> if self.green: <NEW_LINE> <INDENT> self.green.kill() <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> self.program.reset() <NEW_LINE> self.can_reset = False <NEW_LINE> <DEDENT> def switch_program(self, program_id): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> self.program_id = program_id <NEW_LINE> self.program = PROGRAMS[program_id]() <NEW_LINE> self.can_reset = False <NEW_LINE> <DEDENT> def main_loop(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> msg = self.program.loop() <NEW_LINE> if msg: <NEW_LINE> <INDENT> self.messages.put(msg) <NEW_LINE> <DEDENT> sleep(LOOP_DELAY) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, command): <NEW_LINE> <INDENT> if command == 'short:sync': <NEW_LINE> <INDENT> pid = self.program_id <NEW_LINE> running = bool(self.green) <NEW_LINE> can_reset = self.can_reset <NEW_LINE> return "{} {} {}".format(pid, running, can_reset) <NEW_LINE> <DEDENT> if command == 'short:param-help': <NEW_LINE> <INDENT> return json.dumps(self.program.codes) <NEW_LINE> <DEDENT> if command == 'long:status': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = self.messages.get(timeout=STATUS_POLL_TIMEOUT) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return msg <NEW_LINE> <DEDENT> if command.startswith(PROGRAM_PREFIX): <NEW_LINE> <INDENT> prog = command[len(PROGRAM_PREFIX):] <NEW_LINE> self.switch_program(prog) <NEW_LINE> return "switched to {}".format(prog) <NEW_LINE> <DEDENT> if command == 'control:start': <NEW_LINE> <INDENT> reason = self.program.no_start() <NEW_LINE> if reason: <NEW_LINE> <INDENT> return reason <NEW_LINE> <DEDENT> if self.green: <NEW_LINE> <INDENT> return "already running" <NEW_LINE> <DEDENT> self.start() <NEW_LINE> return "program resumed" <NEW_LINE> <DEDENT> if command == 'control:stop': <NEW_LINE> <INDENT> if not self.green: <NEW_LINE> <INDENT> return "not running" <NEW_LINE> <DEDENT> self.stop() <NEW_LINE> return "program paused" <NEW_LINE> <DEDENT> if command == 'control:reset': <NEW_LINE> <INDENT> self.reset() <NEW_LINE> return "program reset" <NEW_LINE> <DEDENT> return self.program(command)
Manages a program's main loop in a Greenlet.
62598fc3d8ef3951e32c7fa8
class Location(mathematics.Point): <NEW_LINE> <INDENT> def __init__(self,a_x=0, a_y=0, a_z=0): <NEW_LINE> <INDENT> super(Location,self).__init__(a_x,a_y,a_z) <NEW_LINE> <DEDENT> def get_quadrant(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Quadrant(int(self.x/Quadrant.resolution),int(self.y/Quadrant.resolution),int(self.z/Quadrant.resolution)) <NEW_LINE> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> logging.error("Passed object: " + type(self).__name__ + " - " + format(self.x) + "," + format(self.y) + "," + format(self.z)) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def get_distance(self,a_location): <NEW_LINE> <INDENT> return Line(self.get_array(),a_location.get_array()).distance() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(int(self.x)) + "," + repr(int(self.y)) + "," + repr(int(self.z))
A representation for a point
62598fc392d797404e388cae
class HiFiGANMultiScaleMultiPeriodDiscriminator(torch.nn.Module): <NEW_LINE> <INDENT> def __init__( self, scales=3, scale_downsample_pooling="AvgPool1d", scale_downsample_pooling_params={ "kernel_size": 4, "stride": 2, "padding": 2, }, scale_discriminator_params={ "in_channels": 1, "out_channels": 1, "kernel_sizes": [15, 41, 5, 3], "channels": 128, "max_downsample_channels": 1024, "max_groups": 16, "bias": True, "downsample_scales": [2, 2, 4, 4, 1], "nonlinear_activation": "LeakyReLU", "nonlinear_activation_params": {"negative_slope": 0.1}, }, follow_official_norm=True, periods=[2, 3, 5, 7, 11], period_discriminator_params={ "in_channels": 1, "out_channels": 1, "kernel_sizes": [5, 3], "channels": 32, "downsample_scales": [3, 3, 3, 3, 1], "max_downsample_channels": 1024, "bias": True, "nonlinear_activation": "LeakyReLU", "nonlinear_activation_params": {"negative_slope": 0.1}, "use_weight_norm": True, "use_spectral_norm": False, }, ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.msd = HiFiGANMultiScaleDiscriminator( scales=scales, downsample_pooling=scale_downsample_pooling, downsample_pooling_params=scale_downsample_pooling_params, discriminator_params=scale_discriminator_params, follow_official_norm=follow_official_norm, ) <NEW_LINE> self.mpd = HiFiGANMultiPeriodDiscriminator( periods=periods, discriminator_params=period_discriminator_params, ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> msd_outs = self.msd(x) <NEW_LINE> mpd_outs = self.mpd(x) <NEW_LINE> return msd_outs + mpd_outs
HiFi-GAN multi-scale + multi-period discriminator module.
62598fc35fdd1c0f98e5e22c
class ConfigMgr(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._initialized = False <NEW_LINE> self._configer = None <NEW_LINE> self.lib_dir = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> self.work_dir = os.path.dirname(self.lib_dir) <NEW_LINE> self.conf_dir = os.path.join(self.work_dir, "conf") <NEW_LINE> <DEDENT> def _load_config_file(self, config_file): <NEW_LINE> <INDENT> if config_file is None: <NEW_LINE> <INDENT> config_file = os.path.join(self.conf_dir, "main.conf") <NEW_LINE> <DEDENT> self._configer = ConfigParser.ConfigParser() <NEW_LINE> readok = self._configer.read(config_file) <NEW_LINE> if config_file not in readok: <NEW_LINE> <INDENT> raise Exception("load config file %s failed" % config_file) <NEW_LINE> <DEDENT> self.logger.info("load config from %s", config_file) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def instance(cls): <NEW_LINE> <INDENT> key = "__instance__" <NEW_LINE> if hasattr(cls, key): <NEW_LINE> <INDENT> return getattr(cls, key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cm = ConfigMgr() <NEW_LINE> setattr(cls, key, cm) <NEW_LINE> return cm <NEW_LINE> <DEDENT> <DEDENT> def init(self, config_file=None): <NEW_LINE> <INDENT> if self._initialized: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.logger = logging.getLogger(__name__) <NEW_LINE> self._load_config_file(config_file) <NEW_LINE> self._initialized = True <NEW_LINE> <DEDENT> def get_section_items(self, section): <NEW_LINE> <INDENT> if self._configer is not None: <NEW_LINE> <INDENT> configs = self._configer.items(section) <NEW_LINE> return dict(configs) <NEW_LINE> <DEDENT> raise Exception("config file not loaded")
conf manage instance class
62598fc360cbc95b063645d6
class Multiply(Math): <NEW_LINE> <INDENT> def __call__(self, state): <NEW_LINE> <INDENT> v1, v2 = self.binary(state) <NEW_LINE> push(state, v1*v2)
Multiply the top two items from the stack
62598fc3a8370b77170f067b
class BasicLogic(DiscardStrategy): <NEW_LINE> <INDENT> def __init__(self, Hand): <NEW_LINE> <INDENT> super().__init__(Hand) <NEW_LINE> self.Max = np.max(Hand) <NEW_LINE> self.Min = np.min(Hand) <NEW_LINE> <DEDENT> def discard_check(self): <NEW_LINE> <INDENT> self.less_then(6) <NEW_LINE> if((self.Max - self.Min) < 4): <NEW_LINE> <INDENT> self.less_then(9) <NEW_LINE> <DEDENT> return self.Discard <NEW_LINE> <DEDENT> def less_then(self, Number): <NEW_LINE> <INDENT> self.Discard = np.append(self.Discard, self.Hand[self.Hand < Number]) <NEW_LINE> self.Hand = self.Hand[self.Hand >= Number]
Players on BasicLogic strategy discard ... less then 6, because a high possibility to draw any of 5-9. If the difference of Max and Min is less then 4, other then nine. To raise the posibility of 9.
62598fc3e1aae11d1e7ce972
class Delfrom(Parameter): <NEW_LINE> <INDENT> pass
RFC 5545: Delegator
62598fc3ad47b63b2c5a7af1
class AutoRestSwaggerBATService(object): <NEW_LINE> <INDENT> def __init__( self, base_url=None): <NEW_LINE> <INDENT> self.config = AutoRestSwaggerBATServiceConfiguration(base_url) <NEW_LINE> self._client = ServiceClient(None, self.config) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self.api_version = '1.0.0' <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.string = StringOperations( self._client, self.config, self._serialize, self._deserialize) <NEW_LINE> self.enum = EnumOperations( self._client, self.config, self._serialize, self._deserialize)
Test Infrastructure for AutoRest Swagger BAT :ivar config: Configuration for client. :vartype config: AutoRestSwaggerBATServiceConfiguration :ivar string: String operations :vartype string: fixtures.acceptancetestsbodystring.operations.StringOperations :ivar enum: Enum operations :vartype enum: fixtures.acceptancetestsbodystring.operations.EnumOperations :param str base_url: Service URL
62598fc363b5f9789fe8540d
class ConvDenseLayer(Layer): <NEW_LINE> <INDENT> def __init__(self, n, weight_factory='xavier_uniform', activation='linear', weights=None, w_regulariser=None, b_regulariser=None, input_shape=None, **kwargs): <NEW_LINE> <INDENT> self.weightFactory = get_weightfactory(weight_factory) <NEW_LINE> self.activation = get_activation(activation) <NEW_LINE> self.w_regulariser = get_regulariser(w_regulariser) <NEW_LINE> self.b_regulariser = get_regulariser(b_regulariser) <NEW_LINE> if(input_shape is not None): <NEW_LINE> <INDENT> self.input_dim = input_shape[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.input_dim = None <NEW_LINE> <DEDENT> self.n = n <NEW_LINE> if(input_shape is not None): <NEW_LINE> <INDENT> kwargs['input_shape'] = input_shape <NEW_LINE> <DEDENT> Layer.__init__(self, **kwargs) <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> if(len(input_shape) != 3): <NEW_LINE> <INDENT> raise ValueError("ConvDenseLayer is currently " "only implemented for sitting " "above Conv1dLayers.") <NEW_LINE> <DEDENT> input_dim = input_shape[1] <NEW_LINE> self.W = self.weightFactory(shape=(input_dim, self.n)) <NEW_LINE> self.b = N.zeros(shape=(self.n,)) <NEW_LINE> self.trainable_weights = [self.W, self.b] <NEW_LINE> self.is_built = True <NEW_LINE> <DEDENT> def prop_up(self, inputs): <NEW_LINE> <INDENT> input_shape = N.int_shape(inputs) <NEW_LINE> if(input_shape[0]): <NEW_LINE> <INDENT> def step(x, _): <NEW_LINE> <INDENT> output = self.activation(N.dot(x, self.W) + self.b) <NEW_LINE> return output, [] <NEW_LINE> <DEDENT> _, outputs, _ = N.rnn(step, inputs, initial_states=[], input_length=input_shape[1], unroll=False) <NEW_LINE> y = outputs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input_length = input_shape[-1] <NEW_LINE> if(not input_length): <NEW_LINE> <INDENT> input_length = N.shape(inputs)[-1] <NEW_LINE> <DEDENT> inputs = N.reshape(inputs, (-1, input_shape[1])) <NEW_LINE> y = self.activation(N.dot(inputs, self.W) + self.b) <NEW_LINE> y = N.reshape(y, (-1, self.n, input_length)) <NEW_LINE> <DEDENT> return y <NEW_LINE> <DEDENT> def get_cost(self): <NEW_LINE> <INDENT> w_cost = self.w_regulariser(self.W) if self.w_regulariser else N.cast(0.) <NEW_LINE> b_cost = self.b_regulariser(self.b) if self.b_regulariser else N.cast(0.) <NEW_LINE> return w_cost + b_cost <NEW_LINE> <DEDENT> def get_output_shape(self, input_shape): <NEW_LINE> <INDENT> assert input_shape and isinstance(input_shape, tuple) <NEW_LINE> assert len(input_shape) >= 3 <NEW_LINE> if(self.input_dim): <NEW_LINE> <INDENT> assert input_shape[1] == self.input_dim <NEW_LINE> <DEDENT> output_shape = list(input_shape) <NEW_LINE> output_shape[1] = self.n <NEW_LINE> return tuple(output_shape)
A dense layer that immediately follows a distributed convolution without any flattening. See the first layers of 'Deep Speech 2' for functionality
62598fc37d847024c075c657
class DeltaUploads(fixtures.Fixture): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.useFixture(fixtures.EnvironmentVariable( 'DELTA_UPLOADS_EXPERIMENTAL', 'True'))
Enable the Delta Uploads Experimental flag.
62598fc3f9cc0f698b1c541e
class TestLiveVmmDomain(TestLiveAPIC): <NEW_LINE> <INDENT> def test_get(self): <NEW_LINE> <INDENT> session = self.login_to_apic() <NEW_LINE> vmm_domains = VmmDomain.get(session) <NEW_LINE> for vmm_domain in vmm_domains: <NEW_LINE> <INDENT> self.assertTrue(isinstance(vmm_domain, VmmDomain)) <NEW_LINE> <DEDENT> return vmm_domains <NEW_LINE> <DEDENT> def test_get_json(self): <NEW_LINE> <INDENT> vmm_domains = self.test_get() <NEW_LINE> for vmm_domain in vmm_domains: <NEW_LINE> <INDENT> self.assertTrue(type(vmm_domain.get_json()) is dict) <NEW_LINE> <DEDENT> <DEDENT> def test_get_by_name(self): <NEW_LINE> <INDENT> session = self.login_to_apic() <NEW_LINE> vmm_domains = VmmDomain.get(session) <NEW_LINE> for vmm_domain in vmm_domains: <NEW_LINE> <INDENT> self.assertEqual(VmmDomain.get_by_name(session, vmm_domain.name), vmm_domain)
Live tests for VmmDomain class
62598fc3ff9c53063f51a8e8
class pantheraConfig: <NEW_LINE> <INDENT> values = dict() <NEW_LINE> path = os.path.expanduser("~/.panthera-cdn/config") <NEW_LINE> createNewFile = True <NEW_LINE> panthera = "" <NEW_LINE> def __init__(self, panthera): <NEW_LINE> <INDENT> self.panthera = panthera <NEW_LINE> self.panthera.hooking.add_option('server.exit', self.save) <NEW_LINE> if not os.path.isfile(self.path): <NEW_LINE> <INDENT> if self.createNewFile == True: <NEW_LINE> <INDENT> f = open(self.path, "w") <NEW_LINE> f.write("") <NEW_LINE> f.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Fatal error: "+self.path+" does not exists") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> f = open(self.path, "r") <NEW_LINE> self.values = json.loads(f.read()) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.values = {} <NEW_LINE> <DEDENT> <DEDENT> def getKey(self, key): <NEW_LINE> <INDENT> if key in self.values: <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def keyExists(self, key): <NEW_LINE> <INDENT> return key in self.values <NEW_LINE> <DEDENT> def setKey(self, key): <NEW_LINE> <INDENT> self.values[key] = key <NEW_LINE> return True <NEW_LINE> <DEDENT> def save(self, a=''): <NEW_LINE> <INDENT> self.panthera.logging.output("Saving "+self.path, 'pantheraConfig') <NEW_LINE> f = open(self.path, "w") <NEW_LINE> f.write(json.dumps(self.values, indent=4)) <NEW_LINE> f.close() <NEW_LINE> return True
Configuration manager based on JSON files
62598fc392d797404e388caf
class RegexpNormalizer(SimpleNormalizer): <NEW_LINE> <INDENT> _possibleSettings = { 'char': { 'docs': ("Character(s) to replace matches in the regular " "expression with. Defaults to empty string (eg strip " "matches)") }, 'regexp': { 'docs': "Regular expression to match in the data.", 'required': True }, 'keep': { 'docs': ("Should instead keep only the matches. Boolean, defaults " "to False"), 'type': int, 'options': "0|1" } } <NEW_LINE> def __init__(self, session, config, parent): <NEW_LINE> <INDENT> SimpleNormalizer.__init__(self, session, config, parent) <NEW_LINE> self.char = self.get_setting(session, 'char', '') <NEW_LINE> self.keep = self.get_setting(session, 'keep', 0) <NEW_LINE> regex = self.get_setting(session, 'regexp') <NEW_LINE> if regex: <NEW_LINE> <INDENT> self.regexp = re.compile(regex) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ConfigFileException("Missing regexp setting for " "%s." % (self.id)) <NEW_LINE> <DEDENT> <DEDENT> def process_string(self, session, data): <NEW_LINE> <INDENT> if self.keep: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> l = self.regexp.findall(data) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> data = data.decode('utf-8') <NEW_LINE> l = self.regexp.findall(data) <NEW_LINE> <DEDENT> return self.char.join(l) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.regexp.sub(self.char, data) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> data = data.decode('utf-8') <NEW_LINE> try: <NEW_LINE> <INDENT> return self.regexp.sub(self.char, data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise
Strip, replace or keep data matching a regular expression.
62598fc33d592f4c4edbb152
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100, unique=True) <NEW_LINE> slug = models.SlugField(max_length=100, unique=True) <NEW_LINE> description = models.TextField(null=True, blank=True) <NEW_LINE> pic = models.ImageField(upload_to='images/catalog/categorievs', null=True, blank=True) <NEW_LINE> parent = models.ForeignKey('self', related_name='sub_categories', null=True, blank=True) <NEW_LINE> tags = models.CharField(max_length=100, null=True, blank=True, help_text='Comma-delimited set of SEO keywords for meta tag') <NEW_LINE> display_order = models.IntegerField(default=0) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_expended = models.BooleanField(default=False, help_text='Catergory will always shown expended') <NEW_LINE> created_on = models.DateTimeField(auto_now_add=True, null=True,blank=True) <NEW_LINE> modified_on = models.DateTimeField(auto_now=True,null=True,blank=True) <NEW_LINE> created_by = models.ForeignKey(User, related_name="category_created_by", null=True,blank=True) <NEW_LINE> modified_by = models.ForeignKey(User, related_name="category_modified_by", null=True,blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('display_order', 'id',) <NEW_LINE> verbose_name_plural = 'Categories'
Represents a Category for Products
62598fc30fa83653e46f5181
class TestUpdateGetTestcaseKarma(BasePyTestCase): <NEW_LINE> <INDENT> def test_feedback_wrong_testcase(self): <NEW_LINE> <INDENT> update = model.Update.query.first() <NEW_LINE> tck = model.TestCaseKarma(karma=1, comment=update.comments[0], testcase=update.builds[0].testcases[0]) <NEW_LINE> self.db.add(tck) <NEW_LINE> testcase = model.TestCase(name='a testcase') <NEW_LINE> update.builds[0].testcases.append(testcase) <NEW_LINE> bad, good = update.get_testcase_karma(testcase) <NEW_LINE> assert bad == 0 <NEW_LINE> assert good == 0 <NEW_LINE> <DEDENT> def test_mixed_feedback(self): <NEW_LINE> <INDENT> update = model.Update.query.first() <NEW_LINE> for i, karma in enumerate([-1, 1, 1]): <NEW_LINE> <INDENT> user = model.User(name='user_{}'.format(i)) <NEW_LINE> comment = model.Comment(text='Test comment', karma=karma, user=user) <NEW_LINE> self.db.add(comment) <NEW_LINE> update.comments.append(comment) <NEW_LINE> testcase_karma = model.TestCaseKarma(karma=karma, comment=comment, testcase=update.builds[0].testcases[0]) <NEW_LINE> self.db.add(testcase_karma) <NEW_LINE> <DEDENT> bad, good = update.get_testcase_karma(update.builds[0].testcases[0]) <NEW_LINE> assert bad == -1 <NEW_LINE> assert good == 2 <NEW_LINE> user = model.User(name='bodhi') <NEW_LINE> comment = model.Comment(text="New build", karma=0, user=user) <NEW_LINE> self.db.add(comment) <NEW_LINE> update.comments.append(comment) <NEW_LINE> bad, good = update.get_testcase_karma(update.builds[0].testcases[0]) <NEW_LINE> assert bad == 0 <NEW_LINE> assert good == 0
Test the get_testcase_karma() method.
62598fc3956e5f7376df57cc
class Typed(Core): <NEW_LINE> <INDENT> def __init__(self, schema): <NEW_LINE> <INDENT> self.resolver = NodeResolver(schema) <NEW_LINE> <DEDENT> def process(self, node, type): <NEW_LINE> <INDENT> content = Content(node) <NEW_LINE> content.type = type <NEW_LINE> return Core.process(self, content) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> log.debug('reset') <NEW_LINE> self.resolver.reset() <NEW_LINE> <DEDENT> def start(self, content): <NEW_LINE> <INDENT> if content.type is None: <NEW_LINE> <INDENT> found = self.resolver.find(content.node) <NEW_LINE> if found is None: <NEW_LINE> <INDENT> log.error(self.resolver.schema) <NEW_LINE> raise TypeNotFound(content.node.qname()) <NEW_LINE> <DEDENT> content.type = found <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> known = self.resolver.known(content.node) <NEW_LINE> frame = Frame(content.type, resolved=known) <NEW_LINE> self.resolver.push(frame) <NEW_LINE> <DEDENT> real = self.resolver.top().resolved <NEW_LINE> content.real = real <NEW_LINE> cls_name = real.name <NEW_LINE> if cls_name is None: <NEW_LINE> <INDENT> cls_name = content.node.name <NEW_LINE> <DEDENT> content.data = Factory.object(cls_name) <NEW_LINE> md = content.data.__metadata__ <NEW_LINE> md.sxtype = real <NEW_LINE> <DEDENT> def end(self, content): <NEW_LINE> <INDENT> self.resolver.pop() <NEW_LINE> <DEDENT> def multi_occurrence(self, content): <NEW_LINE> <INDENT> return content.type.multi_occurrence() <NEW_LINE> <DEDENT> def nillable(self, content): <NEW_LINE> <INDENT> resolved = content.type.resolve() <NEW_LINE> return ( content.type.nillable or (resolved.builtin() and resolved.nillable ) ) <NEW_LINE> <DEDENT> def append_attribute(self, name, value, content): <NEW_LINE> <INDENT> type = self.resolver.findattr(name) <NEW_LINE> if type is None: <NEW_LINE> <INDENT> log.warn('attribute (%s) type, not-found', name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = self.translated(value, type) <NEW_LINE> <DEDENT> Core.append_attribute(self, name, value, content) <NEW_LINE> <DEDENT> def append_text(self, content): <NEW_LINE> <INDENT> Core.append_text(self, content) <NEW_LINE> known = self.resolver.top().resolved <NEW_LINE> content.text = self.translated(content.text, known) <NEW_LINE> <DEDENT> def translated(self, value, type): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> resolved = type.resolve() <NEW_LINE> return resolved.translate(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value
A I{typed} XML unmarshaller @ivar resolver: A schema type resolver. @type resolver: L{NodeResolver}
62598fc363b5f9789fe8540f
class BJ_Deck(cards.Deck): <NEW_LINE> <INDENT> def populate(self): <NEW_LINE> <INDENT> for suit in BJ_Card.SUITS: <NEW_LINE> <INDENT> for rank in BJ_Card.RANKS: <NEW_LINE> <INDENT> self.cards.append(BJ_Card(rank, suit))
Deck of cards required to plaj BJ
62598fc37d847024c075c659
class DomainWhitelist(models.Model): <NEW_LINE> <INDENT> domain = models.CharField(validators=[domain_validator], max_length=255) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.domain
A white list of external domains that we can redirect users to This is currently only used to verify the next url on the /logout/ page
62598fc357b8e32f5250826c
class ExcHandler(object): <NEW_LINE> <INDENT> def __init__(self, testname, todohandler): <NEW_LINE> <INDENT> self.testname = testname <NEW_LINE> self.todohandler = todohandler <NEW_LINE> self.screenpath = os.path.join("tests/logs", testname + ".png") <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, ex_type, ex_val, tb): <NEW_LINE> <INDENT> if ex_type: <NEW_LINE> <INDENT> self.todohandler.take_screenshot(self.screenpath) <NEW_LINE> allure_attach_file(self.screenpath, self.testname, "PNG") <NEW_LINE> pytest.fail(traceback.format_exception_only(ex_type, ex_val)[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.todohandler.take_screenshot(self.screenpath) <NEW_LINE> allure_attach_file(self.screenpath, self.testname, "PNG")
Контекст менеджер для перехвата и обработки исключений При любой ошибке будет сделан скриншот.
62598fc392d797404e388cb0
class TaskLineRestView(BaseRestView): <NEW_LINE> <INDENT> def get_schema(self, submitted): <NEW_LINE> <INDENT> excludes = ('group_id',) <NEW_LINE> return get_add_edit_taskline_schema(excludes=excludes) <NEW_LINE> <DEDENT> def collection_get(self): <NEW_LINE> <INDENT> return self.context.lines <NEW_LINE> <DEDENT> def post_format(self, entry, edit, attributes): <NEW_LINE> <INDENT> if not edit: <NEW_LINE> <INDENT> entry.group = self.context <NEW_LINE> <DEDENT> if 'tva' in attributes and 'product_id' not in attributes and entry.tva is not None: <NEW_LINE> <INDENT> entry.product_id = Product.first_by_tva_value(entry.tva) <NEW_LINE> <DEDENT> return entry <NEW_LINE> <DEDENT> def post_load_lines_from_catalog_view(self): <NEW_LINE> <INDENT> logger.debug("post_load_from_catalog_view") <NEW_LINE> sale_product_ids = self.request.json_body.get('sale_product_ids', []) <NEW_LINE> logger.debug("sale_product_ids : %s", sale_product_ids) <NEW_LINE> lines = [] <NEW_LINE> for id_ in sale_product_ids: <NEW_LINE> <INDENT> sale_product = SaleProduct.get(id_) <NEW_LINE> line = TaskLine.from_sale_product(sale_product) <NEW_LINE> self.context.lines.append(line) <NEW_LINE> lines.append(line) <NEW_LINE> <DEDENT> self.request.dbsession.merge(self.context) <NEW_LINE> return lines
Rest views used to handle the task lines Collection views : Context Task GET Return all the items belonging to the parent task POST Add a new item Item views GET Return the Item PUT/PATCH Edit the item DELETE Delete the item
62598fc3442bda511e95c6fc
class trip_weighted_average_time_hbw_from_home_am_transit_walk(Variable): <NEW_LINE> <INDENT> def dependencies(self): <NEW_LINE> <INDENT> return [my_attribute_label("zone_id"), "psrc.zone.trip_weighted_average_time_hbw_from_home_am_transit_walk"] <NEW_LINE> <DEDENT> def compute(self, dataset_pool): <NEW_LINE> <INDENT> zones = dataset_pool.get_dataset('zone') <NEW_LINE> return self.get_dataset().get_join_data(zones, "trip_weighted_average_time_hbw_from_home_am_transit_walk")
Value of this variable from this gridcell's zone.
62598fc3dc8b845886d53858
class ProcessSampler(RandomSampler): <NEW_LINE> <INDENT> def __init__(self, data_source, augments=(('resize', [(128, 128)]))): <NEW_LINE> <INDENT> super(ProcessSampler, self).__init__(data_source) <NEW_LINE> self.augments = augments <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> super_iter = self(ProcessSampler, self).__iter__() <NEW_LINE> for item in super_iter: <NEW_LINE> <INDENT> yield self.preprocess_image(item) <NEW_LINE> <DEDENT> <DEDENT> def preprocess_image(self, numpy_arr): <NEW_LINE> <INDENT> img = numpy_arr <NEW_LINE> if len(img.shape) < 3: <NEW_LINE> <INDENT> img = Augments.extend(img) <NEW_LINE> <DEDENT> for augment_fn, augment_params in self.augments: <NEW_LINE> <INDENT> img = Augments.__dict__[augment_fn].__func__(img, *augment_params) <NEW_LINE> <DEDENT> return img
Samples randomly over our dataset, and performs augmentation on sample :param data_source: instance of PixDataset :param augments: list containing tuples of ('func_name', [args]), where [args] must be at least [] and func_name must be a valid static function in the Augments class **order of augment functions matters**
62598fc37b180e01f3e4919e
class Application(LoggingApp): <NEW_LINE> <INDENT> name = "insulaudit" <NEW_LINE> devices = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> kwds = { 'root': True } <NEW_LINE> super(Application, self).__init__(**kwds) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> super(Application, self).setup( ) <NEW_LINE> utils.setup_global_options(self.argparser) <NEW_LINE> self.setup_commands( ) <NEW_LINE> <DEDENT> def pre_run(self): <NEW_LINE> <INDENT> super(Application, self).pre_run() <NEW_LINE> key = getattr(self.params, self.dest( ), None) <NEW_LINE> device = self.devices[key] <NEW_LINE> self.selected = device <NEW_LINE> if callable(device.pre_run): <NEW_LINE> <INDENT> device.pre_run(self) <NEW_LINE> <DEDENT> <DEDENT> def dest(self): <NEW_LINE> <INDENT> return 'device' <NEW_LINE> <DEDENT> def help(self): <NEW_LINE> <INDENT> return getattr(self, '__doc__', '').splitlines( )[0] <NEW_LINE> <DEDENT> def title(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_command_kwds(self): <NEW_LINE> <INDENT> fields = [ 'dest', 'title', 'help' ] <NEW_LINE> kwds = dict((f, getattr(self, f, None)( )) for f in fields) <NEW_LINE> kwds['description'] = self.description <NEW_LINE> return kwds <NEW_LINE> <DEDENT> def setup_commands(self): <NEW_LINE> <INDENT> kwds = self.get_command_kwds( ) <NEW_LINE> self.commands = self.argparser.add_subparsers(**kwds) <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> self.selected.main(self)
Test Hello World
62598fc371ff763f4b5e7a1a
class Token(ABC): <NEW_LINE> <INDENT> HAS_PATTERN = False <NEW_LINE> @abstractmethod <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.content + "\n"
The abstract base class (ABC) for all tokens. Each non-abstract child class must have a ``content`` attribute. If the token is not a combination of other tokens, that ``content`` attribute must be a string of the original content of the raw line of text. Otherwise, the ``content`` attribute is the list of subtokens. This class and all child classes have a boolean class attribute named ``HAS_PATTERN``. If ``HAS_PATTERN`` is True, the class has a corresponding regular expression in patterns.py.
62598fc34f88993c371f0659
class EF_CallconfC(TransparentEF): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(fid='6ff2', sfid=None, name='EF.CallconfC', size={24, 24}, desc='Call Configuration of emergency calls Configuration') <NEW_LINE> self._construct = Struct('pl_conf'/PlConfAdapter(Int8ub), 'conf_nr'/BcdAdapter(Bytes(8)), 'max_rand'/Int8ub, 'n_ack_max'/Int16ub, 'pl_ack'/PlCallAdapter(Int8ub), 'n_nested_max'/Int8ub, 'train_emergency_gid'/Int8ub, 'shunting_emergency_gid'/Int8ub, 'imei'/BcdAdapter(Bytes(8)))
Section 7.3
62598fc34a966d76dd5ef172
class DirectoryChanger(object): <NEW_LINE> <INDENT> def change(self, directory=None): <NEW_LINE> <INDENT> os.chdir(directory)
Change current directory
62598fc376e4537e8c3ef843
class QuantumBlock(Statement): <NEW_LINE> <INDENT> def __init__(self, statements=None, loops=None): <NEW_LINE> <INDENT> self.statements = statements <NEW_LINE> self.loops = loops <NEW_LINE> <DEDENT> def eval(self): <NEW_LINE> <INDENT> x={ 'type': 'quantumBlock', 'stmts': [] } <NEW_LINE> if self.statements!=None: <NEW_LINE> <INDENT> if type(self.statements)!=type([]): <NEW_LINE> <INDENT> x['stmts']=self.statements.eval() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for each in self.statements: <NEW_LINE> <INDENT> if each: <NEW_LINE> <INDENT> x['stmts'].append(each.eval()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if self.loops!=None: <NEW_LINE> <INDENT> if type(self.loops)!=type([]): <NEW_LINE> <INDENT> x['loops']=self.loops.eval() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x['loops']=[x.eval() for x in self.loops] <NEW_LINE> <DEDENT> <DEDENT> return x
quantumBlock = | { quantumStatement } | { quantumLoop } | { quantumStatement* | quantumLoop*}
62598fc3e1aae11d1e7ce974
class CellChannelDescription(Packet): <NEW_LINE> <INDENT> name = "Cell Channel Description " <NEW_LINE> fields_desc = [ BitField("bit128", 0x0, 1), BitField("bit127", 0x0, 1), BitField("spare1", 0x0, 1), BitField("spare2", 0x0, 1), BitField("bit124", 0x0, 1), BitField("bit123", 0x0, 1), BitField("bit122", 0x0, 1), BitField("bit121", 0x0, 1), ByteField("bit120", 0x0), ByteField("bit112", 0x0), ByteField("bit104", 0x0), ByteField("bit96", 0x0), ByteField("bit88", 0x0), ByteField("bit80", 0x0), ByteField("bit72", 0x0), ByteField("bit64", 0x0), ByteField("bit56", 0x0), ByteField("bit48", 0x0), ByteField("bit40", 0x0), ByteField("bit32", 0x0), ByteField("bit24", 0x0), ByteField("bit16", 0x0), ByteField("bit8", 0x0) ]
Cell Channel Description Section 10.5.2.1b
62598fc3956e5f7376df57cd
class InstalledAddOnExtensionInstance(InstanceResource): <NEW_LINE> <INDENT> def __init__(self, version, payload, installed_add_on_sid, sid=None): <NEW_LINE> <INDENT> super(InstalledAddOnExtensionInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload.get('sid'), 'installed_add_on_sid': payload.get('installed_add_on_sid'), 'friendly_name': payload.get('friendly_name'), 'product_name': payload.get('product_name'), 'unique_name': payload.get('unique_name'), 'enabled': payload.get('enabled'), 'url': payload.get('url'), } <NEW_LINE> self._context = None <NEW_LINE> self._solution = { 'installed_add_on_sid': installed_add_on_sid, 'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = InstalledAddOnExtensionContext( self._version, installed_add_on_sid=self._solution['installed_add_on_sid'], sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def installed_add_on_sid(self): <NEW_LINE> <INDENT> return self._properties['installed_add_on_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def friendly_name(self): <NEW_LINE> <INDENT> return self._properties['friendly_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def product_name(self): <NEW_LINE> <INDENT> return self._properties['product_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_name(self): <NEW_LINE> <INDENT> return self._properties['unique_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def enabled(self): <NEW_LINE> <INDENT> return self._properties['enabled'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def update(self, enabled): <NEW_LINE> <INDENT> return self._proxy.update(enabled, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Preview.Marketplace.InstalledAddOnExtensionInstance {}>'.format(context)
PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
62598fc3283ffb24f3cf3b22
class ModelMixin: <NEW_LINE> <INDENT> model = None <NEW_LINE> def __init__(self, model=None, url_part=None, **kwargs): <NEW_LINE> <INDENT> if model is not None: <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> elif self.model is None: <NEW_LINE> <INDENT> raise ValueError( "No ``model`` argument provided to __init__" ", and no model defined as class attribute (in {})" "".format(self) ) <NEW_LINE> <DEDENT> if url_part is not None: <NEW_LINE> <INDENT> self.url_part = url_part <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.url_part = self.model_url_part <NEW_LINE> <DEDENT> super().__init__(**kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def model_url_part(self): <NEW_LINE> <INDENT> return self.model._meta.model_name <NEW_LINE> <DEDENT> def get_register_map_kwargs(self): <NEW_LINE> <INDENT> kwargs = super().get_register_map_kwargs() <NEW_LINE> kwargs['model'] = self.model <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def get_base_store_kwargs(self): <NEW_LINE> <INDENT> kwargs = super().get_base_store_kwargs() <NEW_LINE> kwargs['model'] = self.model <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_register_class_map(cls): <NEW_LINE> <INDENT> mapping = super().get_register_class_map() <NEW_LINE> mapping[SingleObjectMixin, MultipleObjectMixin] = ( ModelViewRoute.make_for_view ) <NEW_LINE> return mapping
ModelRouter with no views. Give :attr:`model` kwarg where needed, ask it in :func:`__init__`, and map ``SingleObjectMixin`` and ``MultipleObjectMixin`` to :class:`django_crucrudile.routes.ModelViewRoute` in register functions. .. inheritance-diagram:: ModelMixin
62598fc392d797404e388cb1
class F6s(Platform): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.platformName = "F6s" <NEW_LINE> self.tags = ["jobs"] <NEW_LINE> self.isValidMode = {} <NEW_LINE> self.isValidMode["phonefy"] = False <NEW_LINE> self.isValidMode["usufy"] = True <NEW_LINE> self.isValidMode["searchfy"] = False <NEW_LINE> self.url = {} <NEW_LINE> self.url["usufy"] = "https://f6s.com/" + "<usufy>" <NEW_LINE> self.needsCredentials = {} <NEW_LINE> self.needsCredentials["usufy"] = False <NEW_LINE> self.validQuery = {} <NEW_LINE> self.validQuery["usufy"] = ".+" <NEW_LINE> self.notFoundText = {} <NEW_LINE> self.notFoundText["usufy"] = ["<title>404 - Page Not Found</title>"] <NEW_LINE> self.fieldsRegExp = {} <NEW_LINE> self.fieldsRegExp["usufy"] = {} <NEW_LINE> self.foundFields = {}
A <Platform> object for F6s.
62598fc3a219f33f346c6aa6
class LazyDijkstra: <NEW_LINE> <INDENT> def __init__(self, weighted_grapgh: WeightedGraph, start): <NEW_LINE> <INDENT> self.__g = weighted_grapgh <NEW_LINE> self.__marked = set() <NEW_LINE> self.__pq = Heap(compare) <NEW_LINE> self._dist_to = dict() <NEW_LINE> self._edge_to = dict() <NEW_LINE> self._start = start <NEW_LINE> self._dist_to[start] = 0 <NEW_LINE> self._relax(start) <NEW_LINE> while not self.__pq.is_empty(): <NEW_LINE> <INDENT> e = self.__pq.pop() <NEW_LINE> if e.v2 not in self.__marked: <NEW_LINE> <INDENT> self._relax(e.v2) <NEW_LINE> <DEDENT> <DEDENT> del self.__g <NEW_LINE> del self.__marked <NEW_LINE> del self.__pq <NEW_LINE> <DEDENT> def _relax(self, v): <NEW_LINE> <INDENT> self.__marked.add(v) <NEW_LINE> for e in self.__g.adj(v): <NEW_LINE> <INDENT> if e.v2 not in self._dist_to or self._dist_to.get(e.v2) > self._dist_to[v] + e.weight: <NEW_LINE> <INDENT> self._edge_to[e.v2] = e <NEW_LINE> self._dist_to[e.v2] = self._dist_to[v] + e.weight <NEW_LINE> self.__pq.insert(e) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def dist_to(self, v): <NEW_LINE> <INDENT> return self._dist_to.get(v) <NEW_LINE> <DEDENT> def path_to(self, v): <NEW_LINE> <INDENT> if v not in self._edge_to: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> edges = [] <NEW_LINE> e = self._edge_to[v] <NEW_LINE> while e.v1 != self._start: <NEW_LINE> <INDENT> edges.append(e) <NEW_LINE> e = self._edge_to[e.v1] <NEW_LINE> <DEDENT> edges.append(e) <NEW_LINE> edges.reverse() <NEW_LINE> return edges
alg-1 p421 延时版Dijkstra有向图最短路径算法,不能处理含有负权重的图 时间复杂度 O(ElogE)
62598fc3d8ef3951e32c7fab
class RandomSampler(Sampler): <NEW_LINE> <INDENT> def __init__(self, data_source): <NEW_LINE> <INDENT> self.num_samples = len(data_source) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(torch.randperm(self.num_samples).long()) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.num_samples
Samples elements randomly, without replacement. Arguments: data_source (Dataset): dataset to sample from
62598fc33d592f4c4edbb156
class State: <NEW_LINE> <INDENT> def __init__(self, likes, save): <NEW_LINE> <INDENT> self.likes = likes <NEW_LINE> self.xp = likes * CONST.XP_FACTOR <NEW_LINE> self.level = int(self.xp / 10) <NEW_LINE> if(save): <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.load() <NEW_LINE> <DEDENT> <DEDENT> def likes(self, value): <NEW_LINE> <INDENT> self.likes = value <NEW_LINE> self.xp = value * CONST.XP_FACTOR <NEW_LINE> self.level = self.xp % 10 <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> fields = [ 'level' , 'xp', 'likes' ] <NEW_LINE> values = [ str(self.level), str(self.xp), str(self.likes) ] <NEW_LINE> Parser.updateSave(CONST.SAVE_FILE, 'save', fields, values) <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> if not Parser.exists(CONST.SAVE_FILE): <NEW_LINE> <INDENT> self.initState() <NEW_LINE> <DEDENT> self.likes = int( Parser.get(CONST.SAVE_FILE, 'save', 'likes') ) <NEW_LINE> self.xp = int( Parser.get(CONST.SAVE_FILE, 'save', 'xp') ) <NEW_LINE> self.level = int( Parser.get(CONST.SAVE_FILE, 'save', 'level') ) <NEW_LINE> return self <NEW_LINE> <DEDENT> def initState(self): <NEW_LINE> <INDENT> fields = [ 'level' , 'xp', 'likes' ] <NEW_LINE> values = [ '0', '0', '0' ] <NEW_LINE> Parser.updateSave(CONST.SAVE_FILE, 'save', fields, values) <NEW_LINE> <DEDENT> def text(self): <NEW_LINE> <INDENT> result = '' <NEW_LINE> result += 'Level: ' + str(self.level) <NEW_LINE> result += '\nXP: ' + str(self.xp) <NEW_LINE> result += '\nLikes: ' + str(self.likes) <NEW_LINE> need = (10 * (self.level + 1)) - self.xp <NEW_LINE> result += '\nYou need ' + str(need) + ' XP for next level\n' <NEW_LINE> return result
Represents the actual state of the user
62598fc3f548e778e596b83d
class AlphaBetaPlayer(IsolationPlayer): <NEW_LINE> <INDENT> def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> try: <NEW_LINE> <INDENT> depth = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> best_move = self.alphabeta(game, depth) <NEW_LINE> depth += 1 <NEW_LINE> <DEDENT> <DEDENT> except SearchTimeout: pass <NEW_LINE> return best_move <NEW_LINE> <DEDENT> def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> def terminal_test(game): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> return not bool(game.get_legal_moves()) <NEW_LINE> <DEDENT> def max_value(game, alpha, beta, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if terminal_test(game) or depth == 0: <NEW_LINE> <INDENT> return self.score(game, self) <NEW_LINE> <DEDENT> v = float("-inf") <NEW_LINE> for m in game.get_legal_moves(): <NEW_LINE> <INDENT> v = max(v, min_value(game.forecast_move(m), alpha, beta, depth-1)) <NEW_LINE> if v >= beta: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> alpha = max(alpha, v) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def min_value(game, alpha, beta, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if terminal_test(game) or depth == 0: <NEW_LINE> <INDENT> return self.score(game, self) <NEW_LINE> <DEDENT> v = float("inf") <NEW_LINE> for m in game.get_legal_moves(): <NEW_LINE> <INDENT> v = min(v, max_value(game.forecast_move(m), alpha, beta, depth-1)) <NEW_LINE> if v <= alpha: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> beta = min(beta, v) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> best_action = (-1, -1) <NEW_LINE> for move in game.get_legal_moves(): <NEW_LINE> <INDENT> v = min_value(game.forecast_move(move), alpha, beta, depth-1) <NEW_LINE> if v > alpha: <NEW_LINE> <INDENT> alpha = v <NEW_LINE> best_action = move <NEW_LINE> <DEDENT> <DEDENT> return best_action
Game-playing agent that chooses a move using iterative deepening minimax search with alpha-beta pruning. You must finish and test this player to make sure it returns a good move before the search time limit expires.
62598fc3a05bb46b3848ab0b
class Inverse(Player): <NEW_LINE> <INDENT> name = 'Inverse' <NEW_LINE> def strategy(self, opponent): <NEW_LINE> <INDENT> index = next((index for index,value in enumerate(opponent.history, start = 1) if value == 'D'), None) <NEW_LINE> if index == None: <NEW_LINE> <INDENT> return 'C' <NEW_LINE> <DEDENT> rnd_num = random.random() <NEW_LINE> if rnd_num < 1/abs(index): <NEW_LINE> <INDENT> return 'D' <NEW_LINE> <DEDENT> return 'C'
A player who defects with a probability that diminishes relative to how long ago the opponent defected.
62598fc399fddb7c1ca62f3c
class CFuncPtr(_CData): <NEW_LINE> <INDENT> def __bool__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> argtypes = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> errcheck = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> restype = property(lambda self: object(), lambda self, v: None, lambda self: None)
Function Pointer
62598fc34a966d76dd5ef174
class _BaseEvergreenObject(object): <NEW_LINE> <INDENT> def __init__(self, json: Dict[str, Any], api: "EvergreenApi") -> None: <NEW_LINE> <INDENT> self.json = json <NEW_LINE> self._api = api <NEW_LINE> self._date_fields = None <NEW_LINE> <DEDENT> def _is_field_a_date(self, item: str) -> bool: <NEW_LINE> <INDENT> return bool(self._date_fields and item in self._date_fields and self.json[item]) <NEW_LINE> <DEDENT> def __getattr__(self, item: str) -> Any: <NEW_LINE> <INDENT> if item != "json" and item in self.json: <NEW_LINE> <INDENT> if self._is_field_a_date(item): <NEW_LINE> <INDENT> return parse_evergreen_datetime(self.json[item]) <NEW_LINE> <DEDENT> return self.json[item] <NEW_LINE> <DEDENT> raise AttributeError("Unknown attribute {0}".format(item)) <NEW_LINE> <DEDENT> def __eq__(self, other: Any) -> bool: <NEW_LINE> <INDENT> if isinstance(other, _BaseEvergreenObject): <NEW_LINE> <INDENT> return self.json == other.json <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __ne__(self, other: Any) -> bool: <NEW_LINE> <INDENT> return not self.__eq__(other)
Common evergreen object.
62598fc3aad79263cf42ea75
class GenericObjectList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> queryset = GenericObject.objects.all() <NEW_LINE> serializer = GenericObjectSerializer(queryset, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> if len(request.data) != 1: <NEW_LINE> <INDENT> return HttpResponseBadRequest('<h1>Bad Request</h1>') <NEW_LINE> <DEDENT> post_data = request.data <NEW_LINE> mapped_data = map_post_data(post_data) <NEW_LINE> serializer = GenericObjectSerializer(data=mapped_data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(map_get_data_to_user(serializer.data), status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
API endpoint that allows users to be viewed or edited.
62598fc34c3428357761a55c
class PoiExtHotelOrderCommitResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'surname': 'str', 'given_name': 'str', 'cn_name': 'str' } <NEW_LINE> attribute_map = { 'surname': 'surname', 'given_name': 'given_name', 'cn_name': 'cn_name' } <NEW_LINE> def __init__(self, surname=None, given_name=None, cn_name=None): <NEW_LINE> <INDENT> self._surname = None <NEW_LINE> self._given_name = None <NEW_LINE> self._cn_name = None <NEW_LINE> self.discriminator = None <NEW_LINE> if surname is not None: <NEW_LINE> <INDENT> self.surname = surname <NEW_LINE> <DEDENT> if given_name is not None: <NEW_LINE> <INDENT> self.given_name = given_name <NEW_LINE> <DEDENT> if cn_name is not None: <NEW_LINE> <INDENT> self.cn_name = cn_name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def surname(self): <NEW_LINE> <INDENT> return self._surname <NEW_LINE> <DEDENT> @surname.setter <NEW_LINE> def surname(self, surname): <NEW_LINE> <INDENT> self._surname = surname <NEW_LINE> <DEDENT> @property <NEW_LINE> def given_name(self): <NEW_LINE> <INDENT> return self._given_name <NEW_LINE> <DEDENT> @given_name.setter <NEW_LINE> def given_name(self, given_name): <NEW_LINE> <INDENT> self._given_name = given_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def cn_name(self): <NEW_LINE> <INDENT> return self._cn_name <NEW_LINE> <DEDENT> @cn_name.setter <NEW_LINE> def cn_name(self, cn_name): <NEW_LINE> <INDENT> self._cn_name = cn_name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(PoiExtHotelOrderCommitResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PoiExtHotelOrderCommitResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fc3ec188e330fdf8b34
class QdSchema(schema.Schema): <NEW_LINE> <INDENT> CONFIGURATION_ENTITY = "configurationEntity" <NEW_LINE> OPERATIONAL_ENTITY = "operationalEntity" <NEW_LINE> ROUTER_ID_MAX_LEN = 127 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> qd_schema = get_data('qpid_dispatch.management', 'qdrouter.json').decode('utf8') <NEW_LINE> try: <NEW_LINE> <INDENT> super(QdSchema, self).__init__(**json.loads(qd_schema, **JSON_LOAD_KWARGS)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise ValueError("Invalid schema qdrouter.json: %s" % e) <NEW_LINE> <DEDENT> self.configuration_entity = self.entity_type(self.CONFIGURATION_ENTITY) <NEW_LINE> self.operational_entity = self.entity_type(self.OPERATIONAL_ENTITY) <NEW_LINE> <DEDENT> def validate_add(self, attributes, entities): <NEW_LINE> <INDENT> entities = list(entities) <NEW_LINE> super(QdSchema, self).validate_add(attributes, entities) <NEW_LINE> entities.append(attributes) <NEW_LINE> router_mode = router_id = listener_connector_role = listener_role = None <NEW_LINE> for e in entities: <NEW_LINE> <INDENT> short_type = self.short_name(e['type']) <NEW_LINE> if short_type == "router": <NEW_LINE> <INDENT> router_mode = e['mode'] <NEW_LINE> if 'id' in e: <NEW_LINE> <INDENT> router_id = e['id'] <NEW_LINE> <DEDENT> <DEDENT> if short_type in ["listener", "connector"]: <NEW_LINE> <INDENT> if short_type == "listener": <NEW_LINE> <INDENT> listener_role = e['role'] <NEW_LINE> <DEDENT> list_conn_entity = e <NEW_LINE> listener_connector_role = e['role'] <NEW_LINE> <DEDENT> <DEDENT> if router_id is not None: <NEW_LINE> <INDENT> if len(router_id) > self.ROUTER_ID_MAX_LEN: <NEW_LINE> <INDENT> raise schema.ValidationError( 'Router ID "%s" exceeds the maximum allowed length (%d' ' characters)' % (router_id, self.ROUTER_ID_MAX_LEN)) <NEW_LINE> <DEDENT> <DEDENT> if router_mode and listener_connector_role: <NEW_LINE> <INDENT> if router_mode == "standalone" and listener_connector_role in ('inter-router', 'edge'): <NEW_LINE> <INDENT> raise schema.ValidationError( "role='standalone' not allowed to connect to or accept connections from other routers.") <NEW_LINE> <DEDENT> if router_mode != "interior" and listener_connector_role == "inter-router": <NEW_LINE> <INDENT> raise schema.ValidationError( "role='inter-router' only allowed with router mode='interior' for %s" % list_conn_entity) <NEW_LINE> <DEDENT> <DEDENT> if router_mode and listener_role: <NEW_LINE> <INDENT> if router_mode == "edge" and listener_role == "edge": <NEW_LINE> <INDENT> raise schema.ValidationError( "role='edge' only allowed with router mode='interior' for %s" % list_conn_entity) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def is_configuration(self, entity_type): <NEW_LINE> <INDENT> return entity_type and self.configuration_entity in entity_type.all_bases <NEW_LINE> <DEDENT> def is_operational(self, entity_type): <NEW_LINE> <INDENT> return entity_type and self.operational_entity in entity_type.all_bases
Qpid Dispatch Router management schema.
62598fc357b8e32f5250826e
class DescribeComputeEnvCreateInfosRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EnvIds = None <NEW_LINE> self.Filters = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.EnvIds = params.get("EnvIds") <NEW_LINE> if params.get("Filters") is not None: <NEW_LINE> <INDENT> self.Filters = [] <NEW_LINE> for item in params.get("Filters"): <NEW_LINE> <INDENT> obj = Filter() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Filters.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
DescribeComputeEnvCreateInfos请求参数结构体
62598fc355399d3f056267b8
class TestExport(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return Export( id = 56, created = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), account_id = 56, user_id = 56, entity = 'Coupon', filter = None ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return Export( id = 56, created = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), account_id = 56, user_id = 56, entity = 'Coupon', filter = None, ) <NEW_LINE> <DEDENT> <DEDENT> def testExport(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
Export unit test stubs
62598fc350812a4eaa620d35
class CommonGramTokenFilter(TokenFilter): <NEW_LINE> <INDENT> _validation = { 'odata_type': {'required': True}, 'name': {'required': True}, 'common_words': {'required': True}, } <NEW_LINE> _attribute_map = { 'odata_type': {'key': '@odata\\.type', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'common_words': {'key': 'commonWords', 'type': '[str]'}, 'ignore_case': {'key': 'ignoreCase', 'type': 'bool'}, 'use_query_mode': {'key': 'queryMode', 'type': 'bool'}, } <NEW_LINE> def __init__( self, *, name: str, common_words: List[str], ignore_case: Optional[bool] = False, use_query_mode: Optional[bool] = False, **kwargs ): <NEW_LINE> <INDENT> super(CommonGramTokenFilter, self).__init__(name=name, **kwargs) <NEW_LINE> self.odata_type = '#Microsoft.Azure.Search.CommonGramTokenFilter' <NEW_LINE> self.common_words = common_words <NEW_LINE> self.ignore_case = ignore_case <NEW_LINE> self.use_query_mode = use_query_mode
Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed too, with bigrams overlaid. This token filter is implemented using Apache Lucene. All required parameters must be populated in order to send to Azure. :ivar odata_type: Required. Identifies the concrete type of the token filter.Constant filled by server. :vartype odata_type: str :ivar name: Required. The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. :vartype name: str :ivar common_words: Required. The set of common words. :vartype common_words: list[str] :ivar ignore_case: A value indicating whether common words matching will be case insensitive. Default is false. :vartype ignore_case: bool :ivar use_query_mode: A value that indicates whether the token filter is in query mode. When in query mode, the token filter generates bigrams and then removes common words and single terms followed by a common word. Default is false. :vartype use_query_mode: bool
62598fc3377c676e912f6ec4
class Vector(object): <NEW_LINE> <INDENT> def toArray(self): <NEW_LINE> <INDENT> raise NotImplementedError
Abstract class for DenseVector and SparseVector
62598fc3442bda511e95c700
class AvailabilitySymlinks (object): <NEW_LINE> <INDENT> def __init__(self, dir_a, dir_e, supports_activation): <NEW_LINE> <INDENT> self.dir_a, self.dir_e = dir_a, dir_e <NEW_LINE> self.supports_activation = supports_activation <NEW_LINE> <DEDENT> def list_available(self): <NEW_LINE> <INDENT> return os.listdir(self.dir_a) <NEW_LINE> <DEDENT> def is_enabled(self, entry): <NEW_LINE> <INDENT> if not self.supports_activation: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.find_link(entry) is not None <NEW_LINE> <DEDENT> def get_path(self, entry): <NEW_LINE> <INDENT> return os.path.abspath(os.path.join(self.dir_a, entry)) <NEW_LINE> <DEDENT> def find_link(self, entry): <NEW_LINE> <INDENT> path = self.get_path(entry) <NEW_LINE> for e in os.listdir(self.dir_e): <NEW_LINE> <INDENT> if os.path.abspath(os.path.realpath(os.path.join(self.dir_e, e))) == path: <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def enable(self, entry): <NEW_LINE> <INDENT> if not self.supports_activation: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> e = self.find_link(entry) <NEW_LINE> if not e: <NEW_LINE> <INDENT> os.symlink(self.get_path(entry), os.path.join(self.dir_e, entry)) <NEW_LINE> <DEDENT> <DEDENT> def disable(self, entry): <NEW_LINE> <INDENT> if not self.supports_activation: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> e = self.find_link(entry) <NEW_LINE> if e: <NEW_LINE> <INDENT> os.unlink(os.path.join(self.dir_e, e)) <NEW_LINE> <DEDENT> <DEDENT> def rename(self, old, new): <NEW_LINE> <INDENT> on = self.is_enabled(old) <NEW_LINE> self.disable(old) <NEW_LINE> os.rename(self.get_path(old), self.get_path(new)) <NEW_LINE> if on: <NEW_LINE> <INDENT> self.enable(new) <NEW_LINE> <DEDENT> <DEDENT> def delete(self, entry): <NEW_LINE> <INDENT> self.disable(entry) <NEW_LINE> os.unlink(self.get_path(entry)) <NEW_LINE> <DEDENT> def open(self, entry, mode='r'): <NEW_LINE> <INDENT> return open(os.path.join(self.dir_a, entry), mode) <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> return os.path.exists(self.dir_a) and os.path.exists(self.dir_e)
Manage directories of following style:: --sites.available |-a.site --b.site --sites.enabled --a.site -> ../sites.available/a.site
62598fc3ff9c53063f51a8ee
class Robot(object): <NEW_LINE> <INDENT> def __init__(self, name, version, image_url='', profile_url=''): <NEW_LINE> <INDENT> self._handlers = {} <NEW_LINE> self.name = name <NEW_LINE> self.version = version <NEW_LINE> self.image_url = image_url <NEW_LINE> self.profile_url = profile_url <NEW_LINE> self.cron_jobs = [] <NEW_LINE> <DEDENT> def RegisterListener(self, listener): <NEW_LINE> <INDENT> for event in dir(events): <NEW_LINE> <INDENT> if event.startswith('_'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> lowercase_method_name = 'on_' + event.lower() <NEW_LINE> camelcase_method_name = 'On' + util.ToUpperCamelCase(event) <NEW_LINE> if hasattr(listener, lowercase_method_name): <NEW_LINE> <INDENT> handler = getattr(listener, lowercase_method_name) <NEW_LINE> <DEDENT> elif hasattr(listener, camelcase_method_name): <NEW_LINE> <INDENT> handler = getattr(listener, camelcase_method_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if callable(handler): <NEW_LINE> <INDENT> self.RegisterHandler(event, handler) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def RegisterHandler(self, event_type, handler): <NEW_LINE> <INDENT> self._handlers.setdefault(event_type, []).append(handler) <NEW_LINE> <DEDENT> def RegisterCronJob(self, path, seconds): <NEW_LINE> <INDENT> self.cron_jobs.append((path, seconds)) <NEW_LINE> <DEDENT> def HandleEvent(self, event, context): <NEW_LINE> <INDENT> for handler in self._handlers.get(event.type, []): <NEW_LINE> <INDENT> handler(event.properties, context) <NEW_LINE> <DEDENT> <DEDENT> def GetCapabilitiesXml(self): <NEW_LINE> <INDENT> lines = ['<w:version>%s</w:version>' % self.version] <NEW_LINE> lines.append('<w:capabilities>') <NEW_LINE> for capability in self._handlers: <NEW_LINE> <INDENT> if str(capability) is not "CRON_EVENT": <NEW_LINE> <INDENT> lines.append(' <w:capability name="%s"/>' % capability) <NEW_LINE> <DEDENT> <DEDENT> lines.append('</w:capabilities>') <NEW_LINE> if self.cron_jobs: <NEW_LINE> <INDENT> lines.append('<w:crons>') <NEW_LINE> for job in self.cron_jobs: <NEW_LINE> <INDENT> lines.append(' <w:cron path="%s" timerinseconds="%s"/>' % job) <NEW_LINE> <DEDENT> lines.append('</w:crons>') <NEW_LINE> <DEDENT> robot_attrs = ' name="%s"' % self.name <NEW_LINE> if self.image_url: <NEW_LINE> <INDENT> robot_attrs += ' imageurl="%s"' % self.image_url <NEW_LINE> <DEDENT> if self.profile_url: <NEW_LINE> <INDENT> robot_attrs += ' profileurl="%s"' % self.profile_url <NEW_LINE> <DEDENT> lines.append('<w:profile%s/>' % robot_attrs) <NEW_LINE> return ('<?xml version="1.0"?>\n' '<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n' '%s\n</w:robot>\n') % ('\n'.join(lines)) <NEW_LINE> <DEDENT> def GetProfileJson(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> data['name'] = self.name <NEW_LINE> data['imageUrl'] = self.image_url <NEW_LINE> data['profileUrl'] = self.profile_url <NEW_LINE> data['javaClass'] = 'com.google.wave.api.ParticipantProfile' <NEW_LINE> return simplejson.dumps(data)
Robot metadata class. This class holds on to basic robot information like the name and profile. It also maintains the list of event handlers and cron jobs and dispatches events to the appropriate handlers.
62598fc34527f215b58ea170
class OdomNode(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.sub_odom = rospy.Subscriber("odom", Odometry, self.odom_callback) <NEW_LINE> self.tfBroad = tf.TransformBroadcaster() <NEW_LINE> <DEDENT> def odom_callback(self, msg): <NEW_LINE> <INDENT> trans = (msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z) <NEW_LINE> rot = (msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w) <NEW_LINE> self.tfBroad.sendTransform(translation = trans, rotation = rot, time = msg.header.stamp, parent = '/world', child = '/base_footprint')
Class to hold all ROS related transactions to use split and merge algorithm.
62598fc39f288636728189cc
class RetryDetail(AtomDetail): <NEW_LINE> <INDENT> def __init__(self, name, uuid): <NEW_LINE> <INDENT> super(RetryDetail, self).__init__(name, uuid) <NEW_LINE> self.results = [] <NEW_LINE> <DEDENT> def reset(self, state): <NEW_LINE> <INDENT> self.results = [] <NEW_LINE> self.failure = None <NEW_LINE> self.state = state <NEW_LINE> self.intention = states.EXECUTE <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_results(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.results[-1][0] <NEW_LINE> <DEDENT> except IndexError as e: <NEW_LINE> <INDENT> raise exc.NotFound("Last results not found", e) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def last_failures(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.results[-1][1] <NEW_LINE> <DEDENT> except IndexError as e: <NEW_LINE> <INDENT> raise exc.NotFound("Last failures not found", e) <NEW_LINE> <DEDENT> <DEDENT> def put(self, state, result): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> if _was_failure(state, result): <NEW_LINE> <INDENT> self.failure = result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.results.append((result, {})) <NEW_LINE> self.failure = None <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, data): <NEW_LINE> <INDENT> def decode_results(results): <NEW_LINE> <INDENT> if not results: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> new_results = [] <NEW_LINE> for (data, failures) in results: <NEW_LINE> <INDENT> new_failures = {} <NEW_LINE> for (key, data) in six.iteritems(failures): <NEW_LINE> <INDENT> new_failures[key] = ft.Failure.from_dict(data) <NEW_LINE> <DEDENT> new_results.append((data, new_failures)) <NEW_LINE> <DEDENT> return new_results <NEW_LINE> <DEDENT> obj = cls(data['name'], data['uuid']) <NEW_LINE> obj._from_dict_shared(data) <NEW_LINE> obj.results = decode_results(obj.results) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> def encode_results(results): <NEW_LINE> <INDENT> if not results: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> new_results = [] <NEW_LINE> for (data, failures) in results: <NEW_LINE> <INDENT> new_failures = {} <NEW_LINE> for (key, failure) in six.iteritems(failures): <NEW_LINE> <INDENT> new_failures[key] = failure.to_dict() <NEW_LINE> <DEDENT> new_results.append((data, new_failures)) <NEW_LINE> <DEDENT> return new_results <NEW_LINE> <DEDENT> base = self._to_dict_shared() <NEW_LINE> base['results'] = encode_results(base.get('results')) <NEW_LINE> return base <NEW_LINE> <DEDENT> def merge(self, other, deep_copy=False): <NEW_LINE> <INDENT> if not isinstance(other, RetryDetail): <NEW_LINE> <INDENT> raise exc.NotImplementedError("Can only merge with other" " retry details") <NEW_LINE> <DEDENT> if other is self: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> super(RetryDetail, self).merge(other, deep_copy=deep_copy) <NEW_LINE> results = [] <NEW_LINE> for (data, failures) in other.results: <NEW_LINE> <INDENT> copied_failures = {} <NEW_LINE> for (key, failure) in six.iteritems(failures): <NEW_LINE> <INDENT> if deep_copy: <NEW_LINE> <INDENT> copied_failures[key] = failure.copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> copied_failures[key] = failure <NEW_LINE> <DEDENT> <DEDENT> results.append((data, copied_failures)) <NEW_LINE> <DEDENT> self.results = results <NEW_LINE> return self
This class represents a retry detail for retry controller object.
62598fc3656771135c489910
class _CoordMetaData(namedtuple('CoordMetaData', ['defn', 'dims', 'points_dtype', 'bounds_dtype', 'kwargs'])): <NEW_LINE> <INDENT> def __new__(cls, coord, dims): <NEW_LINE> <INDENT> defn = coord._as_defn() <NEW_LINE> points_dtype = coord.points.dtype <NEW_LINE> bounds_dtype = coord.bounds.dtype if coord.bounds is not None else None <NEW_LINE> kwargs = {} <NEW_LINE> if hasattr(coord, 'circular'): <NEW_LINE> <INDENT> kwargs['circular'] = coord.circular <NEW_LINE> <DEDENT> if isinstance(coord, iris.coords.DimCoord): <NEW_LINE> <INDENT> if coord.points[0] == coord.points[-1]: <NEW_LINE> <INDENT> order = _CONSTANT <NEW_LINE> <DEDENT> elif coord.points[-1] > coord.points[0]: <NEW_LINE> <INDENT> order = _INCREASING <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> order = _DECREASING <NEW_LINE> <DEDENT> kwargs['order'] = order <NEW_LINE> <DEDENT> metadata = super(_CoordMetaData, cls).__new__(cls, defn, dims, points_dtype, bounds_dtype, kwargs) <NEW_LINE> return metadata
Container for the metadata that defines a dimension or auxiliary coordinate. Args: * defn: The :class:`iris.coords.CoordDefn` metadata that represents a coordinate. * dims: The dimension(s) associated with the coordinate. * points_dtype: The points data :class:`np.dtype` of an associated coordinate. * bounds_dtype: The bounds data :class:`np.dtype` of an associated coordinate. * kwargs: A dictionary of key/value pairs required to define a coordinate.
62598fc32c8b7c6e89bd3a64
class RenewInstanceRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Period = None <NEW_LINE> self.InstanceId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Period = params.get("Period") <NEW_LINE> self.InstanceId = params.get("InstanceId")
RenewInstance request structure.
62598fc371ff763f4b5e7a1e
class IntegrationSQS(testing.AsyncTestCase): <NEW_LINE> <INDENT> integration = True <NEW_LINE> queue_name = 'integration-test-%s' % UUID <NEW_LINE> region = 'us-east-1' <NEW_LINE> @attr('integration', 'dry') <NEW_LINE> @testing.gen_test(timeout=60) <NEW_LINE> def integration_01a_create_queue_dry(self): <NEW_LINE> <INDENT> actor = sqs.Create( 'Create %s' % self.queue_name, {'name': self.queue_name, 'region': self.region}, dry=True) <NEW_LINE> done = yield actor.execute() <NEW_LINE> self.assertEquals(done, None) <NEW_LINE> <DEDENT> @attr('integration') <NEW_LINE> @testing.gen_test(timeout=60) <NEW_LINE> def integration_01b_create_queue(self): <NEW_LINE> <INDENT> actor = sqs.Create( 'Create %s' % self.queue_name, {'name': self.queue_name, 'region': self.region}) <NEW_LINE> done = yield actor.execute() <NEW_LINE> self.assertEquals(done, None) <NEW_LINE> <DEDENT> @attr('integration', 'dry') <NEW_LINE> @testing.gen_test(timeout=60) <NEW_LINE> def integration_02a_monitor_queue_dry(self): <NEW_LINE> <INDENT> actor = sqs.WaitUntilEmpty('Wait until empty', {'name': self.queue_name, 'region': self.region}, dry=True) <NEW_LINE> done = yield actor.execute() <NEW_LINE> self.assertEquals(done, None) <NEW_LINE> <DEDENT> @attr('integration') <NEW_LINE> @testing.gen_test(timeout=60) <NEW_LINE> def integration_02b_monitor_queue(self): <NEW_LINE> <INDENT> actor = sqs.WaitUntilEmpty('Wait until empty', {'name': self.queue_name, 'region': self.region}) <NEW_LINE> log.debug('New queue should be empty') <NEW_LINE> queue = actor.sqs_conn.get_queue(self.queue_name) <NEW_LINE> self.assertEquals(queue.count(), 0) <NEW_LINE> done = yield actor.execute() <NEW_LINE> yield utils.tornado_sleep() <NEW_LINE> self.assertEquals(done, None) <NEW_LINE> <DEDENT> @attr('integration', 'dry') <NEW_LINE> @testing.gen_test() <NEW_LINE> def integration_03a_delete_queue_dry(self): <NEW_LINE> <INDENT> actor = sqs.Delete('Delete %s' % self.queue_name, {'name': self.queue_name, 'region': self.region, 'idempotent': True}, dry=True) <NEW_LINE> done = yield actor.execute() <NEW_LINE> self.assertEquals(done, None) <NEW_LINE> <DEDENT> @attr('integration') <NEW_LINE> @testing.gen_test(timeout=120) <NEW_LINE> def integration_03b_delete_queue(self): <NEW_LINE> <INDENT> actor = sqs.Delete('Delete %s' % self.queue_name, {'name': self.queue_name, 'region': self.region}) <NEW_LINE> done = yield actor.execute() <NEW_LINE> self.assertEquals(done, None) <NEW_LINE> <DEDENT> @attr('integration') <NEW_LINE> @testing.gen_test(timeout=120) <NEW_LINE> def integration_03c_delete_fake_queue(self): <NEW_LINE> <INDENT> settings.SQS_RETRY_DELAY = 0 <NEW_LINE> reload(sqs) <NEW_LINE> actor = sqs.Delete('Delete %s' % self.queue_name, {'name': 'totally-fake-queue', 'region': self.region}) <NEW_LINE> with self.assertRaises(sqs.QueueNotFound): <NEW_LINE> <INDENT> yield actor.execute()
High level SQS Actor testing. This suite of tests performs the following actions: * Create a queue with a randomized name * Add a few messages to the queue * Start the WaitUntilEmpty task * Check that this task is not exiting while there are messages * Remove all the messages from the queue * Check that the WaitUntilEmpty notices, and returns success * Delete the temporary queue Note, these tests must be run in-order. The order is defined by their definition order in this file. Nose follows this order according to its documentation: http://nose.readthedocs.org/en/latest/writing_tests.html
62598fc33d592f4c4edbb159
class FlagsService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'flags' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(SqladminV1beta3.FlagsService, self).__init__(client) <NEW_LINE> self._method_configs = { 'List': base_api.ApiMethodInfo( http_method=u'GET', method_id=u'sql.flags.list', ordered_params=[], path_params=[], query_params=[], relative_path=u'flags', request_field='', request_type_name=u'SqlFlagsListRequest', response_type_name=u'FlagsListResponse', supports_download=False, ), } <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def List(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('List') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Service class for the flags resource.
62598fc3851cf427c66b8557
class InputFormContainer(ViewElement): <NEW_LINE> <INDENT> def __init__(self, parent, view_types, collector): <NEW_LINE> <INDENT> ViewElement.__init__(self, parent) <NEW_LINE> self.__views = [] <NEW_LINE> for type_ in view_types: <NEW_LINE> <INDENT> self.__views.append(type_(self, collector)) <NEW_LINE> <DEDENT> self.grid_rowconfigure(0, weight=1) <NEW_LINE> self.grid_columnconfigure(0, weight=1) <NEW_LINE> self.pack_configure(fill="both", expand=True) <NEW_LINE> self.refresh() <NEW_LINE> <DEDENT> def refresh(self, i=0): <NEW_LINE> <INDENT> view = self.__views[i] <NEW_LINE> view.update() <NEW_LINE> view.tkraise() <NEW_LINE> view.set_focus() <NEW_LINE> <DEDENT> def collect_input(self, i): <NEW_LINE> <INDENT> view = self.__views[i] <NEW_LINE> view.collect_input()
Display the current input form. Attributes: parent: parent frame/view/window view_types (list): all available view types collector: data collector
62598fc3ad47b63b2c5a7af9
class AuthSignUpHandler(BaseHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> data = tornado.escape.json_decode(self.request.body) <NEW_LINE> username = data["username"] <NEW_LINE> password = hashlib.sha1( bytes( data["password"], "utf-8" ) ).hexdigest() <NEW_LINE> try: <NEW_LINE> <INDENT> db.Users.select().where(db.Users.name == username).get() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> db.Users.create( id=uuid.uuid4(), name=username, password=password, ) <NEW_LINE> self.write(json.dumps({'is_success': 'true'})) <NEW_LINE> self.set_secure_cookie("user", username) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.write(json.dumps({'is_success': 'false', 'reason': 'exsit'}))
Authorization API endpoint: /auth/signup
62598fc363b5f9789fe85415
class SearchItemsViewSet(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Item.objects.all() <NEW_LINE> serializer_class = ItemSerializer <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def filter_queryset(self, queryset): <NEW_LINE> <INDENT> return queryset.filter(name__contains=self.kwargs['pk'])
List all items from a specific tag.
62598fc3283ffb24f3cf3b26
class SettingsDialog(wx.Dialog): <NEW_LINE> <INDENT> def __init__(self, parent, id, title): <NEW_LINE> <INDENT> wx.Dialog.__init__(self, parent, id, title, size=(600, 250), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER, pos=wx.DefaultPosition) <NEW_LINE> self.parent = parent <NEW_LINE> self.safetyMode = self.parent.safetyMode <NEW_LINE> self.OverviewText = wx.StaticText(self, -1, _(u"This dialog gives you the possibility to set up Template-Designer. " + u"Please take the desired settings.")) <NEW_LINE> self.okayButton = wx.Button(self, wx.ID_OK, name="settingsOkButton") <NEW_LINE> self.okayButton.SetDefault() <NEW_LINE> self.okayButton.Disable() <NEW_LINE> self.cancelButton = wx.Button(self, wx.ID_CANCEL, name="settingsCancelButton") <NEW_LINE> self.__doProperties() <NEW_LINE> self.__doLayout() <NEW_LINE> Safety(self) <NEW_LINE> <DEDENT> def __doProperties(self): <NEW_LINE> <INDENT> self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY) <NEW_LINE> self.SetName("settingsDialog") <NEW_LINE> self.SetMinSize((600, 250)) <NEW_LINE> <DEDENT> def __doLayout(self): <NEW_LINE> <INDENT> buttonSizer = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> buttonSizer.Add(self.okayButton, 0, wx.ALL, 4) <NEW_LINE> buttonSizer.Add(self.cancelButton, 0, wx.ALL, 4) <NEW_LINE> noteBook = wx.Notebook(self) <NEW_LINE> noteBook.AddPage(ClientPathPanel(self, noteBook), _(u"Client Paths")) <NEW_LINE> noteBook.AddPage(ServerPathPanel(self, noteBook), _(u"Server Paths")) <NEW_LINE> noteBook.AddPage(PasswordPanel(self, noteBook), _(u"Passwords")) <NEW_LINE> allSizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> allSizer.Add(self.OverviewText, 0, wx.EXPAND|wx.ALL, 4) <NEW_LINE> allSizer.Add(noteBook, 1, wx.EXPAND|wx.ALL, 4) <NEW_LINE> allSizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 4) <NEW_LINE> allSizer.Add(buttonSizer, 0, wx.ALL|wx.ALIGN_RIGHT, 4) <NEW_LINE> self.SetSizer(allSizer) <NEW_LINE> self.Layout() <NEW_LINE> self.CenterOnParent()
The class settingsDialog is derived from wx.Dialog and builds a dialog to configure the applications settings
62598fc3956e5f7376df57cf
class NSNitroNserrSslPendingCmds(NSNitroSsl2Errors): <NEW_LINE> <INDENT> pass
Nitro error code 3625 Other commands (card health monitoring/traffic) are pending to FIPS card. Please try the firmware update command after some time
62598fc37d847024c075c65f
class loc: <NEW_LINE> <INDENT> def set_path(path = ''): <NEW_LINE> <INDENT> import os <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> if not os.chdir(path): <NEW_LINE> <INDENT> os.chdir(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> os.chdir(path) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise OSError('path not existing::'+ 'Ensure path is properly refrenced') <NEW_LINE> <DEDENT> <DEDENT> def read_csv(csv): <NEW_LINE> <INDENT> data = pd.read_csv(csv) <NEW_LINE> data = data.set_index('Date') <NEW_LINE> return data
Class Location: Contains elementary functions for getting path and data
62598fc3442bda511e95c702
class JSONPath(object): <NEW_LINE> <INDENT> def find(self, data): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def update(self, data, val): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def child(self, child): <NEW_LINE> <INDENT> if isinstance(self, This) or isinstance(self, Root): <NEW_LINE> <INDENT> return child <NEW_LINE> <DEDENT> elif isinstance(child, This): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> elif isinstance(child, Root): <NEW_LINE> <INDENT> return child <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Child(self, child) <NEW_LINE> <DEDENT> <DEDENT> def make_datum(self, value): <NEW_LINE> <INDENT> if isinstance(value, DatumInContext): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return DatumInContext(value, path=Root(), context=None)
The base class for JSONPath abstract syntax; those methods stubbed here are the interface to supported JSONPath semantics.
62598fc35fdd1c0f98e5e235
class SplitPptxPresentationResult(object): <NEW_LINE> <INDENT> swagger_types = { 'result_presentations': 'list[PresentationResult]', 'successful': 'bool' } <NEW_LINE> attribute_map = { 'result_presentations': 'ResultPresentations', 'successful': 'Successful' } <NEW_LINE> def __init__(self, result_presentations=None, successful=None): <NEW_LINE> <INDENT> self._result_presentations = None <NEW_LINE> self._successful = None <NEW_LINE> self.discriminator = None <NEW_LINE> if result_presentations is not None: <NEW_LINE> <INDENT> self.result_presentations = result_presentations <NEW_LINE> <DEDENT> if successful is not None: <NEW_LINE> <INDENT> self.successful = successful <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def result_presentations(self): <NEW_LINE> <INDENT> return self._result_presentations <NEW_LINE> <DEDENT> @result_presentations.setter <NEW_LINE> def result_presentations(self, result_presentations): <NEW_LINE> <INDENT> self._result_presentations = result_presentations <NEW_LINE> <DEDENT> @property <NEW_LINE> def successful(self): <NEW_LINE> <INDENT> return self._successful <NEW_LINE> <DEDENT> @successful.setter <NEW_LINE> def successful(self, successful): <NEW_LINE> <INDENT> self._successful = successful <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(SplitPptxPresentationResult, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SplitPptxPresentationResult): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fc323849d37ff851355
class StructureParser(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.body = None <NEW_LINE> self.structure = None <NEW_LINE> <DEDENT> def accept(self, visitor): <NEW_LINE> <INDENT> self.structure = visitor.visit(self.body) <NEW_LINE> <DEDENT> def load(self, src): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> root = parse(src) <NEW_LINE> self.body = root.body <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> exit("parse error, please check, {}".format(str(e))) <NEW_LINE> <DEDENT> <DEDENT> def export(self): <NEW_LINE> <INDENT> output = [] <NEW_LINE> self._format_structure(self.structure, 0, output) <NEW_LINE> return "\n".join(output) <NEW_LINE> <DEDENT> def _format_structure(self, root, level=0, output=None): <NEW_LINE> <INDENT> if output is None: <NEW_LINE> <INDENT> output = [] <NEW_LINE> <DEDENT> space = " " * level * 2 <NEW_LINE> for value in root.itervalues(): <NEW_LINE> <INDENT> content = value["content"] <NEW_LINE> type_ = value["type"] <NEW_LINE> if "body" in content: <NEW_LINE> <INDENT> name = content["name"] <NEW_LINE> line = "{}{} {}".format(space, type_, name) <NEW_LINE> output.append(line) <NEW_LINE> sub_root = content["body"] <NEW_LINE> self._format_structure(sub_root, level + 1, output) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(content, list): <NEW_LINE> <INDENT> content = ", ".join(content) <NEW_LINE> <DEDENT> line = "{}{} {}".format(space, type_, content) <NEW_LINE> output.append(line)
Parser for the source code
62598fc3d486a94d0ba2c273
class Reporter: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._content = list() <NEW_LINE> self._field_widths = list() <NEW_LINE> <DEDENT> def append(self,line): <NEW_LINE> <INDENT> self._content.append(line) <NEW_LINE> for ix,item in enumerate(line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._field_widths[ix] = max(self._field_widths[ix], len(str(item))) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> self._field_widths.append(len(str(item))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def nlines(self): <NEW_LINE> <INDENT> return len(self._content) <NEW_LINE> <DEDENT> def report(self,delimiter=None,padding=True,prefix=None, rstrip=True): <NEW_LINE> <INDENT> output = [] <NEW_LINE> if delimiter is None: <NEW_LINE> <INDENT> delimiter = ' ' <NEW_LINE> <DEDENT> if padding: <NEW_LINE> <INDENT> for line in self._content: <NEW_LINE> <INDENT> out_line = ["%-*s" % (width,str(item)) for width,item in zip(self._field_widths[:-1], line[:-1])] <NEW_LINE> out_line.append(str(line[-1])) <NEW_LINE> output.append(out_line) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for line in self._content: <NEW_LINE> <INDENT> output.append([str(item) for item in line]) <NEW_LINE> <DEDENT> <DEDENT> if not prefix: <NEW_LINE> <INDENT> prefix = '' <NEW_LINE> <DEDENT> for line in output: <NEW_LINE> <INDENT> out_line = "{}{}".format(prefix,delimiter.join(line)) <NEW_LINE> if rstrip: <NEW_LINE> <INDENT> out_line = out_line.rstrip() <NEW_LINE> <DEDENT> print(out_line)
Class for reporting column data Given multiple "lines" of column data (supplied as lists), pretty print the data in columns. Example usage: >>> output = Reporter() >>> output.append(['Some data',1.0,3]) >>> output.append(['More stuff',21.9,19]) >>> output.report() Some data 1.0 3 More stuff 21.9 19
62598fc3d8ef3951e32c7fad
class TropeExtractor(BasePageHandler): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_tropes_from_page(cls, page_url): <NEW_LINE> <INDENT> logging.info("attempting to get tropes for url: %s", page_url) <NEW_LINE> return cls.get_from_url(page_url) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_items_from_soup(cls, soup): <NEW_LINE> <INDENT> return cls._get_tropes_from_soup(soup) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_tropes_from_soup(cls, soup): <NEW_LINE> <INDENT> if not soup: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> content_div = soup.find('div', class_=TvTropePageConstants.PAGE_CONTENT_CLASS) <NEW_LINE> trope_links = content_div.find_all( class_=TvTropePageConstants.TWIKILINK_CLASS, href=re.compile(TvTropePageConstants.URL_PREFIX_FOR_TROPE_LINKS) ) <NEW_LINE> tropes = [] <NEW_LINE> for tl in trope_links: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t_id = tl.get('href').split('/')[-1] <NEW_LINE> name = tl.string <NEW_LINE> url = tl.get('href') <NEW_LINE> tropes.append( Trope(id=t_id, name=name, url=url, content=None) ) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logging.exception('error processing trope link:%s', tl) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> logging.exception('error parsing soup') <NEW_LINE> raise ContentParsingError('error parsing soup:%s' % soup) <NEW_LINE> <DEDENT> return tropes
Helper to extract tropes from a page
62598fc3fff4ab517ebcda89
@js_defined('window.LibraryContentAuthorView') <NEW_LINE> class StudioLibraryContainerXBlockWrapper(XBlockWrapper): <NEW_LINE> <INDENT> url = None <NEW_LINE> def is_browser_on_page(self): <NEW_LINE> <INDENT> return self.q(css='article.content-primary').visible <NEW_LINE> <DEDENT> def is_finished_loading(self): <NEW_LINE> <INDENT> return not self.q(css='div.ui-loading').visible <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xblock_wrapper(cls, xblock_wrapper): <NEW_LINE> <INDENT> return cls(xblock_wrapper.browser, xblock_wrapper.locator) <NEW_LINE> <DEDENT> def get_body_paragraphs(self): <NEW_LINE> <INDENT> return self.q(css=self._bounded_selector(".xblock-message-area p")) <NEW_LINE> <DEDENT> @wait_for_js <NEW_LINE> def refresh_children(self): <NEW_LINE> <INDENT> btn_selector = self._bounded_selector(".library-update-btn") <NEW_LINE> self.wait_for_element_presence(btn_selector, 'Update now button is present.') <NEW_LINE> self.q(css=btn_selector).first.click() <NEW_LINE> self.wait_for_ajax() <NEW_LINE> self.wait_for(lambda: self.is_browser_on_page(), 'StudioLibraryContainerXBlockWrapper has reloaded.') <NEW_LINE> self.wait_for(lambda: self.is_finished_loading(), 'Loading indicator is not visible.', timeout=120) <NEW_LINE> self.wait_for_ajax() <NEW_LINE> self.wait_for_element_absence(btn_selector, 'Wait for the XBlock to finish reloading')
Wraps :class:`.container.XBlockWrapper` for use with LibraryContent blocks
62598fc33d592f4c4edbb15a
class Stock: <NEW_LINE> <INDENT> def __init__(self, name, code): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.code = code <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "名称:" + self.name +"股票代码:" + self.code
股票类
62598fc37b180e01f3e491a1
class Player(BasePlayer): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = "Player" <NEW_LINE> <DEDENT> def hunt_choices( self, round_number, current_food, current_reputation, m, player_reputations, ): <NEW_LINE> <INDENT> return ['s']*len(player_reputations) <NEW_LINE> <DEDENT> def hunt_outcomes(self, food_earnings): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def round_end(self, award, m, number_hunters): <NEW_LINE> <INDENT> pass
Your strategy starts here.
62598fc3aad79263cf42ea79
class VideoSerializer(DispatchModelSerializer): <NEW_LINE> <INDENT> title = serializers.CharField(required=False, allow_null=True, allow_blank=True) <NEW_LINE> url = serializers.CharField(required=True, allow_null=True, allow_blank=False) <NEW_LINE> authors = AuthorSerializer(many=True, read_only=True) <NEW_LINE> author_ids = serializers.ListField( write_only=True, allow_empty=False, required=True, child=serializers.JSONField(), validators=[AuthorValidator(True)]) <NEW_LINE> tags = TagSerializer(many=True, read_only=True) <NEW_LINE> tag_ids = serializers.ListField( write_only=True, required=False, child=serializers.IntegerField()) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Video <NEW_LINE> fields = ( 'id', 'title', 'url', 'authors', 'author_ids', 'tags', 'tag_ids', 'created_at', 'updated_at' ) <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> return self.update(Video(), validated_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance = super(VideoSerializer, self).update(instance, validated_data) <NEW_LINE> authors = validated_data.get('author_ids') <NEW_LINE> if authors: <NEW_LINE> <INDENT> instance.save_authors(authors) <NEW_LINE> <DEDENT> tag_ids = validated_data.get('tag_ids', False) <NEW_LINE> if tag_ids != False: <NEW_LINE> <INDENT> instance.save_tags(tag_ids) <NEW_LINE> <DEDENT> return instance
Serializes the Video model.
62598fc3851cf427c66b8559
class MyModule(Module): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def add_arguments(cls, parser): <NEW_LINE> <INDENT> parser.add_argument("-c", "--count", type=int, help="number of bytes in each chunk", default=1) <NEW_LINE> <DEDENT> def handle(self, input, count): <NEW_LINE> <INDENT> assert input is not None, "Must provide data as input" <NEW_LINE> for data in input: <NEW_LINE> <INDENT> self.log.debug("Flipping %i bytes by %i", len(data), count) <NEW_LINE> n = len(data) <NEW_LINE> i = 0 <NEW_LINE> b = b"" <NEW_LINE> while i < n: <NEW_LINE> <INDENT> b += data[max(0,n-i-count):max(0,n-i)] <NEW_LINE> i += count <NEW_LINE> <DEDENT> yield b
Flip input data in reverse.
62598fc376e4537e8c3ef849
class DampedHarmonicOscillatorInfo: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Name = 'Damped Harmonic Oscillator (Bose corrected)' <NEW_LINE> self.Order = 6 <NEW_LINE> self.ParameterNumber = 5 <NEW_LINE> self.ParameterNames = ['Position', 'Gamma', 'Amplitude', 'Tempe', 'Assymetry'] <NEW_LINE> self.ParameterUnit = ['cm-1', 'cm-1', 'Intensity', 'T', 'None'] <NEW_LINE> self.ParameterBoundaries = [['-10','10'], ['xmin','xmax'], ['-2','2'], ['0.01','200'], ['-1000','1000'], ['0','Inf'], ['-10','10'], ['-10','10'], ['-0.5','0.5'], ['-0.5','0.5'], ] <NEW_LINE> self.ParameterProcessing = ['1', '0,1,2,4,3']
############################################################################### This class will contain information about the function, parameters and names ###############################################################################
62598fc3656771135c489914
class FolderListView(SuperPermissionsMixin, DokumenListView): <NEW_LINE> <INDENT> template_name = 'folder/list.html' <NEW_LINE> model = Carpeta <NEW_LINE> context_object_name = 'folder_data' <NEW_LINE> user_types = [User.ADMIN, User.MANAGER] <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = super(FolderListView, self).get_queryset() <NEW_LINE> try: <NEW_LINE> <INDENT> folder_exclud = Role.objects.filter( id=self.request.user.role.id).values_list('folder', flat=True) <NEW_LINE> queryset = queryset.exclude( id__in=folder_exclud).filter(padre=None).order_by('modified') <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> queryset = queryset.filter(padre=None).order_by('modified') <NEW_LINE> <DEDENT> return queryset
carpeta List View.
62598fc33346ee7daa33779b
class FileObjectManager: <NEW_LINE> <INDENT> def __init__(self, rootFile): <NEW_LINE> <INDENT> self.rootFile = None <NEW_LINE> if isinstance(rootFile, FileObject): <NEW_LINE> <INDENT> self.rootFile = rootFile <NEW_LINE> <DEDENT> <DEDENT> def all_file_objects(self): <NEW_LINE> <INDENT> filesList = [] <NEW_LINE> if self.rootFile: <NEW_LINE> <INDENT> FileObjectManager.__get_all_files(self.rootFile, filesList) <NEW_LINE> <DEDENT> return filesList <NEW_LINE> <DEDENT> def scan_with_depth(self, depth=999999): <NEW_LINE> <INDENT> if self.rootFile: <NEW_LINE> <INDENT> self.rootFile.tree_file_objects = [] <NEW_LINE> self.__scan_with_depth(self.rootFile, depth) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __get_all_files(rootFile, filesList): <NEW_LINE> <INDENT> if not isinstance(rootFile, FileObject): <NEW_LINE> <INDENT> assert False, 'rootFile不是FileObject类型.' <NEW_LINE> <DEDENT> if type(filesList) != list: <NEW_LINE> <INDENT> assert False, 'filesList不是List类型' <NEW_LINE> <DEDENT> for tmpFile in rootFile.tree_file_objects: <NEW_LINE> <INDENT> filesList.append(tmpFile) <NEW_LINE> if tmpFile.is_dir: <NEW_LINE> <INDENT> FileObjectManager.__get_all_files(tmpFile, filesList) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def __scan_with_depth(rootFile, depth): <NEW_LINE> <INDENT> if rootFile.scan_depth >= depth: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if rootFile.is_dir: <NEW_LINE> <INDENT> filePathList = os.listdir(rootFile.file_path) <NEW_LINE> for fileName in filePathList: <NEW_LINE> <INDENT> file = FileObject(os.path.join(rootFile.file_path, fileName)) <NEW_LINE> file.scan_depth = rootFile.scan_depth + 1 <NEW_LINE> rootFile.tree_file_objects.append(file) <NEW_LINE> if file.is_dir: <NEW_LINE> <INDENT> FileObjectManager.__scan_with_depth(file, depth)
用来扫描FileObject的类
62598fc34f88993c371f065d
class TimeAttestation: <NEW_LINE> <INDENT> TAG = None <NEW_LINE> TAG_SIZE = 8 <NEW_LINE> MAX_PAYLOAD_SIZE = 8192 <NEW_LINE> def _serialize_payload(self, ctx): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def serialize(self, ctx): <NEW_LINE> <INDENT> ctx.write_bytes(self.TAG) <NEW_LINE> payload_ctx = opentimestamps.core.serialize.BytesSerializationContext() <NEW_LINE> self._serialize_payload(payload_ctx) <NEW_LINE> ctx.write_varbytes(payload_ctx.getbytes()) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, TimeAttestation): <NEW_LINE> <INDENT> assert self.__class__ is not other.__class__ <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if isinstance(other, TimeAttestation): <NEW_LINE> <INDENT> assert self.__class__ is not other.__class__ <NEW_LINE> return self.TAG < other.TAG <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def deserialize(cls, ctx): <NEW_LINE> <INDENT> tag = ctx.read_bytes(cls.TAG_SIZE) <NEW_LINE> serialized_attestation = ctx.read_varbytes(cls.MAX_PAYLOAD_SIZE) <NEW_LINE> import opentimestamps.core.serialize <NEW_LINE> payload_ctx = opentimestamps.core.serialize.BytesDeserializationContext(serialized_attestation) <NEW_LINE> import opentimestamps.core.dubious.notary <NEW_LINE> if tag == PendingAttestation.TAG: <NEW_LINE> <INDENT> r = PendingAttestation.deserialize(payload_ctx) <NEW_LINE> <DEDENT> elif tag == BitcoinBlockHeaderAttestation.TAG: <NEW_LINE> <INDENT> r = BitcoinBlockHeaderAttestation.deserialize(payload_ctx) <NEW_LINE> <DEDENT> elif tag == opentimestamps.core.dubious.notary.EthereumBlockHeaderAttestation.TAG: <NEW_LINE> <INDENT> r = opentimestamps.core.dubious.notary.EthereumBlockHeaderAttestation.deserialize(payload_ctx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return UnknownAttestation(tag, serialized_attestation) <NEW_LINE> <DEDENT> payload_ctx.assert_eof() <NEW_LINE> return r
Time-attesting signature
62598fc37c178a314d78d745
class ValidationError(BuildMagicException): <NEW_LINE> <INDENT> msg = 'Validation failed'
Parameter validation failed.
62598fc397e22403b383b1af
class SecurityErrorTestCase(ExceptionTestCase): <NEW_LINE> <INDENT> def test_unauthorized_exposure(self): <NEW_LINE> <INDENT> self.opt(debug=False) <NEW_LINE> risky_info = uuid.uuid4().hex <NEW_LINE> e = exception.Unauthorized(message=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertNotIn(risky_info, str(e)) <NEW_LINE> <DEDENT> def test_unauthorized_exposure_in_debug(self): <NEW_LINE> <INDENT> self.opt(debug=True) <NEW_LINE> risky_info = uuid.uuid4().hex <NEW_LINE> e = exception.Unauthorized(message=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertIn(risky_info, str(e)) <NEW_LINE> <DEDENT> def test_forbidden_exposure(self): <NEW_LINE> <INDENT> self.opt(debug=False) <NEW_LINE> risky_info = uuid.uuid4().hex <NEW_LINE> e = exception.Forbidden(message=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertNotIn(risky_info, str(e)) <NEW_LINE> <DEDENT> def test_forbidden_exposure_in_debug(self): <NEW_LINE> <INDENT> self.opt(debug=True) <NEW_LINE> risky_info = uuid.uuid4().hex <NEW_LINE> e = exception.Forbidden(message=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertIn(risky_info, str(e)) <NEW_LINE> <DEDENT> def test_forbidden_action_exposure(self): <NEW_LINE> <INDENT> self.opt(debug=False) <NEW_LINE> risky_info = uuid.uuid4().hex <NEW_LINE> action = uuid.uuid4().hex <NEW_LINE> e = exception.ForbiddenAction(message=risky_info, action=action) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertNotIn(risky_info, str(e)) <NEW_LINE> self.assertIn(action, str(e)) <NEW_LINE> e = exception.ForbiddenAction(action=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertIn(risky_info, str(e)) <NEW_LINE> <DEDENT> def test_forbidden_action_exposure_in_debug(self): <NEW_LINE> <INDENT> self.opt(debug=True) <NEW_LINE> risky_info = uuid.uuid4().hex <NEW_LINE> e = exception.ForbiddenAction(message=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertIn(risky_info, str(e)) <NEW_LINE> e = exception.ForbiddenAction(action=risky_info) <NEW_LINE> self.assertValidJsonRendering(e) <NEW_LINE> self.assertIn(risky_info, str(e))
Tests whether security-related info is exposed to the API user.
62598fc3167d2b6e312b721c
class MockP4Source(P4Source): <NEW_LINE> <INDENT> invocation = 0 <NEW_LINE> def __init__(self, p4changes, p4change, *args, **kwargs): <NEW_LINE> <INDENT> P4Source.__init__(self, *args, **kwargs) <NEW_LINE> self.p4changes = p4changes <NEW_LINE> self.p4change = p4change <NEW_LINE> <DEDENT> def _get_changes(self): <NEW_LINE> <INDENT> assert self.working <NEW_LINE> result = self.p4changes[self.invocation] <NEW_LINE> self.invocation += 1 <NEW_LINE> return defer.succeed(result) <NEW_LINE> <DEDENT> def _get_describe(self, dummy, num): <NEW_LINE> <INDENT> assert self.working <NEW_LINE> return defer.succeed(self.p4change[num])
Test P4Source which doesn't actually invoke p4.
62598fc34a966d76dd5ef17a
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> first_name = db.Column(db.String(30), nullable=False) <NEW_LINE> last_name = db.Column(db.String(30), nullable=False) <NEW_LINE> image_url = db.Column(db.String, default=None) <NEW_LINE> posts = db.relationship('Post', backref='users') <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return f'{self.first_name} {self.last_name}' <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_name(self): <NEW_LINE> <INDENT> return f'{self.first_name} {self.last_name}' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f'<User: {self.get_full_name()}>'
User model
62598fc33d592f4c4edbb15d
class FieldSet(DOM.FieldSet): <NEW_LINE> <INDENT> __slots__ = ('legend') <NEW_LINE> properties = DOM.FieldSet.properties.copy() <NEW_LINE> properties['legend'] = {'action':'setLegendText'} <NEW_LINE> def _create(self, id=None, name=None, parent=None, **kwargs): <NEW_LINE> <INDENT> DOM.FieldSet._create(self, id, name, parent, **kwargs) <NEW_LINE> self.legend = None <NEW_LINE> <DEDENT> def getLegend(self): <NEW_LINE> <INDENT> if self.legend: <NEW_LINE> <INDENT> return self.legend <NEW_LINE> <DEDENT> self.legend = Box.addChildElement(self, DOM.Legend) <NEW_LINE> self.legend.text = Base.TextNode() <NEW_LINE> return self.legend <NEW_LINE> <DEDENT> def setLegendText(self, legend): <NEW_LINE> <INDENT> self.getLegend().text.setText(legend)
Groups child elements together with a labeled border
62598fc3e1aae11d1e7ce978
@final <NEW_LINE> class TooManyElifsViolation(ASTViolation): <NEW_LINE> <INDENT> error_template = 'Found too many `elif` branches: {0}' <NEW_LINE> code = 223
Forbids to use many ``elif`` branches. Reasoning: This rule is specifically important because of many ``elif`` branches indicate a complex flow in your design: you are reimplementing ``switch`` in python. Solution: There are different design patterns to use instead. For example, you can use some interface that just call a specific method without ``if``. Or separate your ``if`` into multiple functions. .. versionadded:: 0.1.0 .. versionchanged:: 0.5.0
62598fc37047854f4633f679
class SiamCiReceiverServiceTest(SiamCiTestCase): <NEW_LINE> <INDENT> @defer.inlineCallbacks <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> yield self._start_container() <NEW_LINE> services = [ {'name':receiver_service_name, 'module':'siamci.receiver_service', 'class':'SiamCiReceiverService', 'spawnargs':{ 'servicename':receiver_service_name } } ] <NEW_LINE> sup = yield self._spawn_processes(services) <NEW_LINE> svc_id = yield sup.get_child_id(receiver_service_name) <NEW_LINE> self.client = SiamCiReceiverServiceClient(proc=sup,target=svc_id) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def tearDown(self): <NEW_LINE> <INDENT> yield self._stop_container() <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_expect_1(self): <NEW_LINE> <INDENT> self._check_skip() <NEW_LINE> publish_id = "some_publish_id" <NEW_LINE> yield self.client.expect(publish_id) <NEW_LINE> expected = yield self.client.getExpected() <NEW_LINE> self.assertEquals(len(expected), 1) <NEW_LINE> self.assertTrue(publish_id in expected) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_expect_accept_1(self): <NEW_LINE> <INDENT> self._check_skip() <NEW_LINE> publish_id = "some_publish_id" <NEW_LINE> yield self.client.expect(publish_id) <NEW_LINE> yield self.client.acceptResponse(publish_id) <NEW_LINE> expected = yield self.client.getExpected() <NEW_LINE> self.assertEquals(len(expected), 0)
Basic tests of SiamCiReceiverService.
62598fc3a8370b77170f0686
class SimpleComm(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import numpy <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> numpy = None <NEW_LINE> <DEDENT> self._numpy = numpy <NEW_LINE> self._color = None <NEW_LINE> self._group = None <NEW_LINE> <DEDENT> def _is_ndarray(self, obj): <NEW_LINE> <INDENT> if self._numpy: <NEW_LINE> <INDENT> return isinstance(obj, self._numpy.ndarray) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get_size(self): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def get_rank(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def is_manager(self): <NEW_LINE> <INDENT> return self.get_rank() == 0 <NEW_LINE> <DEDENT> def get_color(self): <NEW_LINE> <INDENT> return self._color <NEW_LINE> <DEDENT> def get_group(self): <NEW_LINE> <INDENT> return self._group <NEW_LINE> <DEDENT> def sync(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def allreduce(self, data, op): <NEW_LINE> <INDENT> if isinstance(data, dict): <NEW_LINE> <INDENT> totals = {} <NEW_LINE> for k, v in data.items(): <NEW_LINE> <INDENT> totals[k] = SimpleComm.allreduce(self, v, op) <NEW_LINE> <DEDENT> return totals <NEW_LINE> <DEDENT> elif self._is_ndarray(data): <NEW_LINE> <INDENT> return SimpleComm.allreduce(self, getattr(self._numpy, _OP_MAP[op]['np'])(data), op) <NEW_LINE> <DEDENT> elif hasattr(data, '__len__'): <NEW_LINE> <INDENT> return SimpleComm.allreduce(self, eval(_OP_MAP[op]['py'])(data), op) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> <DEDENT> def partition(self, data=None, func=None, involved=False, tag=0): <NEW_LINE> <INDENT> op = func if func else lambda *x: x[0][x[1] :: x[2]] <NEW_LINE> if involved: <NEW_LINE> <INDENT> return op(data, 0, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def ration(self, data=None, tag=0): <NEW_LINE> <INDENT> err_msg = 'Rationing cannot be used in serial operation' <NEW_LINE> raise RuntimeError(err_msg) <NEW_LINE> <DEDENT> def collect(self, data=None, tag=0): <NEW_LINE> <INDENT> err_msg = 'Collection cannot be used in serial operation' <NEW_LINE> raise RuntimeError(err_msg) <NEW_LINE> <DEDENT> def divide(self, group): <NEW_LINE> <INDENT> err_msg = 'Division cannot be done on a serial communicator' <NEW_LINE> raise RuntimeError(err_msg)
Simple Communicator for serial operation. Attributes: _numpy: Reference to the Numpy module, if found _color: The color associated with the communicator, if colored _group: The group ID associated with the communicator's color
62598fc3377c676e912f6ec7
class Principal(models.Base): <NEW_LINE> <INDENT> id = Column(Integer, primary_key=True) <NEW_LINE> active = Column(Boolean) <NEW_LINE> email = Column(Unicode(100), nullable=False, unique=True) <NEW_LINE> password = Column(Unicode(100)) <NEW_LINE> firstname = Column(Unicode()) <NEW_LINE> lastname = Column(Unicode()) <NEW_LINE> creation_date = Column(DateTime(), nullable=False, default=datetime.now) <NEW_LINE> last_login_date = Column(DateTime()) <NEW_LINE> def __init__(self, email, active=True, **data): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.active = active <NEW_LINE> self.add(**data) <NEW_LINE> self.creation_date = datetime.now() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Principal %r>' % (self.fullname or self.email) <NEW_LINE> <DEDENT> def update(self, password=None, **data): <NEW_LINE> <INDENT> if password is not None: <NEW_LINE> <INDENT> self.password = security.hash_password(password) <NEW_LINE> <DEDENT> for key in 'email', 'firstname', 'lastname': <NEW_LINE> <INDENT> if key in data: <NEW_LINE> <INDENT> setattr(self, key, data[key]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __json__(self, request): <NEW_LINE> <INDENT> return dict(id=self.id, email=self.email, firstname=self.firstname, lastname=self.lastname) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fullname(self): <NEW_LINE> <INDENT> return ' '.join(filter(None, [self.firstname, self.lastname])) <NEW_LINE> <DEDENT> def validate_password(self, clear): <NEW_LINE> <INDENT> return security.validate_password(clear, self.password)
An implementation of 'Principal', i.e. users and groups.
62598fc323849d37ff851359
class CopyTo(object): <NEW_LINE> <INDENT> __COPY_CHUNK_SIZE = 100 * 1024 <NEW_LINE> __sql = None <NEW_LINE> __cursor = None <NEW_LINE> __temp_file_buffer = None <NEW_LINE> def __init__(self, cursor: DictCursor, sql: str): <NEW_LINE> <INDENT> sql = decode_object_from_bytes_if_needed(sql) <NEW_LINE> self.__start_copy_to(cursor=cursor, sql=sql) <NEW_LINE> <DEDENT> def __start_copy_to(self, cursor: DictCursor, sql: str) -> None: <NEW_LINE> <INDENT> sql = decode_object_from_bytes_if_needed(sql) <NEW_LINE> if sql is None: <NEW_LINE> <INDENT> raise McDatabaseHandlerException("SQL is None.") <NEW_LINE> <DEDENT> if len(sql) == '': <NEW_LINE> <INDENT> raise McDatabaseHandlerException("SQL is empty.") <NEW_LINE> <DEDENT> self.__sql = sql <NEW_LINE> self.__cursor = cursor <NEW_LINE> self.__temp_file_buffer = tempfile.TemporaryFile(mode='w+', encoding='utf-8') <NEW_LINE> try: <NEW_LINE> <INDENT> self.__cursor.copy_expert(sql=self.__sql, file=self.__temp_file_buffer, size=self.__COPY_CHUNK_SIZE) <NEW_LINE> self.__temp_file_buffer.seek(0) <NEW_LINE> <DEDENT> except psycopg2.Warning as ex: <NEW_LINE> <INDENT> log.warning('Warning while running COPY TO query: %s' % str(ex)) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> raise McCopyToException('COPY TO query failed: %s' % str(ex)) <NEW_LINE> <DEDENT> <DEDENT> def get_line(self) -> Union[str, None]: <NEW_LINE> <INDENT> line = self.__temp_file_buffer.readline() <NEW_LINE> if line != '': <NEW_LINE> <INDENT> return line <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def end(self) -> None: <NEW_LINE> <INDENT> self.__temp_file_buffer.close() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self) -> Union[str, None]: <NEW_LINE> <INDENT> line = self.get_line() <NEW_LINE> if line is None: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> return line
COPY TO helper. Implements iterator methods too.
62598fc3d8ef3951e32c7faf
class ExtSpace(object): <NEW_LINE> <INDENT> def __init__(self, e=None): <NEW_LINE> <INDENT> if e is not None: <NEW_LINE> <INDENT> self.extensions = e
Simple class to test out namespace implementations of validate_extensions()
62598fc35fdd1c0f98e5e23a
class ServiceBookDetailAllotment(ServiceBookDetail, BookAllotmentData): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Service Book Detail Accomodation' <NEW_LINE> verbose_name_plural = 'Services Book Details Accomodations' <NEW_LINE> <DEDENT> book_service = models.ForeignKey(Allotment, on_delete=models.CASCADE) <NEW_LINE> def fill_data(self): <NEW_LINE> <INDENT> self.base_service = self.book_service <NEW_LINE> super(ServiceBookDetailAllotment, self).fill_data() <NEW_LINE> self.name = '%s - %s' % (self.service, self.book_service) <NEW_LINE> self.time = time(23, 59, 59)
Service Book Detail Allotment
62598fc39f288636728189cf
class KLCRule(KLCRuleBase): <NEW_LINE> <INDENT> def __init__(self, module, args, description): <NEW_LINE> <INDENT> KLCRuleBase.__init__(self, description) <NEW_LINE> self.module = module <NEW_LINE> self.args = args <NEW_LINE> self.needsFixMore=False <NEW_LINE> self.illegal_chars = ['*', '?', ':', '/', '\\', '[', ']', ';', '|', '=', ','] <NEW_LINE> <DEDENT> def fix(self): <NEW_LINE> <INDENT> self.info("fix not supported") <NEW_LINE> return <NEW_LINE> <DEDENT> def fixmore(self): <NEW_LINE> <INDENT> if self.needsFixMore: <NEW_LINE> <INDENT> self.info("fixmore not supported") <NEW_LINE> <DEDENT> return
A base class to represent a KLC rule
62598fc34f88993c371f065e
class RevisionLogList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): <NEW_LINE> <INDENT> queryset = RevisionLogs.objects.all().order_by('-id') <NEW_LINE> filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) <NEW_LINE> pagination_class = MyPageNumberPagination <NEW_LINE> filter_class = RevisionLogFilter <NEW_LINE> serializer_class = RevisionLogSerializer <NEW_LINE> @check_object_perm(codename='opscenter.add_revisionlogs') <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.list(request, *args, **kwargs)
修改日志列表、新增
62598fc37b180e01f3e491a3
class Output: <NEW_LINE> <INDENT> report = FileField( label="Tab-separated file containing the overall conversion rates" ) <NEW_LINE> plot = FileField(label="Overall conversion rate plot file") <NEW_LINE> species = StringField(label="Species") <NEW_LINE> build = StringField(label="Build")
Output fields to process AlleyoopRates.
62598fc3cc40096d6161a32c
class FooException(Exception): <NEW_LINE> <INDENT> class InternalFoo(object): <NEW_LINE> <INDENT> pass
Docstring of :class:`format.numpy.foo.FooException`. Another class of :mod:`format.numpy.foo` module.
62598fc3aad79263cf42ea7d
class TwitterModel(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.param_defaults = {} <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.AsJsonString() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other and self.AsDict() == other.AsDict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def AsJsonString(self): <NEW_LINE> <INDENT> return json.dumps(self.AsDict(), sort_keys=True) <NEW_LINE> <DEDENT> def AsDict(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for (key, value) in self.param_defaults.items(): <NEW_LINE> <INDENT> if isinstance(getattr(self, key, None), (list, tuple, set)): <NEW_LINE> <INDENT> data[key] = list() <NEW_LINE> for subobj in getattr(self, key, None): <NEW_LINE> <INDENT> if getattr(subobj, 'AsDict', None): <NEW_LINE> <INDENT> data[key].append(subobj.AsDict()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data[key].append(subobj) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif getattr(getattr(self, key, None), 'AsDict', None): <NEW_LINE> <INDENT> data[key] = getattr(self, key).AsDict() <NEW_LINE> <DEDENT> elif getattr(self, key, None): <NEW_LINE> <INDENT> data[key] = getattr(self, key, None) <NEW_LINE> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def NewFromJsonDict(cls, data, **kwargs): <NEW_LINE> <INDENT> json_data = data.copy() <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> for key, val in kwargs.items(): <NEW_LINE> <INDENT> json_data[key] = val <NEW_LINE> <DEDENT> <DEDENT> c = cls(**json_data) <NEW_LINE> c._json = data <NEW_LINE> return c
Base class from which all twitter models will inherit.
62598fc3adb09d7d5dc0a824