code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class _SectionFailError(Exception): <NEW_LINE> <INDENT> pass | General error, terminates section processing | 62598fb1e5267d203ee6b967 |
class CaninePreTrainedModel(PreTrainedModel): <NEW_LINE> <INDENT> config_class = CanineConfig <NEW_LINE> load_tf_weights = load_tf_weights_in_canine <NEW_LINE> base_model_prefix = "canine" <NEW_LINE> supports_gradient_checkpointing = True <NEW_LINE> _keys_to_ignore_on_load_missing = [r"position_ids"] <NEW_LINE> def _init_weights(self, module): <NEW_LINE> <INDENT> if isinstance(module, (nn.Linear, nn.Conv1d)): <NEW_LINE> <INDENT> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) <NEW_LINE> if module.bias is not None: <NEW_LINE> <INDENT> module.bias.data.zero_() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(module, nn.Embedding): <NEW_LINE> <INDENT> module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) <NEW_LINE> if module.padding_idx is not None: <NEW_LINE> <INDENT> module.weight.data[module.padding_idx].zero_() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(module, nn.LayerNorm): <NEW_LINE> <INDENT> module.bias.data.zero_() <NEW_LINE> module.weight.data.fill_(1.0) <NEW_LINE> <DEDENT> <DEDENT> def _set_gradient_checkpointing(self, module, value=False): <NEW_LINE> <INDENT> if isinstance(module, CanineEncoder): <NEW_LINE> <INDENT> module.gradient_checkpointing = value | An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models. | 62598fb126068e7796d4c9b4 |
class XenBusConnectionGPLPV(pyxs.connection.PacketConnection): <NEW_LINE> <INDENT> def create_transport(self): <NEW_LINE> <INDENT> return XenBusTransportGPLPV() <NEW_LINE> <DEDENT> def recv(self): <NEW_LINE> <INDENT> packet = super(XenBusConnectionGPLPV, self).recv() <NEW_LINE> if not packet.payload: <NEW_LINE> <INDENT> self.transport.recv(0) <NEW_LINE> <DEDENT> return packet | A pyxs.PacketConnection which communicates with xenstore over the PCI
device exposed by the GPLPV drivers on Windows. The interface of this
driver is very similar to the ones on Linux (direct reads/writes to a
file-like object) so we reuse most of the PacketConnection class and leave
the implementation detail to the XenBusTransportGPLPV. | 62598fb13d592f4c4edbaf1f |
class ImgOutput(Component): <NEW_LINE> <INDENT> def __init__(self, options): <NEW_LINE> <INDENT> super(ImgOutput, self).__init__(options) <NEW_LINE> self.input_observer = ImgOutput.InputObserver(self) <NEW_LINE> self.__file_path = "" <NEW_LINE> self.file_path = self.properties['file_path'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def file_path(self): <NEW_LINE> <INDENT> return self.__file_path <NEW_LINE> <DEDENT> @file_path.setter <NEW_LINE> def file_path(self, value): <NEW_LINE> <INDENT> self.__file_path = value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_parameters(): <NEW_LINE> <INDENT> for key, value in ImgOutput.__dict__.items(): <NEW_LINE> <INDENT> if isinstance(value, property): <NEW_LINE> <INDENT> print(key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> class InputObserver(Component.InputObserver): <NEW_LINE> <INDENT> def update(self, observable, package): <NEW_LINE> <INDENT> self.outer.log_line('save file') <NEW_LINE> cv2.imwrite(self.outer.file_path, package['data']) <NEW_LINE> self.outer.log_line('saved file', LogLevel.SUCCESS) <NEW_LINE> self.outer.send({'status': 'stopped'}) | Class for ImgOutput | 62598fb14e4d562566372485 |
class LoggerManager(object): <NEW_LINE> <INDENT> def __init__(self, log_name, log_directory='.', encoding='utf-8'): <NEW_LINE> <INDENT> self.log_name = log_name <NEW_LINE> self.log_directory = os.path.abspath(log_directory) <NEW_LINE> self.encoding = encoding <NEW_LINE> self.logger = None <NEW_LINE> <DEDENT> def getLogger(self): <NEW_LINE> <INDENT> return self.logger <NEW_LINE> <DEDENT> def init_logger(self): <NEW_LINE> <INDENT> if self.logger is not None: <NEW_LINE> <INDENT> self.close_handlers() <NEW_LINE> <DEDENT> self._reset() <NEW_LINE> <DEDENT> def _reset(self): <NEW_LINE> <INDENT> if hasattr(self, 'logger') and self.logger is not None: <NEW_LINE> <INDENT> self.close_handlers() <NEW_LINE> <DEDENT> self.logger = self.create_new_logger(self.log_name, self.log_directory, self.encoding) <NEW_LINE> <DEDENT> def close_handlers(self): <NEW_LINE> <INDENT> if self.logger.handlers is not None and len(self.logger.handlers) > 0: <NEW_LINE> <INDENT> for handler in self.logger.handlers: <NEW_LINE> <INDENT> handler.close() <NEW_LINE> self.logger.removeHandler(handler) <NEW_LINE> <DEDENT> <DEDENT> del self.logger <NEW_LINE> <DEDENT> class ResultsFilter(logging.Filter): <NEW_LINE> <INDENT> def filter(self, record): <NEW_LINE> <INDENT> return record.startswith(u'new_record') <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def create_new_logger(log_name, log_dir, encoding='utf-8'): <NEW_LINE> <INDENT> now_string = datetime.now().strftime("%Y-%m-%d-%H%M%S") <NEW_LINE> log_results_file = os.path.join(log_dir, "results-{name}-{ts}.NEW.log".format(name=log_name, ts=now_string)) <NEW_LINE> log_general_file = os.path.join(log_dir, "full-{name}-{ts}.log".format(name=log_name, ts=now_string)) <NEW_LINE> log_format = u"%(asctime)s : %(levelname)s : %(pathname)s : %(funcName)s : %(lineno)d : %(message)s" <NEW_LINE> results_format = u"%(message)s" <NEW_LINE> results_start_filter = "new_record\s*" <NEW_LINE> results_strip_start = "new_record\s*" <NEW_LINE> logger = logging.getLogger(log_name) <NEW_LINE> general_handler = logging.FileHandler(log_general_file, encoding=encoding) <NEW_LINE> general_format = logging.Formatter(log_format) <NEW_LINE> general_handler.setFormatter(general_format) <NEW_LINE> results_handler = logging.FileHandler(log_results_file, encoding=encoding) <NEW_LINE> results_format = StripStartFormatter(results_strip_start, results_format) <NEW_LINE> results_handler.setFormatter(results_format) <NEW_LINE> results_filter = StartFilter(results_start_filter) <NEW_LINE> results_handler.addFilter(results_filter) <NEW_LINE> logger.addHandler(general_handler) <NEW_LINE> logger.addHandler(results_handler) <NEW_LINE> logger.setLevel(logging.DEBUG) <NEW_LINE> logger.propagate = False <NEW_LINE> return logger | Class meant to help managing outputs | 62598fb14527f215b58e9f33 |
@union <NEW_LINE> class UnionBase: <NEW_LINE> <INDENT> pass | Docstring for UnionBase | 62598fb1009cb60464d01580 |
class StrictAssignmentTests(SimpleTestCase): <NEW_LINE> <INDENT> def test_setattr_raises_validation_error_field_specific(self): <NEW_LINE> <INDENT> form_class = modelform_factory(model=StrictAssignmentFieldSpecific, fields=['title']) <NEW_LINE> form = form_class(data={'title': 'testing setattr'}, files=None) <NEW_LINE> form.instance._should_error = True <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors, { 'title': ['Cannot set attribute', 'This field cannot be blank.'] }) <NEW_LINE> <DEDENT> def test_setattr_raises_validation_error_non_field(self): <NEW_LINE> <INDENT> form_class = modelform_factory(model=StrictAssignmentAll, fields=['title']) <NEW_LINE> form = form_class(data={'title': 'testing setattr'}, files=None) <NEW_LINE> form.instance._should_error = True <NEW_LINE> self.assertFalse(form.is_valid()) <NEW_LINE> self.assertEqual(form.errors, { '__all__': ['Cannot set attribute'], 'title': ['This field cannot be blank.'] }) | Should a model do anything special with __setattr__() or descriptors which
raise a ValidationError, a model form should catch the error (#24706). | 62598fb1bf627c535bcb14fe |
class MessageHandler(object): <NEW_LINE> <INDENT> outputQmlWarnings = bool(os.environ.get("MESHROOM_OUTPUT_QML_WARNINGS", False)) <NEW_LINE> logFunctions = { QtMsgType.QtDebugMsg: logging.debug, QtMsgType.QtWarningMsg: logging.warning, QtMsgType.QtInfoMsg: logging.info, QtMsgType.QtFatalMsg: logging.fatal, QtMsgType.QtCriticalMsg: logging.critical, QtMsgType.QtSystemMsg: logging.critical } <NEW_LINE> qmlWarningsBlacklist = ( 'Failed to download scene at QUrl("")', 'QVariant(Invalid) Please check your QParameters', 'Texture will be invalid for this frame', ) <NEW_LINE> @classmethod <NEW_LINE> def handler(cls, messageType, context, message): <NEW_LINE> <INDENT> if not cls.outputQmlWarnings and any(w in message for w in cls.qmlWarningsBlacklist): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> MessageHandler.logFunctions[messageType](message) | MessageHandler that translates Qt logs to Python logging system.
Also contains and filters a list of blacklisted QML warnings that end up in the
standard error even when setOutputWarningsToStandardError is set to false on the engine. | 62598fb167a9b606de54602d |
class GpioMotorPWM (adapter.adapters.GPIOAdapter): <NEW_LINE> <INDENT> mandatoryParameters = {'frequency': 50.0, 'speed': 0.0} <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> adapter.adapters.GPIOAdapter.__init__(self) <NEW_LINE> pass <NEW_LINE> <DEDENT> def speed(self, value): <NEW_LINE> <INDENT> if debug: <NEW_LINE> <INDENT> print(self.name, 'speed', value) <NEW_LINE> <DEDENT> if self.active: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> speed = float(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> gpio_0 = self.getChannelByAlias('a') <NEW_LINE> gpio_1 = self.getChannelByAlias('b') <NEW_LINE> if speed > 100.0: <NEW_LINE> <INDENT> self.gpioManager.setPWMDutyCycle(gpio_0, 1 ) <NEW_LINE> self.gpioManager.setPWMDutyCycle(gpio_1, 0 ) <NEW_LINE> <DEDENT> elif speed > 0.001: <NEW_LINE> <INDENT> self.gpioManager.setPWMDutyCycle(gpio_0, speed ) <NEW_LINE> self.gpioManager.setPWMDutyCycle(gpio_1, 0 ) <NEW_LINE> <DEDENT> elif speed > -0.001: <NEW_LINE> <INDENT> self.gpioManager.setPWMDutyCycle(gpio_0, 0 ) <NEW_LINE> self.gpioManager.setPWMDutyCycle(gpio_1, 0 ) <NEW_LINE> <DEDENT> elif speed >= -100.0: <NEW_LINE> <INDENT> self.gpioManager.setPWMDutyCycle(gpio_0, 0 ) <NEW_LINE> self.gpioManager.setPWMDutyCycle(gpio_1, abs( speed ) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.gpioManager.setPWMDutyCycle(gpio_0, 0 ) <NEW_LINE> self.gpioManager.setPWMDutyCycle(gpio_1, 1 ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def setActive(self, state): <NEW_LINE> <INDENT> adapter.adapters.GPIOAdapter.setActive(self, state); <NEW_LINE> if state == True: <NEW_LINE> <INDENT> self.gpioManager.startPWM(self.gpios[0], frequency = float( self.parameters['frequency']), value=float( self.parameters['speed'])) <NEW_LINE> self.gpioManager.startPWM(self.gpios[1], frequency = float( self.parameters['frequency']), value=float( self.parameters['speed'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.gpioManager.resetPWM(self.gpios[0]) <NEW_LINE> self.gpioManager.resetPWM(self.gpios[1]) | controls a motor connected to two half-H-Bridges.
Input 'speed' : float, -100..0.0 .. 100.0
Configuration 'frequency': float, [Hz]
Needs two GPIO port pins.
uses pwm-feature of RPi.GPIO-Library. | 62598fb1be7bc26dc9251e8c |
class Network: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def port(): <NEW_LINE> <INDENT> if 'network' in current and 'port' in current['network']: <NEW_LINE> <INDENT> return current['network']['port'] <NEW_LINE> <DEDENT> return DEFAULT_PORT <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ip(): <NEW_LINE> <INDENT> if 'network' in current and 'ip' in current['network']: <NEW_LINE> <INDENT> return current['network']['ip'] <NEW_LINE> <DEDENT> return DEFAULT_IP | Network configuration | 62598fb130bbd722464699a8 |
class NotLinkedToContent(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return not PublishableContent.objects.filter(gallery__pk=view.kwargs.get('pk_gallery')).exists() <NEW_LINE> <DEDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> gallery = obj if isinstance(obj, Gallery) else obj.gallery <NEW_LINE> return not PublishableContent.objects.filter(gallery=gallery).exists() | Custom permission to denied modification of a gallery linked to a content | 62598fb14428ac0f6e658585 |
class StatusTests(test.TestCase): <NEW_LINE> <INDENT> def test_basic(self): <NEW_LINE> <INDENT> s = base.Status('Test status', 5, 'http://github.com/criteo/defcon', description='This is a test') <NEW_LINE> expected = { 'defcon': 5, 'title': 'Test status', 'description': 'This is a test', 'link': 'http://github.com/criteo/defcon', 'id': uuid.UUID('235c445a-cd6f-5f46-91af-bada596275a6'), 'time_start': None, 'time_end': None, } <NEW_LINE> self.assertEqual(dict(s), expected) | Test that we can build statuses. | 62598fb1bd1bec0571e150f2 |
class TestFlaskBase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.app = create_app() <NEW_LINE> self.app.testing = True <NEW_LINE> self.app_context = self.app.test_request_context() <NEW_LINE> self.app_context.push() <NEW_LINE> self.client = self.app.test_client() <NEW_LINE> self.app.db.create_all() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.app.db.drop_all() | Class Base for Test. | 62598fb1796e427e5384e7f4 |
class ServiceConfigurationError(Error): <NEW_LINE> <INDENT> pass | When service configuration is incorrect. | 62598fb1851cf427c66b831b |
class AllQueryCache(): <NEW_LINE> <INDENT> def __init__(self, bulk_load_callback, single_load_callback): <NEW_LINE> <INDENT> self.cache = {} <NEW_LINE> self.bulk_load_callback = bulk_load_callback <NEW_LINE> self.single_load_callback = single_load_callback <NEW_LINE> self.bulk_load() <NEW_LINE> <DEDENT> def get(self, pk): <NEW_LINE> <INDENT> assert isinstance(pk, int), "Not an integer!" <NEW_LINE> r = self.cache.get(pk) <NEW_LINE> if (r is None): <NEW_LINE> <INDENT> r = self.single_load_callback(pk) <NEW_LINE> self.cache[pk] = r <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> def bulk_load(self): <NEW_LINE> <INDENT> qs = self.bulk_load_callback() <NEW_LINE> for e in qs: <NEW_LINE> <INDENT> self.cache[int(e[0])] = e[1] <NEW_LINE> <DEDENT> <DEDENT> def clear_one(self, pk): <NEW_LINE> <INDENT> assert isinstance(pk, int), "Not an integer!" <NEW_LINE> try: <NEW_LINE> <INDENT> del(self.cache[pk]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def clear_some(self, pks): <NEW_LINE> <INDENT> for pk in pks: <NEW_LINE> <INDENT> self.clear_one(int(pk)) <NEW_LINE> <DEDENT> <DEDENT> def clear_all(self): <NEW_LINE> <INDENT> self.cache = {} <NEW_LINE> self.bulk_load() <NEW_LINE> <DEDENT> def contains(self, pk): <NEW_LINE> <INDENT> return (pk in self.cache) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.cache) | This tiny class has a trick, it bulkloads on startup and clear_all().
Neater and (depends on the efficiency of the supplied callback)
maybe a lot faster.
@param bulk_load_callback a value
@param single_load_callback [(k,v)...]. Key is converted to int | 62598fb11f5feb6acb162c7e |
class Adapter: <NEW_LINE> <INDENT> def __init__(self, object, **adapted_method): <NEW_LINE> <INDENT> self._object = object <NEW_LINE> self.__dict__.update(adapted_method) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self._object, attr) | This change generic method name to individualized method names | 62598fb12ae34c7f260ab141 |
class xasyFilledShape(xasyShape): <NEW_LINE> <INDENT> def __init__(self, path, asyengine, pen = None, transform = identity()): <NEW_LINE> <INDENT> if path.nodeSet[-1] != 'cycle': <NEW_LINE> <INDENT> raise Exception("Filled paths must be cyclic") <NEW_LINE> <DEDENT> super().__init__(path, asyengine, pen, transform) <NEW_LINE> self.path.fill=True <NEW_LINE> <DEDENT> def getObjectCode(self, asy2psmap=identity()): <NEW_LINE> <INDENT> if self.path.fill: <NEW_LINE> <INDENT> return 'fill(KEY="{0}",{1},{2});'.format(self.transfKey, self.path.getCode(asy2psmap), self.pen.getCode())+'\n\n' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'draw(KEY="{0}",{1},{2});'.format(self.transfKey, self.path.getCode(asy2psmap), self.pen.getCode())+'\n\n' <NEW_LINE> <DEDENT> <DEDENT> def generateDrawObjects(self, forceUpdate = False): <NEW_LINE> <INDENT> if self.path.containsCurve: <NEW_LINE> <INDENT> self.path.computeControls() <NEW_LINE> <DEDENT> newObj = DrawObject(self.path.toQPainterPath(), None, drawOrder = 0, transform = self.transfKeymap[self.transfKey][0], pen = self.pen, key = self.transfKey, fill = True) <NEW_LINE> newObj.originalObj = self <NEW_LINE> newObj.setParent(self) <NEW_LINE> newObj.fill=self.path.fill <NEW_LINE> return [newObj] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "xasyFilledShape code:{:s}".format("\n\t".join(self.getCode().splitlines())) <NEW_LINE> <DEDENT> def swapFill(self): <NEW_LINE> <INDENT> self.path.fill = not self.path.fill | A filled shape drawn on the GUI | 62598fb1d7e4931a7ef3c0f4 |
class Polygon(Area): <NEW_LINE> <INDENT> def __init__(self, *points): <NEW_LINE> <INDENT> assert len(points) >= 3 <NEW_LINE> self.points = points <NEW_LINE> <DEDENT> @property <NEW_LINE> def bounding_box(self): <NEW_LINE> <INDENT> lats = sorted([p.latitude for p in self.points]) <NEW_LINE> lons = sorted([p.longitude for p in self.points]) <NEW_LINE> return Rectangle(Point(min(lats), min(lons)), Point(max(lats), max(lons))) <NEW_LINE> <DEDENT> @property <NEW_LINE> def mean_point(self): <NEW_LINE> <INDENT> lats = [p.latitude for p in self.points] <NEW_LINE> lons = [p.longitude for p in self.points] <NEW_LINE> return Point(sum(lats) / len(lats), sum(lons) / len(lons)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def diagonal(self): <NEW_LINE> <INDENT> return self.bounding_box.diagonal | Area defined by bordering Point instances | 62598fb18a43f66fc4bf21db |
class getCertificateCredential_args(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'tokenId', 'UTF8', None, ), (2, TType.STRING, 'gatewayId', 'UTF8', None, ), ) <NEW_LINE> def __init__(self, tokenId=None, gatewayId=None,): <NEW_LINE> <INDENT> self.tokenId = tokenId <NEW_LINE> self.gatewayId = gatewayId <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.tokenId = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.gatewayId = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getCertificateCredential_args') <NEW_LINE> if self.tokenId is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('tokenId', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.tokenId.encode('utf-8') if sys.version_info[0] == 2 else self.tokenId) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.gatewayId is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('gatewayId', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.gatewayId.encode('utf-8') if sys.version_info[0] == 2 else self.gatewayId) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.tokenId is None: <NEW_LINE> <INDENT> raise TProtocolException(message='Required field tokenId is unset!') <NEW_LINE> <DEDENT> if self.gatewayId is None: <NEW_LINE> <INDENT> raise TProtocolException(message='Required field gatewayId is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- tokenId
- gatewayId | 62598fb144b2445a339b69a1 |
class LossHistory(keras.callbacks.Callback): <NEW_LINE> <INDENT> def on_train_begin(self, logs={}): <NEW_LINE> <INDENT> self.losses = [] <NEW_LINE> self.epoch_losses = [] <NEW_LINE> self.epoch_val_losses = [] <NEW_LINE> <DEDENT> def on_batch_end(self, batch, logs={}): <NEW_LINE> <INDENT> self.losses.append(logs.get('loss')) <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch, logs={}): <NEW_LINE> <INDENT> self.epoch_losses.append(logs.get('loss')) <NEW_LINE> self.epoch_val_losses.append(logs.get('val_loss')) | A custom keras callback for recording losses during network training. | 62598fb17047854f4633f43a |
class WheelBuilder(object): <NEW_LINE> <INDENT> def __init__(self, requirement_set, finder, wheel_dir, build_options=[], global_options=[]): <NEW_LINE> <INDENT> self.requirement_set = requirement_set <NEW_LINE> self.finder = finder <NEW_LINE> self.wheel_dir = normalize_path(wheel_dir) <NEW_LINE> self.build_options = build_options <NEW_LINE> self.global_options = global_options <NEW_LINE> <DEDENT> def _build_one(self, req): <NEW_LINE> <INDENT> base_args = [ sys.executable, '-c', "import setuptools;__file__=%r;" "exec(compile(open(__file__).read().replace('\\r\\n', '\\n'), " "__file__, 'exec'))" % req.setup_py ] + list(self.global_options) <NEW_LINE> logger.notify('Running setup.py bdist_wheel for %s' % req.name) <NEW_LINE> logger.notify('Destination directory: %s' % self.wheel_dir) <NEW_LINE> wheel_args = base_args + ['bdist_wheel', '-d', self.wheel_dir] + self.build_options <NEW_LINE> try: <NEW_LINE> <INDENT> call_subprocess(wheel_args, cwd=req.source_dir, show_stdout=False) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error('Failed building wheel for %s' % req.name) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def build(self): <NEW_LINE> <INDENT> self.requirement_set.prepare_files(self.finder) <NEW_LINE> reqset = self.requirement_set.requirements.values() <NEW_LINE> buildset = [] <NEW_LINE> for req in reqset: <NEW_LINE> <INDENT> if req.is_wheel: <NEW_LINE> <INDENT> logger.notify( 'Skipping %s, due to already being wheel.' % req.name) <NEW_LINE> <DEDENT> elif req.editable: <NEW_LINE> <INDENT> logger.notify( 'Skipping %s, due to being editable' % req.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buildset.append(req) <NEW_LINE> <DEDENT> <DEDENT> if not buildset: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> logger.notify( 'Building wheels for collected packages: %s' % ', '.join([req.name for req in buildset]) ) <NEW_LINE> logger.indent += 2 <NEW_LINE> build_success, build_failure = [], [] <NEW_LINE> for req in buildset: <NEW_LINE> <INDENT> if self._build_one(req): <NEW_LINE> <INDENT> build_success.append(req) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> build_failure.append(req) <NEW_LINE> <DEDENT> <DEDENT> logger.indent -= 2 <NEW_LINE> if build_success: <NEW_LINE> <INDENT> logger.notify( 'Successfully built %s' % ' '.join([req.name for req in build_success]) ) <NEW_LINE> <DEDENT> if build_failure: <NEW_LINE> <INDENT> logger.notify( 'Failed to build %s' % ' '.join([req.name for req in build_failure]) ) <NEW_LINE> <DEDENT> return len(build_failure) == 0 | Build wheels from a RequirementSet. | 62598fb1460517430c43208e |
class ResetEvent(asyncio.Event): <NEW_LINE> <INDENT> def set(self) -> None: <NEW_LINE> <INDENT> super().set() <NEW_LINE> super().clear() | An event which automatically clears after being set | 62598fb1be383301e025385a |
class ErrorDetails(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'code': {'readonly': True}, 'http_status_code': {'readonly': True}, 'message': {'readonly': True}, 'details': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'http_status_code': {'key': 'httpStatusCode', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'details': {'key': 'details', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ErrorDetails, self).__init__(**kwargs) <NEW_LINE> self.code = None <NEW_LINE> self.http_status_code = None <NEW_LINE> self.message = None <NEW_LINE> self.details = None | Error details.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: The error code.
:vartype code: str
:ivar http_status_code: The HTTP status code.
:vartype http_status_code: str
:ivar message: The error message.
:vartype message: str
:ivar details: The error details.
:vartype details: str | 62598fb1a79ad1619776a0c9 |
class SentimentAnalysis(object): <NEW_LINE> <INDENT> def __init__(self, graph, clusters): <NEW_LINE> <INDENT> self.graph = graph <NEW_LINE> self.clusters = clusters <NEW_LINE> self.cluster_message = {} <NEW_LINE> <DEDENT> def get_cluster_message(self): <NEW_LINE> <INDENT> for cluster_id, cluster in self.clusters.iteritems(): <NEW_LINE> <INDENT> event_frequency = {} <NEW_LINE> for node in cluster: <NEW_LINE> <INDENT> event = self.graph.node[node]['preprocessed_event'] <NEW_LINE> event_frequency[event] = event_frequency.get(event, 0) + 1 <NEW_LINE> <DEDENT> sorted_event_frequency = sorted(event_frequency.items(), key=itemgetter(1), reverse=True)[0][0] <NEW_LINE> self.cluster_message[cluster_id] = sorted_event_frequency <NEW_LINE> <DEDENT> <DEDENT> def get_sentiment(self): <NEW_LINE> <INDENT> sentiment_score = {} <NEW_LINE> for cluster_id, message in self.cluster_message.iteritems(): <NEW_LINE> <INDENT> possible_sentiment = TextBlob(message) <NEW_LINE> if possible_sentiment.sentiment.polarity >= 0.: <NEW_LINE> <INDENT> sentiment_score[cluster_id] = possible_sentiment.sentiment.polarity <NEW_LINE> <DEDENT> elif possible_sentiment.sentiment.polarity < 0.: <NEW_LINE> <INDENT> sentiment_score[cluster_id] = possible_sentiment.sentiment.polarity <NEW_LINE> <DEDENT> <DEDENT> return sentiment_score | Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
References
----------
.. [Loria2016] Steven Loria and the contributors, TextBlob: Simple, Pythonic, text processing--Sentiment analysis,
part-of-speech tagging, noun phrase extraction, translation, and more.
https://github.com/sloria/TextBlob/ | 62598fb19c8ee823130401a2 |
class RessurrectionState(State): <NEW_LINE> <INDENT> def handle(self, context): <NEW_LINE> <INDENT> context.set_last_state(context.get_state()) <NEW_LINE> if context.get_resolve_sent() is False: <NEW_LINE> <INDENT> context.send_resolve() <NEW_LINE> <DEDENT> self.go_next(context) <NEW_LINE> <DEDENT> def go_next(self, context): <NEW_LINE> <INDENT> alive_state = AliveState() <NEW_LINE> context.set_state(alive_state) | Implement a behavior associated with RessurrectionState
Transitions:
* next state is always AliveState | 62598fb14a966d76dd5eef38 |
class Transformer(nn.Module): <NEW_LINE> <INDENT> def __init__(self, enc_vocab_len, enc_max_seq_len, dec_vocab_len, dec_max_seq_len, n_layer, n_head, d_model, d_k, d_v, d_f, pad_idx=1, pos_pad_idx=0, drop_rate=0.1, use_conv=False, linear_weight_share=True, embed_weight_share=False): <NEW_LINE> <INDENT> super(Transformer, self).__init__() <NEW_LINE> self.pad_idx = pad_idx <NEW_LINE> self.d_model = d_model <NEW_LINE> self.encoder = Encoder(enc_vocab_len, enc_max_seq_len, n_layer, n_head, d_model, d_k, d_v, d_f, pad_idx=pad_idx, pos_pad_idx=pos_pad_idx, drop_rate=drop_rate, use_conv=use_conv) <NEW_LINE> self.decoder = Decoder(dec_vocab_len, dec_max_seq_len, n_layer, n_head, d_model, d_k, d_v, d_f, pad_idx=pad_idx, pos_pad_idx=pos_pad_idx, drop_rate=drop_rate, use_conv=use_conv) <NEW_LINE> self.projection = nn.Linear(d_model, dec_vocab_len, bias=False) <NEW_LINE> if linear_weight_share: <NEW_LINE> <INDENT> self.projection.weight = self.decoder.embed_layer.embedding.weight <NEW_LINE> <DEDENT> if embed_weight_share: <NEW_LINE> <INDENT> assert enc_vocab_len == dec_vocab_len, "vocab length must be same" <NEW_LINE> self.encoder.embed_layer.embedding.weight = self.decoder.embed_layer.embedding.weight <NEW_LINE> <DEDENT> <DEDENT> def forward(self, enc, enc_pos, dec, dec_pos, return_attn=False): <NEW_LINE> <INDENT> dec = dec[:, :-1] <NEW_LINE> dec_pos = dec_pos[:, :-1] <NEW_LINE> if return_attn: <NEW_LINE> <INDENT> enc_output, enc_self_attns = self.encoder(enc, enc_pos, return_attn) <NEW_LINE> dec_output, (dec_self_attns, dec_enc_attns) = self.decoder(dec, dec_pos, enc, enc_output, return_attn) <NEW_LINE> dec_output = self.projection(dec_output) <NEW_LINE> attns_dict = {'enc_self_attns': enc_self_attns, 'dec_self_attns': dec_self_attns, 'dec_enc_attns': dec_enc_attns} <NEW_LINE> return dec_output, attns_dict <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enc_output = self.encoder(enc, enc_pos, return_attn) <NEW_LINE> dec_output = self.decoder(dec, dec_pos, enc, enc_output, return_attn) <NEW_LINE> dec_output = self.projection(dec_output) <NEW_LINE> return dec_output | Transformer Model | 62598fb126068e7796d4c9b6 |
class BatchRename(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.path = 'C://Users//ZCZ//Desktop//青蛙//总集2' <NEW_LINE> <DEDENT> def rename(self): <NEW_LINE> <INDENT> filelist = os.listdir(self.path) <NEW_LINE> total_num = len(filelist) <NEW_LINE> i = 1 <NEW_LINE> for item in filelist: <NEW_LINE> <INDENT> if item.endswith('.jpg'): <NEW_LINE> <INDENT> src = os.path.join(os.path.abspath(self.path), item) <NEW_LINE> dst = os.path.join(os.path.abspath(self.path), format(str(i), '0>1s') + '.jpg') <NEW_LINE> try: <NEW_LINE> <INDENT> os.rename(src, dst) <NEW_LINE> print ('converting %s to %s ...' % (src, dst)) <NEW_LINE> i = i + 1 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> print ('total %d to rename & converted %d jpgs' % (total_num, i)) | 批量重命名文件夹中的图片文件 | 62598fb1a8370b77170f043d |
class Error(ErrorResult): <NEW_LINE> <INDENT> def __init__(self, error): <NEW_LINE> <INDENT> self.is_error = True <NEW_LINE> self.traceback = traceback.format_exc() <NEW_LINE> self.error = error | Indicates an error occurred.
Args:
error (Exception):
Exception that was raised inside of the function or method | 62598fb12c8b7c6e89bd3826 |
class AVL_Tree(object): <NEW_LINE> <INDENT> def getHeight(self, node): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return node.height <NEW_LINE> <DEDENT> def getBalanceFactor(self, node): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.getHeight(node.left) - self.getHeight(node.right) <NEW_LINE> <DEDENT> def leftRotate(self, node): <NEW_LINE> <INDENT> finalNode = node.right <NEW_LINE> tempNode = finalNode.left <NEW_LINE> finalNode.left = node <NEW_LINE> node.right = tempNode <NEW_LINE> node.height = 1 + max( self.getHeight(node.left), self.getHeight(node.right) ) <NEW_LINE> finalNode.height = 1 + max( self.getHeight(finalNode.left), self.getHeight(finalNode.right) ) <NEW_LINE> return finalNode <NEW_LINE> <DEDENT> def rightRotate(self, node): <NEW_LINE> <INDENT> finalNode = node.left <NEW_LINE> tempNode = finalNode.right <NEW_LINE> finalNode.left = node <NEW_LINE> node.right = tempNode <NEW_LINE> node.height = 1 + max( self.getHeight(node.left), self.getHeight(node.right) ) <NEW_LINE> finalNode.height = 1 + max( self.getHeight(finalNode.left), self.getHeight(finalNode.right) ) <NEW_LINE> return finalNode <NEW_LINE> <DEDENT> def insertNode(self, rootNode, value): <NEW_LINE> <INDENT> if not rootNode: return Node(value) <NEW_LINE> if value < rootNode.value: <NEW_LINE> <INDENT> rootNode.left = self.insertNode(rootNode.left, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rootNode.right = self.insertNode(rootNode.right, value) <NEW_LINE> <DEDENT> balanceFactor = self.getBalanceFactor(rootNode) <NEW_LINE> if balanceFactor > 1: <NEW_LINE> <INDENT> if value < rootNode.left.value: <NEW_LINE> <INDENT> return self.rightRotate(rootNode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rootNode.left = self.leftRotate(root.left) <NEW_LINE> return self.rightRotate(root) <NEW_LINE> <DEDENT> <DEDENT> if balanceFactor < -1: <NEW_LINE> <INDENT> if value > rootNode.right.value: <NEW_LINE> <INDENT> return self.leftRotate(rootNode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rootNode.right = self.rightRotate(root.right) <NEW_LINE> return self.leftRotate(rootNode) <NEW_LINE> <DEDENT> <DEDENT> return rootNode | Implements AVL Tree. | 62598fb192d797404e388b94 |
class Lexicographical(Sorting): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Sorting.__init__(self) <NEW_LINE> <DEDENT> def is_applicable(self,choices): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def sort(self,choices): <NEW_LINE> <INDENT> return sorted(choices) | Sorts keys in lexicographical order | 62598fb1bf627c535bcb1500 |
class ExtGridCellSelModel(BaseExtGridSelModel): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ExtGridCellSelModel, self).__init__(*args, **kwargs) <NEW_LINE> self.init_component(*args, **kwargs) <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return 'new Ext.grid.CellSelectionModel()' | Модель для грида с выбором ячеек | 62598fb167a9b606de54602f |
class List(Serializer): <NEW_LINE> <INDENT> def __init__(self, data_type=None, *args, **kwargs): <NEW_LINE> <INDENT> self._type = data_type <NEW_LINE> super(List, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def validate(self, key, value): <NEW_LINE> <INDENT> super(List, self).validate(key, value) <NEW_LINE> if not isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> raise self.ValidationError("'%s's value should be a instance of" "list or tuple." % key) <NEW_LINE> <DEDENT> <DEDENT> def serialize(self, value, **kwargs): <NEW_LINE> <INDENT> if self._type: <NEW_LINE> <INDENT> return [self._type.serialize(i) for i in value] <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def deserialize(self, value): <NEW_LINE> <INDENT> if self._type: <NEW_LINE> <INDENT> return [self._type.deserialize(i) for i in value] <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def is_valid_value(self, value): <NEW_LINE> <INDENT> if isinstance(value, (tuple, list)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Serializer for a list of data. | 62598fb155399d3f0562657e |
class SequentialFile(MultiFile): <NEW_LINE> <INDENT> def __init__(self, raw_files, *args, **kwargs): <NEW_LINE> <INDENT> self.files = raw_files <NEW_LINE> self.filesize = os.path.getsize(self.files[0]) <NEW_LINE> super(SequentialFile, self).__init__(None, *args, **kwargs) <NEW_LINE> self.current_file_number = None <NEW_LINE> self.header_size = 0 <NEW_LINE> self.open(0) <NEW_LINE> self.offset = 0 <NEW_LINE> <DEDENT> def open(self, number=0): <NEW_LINE> <INDENT> if number != self.current_file_number: <NEW_LINE> <INDENT> self.close() <NEW_LINE> self.fh_raw = open(self.files[number], mode='rb') <NEW_LINE> self.current_file_number = number <NEW_LINE> <DEDENT> return self.fh_raw <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.current_file_number is not None: <NEW_LINE> <INDENT> self.fh_raw.close() <NEW_LINE> self.current_file_number = None <NEW_LINE> <DEDENT> <DEDENT> def _seek(self, offset): <NEW_LINE> <INDENT> assert offset % self.recordsize == 0 <NEW_LINE> file_number, file_offset = divmod(offset, self.filesize - self.header_size) <NEW_LINE> self.open(file_number) <NEW_LINE> self.fh_raw.seek(file_offset + self.header_size) <NEW_LINE> self.offset = offset <NEW_LINE> <DEDENT> def read(self, size): <NEW_LINE> <INDENT> if size % self.recordsize != 0: <NEW_LINE> <INDENT> raise ValueError("Cannot read a non-integer number of records") <NEW_LINE> <DEDENT> size = min(size, len(self.files) * self.filesize - self.offset) <NEW_LINE> if size <= 0: <NEW_LINE> <INDENT> raise EOFError('At end of file!') <NEW_LINE> <DEDENT> z = np.empty(size, dtype=np.int8) <NEW_LINE> iz = 0 <NEW_LINE> while(iz < size): <NEW_LINE> <INDENT> self._seek(self.offset) <NEW_LINE> block, already_read = divmod(self.offset, self.filesize) <NEW_LINE> fh_size = min(size - iz, self.filesize - already_read) <NEW_LINE> z[iz:iz+fh_size] = np.fromstring(self.fh_raw.read(fh_size), dtype=z.dtype) <NEW_LINE> iz += fh_size <NEW_LINE> self.offset += fh_size <NEW_LINE> <DEDENT> return z <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.current_file_number is not None: <NEW_LINE> <INDENT> return ("<SequentialFile: file {0} open, offset {1} (time {2})>" .format(self.files[self.current_file_number], self.offset, self.time().isot)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ("<SequentialFile: no files open, file list={0}>" .format(self.files)) | Class for readers that read from data stored in a sequence of files. | 62598fb1e1aae11d1e7ce854 |
class CustomQueueHandler(logging.handlers.QueueHandler): <NEW_LINE> <INDENT> def __init__(self, queue): <NEW_LINE> <INDENT> super().__init__(queue) <NEW_LINE> <DEDENT> def prepare(self, record): <NEW_LINE> <INDENT> record = copy.copy(record) <NEW_LINE> record.exc_info = None <NEW_LINE> record.exc_text = None <NEW_LINE> return record | Overrides the prepare method of QueueHandler to prevent all
messages from being converted to strings | 62598fb197e22403b383af6f |
class CollectorPackage(Logging): <NEW_LINE> <INDENT> _PACKAGE_TYPE_NAMES = { COLLECTOR: 'SumoCollector', } <NEW_LINE> _ROOT_URL = 'https://collectors.sumologic.com/rest/download' <NEW_LINE> _RELEASE_PACKAGE_FORMAT = '{type}-{version}-{build}-{suffix}' <NEW_LINE> __meta__ = ABCMeta <NEW_LINE> def __init__(self, platform): <NEW_LINE> <INDENT> self._platform = None <NEW_LINE> self._installer_name = None <NEW_LINE> self._set_platform(platform) <NEW_LINE> Logging.__init__(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def platform(self): <NEW_LINE> <INDENT> return self._platform <NEW_LINE> <DEDENT> @property <NEW_LINE> def installer_name(self): <NEW_LINE> <INDENT> self._installer_name <NEW_LINE> <DEDENT> @installer_name.setter <NEW_LINE> def installer_name(self, installer_name): <NEW_LINE> <INDENT> self._installer_name = installer_name <NEW_LINE> <DEDENT> @platform.setter <NEW_LINE> def platform(self, platform): <NEW_LINE> <INDENT> self._set_platform(platform) <NEW_LINE> <DEDENT> def _set_platform(self, platform): <NEW_LINE> <INDENT> platform = platform or collector_platform.get_platform() <NEW_LINE> if not isinstance(platform, CollectorPlatform): <NEW_LINE> <INDENT> raise InvalidCollectorPlatform(platform) <NEW_LINE> <DEDENT> self._platform = platform <NEW_LINE> <DEDENT> def _get_package_name(self, version, build): <NEW_LINE> <INDENT> args = { 'suffix': self.platform.package_suffix, 'version': version, 'build': build, } <NEW_LINE> return self._package_name_format.format(**args) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _package_name_format(self): <NEW_LINE> <INDENT> if self.debug_build: <NEW_LINE> <INDENT> return self._DEBUG_PACKAGE_FORMAT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._RELEASE_PACKAGE_FORMAT <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _settings(self): <NEW_LINE> <INDENT> return { 'platform': self.platform, 'package_type': self.package_type, 'debug_build': self.debug_build } <NEW_LINE> <DEDENT> def download(self): <NEW_LINE> <INDENT> return self.download_to(None) <NEW_LINE> <DEDENT> def download_to(self, target=None): <NEW_LINE> <INDENT> url = self.get_url() <NEW_LINE> request = HeadRequest(url) <NEW_LINE> response = urllib2.urlopen(request) <NEW_LINE> response_headers = response.info() <NEW_LINE> filename = response_headers.dict['content-disposition'] <NEW_LINE> filename = filename.split(';')[1].split('=')[1] <NEW_LINE> self.installer_name = filename <NEW_LINE> self.logger.info('Fetching package from %s' % url) <NEW_LINE> if target is None: <NEW_LINE> <INDENT> return urllib.urlretrieve(url, filename)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return urllib.urlretrieve(url, os.path.join(target, filename))[0] <NEW_LINE> <DEDENT> <DEDENT> @abstractmethod <NEW_LINE> def get_url(self): <NEW_LINE> <INDENT> pass | Represents a generic collector package.
@cvar _ROOT_URL: The root URL to the releases page.
@type _ROOT_URL: str
@cvar _RELEASE_PACKAGE_FORMAT: The format of a release package name. Will
contain args type, version, build and suffix.
@type _RELEASE_PACKAGE_FORMAT: str
@ivar _platform: The platform of the package.
@type _platform: L{CollectorPlatform}
@ivar _package_type: The type of package.
@type _package_type: str | 62598fb1796e427e5384e7f6 |
class Timer(object): <NEW_LINE> <INDENT> def __init__(self, interval, callback, arguments=None): <NEW_LINE> <INDENT> super(Timer, self).__init__() <NEW_LINE> self.interval = interval <NEW_LINE> self.callback = callback <NEW_LINE> self.arguments = arguments <NEW_LINE> self.paused = False <NEW_LINE> self.lastcall = pygame.time.get_ticks() <NEW_LINE> <DEDENT> def toggle_pause(self): <NEW_LINE> <INDENT> self.paused = not self.paused | A timer defined in terms of a time interval and a callback function that
is called every time such interval passes. If the callback function has any
arguments, they should be passed in a dict. | 62598fb1851cf427c66b831d |
@admin.register(ChatText) <NEW_LINE> class ChatTextAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('room_id', 'content', 'count') | Registers the ChatText Model
| 62598fb11f5feb6acb162c80 |
class AudioNormalize(object): <NEW_LINE> <INDENT> def __init__(self, _mean=None, _std=None): <NEW_LINE> <INDENT> self._mean = _mean <NEW_LINE> self._std = _std <NEW_LINE> <DEDENT> def __call__(self, data): <NEW_LINE> <INDENT> _mean = data.mean(axis=None) if self._mean is None else self._mean <NEW_LINE> _std = data.std(axis=None) if self._std is None else self._std <NEW_LINE> return (data - _mean) / _std <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def compute_mean_std(dataset, transform, datasets=['train'], samples=None): <NEW_LINE> <INDENT> manifest = list(filter(lambda entry: entry['dataset'] in datasets, dataset.manifest)) <NEW_LINE> length = samples if samples is not None else len(manifest) <NEW_LINE> ids = list(range(0, length)) <NEW_LINE> sampled_manifest = np.array(manifest)[ids] <NEW_LINE> features = [] <NEW_LINE> for entry in sampled_manifest: <NEW_LINE> <INDENT> data = AudioDataset.load_audio(entry['recording_path'], entry['recording_sr']) <NEW_LINE> spect = transform(data) <NEW_LINE> features.append(spect) <NEW_LINE> <DEDENT> features = np.hstack(features) <NEW_LINE> _mean = np.mean(features, axis=None) <NEW_LINE> _std = np.std(features, axis=None) <NEW_LINE> return _mean, _std <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_mean_std(data): <NEW_LINE> <INDENT> return np.mean(data, axis=None), np.std(data, axis=None) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ + '(mean={0}, std={1})'.format(self._mean, self._std) | Normalize spectrogram of mono audio with mean and standard deviation. | 62598fb1f548e778e596b605 |
class RegionInstanceGroupList(_messages.Message): <NEW_LINE> <INDENT> id = _messages.StringField(1) <NEW_LINE> items = _messages.MessageField('InstanceGroup', 2, repeated=True) <NEW_LINE> kind = _messages.StringField(3, default=u'compute#regionInstanceGroupList') <NEW_LINE> nextPageToken = _messages.StringField(4) <NEW_LINE> selfLink = _messages.StringField(5) | Contains a list of InstanceGroup resources.
Fields:
id: [Output Only] The unique identifier for the resource. This identifier
is defined by the server.
items: A list of InstanceGroup resources.
kind: The resource type.
nextPageToken: [Output Only] This token allows you to get the next page of
results for list requests. If the number of results is larger than
maxResults, use the nextPageToken as a value for the query parameter
pageToken in the next list request. Subsequent list requests will have
their own nextPageToken to continue paging through the results.
selfLink: [Output Only] The URL for this resource type. The server
generates this URL. | 62598fb18a43f66fc4bf21dd |
class PrefixList2(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "prefix-list-2" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.name = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | This class does not support CRUD Operations please use parent.
:param name: {"minLength": 1, "maxLength": 128, "type": "string", "description": "IPv6 prefix-list name", "format": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` | 62598fb1d58c6744b42dc309 |
class TestTriggerWorkflowCollectionRep(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 testTriggerWorkflowCollectionRep(self): <NEW_LINE> <INDENT> pass | TriggerWorkflowCollectionRep unit test stubs | 62598fb1f9cc0f698b1c52fb |
class UnitTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.name = "Mysql_Server" <NEW_LINE> self.server_id = 10 <NEW_LINE> self.sql_user = "mysql_user" <NEW_LINE> self.sql_pass = "my_japd" <NEW_LINE> self.machine = getattr(machine, "Linux")() <NEW_LINE> self.host = "host_server" <NEW_LINE> self.port = 3307 <NEW_LINE> self.defaults_file = "def_cfg_file" <NEW_LINE> self.extra_def_file = "extra_cfg_file" <NEW_LINE> <DEDENT> def test_list(self): <NEW_LINE> <INDENT> mysqlrep = mysql_class.SlaveRep(self.name, self.server_id, self.sql_user, self.sql_pass, self.machine, defaults_file=self.defaults_file) <NEW_LINE> mysqlrep.ign_tbl = "db1.tbl1,db2.tbl2,db3.tbl3" <NEW_LINE> self.assertEqual(mysqlrep.fetch_ign_tbl(), {'db1': ['tbl1'], 'db3': ['tbl3'], 'db2': ['tbl2']}) <NEW_LINE> <DEDENT> def test_default(self): <NEW_LINE> <INDENT> mysqlrep = mysql_class.SlaveRep(self.name, self.server_id, self.sql_user, self.sql_pass, self.machine, defaults_file=self.defaults_file) <NEW_LINE> self.assertEqual(mysqlrep.fetch_ign_tbl(), []) | Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp -> Initialize testing environment.
test_list -> Test fetch_ign_tbl method with data.
test_default -> Test fetch_ign_tbl method with no data. | 62598fb166673b3332c3042e |
class Double(Primitive): <NEW_LINE> <INDENT> fmt = "d" | Represents a double-precision floating poing conforming to IEEE 754. | 62598fb130dc7b766599f8af |
class ComputeRegionsListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> orderBy = _messages.StringField(3) <NEW_LINE> pageToken = _messages.StringField(4) <NEW_LINE> project = _messages.StringField(5, required=True) | A ComputeRegionsListRequest object.
Fields:
filter: Sets a filter expression for filtering listed resources, in the
form filter={expression}. Your {expression} must be in the format:
field_name comparison_string literal_string. The field_name is the name
of the field you want to compare. Only atomic field types are supported
(string, number, boolean). The comparison_string must be either eq
(equals) or ne (not equals). The literal_string is the string value to
filter to. The literal value must be valid for the type of field you are
filtering by (string, number, boolean). For string fields, the literal
value is interpreted as a regular expression using RE2 syntax. The
literal value must match the entire field. For example, to filter for
instances that do not have a name of example-instance, you would use
filter=name ne example-instance. Compute Engine Beta API Only: When
filtering in the Beta API, you can also filter on nested fields. For
example, you could filter on instances that have set the
scheduling.automaticRestart field to true. Use filtering on nested
fields to take advantage of labels to organize and search for results
based on label values. The Beta API also supports filtering on multiple
expressions by providing each separate expression within parentheses.
For example, (scheduling.automaticRestart eq true) (zone eq us-
central1-f). Multiple expressions are treated as AND expressions,
meaning that resources must match all expressions to pass the filters.
maxResults: The maximum number of results per page that should be
returned. If the number of available results is larger than maxResults,
Compute Engine returns a nextPageToken that can be used to get the next
page of results in subsequent list requests.
orderBy: Sorts list results by a certain order. By default, results are
returned in alphanumerical order based on the resource name. You can
also sort results in descending order based on the creation timestamp
using orderBy="creationTimestamp desc". This sorts results based on the
creationTimestamp field in reverse chronological order (newest result
first). Use this to sort resources like operations so that the newest
operation is returned first. Currently, only sorting by name or
creationTimestamp desc is supported.
pageToken: Specifies a page token to use. Set pageToken to the
nextPageToken returned by a previous list request to get the next page
of results.
project: Project ID for this request. | 62598fb10c0af96317c563de |
class CuentaList(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Cuenta.objects.all() <NEW_LINE> serializer_class = CuentaSerializer | Listado y creacion de cuenta | 62598fb1d268445f26639bb4 |
class fRect: <NEW_LINE> <INDENT> def __init__(self, pos, size): <NEW_LINE> <INDENT> self.pos = (pos[0], pos[1]) <NEW_LINE> self.size = (size[0], size[1]) <NEW_LINE> <DEDENT> def move(self, x, y): <NEW_LINE> <INDENT> return fRect((self.pos[0]+x, self.pos[1]+y), self.size) <NEW_LINE> <DEDENT> def move_ip(self, x, y, move_factor = 1): <NEW_LINE> <INDENT> self.pos = (self.pos[0] + x*move_factor, self.pos[1] + y*move_factor) <NEW_LINE> <DEDENT> def get_rect(self): <NEW_LINE> <INDENT> return Rect(self.pos, self.size) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return fRect(self.pos, self.size) <NEW_LINE> <DEDENT> def intersect(self, other_frect): <NEW_LINE> <INDENT> for i in range(2): <NEW_LINE> <INDENT> if self.pos[i] < other_frect.pos[i]: <NEW_LINE> <INDENT> if other_frect.pos[i] >= self.pos[i] + self.size[i]: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> elif self.pos[i] > other_frect.pos[i]: <NEW_LINE> <INDENT> if self.pos[i] >= other_frect.pos[i] + other_frect.size[i]: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return 1 <NEW_LINE> <DEDENT> def get_angle(self, y): <NEW_LINE> <INDENT> center = self.pos[1]+self.size[1]/2 <NEW_LINE> rel_dist_from_c = ((y-center)/self.size[1]) <NEW_LINE> rel_dist_from_c = min(0.5, rel_dist_from_c) <NEW_LINE> rel_dist_from_c = max(-0.5, rel_dist_from_c) <NEW_LINE> sign = 1-2*self.facing <NEW_LINE> return sign*rel_dist_from_c*self.max_angle*math.pi/180 | Like PyGame's Rect class, but with floating point coordinates | 62598fb1167d2b6e312b6fd4 |
class BasicResidualBlock(nn.Module): <NEW_LINE> <INDENT> expansion = 1 <NEW_LINE> def __init__(self, inplanes, planes, stride=1, downsample=None): <NEW_LINE> <INDENT> super(BasicResidualBlock, self).__init__() <NEW_LINE> self.conv1 = ConvLayer(inplanes, planes, kernel_size=3, stride=1) <NEW_LINE> self.bn1 = nn.BatchNorm2d(planes) <NEW_LINE> self.relu = nn.ReLU(inplace=True) <NEW_LINE> self.conv2 = ConvLayer(planes, planes, kernel_size=3, stride=1) <NEW_LINE> self.bn2 = nn.BatchNorm2d(planes) <NEW_LINE> self.downsample = downsample <NEW_LINE> self.stride = stride <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> identity = x <NEW_LINE> out = self.conv1(x) <NEW_LINE> out = self.bn1(out) <NEW_LINE> out = self.relu(out) <NEW_LINE> out = self.conv2(out) <NEW_LINE> out = self.bn2(out) <NEW_LINE> if self.downsample is not None: <NEW_LINE> <INDENT> identity = self.downsample(x) <NEW_LINE> <DEDENT> out += identity <NEW_LINE> out = self.relu(out) <NEW_LINE> return out | Residual block
Original Code is from: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
Some parts are modified. | 62598fb1ff9c53063f51a6af |
class TestFace(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._processInterest = None <NEW_LINE> self._sentInterests = [] <NEW_LINE> <DEDENT> def expressInterest(self, interest, onData, onTimeout, onNetworkNack): <NEW_LINE> <INDENT> self._sentInterests.append(Interest(interest)) <NEW_LINE> if self._processInterest != None: <NEW_LINE> <INDENT> self._processInterest(interest, onData, onTimeout, onNetworkNack) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> onTimeout(interest) <NEW_LINE> <DEDENT> return 0 | TestFace extends Face to instantly simulate a call to expressInterest.
See expressInterest for details. | 62598fb14a966d76dd5eef3a |
class data: <NEW_LINE> <INDENT> def __init__(self,name=None,x=[],y=[],E=[]): <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.x = copy.copy(x) <NEW_LINE> self.y = copy.copy(y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name ='none' <NEW_LINE> self.x = [0.0,0.0,0.0] <NEW_LINE> self.y = [0.0,0.0,0.0] <NEW_LINE> <DEDENT> if(len(E)==0): <NEW_LINE> <INDENT> self.E=np.zeros(len(self.x)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.E=copy.copy(E) <NEW_LINE> <DEDENT> self.showError=False <NEW_LINE> self.markers="x" <NEW_LINE> self.colour="k" <NEW_LINE> self.linestyle='--' <NEW_LINE> <DEDENT> def order_data(self): <NEW_LINE> <INDENT> xData=self.x <NEW_LINE> yData=self.y <NEW_LINE> eData=self.E <NEW_LINE> for j in range(0,len(yData)): <NEW_LINE> <INDENT> for k in range(0,len(xData)-1): <NEW_LINE> <INDENT> if xData[k]>xData[k+1]: <NEW_LINE> <INDENT> xData[k+1],xData[k]=xData[k],xData[k+1] <NEW_LINE> yData[k+1],yData[k]=yData[k],yData[k+1] <NEW_LINE> eData[k+1],eData[k]=eData[k],eData[k+1] | Holds the data and relevant information for plotting | 62598fb14f88993c371f053c |
class MoveStopMove(BaseStim): <NEW_LINE> <INDENT> def __init__(self, win, speed=100, stop_t=1.0, stop_dur=1.0, *args, **kwargs): <NEW_LINE> <INDENT> self.stop_t = stop_t <NEW_LINE> self.stop_dur = stop_dur <NEW_LINE> self.speed = speed <NEW_LINE> self.objects = (visual.Circle(win, radius=20, fillColor=(1,1,1), units="pix"), ) <NEW_LINE> super(MoveStopMove, self).__init__(win, *args, **kwargs) <NEW_LINE> <DEDENT> def _move_objects(self): <NEW_LINE> <INDENT> x_0, y_0 = self.start_pos <NEW_LINE> tt = self.time <NEW_LINE> if self.stop_t < tt <= self.stop_t + self.stop_dur: <NEW_LINE> <INDENT> tt = self.stop_t <NEW_LINE> <DEDENT> elif tt > self.stop_t + self.stop_dur: <NEW_LINE> <INDENT> tt -= self.stop_dur <NEW_LINE> <DEDENT> circle = self.objects[0] <NEW_LINE> circle.pos = (self.speed * tt + x_0, y_0) | Moves one circle from left to right and stops it at a given time. | 62598fb167a9b606de546030 |
class showdiff(models.TransientModel): <NEW_LINE> <INDENT> _name = 'wizard.document.page.history.show_diff' <NEW_LINE> def get_diff(self): <NEW_LINE> <INDENT> history = self.env["document.page.history"] <NEW_LINE> ids = self.env.context.get('active_ids', []) <NEW_LINE> diff = "" <NEW_LINE> if len(ids) == 2: <NEW_LINE> <INDENT> if ids[0] > ids[1]: <NEW_LINE> <INDENT> diff = history.getDiff(ids[1], ids[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diff = history.getDiff(ids[0], ids[1]) <NEW_LINE> <DEDENT> <DEDENT> elif len(ids) == 1: <NEW_LINE> <INDENT> old = history.browse(ids[0]) <NEW_LINE> nids = history.search( [('page_id', '=', old.page_id.id)], order='id DESC', limit=1 ) <NEW_LINE> diff = history.getDiff(ids[0], nids.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise exceptions.Warning( _("You need to select minimum one or maximum " "two history revisions!") ) <NEW_LINE> <DEDENT> return diff <NEW_LINE> <DEDENT> diff = fields.Text( 'Diff', readonly=True, default=get_diff ) | Display Difference for History | 62598fb14c3428357761a31c |
class PolicyDefinition(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'policy_type': {'key': 'properties.policyType', 'type': 'str'}, 'mode': {'key': 'properties.mode', 'type': 'str'}, 'display_name': {'key': 'properties.displayName', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'policy_rule': {'key': 'properties.policyRule', 'type': 'object'}, 'metadata': {'key': 'properties.metadata', 'type': 'object'}, 'parameters': {'key': 'properties.parameters', 'type': 'object'}, } <NEW_LINE> def __init__( self, *, policy_type: Optional[Union[str, "PolicyType"]] = None, mode: Optional[Union[str, "PolicyMode"]] = None, display_name: Optional[str] = None, description: Optional[str] = None, policy_rule: Optional[Any] = None, metadata: Optional[Any] = None, parameters: Optional[Any] = None, **kwargs ): <NEW_LINE> <INDENT> super(PolicyDefinition, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.policy_type = policy_type <NEW_LINE> self.mode = mode <NEW_LINE> self.display_name = display_name <NEW_LINE> self.description = description <NEW_LINE> self.policy_rule = policy_rule <NEW_LINE> self.metadata = metadata <NEW_LINE> self.parameters = parameters | The policy definition.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: The ID of the policy definition.
:vartype id: str
:ivar name: The name of the policy definition.
:vartype name: str
:ivar policy_type: The type of policy definition. Possible values are NotSpecified, BuiltIn,
and Custom. Possible values include: "NotSpecified", "BuiltIn", "Custom".
:vartype policy_type: str or ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyType
:ivar mode: The policy definition mode. Possible values are NotSpecified, Indexed, and All.
Possible values include: "NotSpecified", "Indexed", "All".
:vartype mode: str or ~azure.mgmt.resource.policy.v2017_06_01_preview.models.PolicyMode
:ivar display_name: The display name of the policy definition.
:vartype display_name: str
:ivar description: The policy definition description.
:vartype description: str
:ivar policy_rule: The policy rule.
:vartype policy_rule: any
:ivar metadata: The policy definition metadata.
:vartype metadata: any
:ivar parameters: Required if a parameter is used in policy rule.
:vartype parameters: any | 62598fb1627d3e7fe0e06f11 |
class BaseTask(PolymorphicModel): <NEW_LINE> <INDENT> topic_name = models.CharField( _("topic name"), max_length=255, help_text=_("Topics determine which functions need to run for a task."), ) <NEW_LINE> variables = JSONField(default=dict) <NEW_LINE> status = models.CharField( _("status"), max_length=50, choices=Statuses.choices, default=Statuses.initial, help_text=_("The current status of task processing"), ) <NEW_LINE> result_variables = JSONField(default=dict) <NEW_LINE> execution_error = models.TextField( _("execution error"), blank=True, help_text=_("The error that occurred during execution."), ) <NEW_LINE> logs = GenericRelation(TimelineLog, related_query_name="task") <NEW_LINE> objects = PolymorphicManager.from_queryset(BaseTaskQuerySet)() <NEW_LINE> def get_variables(self) -> dict: <NEW_LINE> <INDENT> return self.variables <NEW_LINE> <DEDENT> def request_logs(self) -> models.QuerySet: <NEW_LINE> <INDENT> return self.logs.filter(extra_data__has_key="request").order_by("-timestamp") <NEW_LINE> <DEDENT> def status_logs(self) -> models.QuerySet: <NEW_LINE> <INDENT> return self.logs.filter(extra_data__has_key="status").order_by("-timestamp") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.polymorphic_ctype}: {self.topic_name} / {self.id}" | An external task to be processed by work units.
Use this as the base class for process-engine specific task definitions. | 62598fb171ff763f4b5e77d5 |
class UserFavorites(object): <NEW_LINE> <INDENT> swagger_types = { 'favorites': 'list[str]' } <NEW_LINE> attribute_map = { 'favorites': 'favorites' } <NEW_LINE> def __init__(self, favorites=None): <NEW_LINE> <INDENT> self._favorites = None <NEW_LINE> self.discriminator = None <NEW_LINE> if favorites is not None: <NEW_LINE> <INDENT> self.favorites = favorites <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def favorites(self): <NEW_LINE> <INDENT> return self._favorites <NEW_LINE> <DEDENT> @favorites.setter <NEW_LINE> def favorites(self, favorites): <NEW_LINE> <INDENT> self._favorites = favorites <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(UserFavorites, 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, UserFavorites): <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. | 62598fb167a9b606de546031 |
class FlowUnitChangeViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = FlowUnitChangeSerializer <NEW_LINE> queryset = FlowUnitChange.objects.all() <NEW_LINE> filter_fields = ('cost_manager_id', 'incomes_id') | retrieve:
Return a change in cost or income.
list:
Return all changes, ordered by most recently joined.
create:
Create a new change in cost or income.
delete:
Remove an existing change in cost or income.
partial_update:
Update one or more fields on an existing change.
update:
Update a change in flow. | 62598fb1a17c0f6771d5c298 |
class Polygon: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.LIST, 'coordinates', (TType.STRUCT,(Point, Point.thrift_spec)), None, ), ) <NEW_LINE> def __init__(self, coordinates=None,): <NEW_LINE> <INDENT> self.coordinates = coordinates <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.coordinates = [] <NEW_LINE> (_etype3, _size0) = iprot.readListBegin() <NEW_LINE> for _i4 in xrange(_size0): <NEW_LINE> <INDENT> _elem5 = Point() <NEW_LINE> _elem5.read(iprot) <NEW_LINE> self.coordinates.append(_elem5) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('Polygon') <NEW_LINE> if self.coordinates is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('coordinates', TType.LIST, 1) <NEW_LINE> oprot.writeListBegin(TType.STRUCT, len(self.coordinates)) <NEW_LINE> for iter6 in self.coordinates: <NEW_LINE> <INDENT> iter6.write(oprot) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.coordinates is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field coordinates is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- coordinates | 62598fb1236d856c2adc9470 |
class AdminMatchAdd(LoggedInHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> self._require_admin() <NEW_LINE> event_key = self.request.get('event_key') <NEW_LINE> matches_csv = self.request.get('matches_csv') <NEW_LINE> matches = OffseasonMatchesParser.parse(matches_csv) <NEW_LINE> event = Event.get_by_id(event_key) <NEW_LINE> matches = [Match( id=Match.renderKeyName( event.key.id(), match.get("comp_level", None), match.get("set_number", 0), match.get("match_number", 0)), event=event.key, game=Match.FRC_GAMES_BY_YEAR.get(event.year, "frc_unknown"), set_number=match.get("set_number", 0), match_number=match.get("match_number", 0), comp_level=match.get("comp_level", None), team_key_names=match.get("team_key_names", None), alliances_json=match.get("alliances_json", None) ) for match in matches] <NEW_LINE> MatchManipulator.createOrUpdate(matches) <NEW_LINE> self.redirect('/admin/event/{}'.format(event_key)) | Add Matches from CSV. | 62598fb144b2445a339b69a3 |
class LibvirtdDebugLog(object): <NEW_LINE> <INDENT> def __init__(self, test, log_level="1", log_file=""): <NEW_LINE> <INDENT> self.log_level = log_level <NEW_LINE> self.log_file = log_file <NEW_LINE> self.test = test <NEW_LINE> self.libvirtd = utils_libvirtd.Libvirtd() <NEW_LINE> self.libvirtd_conf = utils_config.LibvirtdConfig() <NEW_LINE> self.backupfile = "%s.backup" % self.libvirtd_conf.conf_path <NEW_LINE> <DEDENT> def enable(self): <NEW_LINE> <INDENT> if not self.log_file or not os.path.isdir(os.path.dirname(self.log_file)): <NEW_LINE> <INDENT> self.log_file = utils_misc.get_path(self.test.debugdir, "libvirtd.log") <NEW_LINE> <DEDENT> if os.path.isfile(self.backupfile): <NEW_LINE> <INDENT> os.remove(self.backupfile) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(self.backupfile, "w") as fd: <NEW_LINE> <INDENT> fd.write(self.libvirtd_conf.backup_content) <NEW_LINE> fd.close() <NEW_LINE> <DEDENT> <DEDENT> except IOError as info: <NEW_LINE> <INDENT> self.test.error(info) <NEW_LINE> <DEDENT> self.test.params["libvirtd_debug_file"] = self.log_file <NEW_LINE> logging.debug("libvirtd debug log stored in: %s", self.log_file) <NEW_LINE> self.libvirtd_conf["log_level"] = self.log_level <NEW_LINE> self.libvirtd_conf["log_outputs"] = '"%s:file:%s"' % (self.log_level, self.log_file) <NEW_LINE> self.libvirtd.restart() <NEW_LINE> <DEDENT> def disable(self): <NEW_LINE> <INDENT> os.rename(self.backupfile, self.libvirtd_conf.conf_path) <NEW_LINE> self.libvirtd.restart() | Enable libvirtd log for testcase incase
with the use of param "enable_libvirtd_debug_log",
with additional params log level("libvirtd_debug_level")
and log file path("libvirtd_debug_file") can be controlled. | 62598fb17d43ff2487427434 |
class Actor(models.Model): <NEW_LINE> <INDENT> name = models.CharField('Имя', max_length=100) <NEW_LINE> age = models.PositiveSmallIntegerField('Возраст', default=0) <NEW_LINE> description = models.TextField('Описание') <NEW_LINE> image = models.ImageField('Изображение', upload_to='actors/') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('actor_detail', kwargs={'slug': self.name}) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Актёры и режиссёры' <NEW_LINE> verbose_name_plural = 'Актёры и режиссёры' | Актёры и режиссёры | 62598fb1fff4ab517ebcd849 |
class InvalidGeometryError(ValueError): <NEW_LINE> <INDENT> pass | This geometry is not valid. | 62598fb11b99ca400228f562 |
class TestInlineFuncs(TestCase): <NEW_LINE> <INDENT> def test_nofunc(self): <NEW_LINE> <INDENT> self.assertEqual(inlinefuncs.parse_inlinefunc( "as$382ewrw w we w werw,|44943}"), "as$382ewrw w we w werw,|44943}") <NEW_LINE> <DEDENT> def test_incomplete(self): <NEW_LINE> <INDENT> self.assertEqual(inlinefuncs.parse_inlinefunc( "testing $blah{without an ending."), "testing $blah{without an ending.") <NEW_LINE> <DEDENT> def test_single_func(self): <NEW_LINE> <INDENT> self.assertEqual(inlinefuncs.parse_inlinefunc( "this is a test with $pad(centered, 20) text in it."), "this is a test with centered text in it.") <NEW_LINE> <DEDENT> def test_nested(self): <NEW_LINE> <INDENT> self.assertEqual(inlinefuncs.parse_inlinefunc( "this $crop(is a test with $pad(padded, 20) text in $pad(pad2, 10) a crop, 80)"), "this is a test with padded text in pad2 a crop") <NEW_LINE> <DEDENT> def test_escaped(self): <NEW_LINE> <INDENT> self.assertEqual(inlinefuncs.parse_inlinefunc( "this should be $pad(escaped,''' and '''instead,''' cropped $crop(with a long,5) text., 80)"), "this should be escaped, and instead, cropped with text. ") <NEW_LINE> <DEDENT> def test_escaped2(self): <NEW_LINE> <INDENT> self.assertEqual(inlinefuncs.parse_inlinefunc( 'this should be $pad(escaped,""" and """instead,""" cropped $crop(with a long,5) text., 80)'), "this should be escaped, and instead, cropped with text. ") | Test the nested inlinefunc module | 62598fb163b5f9789fe851cd |
class E5SslCertificatesInfoDialog(QDialog, Ui_E5SslCertificatesInfoDialog): <NEW_LINE> <INDENT> def __init__(self, certificateChain, parent=None): <NEW_LINE> <INDENT> super(E5SslCertificatesInfoDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.sslWidget.showCertificateChain(certificateChain) | Class implementing a dialog to show SSL certificate infos. | 62598fb17b25080760ed7515 |
class TestMatrixExponentiation(unittest.TestCase): <NEW_LINE> <INDENT> def test_matrix_exponentiation(self): <NEW_LINE> <INDENT> mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]] <NEW_LINE> self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 0), [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) <NEW_LINE> self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 1), [[1, 0, 2], [2, 1, 0], [0, 2, 1]]) <NEW_LINE> self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 2), [[1, 4, 4], [4, 1, 4], [4, 4, 1]]) <NEW_LINE> self.assertEqual(matrix_exponentiation.matrix_exponentiation(mat, 5), [[81, 72, 90], [90, 81, 72], [72, 90, 81]]) | [summary]
Test for the file matrix_exponentiation.py
Arguments:
unittest {[type]} -- [description] | 62598fb163d6d428bbee2810 |
class IntegersCompletion(UniqueRepresentation, Parent): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Parent.__init__(self, facade = (ZZ, FiniteEnumeratedSet([-infinity, +infinity])), category = Sets()) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "An example of a facade set: the integers completed by +-infinity" | An example of a facade parent: the set of integers completed with
`+-\infty`
This class illustrates a minimal implementation of a facade parent
that models the union of several other parents.
EXAMPLES::
sage: S = Sets().Facade().example("union"); S
An example of a facade set: the integers completed by +-infinity
TESTS::
sage: TestSuite(S).run(verbose = True)
running ._test_an_element() . . . pass
running ._test_cardinality() . . . pass
running ._test_category() . . . pass
running ._test_construction() . . . pass
running ._test_elements() . . .
Running the test suite of self.an_element()
running ._test_category() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_nonzero_equal() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
pass
running ._test_elements_eq_reflexive() . . . pass
running ._test_elements_eq_symmetric() . . . pass
running ._test_elements_eq_transitive() . . . pass
running ._test_elements_neq() . . . pass
running ._test_eq() . . . pass
running ._test_new() . . . pass
running ._test_not_implemented_methods() . . . pass
running ._test_pickling() . . . pass
running ._test_some_elements() . . . pass | 62598fb1be383301e025385e |
class StreamConnectProjectInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Status = None <NEW_LINE> self.CurrentInputEndpoint = None <NEW_LINE> self.CurrentStartTime = None <NEW_LINE> self.CurrentStopTime = None <NEW_LINE> self.LastStopTime = None <NEW_LINE> self.MainInput = None <NEW_LINE> self.BackupInput = None <NEW_LINE> self.OutputSet = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Status = params.get("Status") <NEW_LINE> self.CurrentInputEndpoint = params.get("CurrentInputEndpoint") <NEW_LINE> self.CurrentStartTime = params.get("CurrentStartTime") <NEW_LINE> self.CurrentStopTime = params.get("CurrentStopTime") <NEW_LINE> self.LastStopTime = params.get("LastStopTime") <NEW_LINE> if params.get("MainInput") is not None: <NEW_LINE> <INDENT> self.MainInput = StreamInputInfo() <NEW_LINE> self.MainInput._deserialize(params.get("MainInput")) <NEW_LINE> <DEDENT> if params.get("BackupInput") is not None: <NEW_LINE> <INDENT> self.BackupInput = StreamInputInfo() <NEW_LINE> self.BackupInput._deserialize(params.get("BackupInput")) <NEW_LINE> <DEDENT> if params.get("OutputSet") is not None: <NEW_LINE> <INDENT> self.OutputSet = [] <NEW_LINE> for item in params.get("OutputSet"): <NEW_LINE> <INDENT> obj = StreamConnectOutputInfo() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.OutputSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> 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)) | 云转推项目信息,包含输入源、输出源、当前转推开始时间等信息。
| 62598fb1a8370b77170f0440 |
class TestBSMP0x2(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.serial = Mock() <NEW_LINE> self.entities = Mock() <NEW_LINE> self.entities.variables = None <NEW_LINE> self.bsmp = BSMP(self.serial, 1, self.entities) <NEW_LINE> <DEDENT> def test_write_variable(self): <NEW_LINE> <INDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> self.bsmp.write_variable(1, 1.5) <NEW_LINE> <DEDENT> <DEDENT> def test_write_group_of_variables(self): <NEW_LINE> <INDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> self.bsmp.write_group_of_variables(2, [2, 3, 5.0]) <NEW_LINE> <DEDENT> <DEDENT> def test_binoperation_variable(self): <NEW_LINE> <INDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> self.bsmp.binoperation_variable(0, 'and', 0xFF) <NEW_LINE> <DEDENT> <DEDENT> def test_binoperation_group(self): <NEW_LINE> <INDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> self.bsmp.binoperation_group(2, 'and', [0xFF, 0xFF]) <NEW_LINE> <DEDENT> <DEDENT> def test_write_and_read_variable(self): <NEW_LINE> <INDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> self.bsmp.write_and_read_variable(0, 1, 10) | Test BSMP write methods. | 62598fb1851cf427c66b8320 |
class GameBoard: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.board = [] <NEW_LINE> self.rooms = [] <NEW_LINE> <DEDENT> def check_reachable_rooms(self, start, move_points) -> list: <NEW_LINE> <INDENT> result_list = [] <NEW_LINE> if isinstance(start, Player) and not start.in_room: <NEW_LINE> <INDENT> for this_room in self.rooms: <NEW_LINE> <INDENT> for this_door in this_room.entrance: <NEW_LINE> <INDENT> distance = abs(start.coordinate[0] - this_door[0]) + abs(start.coordinate[1] - this_door[1]) <NEW_LINE> if distance <= move_points: <NEW_LINE> <INDENT> result_list.append(this_room) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> start = start.in_room <NEW_LINE> for my_door in start.entrance: <NEW_LINE> <INDENT> for this_room in self.rooms: <NEW_LINE> <INDENT> if this_room == start: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for this_door in this_room.entrance: <NEW_LINE> <INDENT> distance = abs(my_door[0] - this_door[0]) + abs(my_door[1] - this_door[1]) <NEW_LINE> if distance <= move_points: <NEW_LINE> <INDENT> if this_room not in result_list: <NEW_LINE> <INDENT> result_list.append(this_room) <NEW_LINE> <DEDENT> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if start == self.rooms[0]: <NEW_LINE> <INDENT> result_list.append(self.rooms[4]) <NEW_LINE> <DEDENT> if start == self.rooms[6]: <NEW_LINE> <INDENT> result_list.append(self.rooms[2]) <NEW_LINE> <DEDENT> if start == self.rooms[4]: <NEW_LINE> <INDENT> result_list.append(self.rooms[0]) <NEW_LINE> <DEDENT> if start == self.rooms[2]: <NEW_LINE> <INDENT> result_list.append(self.rooms[6]) <NEW_LINE> <DEDENT> return result_list <NEW_LINE> <DEDENT> def move_player_to_room(self, player, room): <NEW_LINE> <INDENT> player.in_room = room <NEW_LINE> <DEDENT> def move_player_to_coordinate(self, player, coord): <NEW_LINE> <INDENT> player.coordinate = coord <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> constr = "" <NEW_LINE> for row in self.board: <NEW_LINE> <INDENT> for col in row: <NEW_LINE> <INDENT> if col == 0: <NEW_LINE> <INDENT> constr += "一" <NEW_LINE> <DEDENT> elif col > 500: <NEW_LINE> <INDENT> constr += "墙" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> constr += "口" <NEW_LINE> <DEDENT> <DEDENT> constr += "\n" <NEW_LINE> <DEDENT> return constr <NEW_LINE> <DEDENT> def check_reachable_square(self,start,move_points) -> list: <NEW_LINE> <INDENT> pass | gameboard for players to move on
Where I really need some other brilliant minds to work together on | 62598fb1cc40096d6161a20b |
class PostView(ViewInterface): <NEW_LINE> <INDENT> def __init__(self, win, left, feed): <NEW_LINE> <INDENT> self.LEFT_BOUNDS = left + 3 <NEW_LINE> self.window = win <NEW_LINE> self.RIGHT_BOUNDS = left + (3 * self.window.getmaxyx()[1]) / 6 <NEW_LINE> self.BOTTOM_BOUNDS = self.window.getmaxyx()[0] - 2 <NEW_LINE> self.window.vline(0, self.RIGHT_BOUNDS, curses.ACS_VLINE, self.BOTTOM_BOUNDS) <NEW_LINE> self.window.addstr( 0, ((self.RIGHT_BOUNDS + self.LEFT_BOUNDS) / 2) - 3, "Posts") <NEW_LINE> self.window.hline(1, self.LEFT_BOUNDS, curses.ACS_HLINE, self.RIGHT_BOUNDS - self.LEFT_BOUNDS) <NEW_LINE> self.posts = feed <NEW_LINE> self.currentFeed = [] <NEW_LINE> self.index = 0 <NEW_LINE> <DEDENT> def getCurrentFeed(self, index): <NEW_LINE> <INDENT> for post in self.posts[index]: <NEW_LINE> <INDENT> self.currentFeed.append(post) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def switch(self, feed): <NEW_LINE> <INDENT> self.updatePost(feed) <NEW_LINE> <DEDENT> def clearScreen(self): <NEW_LINE> <INDENT> self.window.move(2, self.LEFT_BOUNDS) <NEW_LINE> self.window.cleartoeol() <NEW_LINE> <DEDENT> def updatePost(self, feed): <NEW_LINE> <INDENT> oldPos = self.window.getyx()[0] <NEW_LINE> STARTING_POS = 2 <NEW_LINE> for post in feed: <NEW_LINE> <INDENT> if STARTING_POS + 1 > self.BOTTOM_BOUNDS: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.window.addnstr(STARTING_POS, self.LEFT_BOUNDS, post, self.RIGHT_BOUNDS - self.LEFT_BOUNDS) <NEW_LINE> STARTING_POS += 1 <NEW_LINE> <DEDENT> <DEDENT> def displayPost(self, feed): <NEW_LINE> <INDENT> oldPos = self.window.getyx()[0] <NEW_LINE> STARTING_POS = 2 <NEW_LINE> for post in feed: <NEW_LINE> <INDENT> if STARTING_POS + 1 > self.BOTTOM_BOUNDS: <NEW_LINE> <INDENT> self.window.move(oldPos, 0) <NEW_LINE> return <NEW_LINE> <DEDENT> self.window.addnstr(STARTING_POS, self.LEFT_BOUNDS, post, self.RIGHT_BOUNDS - self.LEFT_BOUNDS) <NEW_LINE> STARTING_POS += 1 <NEW_LINE> <DEDENT> self.window.move(oldPos, 0) | docstring for PostView | 62598fb1e5267d203ee6b96d |
class SavedText: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.text_versions = [] <NEW_LINE> <DEDENT> def save_text(self, text: Text): <NEW_LINE> <INDENT> self.text_versions.append(deepcopy(text)) <NEW_LINE> <DEDENT> def get_version(self, number: int) -> Text: <NEW_LINE> <INDENT> return self.text_versions[number] | Control the Text versions and save them | 62598fb1a8370b77170f0441 |
class FileStorage: <NEW_LINE> <INDENT> __file_path = "file.json" <NEW_LINE> __objects = {} <NEW_LINE> def all(self, cls=None): <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> if cls is None: <NEW_LINE> <INDENT> return self.__objects <NEW_LINE> <DEDENT> if cls != "": <NEW_LINE> <INDENT> if isinstance(cls, str) is False: <NEW_LINE> <INDENT> cls = cls.__name__ <NEW_LINE> <DEDENT> for k, v in self.__objects.items(): <NEW_LINE> <INDENT> if cls == k.split(".")[0]: <NEW_LINE> <INDENT> new_dict[k] = v <NEW_LINE> <DEDENT> <DEDENT> return new_dict <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__objects <NEW_LINE> <DEDENT> <DEDENT> def new(self, obj): <NEW_LINE> <INDENT> key = str(obj.__class__.__name__) + "." + str(obj.id) <NEW_LINE> value_dict = obj <NEW_LINE> FileStorage.__objects[key] = value_dict <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> objects_dict = {} <NEW_LINE> for key, val in FileStorage.__objects.items(): <NEW_LINE> <INDENT> objects_dict[key] = val.to_dict() <NEW_LINE> <DEDENT> with open(FileStorage.__file_path, mode='w', encoding="UTF8") as fd: <NEW_LINE> <INDENT> json.dump(objects_dict, fd) <NEW_LINE> <DEDENT> <DEDENT> def reload(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(FileStorage.__file_path, encoding="UTF8") as fd: <NEW_LINE> <INDENT> FileStorage.__objects = json.load(fd) <NEW_LINE> <DEDENT> for key, val in FileStorage.__objects.items(): <NEW_LINE> <INDENT> class_name = val["__class__"] <NEW_LINE> class_name = models.classes[class_name] <NEW_LINE> FileStorage.__objects[key] = class_name(**val) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def delete(self, obj=None): <NEW_LINE> <INDENT> if obj is not None: <NEW_LINE> <INDENT> key = str(obj.__class__.__name__) + "." + str(obj.id) <NEW_LINE> FileStorage.__objects.pop(key, None) <NEW_LINE> self.save() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.reload() | Serializes instances to JSON file and deserializes to JSON file. | 62598fb14f88993c371f053d |
class CBUSH2D(BushElement): <NEW_LINE> <INDENT> type = 'CBUSH2D' <NEW_LINE> def __init__(self, card=None, data=None): <NEW_LINE> <INDENT> BushElement.__init__(self, card, data) <NEW_LINE> if card: <NEW_LINE> <INDENT> self.eid = int(card.field(1)) <NEW_LINE> self.pid = int(card.field(2)) <NEW_LINE> nids = card.fields(3, 5) <NEW_LINE> self.cid = int(card.field(5)) <NEW_LINE> self.plane = card.field(6, 'XY') <NEW_LINE> self.sptid = card.field(7) <NEW_LINE> if self.plane not in ['XY', 'YZ', 'ZX']: <NEW_LINE> <INDENT> msg = 'plane not in required list, plane=|%s|\n' % (self.plane) <NEW_LINE> msg += "expected planes = ['XY','YZ','ZX']" <NEW_LINE> raise RuntimeError(msg) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.eid = data[0] <NEW_LINE> self.pid = data[1] <NEW_LINE> nids = data[2:4] <NEW_LINE> <DEDENT> self.prepareNodeIDs(nids) <NEW_LINE> assert len(self.nodes) == 2 <NEW_LINE> <DEDENT> def rawFields(self): <NEW_LINE> <INDENT> nodeIDs = self.nodeIDs() <NEW_LINE> fields = ['CBUSH1D', self.eid, self.Pid(), nodeIDs[0], nodeIDs[0], self.Cid(), self.plane, self.sptid] <NEW_LINE> return fields <NEW_LINE> <DEDENT> def cross_reference(self, model): <NEW_LINE> <INDENT> self.nodes = model.Nodes(self.nodes) <NEW_LINE> self.cid = model.Coord(self.cid) | 2-D Linear-Nonlinear Connection
Defines the connectivity of a two-dimensional Linear-Nonlinear element. | 62598fb199cbb53fe6830f3e |
class FederationGroupsJoinServlet(BaseGroupsServerServlet): <NEW_LINE> <INDENT> PATH = "/groups/(?P<group_id>[^/]*)/users/(?P<user_id>[^/]*)/join" <NEW_LINE> async def on_POST( self, origin: str, content: JsonDict, query: Dict[bytes, List[bytes]], group_id: str, user_id: str, ) -> Tuple[int, JsonDict]: <NEW_LINE> <INDENT> if get_domain_from_id(user_id) != origin: <NEW_LINE> <INDENT> raise SynapseError(403, "user_id doesn't match origin") <NEW_LINE> <DEDENT> new_content = await self.handler.join_group(group_id, user_id, content) <NEW_LINE> return 200, new_content | Attempt to join a group | 62598fb171ff763f4b5e77d7 |
class DataMessage(messages.AsyncMessage): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> AsyncMessage.__init__(self, **kwargs) <NEW_LINE> self.identity = kwargs.pop('identity', None) <NEW_LINE> self.operation = kwargs.pop('operation', None) | This message is used to transport an operation that occured on a managed
object or collection.
This class of message is transmitted between clients subscribed to a
remote destination as well as between server nodes within a cluster.
The payload of this message describes all of the relevant details of
the operation. This information is used to replicate updates and detect
conflicts.
:ivar identity: Provides access to the identity map which defines the
unique identity of the item affected by this `DataMessage`
(relevant for create/update/delete but not fill operations).
:ivar operation: Provides access to the operation/command of this
`DataMessage`. Operations indicate how the remote destination should
process this message.
.. seealso:: `DataMessage on Livedocs
<http://livedocs.adobe.com/flex/201/langref/mx/data/messages/DataMessage.html>`_ | 62598fb14428ac0f6e65858b |
class SOAP_Service(object): <NEW_LINE> <INDENT> def __init__(self, service): <NEW_LINE> <INDENT> self.service = service <NEW_LINE> <DEDENT> def serialize(self, response): <NEW_LINE> <INDENT> return serialize_object(response) | Base SOAP Service to bootstrap a service | 62598fb199fddb7c1ca62e1c |
class Base: <NEW_LINE> <INDENT> SETTINGS = [ "path_to_executable", "mandatory_options", "common_options" ] <NEW_LINE> HAS_COLUMN_INFO = re.compile('^[^:]+:\d+:\d+:') <NEW_LINE> def __init__(self, settings, view): <NEW_LINE> <INDENT> self.settings = settings <NEW_LINE> for setting_name in self.__class__.SETTINGS: <NEW_LINE> <INDENT> setting_value = view.settings().get(self._full_settings_name(setting_name), self.settings.get(self._full_settings_name(setting_name), '')) <NEW_LINE> if sys.version < '3': <NEW_LINE> <INDENT> setting_value = setting_value.encode() <NEW_LINE> <DEDENT> setattr(self, setting_name, setting_value) <NEW_LINE> <DEDENT> if os.name=='nt': <NEW_LINE> <INDENT> self._resolve_windows_path_to_executable() <NEW_LINE> <DEDENT> <DEDENT> def run(self, query, folders): <NEW_LINE> <INDENT> arguments = self._arguments(query, folders) <NEW_LINE> print("Running: %s" % " ".join(arguments)) <NEW_LINE> try: <NEW_LINE> <INDENT> startupinfo = None <NEW_LINE> if os.name == 'nt': <NEW_LINE> <INDENT> startupinfo = subprocess.STARTUPINFO() <NEW_LINE> startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW <NEW_LINE> <DEDENT> pipe = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=folders[0], startupinfo=startupinfo ) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> raise RuntimeError("Could not find executable %s" % self.path_to_executable) <NEW_LINE> <DEDENT> output, error = pipe.communicate() <NEW_LINE> if self._is_search_error(pipe.returncode, output, error): <NEW_LINE> <INDENT> raise RuntimeError(self._sanitize_output(error)) <NEW_LINE> <DEDENT> return self._parse_output(self._sanitize_output(output)) <NEW_LINE> <DEDENT> def _arguments(self, query, folders): <NEW_LINE> <INDENT> return ( [self.path_to_executable] + shlex.split(self.mandatory_options) + shlex.split(self.common_options) + [query] + folders) <NEW_LINE> <DEDENT> def _sanitize_output(self, output): <NEW_LINE> <INDENT> return output.decode('utf-8', 'ignore').strip() <NEW_LINE> <DEDENT> def _parse_output(self, output): <NEW_LINE> <INDENT> lines = output.split("\n") <NEW_LINE> line_parts = [line.split(":", 3) if Base.HAS_COLUMN_INFO.match(line) else line.split(":", 2) for line in lines] <NEW_LINE> line_parts = self._filter_lines_without_matches(line_parts) <NEW_LINE> return [(":".join(line[0:-1]), line[-1].strip()) for line in line_parts] <NEW_LINE> <DEDENT> def _is_search_error(self, returncode, output, error): <NEW_LINE> <INDENT> returncode != 0 <NEW_LINE> <DEDENT> def _full_settings_name(self, name): <NEW_LINE> <INDENT> return "search_in_project_%s_%s" % (self.__class__.__name__, name) <NEW_LINE> <DEDENT> def _filter_lines_without_matches(self, line_parts): <NEW_LINE> <INDENT> return filter(lambda line: len(line) > 2, line_parts) <NEW_LINE> <DEDENT> def _resolve_windows_path_to_executable(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> startupinfo = subprocess.STARTUPINFO() <NEW_LINE> startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW <NEW_LINE> self.path_to_executable = self._sanitize_output(subprocess.check_output("where %s" % self.path_to_executable, startupinfo=startupinfo)) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except sys.FileNotFoundError: <NEW_LINE> <INDENT> pass | This is the base search engine class.
Override it to define new search engines. | 62598fb14527f215b58e9f3a |
class Token(collections.namedtuple('_Token', 'num val')): <NEW_LINE> <INDENT> pass | Represents a single Token.
Attributes:
num: The token type as per the tokenize module.
val: The token value as per the tokenize module. | 62598fb185dfad0860cbfaa6 |
class Data_ERROR(Base): <NEW_LINE> <INDENT> name = "error" <NEW_LINE> def __init__(self, request=False, body = b'', cmd=CMD_ERROR, sub_cmd=CMD_ERROR, msg = '', msg_type = MSG_TYPE_STR): <NEW_LINE> <INDENT> self.cmd = cmd <NEW_LINE> self.sub_cmd = sub_cmd <NEW_LINE> self.msg = msg <NEW_LINE> self.msg_type = msg_type <NEW_LINE> super().__init__(request, body=body) <NEW_LINE> <DEDENT> def decode(self, body): <NEW_LINE> <INDENT> self.cmd = body[0] <NEW_LINE> self.sub_cmd = body[1] <NEW_LINE> self.msg_type = body[2] <NEW_LINE> if self.msg_type == MSG_TYPE_STR: <NEW_LINE> <INDENT> self.msg = body[3:].decode("utf-8") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.msg = body[3:] <NEW_LINE> <DEDENT> <DEDENT> def encode(self): <NEW_LINE> <INDENT> body = bytes([self.cmd, self.sub_cmd]) <NEW_LINE> if self.msg: <NEW_LINE> <INDENT> if self.msg_type == MSG_TYPE_RAW: <NEW_LINE> <INDENT> body += bytes([MSG_TYPE_RAW]) <NEW_LINE> body += self.msg <NEW_LINE> <DEDENT> elif self.msg_type == MSG_TYPE_STR: <NEW_LINE> <INDENT> body += bytes([MSG_TYPE_STR]) <NEW_LINE> body += self.msg.encode("utf-8") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> body += bytes([MSG_TYPE_RAW]) <NEW_LINE> <DEDENT> return body <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> ret = { "type": self.name, "msg": str(self.msg) if self.msg else "", "cmd": self.cmd, "sub_cmd": self.sub_cmd } <NEW_LINE> return json.dumps(ret, ensure_ascii=False) | response
| cmd(1B) | sub_cmd(1B) | msg_type(1B) | msg | | 62598fb155399d3f05626580 |
class Display(): <NEW_LINE> <INDENT> def __init__(self,on_page=None,on_poll=None,on_tick=None,on_refresh=None): <NEW_LINE> <INDENT> self.ser = serial.Serial('/dev/ttyAMA0',115200,timeout=0.1) <NEW_LINE> self.on_page = on_page <NEW_LINE> self.on_poll = on_poll <NEW_LINE> self.on_tick = on_tick <NEW_LINE> self.on_refresh = on_refresh <NEW_LINE> self.page = 'a' <NEW_LINE> self.poll = POLL_TICKS <NEW_LINE> self.refresh = REFRESH_TICKS <NEW_LINE> <DEDENT> def position_cursor(self,line,column): <NEW_LINE> <INDENT> self.ser.write(ESC+'P'+chr(line)+chr(column)) <NEW_LINE> <DEDENT> def scroll_down(self): <NEW_LINE> <INDENT> self.ser.write(ESC+'O'+chr(0)) <NEW_LINE> <DEDENT> def window_home(self): <NEW_LINE> <INDENT> self.ser.write(ESC+'G'+chr(1)) <NEW_LINE> <DEDENT> def capped_bar(self, length, percent): <NEW_LINE> <INDENT> self.ser.write(ESC+'b'+chr(length)+chr(percent)) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.ser.write(CLEAR) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> display.ser.write(' Starting.... ') <NEW_LINE> if self.on_page != None: <NEW_LINE> <INDENT> self.on_page() <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> key = str(self.ser.read(1)) <NEW_LINE> if key != '' and key in 'abcd': <NEW_LINE> <INDENT> self.page = key <NEW_LINE> self.refresh = REFRESH_TICKS <NEW_LINE> self.poll = POLL_TICKS <NEW_LINE> if self.on_page != None: <NEW_LINE> <INDENT> self.on_page() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.refresh-=1 <NEW_LINE> if self.refresh == 0: <NEW_LINE> <INDENT> self.refresh = REFRESH_TICKS <NEW_LINE> if self.on_refresh != None: <NEW_LINE> <INDENT> self.on_refresh() <NEW_LINE> <DEDENT> <DEDENT> self.poll-=1 <NEW_LINE> if self.poll == 0: <NEW_LINE> <INDENT> self.poll = POLL_TICKS <NEW_LINE> if self.on_poll != None: <NEW_LINE> <INDENT> self.on_poll() <NEW_LINE> <DEDENT> <DEDENT> if self.on_tick != None: <NEW_LINE> <INDENT> self.on_tick() | Manages the 16x2 4 button display:
on_tick called every 0.1 seconds as part of the main loop after the button read
on_poll called every 1.5 seconds
on_page called when a new page has been selected
on_refresh called every 30 seconds | 62598fb157b8e32f5250814e |
class Person: <NEW_LINE> <INDENT> def __init__(self, name, age, pay=0, job=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> self.pay = pay <NEW_LINE> self.job = job <NEW_LINE> <DEDENT> def lastName(self): <NEW_LINE> <INDENT> return self.name.split()[-1] <NEW_LINE> <DEDENT> def giveRaise(self, percent): <NEW_LINE> <INDENT> self.pay *= (1.0 + percent) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('<%s => %s: %s,%s>' % (self.__class__.__name__, self.name, self.job, self.pay)) | 一般perosn: 数据+逻辑 | 62598fb1adb09d7d5dc0a5f0 |
class TimeRestriction(models.Model): <NEW_LINE> <INDENT> _name = 'hr_time_labour.time_restriction' <NEW_LINE> _description = 'Shift Time Restriction' <NEW_LINE> name = fields.Char('Restriction Name') <NEW_LINE> code = fields.Char('Restriction Code') <NEW_LINE> description = fields.Text('Description') <NEW_LINE> active = fields.Boolean('Active') <NEW_LINE> effective_date = fields.Date('Effective Date') <NEW_LINE> early_in = fields.Float('Early In') <NEW_LINE> late_in = fields.Float('Late In') <NEW_LINE> early_meal = fields.Float('Early Meal') <NEW_LINE> late_meal = fields.Float('Late Meal') <NEW_LINE> early_out = fields.Float('Early Out') <NEW_LINE> late_out = fields.Float('Late Out') | Restriction punch type | 62598fb160cbc95b063643b6 |
class VirtualHostCollection(roots.Homogenous): <NEW_LINE> <INDENT> entityType = resource.Resource <NEW_LINE> def __init__(self, nvh): <NEW_LINE> <INDENT> self.nvh = nvh <NEW_LINE> <DEDENT> def listStaticEntities(self): <NEW_LINE> <INDENT> return self.nvh.hosts.items() <NEW_LINE> <DEDENT> def getStaticEntity(self, name): <NEW_LINE> <INDENT> return self.nvh.hosts.get(self) <NEW_LINE> <DEDENT> def reallyPutEntity(self, name, entity): <NEW_LINE> <INDENT> self.nvh.addHost(name, entity) <NEW_LINE> <DEDENT> def delEntity(self, name): <NEW_LINE> <INDENT> self.nvh.removeHost(name) | Wrapper for virtual hosts collection.
This exists for configuration purposes. | 62598fb138b623060ffa9102 |
class _Float4x4Element(_XML3DElement): <NEW_LINE> <INDENT> _name = None <NEW_LINE> def __init__(self, doc_, id_, name_): <NEW_LINE> <INDENT> _XML3DElement.__init__(self, doc_, "float4x4", id_) <NEW_LINE> self._name = name_ <NEW_LINE> if not (self._name == None): <NEW_LINE> <INDENT> self.setAttribute("name", self._name) <NEW_LINE> <DEDENT> <DEDENT> def setName(self, value): <NEW_LINE> <INDENT> self._name = value <NEW_LINE> self.setAttribute("name", self._name) <NEW_LINE> return <NEW_LINE> <DEDENT> def setValue(self, value): <NEW_LINE> <INDENT> self.appendChild(self.ownerDocument.createTextNode(value)) | A float4x4 Element | 62598fb1442bda511e95c4bf |
class XYInspector(BaseTool): <NEW_LINE> <INDENT> new_value = Event <NEW_LINE> visible = Bool(True) <NEW_LINE> last_mouse_position = Tuple <NEW_LINE> inspector_key = KeySpec('p') <NEW_LINE> _old_visible = Enum(None, True, False) <NEW_LINE> def normal_key_pressed(self, event): <NEW_LINE> <INDENT> if self.inspector_key.match(event): <NEW_LINE> <INDENT> self.visible = not self.visible <NEW_LINE> event.handled = True <NEW_LINE> <DEDENT> <DEDENT> def normal_mouse_leave(self, event): <NEW_LINE> <INDENT> if self._old_visible is None: <NEW_LINE> <INDENT> self._old_visible = self.visible <NEW_LINE> self.visible = False <NEW_LINE> <DEDENT> <DEDENT> def normal_mouse_enter(self, event): <NEW_LINE> <INDENT> if self._old_visible is not None: <NEW_LINE> <INDENT> self.visible = self._old_visible <NEW_LINE> self._old_visible = None <NEW_LINE> <DEDENT> <DEDENT> def normal_mouse_move(self, event): <NEW_LINE> <INDENT> plot = self.component <NEW_LINE> if plot is not None: <NEW_LINE> <INDENT> pos = plot.map_data((event.x, event.y), all_values=True) <NEW_LINE> self.new_value = dict(pos=pos) | A tool that captures the color and underlying values of an image plot.
| 62598fb1f548e778e596b60a |
class ZincArtifactState(object): <NEW_LINE> <INDENT> def __init__(self, artifact): <NEW_LINE> <INDENT> self.artifact = artifact <NEW_LINE> relfile = self.artifact.relations_file <NEW_LINE> self.analysis_fprint = ZincArtifactState._fprint_file(relfile) if os.path.exists(relfile) else None <NEW_LINE> self.classes_by_src = ZincArtifactState._compute_classes_by_src(self.artifact) <NEW_LINE> self.classes_by_target = ZincArtifactState._compute_classes_by_target(self.classes_by_src, self.artifact.sources_by_target) <NEW_LINE> self.classes = set() <NEW_LINE> for classes in self.classes_by_src.values(): <NEW_LINE> <INDENT> self.classes.update(classes) <NEW_LINE> <DEDENT> self.timestamp = time.time() <NEW_LINE> <DEDENT> def find_filesystem_classes(self): <NEW_LINE> <INDENT> return ZincArtifactState._find_filesystem_classes(self.artifact) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _fprint_file(path): <NEW_LINE> <INDENT> hasher = hashlib.md5() <NEW_LINE> with open(path, 'r') as f: <NEW_LINE> <INDENT> hasher.update(f.read()) <NEW_LINE> <DEDENT> return hasher.hexdigest() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _compute_classes_by_src(artifact): <NEW_LINE> <INDENT> if not os.path.exists(artifact.analysis_file): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> len_rel_classes_dir = len(artifact.classes_dir) - len(get_buildroot()) <NEW_LINE> analysis = ZincAnalysisCollection(stop_after=ZincAnalysisCollection.PRODUCTS) <NEW_LINE> analysis.add_and_parse_file(artifact.analysis_file, artifact.classes_dir) <NEW_LINE> classes_by_src = {} <NEW_LINE> for src, classes in analysis.products.items(): <NEW_LINE> <INDENT> classes_by_src[src] = [cls[len_rel_classes_dir:] for cls in classes] <NEW_LINE> <DEDENT> return classes_by_src <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _compute_classes_by_target(classes_by_src, srcs_by_target): <NEW_LINE> <INDENT> classes_by_target = defaultdict(set) <NEW_LINE> for target, srcs in srcs_by_target.items(): <NEW_LINE> <INDENT> for src in srcs: <NEW_LINE> <INDENT> classes_by_target[target].update(classes_by_src.get(src, [])) <NEW_LINE> <DEDENT> <DEDENT> return classes_by_target <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _find_filesystem_classes(artifact): <NEW_LINE> <INDENT> classes = [] <NEW_LINE> classes_dir_prefix_len = len(artifact.classes_dir) + 1 <NEW_LINE> for (dirpath, _, filenames) in os.walk(artifact.classes_dir, followlinks=False): <NEW_LINE> <INDENT> for f in filenames: <NEW_LINE> <INDENT> classes.append(os.path.join(dirpath, f)[classes_dir_prefix_len:]) <NEW_LINE> <DEDENT> <DEDENT> return classes | The current state of a zinc artifact. | 62598fb15fcc89381b26617f |
class MarkerSize(Formatoption): <NEW_LINE> <INDENT> connections = ['plot'] <NEW_LINE> priority = BEFOREPLOTTING <NEW_LINE> def update(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self.plot._kwargs.pop('markersize', None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.plot._kwargs['markersize'] = value | Choose the size of the markers for points
Possible types
--------------
None
Use the default from matplotlibs rcParams
float
The size of the marker | 62598fb1d268445f26639bb6 |
class Console(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.required=[] <NEW_LINE> self.b_key = "console" <NEW_LINE> self.a10_url="/axapi/v3/authentication/console" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.type_cfg = {} <NEW_LINE> self.uuid = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | Class Description::
Configure console authentication type.
Class console supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/authentication/console`. | 62598fb10c0af96317c563e2 |
class Voronoi_probabilistic_algorithm: <NEW_LINE> <INDENT> def __init__(self, parameters): <NEW_LINE> <INDENT> self.parameters = parameters <NEW_LINE> self.dimensions = None <NEW_LINE> <DEDENT> def _run(self, data, weigths, dict_data_indexes): <NEW_LINE> <INDENT> print("data len : "+ str(len(data))) <NEW_LINE> return _merge(data, weigths, self.parameters, dict_data_indexes) | Main algorithm. Parameters is Voronoi_probabilistic_algorithm_parameters | 62598fb14a966d76dd5eef3d |
class CardsDirective(InsertInputDirective): <NEW_LINE> <INDENT> required_arguments = 0 <NEW_LINE> final_argument_whitespace = True <NEW_LINE> def get_rst(self): <NEW_LINE> <INDENT> cellsep = '<NEXTCARD>' <NEW_LINE> rowsep = '<NEXTROW>' <NEW_LINE> rows = [] <NEW_LINE> content = '\n'.join(self.content) <NEW_LINE> for row in content.split(rowsep): <NEW_LINE> <INDENT> cells = [cell.strip() for cell in row.split(cellsep)] <NEW_LINE> col_class = card_class_map[len(cells)] <NEW_LINE> rows.append([col_class, cells]) <NEW_LINE> <DEDENT> tpl = JINJA_ENV.from_string(container_tpl) <NEW_LINE> s = tpl.render(rows=rows) <NEW_LINE> return s | Defines the :rst:dir:`cards` directive. | 62598fb132920d7e50bc60ba |
class TestFeatureValueListResponse1(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 testFeatureValueListResponse1(self): <NEW_LINE> <INDENT> model = kinow_client.models.feature_value_list_response_1.FeatureValueListResponse1() | FeatureValueListResponse1 unit test stubs | 62598fb121bff66bcd722ccd |
class BoolType(FieldType): <NEW_LINE> <INDENT> def __init__(self ,default=False): <NEW_LINE> <INDENT> self.default = default <NEW_LINE> <DEDENT> def check(self, field_value=None): <NEW_LINE> <INDENT> if field_value is None: <NEW_LINE> <INDENT> return self.default <NEW_LINE> <DEDENT> return bool(field_value) | True or False. Default if False. | 62598fb13d592f4c4edbaf27 |
class DefaultBranchProtection(enum.Enum): <NEW_LINE> <INDENT> NONE = 0 <NEW_LINE> PARTIAL = 1 <NEW_LINE> FULL = 2 | Default branch protection values, see
https://docs.gitlab.com/ee/api/groups.html#options-for-default_branch_protection | 62598fb123849d37ff85111a |
class ShortTermUFValues(PyObserver, ql.SimpleQuote): <NEW_LINE> <INDENT> def __init__(self, dates, prices): <NEW_LINE> <INDENT> PyObserver.__init__(self) <NEW_LINE> ql.SimpleQuote.__init__(self, 0) <NEW_LINE> self.dates = dates <NEW_LINE> self.prices = prices <NEW_LINE> self.fn = self.buildUfFwd <NEW_LINE> self.exc = 0 <NEW_LINE> self.registerCurveWithQuotes() <NEW_LINE> self.buildUfFwd() <NEW_LINE> <DEDENT> def notifyObservers(self): <NEW_LINE> <INDENT> tmp = self.value() <NEW_LINE> self.setValue(tmp + 1) <NEW_LINE> <DEDENT> def registerCurveWithQuotes(self): <NEW_LINE> <INDENT> for i in self.prices: <NEW_LINE> <INDENT> self.registerWith(i) <NEW_LINE> <DEDENT> <DEDENT> def buildUfFwd(self): <NEW_LINE> <INDENT> ipc = [] <NEW_LINE> adj_uf = [self.prices[0].value()] <NEW_LINE> contract_dates = [] <NEW_LINE> period_dates = [self.dates[0]] <NEW_LINE> proy_uf = [] <NEW_LINE> period_days = [] <NEW_LINE> proy_uf = [self.prices[0].value()] <NEW_LINE> for i in range(len(self.prices)-1): <NEW_LINE> <INDENT> start_period = ql.Date(9,self.dates[i].month(),self.dates[i].year()) <NEW_LINE> next_period = ql.Date(9,self.dates[i+1].month(),self.dates[i+1].year()) <NEW_LINE> next_contract_period = self.dates[i+1] <NEW_LINE> if i == 0: <NEW_LINE> <INDENT> start_contract_period = self.dates[i] <NEW_LINE> dt = (next_period-start_period)/(next_contract_period - start_contract_period) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_contract_period = start_period <NEW_LINE> dt = (next_period-start_period)/(next_contract_period - start_contract_period) <NEW_LINE> adj_uf.append(adj_uf[-1]*(1+ipc[-1])) <NEW_LINE> <DEDENT> ipc.append((self.prices[i+1].value()/adj_uf[i])**(dt)-1) <NEW_LINE> period_days.append(next_period-start_period) <NEW_LINE> contract_dates.append(start_contract_period) <NEW_LINE> period_dates.append(next_period) <NEW_LINE> <DEDENT> self.uf_dict = {} <NEW_LINE> final_dates = self.dates[0] <NEW_LINE> total_days = period_dates[-1] - period_dates[0] <NEW_LINE> counter = 0 <NEW_LINE> j = 0 <NEW_LINE> for i in range(total_days): <NEW_LINE> <INDENT> final_dates += 1 <NEW_LINE> counter += 1 <NEW_LINE> if counter > period_days[j]: <NEW_LINE> <INDENT> counter = 1 <NEW_LINE> j += 1 <NEW_LINE> <DEDENT> next_uf = proy_uf[-1]*(1+ipc[j])**(1/period_days[j]) <NEW_LINE> proy_uf.append(next_uf) <NEW_LINE> self.uf_dict[final_dates] = next_uf <NEW_LINE> <DEDENT> self.uf_dict = OrderedDict(self.uf_dict) <NEW_LINE> self.notifyObservers() <NEW_LINE> <DEDENT> def showUfs(self): <NEW_LINE> <INDENT> print('Date','Value') <NEW_LINE> for k, v in self.uf_dict.items(): <NEW_LINE> <INDENT> if k.dayOfMonth() == 9: <NEW_LINE> <INDENT> print(k, round(v,4)) | Recieves an evaluation date, UF FWD contract dates -as QL Date Object-
and UF prices -as QL Simple Quote Objects-. The ShortTermUFValues object inherits
from the SimpleQuote SWIG class to simulate the ql.Observeable interface,
which is not avaible for Python. | 62598fb15fc7496912d482b1 |
class DingzNoDataAvailable(DingzError): <NEW_LINE> <INDENT> pass | When no data is available. | 62598fb14527f215b58e9f3b |
class MapPythonExportedSymbols(Task): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def product_types(cls): <NEW_LINE> <INDENT> return [ 'python_source_to_exported_symbols', ] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def prepare(cls, options, round_manager): <NEW_LINE> <INDENT> round_manager.require_data('python') <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> python_source_to_exported_symbols = defaultdict(set) <NEW_LINE> for target in self.context.build_graph.targets(lambda t: isinstance(t, PythonTarget)): <NEW_LINE> <INDENT> for source_candidate in target.sources_relative_to_source_root(): <NEW_LINE> <INDENT> source_root_relative_dir = P.dirname(source_candidate) <NEW_LINE> if P.basename(source_candidate) == '__init__.py': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if P.splitext(source_candidate)[1] == '.py': <NEW_LINE> <INDENT> terminal_symbol = P.basename(source_candidate)[:-len('.py')] <NEW_LINE> prefix_symbol = source_root_relative_dir.replace('/', '.') <NEW_LINE> fq_symbol = '.'.join([prefix_symbol, terminal_symbol]) <NEW_LINE> source_relative_to_buildroot = P.join(target.target_base, source_candidate) <NEW_LINE> python_source_to_exported_symbols[source_relative_to_buildroot].update([fq_symbol]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.context.products.safe_create_data( 'python_source_to_exported_symbols', lambda: python_source_to_exported_symbols, ) | A naive map of python sources to the symbols they export.
We just assume that each python source file represents a single symbol
defined by the directory structure (from the source root) and terminating in the name of the
file with '.py' stripped off. | 62598fb199fddb7c1ca62e1d |
class OutOfRetries(exceptions.HomeAssistantError): <NEW_LINE> <INDENT> pass | Error to indicate too many error attempts. | 62598fb1bf627c535bcb1506 |
class PagesController(BaseAPIController, SharableItemSecurityMixin, UsesAnnotations, SharableMixin): <NEW_LINE> <INDENT> def __init__(self, app): <NEW_LINE> <INDENT> super(PagesController, self).__init__(app) <NEW_LINE> self.manager = PageManager(app) <NEW_LINE> self.serializer = PageSerializer(app) <NEW_LINE> <DEDENT> @expose_api <NEW_LINE> def index(self, trans, deleted=False, **kwd): <NEW_LINE> <INDENT> out = [] <NEW_LINE> if trans.user_is_admin: <NEW_LINE> <INDENT> r = trans.sa_session.query(trans.app.model.Page) <NEW_LINE> if not deleted: <NEW_LINE> <INDENT> r = r.filter_by(deleted=False) <NEW_LINE> <DEDENT> for row in r: <NEW_LINE> <INDENT> out.append(self.encode_all_ids(trans, row.to_dict(), True)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> user = trans.get_user() <NEW_LINE> r = trans.sa_session.query(trans.app.model.Page).filter_by(user=user) <NEW_LINE> if not deleted: <NEW_LINE> <INDENT> r = r.filter_by(deleted=False) <NEW_LINE> <DEDENT> for row in r: <NEW_LINE> <INDENT> out.append(self.encode_all_ids(trans, row.to_dict(), True)) <NEW_LINE> <DEDENT> r = trans.sa_session.query(trans.app.model.Page).filter(trans.app.model.Page.user != user).filter_by(published=True) <NEW_LINE> if not deleted: <NEW_LINE> <INDENT> r = r.filter_by(deleted=False) <NEW_LINE> <DEDENT> for row in r: <NEW_LINE> <INDENT> out.append(self.encode_all_ids(trans, row.to_dict(), True)) <NEW_LINE> <DEDENT> <DEDENT> return out <NEW_LINE> <DEDENT> @expose_api <NEW_LINE> def create(self, trans, payload, **kwd): <NEW_LINE> <INDENT> page = self.manager.create(trans, payload) <NEW_LINE> rval = self.encode_all_ids(trans, page.to_dict(), True) <NEW_LINE> rval['content'] = page.latest_revision.content <NEW_LINE> self.manager.rewrite_content_for_export(trans, rval) <NEW_LINE> return rval <NEW_LINE> <DEDENT> @expose_api <NEW_LINE> def delete(self, trans, id, **kwd): <NEW_LINE> <INDENT> page = get_object(trans, id, 'Page', check_ownership=True) <NEW_LINE> page.deleted = True <NEW_LINE> trans.sa_session.flush() <NEW_LINE> return '' <NEW_LINE> <DEDENT> @expose_api <NEW_LINE> def show(self, trans, id, **kwd): <NEW_LINE> <INDENT> page = get_object(trans, id, 'Page', check_ownership=False, check_accessible=True) <NEW_LINE> rval = self.encode_all_ids(trans, page.to_dict(), True) <NEW_LINE> rval['content'] = page.latest_revision.content <NEW_LINE> self.manager.rewrite_content_for_export(trans, rval) <NEW_LINE> return rval | RESTful controller for interactions with pages. | 62598fb18e7ae83300ee910a |
class SphinxParallelError(SphinxError): <NEW_LINE> <INDENT> category = 'Sphinx parallel build error' <NEW_LINE> def __init__(self, message: str, traceback: Any) -> None: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.traceback = traceback <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return self.message | Sphinx parallel build error. | 62598fb15fdd1c0f98e5dff4 |
class Movie(): <NEW_LINE> <INDENT> VALID_RATINGS = ["G", "PG", "PG-13", "R"] <NEW_LINE> def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline=movie_storyline <NEW_LINE> self.poster_image_url=poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self): <NEW_LINE> <INDENT> webbrowser.open(self.trailer_youtube_url) | This Class provides a way to store movie related information | 62598fb1f9cc0f698b1c52fe |
class TestUserContactMethodsApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = victorops_client.apis.user_contact_methods_api.UserContactMethodsApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_devices_contact_id_delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_devices_contact_id_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_devices_contact_id_put(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_devices_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_emails_contact_id_delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_emails_contact_id_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_emails_contact_id_put(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_emails_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_emails_post(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_phones_contact_id_delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_phones_contact_id_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_phones_contact_id_put(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_phones_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_contact_methods_phones_post(self): <NEW_LINE> <INDENT> pass | UserContactMethodsApi unit test stubs | 62598fb1236d856c2adc9472 |
class PBFT: <NEW_LINE> <INDENT> def __init__(self, blockChain): <NEW_LINE> <INDENT> self.blockChain = blockChain <NEW_LINE> self.node = blockChain.node <NEW_LINE> self.pendingBlocks = {} <NEW_LINE> self.prepareInfo = None <NEW_LINE> self.commitInfo = {} <NEW_LINE> self.state = PBFT_STATES["NONE"] <NEW_LINE> pass <NEW_LINE> <DEDENT> def changeState(self): <NEW_LINE> <INDENT> if self.state == PBFT_STATES["NONE"]: <NEW_LINE> <INDENT> self.state = PBFT_STATES["PRE-PREPARE"] <NEW_LINE> <DEDENT> elif self.state == PBFT_STATES["PRE-PREPARE"]: <NEW_LINE> <INDENT> self.state = PBFT_STATES["PREPARE"] <NEW_LINE> <DEDENT> elif self.state == PBFT_STATES["PREPARE"]: <NEW_LINE> <INDENT> self.state = PBFT_STATES["COMMIT"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def has_block(self, block_hash): <NEW_LINE> <INDENT> if block_hash in self.pendingBlocks: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def is_busy(self): <NEW_LINE> <INDENT> if self.state == PBFT_STATES["None"]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def add_block(self, block): <NEW_LINE> <INDENT> blockhash = block.get_hash() <NEW_LINE> self.pendingBlocks[blockhash] = block <NEW_LINE> if self.state == PBFT_STATES["None"]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def verify_request(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Pre_Prepare(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def verify_pre_prepare(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Prepare(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def verify_prepare(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Commit(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def verify_commit(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def execute(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def process_message(self, msg): <NEW_LINE> <INDENT> if self.state == PBFT_STATES["NONE"]: <NEW_LINE> <INDENT> verified = self.verify_pre_prepare(msg) <NEW_LINE> if verified : <NEW_LINE> <INDENT> self.changeState() <NEW_LINE> prepare_msg = "" <NEW_LINE> <DEDENT> <DEDENT> elif self.state == PBFT_STATES["PRE-PREPARE"]: <NEW_LINE> <INDENT> verified = self.verify_prepare(msg) <NEW_LINE> if verified: <NEW_LINE> <INDENT> if prepare_counts > PBFT_F: <NEW_LINE> <INDENT> self.changeState() <NEW_LINE> commit_msg = "" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif self.state == PBFT_STATES["PREPARE"]: <NEW_LINE> <INDENT> verified = self.verify_prepare(msg) <NEW_LINE> if verified: <NEW_LINE> <INDENT> if commit_counts > PBFT_F: <NEW_LINE> <INDENT> self.changeState() <NEW_LINE> execute() <NEW_LINE> reply_msg = "" | Pbft class for implementing PBFT protocol, for consensus
within a committee. | 62598fb1f7d966606f74804d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.