code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class SharedData(Belief): <NEW_LINE> <INDENT> pass | Shared belief amond the whole network | 62598f9c507cdc57c63a4b45 |
class GloboPlayViewTestCase(APITestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.url = reverse('api:globo_play') <NEW_LINE> <DEDENT> def test_post_for_the_view_pogram(self): <NEW_LINE> <INDENT> data = {'title':'teste', 'duration':'10:15:00;FF', 'name':'teste name'} <NEW_LINE> response = self.client.post(self.url, data, format='json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_201_CREATED) <NEW_LINE> self.assertEqual('sussses', response.data['message']) <NEW_LINE> self.assertEquals(ProcessedVideo.objects.count(), 1) <NEW_LINE> self.assertEquals(ProcessedVideo.objects.all()[0].title, 'teste') <NEW_LINE> self.assertEquals(ProcessedVideo.objects.all()[0].duration, '10:15:00;FF') <NEW_LINE> self.assertEquals(ProcessedVideo.objects.all()[0].name, 'teste name') | Class Testing View Pogramas | 62598f9c596a897236127a31 |
class TrafficLightMachine(StateMachine): <NEW_LINE> <INDENT> green = State('Green', initial=True) <NEW_LINE> yellow = State('Yellow') <NEW_LINE> red = State('Red') <NEW_LINE> cycle = green.to(yellow) | yellow.to(red) | red.to(green) <NEW_LINE> @green.to(yellow) <NEW_LINE> def slowdown(self, *args, **kwargs): <NEW_LINE> <INDENT> return args, kwargs <NEW_LINE> <DEDENT> @yellow.to(red) <NEW_LINE> def stop(self, *args, **kwargs): <NEW_LINE> <INDENT> return args, kwargs <NEW_LINE> <DEDENT> @red.to(green) <NEW_LINE> def go(self, *args, **kwargs): <NEW_LINE> <INDENT> return args, kwargs <NEW_LINE> <DEDENT> def on_cicle(self, *args, **kwargs): <NEW_LINE> <INDENT> return args, kwargs | A traffic light machine | 62598f9c4527f215b58e9c94 |
class Menu: <NEW_LINE> <INDENT> def __init__(self, screen, **kwargs): <NEW_LINE> <INDENT> self.log = logging.getLogger('DragonHab') <NEW_LINE> self.screen = screen <NEW_LINE> self.id = kwargs['id'] <NEW_LINE> self.parent = kwargs.get("parent",None) <NEW_LINE> self.title = kwargs.get("title","NO TITLE") <NEW_LINE> self.options = kwargs.get("options",None) <NEW_LINE> self.index = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> ret_val = f"<< {self.title} >>" <NEW_LINE> if self.options: <NEW_LINE> <INDENT> ret_val += f"\n{self.index+1} " <NEW_LINE> display_object = self.screen.objs[self.options[self.index]] <NEW_LINE> if type(display_object) == Menu: <NEW_LINE> <INDENT> ret_val += display_object.title <NEW_LINE> <DEDENT> elif hasattr(display_object,'title'): <NEW_LINE> <INDENT> ret_val += display_object.title <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret_val += "???" <NEW_LINE> <DEDENT> <DEDENT> return ret_val <NEW_LINE> <DEDENT> def up(self): <NEW_LINE> <INDENT> self.index += 1 <NEW_LINE> self.index %= len(self.options) <NEW_LINE> return self <NEW_LINE> <DEDENT> def down(self): <NEW_LINE> <INDENT> self.index -= 1 <NEW_LINE> self.index %= len(self.options) <NEW_LINE> return self <NEW_LINE> <DEDENT> def right(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def left(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def enter(self): <NEW_LINE> <INDENT> return self.screen.objs[self.options[self.index]] <NEW_LINE> <DEDENT> def cancel(self): <NEW_LINE> <INDENT> if self.parent is not None: <NEW_LINE> <INDENT> return self.screen.objs[self.parent] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self | Menu Class
| 62598f9c3cc13d1c6d46551c |
class EditarItemOpcao(RestauranteMixin, CardapioMixin, OpcaoMixin, ItemOpcaoMixin, View): <NEW_LINE> <INDENT> form_class = Form_Item_Default <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> form = self.form_class(request.POST, instance=self.item) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> form.save() <NEW_LINE> itens = self.opcao.getEvery_item() <NEW_LINE> result = buildItemOpcaoTable(itens, self.cardapio.id, self.opcao.id, token=request.COOKIES['csrftoken']) <NEW_LINE> data = prepareAjaxSuccessData(result, len(itens)) <NEW_LINE> <DEDENT> return JsonResponse(data) | Edita item de opcao via json | 62598f9c4a966d76dd5eec91 |
class Threshold(object): <NEW_LINE> <INDENT> def __init__(self, weights, thresh_type='soft'): <NEW_LINE> <INDENT> self.weights = weights <NEW_LINE> self.thresh_type = thresh_type <NEW_LINE> <DEDENT> def op(self, data, extra_factor=1.0): <NEW_LINE> <INDENT> threshold = self.weights * extra_factor <NEW_LINE> return thresh(data, threshold, self.thresh_type) | Threshold proximity operator
This class defines the threshold proximity operator
Parameters
----------
weights : np.ndarray
Input array of weights
thresh_type : str {'hard', 'soft'}, optional
Threshold type (default is 'soft') | 62598f9c3539df3088ecc067 |
class StateLayer(tf.compat.v1.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, input_layer_norm: bool = False) -> None: <NEW_LINE> <INDENT> super(StateLayer, self).__init__(name='state_layer') <NEW_LINE> self.flatten = tf.compat.v1.layers.Flatten() <NEW_LINE> self.input_layer_norm = input_layer_norm <NEW_LINE> <DEDENT> @property <NEW_LINE> def trainable_variables(self) -> None: <NEW_LINE> <INDENT> variables = [] <NEW_LINE> return variables <NEW_LINE> <DEDENT> def call(self, inputs: Sequence[tf.Tensor]) -> tf.Tensor: <NEW_LINE> <INDENT> state_layers = [] <NEW_LINE> for tensor in inputs: <NEW_LINE> <INDENT> layer = self.flatten(tensor) <NEW_LINE> if self.input_layer_norm: <NEW_LINE> <INDENT> layer = tf.contrib.layers.layer_norm(layer) <NEW_LINE> <DEDENT> state_layers.append(layer) <NEW_LINE> <DEDENT> return tf.concat(state_layers, axis=1) | StateLayer should be used as an input layer in a DRP.
It flattens each state fluent and returns a single
concatenated tensor.
Args:
input_layer_norm (bool): The boolean flag for enabling layer normalization. | 62598f9c07f4c71912baf1fc |
class EventSource(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "EventSource %s" % self.name | A source catalogue of seismic events. E.g. ISC Web Catalogue
:attribute id:
Internal identifier
:attribute created_at:
When this object has been imported into the catalogue db
:attribute name:
an unique event source short name.
:attribyte agencies:
a list of :py:class:`~eqcatalogue.models.Agency` instances
imported by this eventsource
:attribyte events:
a list of :py:class:`~eqcatalogue.models.Event` instances
imported by this eventsource
:attribyte origins:
a list of :py:class:`~eqcatalogue.models.Origin` instances
imported by this eventsource | 62598f9cd53ae8145f91823f |
class LineStringBufferByM(AlgorithmMetadata, QgsProcessingFeatureBasedAlgorithm): <NEW_LINE> <INDENT> METADATA = AlgorithmMetadata.read(__file__, 'LineStringBufferByM') <NEW_LINE> def inputLayerTypes(self): <NEW_LINE> <INDENT> return [QgsProcessing.TypeVectorLine] <NEW_LINE> <DEDENT> def outputName(self): <NEW_LINE> <INDENT> return self.tr('Buffer') <NEW_LINE> <DEDENT> def outputWkbType(self, inputWkbType): <NEW_LINE> <INDENT> return QgsWkbTypes.Polygon <NEW_LINE> <DEDENT> def supportInPlaceEdit(self, layer): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def prepareAlgorithm(self, parameters, context, feedback): <NEW_LINE> <INDENT> layer = self.parameterAsSource(parameters, 'INPUT', context) <NEW_LINE> if not QgsWkbTypes.hasM(layer.wkbType()): <NEW_LINE> <INDENT> feedback.reportError(self.tr('Input must have M coordinate.'), True) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def processFeature(self, feature, context, feedback): <NEW_LINE> <INDENT> features = [] <NEW_LINE> for geometry in feature.geometry().asGeometryCollection(): <NEW_LINE> <INDENT> new_geometry = geometry.variableWidthBufferByM(5) <NEW_LINE> new_feature = QgsFeature() <NEW_LINE> new_feature.setAttributes(feature.attributes()) <NEW_LINE> new_feature.setGeometry(new_geometry) <NEW_LINE> features.append(new_feature) <NEW_LINE> <DEDENT> return features | Variable-Width Vertex-Wise Buffer.
Local buffer width at each vertex is determined from M coordinate. | 62598f9c56ac1b37e6301f9b |
class DbTestCase(test_base.BaseTestCase): <NEW_LINE> <INDENT> FIXTURE = DbFixture <NEW_LINE> SCHEMA_SCOPE = None <NEW_LINE> _schema_resources = {} <NEW_LINE> _database_resources = {} <NEW_LINE> def _resources_for_driver(self, driver, schema_scope, generate_schema): <NEW_LINE> <INDENT> if driver not in self._database_resources: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._database_resources[driver] = provision.DatabaseResource(driver) <NEW_LINE> <DEDENT> except exception.BackendNotAvailable: <NEW_LINE> <INDENT> self._database_resources[driver] = None <NEW_LINE> <DEDENT> <DEDENT> database_resource = self._database_resources[driver] <NEW_LINE> if database_resource is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if schema_scope: <NEW_LINE> <INDENT> key = (driver, schema_scope) <NEW_LINE> if key not in self._schema_resources: <NEW_LINE> <INDENT> schema_resource = provision.SchemaResource( database_resource, generate_schema) <NEW_LINE> transaction_resource = provision.TransactionResource( database_resource, schema_resource) <NEW_LINE> self._schema_resources[key] = transaction_resource <NEW_LINE> <DEDENT> transaction_resource = self._schema_resources[key] <NEW_LINE> return [ ('transaction_engine', transaction_resource), ('db', database_resource), ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key = (driver, None) <NEW_LINE> if key not in self._schema_resources: <NEW_LINE> <INDENT> self._schema_resources[key] = provision.SchemaResource( database_resource, generate_schema, teardown=True) <NEW_LINE> <DEDENT> schema_resource = self._schema_resources[key] <NEW_LINE> return [ ('schema', schema_resource), ('db', database_resource) ] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def resources(self): <NEW_LINE> <INDENT> return self._resources_for_driver( self.FIXTURE.DRIVER, self.SCHEMA_SCOPE, self.generate_schema) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super(DbTestCase, self).setUp() <NEW_LINE> self.useFixture(self.FIXTURE(self)) <NEW_LINE> <DEDENT> def generate_schema(self, engine): <NEW_LINE> <INDENT> if self.SCHEMA_SCOPE: <NEW_LINE> <INDENT> raise NotImplementedError( "This test requires schema-level setup to be " "implemented within generate_schema().") | Base class for testing of DB code.
| 62598f9c76e4537e8c3ef367 |
class PIDrecord: <NEW_LINE> <INDENT> def __init__(self, fields): <NEW_LINE> <INDENT> self.pidType = int(fields[0]) <NEW_LINE> self.pidSType = int(fields[1]) <NEW_LINE> self.pidAPID = int(fields[2]) <NEW_LINE> self.pidPI1 = int(fields[3]) <NEW_LINE> self.pidPI2 = int(fields[4]) <NEW_LINE> self.pidSPID = int(fields[5]) <NEW_LINE> self.pidDescr = fields[6] <NEW_LINE> self.pidTPSD = int(fields[8]) <NEW_LINE> self.pidDFHsize = int(fields[9]) <NEW_LINE> self.pidCheck = bool(int((fields[13]+"0")[0])) <NEW_LINE> <DEDENT> def key(self): <NEW_LINE> <INDENT> return self.pidSPID <NEW_LINE> <DEDENT> def picKey(self): <NEW_LINE> <INDENT> return str([self.pidType, self.pidSType, self.pidAPID]) <NEW_LINE> <DEDENT> def picAlternateKey(self): <NEW_LINE> <INDENT> return str([self.pidType, self.pidSType, -1]) | MIB record from pid.dat | 62598f9c8e7ae83300ee8e50 |
class AdaptorDiagCap(ManagedObject): <NEW_LINE> <INDENT> consts = AdaptorDiagCapConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = MoMeta("AdaptorDiagCap", "adaptorDiagCap", "diag", VersionMeta.Version131c, "InputOutput", 0x3f, [], ["read-only"], ['adaptorFruCapProvider'], [], ["Get"]) <NEW_LINE> prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version131c, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "enable_lldp_transmit": MoPropertyMeta("enable_lldp_transmit", "enableLldpTransmit", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["false", "no", "true", "yes"], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } <NEW_LINE> prop_map = { "childAction": "child_action", "dn": "dn", "enableLldpTransmit": "enable_lldp_transmit", "rn": "rn", "sacl": "sacl", "status": "status", } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.child_action = None <NEW_LINE> self.enable_lldp_transmit = None <NEW_LINE> self.sacl = None <NEW_LINE> self.status = None <NEW_LINE> ManagedObject.__init__(self, "AdaptorDiagCap", parent_mo_or_dn, **kwargs) | This is AdaptorDiagCap class. | 62598f9c85dfad0860cbf94d |
class MainCharacter(Character): <NEW_LINE> <INDENT> health = 100 <NEW_LINE> List = [] <NEW_LINE> def __init__(self, x, y, agent): <NEW_LINE> <INDENT> self.health = MainCharacter.health <NEW_LINE> self.description = "maincharacter" <NEW_LINE> self.direction = 'w' <NEW_LINE> self.velocity = 16 <NEW_LINE> self.imgPath = 'img/player_' <NEW_LINE> self.img = pygame.image.load(self.imgPath+'w.png') <NEW_LINE> Character.__init__(self, x, y, agent) <NEW_LINE> MainCharacter.List.append(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def draw(screen): <NEW_LINE> <INDENT> for mainCharacter in MainCharacter.List: <NEW_LINE> <INDENT> mainCharacter._draw(screen) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def clear(): <NEW_LINE> <INDENT> del MainCharacter.List[:] | This class represents the MainCharacter for the
game | 62598f9c44b2445a339b6845 |
class Synthesizer(): <NEW_LINE> <INDENT> def __init__(self, lpc_frame_array): <NEW_LINE> <INDENT> self._frame_array = lpc_frame_array <NEW_LINE> <DEDENT> def decode(self): <NEW_LINE> <INDENT> audio_frames = self._reconstruct_frames() <NEW_LINE> audio_array = self._merge_frames(audio_frames) <NEW_LINE> return audio_array <NEW_LINE> <DEDENT> def _reconstruct_frames(self): <NEW_LINE> <INDENT> frames = self.get_frame_array().get_frames() <NEW_LINE> return np.asarray(map(reconstruct, frames)) <NEW_LINE> <DEDENT> def _merge_frames(self, audio_frames): <NEW_LINE> <INDENT> lpc_frame_array = self.get_frame_array() <NEW_LINE> lpc_frames = lpc_frame_array.get_frames() <NEW_LINE> lpc_length = lpc_frames.shape[0] <NEW_LINE> samples_per_frame = lpc_frame_array.get_fs() * lpc_frame_array.get_frame_size() <NEW_LINE> base_window = np.hamming(samples_per_frame * 2) <NEW_LINE> window = np.insert(base_window, base_window.size // 2, np.ones(samples_per_frame)) <NEW_LINE> windows = np.tile(window, (lpc_length, 1)) <NEW_LINE> windows[0, :samples_per_frame] = np.ones(samples_per_frame) <NEW_LINE> windows[-1, -samples_per_frame:] = np.ones(samples_per_frame) <NEW_LINE> tapered_audio = audio_frames * windows <NEW_LINE> def merge(arr1, arr2): <NEW_LINE> <INDENT> combined_overlap = arr1[-samples_per_frame:] + arr2[:samples_per_frame] <NEW_LINE> return np.concatenate((arr1[:-samples_per_frame], combined_overlap, arr2[samples_per_frame:])) <NEW_LINE> <DEDENT> return reduce(merge, tapered_audio) <NEW_LINE> <DEDENT> def get_frame_array(self): <NEW_LINE> <INDENT> return self._frame_array <NEW_LINE> <DEDENT> def get_fs(self): <NEW_LINE> <INDENT> return self.get_frame_array().get_fs() | Class decodes lpc packets into an array. | 62598f9c67a9b606de545d7b |
class Operator(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String, nullable=False, index=True, unique=True) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Operator name={0!r}>'.format(self.name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_or_create(cls, name): <NEW_LINE> <INDENT> operator = cls.query.filter_by(name=name).first() <NEW_LINE> if not operator: <NEW_LINE> <INDENT> operator = Operator(name=name) <NEW_LINE> db.session.add(operator) <NEW_LINE> <DEDENT> return operator | An operator that has been handled by IIB. | 62598f9c56ac1b37e6301f9c |
class Measure(models.Model): <NEW_LINE> <INDENT> index_weight = 5 <NEW_LINE> code = models.CharField(_("code"),max_length=const.DB_CHAR_CODE_6,blank=True,null=True) <NEW_LINE> name = models.CharField(_("name"),max_length=const.DB_CHAR_NAME_20) <NEW_LINE> status = models.BooleanField(_("in use"),default=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '%s' % self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('measure') <NEW_LINE> verbose_name_plural = _('measure') | 计量单位 | 62598f9c60cbc95b063640fe |
class Paraboloid(Component): <NEW_LINE> <INDENT> x = Float(0.0, iotype='in', desc='The variable x') <NEW_LINE> y = Float(0.0, iotype='in', desc='The variable y') <NEW_LINE> f_xy = Float(0.0, iotype='out', desc='F(x,y)') <NEW_LINE> def execute(self): <NEW_LINE> <INDENT> x = self.x <NEW_LINE> y = self.y <NEW_LINE> self.f_xy = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0 | Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 | 62598f9cc432627299fa2d8a |
class CntFlagB(CntBasic): <NEW_LINE> <INDENT> @property <NEW_LINE> def _regular_cnt_id(self): <NEW_LINE> <INDENT> return NPK_FLAG_B | Flag typ found in gps-5.23-mipsbe.npk
Payload contains b'
update-console
'
| 62598f9cdd821e528d6d8ce6 |
class UserFavoriteAdmin(object): <NEW_LINE> <INDENT> list_display = ['user', 'fav_id', 'fav_type', 'add_time'] <NEW_LINE> search_fields = ['user', 'fav_id', 'fav_type'] <NEW_LINE> list_filter = ['user', 'fav_id', 'fav_type', 'add_time'] <NEW_LINE> model_icon = 'fas fa-star' | 用户收藏后台 | 62598f9c8e71fb1e983bb867 |
class DmozSpider(scrapy.Spider): <NEW_LINE> <INDENT> name = 'dmoz' <NEW_LINE> allowed_domains = ['dmoz.org'] <NEW_LINE> start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/" ] <NEW_LINE> def parse(self, response): <NEW_LINE> <INDENT> for href in response.css('ul.directory.dir-col > li > a::attr(\'href\')'): <NEW_LINE> <INDENT> url = response.urljoin(href.extract()) <NEW_LINE> yield scrapy.Request(url, callback=self.parse_dir_contents) <NEW_LINE> <DEDENT> <DEDENT> def parse_dir_contents(self, response): <NEW_LINE> <INDENT> for sel in response.xpath('//ul/li'): <NEW_LINE> <INDENT> item = DmozItem() <NEW_LINE> item['title'] = sel.xpath('a/text()').extract() <NEW_LINE> item['link'] = sel.xpath('a/@href').extract() <NEW_LINE> item['desc'] = sel.xpath('text()').extract() <NEW_LINE> yield item | docstring for DmozSpider | 62598f9c627d3e7fe0e06c5c |
class AffineTransform3D(ImagePreprocessing3D): <NEW_LINE> <INDENT> def __init__(self, affine_mat, translation=np.zeros(3), clamp_mode="clamp", pad_val=0.0, bigdl_type="float"): <NEW_LINE> <INDENT> affine_mat_tensor = JTensor.from_ndarray(affine_mat) <NEW_LINE> translation_tensor = JTensor.from_ndarray(translation) <NEW_LINE> super(AffineTransform3D, self).__init__(bigdl_type, affine_mat_tensor, translation_tensor, clamp_mode, pad_val) | Affine transformer implements affine transformation on a given tensor.
To avoid defects in resampling, the mapping is from destination to source.
dst(z,y,x) = src(f(z),f(y),f(x)) where f: dst -> src
:param affine_mat: numpy array in 3x3 shape.Define affine transformation from dst to src.
:param translation: numpy array in 3 dimension.Default value is np.zero(3).
Define translation in each axis.
:param clampMode: str, default value is "clamp".
Define how to handle interpolation off the input image.
:param padVal: float, default is 0.0. Define padding value when clampMode="padding".
Setting this value when clampMode="clamp" will cause an error. | 62598f9cd268445f26639a5c |
class PyPath: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.py_buffer = "" <NEW_LINE> <DEDENT> def call(self, pathobj): <NEW_LINE> <INDENT> cursym = pathobj.prog[pathobj.y][pathobj.x] <NEW_LINE> if cursym == '@': <NEW_LINE> <INDENT> result = eval(self.getstr(pathobj), {'pathobj' : pathobj}) <NEW_LINE> if type(result) is int: <NEW_LINE> <INDENT> pathobj.debug("Storing result " + str(result) + " to memory cell " + pathobj.p) <NEW_LINE> pathobj.mem[pathobj.p] = result <NEW_LINE> <DEDENT> elif type(result) is float: <NEW_LINE> <INDENT> pathobj.debug("Storing result " + str(result) + " to memory cell " + pathobj.p) <NEW_LINE> pathobj.mem[pathobj.p] = result.round() <NEW_LINE> <DEDENT> elif type(result) is str: <NEW_LINE> <INDENT> i = pathobj.p <NEW_LINE> for c in (result + chr(0)): <NEW_LINE> <INDENT> pathobj.debug("Storing character " + str(ord(c)) + " to memory cell " + str(i)) <NEW_LINE> if i > len(pathobj.mem) - 1: <NEW_LINE> <INDENT> pathobj.mem.append(0) <NEW_LINE> <DEDENT> pathobj.mem[i] = ord(c) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> elif cursym == '%': <NEW_LINE> <INDENT> exec(self.getstr(pathobj), {'pathobj' : pathobj}) <NEW_LINE> pathobj.debug("Python statement executed") <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def getstr(self, pathobj): <NEW_LINE> <INDENT> self.py_buffer = "" <NEW_LINE> i = pathobj.p <NEW_LINE> while pathobj.mem[i] != 0: <NEW_LINE> <INDENT> self.py_buffer += chr(pathobj.mem[i]) <NEW_LINE> i += 1 <NEW_LINE> if i > len(pathobj.mem) - 1: <NEW_LINE> <INDENT> pathobj.mem.append(0) <NEW_LINE> <DEDENT> <DEDENT> return self.py_buffer | Plugin that allows inline execution of Python expressions and statements. | 62598f9c91af0d3eaad39bbc |
@attr.s <NEW_LINE> class TurnParams(object): <NEW_LINE> <INDENT> main_corridor_length = attr.ib(default=8, type=float) <NEW_LINE> turn_corridor_length = attr.ib(default=5, type=float) <NEW_LINE> turn_corridor_angle = attr.ib(default= 2 * np.pi / 8, type=float) <NEW_LINE> main_corridor_width = attr.ib(default=1.0, type=float) <NEW_LINE> turn_corridor_width = attr.ib(default=1.0, type=float) <NEW_LINE> margin = attr.ib(default=1.0, type=float) <NEW_LINE> flip_arnd_oy = attr.ib(default=False, type=bool) <NEW_LINE> flip_arnd_ox = attr.ib(default=False, type=bool) <NEW_LINE> rot_theta = attr.ib(default=0, type=float) | Parametrization of a specific turn | 62598f9ca219f33f346c65cc |
class ListTopDDoSDataResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Data = None <NEW_LINE> self.IPData = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Data") is not None: <NEW_LINE> <INDENT> self.Data = [] <NEW_LINE> for item in params.get("Data"): <NEW_LINE> <INDENT> obj = DDoSTopData() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Data.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if params.get("IPData") is not None: <NEW_LINE> <INDENT> self.IPData = [] <NEW_LINE> for item in params.get("IPData"): <NEW_LINE> <INDENT> obj = DDoSAttackIPTopData() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.IPData.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId") | ListTopDDoSData返回参数结构体
| 62598f9ca8370b77170f0195 |
class MsgLinuxMemState(SBP): <NEW_LINE> <INDENT> _parser = construct.Struct( 'index' / construct.Int8ul, 'pid' / construct.Int16ul, 'pmem' / construct.Int8ul, 'time' / construct.Int32ul, 'flags' / construct.Int8ul, 'tname'/ construct.Bytes(15), 'cmdline' / construct.GreedyBytes,) <NEW_LINE> __slots__ = [ 'index', 'pid', 'pmem', 'time', 'flags', 'tname', 'cmdline', ] <NEW_LINE> def __init__(self, sbp=None, **kwargs): <NEW_LINE> <INDENT> if sbp: <NEW_LINE> <INDENT> super( MsgLinuxMemState, self).__init__(sbp.msg_type, sbp.sender, sbp.length, sbp.payload, sbp.crc) <NEW_LINE> self.from_binary(sbp.payload) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super( MsgLinuxMemState, self).__init__() <NEW_LINE> self.msg_type = SBP_MSG_LINUX_MEM_STATE <NEW_LINE> self.sender = kwargs.pop('sender', SENDER_ID) <NEW_LINE> self.index = kwargs.pop('index') <NEW_LINE> self.pid = kwargs.pop('pid') <NEW_LINE> self.pmem = kwargs.pop('pmem') <NEW_LINE> self.time = kwargs.pop('time') <NEW_LINE> self.flags = kwargs.pop('flags') <NEW_LINE> self.tname = kwargs.pop('tname') <NEW_LINE> self.cmdline = kwargs.pop('cmdline') <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return fmt_repr(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(s): <NEW_LINE> <INDENT> d = json.loads(s) <NEW_LINE> return MsgLinuxMemState.from_json_dict(d) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json_dict(d): <NEW_LINE> <INDENT> sbp = SBP.from_json_dict(d) <NEW_LINE> return MsgLinuxMemState(sbp, **d) <NEW_LINE> <DEDENT> def from_binary(self, d): <NEW_LINE> <INDENT> p = MsgLinuxMemState._parser.parse(d) <NEW_LINE> for n in self.__class__.__slots__: <NEW_LINE> <INDENT> setattr(self, n, getattr(p, n)) <NEW_LINE> <DEDENT> <DEDENT> def to_binary(self): <NEW_LINE> <INDENT> c = containerize(exclude_fields(self)) <NEW_LINE> self.payload = MsgLinuxMemState._parser.build(c) <NEW_LINE> return self.pack() <NEW_LINE> <DEDENT> def into_buffer(self, buf, offset): <NEW_LINE> <INDENT> self.payload = containerize(exclude_fields(self)) <NEW_LINE> self.parser = MsgLinuxMemState._parser <NEW_LINE> self.stream_payload.reset(buf, offset) <NEW_LINE> return self.pack_into(buf, offset, self._build_payload) <NEW_LINE> <DEDENT> def to_json_dict(self): <NEW_LINE> <INDENT> self.to_binary() <NEW_LINE> d = super( MsgLinuxMemState, self).to_json_dict() <NEW_LINE> j = walk_json_dict(exclude_fields(self)) <NEW_LINE> d.update(j) <NEW_LINE> return d | SBP class for message MSG_LINUX_MEM_STATE (0x7F09).
You can have MSG_LINUX_MEM_STATE inherit its fields directly
from an inherited SBP object, or construct it inline using a dict
of its fields.
This message indicates the process state of the top 10 heaviest consumers of
memory on the system, including a timestamp.
Parameters
----------
sbp : SBP
SBP parent object to inherit from.
index : int
sequence of this status message, values from 0-9
pid : int
the PID of the process
pmem : int
percent of memory used, expressed as a fraction of 256
time : int
timestamp of message, refer to flags field for how to interpret
flags : int
flags
tname : string
fixed length string representing the thread name
cmdline : string
the command line (as much as it fits in the remaining packet)
sender : int
Optional sender ID, defaults to SENDER_ID (see sbp/msg.py). | 62598f9c442bda511e95c20f |
class PathType(Enum): <NEW_LINE> <INDENT> STOP = 0 <NEW_LINE> MAY_STOP = 1 <NEW_LINE> CURVE = 2 <NEW_LINE> LINEAR = 3 <NEW_LINE> STEP = 4 | Interpolation type of Path. | 62598f9ce5267d203ee6b6c0 |
class MyDynamicMplCanvas(MyMplCanvas): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> MyMplCanvas.__init__(self, *args, **kwargs) <NEW_LINE> timer = QtCore.QTimer(self) <NEW_LINE> timer.timeout.connect(self.update_figure) <NEW_LINE> timer.start(1000) <NEW_LINE> <DEDENT> def compute_initial_figure(self): <NEW_LINE> <INDENT> self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r') <NEW_LINE> self.axes.set_ylabel('label1') <NEW_LINE> self.axes.set_xlabel('label') <NEW_LINE> self.axes.grid(True) <NEW_LINE> <DEDENT> def update_figure(self): <NEW_LINE> <INDENT> l = [random.randint(0, 10) for i in range(4)] <NEW_LINE> self.axes.plot([0, 1, 2, 3], l, 'r') <NEW_LINE> self.axes.set_ylabel('label y din plot') <NEW_LINE> self.axes.set_xlabel('label x din plot') <NEW_LINE> self.axes.grid(True) <NEW_LINE> self.draw() | A canvas that updates itself every second with a new plot. | 62598f9cbe383301e02535a8 |
class TestCheck(Check): <NEW_LINE> <INDENT> __test__ = True <NEW_LINE> @property <NEW_LINE> def this_check(self): <NEW_LINE> <INDENT> return chk <NEW_LINE> <DEDENT> def test_smoke(self): <NEW_LINE> <INDENT> assert self.passes("""Smoke phrase with nothing flagged.""") <NEW_LINE> assert not self.passes( """The legal team had two lawyers and a lady lawyer.""") | The test class for sexism.misc. | 62598f9c7047854f4633f194 |
class TDistSoftAttention(ProbabilityTensor): <NEW_LINE> <INDENT> def get_output_shape_for(self, input_shape): <NEW_LINE> <INDENT> return (input_shape[0], input_shape[1], input_shape[2]) <NEW_LINE> <DEDENT> def compute_mask(self, x, mask=None): <NEW_LINE> <INDENT> if mask is None or mask.ndim==2: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Unexpected situation") <NEW_LINE> <DEDENT> <DEDENT> def call(self, x, mask=None): <NEW_LINE> <INDENT> tdcontext = K.zeros_like(x) <NEW_LINE> zero_out_time = K.zeros_like(x) <NEW_LINE> numtime = max_sen_length <NEW_LINE> for t in range(numtime): <NEW_LINE> <INDENT> timestep_idx = t+1 <NEW_LINE> x_in = x <NEW_LINE> if timestep_idx < numtime: <NEW_LINE> <INDENT> x_in = K.set_subtensor(x_in[:, timestep_idx:, :], zero_out_time[:, timestep_idx:, :]) <NEW_LINE> <DEDENT> p_vectors = K.expand_dims(super(TDistSoftAttention, self).call(x_in, mask), 2) <NEW_LINE> expanded_p = K.repeat_elements(p_vectors, K.shape(x)[2], axis=2) <NEW_LINE> context = K.sum(expanded_p * x_in, axis=1) <NEW_LINE> tdcontext = K.set_subtensor(tdcontext[:, t, :], context) <NEW_LINE> <DEDENT> return tdcontext | This will create the context vector at each timestep | 62598f9c4f6381625f199396 |
class FileHandler: <NEW_LINE> <INDENT> def get_srtm_dir(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> if 'HOME' in os.environ: <NEW_LINE> <INDENT> result = '{0}/.cache/srtm'.format(os.environ['HOME']) <NEW_LINE> <DEDENT> elif 'HOMEPATH' in os.environ: <NEW_LINE> <INDENT> result = '{0}/.cache/srtm'.format(os.environ['HOMEPATH']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('No default HOME directory found, please specify a path where to store files') <NEW_LINE> <DEDENT> if not os.path.exists(result): <NEW_LINE> <INDENT> os.makedirs(result) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def exists(self, file_name): <NEW_LINE> <INDENT> return os.path.exists('%s/%s' % (self.get_srtm_dir(), file_name)) <NEW_LINE> <DEDENT> def write(self, file_name, contents): <NEW_LINE> <INDENT> with open('%s/%s' % (self.get_srtm_dir(), file_name), 'wb') as f: <NEW_LINE> <INDENT> f.write(contents) <NEW_LINE> <DEDENT> <DEDENT> def read(self, file_name): <NEW_LINE> <INDENT> with open('%s/%s' % (self.get_srtm_dir(), file_name), 'rb') as f: <NEW_LINE> <INDENT> return f.read() | The default file handler. It can be changed if you need to save/read SRTM
files in a database or Amazon S3. | 62598f9c009cb60464d012d8 |
class TriggerEfficiency: <NEW_LINE> <INDENT> def __init__(self, triggername, minbiascontainer, triggeredcontainer): <NEW_LINE> <INDENT> self.__triggername = triggername <NEW_LINE> self.__minbiascontainer = minbiascontainer <NEW_LINE> self.__triggeredcontainer = triggeredcontainer <NEW_LINE> self.__triggerefficiency = None <NEW_LINE> self.__CalculateTriggerEfficiency() <NEW_LINE> <DEDENT> def __MakeNormalisedSpectrum(self, container, name): <NEW_LINE> <INDENT> container.SetVertexRange(-10., 10.) <NEW_LINE> container.SetPileupRejection(True) <NEW_LINE> if container.__class__ == "TrackContainer": <NEW_LINE> <INDENT> container.SelectTrackCuts(1) <NEW_LINE> container.RequestSeenInMinBias() <NEW_LINE> <DEDENT> return container.MakeProjection(0, "ptSpectrum%s" %(name), "p_{#rm{t}} (GeV/c)", "1/N_{event} 1/(#Delta p_{#rm t}) dN/dp_{#rm{t}} ((GeV/c)^{-2}", doNorm = False) <NEW_LINE> <DEDENT> def __CalculateTriggerEfficiency(self): <NEW_LINE> <INDENT> minbiasspectrum = self.__MakeNormalisedSpectrum(self.__minbiascontainer, "minbias") <NEW_LINE> self.__triggerefficiency = self.__MakeNormalisedSpectrum(self.__triggeredcontainer, self.__triggername) <NEW_LINE> self.__triggerefficiency.Divide(self.__triggerefficiency, minbiasspectrum, 1., 1., "b") <NEW_LINE> self.__triggerefficiency.SetName("triggerEff%s" %(self.__triggername)) <NEW_LINE> <DEDENT> def GetEfficiencyCurve(self): <NEW_LINE> <INDENT> return self.__triggerefficiency | Class calculating the trigger efficiency from a given min. bias container and a given triggered container | 62598f9cd7e4931a7ef3be4b |
class UnityML(): <NEW_LINE> <INDENT> def __init__(self, name, seed=0): <NEW_LINE> <INDENT> from unityagents import UnityEnvironment <NEW_LINE> self.seed = seed <NEW_LINE> print('SEED: {}'.format(self.seed)) <NEW_LINE> self.env = UnityEnvironment(file_name=name, seed=seed) <NEW_LINE> self.brain_name = self.env.brain_names[0] <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> info = self.env.reset(train_mode=True)[self.brain_name] <NEW_LINE> state = info.vector_observations <NEW_LINE> return state <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> info = self.env.step(action)[self.brain_name] <NEW_LINE> state = info.vector_observations <NEW_LINE> reward = info.rewards <NEW_LINE> done = info.local_done <NEW_LINE> return state, reward, done <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> pass | Base class for Unity ML environments using unityagents (v0.4). | 62598f9c38b623060ffa8e44 |
class DeleteProductResponse(SdkResponse): <NEW_LINE> <INDENT> sensitive_list = [] <NEW_LINE> openapi_types = { 'body': 'str' } <NEW_LINE> attribute_map = { 'body': 'body' } <NEW_LINE> def __init__(self, body=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._body = None <NEW_LINE> self.discriminator = None <NEW_LINE> if body is not None: <NEW_LINE> <INDENT> self.body = body <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def body(self): <NEW_LINE> <INDENT> return self._body <NEW_LINE> <DEDENT> @body.setter <NEW_LINE> def body(self, body): <NEW_LINE> <INDENT> self._body = body <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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> if attr in self.sensitive_list: <NEW_LINE> <INDENT> result[attr] = "****" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <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, DeleteProductResponse): <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 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition. | 62598f9c236d856c2adc9313 |
class PartialRollout(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.states = [] <NEW_LINE> self.actions = [] <NEW_LINE> self.rewards = [] <NEW_LINE> self.values = [] <NEW_LINE> self.r = 0.0 <NEW_LINE> self.features = [] <NEW_LINE> <DEDENT> def add(self, state, action, reward, value, features): <NEW_LINE> <INDENT> self.states += [state] <NEW_LINE> self.actions += [action] <NEW_LINE> self.rewards += [reward] <NEW_LINE> self.values += [value] <NEW_LINE> self.features += [features] <NEW_LINE> <DEDENT> def extend(self, other): <NEW_LINE> <INDENT> self.states.extend(other.states) <NEW_LINE> self.actions.extend(other.actions) <NEW_LINE> self.rewards.extend(other.rewards) <NEW_LINE> self.values.extend(other.values) <NEW_LINE> self.r = other.r <NEW_LINE> self.features.extend(other.features) | a piece of a complete rollout. We run our agent, and process its experience
once it has processed enough steps. | 62598f9c0a50d4780f70518c |
class GameAlreadyStarted(Exception): <NEW_LINE> <INDENT> pass | An action requiring the game to be waiting was attempted after starting it | 62598f9cd7e4931a7ef3be4c |
class SlackIssuesMessageBuilder(SlackMessageBuilder): <NEW_LINE> <INDENT> def __init__( self, group: Group, event: Event | None = None, tags: set[str] | None = None, identity: Identity | None = None, actions: Sequence[MessageAction] | None = None, rules: list[Rule] | None = None, link_to_event: bool = False, issue_details: bool = False, notification: ProjectNotification | None = None, recipient: Team | User | None = None, ) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.group = group <NEW_LINE> self.event = event <NEW_LINE> self.tags = tags <NEW_LINE> self.identity = identity <NEW_LINE> self.actions = actions <NEW_LINE> self.rules = rules <NEW_LINE> self.link_to_event = link_to_event <NEW_LINE> self.issue_details = issue_details <NEW_LINE> self.notification = notification <NEW_LINE> self.recipient = recipient <NEW_LINE> <DEDENT> def build(self) -> SlackBody: <NEW_LINE> <INDENT> text = build_attachment_text(self.group, self.event) or "" <NEW_LINE> project = Project.objects.get_from_cache(id=self.group.project_id) <NEW_LINE> event_for_tags = self.event or self.group.get_latest_event() <NEW_LINE> color = get_color(event_for_tags, self.notification) <NEW_LINE> fields = build_tag_fields(event_for_tags, self.tags) <NEW_LINE> footer = ( self.notification.build_notification_footer(self.recipient) if self.notification and self.recipient else build_footer(self.group, project, self.rules) ) <NEW_LINE> obj = self.event if self.event is not None else self.group <NEW_LINE> if not self.issue_details or (self.recipient and isinstance(self.recipient, Team)): <NEW_LINE> <INDENT> payload_actions, text, color = build_actions( self.group, project, text, color, self.actions, self.identity ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> payload_actions = [] <NEW_LINE> <DEDENT> return self._build( actions=payload_actions, callback_id=json.dumps({"issue": self.group.id}), color=color, fallback=f"[{project.slug}] {obj.title}", fields=fields, footer=footer, text=text, title=build_attachment_title(obj), title_link=get_title_link( self.group, self.event, self.link_to_event, self.issue_details, self.notification ), ts=get_timestamp(self.group, self.event) if not self.issue_details else None, ) | We're keeping around this awkward interface so that we can share logic with unfurling. | 62598f9cc432627299fa2d8c |
class TerminalMode: <NEW_LINE> <INDENT> def __init__(self, fileno: int): <NEW_LINE> <INDENT> self.fileno = fileno <NEW_LINE> self.mode = None <NEW_LINE> self.ttysize = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.mode = tty.tcgetattr(self.fileno) <NEW_LINE> <DEDENT> except tty.error as exc: <NEW_LINE> <INDENT> logger.debug('Terminal mode could not be saved: {}'.format(exc)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> columns, lines = os.get_terminal_size(self.fileno) <NEW_LINE> self.ttysize = struct.pack("HHHH", lines, columns, 0, 0) <NEW_LINE> <DEDENT> except OSError as exc: <NEW_LINE> <INDENT> logger.debug('Terminal size could not be saved: {}'.format(exc)) <NEW_LINE> <DEDENT> return self.mode, self.ttysize <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> if self.ttysize is not None: <NEW_LINE> <INDENT> fcntl.ioctl(self.fileno, termios.TIOCSWINSZ, self.ttysize) <NEW_LINE> <DEDENT> if self.mode is not None: <NEW_LINE> <INDENT> tty.tcsetattr(self.fileno, tty.TCSAFLUSH, self.mode) | Save terminal mode and size on entry, restore them on exit | 62598f9c627d3e7fe0e06c5e |
class ActionStructure(PClass): <NEW_LINE> <INDENT> type = field(type=(unicode, None.__class__)) <NEW_LINE> children = pvector_field(object) <NEW_LINE> failed = field(type=bool) <NEW_LINE> @classmethod <NEW_LINE> def from_written(cls, written): <NEW_LINE> <INDENT> if isinstance(written, WrittenMessage): <NEW_LINE> <INDENT> return written.as_dict()[MESSAGE_TYPE_FIELD] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not written.end_message: <NEW_LINE> <INDENT> raise AssertionError("Missing end message.") <NEW_LINE> <DEDENT> return cls( type=written.action_type, failed=(written.end_message.contents[ACTION_STATUS_FIELD] == FAILED_STATUS), children=[cls.from_written(o) for o in written.children]) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def to_eliot(cls, structure_or_message, logger): <NEW_LINE> <INDENT> if isinstance(structure_or_message, cls): <NEW_LINE> <INDENT> action = structure_or_message <NEW_LINE> try: <NEW_LINE> <INDENT> with start_action(logger, action_type=action.type): <NEW_LINE> <INDENT> for child in action.children: <NEW_LINE> <INDENT> cls.to_eliot(child, logger) <NEW_LINE> <DEDENT> if structure_or_message.failed: <NEW_LINE> <INDENT> raise RuntimeError("Make the eliot action fail.") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> Message.new(message_type=structure_or_message).write(logger) <NEW_LINE> <DEDENT> return logger.messages | A tree structure used to generate/compare to Eliot trees.
Individual messages are encoded as a unicode string; actions are
encoded as a L{ActionStructure} instance. | 62598f9cd268445f26639a5d |
class HomeKitEntity(Entity): <NEW_LINE> <INDENT> def __init__(self, accessory, devinfo): <NEW_LINE> <INDENT> self._name = accessory.model <NEW_LINE> self._accessory = accessory <NEW_LINE> self._aid = devinfo['aid'] <NEW_LINE> self._iid = devinfo['iid'] <NEW_LINE> self._address = "homekit-{}-{}".format(devinfo['serial'], self._iid) <NEW_LINE> self._features = 0 <NEW_LINE> self._chars = {} <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self._accessory.get_json('/accessories') <NEW_LINE> <DEDENT> except HomeKitConnectionError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for accessory in data['accessories']: <NEW_LINE> <INDENT> if accessory['aid'] != self._aid: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for service in accessory['services']: <NEW_LINE> <INDENT> if service['iid'] != self._iid: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.update_characteristics(service['characteristics']) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self._address <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self) -> bool: <NEW_LINE> <INDENT> return self._accessory.conn is not None <NEW_LINE> <DEDENT> def update_characteristics(self, characteristics): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def put_characteristics(self, characteristics): <NEW_LINE> <INDENT> body = json.dumps({'characteristics': characteristics}) <NEW_LINE> self._accessory.securecon.put('/characteristics', body) | Representation of a Home Assistant HomeKit device. | 62598f9c442bda511e95c210 |
class FuzzyAvoidObstacle(ISensorBasedController): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> sensors = [] <NEW_LINE> for i in range(0, 8): <NEW_LINE> <INDENT> sensors.append(createSensorAtecendent('sensor' + str(i))) <NEW_LINE> <DEDENT> self.linearCsq = createLinearSpeedConsequent() <NEW_LINE> self.angularCsq = createAngularSpeedConsequent() <NEW_LINE> self.rules = createRules([sensors[3], sensors[4]], [sensors[0], sensors[1], sensors[2]], [sensors[5], sensors[6], sensors[7]], self.linearCsq, self.angularCsq) <NEW_LINE> self.ctrl = ctrl.ControlSystem(self.rules) <NEW_LINE> self.sys = ctrl.ControlSystemSimulation(self.ctrl) <NEW_LINE> self.sensors = sensors <NEW_LINE> <DEDENT> def compute(self, sensorsReadings: List[float]): <NEW_LINE> <INDENT> logging.debug(sensorsReadings) <NEW_LINE> for i in range(0, 8): <NEW_LINE> <INDENT> self.sys.input['sensor' + str(i)] = sensorsReadings[i] <NEW_LINE> <DEDENT> self.sys.compute() <NEW_LINE> return self.sys.output['linearSpeed'], self.sys.output['angularSpeed'] | Fuzzy controller to avoid obstacles. | 62598f9c379a373c97d98dc9 |
class QuickDjangoTest(object): <NEW_LINE> <INDENT> DIRNAME = os.path.dirname(__file__) <NEW_LINE> INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', ) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.apps = args <NEW_LINE> self.version = self.get_test_version() <NEW_LINE> if self.version == 'new': <NEW_LINE> <INDENT> self._new_tests() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._old_tests() <NEW_LINE> <DEDENT> <DEDENT> def get_test_version(self): <NEW_LINE> <INDENT> from django import VERSION <NEW_LINE> if VERSION[0] == 1 and VERSION[1] >= 2: <NEW_LINE> <INDENT> return 'new' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'old' <NEW_LINE> <DEDENT> <DEDENT> def _old_tests(self): <NEW_LINE> <INDENT> settings.configure(DEBUG = True, DATABASE_ENGINE = 'postgresql_psycopg2', DATABASE_NAME = 'pgcryptoauth_test', DATABASE_USER = 'postgres', DATABASE_HOST = '127.0.0.1', INSTALLED_APPS = self.INSTALLED_APPS + self.apps, PASSWORD_HASHERS = ('pgcryptoauth.hashers.PgCryptoPasswordHasher', ), ) <NEW_LINE> from django.test.simple import run_tests <NEW_LINE> failures = run_tests(self.apps, verbosity=1) <NEW_LINE> if failures: <NEW_LINE> <INDENT> sys.exit(failures) <NEW_LINE> <DEDENT> <DEDENT> def _new_tests(self): <NEW_LINE> <INDENT> settings.configure( DEBUG = True, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pgcryptoauth_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '', } }, PASSWORD_HASHERS = ('pgcryptoauth.hashers.PgCryptoPasswordHasher', ), INSTALLED_APPS = self.INSTALLED_APPS + self.apps, ) <NEW_LINE> from django.test.simple import DjangoTestSuiteRunner <NEW_LINE> failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1) <NEW_LINE> if failures: <NEW_LINE> <INDENT> sys.exit(failures) | A quick way to run the Django test suite without a fully-configured project.
Example usage:
>>> QuickDjangoTest('app1', 'app2')
Based on a script published by Lukasz Dziedzia at:
http://stackoverflow.com/questions/3841725/how-to-launch-tests-for-django-reusable-app | 62598f9c8a43f66fc4bf1f30 |
class UO2(UraniumOxide): <NEW_LINE> <INDENT> pass | Another name for UraniumOxide | 62598f9c1f5feb6acb1629d6 |
class ResponseError(UltronClientError): <NEW_LINE> <INDENT> pass | The base exception for errors stemming from UltronClient responses. | 62598f9c090684286d5935b4 |
class Config: <NEW_LINE> <INDENT> def __init__(self, yaml_file): <NEW_LINE> <INDENT> with open(yaml_file, 'r') as f: <NEW_LINE> <INDENT> s = yaml.load(f) <NEW_LINE> <DEDENT> self.data_path = s['data'] <NEW_LINE> self.strategy = s['strategy'] <NEW_LINE> self.strategy_parameters = s['parameters'] <NEW_LINE> self.output_file = s['output']['file'] <NEW_LINE> self.show = s['show_plot'] <NEW_LINE> if self.show and (not HasMatplotlib): <NEW_LINE> <INDENT> self.show = False <NEW_LINE> log.warning('Matplotlib could not be imported. Plotting will be' 'disabled!') | Class representing the global configuration of the marketcrush scripts
Parameters
----------
yaml_file : string
The path to the yaml config file. For details on the yaml schema
see the marketcrush documentation | 62598f9ce76e3b2f99fd87eb |
class AlignmentQCReport(QCReport): <NEW_LINE> <INDENT> data_process = AlignmentQC <NEW_LINE> target_name = 'alignment' <NEW_LINE> data_file = AlnQCfile <NEW_LINE> file_target_name = 'alignmentqc' | Abstract class handling all alignment-based QC Reports. | 62598f9c596a897236127a35 |
class SQLTableExporter(DjangoModelExporter): <NEW_LINE> <INDENT> def __init__(self, session): <NEW_LINE> <INDENT> DjangoModelExporter.__init__(self) <NEW_LINE> self.session = session | public interface for sql table export | 62598f9cf8510a7c17d7e052 |
class Ports(APIClassTemplate): <NEW_LINE> <INDENT> URL_SUFFIX = "/object/ports" <NEW_LINE> def __init__(self, fmc, **kwargs): <NEW_LINE> <INDENT> super().__init__(fmc, **kwargs) <NEW_LINE> logging.debug("In __init__() for Ports class.") <NEW_LINE> self.parse_kwargs(**kwargs) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> logging.info("POST method for API for Ports not supported.") <NEW_LINE> pass <NEW_LINE> <DEDENT> def put(self): <NEW_LINE> <INDENT> logging.info("PUT method for API for Ports not supported.") <NEW_LINE> pass <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> logging.info("DELETE method for API for Ports not supported.") <NEW_LINE> pass | The Ports Object in the FMC. | 62598f9c442bda511e95c211 |
class NodeVisitor(object): <NEW_LINE> <INDENT> def visit(self, node): <NEW_LINE> <INDENT> method = 'visit_' + node.__class__.__name__ <NEW_LINE> visitor = getattr(self, method, self.generic_visit) <NEW_LINE> return visitor(node) <NEW_LINE> <DEDENT> def generic_visit(self, node): <NEW_LINE> <INDENT> for c_name, c in node.children(): <NEW_LINE> <INDENT> self.visit(c) | A base NodeVisitor class for visiting c_ast nodes.
Subclass it and define your own visit_XXX methods, where
XXX is the class name you want to visit with these
methods.
For example:
class ConstantVisitor(NodeVisitor):
def __init__(self):
self.values = []
def visit_Constant(self, node):
self.values.append(node.value)
Creates a list of values of all the bant nodes
encountered below the given node. To use it:
cv = ConstantVisitor()
cv.visit(node)
Notes:
* generic_visit() will be called for AST nodes for which
no visit_XXX method was defined.
* The children of nodes for which a visit_XXX was
defined will not be visited - if you need this, call
generic_visit() on the node.
You can use:
NodeVisitor.generic_visit(self, node)
* Modeled after Python's own AST visiting facilities
(the ast module of Python 3.0) | 62598f9c4527f215b58e9c98 |
class RegistroY600(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'Y600'), CampoData(2, 'DT_INCL_SOC'), CampoData(3, 'DT_FIM_SOC'), Campo(4, 'PAIS'), Campo(5, 'IND_QUALIF_SOCIO'), Campo(6, 'CPF_CNPJ'), Campo(7, 'NOM_EMP'), Campo(8, 'QUALIF'), CampoNumerico(9, 'PERC_CAP_TOT'), CampoNumerico(10, 'PERC_CAP_VOT'), Campo(11, 'CPF_REP_LEG'), Campo(12, 'QUALIF_REP_LEG'), ] | Identificação de Sócios ou Titular | 62598f9ca17c0f6771d5bff0 |
class TestHaskellComments(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 test_name_to_func_map(self): <NEW_LINE> <INDENT> test_file = 'tests/commentsForHaskell' <NEW_LINE> options = Namespace() <NEW_LINE> options.already = set() <NEW_LINE> options.ex_re = None <NEW_LINE> options.map_holder = MapHolder() <NEW_LINE> options.verbose = False <NEW_LINE> lines, sloc = count_lines_double_dash(test_file, options, 'occ') <NEW_LINE> self.assertEqual(lines, 27) <NEW_LINE> self.assertEqual(sloc, 10) | Test line counter for the Haskell programmig language. | 62598f9c009cb60464d012da |
class Interactive: <NEW_LINE> <INDENT> def __init__(self, f, event="auto", recompute_out_event="auto", *args, **kwargs): <NEW_LINE> <INDENT> from hyperspy.signal import BaseSignal <NEW_LINE> self.f = f <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> _plot_kwargs = self.kwargs.pop('_plot_kwargs', None) <NEW_LINE> if 'out' in self.kwargs: <NEW_LINE> <INDENT> self.f(*self.args, **self.kwargs) <NEW_LINE> self.out = self.kwargs.pop('out') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.out = self.f(*self.args, **self.kwargs) <NEW_LINE> <DEDENT> if _plot_kwargs and 'signal' in self.kwargs: <NEW_LINE> <INDENT> self.out._plot_kwargs = self.kwargs['signal']._plot_kwargs <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> fargs = list(inspect.signature(self.f).parameters.keys()) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> fargs = [] <NEW_LINE> <DEDENT> has_out = "out" in fargs <NEW_LINE> if hasattr(f, "__self__") and isinstance(f.__self__, BaseSignal): <NEW_LINE> <INDENT> if event == "auto": <NEW_LINE> <INDENT> event = self.f.__self__.events.data_changed <NEW_LINE> <DEDENT> if recompute_out_event == "auto": <NEW_LINE> <INDENT> recompute_out_event = self.f.__self__.axes_manager.events.any_axis_changed <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> event = None if event == "auto" else event <NEW_LINE> recompute_out_event = (None if recompute_out_event == "auto" else recompute_out_event) <NEW_LINE> <DEDENT> if recompute_out_event: <NEW_LINE> <INDENT> _connect_events(recompute_out_event, self.recompute_out) <NEW_LINE> <DEDENT> if event: <NEW_LINE> <INDENT> if has_out: <NEW_LINE> <INDENT> _connect_events(event, self.update) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _connect_events(event, self.recompute_out) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def recompute_out(self): <NEW_LINE> <INDENT> out = self.f(*self.args, **self.kwargs) <NEW_LINE> if out.data.shape == self.out.data.shape: <NEW_LINE> <INDENT> self.out.data[:] = out.data[:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.out.data = out.data <NEW_LINE> <DEDENT> self.out.axes_manager.update_axes_attributes_from( out.axes_manager._axes, attributes=["scale", "offset", "size"]) <NEW_LINE> self.out.events.data_changed.trigger(self.out) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.f(*self.args, out=self.out, **self.kwargs) | Chainable operations on Signals that update on events.
| 62598f9c45492302aabfc28d |
class Hook(Action): <NEW_LINE> <INDENT> def __init__(self, hook): <NEW_LINE> <INDENT> super(Hook, self).__init__(hook) | Base class for all python hackabot hooks | 62598f9cadb09d7d5dc0a33f |
class SlackNotificationError(BaseError): <NEW_LINE> <INDENT> pass | Raises error when a response code from Slack is not 200 | 62598f9c56b00c62f0fb2666 |
class Raw(Field): <NEW_LINE> <INDENT> pass | Field that applies no formatting or validation. | 62598f9ccc0a2c111447adc1 |
class PriorityLevel(IntEnum): <NEW_LINE> <INDENT> STANDARD = 0 <NEW_LINE> IFB = 1 | Possible priority levels. | 62598f9c45492302aabfc28e |
class QueueColumn(Column): <NEW_LINE> <INDENT> def __init__(self, name, wip_limit=None, card_type=None, card_source=None): <NEW_LINE> <INDENT> super(QueueColumn, self).__init__(name, touch=0, wip_limit=wip_limit, card_type=card_type, card_source=card_source) <NEW_LINE> <DEDENT> def next_card(self, card_type=None): <NEW_LINE> <INDENT> card = super(QueueColumn, self).next_card(card_type) <NEW_LINE> if card is None and self.card_source is not None: <NEW_LINE> <INDENT> card = self.card_source.next_card(card_type) <NEW_LINE> <DEDENT> return card <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<QueueColumn %s of %s>" % (self.name, self.lane.name if self.lane is not None else "<no lane>") | A queue column in a lane
name: name of the column
wip_limit: max number of cards allowed at any one time
card_type: the Card type (class) accepted, or None if all types accepted
card_source: the CardSource where this column pulls from
It is normally not necerssary to set card_source, because it is set when
the Board is wired up in the constructor. | 62598f9c30bbd72246469851 |
class UserGroupsEntity(object): <NEW_LINE> <INDENT> swagger_types = { 'user_groups': 'list[UserGroupEntity]' } <NEW_LINE> attribute_map = { 'user_groups': 'userGroups' } <NEW_LINE> def __init__(self, user_groups=None): <NEW_LINE> <INDENT> self._user_groups = None <NEW_LINE> if user_groups is not None: <NEW_LINE> <INDENT> self.user_groups = user_groups <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def user_groups(self): <NEW_LINE> <INDENT> return self._user_groups <NEW_LINE> <DEDENT> @user_groups.setter <NEW_LINE> def user_groups(self, user_groups): <NEW_LINE> <INDENT> self._user_groups = user_groups <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in 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> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return 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, UserGroupsEntity): <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. | 62598f9cd7e4931a7ef3be4e |
class DayGroupDay(models.Model): <NEW_LINE> <INDENT> objects = DayGroupDayManager() <NEW_LINE> daygroup = models.ForeignKey(DayGroup, on_delete=models.CASCADE) <NEW_LINE> day = models.ForeignKey(Day, on_delete=models.CASCADE) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ("day__number",) <NEW_LINE> unique_together = ( "daygroup", "day", ) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.daygroup.name) + str(self.day.number) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("daygroupday_detail", args=[str(self.id)]) | Day Group Day. | 62598f9c44b2445a339b6847 |
@view_config( route_name='ptahcrowd-login-success', renderer='ptahcrowd:login-success.lt', layout='ptahcrowd' ) <NEW_LINE> class LoginSuccess(ptah.View): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> user = ptah.auth_service.get_current_principal() <NEW_LINE> if user is None: <NEW_LINE> <INDENT> request = self.request <NEW_LINE> headers = security.forget(request) <NEW_LINE> return HTTPFound( headers=headers, location='%s/login.html' % request.application_url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.user = user.name | Login successful information page. | 62598f9ce5267d203ee6b6c3 |
class Debugger(DebugObject): <NEW_LINE> <INDENT> def __init__(self, project_id): <NEW_LINE> <INDENT> self._CheckClient() <NEW_LINE> self._project_id = project_id <NEW_LINE> self._project_number = str(self.GetProjectNumber(project_id)) <NEW_LINE> <DEDENT> @errors.HandleHttpError <NEW_LINE> def ListDebuggees(self, include_inactive=False): <NEW_LINE> <INDENT> request = messages.ClouddebuggerDebuggerDebuggeesListRequest( project=self._project_number, includeInactive=include_inactive) <NEW_LINE> response = self._debug_client.debugger_debuggees.List(request) <NEW_LINE> return [Debuggee(debuggee) for debuggee in response.debuggees] | Abstracts Cloud Debugger service for a project. | 62598f9ca05bb46b3848a635 |
class ajaxGetClients(BrowserView): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> CheckAuthenticator(self.request) <NEW_LINE> searchTerm = self.request.get('searchTerm', '').lower() <NEW_LINE> page = self.request.get('page', 1) <NEW_LINE> nr_rows = self.request.get('rows', 20) <NEW_LINE> sord = self.request.get('sord', 'asc') <NEW_LINE> sidx = self.request.get('sidx', '') <NEW_LINE> wf = getToolByName(self.context, 'portal_workflow') <NEW_LINE> clients = (x.getObject() for x in self.portal_catalog(portal_type="Client", inactive_state = 'active')) <NEW_LINE> rows = [{'ClientID': b.getClientID() and b.getClientID() or '', 'Title': b.Title() , 'ClientUID': b.UID()} for b in clients if b.Title().lower().find(searchTerm) > -1 or b.getClientID().lower().find(searchTerm) > -1 or b.Description().lower().find(searchTerm) > -1] <NEW_LINE> rows = sorted(rows, cmp=lambda x,y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'Title')) <NEW_LINE> if sord == 'desc': <NEW_LINE> <INDENT> rows.reverse() <NEW_LINE> <DEDENT> pages = len(rows) / int(nr_rows) <NEW_LINE> pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 <NEW_LINE> ret = {'page': page, 'total': pages, 'records': len(rows), 'rows': rows[(int(page) - 1) * int(nr_rows): int(page) * int(nr_rows)]} <NEW_LINE> return json.dumps(ret) | Vocabulary source for jquery combo dropdown box
| 62598f9c009cb60464d012db |
class PrivateUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = create_user( email='test@MAANTAITO.FI', password='Testtestpass123', name='name' ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrieve_profile_success(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email }) <NEW_LINE> <DEDENT> def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = {'name': 'new name', 'password': 'newpassword123'} <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(payload['password'])) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) | Test API requests that require authentication | 62598f9c8c0ade5d55dc356a |
class Eng_AllRunning(MultistateDerivedParameterNode): <NEW_LINE> <INDENT> name = 'Eng (*) All Running' <NEW_LINE> values_mapping = { 0 : 'Not Running', 1 : 'Running', } <NEW_LINE> @classmethod <NEW_LINE> def can_operate(cls, available): <NEW_LINE> <INDENT> return 'Eng (*) N1 Min' in available or 'Eng (*) N2 Min' in available or 'Eng (*) Fuel Flow Min' in available <NEW_LINE> <DEDENT> def derive(self, eng_n1=P('Eng (*) N1 Min'), eng_n2=P('Eng (*) N2 Min'), fuel_flow=P('Eng (*) Fuel Flow Min')): <NEW_LINE> <INDENT> if eng_n2 or fuel_flow: <NEW_LINE> <INDENT> n2_running = eng_n2.array > 10 if eng_n2 else np.ones_like(fuel_flow.array, dtype=bool) <NEW_LINE> fuel_flowing = fuel_flow.array > 50 if fuel_flow else np.ones_like(eng_n2.array, dtype=bool) <NEW_LINE> self.array = n2_running & fuel_flowing <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.array = eng_n1.array > 10 | Discrete parameter describing when all available engines are running.
TODO: Include Fuel cut-off switch if recorded?
TODO: Confirm that all engines were recording for the N2 Min / Fuel Flow
Min parameters - theoretically there could be only three engines in the
frame for a four engine aircraft. Use "Engine Count".
TODO: Support shutdown for Propellor aircraft that don't record fuel flow. | 62598f9cb7558d58954633e5 |
class MonitoringWindow(QtGui.QMainWindow): <NEW_LINE> <INDENT> closed = QtCore.pyqtSignal() <NEW_LINE> def __init__(self, main, feature, layer): <NEW_LINE> <INDENT> QtGui.QMainWindow.__init__(self, main.iface.mainWindow()) <NEW_LINE> self.main = main <NEW_LINE> self.feature = feature <NEW_LINE> self.layer = layer <NEW_LINE> self.setWindowTitle('Bewerk monitoring %s' % self.feature.attribute( 'uniek_id')) <NEW_LINE> self.monitoringWidget = MonitoringWidget(self, self.main, self.feature, self.layer) <NEW_LINE> self.setCentralWidget(self.monitoringWidget) <NEW_LINE> self.setMinimumSize(800, 1000) <NEW_LINE> <DEDENT> def closeEvent(self, event): <NEW_LINE> <INDENT> self.closed.emit() | Window showing the MonitoringWidget for a specific field. | 62598f9c0a50d4780f70518f |
class AssertionClient(object): <NEW_LINE> <INDENT> DEFAULT_GRANT_TYPE = None <NEW_LINE> ASSERTION_METHODS = {} <NEW_LINE> token_auth_class = None <NEW_LINE> def __init__(self, session, token_endpoint, issuer, subject, audience=None, grant_type=None, claims=None, token_placement='header', scope=None, **kwargs): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> if audience is None: <NEW_LINE> <INDENT> audience = token_endpoint <NEW_LINE> <DEDENT> self.token_endpoint = token_endpoint <NEW_LINE> if grant_type is None: <NEW_LINE> <INDENT> grant_type = self.DEFAULT_GRANT_TYPE <NEW_LINE> <DEDENT> self.grant_type = grant_type <NEW_LINE> self.issuer = issuer <NEW_LINE> self.subject = subject <NEW_LINE> self.audience = audience <NEW_LINE> self.claims = claims <NEW_LINE> self.scope = scope <NEW_LINE> if self.token_auth_class is not None: <NEW_LINE> <INDENT> self.token_auth = self.token_auth_class(None, token_placement, self) <NEW_LINE> <DEDENT> self._kwargs = kwargs <NEW_LINE> <DEDENT> @property <NEW_LINE> def token(self): <NEW_LINE> <INDENT> return self.token_auth.token <NEW_LINE> <DEDENT> @token.setter <NEW_LINE> def token(self, token): <NEW_LINE> <INDENT> self.token_auth.set_token(token) <NEW_LINE> <DEDENT> def refresh_token(self): <NEW_LINE> <INDENT> generate_assertion = self.ASSERTION_METHODS[self.grant_type] <NEW_LINE> assertion = generate_assertion( issuer=self.issuer, subject=self.subject, audience=self.audience, claims=self.claims, **self._kwargs ) <NEW_LINE> data = { 'assertion': to_native(assertion), 'grant_type': self.grant_type, } <NEW_LINE> if self.scope: <NEW_LINE> <INDENT> data['scope'] = self.scope <NEW_LINE> <DEDENT> return self._refresh_token(data) <NEW_LINE> <DEDENT> def _refresh_token(self, data): <NEW_LINE> <INDENT> resp = self.session.request( 'POST', self.token_endpoint, data=data, withhold_token=True) <NEW_LINE> token = resp.json() <NEW_LINE> if 'error' in token: <NEW_LINE> <INDENT> raise OAuth2Error( error=token['error'], description=token.get('error_description') ) <NEW_LINE> <DEDENT> self.token = token <NEW_LINE> return self.token | Constructs a new Assertion Framework for OAuth 2.0 Authorization Grants
per RFC7521_.
.. _RFC7521: https://tools.ietf.org/html/rfc7521 | 62598f9c442bda511e95c212 |
class GetReportCountTestResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) <NEW_LINE> <DEDENT> def get_Count(self): <NEW_LINE> <INDENT> return self._output.get('Count', None) | A ResultSet with methods tailored to the values returned by the GetReportCountTest Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62598f9c24f1403a9268578d |
class tanh(SimpleBlock): <NEW_LINE> <INDENT> def data_fn(self, args): <NEW_LINE> <INDENT> new_data = np.tanh(args.data) <NEW_LINE> return(new_data) <NEW_LINE> <DEDENT> def gradient_fn(self, args): <NEW_LINE> <INDENT> grad = 1 - np.tanh(args.data)**2 <NEW_LINE> return(grad) | vectorized tan h function on vectors | 62598f9c851cf427c66b807e |
class IdpProfileForm(happyforms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = IdpProfile <NEW_LINE> fields = ['privacy'] | Form for the IdpProfile model. | 62598f9ca8370b77170f0199 |
class Buller(Sprite): <NEW_LINE> <INDENT> def __init__(self,setting,screen,ship): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect(0,0,setting.buller_width, setting.buller_height) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.color = setting.buller_color <NEW_LINE> self.speed_factor = setting.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_buller(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen,self.color,self.rect) | 一个队飞机发射子弹管理的类 | 62598f9c32920d7e50bc5e0d |
class TaskFailedError(TaskError): <NEW_LINE> <INDENT> def __init__(self, code=4): <NEW_LINE> <INDENT> super(TaskFailedError, self).__init__(code) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'TaskFailedError({code})'.format(code=self.code) | Exception to indicate that a task execution has failed. Tasks can choose
to raise this exception directly or derive from a more specific exception
to provide more information about the error. | 62598f9cac7a0e7691f722c2 |
class RedisPort(object): <NEW_LINE> <INDENT> def __init__(self, redis_hosts, counter_keyname): <NEW_LINE> <INDENT> self.redis_hosts = redis_hosts <NEW_LINE> self.counter_keyname = counter_keyname <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _create_redis_client(cls, host, port): <NEW_LINE> <INDENT> client = redis.Redis(host, port) <NEW_LINE> client.ping() <NEW_LINE> return client <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _execute_pipelines(cls, pipelines): <NEW_LINE> <INDENT> for pipeline in pipelines: <NEW_LINE> <INDENT> pipeline.execute() <NEW_LINE> <DEDENT> <DEDENT> def migrate_keys(self, from_client, from_index, to_clients): <NEW_LINE> <INDENT> num = len(to_clients) <NEW_LINE> command_limit = num * 1000 <NEW_LINE> from_pipeline = from_client.pipeline() <NEW_LINE> to_pipelines = [] <NEW_LINE> for client in to_clients: <NEW_LINE> <INDENT> to_pipelines.append(client.pipeline()) <NEW_LINE> <DEDENT> keys = from_client.keys() <NEW_LINE> count = 0 <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> if key == self.counter_keyname: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> index = KeyHashUtil.get_index(key, num) <NEW_LINE> if index != from_index: <NEW_LINE> <INDENT> dump_data = from_client.dump(key) <NEW_LINE> to_pipelines[index].restore(key, 0, dump_data) <NEW_LINE> count += 1 <NEW_LINE> if count % command_limit == 0: <NEW_LINE> <INDENT> self._execute_pipelines(to_pipelines) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._execute_pipelines(to_pipelines) <NEW_LINE> count = 0 <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> index = KeyHashUtil.get_index(key, num) <NEW_LINE> if index != from_index: <NEW_LINE> <INDENT> from_pipeline.delete(key) <NEW_LINE> count += 1 <NEW_LINE> if count % 1000: <NEW_LINE> <INDENT> from_client.execute() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> from_pipeline.execute() <NEW_LINE> <DEDENT> def add_instances(self, add_hosts): <NEW_LINE> <INDENT> for host in add_hosts: <NEW_LINE> <INDENT> if host in self.redis_hosts: <NEW_LINE> <INDENT> raise Exception("host: %s already exists" % host) <NEW_LINE> <DEDENT> <DEDENT> current_clients = [] <NEW_LINE> extend_clients = [] <NEW_LINE> for host in self.redis_hosts: <NEW_LINE> <INDENT> client = self._create_redis_client(*host) <NEW_LINE> current_clients.append(client) <NEW_LINE> extend_clients.append(client) <NEW_LINE> <DEDENT> for host in add_hosts: <NEW_LINE> <INDENT> client = self._create_redis_client(*host) <NEW_LINE> extend_clients.append(client) <NEW_LINE> <DEDENT> for index, from_client in enumerate(current_clients): <NEW_LINE> <INDENT> self.migrate_keys(from_client, index, extend_clients) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def remove_instance(cls, remove_hosts): <NEW_LINE> <INDENT> pass | 将已有的redis instances中的数据迁移到其他节点上。
注意添加的redis instance的顺序一定要和以后利用SimpleRedisPort的顺序一样。
hosts格式: [("127.0.0.1", 6379), ("127.0.0.1", 6380)] | 62598f9c4a966d76dd5eec97 |
class ShowOspfNeighborSchema(MetaParser): <NEW_LINE> <INDENT> schema = { Optional('process_name'): str, 'vrfs': { Any(): { 'neighbors': { Optional(Any()): { 'priority': str, 'state': str, 'dead_time': str, 'address': str, 'interface': str, 'up_time': str } }, Optional('total_neighbor_count'): int } } } | Schema detail for:
* show ospf neighbor
* show ospf {process_name} neighbor
* show ospf vrf {vrf} neighbor
* show ospf {process} vrf {vrf} neighbor | 62598f9c009cb60464d012dc |
class Meta: <NEW_LINE> <INDENT> unique_together = (('gene', 'aa_reference', 'aa_position', 'aa_variant'),) | Defines combination of gene and amino acid change as unique. | 62598f9c38b623060ffa8e48 |
class Query(object): <NEW_LINE> <INDENT> def __init__(self, snmp_params): <NEW_LINE> <INDENT> self.snmp_query = snmp_manager.Interact(snmp_params) <NEW_LINE> <DEDENT> def supported(self): <NEW_LINE> <INDENT> validity = False <NEW_LINE> oid = '.1.3.6.1.4.1.9.9.87.1.4.1.1.18' <NEW_LINE> if self.snmp_query.oid_exists(oid) is True: <NEW_LINE> <INDENT> validity = True <NEW_LINE> <DEDENT> return validity <NEW_LINE> <DEDENT> def layer1(self): <NEW_LINE> <INDENT> final = defaultdict(lambda: defaultdict(dict)) <NEW_LINE> values = self.c2900portduplexstatus() <NEW_LINE> for key, value in values.items(): <NEW_LINE> <INDENT> final[key]['c2900PortDuplexStatus'] = value <NEW_LINE> <DEDENT> values = self.c2900portlinkbeatstatus() <NEW_LINE> for key, value in values.items(): <NEW_LINE> <INDENT> final[key]['c2900PortLinkbeatStatus'] = value <NEW_LINE> <DEDENT> return final <NEW_LINE> <DEDENT> def c2900portlinkbeatstatus(self): <NEW_LINE> <INDENT> data_dict = defaultdict(dict) <NEW_LINE> oid = '.1.3.6.1.4.1.9.9.87.1.4.1.1.18' <NEW_LINE> results = self.snmp_query.walk(oid, normalized=True) <NEW_LINE> for key, value in sorted(results.items()): <NEW_LINE> <INDENT> data_dict[int(key)] = value <NEW_LINE> <DEDENT> return data_dict <NEW_LINE> <DEDENT> def c2900portduplexstatus(self): <NEW_LINE> <INDENT> data_dict = defaultdict(dict) <NEW_LINE> oid = '.1.3.6.1.4.1.9.9.87.1.4.1.1.32' <NEW_LINE> results = self.snmp_query.walk(oid, normalized=True) <NEW_LINE> for key, value in sorted(results.items()): <NEW_LINE> <INDENT> data_dict[int(key)] = value <NEW_LINE> <DEDENT> return data_dict | Class interacts with CISCO-C2900-MIB.
Args:
None
Returns:
None
Key Methods:
supported: Queries the device to determine whether the MIB is
supported using a known OID defined in the MIB. Returns True
if the device returns a response to the OID, False if not.
layer1: Returns all needed layer 1 MIB information from the device.
Keyed by OID's MIB name (primary key), ifIndex (secondary key) | 62598f9c7b25080760ed725d |
class PlaneNormalizedCuts(SegmentationStrategy): <NEW_LINE> <INDENT> def __init__(self, affinity_method=None, cut_max_pen=0.01, cut_min_size=40, cut_max_size=200): <NEW_LINE> <INDENT> super(PlaneNormalizedCuts, self).__init__() <NEW_LINE> if affinity_method is None: <NEW_LINE> <INDENT> affinity_method = BasicAffinityMatrix(channel=0, num_pcs=75) <NEW_LINE> <DEDENT> d = locals() <NEW_LINE> d.pop('self') <NEW_LINE> self._params = Struct(**d) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _rois_from_cuts(cls, cuts): <NEW_LINE> <INDENT> ROIs = ROIList([]) <NEW_LINE> for cut in cuts: <NEW_LINE> <INDENT> if len(cut.indices): <NEW_LINE> <INDENT> mask = np.zeros(cut.shape) <NEW_LINE> for x in cut.indices: <NEW_LINE> <INDENT> mask[np.unravel_index(x, cut.shape)] = 1 <NEW_LINE> <DEDENT> ROIs.append(ROI(mask=mask)) <NEW_LINE> <DEDENT> <DEDENT> return ROIs <NEW_LINE> <DEDENT> @_check_single_plane <NEW_LINE> def _segment(self, dataset): <NEW_LINE> <INDENT> params = self._params <NEW_LINE> affinity = params.affinity_method.calculate(dataset) <NEW_LINE> shape = dataset.frame_shape[1:3] <NEW_LINE> cuts = itercut(affinity, shape, params.cut_max_pen, params.cut_min_size, params.cut_max_size) <NEW_LINE> return self._rois_from_cuts(cuts) | Segment image by iteratively performing normalized cuts.
Parameters
----------
affinity_method : AffinityMatrixMethod
The method used to calculate the affinity matrix.
max_pen : float
Iterative cutting will continue as long as the cut cost is less than
max_pen.
cut_min_size, cut_max_size : int
Regardless of the cut cost, iterative cutting will not be performed on
regions with fewer pixels than min_size and will always be performed
on regions larger than max_size.
Notes
-----
The normalized cut procedure [3]_ is iteratively applied, first to the
entire image, and then to each cut made from the previous application of
the procedure.
References
----------
.. [3] Jianbo Shi and Jitendra Malik. Normalized Cuts and Image
Segmentation. IEEE TRANSACTIONS ON PATTERN ANALYSIS AND MACHINE
INTELLIGENCE, VOL. 22, NO. 8, AUGUST 2000.
Warning
-------
In version 1.0.0, this method currently only works on datasets with a
single plane, or in conjunction with
:class:`sima.segment.PlaneWiseSegmentation`. | 62598f9c76e4537e8c3ef36d |
class TestComponentsComponentResponse(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 testComponentsComponentResponse(self): <NEW_LINE> <INDENT> pass | ComponentsComponentResponse unit test stubs | 62598f9c63d6d428bbee2569 |
class TotalWordsView(ListAPIView): <NEW_LINE> <INDENT> serializer_class = TotalWordsSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return TotalWords.objects.all() <NEW_LINE> <DEDENT> def get(self, request): <NEW_LINE> <INDENT> queryset = self.get_queryset() <NEW_LINE> serialized_data = self.serializer_class(queryset, many=True).data <NEW_LINE> total_json = dict() <NEW_LINE> for word in serialized_data: <NEW_LINE> <INDENT> total_json[word['word']] = word['word_count'] <NEW_LINE> <DEDENT> return Response(total_json) | View for listing word:word_count pairs. | 62598f9cb7558d58954633e6 |
class ProxyAdapterTestFixture(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.num_targets = 2 <NEW_LINE> self.test_servers = [] <NEW_LINE> self.ports = [] <NEW_LINE> self.target_config = "" <NEW_LINE> for _ in range(self.num_targets): <NEW_LINE> <INDENT> test_server = ProxyTestServer() <NEW_LINE> self.test_servers.append(test_server) <NEW_LINE> self.ports.append(test_server.port) <NEW_LINE> <DEDENT> self.target_config = ','.join([ "node_{}=http://127.0.0.1:{}/".format(tgt, port) for (tgt, port) in enumerate(self.ports) ]) <NEW_LINE> self.adapter_kwargs = { 'targets': self.target_config, 'request_timeout': 1.0, } <NEW_LINE> self.adapter = ProxyAdapter(**self.adapter_kwargs) <NEW_LINE> self.path = '' <NEW_LINE> self.request = Mock() <NEW_LINE> self.request.headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} <NEW_LINE> self.request.body = '{"pi":2.56}' <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> for target in self.adapter.targets: <NEW_LINE> <INDENT> target.http_client.close() <NEW_LINE> <DEDENT> for test_server in self.test_servers: <NEW_LINE> <INDENT> test_server.stop() <NEW_LINE> <DEDENT> <DEDENT> def clear_access_counts(self): <NEW_LINE> <INDENT> for test_server in self.test_servers: <NEW_LINE> <INDENT> test_server.clear_access_count() | Container class used in fixtures for testing proxy adapters. | 62598f9ca79ad16197769e1b |
class MinConflictsSolver(Solver): <NEW_LINE> <INDENT> def __init__(self, steps=1000): <NEW_LINE> <INDENT> self._steps = steps <NEW_LINE> self.GRID = [] <NEW_LINE> self.PG = None <NEW_LINE> self.SCREEN = None <NEW_LINE> self.CLOCK = None <NEW_LINE> self.steps = 0 <NEW_LINE> <DEDENT> def getSolution(self, domains, constraints, vconstraints,grid,pg,screen, smart_choice): <NEW_LINE> <INDENT> solution, self.steps = self.solve(domains, constraints, vconstraints,grid,pg,screen) <NEW_LINE> while solution is None and smart_choice: <NEW_LINE> <INDENT> solution, self.steps = self.solve(domains, constraints, vconstraints,grid,pg,screen) <NEW_LINE> print("Fallimento",self.steps) <NEW_LINE> <DEDENT> if solution is None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.steps <NEW_LINE> <DEDENT> <DEDENT> def solve(self, domains, constraints, vconstraints,grid,pg,screen): <NEW_LINE> <INDENT> self.GRID = grid <NEW_LINE> self.PG = pg <NEW_LINE> self.SCREEN = screen <NEW_LINE> assignments = {} <NEW_LINE> for variable in domains: <NEW_LINE> <INDENT> assignments[variable] = random.choice(domains[variable]) <NEW_LINE> <DEDENT> drawCurrentAssignemnt(assignments,self.GRID,self.PG,self.SCREEN) <NEW_LINE> for _ in xrange(self._steps): <NEW_LINE> <INDENT> conflicted = False <NEW_LINE> lst = list(domains.keys()) <NEW_LINE> random.shuffle(lst) <NEW_LINE> for variable in lst: <NEW_LINE> <INDENT> for constraint, variables in vconstraints[variable]: <NEW_LINE> <INDENT> if not constraint(variables, domains, assignments): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> mincount = len(vconstraints[variable]) <NEW_LINE> minvalues = [] <NEW_LINE> for value in domains[variable]: <NEW_LINE> <INDENT> assignments[variable] = value <NEW_LINE> count = 0 <NEW_LINE> for constraint, variables in vconstraints[variable]: <NEW_LINE> <INDENT> if not constraint(variables, domains, assignments): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> if count == mincount: <NEW_LINE> <INDENT> minvalues.append(value) <NEW_LINE> <DEDENT> elif count < mincount: <NEW_LINE> <INDENT> mincount = count <NEW_LINE> del minvalues[:] <NEW_LINE> minvalues.append(value) <NEW_LINE> <DEDENT> <DEDENT> assignments[variable] = random.choice(minvalues) <NEW_LINE> conflicted = True <NEW_LINE> <DEDENT> self.steps += 1 <NEW_LINE> drawCurrentAssignemnt(assignments,self.GRID,self.PG,self.SCREEN) <NEW_LINE> if not conflicted: <NEW_LINE> <INDENT> return assignments, self.steps <NEW_LINE> <DEDENT> <DEDENT> return None, self.steps | Problem solver based on the minimum conflicts theory
Examples:
>>> result = [[('a', 1), ('b', 2)],
... [('a', 1), ('b', 3)],
... [('a', 2), ('b', 3)]]
>>> problem = Problem(MinConflictsSolver())
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b > a, ["a", "b"])
>>> solution = problem.getSolution()
>>> sorted(solution.items()) in result
True
>>> problem.getSolutions()
Traceback (most recent call last):
...
NotImplementedError: MinConflictsSolver provides only a single solution
>>> problem.getSolutionIter()
Traceback (most recent call last):
...
NotImplementedError: MinConflictsSolver doesn't provide iteration | 62598f9c91f36d47f2230d7b |
class History(BaseObject): <NEW_LINE> <INDENT> def __init__(self, gox, timeframe): <NEW_LINE> <INDENT> BaseObject.__init__(self) <NEW_LINE> self.signal_changed = Signal() <NEW_LINE> self.gox = gox <NEW_LINE> self.candles = [] <NEW_LINE> self.timeframe = timeframe <NEW_LINE> gox.signal_trade.connect(self.slot_trade) <NEW_LINE> gox.signal_fullhistory.connect(self.slot_fullhistory) <NEW_LINE> <DEDENT> def add_candle(self, candle): <NEW_LINE> <INDENT> self._add_candle(candle) <NEW_LINE> self.signal_changed(self, (self.length())) <NEW_LINE> <DEDENT> def slot_trade(self, dummy_sender, data): <NEW_LINE> <INDENT> (date, price, volume, dummy_typ, own) = data <NEW_LINE> if not own: <NEW_LINE> <INDENT> time_round = int(date / self.timeframe) * self.timeframe <NEW_LINE> candle = self.last_candle() <NEW_LINE> if candle: <NEW_LINE> <INDENT> if candle.tim == time_round: <NEW_LINE> <INDENT> candle.update(price, volume) <NEW_LINE> self.signal_changed(self, (1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.debug("### opening new candle") <NEW_LINE> self.add_candle(OHLCV( time_round, price, price, price, price, volume)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.debug("### starting first candle") <NEW_LINE> self.add_candle(OHLCV( time_round, price, price, price, price, volume)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _add_candle(self, candle): <NEW_LINE> <INDENT> self.candles.insert(0, candle) <NEW_LINE> <DEDENT> def slot_fullhistory(self, dummy_sender, data): <NEW_LINE> <INDENT> (history) = data <NEW_LINE> if not len(history): <NEW_LINE> <INDENT> self.debug("### history download was empty") <NEW_LINE> return <NEW_LINE> <DEDENT> def get_time_round(date): <NEW_LINE> <INDENT> return int(date / self.timeframe) * self.timeframe <NEW_LINE> <DEDENT> date_begin = get_time_round(int(history[0]["date"])) <NEW_LINE> while len(self.candles) and self.candles[0].tim >= date_begin: <NEW_LINE> <INDENT> self.candles.pop(0) <NEW_LINE> <DEDENT> new_candle = OHLCV(0, 0, 0, 0, 0, 0) <NEW_LINE> count_added = 0 <NEW_LINE> for trade in history: <NEW_LINE> <INDENT> date = int(trade["date"]) <NEW_LINE> price = int(trade["price_int"]) <NEW_LINE> volume = int(trade["amount_int"]) <NEW_LINE> time_round = get_time_round(date) <NEW_LINE> if time_round > new_candle.tim: <NEW_LINE> <INDENT> if new_candle.tim > 0: <NEW_LINE> <INDENT> self._add_candle(new_candle) <NEW_LINE> count_added += 1 <NEW_LINE> <DEDENT> new_candle = OHLCV( time_round, price, price, price, price, volume) <NEW_LINE> <DEDENT> new_candle.update(price, volume) <NEW_LINE> <DEDENT> self._add_candle(new_candle) <NEW_LINE> count_added += 1 <NEW_LINE> self.debug("### got %d updated candle(s)" % count_added) <NEW_LINE> self.signal_changed(self, (self.length())) <NEW_LINE> <DEDENT> def last_candle(self): <NEW_LINE> <INDENT> if self.length() > 0: <NEW_LINE> <INDENT> return self.candles[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def length(self): <NEW_LINE> <INDENT> return len(self.candles) | represents the trading history | 62598f9c56b00c62f0fb2668 |
@dataclass <NEW_LINE> class RemoveTextDefinition(NodeTextDefinitionChange): <NEW_LINE> <INDENT> _inherited_slots: ClassVar[List[str]] = [] <NEW_LINE> class_class_uri: ClassVar[URIRef] = KGCL.RemoveTextDefinition <NEW_LINE> class_class_curie: ClassVar[str] = "kgcl:RemoveTextDefinition" <NEW_LINE> class_name: ClassVar[str] = "remove text definition" <NEW_LINE> class_model_uri: ClassVar[URIRef] = KGCL.RemoveTextDefinition <NEW_LINE> id: Union[str, RemoveTextDefinitionId] = None <NEW_LINE> old_value: Optional[str] = None <NEW_LINE> def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]): <NEW_LINE> <INDENT> if self._is_empty(self.id): <NEW_LINE> <INDENT> self.MissingRequiredField("id") <NEW_LINE> <DEDENT> if not isinstance(self.id, RemoveTextDefinitionId): <NEW_LINE> <INDENT> self.id = RemoveTextDefinitionId(self.id) <NEW_LINE> <DEDENT> if self.old_value is not None and not isinstance(self.old_value, str): <NEW_LINE> <INDENT> self.old_value = str(self.old_value) <NEW_LINE> <DEDENT> super().__post_init__(**kwargs) | A node change where a text definition is deleted | 62598f9c21a7993f00c65d39 |
class MultiprocessLivestreamRecordersController(MultiprocessRecordersController): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MultiprocessLivestreamRecordersController, self).__init__() <NEW_LINE> <DEDENT> def recording_stopped(self, context: Context, item: ContentItem): <NEW_LINE> <INDENT> context.bus.add_event(Event(type=Event.LIVESTREAM_INTERRUPTED, content=item)) <NEW_LINE> <DEDENT> def start_recording(self, context: Context, item: ContentItem): <NEW_LINE> <INDENT> self.active_recordings[item.video_id] = item <NEW_LINE> process = Process( name='ytarchiver-livestream-recorder', target=_livestream_recorder_task, args=(item, self.recorders_queue, context.logger) ) <NEW_LINE> process.start() | Livestreams recorder which starts new worker process every time it is invoked. | 62598f9cbaa26c4b54d4f064 |
class GroupChatSetModifyMyCardPage(BasePage): <NEW_LINE> <INDENT> ACTIVITY = 'com.cmcc.cmrcs.android.ui.activities.GroupCardActivity' <NEW_LINE> __locators = {'': (MobileBy.ID, ''), 'com.chinasofti.rcs:id/action_bar_root': (MobileBy.ID, 'com.chinasofti.rcs:id/action_bar_root'), 'android:id/content': (MobileBy.ID, 'android:id/content'), 'com.chinasofti.rcs:id/id_toolbar': (MobileBy.ID, 'com.chinasofti.rcs:id/id_toolbar'), 'com.chinasofti.rcs:id/back': (MobileBy.ID, 'com.chinasofti.rcs:id/back'), '修改群名片': (MobileBy.ID, 'com.chinasofti.rcs:id/title'), '保存': (MobileBy.ID, 'com.chinasofti.rcs:id/group_card_save'), '我的群名片': (MobileBy.ID, 'com.chinasofti.rcs:id/edit_query'), '删除': (MobileBy.ID, 'com.chinasofti.rcs:id/iv_delect') } <NEW_LINE> @TestLogger.log() <NEW_LINE> def wait_for_page_load(self, timeout=3, auto_accept_alerts=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.wait_until( timeout=timeout, auto_accept_permission_alert=auto_accept_alerts, condition=lambda d: self._is_element_present(self.__class__.__locators["修改群名片"]) ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> message = "页面在{}s内,没有加载成功".format(str(timeout)) <NEW_LINE> raise AssertionError( message ) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> @TestLogger.log() <NEW_LINE> def input_my_name(self, name): <NEW_LINE> <INDENT> self.input_text(self.__class__.__locators["我的群名片"], name) <NEW_LINE> try: <NEW_LINE> <INDENT> self.driver.hide_keyboard() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> @TestLogger.log() <NEW_LINE> def click_save(self): <NEW_LINE> <INDENT> self.click_element(self.__class__.__locators["保存"]) <NEW_LINE> <DEDENT> @TestLogger.log() <NEW_LINE> def save_btn_is_enabled(self): <NEW_LINE> <INDENT> return self._is_enabled(self.__class__.__locators["保存"]) <NEW_LINE> <DEDENT> @TestLogger.log() <NEW_LINE> def click_delete_my_name(self): <NEW_LINE> <INDENT> self.click_element(self.__class__.__locators["删除"]) <NEW_LINE> <DEDENT> @TestLogger.log() <NEW_LINE> def wait_for_modify_ok_tips_load(self, timeout=8, auto_accept_alerts=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.wait_until( timeout=timeout, auto_accept_permission_alert=auto_accept_alerts, condition=lambda d: self.is_toast_exist("修改成功", timeout) ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> message = "页面在{}s内,没有加载成功".format(str(timeout)) <NEW_LINE> raise AssertionError( message ) <NEW_LINE> <DEDENT> return self | 修改群名片页面 | 62598f9c01c39578d7f12b35 |
class ProductionConfig(): <NEW_LINE> <INDENT> SECRET_KEY = os.urandom(24) <NEW_LINE> SESSION_COOKIE_NAME = 'session name' <NEW_LINE> SESSION_PERMANENT = True | Set app config vars. | 62598f9cf548e778e596b363 |
class Author(models.Model): <NEW_LINE> <INDENT> author = models.CharField(max_length=255) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.author <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('author-detail', args=[str(self.id)]) | Book Author | 62598f9cbe8e80087fbbee16 |
class Check(base.Endpoint): <NEW_LINE> <INDENT> def register(self, name, script=None, check_id=None, interval=None, ttl=None, notes=None, http=None): <NEW_LINE> <INDENT> if script and not interval: <NEW_LINE> <INDENT> raise ValueError('Must specify interval when using script') <NEW_LINE> <DEDENT> elif script and ttl: <NEW_LINE> <INDENT> raise ValueError('Can not specify script and ttl together') <NEW_LINE> <DEDENT> if http and not interval: <NEW_LINE> <INDENT> raise ValueError('Must specify interval when using http') <NEW_LINE> <DEDENT> elif http and ttl: <NEW_LINE> <INDENT> raise ValueError('Can not specify http and ttl together') <NEW_LINE> <DEDENT> if http and script: <NEW_LINE> <INDENT> raise ValueError('Can not specify script and http together') <NEW_LINE> <DEDENT> return self._put_no_response_body(['register'], None, { 'ID': check_id, 'Name': name, 'Notes': notes, 'Script': script, 'HTTP': http, 'Interval': interval, 'TTL': ttl }) <NEW_LINE> <DEDENT> def deregister(self, check_id): <NEW_LINE> <INDENT> return self._get_no_response_body(['deregister', check_id]) <NEW_LINE> <DEDENT> def ttl_pass(self, check_id): <NEW_LINE> <INDENT> return self._get_no_response_body(['pass', check_id]) <NEW_LINE> <DEDENT> def ttl_warn(self, check_id): <NEW_LINE> <INDENT> return self._get_no_response_body(['warn', check_id]) <NEW_LINE> <DEDENT> def ttl_fail(self, check_id): <NEW_LINE> <INDENT> return self._get_no_response_body(['fail', check_id]) | One of the primary roles of the agent is the management of system
and application level health checks. A health check is considered to be
application level if it associated with a service. A check is defined
in a configuration file, or added at runtime over the HTTP interface.
There are two different kinds of checks:
- Script + Interval: These checks depend on invoking an external
application which does the health check and
exits with an appropriate exit code,
potentially generating some output. A script
is paired with an invocation interval
(e.g. every 30 seconds). This is similar to
the Nagios plugin system.
- TTL: These checks retain their last known state for a given TTL.
The state of the check must be updated periodically
over the HTTP interface. If an external system fails to
update the status within a given TTL, the check is set to
the failed state. This mechanism is used to allow an
application to directly report it's health. For example,
a web app can periodically curl the endpoint, and if the
app fails, then the TTL will expire and the health check
enters a critical state. This is conceptually similar to a
dead man's switch. | 62598f9cdd821e528d6d8ced |
class PrechatCapture(object): <NEW_LINE> <INDENT> openapi_types = { 'avatar_url': 'str', 'enabled': 'bool', 'enable_email_linking': 'bool', 'fields': 'list[Field]' } <NEW_LINE> attribute_map = { 'avatar_url': 'avatarUrl', 'enabled': 'enabled', 'enable_email_linking': 'enableEmailLinking', 'fields': 'fields' } <NEW_LINE> nulls = set() <NEW_LINE> def __init__(self, avatar_url='undefined', enabled=False, enable_email_linking=False, fields=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._avatar_url = None <NEW_LINE> self._enabled = None <NEW_LINE> self._enable_email_linking = None <NEW_LINE> self._fields = None <NEW_LINE> self.discriminator = None <NEW_LINE> if avatar_url is not None: <NEW_LINE> <INDENT> self.avatar_url = avatar_url <NEW_LINE> <DEDENT> if enabled is not None: <NEW_LINE> <INDENT> self.enabled = enabled <NEW_LINE> <DEDENT> if enable_email_linking is not None: <NEW_LINE> <INDENT> self.enable_email_linking = enable_email_linking <NEW_LINE> <DEDENT> if fields is not None: <NEW_LINE> <INDENT> self.fields = fields <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def avatar_url(self): <NEW_LINE> <INDENT> return self._avatar_url <NEW_LINE> <DEDENT> @avatar_url.setter <NEW_LINE> def avatar_url(self, avatar_url): <NEW_LINE> <INDENT> self._avatar_url = avatar_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def enabled(self): <NEW_LINE> <INDENT> return self._enabled <NEW_LINE> <DEDENT> @enabled.setter <NEW_LINE> def enabled(self, enabled): <NEW_LINE> <INDENT> self._enabled = enabled <NEW_LINE> <DEDENT> @property <NEW_LINE> def enable_email_linking(self): <NEW_LINE> <INDENT> return self._enable_email_linking <NEW_LINE> <DEDENT> @enable_email_linking.setter <NEW_LINE> def enable_email_linking(self, enable_email_linking): <NEW_LINE> <INDENT> self._enable_email_linking = enable_email_linking <NEW_LINE> <DEDENT> @property <NEW_LINE> def fields(self): <NEW_LINE> <INDENT> return self._fields <NEW_LINE> <DEDENT> @fields.setter <NEW_LINE> def fields(self, fields): <NEW_LINE> <INDENT> self._fields = fields <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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> 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, PrechatCapture): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PrechatCapture): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62598f9ca05bb46b3848a637 |
class FlowFailedError(Error): <NEW_LINE> <INDENT> pass | Raised when waiting on a flow that eventually fails. | 62598f9cc432627299fa2d90 |
class WeakTimer(notifier.WeakNotifierCallback, Timer): <NEW_LINE> <INDENT> pass | Weak variant of the Timer class.
All references to the callback and supplied args/kwargs are weak
references. When any of the underlying objects are deleted,
the WeakTimer is automatically stopped. | 62598f9c30dc7b766599f605 |
class HypixelSkyblockCollection: <NEW_LINE> <INDENT> def __init__(self, id: str, data: dict) -> None: <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self._id = id <NEW_LINE> self._name = None <NEW_LINE> self._items = tuple() <NEW_LINE> self.__parse_data() <NEW_LINE> <DEDENT> def __parse_data(self) -> None: <NEW_LINE> <INDENT> self._name = self._data.get('name', None) <NEW_LINE> self._items = tuple( HypixelSkyblockItemCollection(i, self._data.get('items')[i]) for i in self._data.get('items', {}).keys() ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self) -> str: <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self) -> Tuple[HypixelSkyblockItemCollection]: <NEW_LINE> <INDENT> return self._items | Object representing a Skyblock Collection | 62598f9c91af0d3eaad39bc2 |
class RecordingRegistrantStatus(object): <NEW_LINE> <INDENT> swagger_types = { 'action': 'str', 'registrants': 'list[MeetingsmeetingIdrecordingsregistrantsstatusRegistrants]' } <NEW_LINE> attribute_map = { 'action': 'action', 'registrants': 'registrants' } <NEW_LINE> def __init__(self, action=None, registrants=None): <NEW_LINE> <INDENT> self._action = None <NEW_LINE> self._registrants = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.action = action <NEW_LINE> if registrants is not None: <NEW_LINE> <INDENT> self.registrants = registrants <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def action(self): <NEW_LINE> <INDENT> return self._action <NEW_LINE> <DEDENT> @action.setter <NEW_LINE> def action(self, action): <NEW_LINE> <INDENT> if action is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `action`, must not be `None`") <NEW_LINE> <DEDENT> allowed_values = ["approve", "deny"] <NEW_LINE> if action not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `action` ({0}), must be one of {1}" .format(action, allowed_values) ) <NEW_LINE> <DEDENT> self._action = action <NEW_LINE> <DEDENT> @property <NEW_LINE> def registrants(self): <NEW_LINE> <INDENT> return self._registrants <NEW_LINE> <DEDENT> @registrants.setter <NEW_LINE> def registrants(self, registrants): <NEW_LINE> <INDENT> self._registrants = registrants <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(RecordingRegistrantStatus, 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, RecordingRegistrantStatus): <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. | 62598f9cd268445f26639a5f |
class ShoppingBasket(InjectionProvider): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.baskets = defaultdict(list) <NEW_LINE> <DEDENT> def acquire_injection(self, worker_ctx): <NEW_LINE> <INDENT> class Basket(object): <NEW_LINE> <INDENT> def __init__(self, basket): <NEW_LINE> <INDENT> self._basket = basket <NEW_LINE> self.worker_ctx = worker_ctx <NEW_LINE> <DEDENT> def add(self, item): <NEW_LINE> <INDENT> self._basket.append(item) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for item in self._basket: <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> user_id = worker_ctx.data['user_id'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise NotLoggedIn() <NEW_LINE> <DEDENT> return Basket(self.baskets[user_id]) | A shopping basket tied to the current ``user_id``.
| 62598f9c379a373c97d98dcd |
class RespCondition(common.QTICommentContainer, ConditionMixin): <NEW_LINE> <INDENT> XMLNAME = 'respcondition' <NEW_LINE> XMLATTR_continue = ('continueFlag', core.ParseYesNo, core.FormatYesNo) <NEW_LINE> XMLATTR_title = 'title' <NEW_LINE> XMLCONTENT = xml.ElementContent <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> common.QTICommentContainer.__init__(self, parent) <NEW_LINE> self.continueFlag = False <NEW_LINE> self.title = None <NEW_LINE> self.ConditionVar = common.ConditionVar(self) <NEW_LINE> self.SetVar = [] <NEW_LINE> self.DisplayFeedback = [] <NEW_LINE> self.RespCondExtension = None <NEW_LINE> <DEDENT> def get_children(self): <NEW_LINE> <INDENT> for child in common.QTICommentContainer.get_children(self): <NEW_LINE> <INDENT> yield child <NEW_LINE> <DEDENT> yield self.ConditionVar <NEW_LINE> for child in itertools.chain( self.SetVar, self.DisplayFeedback): <NEW_LINE> <INDENT> yield child <NEW_LINE> <DEDENT> if self.RespCondExtension: <NEW_LINE> <INDENT> yield self.RespCondExtension <NEW_LINE> <DEDENT> <DEDENT> def MigrateV2Rule(self, cMode, ruleContainer, log): <NEW_LINE> <INDENT> if self.continueFlag: <NEW_LINE> <INDENT> if not cMode: <NEW_LINE> <INDENT> ruleContainer = ruleContainer.add_child( qtiv2.processing.ResponseElse) <NEW_LINE> <DEDENT> rc = ruleContainer.add_child(qtiv2.processing.ResponseCondition) <NEW_LINE> rcIf = rc.add_child(qtiv2.processing.ResponseIf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if cMode: <NEW_LINE> <INDENT> rc = ruleContainer.add_child( qtiv2.processing.ResponseCondition) <NEW_LINE> ruleContainer = rc <NEW_LINE> rcIf = rc.add_child(qtiv2.processing.ResponseIf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rcIf = ruleContainer.add_child( qtiv2.processing.ResponseElseIf) <NEW_LINE> <DEDENT> <DEDENT> self.ConditionVar.MigrateV2Expression(rcIf, log) <NEW_LINE> for rule in self.SetVar: <NEW_LINE> <INDENT> rule.MigrateV2Rule(rcIf, log) <NEW_LINE> <DEDENT> for rule in self.DisplayFeedback: <NEW_LINE> <INDENT> rule.MigrateV2Rule(rcIf, log) <NEW_LINE> <DEDENT> return self.continueFlag, ruleContainer | This element contains the actual test to be applied to the user responses
to determine their correctness or otherwise. Each <respcondition> contains
an actual test, the assignment of a value to the associate scoring variables
and the identification of the feedback to be associated with the test::
<!ELEMENT respcondition (qticomment? , conditionvar , setvar* , displayfeedback* , respcond_extension?)>
<!ATTLIST respcondition
continue (Yes | No ) 'No'
title CDATA #IMPLIED > | 62598f9cd99f1b3c44d05468 |
class Adjective(ConjugationType): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def conforms_to(pos_info: List[str], base: str, c_type_info: str) -> bool: <NEW_LINE> <INDENT> return pos.Adjective.conforms_to(pos_info) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def conjugate(base: str, ending: str) -> str: <NEW_LINE> <INDENT> return base[:-1] + ending | 形容詞活用 | 62598f9cd486a94d0ba2bd8d |
class PublishDrop8Test(BaseTest): <NEW_LINE> <INDENT> fixtureCmds = [ "aptly repo create local1", "aptly repo create local2", "aptly repo add local1 ${files}/libboost-program-options-dev_1.49.0.1_i386.deb", "aptly repo add local2 ${files}", "aptly publish repo -keyring=${files}/aptly.pub -secret-keyring=${files}/aptly.sec -distribution=sq1 local1", "aptly publish repo -keyring=${files}/aptly.pub -secret-keyring=${files}/aptly.sec -distribution=sq2 local2", ] <NEW_LINE> runCmd = "aptly publish drop -skip-cleanup sq2" <NEW_LINE> gold_processor = BaseTest.expand_environ <NEW_LINE> def check(self): <NEW_LINE> <INDENT> super(PublishDrop8Test, self).check() <NEW_LINE> self.check_exists('public/dists/sq1') <NEW_LINE> self.check_not_exists('public/dists/sq2') <NEW_LINE> self.check_exists('public/pool/main/') <NEW_LINE> self.check_exists('public/pool/main/p/pyspi/pyspi_0.6.1-1.3.dsc') <NEW_LINE> self.check_exists('public/pool/main/p/pyspi/pyspi_0.6.1-1.3.diff.gz') <NEW_LINE> self.check_exists('public/pool/main/p/pyspi/pyspi_0.6.1.orig.tar.gz') <NEW_LINE> self.check_exists('public/pool/main/p/pyspi/pyspi-0.6.1-1.3.stripped.dsc') <NEW_LINE> self.check_exists('public/pool/main/b/boost-defaults/libboost-program-options-dev_1.49.0.1_i386.deb') | publish drop: skip component cleanup | 62598f9c596a897236127a38 |
class InboundNatRuleListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[InboundNatRule]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["InboundNatRule"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(InboundNatRuleListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | Response for ListInboundNatRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of inbound nat rules in a load balancer.
:type value: list[~azure.mgmt.network.v2019_07_01.models.InboundNatRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str | 62598f9c99cbb53fe6830c8a |
class Blockchain: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.blockchain = [Blockchain._create_genesis_block()] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _create_genesis_block(): <NEW_LINE> <INDENT> return Block(0, datetime.datetime.now(), 'genesis', '0') <NEW_LINE> <DEDENT> def latest(self): <NEW_LINE> <INDENT> return self.blockchain[-1] <NEW_LINE> <DEDENT> def add(self, blocks_to_add): <NEW_LINE> <INDENT> for _ in range(blocks_to_add): <NEW_LINE> <INDENT> block = self.latest() <NEW_LINE> self.blockchain.append(block.next_block()) <NEW_LINE> print(f"Block {block.index} has been added to the blockchain!") <NEW_LINE> print(f"Hash: {block.hash}\n") | A snakecoin blockchain. | 62598f9c0c0af96317c5613b |
class TestAccountBrokerBeforeMetadata(TestAccountBroker): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._imported_create_account_stat_table = AccountBroker.create_account_stat_table <NEW_LINE> AccountBroker.create_account_stat_table = premetadata_create_account_stat_table <NEW_LINE> broker = AccountBroker(':memory:', account='a') <NEW_LINE> broker.initialize(Timestamp('1').internal) <NEW_LINE> exc = None <NEW_LINE> with broker.get() as conn: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn.execute('SELECT metadata FROM account_stat') <NEW_LINE> <DEDENT> except BaseException as err: <NEW_LINE> <INDENT> exc = err <NEW_LINE> <DEDENT> <DEDENT> self.assert_('no such column: metadata' in str(exc)) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> AccountBroker.create_account_stat_table = self._imported_create_account_stat_table <NEW_LINE> broker = AccountBroker(':memory:', account='a') <NEW_LINE> broker.initialize(Timestamp('1').internal) <NEW_LINE> with broker.get() as conn: <NEW_LINE> <INDENT> conn.execute('SELECT metadata FROM account_stat') | Tests for AccountBroker against databases created before
the metadata column was added. | 62598f9c3cc13d1c6d465524 |
class TestNewActivity(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 testNewActivity(self): <NEW_LINE> <INDENT> pass | NewActivity unit test stubs | 62598f9cd7e4931a7ef3be51 |
class PermissionTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_get_methods(self): <NEW_LINE> <INDENT> permission = Permission("GRANT_READ", "PROJECT", "uuid") <NEW_LINE> self.assertEqual("GRANT_READ", permission.get_right()) <NEW_LINE> self.assertEqual("PROJECT", permission.get_target_type()) <NEW_LINE> self.assertEqual("uuid", permission.get_target_uuid()) <NEW_LINE> <DEDENT> def test_bad_inputs(self): <NEW_LINE> <INDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission(None, "PROJECT", "id") <NEW_LINE> <DEDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission("Not a right", "PROJECT", "id") <NEW_LINE> <DEDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission("Admin", "PROJECT", "id") <NEW_LINE> <DEDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission("ADMIN", None, "id") <NEW_LINE> <DEDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission("ADMIN", "not a target type", "id") <NEW_LINE> <DEDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission("ADMIN", "pROJECT", "id") <NEW_LINE> <DEDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> Permission("ADMIN", "PROJECT", None) | Unit tests for permission object
| 62598f9cfbf16365ca793e72 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.