code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Conditional(CodeGen): <NEW_LINE> <INDENT> def __init__(self, opt, indent, condition, content): <NEW_LINE> <INDENT> super(Conditional, self).__init__(opt, indent) <NEW_LINE> if condition: <NEW_LINE> <INDENT> self.content = content
A conditional block of code.
62598fb444b2445a339b69d6
class ComparisonTargetPermission(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> if view.action in ['list', 'retrieve']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if view.action == 'retrieve': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
List : anyone Create : X Retrieve : anyone Update : X Partial update : X Destroy : X
62598fb49c8ee823130401d6
class ImageType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'ImageType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('http://ddex.net/xml/avs/avs.xsd', 2574, 3) <NEW_LINE> _Documentation = 'A Type of Image.'
A Type of Image.
62598fb4adb09d7d5dc0a654
class checkNamespaceIteratorConflicts_result(object): <NEW_LINE> <INDENT> def __init__(self, ouch1=None, ouch2=None, ouch3=None,): <NEW_LINE> <INDENT> self.ouch1 = ouch1 <NEW_LINE> self.ouch2 = ouch2 <NEW_LINE> self.ouch3 = ouch3 <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch1 = AccumuloException() <NEW_LINE> self.ouch1.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch2 = AccumuloSecurityException() <NEW_LINE> self.ouch2.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch3 = NamespaceNotFoundException() <NEW_LINE> self.ouch3.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('checkNamespaceIteratorConflicts_result') <NEW_LINE> if self.ouch1 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch1', TType.STRUCT, 1) <NEW_LINE> self.ouch1.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ouch2 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch2', TType.STRUCT, 2) <NEW_LINE> self.ouch2.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ouch3 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch3', TType.STRUCT, 3) <NEW_LINE> self.ouch3.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - ouch1 - ouch2 - ouch3
62598fb457b8e32f52508180
class GradingSectionsTestRecipe(GradingSectionsTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.rub = baker.make_recipe("makeReports.gradedRubric",rubricVersion=self.r) <NEW_LINE> self.rInG = baker.make_recipe("makeReports.rubricItem",rubricVersion=self.r,section=1) <NEW_LINE> self.rInG2 = baker.make_recipe("makeReports.rubricItem",rubricVersion=self.r,section=2) <NEW_LINE> self.rInG3 = baker.make_recipe("makeReports.rubricItem",rubricVersion=self.r,section=3) <NEW_LINE> self.rInG4 = baker.make_recipe("makeReports.rubricItem",rubricVersion=self.r,section=4) <NEW_LINE> self.rI = baker.make_recipe("makeReports.gradedRubricItem", rubric=self.rub, item=self.rInG) <NEW_LINE> self.rI2 = baker.make_recipe("makeReports.gradedRubricItem", rubric=self.rub, item=self.rInG2) <NEW_LINE> self.rI3 = baker.make_recipe("makeReports.gradedRubricItem", rubric=self.rub, item=self.rInG3) <NEW_LINE> self.rI4 = baker.make_recipe("makeReports.gradedRubricItem", rubric=self.rub, item=self.rInG4) <NEW_LINE> self.rpt.rubric = self.rub <NEW_LINE> self.rpt.save()
Tests the grading sections using recipe based models
62598fb47d847024c075c485
class TestConfig(BaseTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> parser = RawConfigParser() <NEW_LINE> parser.read(TEST_CONFIG_FILE_PATH) <NEW_LINE> cls.old_fpath = parser.get("pysemantic", "specfile") <NEW_LINE> parser.set("pysemantic", "specfile", op.abspath(cls.old_fpath)) <NEW_LINE> with open(TEST_CONFIG_FILE_PATH, "w") as fileobj: <NEW_LINE> <INDENT> parser.write(fileobj) <NEW_LINE> <DEDENT> cls._parser = parser <NEW_LINE> pr.CONF_FILE_NAME = "test.conf" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls._parser.set("pysemantic", "specfile", cls.old_fpath) <NEW_LINE> with open(TEST_CONFIG_FILE_PATH, "w") as fileobj: <NEW_LINE> <INDENT> cls._parser.write(fileobj) <NEW_LINE> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.testParser = RawConfigParser() <NEW_LINE> for section in self._parser.sections(): <NEW_LINE> <INDENT> self.testParser.add_section(section) <NEW_LINE> for item in self._parser.items(section): <NEW_LINE> <INDENT> self.testParser.set(section, item[0], item[1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_loader_default_location(self): <NEW_LINE> <INDENT> cwd_file = op.join(os.getcwd(), "test.conf") <NEW_LINE> home_file = op.join(op.expanduser('~'), "test.conf") <NEW_LINE> try: <NEW_LINE> <INDENT> self.testParser.set("pysemantic", "specfile", os.getcwd()) <NEW_LINE> with open(cwd_file, "w") as fileobj: <NEW_LINE> <INDENT> self.testParser.write(fileobj) <NEW_LINE> <DEDENT> specfile = pr.get_default_specfile("pysemantic") <NEW_LINE> self.assertEqual(specfile, os.getcwd()) <NEW_LINE> os.unlink(cwd_file) <NEW_LINE> self.testParser.set("pysemantic", "specfile", op.expanduser('~')) <NEW_LINE> with open(home_file, "w") as fileobj: <NEW_LINE> <INDENT> self.testParser.write(fileobj) <NEW_LINE> <DEDENT> specfile = pr.get_default_specfile("pysemantic") <NEW_LINE> self.assertEqual(specfile, op.expanduser('~')) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.unlink(home_file)
Test the configuration management utilities.
62598fb4a05bb46b3848a933
class ExceptionManagerBase: <NEW_LINE> <INDENT> RAISE = 0 <NEW_LINE> PASS = 1 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.handlers = [] <NEW_LINE> self.policy = ExceptionManagerBase.RAISE <NEW_LINE> <DEDENT> def add_handler(self, cls): <NEW_LINE> <INDENT> if not cls in self.handlers: <NEW_LINE> <INDENT> self.handlers.append(cls) <NEW_LINE> <DEDENT> <DEDENT> def remove_handler(self, cls): <NEW_LINE> <INDENT> if cls in self.handlers: <NEW_LINE> <INDENT> self.handlers.remove(cls) <NEW_LINE> <DEDENT> <DEDENT> def handle_exception(self, inst): <NEW_LINE> <INDENT> ret = self.policy <NEW_LINE> for handler in self.handlers: <NEW_LINE> <INDENT> r = handler.handle_exception(inst) <NEW_LINE> if r == ExceptionManagerBase.PASS: <NEW_LINE> <INDENT> ret = r <NEW_LINE> <DEDENT> <DEDENT> return ret
ExceptionManager manages exceptions handlers.
62598fb456b00c62f0fb2980
class TopLevel(Resource): <NEW_LINE> <INDENT> decorators = [multi_auth.login_required] <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(self, *args, **kwargs) <NEW_LINE> self.debug = 0 <NEW_LINE> self.api = args[0] <NEW_LINE> if self.debug > 2: <NEW_LINE> <INDENT> mydebug(f"kwargs {kwargs}") <NEW_LINE> <DEDENT> if "entrypoint" in kwargs: <NEW_LINE> <INDENT> self.entrypoint = kwargs["entrypoint"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.entrypoint = "/api/v1.0" <NEW_LINE> <DEDENT> <DEDENT> def get(self, subpath=None): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print("path", subpath) <NEW_LINE> <DEDENT> mydebug(f"path {subpath}") <NEW_LINE> return redirect(self.entrypoint) <NEW_LINE> <DEDENT> def post(self, subpath=None): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print("path", subpath) <NEW_LINE> <DEDENT> return redirect(self.entrypoint) <NEW_LINE> <DEDENT> def put(self, subpath=None): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print("path", subpath) <NEW_LINE> <DEDENT> return redirect(self.entrypoint) <NEW_LINE> <DEDENT> def delete(self, subpath=None): <NEW_LINE> <INDENT> if self.debug: <NEW_LINE> <INDENT> print("path", subpath) <NEW_LINE> <DEDENT> if ("FLASK_ENV" in os.environ) and (os.environ["FLASK_ENV"] == "development"): <NEW_LINE> <INDENT> sys.exit(255) <NEW_LINE> <DEDENT> return redirect(self.entrypoint)
Simple resource to redirect to the correct entry point.
62598fb430bbd722464699dd
class Frame_order(GuiTestCase, system_tests.frame_order.Frame_order): <NEW_LINE> <INDENT> def __init__(self, methodName=None): <NEW_LINE> <INDENT> super(Frame_order, self).__init__(methodName) <NEW_LINE> whitelist = [ 'test_cam_iso_cone' ] <NEW_LINE> if methodName not in whitelist: <NEW_LINE> <INDENT> status.skipped_tests.append([methodName, None, self._skip_type]) <NEW_LINE> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> GuiTestCase.setUp(self) <NEW_LINE> system_tests.frame_order.Frame_order.setUp(self)
Class for testing the frame order related functions in the GUI.
62598fb4be8e80087fbbf12f
class TestDeDe: <NEW_LINE> <INDENT> def test_city(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> city = faker.city() <NEW_LINE> assert isinstance(city, str) <NEW_LINE> assert city in DeDeAddressProvider.cities <NEW_LINE> <DEDENT> <DEDENT> def test_state(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> state = faker.state() <NEW_LINE> assert isinstance(state, str) <NEW_LINE> assert state in DeDeAddressProvider.states <NEW_LINE> <DEDENT> <DEDENT> def test_street_suffix_short(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> street_suffix_short = faker.street_suffix_short() <NEW_LINE> assert isinstance(street_suffix_short, str) <NEW_LINE> assert street_suffix_short in DeDeAddressProvider.street_suffixes_short <NEW_LINE> <DEDENT> <DEDENT> def test_street_suffix_long(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> street_suffix_long = faker.street_suffix_long() <NEW_LINE> assert isinstance(street_suffix_long, str) <NEW_LINE> assert street_suffix_long in DeDeAddressProvider.street_suffixes_long <NEW_LINE> <DEDENT> <DEDENT> def test_country(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> country = faker.country() <NEW_LINE> assert isinstance(country, str) <NEW_LINE> assert country in DeDeAddressProvider.countries <NEW_LINE> <DEDENT> <DEDENT> def test_postcode(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> postcode = faker.postcode() <NEW_LINE> assert isinstance(postcode, str) <NEW_LINE> assert re.fullmatch(r"\d{5}", postcode) <NEW_LINE> <DEDENT> <DEDENT> def test_city_with_postcode(self, faker, num_samples): <NEW_LINE> <INDENT> for _ in range(num_samples): <NEW_LINE> <INDENT> city_with_postcode = faker.city_with_postcode() <NEW_LINE> assert isinstance(city_with_postcode, str) <NEW_LINE> match = re.fullmatch(r"\d{5} (?P<city>.*)", city_with_postcode) <NEW_LINE> assert match.groupdict()["city"] in DeDeAddressProvider.cities
Test de_DE address provider methods
62598fb466656f66f7d5a4b9
class Field(AbstractField): <NEW_LINE> <INDENT> form = models.ForeignKey("Form", related_name="fields", on_delete=models.CASCADE) <NEW_LINE> order = models.IntegerField(_("Order"), null=True, blank=True) <NEW_LINE> class Meta(AbstractField.Meta): <NEW_LINE> <INDENT> ordering = ("order",) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.order is None: <NEW_LINE> <INDENT> self.order = self.form.fields.count() <NEW_LINE> <DEDENT> if not self.slug: <NEW_LINE> <INDENT> slug = slugify(self).replace('-', '_') <NEW_LINE> self.slug = unique_slug(self.form.fields, "slug", slug) <NEW_LINE> <DEDENT> super(Field, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> fields_after = self.form.fields.filter(order__gte=self.order) <NEW_LINE> fields_after.update(order=models.F("order") - 1) <NEW_LINE> super(Field, self).delete(*args, **kwargs)
Implements automated field ordering.
62598fb4a8370b77170f04a5
class KuramotoIndex(metrics_base.BaseTimeseriesMetricAlgorithm): <NEW_LINE> <INDENT> def evaluate(self): <NEW_LINE> <INDENT> if self.time_series.data.shape[1] < 2: <NEW_LINE> <INDENT> msg = " The number of state variables should be at least 2." <NEW_LINE> self.log.error(msg) <NEW_LINE> raise Exception(msg) <NEW_LINE> <DEDENT> theta_sum = numpy.sum(numpy.exp(0.0 + 1j * (numpy.vectorize(cmath.polar) (numpy.vectorize(complex)(self.time_series.data[:, 0, :, 0], self.time_series.data[:, 1, :, 0]))[1])), axis=1) <NEW_LINE> result = numpy.vectorize(cmath.polar)(theta_sum / self.time_series.data.shape[2]) <NEW_LINE> return result[0].mean()
Return the Kuramoto synchronization index. Useful metric for a parameter analysis when the collective brain dynamics represent coupled oscillatory processes. The *order* parameters are :math:`r` and :math:`Psi`. .. math:: r e^{i * \psi} = \frac{1}{N}\,\sum_{k=1}^N(e^{i*\theta_k}) The first is the phase coherence of the population of oscillators (KSI) and the second is the average phase. When :math:`r=0` means 0 coherence among oscillators. Input: TimeSeries DataType Output: Float This is a crude indicator of synchronization among nodes over the entire network. #NOTE: For the time being it is meant to be another global metric. However, it should be consider to have a sort of TimeSeriesDatatype for this analyzer.
62598fb401c39578d7f12e42
class LeaderAssignor(Service, LeaderAssignorT): <NEW_LINE> <INDENT> def __init__(self, app: AppT, **kwargs: Any) -> None: <NEW_LINE> <INDENT> Service.__init__(self, **kwargs) <NEW_LINE> self.app = app <NEW_LINE> <DEDENT> async def on_start(self) -> None: <NEW_LINE> <INDENT> leader_topic = self._leader_topic <NEW_LINE> await leader_topic.maybe_declare() <NEW_LINE> self.app.topics.add(leader_topic) <NEW_LINE> self.app.consumer.randomly_assigned_topics.add( leader_topic.get_topic_name()) <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def _leader_topic(self) -> TopicT: <NEW_LINE> <INDENT> return self.app.topic( self._leader_topic_name, partitions=1, acks=False, internal=True, ) <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def _leader_topic_name(self) -> str: <NEW_LINE> <INDENT> return f'{self.app.conf.id}-__assignor-__leader' <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def _leader_tp(self) -> TP: <NEW_LINE> <INDENT> return TP(self._leader_topic_name, 0) <NEW_LINE> <DEDENT> def is_leader(self) -> bool: <NEW_LINE> <INDENT> return self._leader_tp in self.app.consumer.assignment()
Leader assignor, ensures election of a leader.
62598fb432920d7e50bc611c
class PathHash: <NEW_LINE> <INDENT> def hash(self, items): <NEW_LINE> <INDENT> node = self <NEW_LINE> for part in items: <NEW_LINE> <INDENT> node = node[part] <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def alias(self, target, alias): <NEW_LINE> <INDENT> original = None if alias not in self else self[alias] <NEW_LINE> self[alias] = target <NEW_LINE> return original <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.nodes = collections.defaultdict(PathHash) <NEW_LINE> return <NEW_LINE> <DEDENT> def __contains__(self, name): <NEW_LINE> <INDENT> return name in self.nodes <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> return self.nodes[name] <NEW_LINE> <DEDENT> def __setitem__(self, name, key): <NEW_LINE> <INDENT> self.nodes[name] = key <NEW_LINE> return <NEW_LINE> <DEDENT> def dump(self, graphic=''): <NEW_LINE> <INDENT> for name, node in self.nodes.items(): <NEW_LINE> <INDENT> print("{}{!r}".format(graphic, name)) <NEW_LINE> node.dump(graphic=graphic+' ') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> __slots__ = ["nodes"]
Implementation of a hash function for hierarchical namespaces with aliased entries. PathHash encodes the hierarchical relationships among its contents by having each node in the hierarchy store the names of the nodes that are its immediate children. Aliases are permitted and they hash to the same key as the original entry. PathHash does not provide storage for any values associated with the names of the various levels in the hierarchy; that's the responsibility of the client. One implementation strategy is to create a dictionary at the client side that maps the keys generated by PathHash to the associated values.
62598fb48e7ae83300ee916d
@world.absorb <NEW_LINE> class GroupFactory(sf.GroupFactory): <NEW_LINE> <INDENT> pass
Groups for user permissions for courses
62598fb44c3428357761a383
class ApplicationSessionFactory(FutureMixin, protocol.ApplicationSessionFactory): <NEW_LINE> <INDENT> session = ApplicationSession
WAMP application session factory for Twisted-based applications.
62598fb43d592f4c4edbaf89
class ANSIFormatter(logging.Formatter): <NEW_LINE> <INDENT> BLACK = '\033[1;30m%s\033[0m' <NEW_LINE> RED = '\033[1;31m%s\033[0m' <NEW_LINE> GREEN = '\033[1;32m%s\033[0m' <NEW_LINE> YELLOW = '\033[1;33m%s\033[0m' <NEW_LINE> GREY = '\033[1;37m%s\033[0m' <NEW_LINE> RED_UNDERLINE = '\033[4;31m%s\033[0m' <NEW_LINE> def __init__(self, fmt='[%(levelname)s] %(name)s: %(message)s'): <NEW_LINE> <INDENT> logging.Formatter.__init__(self, fmt) <NEW_LINE> <DEDENT> def format(self, record): <NEW_LINE> <INDENT> keywords = {'skip': self.BLACK, 'create': self.GREEN, 'identical': self.BLACK, 'update': self.YELLOW, 're-initialized': self.YELLOW, 'remove': self.BLACK, 'notice': self.BLACK, 'execute': self.BLACK} <NEW_LINE> if record.levelno in (SKIP, INFO): <NEW_LINE> <INDENT> for item in keywords: <NEW_LINE> <INDENT> if record.msg.startswith(item): <NEW_LINE> <INDENT> record.msg = record.msg.replace(item, ' '*2 + keywords[item] % item.rjust(9)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif record.levelno >= logging.WARN: <NEW_LINE> <INDENT> record.levelname = record.levelname.replace('WARNING', 'WARN') <NEW_LINE> record.msg = ''.join([' '*2, self.RED % record.levelname.lower().rjust(9), ' ', record.msg]) <NEW_LINE> <DEDENT> return logging.Formatter.format(self, record)
Implements basic colored output using ANSI escape codes. Currently acrylamid uses nanoc's color and information scheme: skip, create, identical, update, re-initialized, removed. If log level is greater than logging.WARN the level name is printed red underlined.
62598fb456ac1b37e63022b3
class PublishLongNew(APIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated, ) <NEW_LINE> def post(self, request, format=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request_data = self.request.data['newData'] <NEW_LINE> user = request.user <NEW_LINE> data_to_save = dict({'new_title': request_data['title'], 'headline1': request_data['headline1'], 'headline2': request_data['headline2'], 'headline3': request_data['headline3'], 'content': request_data['content'], 'tables': request_data['references']['tables'], 'charts': request_data['references']['charts'], 'created_by': user.username}) <NEW_LINE> serializer = NewSerializer(data=data_to_save) <NEW_LINE> if serializer.is_valid(raise_exception=True): <NEW_LINE> <INDENT> serializer.create(serializer.validated_data) <NEW_LINE> <DEDENT> <DEDENT> except ParseError: <NEW_LINE> <INDENT> return Response(None, status=400, content_type=json) <NEW_LINE> <DEDENT> except DatabaseError: <NEW_LINE> <INDENT> return Response(None, status=400, content_type=json) <NEW_LINE> <DEDENT> except ValidationError: <NEW_LINE> <INDENT> return Response(None, status=400, content_type=json) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(None, status=200, content_type=json)
Class dedicated to API call 'createnew/publishlongnew', authentication required. Method post - Create 'New' model object.
62598fb4097d151d1a2c10f7
class OperationsHandlerMixin: <NEW_LINE> <INDENT> csrf_exempt = False <NEW_LINE> exports = None <NEW_LINE> anonymous = None <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> op = request.GET.get("op") or request.POST.get("op") <NEW_LINE> signature = request.method.upper(), op <NEW_LINE> function = self.exports.get(signature) <NEW_LINE> if function is None: <NEW_LINE> <INDENT> raise ("Unrecognised signature: method=%s op=%s" % signature) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return function(self, request, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def decorate(cls, func): <NEW_LINE> <INDENT> cls.exports = { name: func(export) for name, export in cls.exports.items() } <NEW_LINE> if cls.anonymous is not None and bool(cls.anonymous): <NEW_LINE> <INDENT> if issubclass(cls.anonymous, OperationsHandlerMixin): <NEW_LINE> <INDENT> cls.anonymous.decorate(func)
Handler mixin for operations dispatch. This enabled dispatch to custom functions that piggyback on HTTP methods that ordinarily, in Piston, are used for CRUD operations. This must be used in cooperation with :class:`OperationsResource` and :class:`OperationsHandlerType`.
62598fb44428ac0f6e6585e9
class BgpServiceCommunityListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[BgpServiceCommunity]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["BgpServiceCommunity"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(BgpServiceCommunityListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
Response for the ListServiceCommunity API service call. :param value: A list of service community resources. :type value: list[~azure.mgmt.network.v2018_01_01.models.BgpServiceCommunity] :param next_link: The URL to get the next set of results. :type next_link: str
62598fb4a8370b77170f04a6
class ISOExtra(object): <NEW_LINE> <INDENT> def __init__(self, element_type, source, destination): <NEW_LINE> <INDENT> self.element_type = element_type <NEW_LINE> self.source = source <NEW_LINE> self.destination = destination
Class that represents an extra element to add to an installation ISO. Objects of this type contain 3 pieces of information: element_type - "file" or "directory" source - A source URL for the element. destination - A relative destination for the element.
62598fb471ff763f4b5e783d
class HTMLResponse(Response): <NEW_LINE> <INDENT> def __init__(self, content='', printed_output=''): <NEW_LINE> <INDENT> Response.__init__(self, content) <NEW_LINE> self.printed_output = printed_output <NEW_LINE> self.headers['Content-type'] = 'text/html' <NEW_LINE> self.headers['Cache-Control'] = 'no-cache' <NEW_LINE> self.headers['X-FRAME-OPTIONS'] = 'DENY' <NEW_LINE> <DEDENT> def render_doc(self): <NEW_LINE> <INDENT> tpl = self.content.replace('{*PRINTED*}', self.printed_output) <NEW_LINE> doc = tpl.encode('utf-8') <NEW_LINE> return doc
HTML response >>> import response >>> response.HTMLResponse('test123').render() == ( ... 'X-FRAME-OPTIONS: DENY\n' ... 'Content-type: text/html\n' ... 'Content-length: 7\n' ... 'Cache-Control: no-cache\n\n' ... 'test123' ... ) True >>> response.HTMLResponse('test123').render_wsgi() == ( ... '200 OK', ... [ ... ('X-FRAME-OPTIONS', 'DENY'), ... ('Content-type', 'text/html'), ... ('Cache-Control', 'no-cache'), ... ('Content-length', '7') ... ], ... 'test123' ... ) True
62598fb47c178a314d78d566
class RandomPlanarGraph(UndirectedGraph): <NEW_LINE> <INDENT> def __init__(self, geometry, count): <NEW_LINE> <INDENT> super(RandomPlanarGraph, self).__init__() <NEW_LINE> self.geometry = geometry <NEW_LINE> configurations = numpy.array([ geometry.sample_configuration() for _ in xrange(5 * count)]) <NEW_LINE> self.configurations = metis.geometry.sparsify_point_set( configurations, count) <NEW_LINE> self.delaunay = Delaunay(self.configurations, incremental=True) <NEW_LINE> <DEDENT> def __contains__(self, vertex): <NEW_LINE> <INDENT> return 0 <= vertex < len(self.configurations) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "RandomPlanarGraph(configurations={})".format( repr(self.configurations)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "RandomPlanarGraph(count={})".format(len(self.configurations)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.configurations) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(xrange(len(self.configurations))) <NEW_LINE> <DEDENT> def __getitem__(self, vertex): <NEW_LINE> <INDENT> return self.configurations[vertex] <NEW_LINE> <DEDENT> def neighbors(self, vertex): <NEW_LINE> <INDENT> indices, indptr = self.delaunay.vertex_neighbor_vertices <NEW_LINE> for neighbor in indptr[indices[vertex]:indices[vertex+1]]: <NEW_LINE> <INDENT> yield neighbor <NEW_LINE> <DEDENT> <DEDENT> def cost(self, parent, child): <NEW_LINE> <INDENT> if self.geometry.path_is_free(self.configurations[parent], self.configurations[child]): <NEW_LINE> <INDENT> return distance.euclidean(self.configurations[parent], self.configurations[child]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return float('inf')
Random planar graph in R^2 This is mostly useful for debugging and demonstration; because it is planar, it is easier to parse visually than an RGG. The construction employs uses a Delauanay triangulation to select edges, optionally removing any edges which intersect some geometry. Vertex labels are just indices of an array of points, so any integer between 0 and `count-1`. Args: geometry (metis.geometry.Geometry): object describing problem geometry count (int): number of vertices in the graph Attributes: geometry (metis.geometry.Geometry): object describing problem geometry configurations (numpy.array): a (count x 2) array of samples corresponding to vertices. Each row is a sample from the 2D configuration space defined by the geometry. delaunay: the Delaunay triangulation of the vertices in the graph.
62598fb4adb09d7d5dc0a656
class IfFeatureNode(Node): <NEW_LINE> <INDENT> child_nodelists = ('nodelist_true', 'nodelist_false') <NEW_LINE> def __init__(self, nodelist_enabled, nodelist_disabled, feature_id, extra_kwargs): <NEW_LINE> <INDENT> self.nodelist_enabled = nodelist_enabled <NEW_LINE> self.nodelist_disabled = nodelist_disabled <NEW_LINE> self.feature_id = feature_id <NEW_LINE> self.extra_kwargs = extra_kwargs <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<IfFeatureNode for %s>' % self.feature_id <NEW_LINE> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> feature_id = self.feature_id.resolve(context, True) <NEW_LINE> extra_kwargs = { key: value.resolve(context) for key, value in six.iteritems(self.extra_kwargs) } <NEW_LINE> feature = get_features_registry().get_feature(feature_id) <NEW_LINE> if feature: <NEW_LINE> <INDENT> enabled = feature.is_enabled(request=context.get('request'), **extra_kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> enabled = False <NEW_LINE> <DEDENT> if enabled: <NEW_LINE> <INDENT> return self.nodelist_enabled.render(context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.nodelist_disabled.render(context)
Template node for feature-based if statements. This works mostly like a standard ``{% if %}`` tag, checking whether the given feature is enabled and rendering the content between it and the else/end tags only if matching the desired state. This supports a ``{% else %}``, to allow rendering content if the feature does not match the desired state. This is used by both the :py:class:`{% if_feature_enabled %} <if_feature_enabled>` and :py:class:`{% if_feature_disabled %} <if_feature_disabled>` tags.
62598fb42ae34c7f260ab1a5
class MetaBeing(Being): <NEW_LINE> <INDENT> pass
complement of being
62598fb4f548e778e596b66d
class PSSM: <NEW_LINE> <INDENT> def __init__(self, description=""): <NEW_LINE> <INDENT> self.description = description <NEW_LINE> self.seqCount = 0 <NEW_LINE> self.size = None <NEW_LINE> self.aaDistribution = None <NEW_LINE> self.aaCount = None <NEW_LINE> self.gapPenalties = None <NEW_LINE> <DEDENT> def add(self, Sequence): <NEW_LINE> <INDENT> if self.size is None: <NEW_LINE> <INDENT> self.size = len(Sequence) <NEW_LINE> self.aaDistribution = [{} for i in range(self.size)] <NEW_LINE> self.aaCount = [0 for i in range(self.size)] <NEW_LINE> self.gapPenalties = [0 for i in range(self.size + 1)] <NEW_LINE> <DEDENT> assert (len(Sequence) == self.size) <NEW_LINE> for index in range(self.size): <NEW_LINE> <INDENT> if not Sequence[index].isGap(): <NEW_LINE> <INDENT> self.aaCount[index] += 1 <NEW_LINE> try: <NEW_LINE> <INDENT> self.aaDistribution[index][Sequence[index]] += 1 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.aaDistribution[index][Sequence[index]] = 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.seqCount += 1 <NEW_LINE> <DEDENT> def getDescription(self): <NEW_LINE> <INDENT> return self.description <NEW_LINE> <DEDENT> def getScore(self, aminoAcid, columnIndex): <NEW_LINE> <INDENT> alpha = self.aaCount[columnIndex] - 1 <NEW_LINE> beta = sqrt(self.seqCount) <NEW_LINE> alphaplusbeta = alpha + beta <NEW_LINE> try: <NEW_LINE> <INDENT> p_aa = uniprob[aminoAcid] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> p_aa = 0.001 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> f_aa = self.aaDistribution[columnIndex][aminoAcid] / self.seqCount <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> f_aa = 0 <NEW_LINE> <DEDENT> q_aa = (alpha * f_aa + beta * p_aa) / alphaplusbeta <NEW_LINE> return log(q_aa / p_aa) <NEW_LINE> <DEDENT> def getGapPenalty(self, columnIndex): <NEW_LINE> <INDENT> return self.gapPenalties[columnIndex] <NEW_LINE> <DEDENT> def setGapPenalty(self, penalty, columnIndex=None): <NEW_LINE> <INDENT> if columnIndex is None: <NEW_LINE> <INDENT> for i in range(self.size): <NEW_LINE> <INDENT> self.gapPenalties[i] = penalty <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.gapPenalties[columnIndex] = penalty <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.size <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> for i in range(self.size): <NEW_LINE> <INDENT> for key, score in self.aaDistribution[i].items(): <NEW_LINE> <INDENT> print(key, ": ", score, "(", self.getScore(key, i), ")", sep="", end=", ") <NEW_LINE> <DEDENT> print()
Position Specific Score Matrix. Creates a profile for a series of aligned Sequences, and gives a score to each AA subsitution in a given column.
62598fb4fff4ab517ebcd8b0
class ClasseAction(Action): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def init_types(cls): <NEW_LINE> <INDENT> cls.ajouter_types(cls.supprimer_alarme, "Personnage", "str") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def supprimer_alarme(personnage, cle_alarme): <NEW_LINE> <INDENT> importeur.scripting.supprimer_alarme(personnage, cle_alarme)
Supprime l'alarme indiquée.
62598fb455399d3f056265de
class Action(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.command = None <NEW_LINE> self.parameters = None <NEW_LINE> self.type = None <NEW_LINE> self.message = None <NEW_LINE> self._parameter_start_pos = 0 <NEW_LINE> <DEDENT> def setParameterStartPos(self, pos): <NEW_LINE> <INDENT> self._parameter_start_pos = pos <NEW_LINE> <DEDENT> def getParameterStartPos(self): <NEW_LINE> <INDENT> return self._parameter_start_pos <NEW_LINE> <DEDENT> def execute(self, parameters, message_uuid): <NEW_LINE> <INDENT> if self.message is not None: <NEW_LINE> <INDENT> log_message = '[%s] ' % message_uuid <NEW_LINE> if self.message.count('%s') > 0 and parameters is not None and len(parameters) > 0: <NEW_LINE> <INDENT> log_message = log_message + self.message % tuple(parameters[0:self.message.count('%s')]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_message = log_message + self.message.replace("%s", "") <NEW_LINE> <DEDENT> syslog.syslog(syslog.LOG_NOTICE, log_message) <NEW_LINE> <DEDENT> if self.type is None: <NEW_LINE> <INDENT> return 'No action type' <NEW_LINE> <DEDENT> elif self.type.lower() in ('script', 'script_output'): <NEW_LINE> <INDENT> if self.command is None: <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_ERR, '[%s] returned "No command"' % message_uuid) <NEW_LINE> return 'No command' <NEW_LINE> <DEDENT> script_command = self.command <NEW_LINE> if self.parameters is not None and type(self.parameters) == str and len(parameters) > 0: <NEW_LINE> <INDENT> script_command = '%s %s' % (script_command, self.parameters) <NEW_LINE> if script_command.find('%s') > -1: <NEW_LINE> <INDENT> script_command = script_command % tuple(map(lambda x: '"'+x.replace('"', '\\"')+'"', parameters[0:script_command.count('%s')])) <NEW_LINE> <DEDENT> <DEDENT> if self.type.lower() == 'script': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exit_status = subprocess.call(script_command, shell=True) <NEW_LINE> if exit_status == 0: <NEW_LINE> <INDENT> return 'OK' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_ERR, '[%s] returned exit status %d' % (message_uuid, exit_status)) <NEW_LINE> return 'Error (%d)' % exit_status <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_ERR, '[%s] Script action failed at %s' % (message_uuid, traceback.format_exc())) <NEW_LINE> return 'Execute error' <NEW_LINE> <DEDENT> <DEDENT> elif self.type.lower() == 'script_output': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> script_output = subprocess.check_output(script_command, shell=True) <NEW_LINE> return script_output <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_ERR, '[%s] Script action failed at %s' % (message_uuid, traceback.format_exc())) <NEW_LINE> return 'Execute error' <NEW_LINE> <DEDENT> <DEDENT> return "type error" <NEW_LINE> <DEDENT> elif self.type.lower() == 'inline': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(parameters) > 0: <NEW_LINE> <INDENT> inline_act_parameters = self.parameters % tuple(parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inline_act_parameters = '' <NEW_LINE> <DEDENT> return ph_inline_actions.execute(self, inline_act_parameters) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_ERR, '[%s] Inline action failed at %s' % (message_uuid, traceback.format_exc())) <NEW_LINE> return 'Execute error' <NEW_LINE> <DEDENT> <DEDENT> return 'Unknown action type'
Action class, handles actual (system) calls. set command, parameters (template) type and log message
62598fb44527f215b58e9f9f
class MailSchema(Schema): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> type_ = 'mail' <NEW_LINE> self_view = 'v1.mail_detail' <NEW_LINE> self_view_kwargs = {'id': '<id>'} <NEW_LINE> self_view_many = 'v1.mail_list' <NEW_LINE> inflect = dasherize <NEW_LINE> <DEDENT> id = fields.Str(dump_only=True) <NEW_LINE> recipient = fields.Email(dump_only=True) <NEW_LINE> time = fields.DateTime(dump_only=True) <NEW_LINE> action = fields.Str(dump_only=True) <NEW_LINE> subject = fields.Str(dump_only=True) <NEW_LINE> message = fields.Str(dump_only=True)
Api schema for mail Model
62598fb45fcc89381b2661b1
class BaseModel(object): <NEW_LINE> <INDENT> def __init__(self, in_shape, output_shape): <NEW_LINE> <INDENT> self._input_shape = in_shape <NEW_LINE> self._output_shape = output_shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_shape(self): <NEW_LINE> <INDENT> return self._input_shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_shape(self): <NEW_LINE> <INDENT> return self._output_shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def loss_val(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def evaluate(self, environment): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def train(self, x, y): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def load(self, input_file): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def save(self, output_file): <NEW_LINE> <INDENT> raise NotImplementedError()
Represents a learning capable entity
62598fb4cc40096d6161a23e
class BiosVfOnboardStorage(ManagedObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ManagedObject.__init__(self, "BiosVfOnboardStorage") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def class_id(): <NEW_LINE> <INDENT> return "biosVfOnboardStorage" <NEW_LINE> <DEDENT> DN = "Dn" <NEW_LINE> RN = "Rn" <NEW_LINE> STATUS = "Status" <NEW_LINE> VP_ONBOARD_SCUSTORAGE_SUPPORT = "VpOnboardSCUStorageSupport" <NEW_LINE> CONST_VP_ONBOARD_SCUSTORAGE_SUPPORT_DISABLED = "Disabled" <NEW_LINE> CONST_VP_ONBOARD_SCUSTORAGE_SUPPORT_ENABLED = "Enabled" <NEW_LINE> CONST__VP_ONBOARD_SCUSTORAGE_SUPPORT_DISABLED = "disabled" <NEW_LINE> CONST__VP_ONBOARD_SCUSTORAGE_SUPPORT_ENABLED = "enabled" <NEW_LINE> CONST_VP_ONBOARD_SCUSTORAGE_SUPPORT_PLATFORM_DEFAULT = "platform-default"
This class contains the relevant properties and constant supported by this MO.
62598fb4cc0a2c111447b0dd
class CreateApp(Base): <NEW_LINE> <INDENT> def __init__(self, business_criticality, app_name, web_application=None, vendor_id=None, teams=None, tags=None, policy=None, origin=None, next_day_scheduling_enabled=None, industry=None, description=None, deployment_method=None, business_unit=None, business_owner_email=None, business_owner=None, archer_app_name=None, app_type=None, ): <NEW_LINE> <INDENT> super(CreateApp, self).__init__( module='upload', cls='CreateApp', fn='get', args={ 'business_criticality':business_criticality, 'app_name':app_name, 'web_application':web_application, 'vendor_id':vendor_id, 'teams':teams, 'tags':tags, 'policy':policy, 'origin':origin, 'next_day_scheduling_enabled':next_day_scheduling_enabled, 'industry':industry, 'description':description, 'deployment_method':deployment_method, 'business_unit':business_unit, 'business_owner_email':business_owner_email, 'business_owner':business_owner, 'archer_app_name':archer_app_name, 'app_type':app_type, })
class: veracode.SDK.upload.CreateApp params: business_criticality: required app_name: required web_application: optional vendor_id: optional teams: optional tags: optional policy: optional origin: optional next_day_scheduling_enabled: optional industry: optional description: optional deployment_method: optional business_unit: optional business_owner_email: optional business_owner: optional archer_app_name: optional app_type: optional returns: A python object that represents the returned API data.
62598fb456ac1b37e63022b5
class FontAwesomeFont(IconsFont): <NEW_LINE> <INDENT> name = 'font-awesome' <NEW_LINE> shortcut = 'fa' <NEW_LINE> css_url = '//cdn.jsdelivr.net/fontawesome/latest/css/font-awesome.css' <NEW_LINE> tag_classes = 'fa' <NEW_LINE> prefix = 'fa-'
http://fontawesome.io/icons/ <i class="fa fa-star"></i>
62598fb44428ac0f6e6585eb
class AzureSqlTableDataset(Dataset): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'linked_service_name': {'required': True}, } <NEW_LINE> _attribute_map = { 'additional_properties': {'key': '', 'type': '{object}'}, 'type': {'key': 'type', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'structure': {'key': 'structure', 'type': 'object'}, 'schema': {'key': 'schema', 'type': 'object'}, 'linked_service_name': {'key': 'linkedServiceName', 'type': 'LinkedServiceReference'}, 'parameters': {'key': 'parameters', 'type': '{ParameterSpecification}'}, 'annotations': {'key': 'annotations', 'type': '[object]'}, 'folder': {'key': 'folder', 'type': 'DatasetFolder'}, 'table_name': {'key': 'typeProperties.tableName', 'type': 'object'}, 'schema_type_properties_schema': {'key': 'typeProperties.schema', 'type': 'object'}, 'table': {'key': 'typeProperties.table', 'type': 'object'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AzureSqlTableDataset, self).__init__(**kwargs) <NEW_LINE> self.type = 'AzureSqlTable' <NEW_LINE> self.table_name = kwargs.get('table_name', None) <NEW_LINE> self.schema_type_properties_schema = kwargs.get('schema_type_properties_schema', None) <NEW_LINE> self.table = kwargs.get('table', None)
The Azure SQL Server database dataset. All required parameters must be populated in order to send to Azure. :param additional_properties: Unmatched properties from the message are deserialized to this collection. :type additional_properties: dict[str, object] :param type: Required. Type of dataset.Constant filled by server. :type type: str :param description: Dataset description. :type description: str :param structure: Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement. :type structure: object :param schema: Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement. :type schema: object :param linked_service_name: Required. Linked service reference. :type linked_service_name: ~azure.synapse.artifacts.models.LinkedServiceReference :param parameters: Parameters for dataset. :type parameters: dict[str, ~azure.synapse.artifacts.models.ParameterSpecification] :param annotations: List of tags that can be used for describing the Dataset. :type annotations: list[object] :param folder: The folder that this Dataset is in. If not specified, Dataset will appear at the root level. :type folder: ~azure.synapse.artifacts.models.DatasetFolder :param table_name: This property will be retired. Please consider using schema + table properties instead. :type table_name: object :param schema_type_properties_schema: The schema name of the Azure SQL database. Type: string (or Expression with resultType string). :type schema_type_properties_schema: object :param table: The table name of the Azure SQL database. Type: string (or Expression with resultType string). :type table: object
62598fb4a8370b77170f04a8
class Socket(QTcpSocket): <NEW_LINE> <INDENT> def __init__(self, parent=None,upLoadFunction=None): <NEW_LINE> <INDENT> super(Socket, self).__init__(parent) <NEW_LINE> self.connect(self, SIGNAL("readyRead()"),self.readPacket) <NEW_LINE> self.connect(self, SIGNAL("disconnected()"), self.deleteLater) <NEW_LINE> self.nextBlockSize = 0 <NEW_LINE> self.upLoadFunction = upLoadFunction <NEW_LINE> <DEDENT> def readPacket(self): <NEW_LINE> <INDENT> if DEBUG: <NEW_LINE> <INDENT> print("Reading packet") <NEW_LINE> <DEDENT> stream = QDataStream(self) <NEW_LINE> stream.setVersion(QDataStream.Qt_4_2) <NEW_LINE> if self.nextBlockSize == 0: <NEW_LINE> <INDENT> if self.bytesAvailable() < SIZEOF_UINT64: <NEW_LINE> <INDENT> print("\tBytes less than SIZEOF_UINT64") <NEW_LINE> return <NEW_LINE> <DEDENT> plBytes = stream.readRawData(SIZEOF_UINT64) <NEW_LINE> print("Bytes read:") <NEW_LINE> print(plBytes) <NEW_LINE> packetLength = int(np.fromstring(plBytes, dtype=np.uint64)) <NEW_LINE> self.nextBlockSize = packetLength - SIZEOF_UINT64 <NEW_LINE> print("Packet length = %i" % packetLength) <NEW_LINE> print("Reading rest of packet [%i]" % self.nextBlockSize) <NEW_LINE> <DEDENT> if self.bytesAvailable() < self.nextBlockSize: <NEW_LINE> <INDENT> print("\tBytes less than packet size") <NEW_LINE> return <NEW_LINE> <DEDENT> packet = stream.readRawData(self.nextBlockSize) <NEW_LINE> packetType,remainingPacket = getPacketType(packet) <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> print("\tPacket type = %d" % packetType) <NEW_LINE> <DEDENT> if packetType == DATA_PACKET: <NEW_LINE> <INDENT> data4scope = extractDataPacket(remainingPacket) <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> print("Data packet received [size = %d bytes]" % len(remainingPacket)) <NEW_LINE> print(remainingPacket) <NEW_LINE> print("\n\nNumerical data is:") <NEW_LINE> print(data4scope[1]) <NEW_LINE> <DEDENT> self.upLoadFunction(data4scope)
Custom socket handler for our packet format
62598fb47cff6e4e811b5aea
class NodeList(set): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def deserialize(cls, stream: BitStreamReader): <NEW_LINE> <INDENT> nodeList = cls() <NEW_LINE> for i in range(28): <NEW_LINE> <INDENT> nodeByte = uint8_t.deserialize(stream) <NEW_LINE> for j in range(8): <NEW_LINE> <INDENT> if nodeByte & (1 << j): <NEW_LINE> <INDENT> nodeList.add(i * 8 + j + 1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return nodeList
Deserializer for nodelist returned in NODE_LIST_REPORT
62598fb456ac1b37e63022b6
class Tests(IMP.test.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> IMP.test.TestCase.setUp(self) <NEW_LINE> IMP.base.set_log_level(IMP.base.TERSE) <NEW_LINE> self.data_file = self.get_input_file_name("anchors.input") <NEW_LINE> <DEDENT> def test_run(self): <NEW_LINE> <INDENT> self.anchors_data = IMP.multifit.read_anchors_data(self.data_file) <NEW_LINE> self.assertEqual(self.anchors_data.get_number_of_points(), 3) <NEW_LINE> self.assertEqual(self.anchors_data.get_number_of_edges(), 2)
Tests for a domino run on a single mapping
62598fb47b180e01f3e490b6
class CoffeeMachine(Thing): <NEW_LINE> <INDENT> def __init__(self, w): <NEW_LINE> <INDENT> super().__init__(w, "kaffemaskin", "kaffemaskiner", "en") <NEW_LINE> self.broken = True <NEW_LINE> <DEDENT> def description(self): <NEW_LINE> <INDENT> return "En kaffemaskin som kan brygga liten kaffe, stor kaffe, frappuchino, caffe latte, " + "espresso, choklad och wiener melange." <NEW_LINE> <DEDENT> def use(self): <NEW_LINE> <INDENT> if self.v_world.checkAchievment(world.ACH_FIXED_COFFEE_BUG): <NEW_LINE> <INDENT> if any(isinstance(thing, Coffee) for thing in self.v_world.player.contains()): <NEW_LINE> <INDENT> self.v_failMsg = "Jag har ju redan en mugg med kaffe." <NEW_LINE> <DEDENT> elif any(isinstance(thing, Coffee) for thing in self.contains()): <NEW_LINE> <INDENT> self.v_failMsg = "Det står ju redan en mugg med kaffe i maskinen." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.v_world.output("Kaffemojjan spottar ut en pappersmugg och fyller på den med nåt svart.") <NEW_LINE> coffee = Coffee(self.v_world) <NEW_LINE> coffee.v_parentEntity = self <NEW_LINE> self.v_container.append(coffee) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.v_failMsg = "Maskinen säger bara pip - på displayen står det 'UNABLE TO COMMUNICATE WITH PUMP'. " + "Hmm, bara jag hade nåt att felsöka den med skulle jag nog kunna fixa det." <NEW_LINE> <DEDENT> return False
CoffeeMachine class
62598fb43317a56b869be5b2
class Problem2D(Problem): <NEW_LINE> <INDENT> def __init__(self, random_seed=None, noise_stdev=0.0): <NEW_LINE> <INDENT> param_shapes = [(2,)] <NEW_LINE> super(Problem2D, self).__init__(param_shapes, random_seed, noise_stdev) <NEW_LINE> <DEDENT> def surface(self, n=50, xlim=5, ylim=5): <NEW_LINE> <INDENT> xm, ym = _mesh(xlim, ylim, n) <NEW_LINE> with tf.Graph().as_default(), tf.Session() as sess: <NEW_LINE> <INDENT> x = tf.placeholder(tf.float32, shape=xm.shape) <NEW_LINE> y = tf.placeholder(tf.float32, shape=ym.shape) <NEW_LINE> obj = self.objective([[x, y]]) <NEW_LINE> zm = sess.run(obj, feed_dict={x: xm, y: ym}) <NEW_LINE> <DEDENT> return xm, ym, zm
2D problem.
62598fb44527f215b58e9fa1
class DownloadManager(Thread): <NEW_LINE> <INDENT> PUBLISHER_TOPIC = 'dlmanager' <NEW_LINE> MAX_DOWNLOAD_THREADS = 3 <NEW_LINE> def __init__(self, threads_list, update_thread=None): <NEW_LINE> <INDENT> super(DownloadManager, self).__init__() <NEW_LINE> self.threads_list = threads_list <NEW_LINE> self.update_thread = update_thread <NEW_LINE> self._successful_downloads = 0 <NEW_LINE> self._running = True <NEW_LINE> self._time = 0 <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self.update_thread is not None: <NEW_LINE> <INDENT> self.update_thread.join() <NEW_LINE> <DEDENT> self._time = time.time() <NEW_LINE> while self._running and not self._threads_finished(): <NEW_LINE> <INDENT> for thread in self.threads_list: <NEW_LINE> <INDENT> if not self._running: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self._start_thread(thread) <NEW_LINE> <DEDENT> time.sleep(0.1) <NEW_LINE> <DEDENT> for thread in self.threads_list: <NEW_LINE> <INDENT> if thread.is_alive(): <NEW_LINE> <INDENT> thread.join() <NEW_LINE> <DEDENT> if thread.status == 0: <NEW_LINE> <INDENT> self._successful_downloads += 1 <NEW_LINE> <DEDENT> <DEDENT> self._time = time.time() - self._time <NEW_LINE> if not self._running: <NEW_LINE> <INDENT> self._callafter('closed') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._callafter('finished') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def time(self): <NEW_LINE> <INDENT> return self._time <NEW_LINE> <DEDENT> @property <NEW_LINE> def successful_downloads(self): <NEW_LINE> <INDENT> return self._successful_downloads <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._callafter('closing') <NEW_LINE> self._running = False <NEW_LINE> for thread in self.threads_list: <NEW_LINE> <INDENT> thread.close() <NEW_LINE> <DEDENT> <DEDENT> def add_thread(self, thread): <NEW_LINE> <INDENT> self.threads_list.append(thread) <NEW_LINE> <DEDENT> def alive_threads(self): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> for thread in self.threads_list: <NEW_LINE> <INDENT> if thread.is_alive(): <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> <DEDENT> <DEDENT> return counter <NEW_LINE> <DEDENT> def not_finished(self): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> for thread in self.threads_list: <NEW_LINE> <INDENT> if thread.ident is None or thread.is_alive(): <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> <DEDENT> <DEDENT> return counter <NEW_LINE> <DEDENT> def _start_thread(self, thread): <NEW_LINE> <INDENT> while self.alive_threads() >= self.MAX_DOWNLOAD_THREADS: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> if not self._running: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if thread.ident is None and self._running: <NEW_LINE> <INDENT> thread.start() <NEW_LINE> <DEDENT> <DEDENT> def _threads_finished(self): <NEW_LINE> <INDENT> for thread in self.threads_list: <NEW_LINE> <INDENT> if thread.ident is None or thread.is_alive(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def _callafter(self, data): <NEW_LINE> <INDENT> CallAfter(Publisher.sendMessage, self.PUBLISHER_TOPIC, data)
Manage youtube-dlG download list. Params threads_list: Python list that contains DownloadThread objects. update_thread: UpdateThread.py thread. Accessible Methods close() Params: None Return: None add_thread() Params: DownloadThread object Return: None alive_threads() Params: None Return: Number of alive threads. not_finished() Params: None Return: Number of threads not finished yet. Properties successful_downloads: Number of successful downloads. time: Time (seconds) it took for all downloads to complete.
62598fb410dbd63aa1c70c81
class LedMatrix(object): <NEW_LINE> <INDENT> def __init__(self, columns, rows, colors): <NEW_LINE> <INDENT> self.rows = rows <NEW_LINE> self.columns = columns <NEW_LINE> self.mat = [LedColumn(colors[row]) for row in range(columns)] <NEW_LINE> self.act_column = it.cycle(range(columns)) <NEW_LINE> <DEDENT> def __getitem__(self, column): <NEW_LINE> <INDENT> return self.mat[column] <NEW_LINE> <DEDENT> def set_led(self, column, row, on_off): <NEW_LINE> <INDENT> self[column].states[row] = on_off <NEW_LINE> <DEDENT> def draw_column(self, device): <NEW_LINE> <INDENT> column = next(self.act_column) <NEW_LINE> for i, (col, state) in enumerate(self[column]): <NEW_LINE> <INDENT> if state: <NEW_LINE> <INDENT> device.set_color(col) <NEW_LINE> device.rect(column, i)
Coluns and Rows.
62598fb4ff9c53063f51a719
class DHT22Sensor(DHTSensor): <NEW_LINE> <INDENT> def __init__(self, pin): <NEW_LINE> <INDENT> DHTSensor.__init__(self, 22, pin)
DHT22 sensor class Take as args : - Sensor Pin
62598fb4379a373c97d990e1
class CrossRef(models.Model): <NEW_LINE> <INDENT> startverse = models.ForeignKey(Verse, related_name="startverse") <NEW_LINE> endverse = models.ForeignKey(Verse, related_name="endverse") <NEW_LINE> objects = CrossRefManager() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> if self.startverse.id == self.endverse.id: <NEW_LINE> <INDENT> return u'%s %s:%s' % (self.startverse.book, self.startverse.chapter_ref, self.startverse.verse_ref) <NEW_LINE> <DEDENT> elif self.startverse.chapter_ref == self.endverse.chapter_ref: <NEW_LINE> <INDENT> return u'%s %s:%s-%s' % (self.startverse.book, self.startverse.chapter_ref, self.startverse.verse_ref, self.endverse.verse_ref) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u'%s %s:%s-%s:%s' % (self.startverse.book, self.startverse.chapter_ref, self.startverse.verse_ref, self.endverse.chapter_ref, self.endverse.verse_ref) <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['startverse', 'endverse'] <NEW_LINE> unique_together = ('startverse', 'endverse') <NEW_LINE> verbose_name = "Cross Reference"
Encapsulates a "passage" or "cross reference." startverse should be before endverse. If there is only one verse, then startverse = endverse (neither should be null). In addition, should restrict that both verses be contained in the same book.
62598fb4851cf427c66b8383
class RegisterServer2Parameters(FrozenClass): <NEW_LINE> <INDENT> ua_types = { 'Server': 'RegisteredServer', 'DiscoveryConfiguration': 'ExtensionObject', } <NEW_LINE> def __init__(self, binary=None): <NEW_LINE> <INDENT> if binary is not None: <NEW_LINE> <INDENT> self._binary_init(binary) <NEW_LINE> self._freeze = True <NEW_LINE> return <NEW_LINE> <DEDENT> self.Server = RegisteredServer() <NEW_LINE> self.DiscoveryConfiguration = [] <NEW_LINE> self._freeze = True <NEW_LINE> <DEDENT> def to_binary(self): <NEW_LINE> <INDENT> packet = [] <NEW_LINE> packet.append(self.Server.to_binary()) <NEW_LINE> packet.append(uabin.Primitives.Int32.pack(len(self.DiscoveryConfiguration))) <NEW_LINE> for fieldname in self.DiscoveryConfiguration: <NEW_LINE> <INDENT> packet.append(extensionobject_to_binary(fieldname)) <NEW_LINE> <DEDENT> return b''.join(packet) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_binary(data): <NEW_LINE> <INDENT> return RegisterServer2Parameters(data) <NEW_LINE> <DEDENT> def _binary_init(self, data): <NEW_LINE> <INDENT> self.Server = RegisteredServer.from_binary(data) <NEW_LINE> length = uabin.Primitives.Int32.unpack(data) <NEW_LINE> array = [] <NEW_LINE> if length != -1: <NEW_LINE> <INDENT> for _ in range(0, length): <NEW_LINE> <INDENT> array.append(extensionobject_from_binary(data)) <NEW_LINE> <DEDENT> <DEDENT> self.DiscoveryConfiguration = array <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'RegisterServer2Parameters(' + 'Server:' + str(self.Server) + ', ' + 'DiscoveryConfiguration:' + str(self.DiscoveryConfiguration) + ')' <NEW_LINE> <DEDENT> __repr__ = __str__
:ivar Server: :vartype Server: RegisteredServer :ivar DiscoveryConfiguration: :vartype DiscoveryConfiguration: ExtensionObject
62598fb591f36d47f2230f0e
class Organization(_messages.Message): <NEW_LINE> <INDENT> class LifecycleStateValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> LIFECYCLE_STATE_UNSPECIFIED = 0 <NEW_LINE> ACTIVE = 1 <NEW_LINE> DELETE_REQUESTED = 2 <NEW_LINE> <DEDENT> creationTime = _messages.StringField(1) <NEW_LINE> displayName = _messages.StringField(2) <NEW_LINE> lifecycleState = _messages.EnumField('LifecycleStateValueValuesEnum', 3) <NEW_LINE> name = _messages.StringField(4) <NEW_LINE> organizationId = _messages.StringField(5) <NEW_LINE> owner = _messages.MessageField('OrganizationOwner', 6)
The root node in the resource hierarchy to which a particular entity's (e.g., company) resources belong. Enums: LifecycleStateValueValuesEnum: The organization's current lifecycle state. Assigned by the server. @OutputOnly Fields: creationTime: Timestamp when the Organization was created. Assigned by the server. @OutputOnly displayName: A friendly string to be used to refer to the Organization in the UI. This field is required. lifecycleState: The organization's current lifecycle state. Assigned by the server. @OutputOnly name: Output Only. The resource name of the organization. This is the organization's relative path in the API. Its format is "organizations/[organization_id]". For example, "organizations/1234". Warning: Support for this field is not yet implemented. organizationId: An immutable id for the Organization that is assigned on creation. This should be omitted when creating a new Organization. This field is read-only. owner: The owner of this Organization. The owner should be specified on creation. Once set, it cannot be changed. This field is required.
62598fb55fc7496912d482e2
class TestMapCTP(object): <NEW_LINE> <INDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(RESULTS, True) <NEW_LINE> <DEDENT> def test_map_ctp(self): <NEW_LINE> <INDENT> logger(__name__).debug("Testing Map CTP on %s..." % SUBJECTS) <NEW_LINE> map_ctp = MapCTP(collection=COLLECTION, subjects=SUBJECTS, dest=RESULTS) <NEW_LINE> result = map_ctp.run() <NEW_LINE> prop_file = result.outputs.out_file <NEW_LINE> assert_true(os.path.exists(prop_file), "Property file was not created:" " %s" % prop_file) <NEW_LINE> assert_equal(os.path.dirname(prop_file), RESULTS, "Property file was" " not created in %s: %s" % (RESULTS, prop_file)) <NEW_LINE> for line in open(prop_file).readlines(): <NEW_LINE> <INDENT> qin_id, ctp_suffix = re.match(PAT, line).groups() <NEW_LINE> assert_true( qin_id in SUBJECTS, "Subject id not found: %s" % qin_id) <NEW_LINE> qin_nbr = int(qin_id[-2:]) <NEW_LINE> ctp_nbr = int(ctp_suffix) <NEW_LINE> assert_equal(ctp_nbr, qin_nbr, "Patient number incorrect; expected:" " %d found: %d" % (qin_nbr, ctp_nbr))
Map CTP unit tests.
62598fb5236d856c2adc94a5
class MockBinarySensor(MockEntity, BinarySensorDevice): <NEW_LINE> <INDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._handle("is_on") <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> return self._handle("device_class")
Mock Binary Sensor class.
62598fb5a8370b77170f04a9
class ResultProxy(object): <NEW_LINE> <INDENT> def __init__(self, result): <NEW_LINE> <INDENT> self._result = result <NEW_LINE> self._object = None <NEW_LINE> <DEDENT> def deserialize(self, request): <NEW_LINE> <INDENT> if self._object is None: <NEW_LINE> <INDENT> obj, id_, *args = self._result.get() <NEW_LINE> if obj == "failure": <NEW_LINE> <INDENT> class_ = deserialize_error(id_) <NEW_LINE> if class_ is not None: <NEW_LINE> <INDENT> self._object = class_(*args) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> dbsession = request.find_service(name="db") <NEW_LINE> class_ = deserialize_model(obj) <NEW_LINE> if class_ is not None: <NEW_LINE> <INDENT> self._object = dbsession.query(class_).get(id_) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self._object <NEW_LINE> <DEDENT> def success(self): <NEW_LINE> <INDENT> return self._result.state == states.SUCCESS <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return self._result.__getattribute__(name)
A proxy class for :class:`celery.result.AsyncResult` that provide results serialization using :func:`fanboi2.errors.deserialize_error` and :func:`fanboi2.models.deserialize_model`. :param result: A result of :class:`celery.AsyncResult`.
62598fb5097d151d1a2c10fb
class InMageRcmReprotectInput(ReverseReplicationProviderSpecificInput): <NEW_LINE> <INDENT> _validation = { 'instance_type': {'required': True}, 'reprotect_agent_id': {'required': True}, 'datastore_name': {'required': True}, 'log_storage_account_id': {'required': True}, } <NEW_LINE> _attribute_map = { 'instance_type': {'key': 'instanceType', 'type': 'str'}, 'reprotect_agent_id': {'key': 'reprotectAgentId', 'type': 'str'}, 'datastore_name': {'key': 'datastoreName', 'type': 'str'}, 'log_storage_account_id': {'key': 'logStorageAccountId', 'type': 'str'}, 'policy_id': {'key': 'policyId', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, reprotect_agent_id: str, datastore_name: str, log_storage_account_id: str, policy_id: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(InMageRcmReprotectInput, self).__init__(**kwargs) <NEW_LINE> self.instance_type = 'InMageRcm' <NEW_LINE> self.reprotect_agent_id = reprotect_agent_id <NEW_LINE> self.datastore_name = datastore_name <NEW_LINE> self.log_storage_account_id = log_storage_account_id <NEW_LINE> self.policy_id = policy_id
InMageRcm specific provider input. All required parameters must be populated in order to send to Azure. :param instance_type: Required. The class type.Constant filled by server. :type instance_type: str :param reprotect_agent_id: Required. The reprotect agent Id. :type reprotect_agent_id: str :param datastore_name: Required. The target datastore name. :type datastore_name: str :param log_storage_account_id: Required. The log storage account ARM Id. :type log_storage_account_id: str :param policy_id: The Policy Id. :type policy_id: str
62598fb55fdd1c0f98e5e05b
class InstanceDNSTestCase(test.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(InstanceDNSTestCase, self).setUp() <NEW_LINE> self.tempdir = tempfile.mkdtemp() <NEW_LINE> self.flags(logdir=self.tempdir) <NEW_LINE> self.network = TestFloatingIPManager() <NEW_LINE> self.network.db = db <NEW_LINE> self.project_id = 'testproject' <NEW_LINE> self.context = context.RequestContext('testuser', self.project_id, is_admin=False) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.tempdir) <NEW_LINE> super(InstanceDNSTestCase, self).tearDown() <NEW_LINE> <DEDENT> def test_dns_domains_private(self): <NEW_LINE> <INDENT> zone1 = 'testzone' <NEW_LINE> domain1 = 'example.org' <NEW_LINE> context_admin = context.RequestContext('testuser', 'testproject', is_admin=True) <NEW_LINE> self.assertRaises(exception.AdminRequired, self.network.create_private_dns_domain, self.context, domain1, zone1) <NEW_LINE> self.network.create_private_dns_domain(context_admin, domain1, zone1) <NEW_LINE> domains = self.network.get_dns_domains(self.context) <NEW_LINE> self.assertEquals(len(domains), 1) <NEW_LINE> self.assertEquals(domains[0]['domain'], domain1) <NEW_LINE> self.assertEquals(domains[0]['availability_zone'], zone1) <NEW_LINE> self.assertRaises(exception.AdminRequired, self.network.delete_dns_domain, self.context, domain1) <NEW_LINE> self.network.delete_dns_domain(context_admin, domain1)
Tests nova.network.manager instance DNS
62598fb544b2445a339b69d9
class ModifyDBInstanceVipVportResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.AsyncRequestId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.AsyncRequestId = params.get("AsyncRequestId") <NEW_LINE> self.RequestId = params.get("RequestId")
ModifyDBInstanceVipVport返回参数结构体
62598fb5460517430c4320c3
class CommandSpecification(Specification): <NEW_LINE> <INDENT> _prefix = "core.command"
CommandSpecifications are used to define commands that may be executed thought the API's command mechanism. Not all Hosts or Managers may support a particular command. \see python.implementation.ManagerInterfaceBase.ManagerInterfaceBase.commandSupported \see python.implementation.ManagerInterfaceBase.ManagerInterfaceBase.commandAvailable \see python.implementation.ManagerInterfaceBase.ManagerInterfaceBase.runCommand \see python.Host.Host.commandSupported \see python.Host.Host.commandAvailable \see python.Host.Host.runCommand
62598fb599cbb53fe6830fa2
class ACSZoneViewset(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = ACSZone.objects.all() <NEW_LINE> serializer_class = ACSZoneSerializer <NEW_LINE> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.serializer_class = ListACSZoneSerializer <NEW_LINE> return super(ACSZoneViewset, self).list(request, args, kwargs) <NEW_LINE> <DEDENT> @detail_route(methods=['get']) <NEW_LINE> def persons_count(self, request, pk): <NEW_LINE> <INDENT> resp = {} <NEW_LINE> zone = self.get_object() <NEW_LINE> resp['count'] = zone.persons.count() <NEW_LINE> return Response(resp)
ACS zone API viewset
62598fb5f548e778e596b671
class OperationDefinition(dict): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> assert "name" in kwargs <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def __to_myia__(self): <NEW_LINE> <INDENT> return self["mapping"] <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise TypeError( f'Operation definition for {self["name"]} is not callable.' )
Definition of an operation.
62598fb5d486a94d0ba2c09f
class MatplotlibWidget(FigureCanvas): <NEW_LINE> <INDENT> def __init__(self, parent=None, title='', xlabel='', ylabel='', xlim=None, ylim=None, xscale='linear', yscale='linear', width=4, height=3, dpi=100, hold=True, X = None, Y = None, Z = None): <NEW_LINE> <INDENT> self.figure = Figure(figsize=(width, height), dpi=dpi) <NEW_LINE> self.axes = self.figure.add_subplot(111) <NEW_LINE> self.axes.set_title(title) <NEW_LINE> self.axes.set_xlabel(xlabel) <NEW_LINE> self.axes.set_ylabel(ylabel) <NEW_LINE> if xscale is not None: <NEW_LINE> <INDENT> self.axes.set_xscale(xscale) <NEW_LINE> <DEDENT> if yscale is not None: <NEW_LINE> <INDENT> self.axes.set_yscale(yscale) <NEW_LINE> <DEDENT> if xlim is not None: <NEW_LINE> <INDENT> self.axes.set_xlim(*xlim) <NEW_LINE> <DEDENT> if ylim is not None: <NEW_LINE> <INDENT> self.axes.set_ylim(*ylim) <NEW_LINE> <DEDENT> self.axes.hold(hold) <NEW_LINE> if X is not None: <NEW_LINE> <INDENT> self.X = X <NEW_LINE> <DEDENT> if Y is not None: <NEW_LINE> <INDENT> self.Y = Y <NEW_LINE> <DEDENT> if Z is not None: <NEW_LINE> <INDENT> self.Z = Z <NEW_LINE> <DEDENT> FigureCanvas.__init__(self, self.figure) <NEW_LINE> if parent is not None: <NEW_LINE> <INDENT> self.setParent(parent) <NEW_LINE> <DEDENT> FigureCanvas.updateGeometry(self) <NEW_LINE> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> w, h = self.get_width_height() <NEW_LINE> return QtCore.QSize(w, h) <NEW_LINE> <DEDENT> def minimumSizeHint(self): <NEW_LINE> <INDENT> return QtCore.QSize(10, 10)
MatplotlibWidget inherits PySide.QtGui.QWidget and matplotlib.backend_bases.FigureCanvasBase Options: option_name (default_value) ------- parent (None): parent widget title (''): figure title xlabel (''): X-axis label ylabel (''): Y-axis label xlim (None): X-axis limits ([min, max]) ylim (None): Y-axis limits ([min, max]) xscale ('linear'): X-axis scale yscale ('linear'): Y-axis scale width (4): width in inches height (3): height in inches dpi (100): resolution in dpi hold (False): if False, figure will be cleared each time plot is called Widget attributes: ----------------- figure: instance of matplotlib.figure.Figure axes: figure axes Example: ------- self.widget = MatplotlibWidget(self, yscale='log', hold=True) from numpy import linspace x = linspace(-10, 10) self.widget.axes.plot(x, x**2) self.wdiget.axes.plot(x, x**3)
62598fb57047854f4633f4a8
class TestScriptPubKey(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 testScriptPubKey(self): <NEW_LINE> <INDENT> pass
ScriptPubKey unit test stubs
62598fb53346ee7daa3376ae
class TexteLibre(Masque): <NEW_LINE> <INDENT> nom = "texte_libre" <NEW_LINE> nom_complet = "texte libre" <NEW_LINE> def init(self): <NEW_LINE> <INDENT> self.texte = "" <NEW_LINE> <DEDENT> def repartir(self, personnage, masques, commande): <NEW_LINE> <INDENT> message = liste_vers_chaine(commande).lstrip() <NEW_LINE> self.a_interpreter = message <NEW_LINE> commande[:] = [] <NEW_LINE> if not message: <NEW_LINE> <INDENT> raise ErreurValidation( "Entrez quelque chose, au moins.") <NEW_LINE> <DEDENT> masques.append(self) <NEW_LINE> return True <NEW_LINE> <DEDENT> def valider(self, personnage, dic_masques): <NEW_LINE> <INDENT> Masque.valider(self, personnage, dic_masques) <NEW_LINE> message = self.a_interpreter <NEW_LINE> self.texte = message <NEW_LINE> return True
Masque <texte_libre>. On attend un n'importe quoi en paramètre.
62598fb54527f215b58e9fa3
class TeamMember(object): <NEW_LINE> <INDENT> def __init__(self, first_name=None, last_name=None, username=None, version=None, verified=None, self_url=None): <NEW_LINE> <INDENT> self.swagger_types = { 'first_name': 'str', 'last_name': 'str', 'username': 'str', 'version': 'float', 'verified': 'str', 'self_url': 'str' } <NEW_LINE> self.attribute_map = { 'first_name': 'firstName', 'last_name': 'lastName', 'username': 'username', 'version': 'version', 'verified': 'verified', 'self_url': '_selfUrl' } <NEW_LINE> self._first_name = first_name <NEW_LINE> self._last_name = last_name <NEW_LINE> self._username = username <NEW_LINE> self._version = version <NEW_LINE> self._verified = verified <NEW_LINE> self._self_url = self_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def first_name(self): <NEW_LINE> <INDENT> return self._first_name <NEW_LINE> <DEDENT> @first_name.setter <NEW_LINE> def first_name(self, first_name): <NEW_LINE> <INDENT> self._first_name = first_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_name(self): <NEW_LINE> <INDENT> return self._last_name <NEW_LINE> <DEDENT> @last_name.setter <NEW_LINE> def last_name(self, last_name): <NEW_LINE> <INDENT> self._last_name = last_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def username(self): <NEW_LINE> <INDENT> return self._username <NEW_LINE> <DEDENT> @username.setter <NEW_LINE> def username(self, username): <NEW_LINE> <INDENT> self._username = username <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return self._version <NEW_LINE> <DEDENT> @version.setter <NEW_LINE> def version(self, version): <NEW_LINE> <INDENT> self._version = version <NEW_LINE> <DEDENT> @property <NEW_LINE> def verified(self): <NEW_LINE> <INDENT> return self._verified <NEW_LINE> <DEDENT> @verified.setter <NEW_LINE> def verified(self, verified): <NEW_LINE> <INDENT> self._verified = verified <NEW_LINE> <DEDENT> @property <NEW_LINE> def self_url(self): <NEW_LINE> <INDENT> return self._self_url <NEW_LINE> <DEDENT> @self_url.setter <NEW_LINE> def self_url(self, self_url): <NEW_LINE> <INDENT> self._self_url = self_url <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, TeamMember): <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.
62598fb51f5feb6acb162cec
class Op(namedtuple('Op', 'entity, action')): <NEW_LINE> <INDENT> pass
Op holds an entity and action to be authorized on that entity. entity string holds the name of the entity to be authorized. @param entity should not contain spaces and should not start with the prefix "login" or "multi-" (conventionally, entity names will be prefixed with the entity type followed by a hyphen. @param action string holds the action to perform on the entity, such as "read" or "delete". It is up to the service using a checker to define a set of operations and keep them consistent over time.
62598fb5be7bc26dc9251ec3
class QMax(sequencetools.AideSequence): <NEW_LINE> <INDENT> NDIM, NUMERIC, SPAN = 0, False, (0., None)
Obere Abflussgrenze (upper discharge boundary) [m³/s].
62598fb5f548e778e596b672
class FakeCreatTargetResponse(object): <NEW_LINE> <INDENT> status = 'fackStatus' <NEW_LINE> def read(self): <NEW_LINE> <INDENT> return FAKE_RES_DETAIL_DATA_CREATE_TARGET
Fake create target response.
62598fb5627d3e7fe0e06f7e
class MonthEnd(CacheableOffset, DateOffset): <NEW_LINE> <INDENT> def apply(self, other): <NEW_LINE> <INDENT> other = datetime(other.year, other.month, other.day, tzinfo=other.tzinfo) <NEW_LINE> n = self.n <NEW_LINE> _, days_in_month = tslib.monthrange(other.year, other.month) <NEW_LINE> if other.day != days_in_month: <NEW_LINE> <INDENT> other = other + relativedelta(months=-1, day=31) <NEW_LINE> if n <= 0: <NEW_LINE> <INDENT> n = n + 1 <NEW_LINE> <DEDENT> <DEDENT> other = other + relativedelta(months=n, day=31) <NEW_LINE> return other <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def onOffset(cls, dt): <NEW_LINE> <INDENT> days_in_month = tslib.monthrange(dt.year, dt.month)[1] <NEW_LINE> return dt.day == days_in_month <NEW_LINE> <DEDENT> @property <NEW_LINE> def rule_code(self): <NEW_LINE> <INDENT> return 'M'
DateOffset of one month end
62598fb5cc40096d6161a240
class Connection(_http.JSONConnection): <NEW_LINE> <INDENT> API_BASE_URL = 'https://' + PUBSUB_API_HOST <NEW_LINE> API_VERSION = 'v1' <NEW_LINE> API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}' <NEW_LINE> _EXTRA_HEADERS = { _http.CLIENT_INFO_HEADER: _CLIENT_INFO, } <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(Connection, self).__init__(client) <NEW_LINE> emulator_host = os.getenv(PUBSUB_EMULATOR) <NEW_LINE> if emulator_host is None: <NEW_LINE> <INDENT> self.host = self.__class__.API_BASE_URL <NEW_LINE> self.api_base_url = self.__class__.API_BASE_URL <NEW_LINE> self.in_emulator = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.host = emulator_host <NEW_LINE> self.api_base_url = 'http://' + emulator_host <NEW_LINE> self.in_emulator = True <NEW_LINE> <DEDENT> <DEDENT> def build_api_url(self, path, query_params=None, api_base_url=None, api_version=None): <NEW_LINE> <INDENT> if api_base_url is None: <NEW_LINE> <INDENT> api_base_url = self.api_base_url <NEW_LINE> <DEDENT> return super(Connection, self.__class__).build_api_url( path, query_params=query_params, api_base_url=api_base_url, api_version=api_version)
A connection to Google Cloud Pub/Sub via the JSON REST API. :type client: :class:`~google.cloud.pubsub.client.Client` :param client: The client that owns the current connection.
62598fb5a05bb46b3848a939
class script_list(object): <NEW_LINE> <INDENT> def __init__(self, directory_name): <NEW_LINE> <INDENT> self.scripts = [] <NEW_LINE> if not directory_name: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> script_directory = os.path.expanduser(directory_name) <NEW_LINE> if os.path.isdir(script_directory): <NEW_LINE> <INDENT> if os.access(script_directory, os.R_OK): <NEW_LINE> <INDENT> logger.info("Scanning %s for user scripts" % (script_directory)) <NEW_LINE> for f in os.listdir(script_directory): <NEW_LINE> <INDENT> if 'user_script' in f: <NEW_LINE> <INDENT> file_path = os.path.join(script_directory, f) <NEW_LINE> if os.access(file_path, os.X_OK): <NEW_LINE> <INDENT> script = user_script(file_path) <NEW_LINE> if script.is_ready(): <NEW_LINE> <INDENT> self.scripts.append(script) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("directory [%s] is not readable" % (script_directory)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("directory [%s] does not exist" % (script_directory)) <NEW_LINE> <DEDENT> <DEDENT> def get_scripts(self): <NEW_LINE> <INDENT> return self.scripts
Manages a list of user scripts for the Google AIY voice project. The specified directory is scanned for scripts, expected to provide actions for voice commands. Each script can offer to handle multiple keywords. Each script can provide a handler called before and after recognition.
62598fb566656f66f7d5a4bf
class ELU(Module): <NEW_LINE> <INDENT> def __init__(self, alpha=1., inplace=False): <NEW_LINE> <INDENT> super(ELU, self).__init__() <NEW_LINE> self.alpha = alpha <NEW_LINE> self.inplace = inplace <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> return F.elu(input, self.alpha, self.inplace) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> inplace_str = ', inplace' if self.inplace else '' <NEW_LINE> return self.__class__.__name__ + ' (' + 'alpha=' + str(self.alpha) + inplace_str + ')'
Applies element-wise, :math:`f(x) = max(0,x) + min(0, alpha * (exp(x) - 1))` Args: alpha: the alpha value for the ELU formulation. Default: 1.0 inplace: can optionally do the operation in-place. Default: False Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input Examples:: >>> m = nn.ELU() >>> input = autograd.Variable(torch.randn(2)) >>> print(input) >>> print(m(input))
62598fb53d592f4c4edbaf8f
class CartSerializer(serializers.Serializer): <NEW_LINE> <INDENT> sku_id = serializers.IntegerField(label='商品 SKU ID', min_value=1) <NEW_LINE> count = serializers.IntegerField(label='商品数量', min_value=1) <NEW_LINE> selected = serializers.BooleanField(label='是否勾选', default=True) <NEW_LINE> def validate_sku_id(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> SKU.objects.get(id=value) <NEW_LINE> <DEDENT> except SKU.DoesNotExist: <NEW_LINE> <INDENT> raise serializers.ValidationError('sku id 不存在') <NEW_LINE> <DEDENT> return value
购物车序列化器:校验数据使用
62598fb58a43f66fc4bf2248
@nest.check_stack <NEW_LINE> class RateInstantaneousAndDelayedTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_rate_instantaneous_and_delayed(self): <NEW_LINE> <INDENT> neuron_params = {'tau': 5., 'std': 0.} <NEW_LINE> drive = 1.5 <NEW_LINE> delay = 2. <NEW_LINE> weight = 0.5 <NEW_LINE> simtime = 100. <NEW_LINE> dt = 0.001 <NEW_LINE> nest.set_verbosity('M_WARNING') <NEW_LINE> nest.ResetKernel() <NEW_LINE> nest.SetKernelStatus( {'resolution': dt, 'use_wfr': True, 'print_time': False}) <NEW_LINE> rate_neuron_drive = nest.Create( 'lin_rate_ipn', params={'mean': drive, 'std': 0.}) <NEW_LINE> rate_neuron_1 = nest.Create( 'lin_rate_ipn', params=neuron_params) <NEW_LINE> rate_neuron_2 = nest.Create( 'lin_rate_ipn', params=neuron_params) <NEW_LINE> multimeter = nest.Create( 'multimeter', params={ 'record_from': ['rate'], 'precision': 10, 'interval': dt}) <NEW_LINE> neurons = rate_neuron_1 + rate_neuron_2 <NEW_LINE> nest.Connect( multimeter, neurons, 'all_to_all', {'delay': 10.}) <NEW_LINE> nest.Connect(rate_neuron_drive, rate_neuron_1, 'all_to_all', {'model': 'rate_connection_instantaneous', 'weight': weight}) <NEW_LINE> nest.Connect(rate_neuron_drive, rate_neuron_2, 'all_to_all', {'model': 'rate_connection_delayed', 'delay': delay, 'weight': weight}) <NEW_LINE> nest.Simulate(simtime) <NEW_LINE> events = nest.GetStatus(multimeter)[0]['events'] <NEW_LINE> senders = events['senders'] <NEW_LINE> rate_1 = np.array(events['rate'][np.where(senders == rate_neuron_1)]) <NEW_LINE> times_2 = np.array(events['times'][np.where(senders == rate_neuron_2)]) <NEW_LINE> rate_2 = np.array(events['rate'][np.where(senders == rate_neuron_2)]) <NEW_LINE> rate_2 = rate_2[times_2 > delay] <NEW_LINE> rate_1 = rate_1[:len(rate_2)] <NEW_LINE> assert(np.sum(np.abs(rate_2 - rate_1)) < 1e-12)
Test whether delayed rate connections have same properties as instantaneous connections but with the correct delay
62598fb5167d2b6e312b7042
class DateTime(types.UInt): <NEW_LINE> <INDENT> @property <NEW_LINE> def _input_casts(self): <NEW_LINE> <INDENT> casts = super(DateTime, self)._input_casts <NEW_LINE> casts[datetime] = self._datetime_cast <NEW_LINE> return casts <NEW_LINE> <DEDENT> def _datetime_cast(self, value): <NEW_LINE> <INDENT> initial_date = datetime(year=2010, month=1, day=1, hour=0, minute=0, second=0) <NEW_LINE> seconds = int((value - initial_date).total_seconds()) <NEW_LINE> self._value = int(seconds) <NEW_LINE> <DEDENT> def _string_cast(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mat = re.match('(\d{4})\-(\d{2})\-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})$', value) <NEW_LINE> if mat is not None: <NEW_LINE> <INDENT> self._datetime_cast(datetime(*(map(int, mat.groups())))) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> super(DateTime, self)._string_cast(value)
Date-Time field which accepts datetime input and string time inputs
62598fb5460517430c4320c4
class excTWCC_CAPSEQERROR(Exception): <NEW_LINE> <INDENT> pass
Capability has dependencies on other capabilities and cannot be operated upon at this time.
62598fb55166f23b2e2434aa
class FieldLevelAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> def get_fieldsets(self, request, obj=None): <NEW_LINE> <INDENT> if self.declared_fieldsets: <NEW_LINE> <INDENT> fieldsets = self.declared_fieldsets <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = self.get_form(request, obj) <NEW_LINE> fieldsets = form.base_fields.keys() + list(self.get_readonly_fields(request, obj)) <NEW_LINE> <DEDENT> fieldsets = super(FieldLevelAdmin, self).get_fieldsets(request, obj=obj) <NEW_LINE> fieldsets = deepcopy(fieldsets) <NEW_LINE> for fieldset in fieldsets: <NEW_LINE> <INDENT> fieldset[1]['fields'] = [field for field in fieldset[1]['fields'] if self.can_change_field(request, obj, field)] <NEW_LINE> <DEDENT> for fieldset in fieldsets: <NEW_LINE> <INDENT> if not fieldset[1]['fields']: <NEW_LINE> <INDENT> fieldsets.remove(fieldset) <NEW_LINE> <DEDENT> <DEDENT> return fieldsets <NEW_LINE> <DEDENT> def get_form(self, request, obj=None, *args, **kwargs): <NEW_LINE> <INDENT> form = super(FieldLevelAdmin, self).get_form(request, obj, *args, **kwargs) <NEW_LINE> for field_name, field in form.base_fields.items(): <NEW_LINE> <INDENT> if not self.can_change_field(request, obj, field_name): <NEW_LINE> <INDENT> del form.base_fields[field_name] <NEW_LINE> <DEDENT> <DEDENT> self.inline_instances = [] <NEW_LINE> for inline_class in self.inlines: <NEW_LINE> <INDENT> if(self.can_change_inline(request, obj, inline_class.__name__)): <NEW_LINE> <INDENT> inline_instance = inline_class(self.model, self) <NEW_LINE> self.inline_instances.append(inline_instance) <NEW_LINE> <DEDENT> <DEDENT> return form <NEW_LINE> <DEDENT> def can_change_inline(self, request, obj, inline_name): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def can_change_field(self, request, obj, field_name): <NEW_LINE> <INDENT> return True
A subclass of ModelAdmin that provides hooks for setting field-level permissions based on object or request properties. Intended to be used as an abstract base class replacement for ModelAdmin, with can_change_inline() and can_change_field() customized to each use.
62598fb5283ffb24f3cf395c
class _BufferedReader(object): <NEW_LINE> <INDENT> def __init__(self, iterator): <NEW_LINE> <INDENT> self._iterator = iterator <NEW_LINE> try: <NEW_LINE> <INDENT> self._current_element = next(self._iterator) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> self._current_element = self._iterator <NEW_LINE> <DEDENT> <DEDENT> def next_if_equals(self, requested_element): <NEW_LINE> <INDENT> result = None <NEW_LINE> if requested_element == self._current_element: <NEW_LINE> <INDENT> result = self._current_element <NEW_LINE> self._current_element = self._get_next() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def _get_next(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return next(self._iterator) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return None
A look-ahead reader that expedites merging. Accepts an iterator and returns element (advancing current element) if requested element equals next element in collection and None otherwise. Never returns StopIteration so cannot be used as iteration control-flow. This behavior is useful only because VcfRecord equality is based on their coordinate (chrom, pos, ref, alt), so by iterating over a list of coordinates, you can either park on your next record or return the current record and advance the reader to the next. Each incoming VcfReader is wrapped in a a BufferedReader and readers are advanced to the next reader when their current coordinate is requested. This approach avoids reading all VCFs into memory, but does require a file handle for each VCF you are merging and also requires that VcfReaders are sorted identically. Stylistic note: This class must capture the state of the incoming iterator and provide modified behavior based on data in that iterator. A small class works ok, but suspect there may be a more pythonic way to curry iterator in a partial function. Uncertain if that would be clearer/simpler. [cgates]
62598fb597e22403b383afd5
class TestCloudInstall(TestDistributed): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(self): <NEW_LINE> <INDENT> super().setUpClass() <NEW_LINE> th.start_streams_cloud_instance() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(self): <NEW_LINE> <INDENT> th.stop_streams_cloud_instance() <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> Tester.setup_streaming_analytics(self, force_remote_build=True) <NEW_LINE> self.object_storage_toolkit_location = None <NEW_LINE> self.cos_endpoint = "s3-api.dal-us-geo.objectstorage.service.networklayer.com" <NEW_LINE> self.isCloudTest = True
Test invocations of composite operators in Streaming Analytics Service using remote toolkit
62598fb57b180e01f3e490b8
class MakeServiceTest(TestCase): <NEW_LINE> <INDENT> if not Crypto: <NEW_LINE> <INDENT> skip = "can't run w/o PyCrypto" <NEW_LINE> <DEDENT> if not pyasn1: <NEW_LINE> <INDENT> skip = "can't run w/o PyASN1" <NEW_LINE> <DEDENT> if not unix: <NEW_LINE> <INDENT> skip = "can't run on non-posix computers" <NEW_LINE> <DEDENT> def test_basic(self): <NEW_LINE> <INDENT> config = tap.Options() <NEW_LINE> service = tap.makeService(config) <NEW_LINE> self.assertIsInstance(service, TCPServer) <NEW_LINE> self.assertEquals(service.args[0], 22) <NEW_LINE> factory = service.args[1] <NEW_LINE> self.assertIsInstance(factory, OpenSSHFactory) <NEW_LINE> <DEDENT> def test_checkersPamAuth(self): <NEW_LINE> <INDENT> self.patch(tap, "pamauth", object()) <NEW_LINE> config = tap.Options() <NEW_LINE> service = tap.makeService(config) <NEW_LINE> portal = service.args[1].portal <NEW_LINE> self.assertEquals( set(portal.checkers.keys()), set([IPluggableAuthenticationModules, ISSHPrivateKey, IUsernamePassword])) <NEW_LINE> <DEDENT> def test_checkersWithoutPamAuth(self): <NEW_LINE> <INDENT> self.patch(tap, "pamauth", None) <NEW_LINE> config = tap.Options() <NEW_LINE> service = tap.makeService(config) <NEW_LINE> portal = service.args[1].portal <NEW_LINE> self.assertEquals( set(portal.checkers.keys()), set([ISSHPrivateKey, IUsernamePassword]))
Tests for L{tap.makeService}.
62598fb566673b3332c3049c
class TextCallbackWidget(TextWidget): <NEW_LINE> <INDENT> def __init__( self, pos: Point, callback: Callable, style: Optional[int] = None ): <NEW_LINE> <INDENT> self._callback = callback <NEW_LINE> super(TextCallbackWidget, self).__init__(pos, callback(), style) <NEW_LINE> <DEDENT> def update(self, dt): <NEW_LINE> <INDENT> text = self._callback() <NEW_LINE> if self._text != text: <NEW_LINE> <INDENT> self._text = text <NEW_LINE> self._image = self._make_image()
Simple text widget with callback. :param pos: widget's global position :param text: contained text :param style: curses style for text
62598fb54a966d76dd5eefa7
class HelloAPIView(APIView): <NEW_LINE> <INDENT> serializer_class = HelloSerializer <NEW_LINE> def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Use HTTP methods as function (get, post, patch, put, delete)', 'It is similar to traditional Django view', 'gives you the most control over your logic', 'Is mapped manually to URLs' ] <NEW_LINE> return Response({"message": "Hello!", 'an_apiview': an_apiview}) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> serializer = HelloSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.data.get('name') <NEW_LINE> message = 'Hello {0}'.format(name) <NEW_LINE> return Response({'message': message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def put(self, request, pk=None): <NEW_LINE> <INDENT> return Response({"method": 'put'}) <NEW_LINE> <DEDENT> def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({"method": 'patch'}) <NEW_LINE> <DEDENT> def delete(self, request, pk=None): <NEW_LINE> <INDENT> return Response({"method": 'delete'})
Test API View
62598fb5a79ad1619776a13b
class DepthFirstTraverser(object): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def _processing_map(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def nodes_to_be_processed(self): <NEW_LINE> <INDENT> return tuple(k for k in self._processing_map().keys()) <NEW_LINE> <DEDENT> def process(self, node): <NEW_LINE> <INDENT> for class_key, processor in self._processing_map().items(): <NEW_LINE> <INDENT> if isinstance(node, class_key): <NEW_LINE> <INDENT> return processor(node) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def pre_processing_of_child(self, parent_node, child_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def traverse_node_recursively(self, node, child_id=-1): <NEW_LINE> <INDENT> if isinstance(node, Node): <NEW_LINE> <INDENT> parent_node = node.parent <NEW_LINE> if node.children is not None: <NEW_LINE> <INDENT> for i, child_node in enumerate(node.children): <NEW_LINE> <INDENT> self.pre_processing_of_child(node, i) <NEW_LINE> self.traverse_node_recursively(child_node, i) <NEW_LINE> <DEDENT> <DEDENT> if isinstance(node, self.nodes_to_be_processed()): <NEW_LINE> <INDENT> node = self.process(node) <NEW_LINE> node.parent = parent_node <NEW_LINE> parent_node.children[child_id] = node <NEW_LINE> <DEDENT> <DEDENT> return node <NEW_LINE> <DEDENT> def traverse(self, node): <NEW_LINE> <INDENT> return self.traverse_node_recursively(node)
Helper class that allows depth first traversal and to implement custom processing for certain AST nodes. The processor of a node must return the new resulting node. This node will be placed in the tree. Processing of a node using this traverser should therefore only transform child nodes. The returned node will get the same parent as the node before processing had.
62598fb526068e7796d4ca26
class Role(Resource): <NEW_LINE> <INDENT> PATH = 'admin/Role' <NEW_LINE> COLLECTION_NAME = 'roles' <NEW_LINE> PRIMARY_KEY = 'role_id' <NEW_LINE> def __init__(self, role_id=None, *args, **kwargs): <NEW_LINE> <INDENT> Resource.__init__(self) <NEW_LINE> self.__role_id = role_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def role_id(self): <NEW_LINE> <INDENT> return self.__role_id <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def acl(self): <NEW_LINE> <INDENT> return self.__acl <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self.__description <NEW_LINE> <DEDENT> @description.setter <NEW_LINE> def description(self, b): <NEW_LINE> <INDENT> self.__description = b <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def customer(self): <NEW_LINE> <INDENT> return self.__customer <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, b): <NEW_LINE> <INDENT> self.__name = b <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self.__status <NEW_LINE> <DEDENT> @required_attrs(['role_id']) <NEW_LINE> def grant(self,role_id,resource_type, action, qualifier): <NEW_LINE> <INDENT> parms = [{'acl': [{'resourceType' : resource_type, 'action' : action, 'qualifier' : qualifier}]}] <NEW_LINE> p = '%s/%s' % (self.PATH, str(self.role_id)) <NEW_LINE> payload = {'grant':camel_keys(parms)} <NEW_LINE> return self.put(p, data=json.dumps(payload)) <NEW_LINE> if self.last_error is None: <NEW_LINE> <INDENT> self.load() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise setACLException(self.last_error) <NEW_LINE> <DEDENT> <DEDENT> @required_attrs(['name', 'description']) <NEW_LINE> def create(self): <NEW_LINE> <INDENT> parms = [{'status': "ACTIVE", 'name':self.name, 'description': self.description}] <NEW_LINE> payload = {'addRole':camel_keys(parms)} <NEW_LINE> response=self.post(data=json.dumps(payload)) <NEW_LINE> if self.last_error is None: <NEW_LINE> <INDENT> self.load() <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RoleCreationException(self.last_error) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def all(cls, keys_only = False, **kwargs): <NEW_LINE> <INDENT> r = Resource(cls.PATH) <NEW_LINE> params = {} <NEW_LINE> if 'detail' in kwargs: <NEW_LINE> <INDENT> r.request_details = kwargs['detail'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r.request_details = 'basic' <NEW_LINE> <DEDENT> if 'account_id' in kwargs: <NEW_LINE> <INDENT> params['account_id'] = kwargs['account_id'] <NEW_LINE> <DEDENT> if 'group_id' in kwargs: <NEW_LINE> <INDENT> params['group_id'] = kwargs['group_id'] <NEW_LINE> <DEDENT> x = r.get(params=params) <NEW_LINE> if r.last_error is None: <NEW_LINE> <INDENT> if keys_only is True: <NEW_LINE> <INDENT> return [i['roleId'] for i in x[cls.COLLECTION_NAME]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [cls(i['roleId']) for i in x[cls.COLLECTION_NAME]] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise RoleException(r.last_error)
A role defines a common set of permissions that govern access into a given account
62598fb57047854f4633f4ab
class UserManager(BaseUserManager): <NEW_LINE> <INDENT> use_in_migrations = True <NEW_LINE> def _create_user(self, email, password, **extra_fields): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('The given email must be set') <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> user = self.model(email=email, **extra_fields) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_user(self, email, password=None, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault('is_staff', False) <NEW_LINE> extra_fields.setdefault('is_superuser', False) <NEW_LINE> return self._create_user(email, password, **extra_fields) <NEW_LINE> <DEDENT> def create_superuser(self, email, password, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault('is_staff', True) <NEW_LINE> extra_fields.setdefault('is_superuser', True) <NEW_LINE> extra_fields.setdefault('is_active', True) <NEW_LINE> if extra_fields.get('is_staff') is not True: <NEW_LINE> <INDENT> raise ValueError('Superuser must have is_staff=True.') <NEW_LINE> <DEDENT> if extra_fields.get('is_superuser') is not True: <NEW_LINE> <INDENT> raise ValueError('Superuser must have is_superuser=True.') <NEW_LINE> <DEDENT> if extra_fields.get('is_active') is not True: <NEW_LINE> <INDENT> raise ValueError('Superuser must have is_active=True') <NEW_LINE> <DEDENT> return self._create_user(email, password, **extra_fields)
ユーザーマネージャー.
62598fb5379a373c97d990e5
class ProxiedInterface(object): <NEW_LINE> <INDENT> send_midi = nop <NEW_LINE> def __init__(self, outer = None, *a, **k): <NEW_LINE> <INDENT> super(ControlElement.ProxiedInterface, self).__init__(*a, **k) <NEW_LINE> self._outer = outer <NEW_LINE> <DEDENT> @property <NEW_LINE> def outer(self): <NEW_LINE> <INDENT> return self._outer
Declaration of the interface to be used when the ControlElement is wrapped in any form of Proxy object.
62598fb50fa83653e46f4faf
class Solution: <NEW_LINE> <INDENT> def permute(self, nums): <NEW_LINE> <INDENT> results = [] <NEW_LINE> if nums is None: <NEW_LINE> <INDENT> return results <NEW_LINE> <DEDENT> visited = [False for i in range(len(nums))] <NEW_LINE> self.dfs_permute(nums, visited, [], results) <NEW_LINE> return results <NEW_LINE> <DEDENT> def dfs_permute(self, nums, visited, permutation, results): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> if len(permutation) == n: <NEW_LINE> <INDENT> results.append(list(permutation)) <NEW_LINE> return <NEW_LINE> <DEDENT> for i in range(0, n): <NEW_LINE> <INDENT> if visited[i]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> permutation.append(nums[i]) <NEW_LINE> visited[i] = True <NEW_LINE> self.dfs_permute(nums, visited, permutation, results) <NEW_LINE> visited[i] = False <NEW_LINE> permutation.pop()
@param: nums: A list of integers. @return: A list of permutations.
62598fb532920d7e50bc6124
class Closed(RuntimeError): <NEW_LINE> <INDENT> pass
Raised when sending command to closed client
62598fb55fdd1c0f98e5e05e
class Crawler(object): <NEW_LINE> <INDENT> def __init__(self, urls, threadnum): <NEW_LINE> <INDENT> super(Crawler, self).__init__() <NEW_LINE> self.threadnum = threadnum <NEW_LINE> self.urls = urls <NEW_LINE> <DEDENT> def craw(self): <NEW_LINE> <INDENT> threads = [] <NEW_LINE> for i in range(self.threadnum): <NEW_LINE> <INDENT> thread = CrawlerThread(self.urls[i]) <NEW_LINE> threads.append(thread) <NEW_LINE> <DEDENT> for i in range(self.threadnum): <NEW_LINE> <INDENT> threads[i].start() <NEW_LINE> <DEDENT> for i in range(self.threadnum): <NEW_LINE> <INDENT> threads[i].join()
爬取公司名字的爬虫
62598fb5097d151d1a2c10ff
class TestTransactionUpdateView(object): <NEW_LINE> <INDENT> def test_404_when_not_exists(self, testapp): <NEW_LINE> <INDENT> testapp.get("/transactions/1/update", status=404) <NEW_LINE> <DEDENT> def test_get_update(self, testapp, example_transactions): <NEW_LINE> <INDENT> testapp.get("/transactions/1/update", status=200) <NEW_LINE> <DEDENT> def test_update_page_content(self, testapp, example_transactions): <NEW_LINE> <INDENT> response = testapp.get("/transactions/1/update", status=200) <NEW_LINE> soup = bs4.BeautifulSoup(response.body, HTML_PARSER) <NEW_LINE> assert "Update" in soup.h1.text <NEW_LINE> assert soup.find(id="description")["value"] == "First transaction" <NEW_LINE> assert soup.find(id="amount")["value"] == "100.00" <NEW_LINE> cancel_link = soup.find(href=re.compile("/transactions/1")) <NEW_LINE> assert cancel_link.text == "Cancel" <NEW_LINE> <DEDENT> def test_post_update_data(self, testapp, example_transactions): <NEW_LINE> <INDENT> testapp.post( "/transactions/1/update", { "description": "New title", "amount": "99.99", }, status=302, ) <NEW_LINE> response = testapp.get("/transactions/1", status=200) <NEW_LINE> soup = bs4.BeautifulSoup(response.body, HTML_PARSER) <NEW_LINE> assert soup.find(id="description").text == "New title" <NEW_LINE> assert soup.find(id="amount").text == "99.99" <NEW_LINE> <DEDENT> def test_post_update_with_invalid_amount( self, testapp, example_transactions, ): <NEW_LINE> <INDENT> response = testapp.post( "/transactions/1/update", { "description": "New title", "amount": "Not a number", }, status=200, ) <NEW_LINE> soup = bs4.BeautifulSoup(response.body, HTML_PARSER) <NEW_LINE> assert soup.find("input", id="description")["value"] == "New title" <NEW_LINE> assert soup.find("input", id="amount")["value"] == "100.00" <NEW_LINE> error_element = soup.find(id="errors") <NEW_LINE> assert error_element is not None <NEW_LINE> assert "Amount has to be a number" in error_element.text <NEW_LINE> <DEDENT> def test_post_update_with_form(self, testapp, example_transactions): <NEW_LINE> <INDENT> response = testapp.get( "/transactions/1/update", status=200, ) <NEW_LINE> form = response.form <NEW_LINE> form["description"] = "New Title" <NEW_LINE> form["amount"] = "99.99" <NEW_LINE> submit_response = form.submit("create") <NEW_LINE> assert submit_response.status_code == 302 <NEW_LINE> response = submit_response.follow() <NEW_LINE> soup = bs4.BeautifulSoup(response.body, HTML_PARSER) <NEW_LINE> table = soup.find("table", id="transactions") <NEW_LINE> description_cell = table.tbody.find("td", text=re.compile("Title")) <NEW_LINE> assert "New Title" in description_cell.text <NEW_LINE> amount_cell = description_cell.find_next_sibling("td") <NEW_LINE> assert "99.99" in amount_cell.text
Test for the transaction detail view.
62598fb563b5f9789fe8523c
class Spawn(LaunchMode): <NEW_LINE> <INDENT> def run(self, cmdline, **kwargs): <NEW_LINE> <INDENT> if ver.islinux(): <NEW_LINE> <INDENT> self.popen = subprocess.Popen('%s %s' % (pyfile, cmdline), **kwargs) <NEW_LINE> <DEDENT> elif ver.iswin(): <NEW_LINE> <INDENT> self.popen = subprocess.Popen('%s %s' % (pyfile, cmdline), **kwargs)
create a new process and run python in the process; can be used both Windows and Unix
62598fb57b25080760ed7583
class SubmitSkillForCertificationRequest(object): <NEW_LINE> <INDENT> deserialized_types = { 'publication_method': 'ask_smapi_model.v1.skill.publication_method.PublicationMethod', 'version_message': 'str' } <NEW_LINE> attribute_map = { 'publication_method': 'publicationMethod', 'version_message': 'versionMessage' } <NEW_LINE> supports_multiple_types = False <NEW_LINE> def __init__(self, publication_method=None, version_message=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.publication_method = publication_method <NEW_LINE> self.version_message = version_message <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_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 if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.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[0], item[1].value) if isinstance(item[1], Enum) 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, SubmitSkillForCertificationRequest): <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
:param publication_method: :type publication_method: (optional) ask_smapi_model.v1.skill.publication_method.PublicationMethod :param version_message: Description of the version (limited to 300 characters). :type version_message: (optional) str
62598fb5baa26c4b54d4f388
class Proxmox: <NEW_LINE> <INDENT> def __init__(self, user, password, host, verify_ssl): <NEW_LINE> <INDENT> from proxmoxer import ProxmoxAPI <NEW_LINE> self.data = None <NEW_LINE> try: <NEW_LINE> <INDENT> self._api = ProxmoxAPI(host, user=user, password=password, verify_ssl=verify_ssl) <NEW_LINE> _LOGGER.error('Proxmox init in class: %s', self._api) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> _LOGGER.error("Error setting up connection with Proxmox server") <NEW_LINE> <DEDENT> <DEDENT> @Throttle(MIN_TIME_BETWEEN_UPDATES) <NEW_LINE> def update(self): <NEW_LINE> <INDENT> self.data = self._api.cluster.resources.get(type='vm') <NEW_LINE> _LOGGER.error('Updating Proxmox data: %s', self.data) <NEW_LINE> <DEDENT> def get_vm(self, vmid): <NEW_LINE> <INDENT> if self.data: <NEW_LINE> <INDENT> vm = next((vm for vm in self.data if vm['vmid'] == vmid), None) <NEW_LINE> _LOGGER.error('Updating Proxmox VM: %s with data: %s', vmid, vm) <NEW_LINE> return vm <NEW_LINE> <DEDENT> return None
Handle all communication with the Proxmox API.
62598fb5a8370b77170f04ae
class ScanReport(object): <NEW_LINE> <INDENT> def __init__(self, adv_report): <NEW_LINE> <INDENT> self.timestamp = time.time() <NEW_LINE> self.peer_address = adv_report.peer_addr <NEW_LINE> self.packet_type: AdvertisingPacketType = adv_report.adv_type <NEW_LINE> self._current_advertise_data = adv_report.adv_data.records.copy() <NEW_LINE> self.advertise_data = AdvertisingData.from_ble_adv_records(self._current_advertise_data) <NEW_LINE> self.rssi = adv_report.rssi <NEW_LINE> self.duplicate = False <NEW_LINE> self.raw_bytes = adv_report.adv_data.raw_bytes <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_name(self) -> str: <NEW_LINE> <INDENT> return self.advertise_data.local_name or str(self.peer_address) <NEW_LINE> <DEDENT> def update(self, adv_report): <NEW_LINE> <INDENT> if adv_report.peer_addr != self.peer_address: <NEW_LINE> <INDENT> raise exceptions.InvalidOperationException("Peer address doesn't match") <NEW_LINE> <DEDENT> self._current_advertise_data.update(adv_report.adv_data.records.copy()) <NEW_LINE> self.advertise_data = AdvertisingData.from_ble_adv_records(self._current_advertise_data.copy()) <NEW_LINE> self.rssi = max(self.rssi, adv_report.rssi) <NEW_LINE> self.raw_bytes = b"" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ScanReport): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.peer_address == other.peer_address and self.advertise_data == other.advertise_data <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}: {}dBm - {}".format(self.device_name, self.rssi, self.advertise_data)
Represents a payload and associated metadata that's received during scanning
62598fb57c178a314d78d56e
class IsisAddressFamilyEnum(Enum): <NEW_LINE> <INDENT> ipv4 = 0 <NEW_LINE> ipv6 = 1 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_clns_isis_datatypes as meta <NEW_LINE> return meta._meta_table['IsisAddressFamilyEnum']
IsisAddressFamilyEnum Isis address family .. data:: ipv4 = 0 IPv4 .. data:: ipv6 = 1 IPv6
62598fb58a43f66fc4bf224a
class DatasetSettings(BaseSettings): <NEW_LINE> <INDENT> dataset_path: str = None
Base settings for dataset
62598fb5283ffb24f3cf395e
class Threat(CSKAType): <NEW_LINE> <INDENT> @property <NEW_LINE> def _fields(self): <NEW_LINE> <INDENT> return ['time', 'threat_id', 'threat', 'count', 'has_capture', 'acknowledged', 'name', 'signer_seat_id', 'device_id', 'validator', 'validator_seat_id', 'seat_id', 'device'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def _complex_fields(self): <NEW_LINE> <INDENT> return {'device':Device}
Threat details. Threat details contain the following fields: - time (int): Seconds since epoch (UTC) when threat occurred. - threat_id (string): Unique internal id representing the threat. - threat (string): Description of the threat. - count (int): Number of threats in this record. - has_capture (bool): Is there a capture available for this threat. - acknowledged (bool): Has this threat been acknowledged. - name (string): Name of signing device or the IP address if the source is unknown. - signer_seat_id (string): Seat id of the signer if the source is known. - device_id (string): Device id of the signer if the source is known. - device (:py:class:`pycska.basetypes.Device`) - Device of the signer if the source is known. - validator (string): Name of the validator that detected the issue. - validator_seat_id (string): Seat id of the validator that detected the issue. - seat_id (string): Seat id of the device that detected the issue - typically the validator.
62598fb5d268445f26639bec
class WinkTime(Enum): <NEW_LINE> <INDENT> STOP = 0 <NEW_LINE> BY_SECONDS = 1 <NEW_LINE> BY_MANUFACTUERER = 254 <NEW_LINE> FOREVER = 255
Enum class for Wink Time.
62598fb5fff4ab517ebcd8b7
class PtpIpCmdResponse(PtpIpPacket): <NEW_LINE> <INDENT> def __init__(self, data=None): <NEW_LINE> <INDENT> super(PtpIpCmdResponse, self).__init__() <NEW_LINE> self.cmdtype = struct.pack('I', 0x07) <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> self.ptp_response_code = struct.unpack('H', data[0:2])[0] <NEW_LINE> self.transaction_id = data[2:6] <NEW_LINE> self.args = data[6:]
ResponseCode Description 0x2000 Undefined 0x2001 OK 0x2002 General Error 0x2003 Session Not Open 0x2004 Invalid TransactionID 0x2005 Operation Not Supported 0x2006 Parameter Not Supported 0x2007 Incomplete Transfer 0x2008 Invalid StorageID 0x2009 Invalid ObjectHandle 0x200A DeviceProp Not Supported 0x200B Invalid ObjectFormatCode 0x200C Store Full 0x200D Object WriteProtected 0x200E Store Read-Only 0x200F Access Denied 0x2010 No Thumbnail Present 0x2011 SelfTest Failed 0x2012 Partial Deletion 0x2013 Store Not Available 0x2014 Specification By Format Unsupported 0x2015 No Valid ObjectInfo 0x2016 Invalid Code Format 0x2017 Unknown Vendor Code 0x2018 Capture Already Terminated 0x2019 Device Busy 0x201A Invalid ParentObject 0x201B Invalid DeviceProp Format 0x201C Invalid DeviceProp Value 0x201D Invalid Parameter 0x201E Session Already Open 0x201F Transaction Cancelled 0x2020 Specification of Destination Unsupported
62598fb54f88993c371f0574
class InvenioDB(object): <NEW_LINE> <INDENT> def __init__(self, app=None, **kwargs): <NEW_LINE> <INDENT> self.kwargs = kwargs <NEW_LINE> if app: <NEW_LINE> <INDENT> self.init_app(app, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def init_app(self, app, **kwargs): <NEW_LINE> <INDENT> self.kwargs.update(kwargs) <NEW_LINE> self.init_db(app, **self.kwargs) <NEW_LINE> app.extensions['invenio-db'] = self <NEW_LINE> app.cli.add_command(db_cmd) <NEW_LINE> <DEDENT> def init_db(self, app, entrypoint_name='invenio_db.models', **kwargs): <NEW_LINE> <INDENT> app.config.setdefault( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///' + os.path.join(app.instance_path, app.name + '.db') ) <NEW_LINE> app.config.setdefault('SQLALCHEMY_ECHO', app.debug) <NEW_LINE> db.init_app(app) <NEW_LINE> if entrypoint_name: <NEW_LINE> <INDENT> for base_entry in pkg_resources.iter_entry_points(entrypoint_name): <NEW_LINE> <INDENT> base_entry.load()
Invenio database extension.
62598fb560cbc95b06364416
class Median(Aggregation): <NEW_LINE> <INDENT> def __init__(self, column_name): <NEW_LINE> <INDENT> self._column_name = column_name <NEW_LINE> self._percentiles = Percentiles(column_name) <NEW_LINE> <DEDENT> def get_aggregate_data_type(self, table): <NEW_LINE> <INDENT> return Number() <NEW_LINE> <DEDENT> def validate(self, table): <NEW_LINE> <INDENT> column = table.columns[self._column_name] <NEW_LINE> if not isinstance(column.data_type, Number): <NEW_LINE> <INDENT> raise DataTypeError('Median can only be applied to columns containing Number data.') <NEW_LINE> <DEDENT> has_nulls = HasNulls(self._column_name).run(table) <NEW_LINE> if has_nulls: <NEW_LINE> <INDENT> warn_null_calculation(self, column) <NEW_LINE> <DEDENT> <DEDENT> def run(self, table): <NEW_LINE> <INDENT> percentiles = self._percentiles.run(table) <NEW_LINE> return percentiles[50]
Calculate the median value of a column containing :class:`.Number` data. This is the 50th percentile. See :class:`Percentiles` for implementation details.
62598fb599fddb7c1ca62e53
class BatchPad(base.NetworkHandlerImpl): <NEW_LINE> <INDENT> def __init__(self, batch_size, keys, axis=0): <NEW_LINE> <INDENT> self.keys = keys <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.axis = axis <NEW_LINE> <DEDENT> def _pad(self, arr): <NEW_LINE> <INDENT> rem = arr.shape[self.axis] % self.batch_size <NEW_LINE> if rem == 0: <NEW_LINE> <INDENT> return arr <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pad_shape = [s if i != self.axis else (self.batch_size - rem) for i, s in enumerate(arr.shape)] <NEW_LINE> to_pad = np.zeros(pad_shape, dtype=arr.dtype) <NEW_LINE> return np.concatenate([arr, to_pad], axis=self.axis) <NEW_LINE> <DEDENT> <DEDENT> def call(self, fn, in_dict, *args, **kwargs): <NEW_LINE> <INDENT> in_dict = dict(in_dict) <NEW_LINE> for key in self.keys: <NEW_LINE> <INDENT> in_dict[key] = self._pad(in_dict[key]) <NEW_LINE> <DEDENT> return fn(in_dict, *args, **kwargs)
pads variables with 0's to the specified batch size
62598fb5f548e778e596b675
class Solution: <NEW_LINE> <INDENT> @timeit <NEW_LINE> def judgeCircle(self, moves: str) -> bool: <NEW_LINE> <INDENT> st = 0 <NEW_LINE> d = {"U":1, "D":-1, "L":-1j, "R":1j} <NEW_LINE> for c in moves: <NEW_LINE> <INDENT> st += d[c] <NEW_LINE> <DEDENT> return st == 0
[657. 机器人能否返回原点](https://leetcode-cn.com/problems/robot-return-to-origin/)
62598fb54e4d5625663724f3
class Meta(UserSerializer.Meta): <NEW_LINE> <INDENT> fields = UserSerializer.Meta.fields + ('roles', )
Metaclass for serializer.
62598fb53317a56b869be5b5
class PortalLanguagesVocabulary(object): <NEW_LINE> <INDENT> implements(IVocabularyFactory) <NEW_LINE> def __call__(self, context): <NEW_LINE> <INDENT> portal_languages = getToolByName(context, 'portal_languages', None) <NEW_LINE> if not portal_languages: <NEW_LINE> <INDENT> return SimpleVocabulary([]) <NEW_LINE> <DEDENT> res = portal_languages.listSupportedLanguages() <NEW_LINE> res = [(x, (isinstance(y, str) and y.decode('utf-8') or y)) for x, y in res] <NEW_LINE> res.sort(key=operator.itemgetter(1), cmp=compare) <NEW_LINE> items = [SimpleTerm(key, key, value) for key, value in res] <NEW_LINE> return SimpleVocabulary(items)
Return portal types as vocabulary
62598fb53346ee7daa3376b0
class AbstractContextManager(abc.ABC): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __subclasshook__(cls, C): <NEW_LINE> <INDENT> if cls is AbstractContextManager: <NEW_LINE> <INDENT> return _collections_abc._check_methods(C, "__enter__", "__exit__") <NEW_LINE> <DEDENT> return NotImplemented
An abstract base class for context managers.
62598fb54f6381625f199529
class LogfileModuleLogger(ModuleLogger): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> ModuleLogger.__init__(self) <NEW_LINE> self._file = open(filename, 'w') <NEW_LINE> <DEDENT> def set_current_module(self, name): <NEW_LINE> <INDENT> self._update_file(self._file) <NEW_LINE> <DEDENT> def clear_current_module(self): <NEW_LINE> <INDENT> pass
The file output logger, all the outputs go to the same log file.
62598fb567a9b606de5460a1