code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class _DeltaParser: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> object.__init__(self) <NEW_LINE> self.delta = 0 <NEW_LINE> <DEDENT> def __call__(self, token): <NEW_LINE> <INDENT> error = False <NEW_LINE> try: <NEW_LINE> <INDENT> start = 2 if token[1] == '-' else 1 <NEW_LINE> delta = int(token[start:].string()) <NEW_LINE> if delta < 0: <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> error = True <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> error = True <NEW_LINE> <DEDENT> if error: <NEW_LINE> <INDENT> raise FormatError('at "%s": Can\'t parse delta' % token) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.delta = delta <NEW_LINE> <DEDENT> <DEDENT> def apply(self, cond): <NEW_LINE> <INDENT> return cond if self.delta == 0 else ShiftDateCondition(cond, -self.delta)
Парсер короткой опции <Delta> Использование: - добавить в список L{optionHandlers<ChainData.optionHandlers>} объекта класса L{ChainData} - выполнить разбор строки - вызвать метод L{apply} для применения параметра <Delta> к объекту класса L{DateCondition<DateCondition.DateCondition>}
62598fb38a349b6b436862e7
class CommitmentStatus(models.Model): <NEW_LINE> <INDENT> commitment = models.ForeignKey(Commitment) <NEW_LINE> parent_snapshot = models.ForeignKey(CommitmentDailySnapshot) <NEW_LINE> time_accomplished = models.DateTimeField(blank=True, null=True) <NEW_LINE> comment = models.CharField(max_length=140, blank=True, null=True) <NEW_LINE> def set_accomplished(self, comment, time=timezone.now()): <NEW_LINE> <INDENT> self.time_accomplished = time <NEW_LINE> self.comment = comment <NEW_LINE> return self.save() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__() <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "'{0}' on {1}: Accomplished - {2}".format( self.commitment.name, self.parent_snapshot.date, self.time_accomplished)
The progress of one specific commitment on one specific day
62598fb3a8370b77170f0488
class ExternalNode(gpi.NodeAPI): <NEW_LINE> <INDENT> def initUI(self): <NEW_LINE> <INDENT> self.addWidget('PushButton', 'SVD Econ', toggle=True) <NEW_LINE> self.addInPort('input', 'NPYarray', obligation=gpi.REQUIRED) <NEW_LINE> self.addOutPort('U', 'NPYarray') <NEW_LINE> self.addOutPort('S', 'NPYarray') <NEW_LINE> self.addOutPort('VH', 'NPYarray') <NEW_LINE> return 0 <NEW_LINE> <DEDENT> def compute(self): <NEW_LINE> <INDENT> e = self.getVal('SVD Econ') <NEW_LINE> inp = self.getData('input') <NEW_LINE> args = [base_path+'/bart svd'] <NEW_LINE> if e: <NEW_LINE> <INDENT> args += ['-e'] <NEW_LINE> <DEDENT> in1 = IFilePath(cfl.writecfl, inp, asuffix=['.cfl','.hdr']) <NEW_LINE> args += [in1] <NEW_LINE> out1 = OFilePath(cfl.readcfl, asuffix=['.cfl','.hdr']) <NEW_LINE> args += [out1] <NEW_LINE> out2 = OFilePath(cfl.readcfl, asuffix=['.cfl','.hdr']) <NEW_LINE> args += [out2] <NEW_LINE> out3 = OFilePath(cfl.readcfl, asuffix=['.cfl','.hdr']) <NEW_LINE> args += [out3] <NEW_LINE> print(Command(*args)) <NEW_LINE> self.setData('U', out1.data()) <NEW_LINE> self.setData('S', out2.data()) <NEW_LINE> self.setData('VH', out3.data()) <NEW_LINE> out1.close() <NEW_LINE> out2.close() <NEW_LINE> out3.close() <NEW_LINE> return 0
Usage svd: [-e] <input> <U> <S> <VH> Compute singular-value-decomposition (SVD).
62598fb3167d2b6e312b701e
class IPiwikSettings(Interface): <NEW_LINE> <INDENT> piwik_server = schema.TextLine(title=_(u"Piwik server URL"), description=u'Where is your piwik located? e.g. http://demo.piwik.org ', required=True, default = u'', ) <NEW_LINE> piwik_siteid = schema.TextLine(title=_(u"Piwik site id"), description=u'integer siteId', required=True, default = u'', ) <NEW_LINE> piwik_key = schema.TextLine(title=_(u"Piwik API key"), description=u'piwik API token auth key, or anonymous if no auth', required=True, default = u'anonymous', )
Piwik settings.
62598fb326068e7796d4ca02
class UserList(TrapDjangoValidationErrorCreateMixin, UserMixin, ListCreateAPIView): <NEW_LINE> <INDENT> permission_classes = ( And(IsUserActive, IsAuthenticated, Or(IsAdminSuperUser, IsAdministrator, And(IsReadOnly, Or(IsDefaultUser, IsAnyProjectUser) ) ) ), ) <NEW_LINE> pagination_class = SmallResultsSetPagination <NEW_LINE> filter_backends = (SearchFilter,) <NEW_LINE> search_fields = ('username', 'first_name', 'last_name', 'email',) <NEW_LINE> lookup_field = 'public_id'
User list endpoint.
62598fb35166f23b2e243486
class InvalidToken(Exception): <NEW_LINE> <INDENT> pass
Token is invalid or expired
62598fb355399d3f056265c5
class NodeAuthSSHKey(object): <NEW_LINE> <INDENT> def __init__(self, pubkey): <NEW_LINE> <INDENT> self.pubkey = pubkey <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<NodeAuthSSHKey>'
An SSH key to be installed for authentication to a node. This is the actual contents of the users ssh public key which will normally be installed as root's public key on the node. >>> pubkey = '...' # read from file >>> from libcloud.compute.base import NodeAuthSSHKey >>> k = NodeAuthSSHKey(pubkey) >>> k <NodeAuthSSHKey>
62598fb37d43ff2487427458
class UserMixin(object): <NEW_LINE> <INDENT> email = EmailProperty(unique_index=True) <NEW_LINE> hashed_password = StringProperty() <NEW_LINE> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> raise AttributeError('Password is not readable attribute') <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, plain_password): <NEW_LINE> <INDENT> self.hashed_password = generate_password_hash(plain_password) <NEW_LINE> <DEDENT> def check_password(self, plain_password): <NEW_LINE> <INDENT> return check_password_hash(self.hashed_password, plain_password)
User auth values
62598fb37047854f4633f487
class ViewPostHandler(Handler): <NEW_LINE> <INDENT> def get(self, id): <NEW_LINE> <INDENT> posts = db.GqlQuery("SELECT * FROM Post ") <NEW_LINE> post_id = Post.get_by_id(int(id)) <NEW_LINE> self.render("view-post.html", post_id = post_id)
Uses webapp2.route route to show a single blog post when the link is clicked or a new post is created
62598fb3fff4ab517ebcd891
class TestProcessWrap(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.process = AFunctionToWrap() <NEW_LINE> self.process.fname = "fname" <NEW_LINE> self.process.directory = "directory" <NEW_LINE> self.process.value = 1.2 <NEW_LINE> self.process.enum = "choice1" <NEW_LINE> self.process.list_of_str = ["a_string"] <NEW_LINE> <DEDENT> def test_process_wrap(self): <NEW_LINE> <INDENT> self.process() <NEW_LINE> self.assertEqual(getattr(self.process, "reference"), ["27"]) <NEW_LINE> self.assertEqual( getattr(self.process, "string"), "ALL FUNCTION PARAMETERS::\n\nfnamedirectory1.2choice1['a_string']")
Class to test the function used to wrap a function to a process
62598fb338b623060ffa9148
@register <NEW_LINE> class Request(BaseSchema): <NEW_LINE> <INDENT> __props__ = { "seq": { "type": "integer", "description": "Sequence number." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "description": "The command to execute." }, "arguments": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Object containing arguments for the command." } } <NEW_LINE> __refs__ = set() <NEW_LINE> __slots__ = list(__props__.keys()) + ['kwargs'] <NEW_LINE> def __init__(self, command, seq=-1, arguments=None, **kwargs): <NEW_LINE> <INDENT> self.type = 'request' <NEW_LINE> self.command = command <NEW_LINE> self.seq = seq <NEW_LINE> self.arguments = arguments <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> dct = { 'type': self.type, 'command': self.command, 'seq': self.seq, } <NEW_LINE> if self.arguments is not None: <NEW_LINE> <INDENT> dct['arguments'] = self.arguments <NEW_LINE> <DEDENT> dct.update(self.kwargs) <NEW_LINE> return dct
A client or server-initiated request. Note: automatically generated code. Do not edit manually.
62598fb367a9b606de54607b
class ProvisionServiceView(MSSPBaseAuth, FormView): <NEW_LINE> <INDENT> template_name = 'mssp/simple_demo.html' <NEW_LINE> form_class = forms.Form <NEW_LINE> success_url = '/mssp/services' <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> service_name = self.request.POST.get('service_id', '') <NEW_LINE> customer_name = self.request.POST.get('customer_name', '') <NEW_LINE> if service_name == '': <NEW_LINE> <INDENT> print('No Service ID found!') <NEW_LINE> return super().form_valid(form) <NEW_LINE> <DEDENT> service = snippet_utils.load_snippet_with_name(service_name) <NEW_LINE> jinja_context = dict() <NEW_LINE> jinja_context['customer_name'] = customer_name <NEW_LINE> jinja_context['service_tier'] = service_name <NEW_LINE> for v in service['variables']: <NEW_LINE> <INDENT> if self.request.POST.get(v['name']): <NEW_LINE> <INDENT> jinja_context[v['name']] = self.request.POST.get(v['name']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Required Variable not found on request!') <NEW_LINE> return super().form_valid(form) <NEW_LINE> <DEDENT> <DEDENT> print(jinja_context) <NEW_LINE> if 'extends' in service and service['extends'] is not None: <NEW_LINE> <INDENT> baseline = service['extends'] <NEW_LINE> baseline_service = snippet_utils.load_snippet_with_name(baseline) <NEW_LINE> if baseline_service is not None: <NEW_LINE> <INDENT> if not pan_utils.validate_snippet_present(baseline_service, jinja_context): <NEW_LINE> <INDENT> print('Pushing configuration dependency: %s' % baseline_service['name']) <NEW_LINE> pan_utils.push_service(baseline_service, jinja_context) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not pan_utils.validate_snippet_present(service, jinja_context): <NEW_LINE> <INDENT> print('Pushing new service: %s' % service['name']) <NEW_LINE> pan_utils.push_service(service, jinja_context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('This service was already configured on the server') <NEW_LINE> <DEDENT> return super().form_valid(form)
Provision Service View - This view uses the Base Auth and Form View The posted view is actually a dynamically generated form so the forms.Form will actually be blank use form_valid as it will always be true in this case.
62598fb37b25080760ed755d
class HostsConfig(AppConfig): <NEW_LINE> <INDENT> name = 'django_hosts' <NEW_LINE> verbose_name = _('Hosts') <NEW_LINE> def ready(self): <NEW_LINE> <INDENT> checks.register(check_root_hostconf) <NEW_LINE> checks.register(check_default_host) <NEW_LINE> if getattr(settings, 'HOST_OVERRIDE_URL_TAG', False): <NEW_LINE> <INDENT> add_to_builtins('django_hosts.templatetags.hosts_override')
The django-hosts app config that conditionally adds its url to the built-ins of Django if the HOST_OVERRIDE_URL_TAG setting is set.
62598fb3ff9c53063f51a6f9
class ExposeProcess(ExposeObjectPlugin): <NEW_LINE> <INDENT> full_model_name = "flow.Process" <NEW_LINE> def filter_objects( self, user: UserClass, queryset: QuerySet, data: Data ) -> QuerySet: <NEW_LINE> <INDENT> processes_of_inputs = queryset.filter(data__in=data.parents.all()) <NEW_LINE> return queryset.filter_for_user(user).distinct().union(processes_of_inputs)
Expose the Process model.
62598fb3091ae35668704cca
class DatabaseIdentity(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'tenant_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '{DatabaseUserIdentity}'}, 'delegated_resources': {'key': 'delegatedResources', 'type': '{Delegation}'}, } <NEW_LINE> def __init__( self, *, type: Optional[Union[str, "DatabaseIdentityType"]] = None, user_assigned_identities: Optional[Dict[str, "DatabaseUserIdentity"]] = None, delegated_resources: Optional[Dict[str, "Delegation"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(DatabaseIdentity, self).__init__(**kwargs) <NEW_LINE> self.type = type <NEW_LINE> self.tenant_id = None <NEW_LINE> self.user_assigned_identities = user_assigned_identities <NEW_LINE> self.delegated_resources = delegated_resources
Azure Active Directory identity configuration for a resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: The identity type. Possible values include: "None", "UserAssigned". :vartype type: str or ~azure.mgmt.sql.models.DatabaseIdentityType :ivar tenant_id: The Azure Active Directory tenant id. :vartype tenant_id: str :ivar user_assigned_identities: The resource ids of the user assigned identities to use. :vartype user_assigned_identities: dict[str, ~azure.mgmt.sql.models.DatabaseUserIdentity] :ivar delegated_resources: Resources delegated to the database - Internal Use Only. :vartype delegated_resources: dict[str, ~azure.mgmt.sql.models.Delegation]
62598fb32ae34c7f260ab188
class Suscription(models.Model): <NEW_LINE> <INDENT> shift = models.ForeignKey(Shift) <NEW_LINE> student = models.ForeignKey(Student) <NEW_LINE> state = models.CharField(max_length = 32) <NEW_LINE> suscription_date = models.DateField(default = timezone.now) <NEW_LINE> resolve_date = models.DateField(null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return _("{id} - Suscription to {shift} of {student}").format(id = self.pk, shift = self.shift, student = self.student)
The Subscriptions are actually the reflection of the action, performed by a Student, of applying to be enrrolled to a given Course. It is not the enrollement, only the request to be accepted. It can either be aproved or discarded.
62598fb321bff66bcd722d13
class Graveyard(Card_container): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(type(self)) <NEW_LINE> self.name = 'yard' <NEW_LINE> self.container = self.initialize_container() <NEW_LINE> self.size = self.container_size()
sets the graveyard card container.
62598fb33317a56b869be5a2
class EntryNotFoundError(Exception): <NEW_LINE> <INDENT> def __init__(self, table, entry_id): <NEW_LINE> <INDENT> super(EntryNotFoundError, self).__init__("") <NEW_LINE> self.message = "The {} with id {} was not found".format( table, entry_id) <NEW_LINE> self.table = table <NEW_LINE> self.entry_id = entry_id
This is the error thrown when an entry was not found in the database. May be associated to single-item UPDATE or DELETE operations. The id of the entry/item is stored in EntryNotFoundError.entry_id
62598fb3be7bc26dc9251eb2
class PublicUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_create_valid_user_success(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@email.com', 'password': 'testpass', 'name': 'Test Name' } <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_201_CREATED) <NEW_LINE> user = get_user_model().objects.get(**res.data) <NEW_LINE> self.assertTrue(user.check_password(payload['password'])) <NEW_LINE> self.assertNotIn('password', res.data) <NEW_LINE> <DEDENT> def test_user_exists(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@email.com', 'password': 'testpass' } <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_password_too_short(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@email.com', 'password': 'py', } <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> user_exists = get_user_model().objects.filter( email=payload['email'] ) <NEW_LINE> self.assertFalse(user_exists) <NEW_LINE> <DEDENT> def test_create_token_for_user(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@email.com', 'password': 'testpass', } <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_create_token_invalid_credentials(self): <NEW_LINE> <INDENT> create_user(email='test@email.com', password='testpass') <NEW_LINE> payload = { 'email': 'test@email.com', 'password': 'wrong', } <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_created_token_no_user(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@email.com', 'password': 'testpass', } <NEW_LINE> res = self.client.post(TOKEN_URL, payload) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_create_token_missing_field(self): <NEW_LINE> <INDENT> res = self.client.post(TOKEN_URL, {'email': 'one', 'password': ''}) <NEW_LINE> self.assertNotIn('token', res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_retrieve_user_unauthorized(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
Test the users API (public).
62598fb3aad79263cf42e87f
class Signable(object): <NEW_LINE> <INDENT> def __init__(self, network_id, message): <NEW_LINE> <INDENT> self.network_id = network_id <NEW_LINE> self._message = message <NEW_LINE> self._hash = None <NEW_LINE> if not COLLATERAL_ASSET_ID_BY_NETWORK_ID[self.network_id]: <NEW_LINE> <INDENT> raise ValueError( 'Unknown network ID or unknown collateral asset for network: ' '{}'.format(network_id), ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def hash(self): <NEW_LINE> <INDENT> if self._hash is None: <NEW_LINE> <INDENT> self._hash = self._calculate_hash() <NEW_LINE> <DEDENT> return self._hash <NEW_LINE> <DEDENT> def sign(self, private_key_hex): <NEW_LINE> <INDENT> r, s = sign(self.hash, int(private_key_hex, 16)) <NEW_LINE> return serialize_signature(r, s) <NEW_LINE> <DEDENT> def verify_signature(self, signature_hex, public_key_hex): <NEW_LINE> <INDENT> r, s = deserialize_signature(signature_hex) <NEW_LINE> return verify(self.hash, r, s, int(public_key_hex, 16)) <NEW_LINE> <DEDENT> def _calculate_hash(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for an object signable with a STARK key.
62598fb356b00c62f0fb2964
class MerlinBuffer(sublime_plugin.EventListener): <NEW_LINE> <INDENT> _process = None <NEW_LINE> error_messages = [] <NEW_LINE> def process(self, view): <NEW_LINE> <INDENT> if not self._process: <NEW_LINE> <INDENT> self._process = merlin_process(view.file_name()) <NEW_LINE> <DEDENT> return self._process <NEW_LINE> <DEDENT> @only_ocaml <NEW_LINE> def on_post_save(self, view): <NEW_LINE> <INDENT> self.process(view).sync_buffer(view) <NEW_LINE> self.display_to_status_bar(view) <NEW_LINE> self.show_errors(view) <NEW_LINE> <DEDENT> @only_ocaml <NEW_LINE> def on_modified(self, view): <NEW_LINE> <INDENT> view.erase_regions('ocaml-underlines-errors') <NEW_LINE> <DEDENT> def show_errors(self, view): <NEW_LINE> <INDENT> view.erase_regions('ocaml-underlines-errors') <NEW_LINE> errors = self.process(view).report_errors() <NEW_LINE> error_messages = [] <NEW_LINE> underlines = [] <NEW_LINE> for e in errors: <NEW_LINE> <INDENT> pos_start = e['start'] <NEW_LINE> pos_stop = e['end'] <NEW_LINE> pnt_start = merlin_pos(view, pos_start) <NEW_LINE> pnt_stop = merlin_pos(view, pos_stop) <NEW_LINE> r = sublime.Region(pnt_start, pnt_stop) <NEW_LINE> line_r = view.full_line(r) <NEW_LINE> line_r = sublime.Region(line_r.a - 1, line_r.b) <NEW_LINE> underlines.append(r) <NEW_LINE> message = e['message'] <NEW_LINE> error_messages.append((line_r, message)) <NEW_LINE> <DEDENT> self.error_messages = error_messages <NEW_LINE> flag = sublime.DRAW_OUTLINED <NEW_LINE> view.add_regions('ocaml-underlines-errors', underlines, 'invalid', 'dot', flag) <NEW_LINE> <DEDENT> @only_ocaml <NEW_LINE> def on_selection_modified(self, view): <NEW_LINE> <INDENT> self.display_to_status_bar(view) <NEW_LINE> <DEDENT> def display_to_status_bar(self, view): <NEW_LINE> <INDENT> caret_region = view.sel()[0] <NEW_LINE> for message_region, message_text in self.error_messages: <NEW_LINE> <INDENT> if message_region.intersects(caret_region): <NEW_LINE> <INDENT> sublime.status_message(message_text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sublime.status_message('')
Synchronize the current buffer with Merlin and: - autocomplete words with type informations; - display errors in the gutter.
62598fb35fc7496912d482d2
class ResourceMoveDetails(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'operation_in_progress': {'key': 'operationInProgress', 'type': 'str'}, 'operation_in_progress_lock_timeout_in_utc': {'key': 'operationInProgressLockTimeoutInUTC', 'type': 'iso-8601'}, } <NEW_LINE> def __init__( self, *, operation_in_progress: Optional[Union[str, "ResourceMoveStatus"]] = None, operation_in_progress_lock_timeout_in_utc: Optional[datetime.datetime] = None, **kwargs ): <NEW_LINE> <INDENT> super(ResourceMoveDetails, self).__init__(**kwargs) <NEW_LINE> self.operation_in_progress = operation_in_progress <NEW_LINE> self.operation_in_progress_lock_timeout_in_utc = operation_in_progress_lock_timeout_in_utc
Fields for tracking resource move. :param operation_in_progress: Denotes whether move operation is in progress. Possible values include: "None", "ResourceMoveInProgress", "ResourceMoveFailed". :type operation_in_progress: str or ~azure.mgmt.databoxedge.v2021_02_01_preview.models.ResourceMoveStatus :param operation_in_progress_lock_timeout_in_utc: Denotes the timeout of the operation to finish. :type operation_in_progress_lock_timeout_in_utc: ~datetime.datetime
62598fb34527f215b58e9f81
class PostForm(Form): <NEW_LINE> <INDENT> title = StringField('Title', [DataRequired(), Length(max=255)]) <NEW_LINE> text = TextAreaField('Blog Content', [DataRequired()])
Post Form.
62598fb32c8b7c6e89bd3871
class InvalidAuthType(StrcredException): <NEW_LINE> <INDENT> pass
Raised when a user provides an invalid identifier for the authentication plugin (known as the authType).
62598fb38a349b6b436862e9
class User(AbstractUser): <NEW_LINE> <INDENT> GENDER_MALE = "male" <NEW_LINE> GENDER_FEMALE = "female" <NEW_LINE> GENDER_OTHER = "other" <NEW_LINE> GENDER_CHOICES = ( (GENDER_MALE, "Male"), (GENDER_FEMALE, "Female"), (GENDER_OTHER, "Other"), ) <NEW_LINE> LANGUAGE_ENGLISH = "en" <NEW_LINE> LANGUAGE_DUTCH = "nl" <NEW_LINE> LANGUAGE_CHOICES = ((LANGUAGE_ENGLISH, "English"), (LANGUAGE_DUTCH, "Dutch")) <NEW_LINE> CURRENCY_USD = "usd" <NEW_LINE> CURRENCY_EUR = "eur" <NEW_LINE> CURRENCY_CHOICES = ((CURRENCY_USD, "USD"), (CURRENCY_EUR, "EUR")) <NEW_LINE> avatar = models.ImageField(upload_to="avatars", blank=True) <NEW_LINE> gender = models.CharField(choices=GENDER_CHOICES, max_length=10, blank=True) <NEW_LINE> bio = models.TextField(blank=True) <NEW_LINE> birthdate = models.DateField(blank=True, null=True) <NEW_LINE> language = models.CharField( choices=LANGUAGE_CHOICES, max_length=2, blank=True, default=LANGUAGE_ENGLISH) <NEW_LINE> currency = models.CharField( choices=CURRENCY_CHOICES, max_length=3, blank=True, default=CURRENCY_EUR) <NEW_LINE> superhost = models.BooleanField(default=False)
Custom User Model
62598fb463d6d428bbee285a
class SelectFlid: <NEW_LINE> <INDENT> def __init__(self, X, Y, fwd_batch_size, batch_size, optimizer, loss): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.Y = Y <NEW_LINE> self.loss = loss <NEW_LINE> self.candidate_points = [] <NEW_LINE> self.fwd_batch_size = fwd_batch_size <NEW_LINE> self.batch_size =batch_size <NEW_LINE> self.entropy = np.array((self.X.shape[0], 1)) <NEW_LINE> self.features = None <NEW_LINE> self.optimizer = optimizer <NEW_LINE> <DEDENT> def compute_entropy(self, model, candidate_points, sampled_points): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> intermediate_layer_model = Model (inputs=model.input, outputs=[model.get_layer ("prob").output, model.get_layer("features").output]) <NEW_LINE> idx = np.hstack((candidate_points, sampled_points)) <NEW_LINE> idx = idx.astype("int") <NEW_LINE> prob, feat= intermediate_layer_model.predict (self.X[idx]) <NEW_LINE> ent = np.array([entropy(i) for i in prob]).reshape((len(idx), 1)) <NEW_LINE> if any(np.isnan(ent)) or any(np.isinf(ent)): <NEW_LINE> <INDENT> raise("Error") <NEW_LINE> <DEDENT> self.entropy[idx] = ent <NEW_LINE> self.features = np.empty(shape=((self.X.shape[0], feat.shape[1]))) <NEW_LINE> self.features[idx] = feat <NEW_LINE> end_time = time.time() <NEW_LINE> self.entropy = normalize(self.entropy, axis=0) <NEW_LINE> tot = int(end_time - start_time) <NEW_LINE> <DEDENT> def modular(self, idx): <NEW_LINE> <INDENT> return self.entropy[idx] <NEW_LINE> <DEDENT> def distance(self, idx, candidate_points, sampled_points): <NEW_LINE> <INDENT> if len(sampled_points) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> feature_matrix = self.features[sampled_points] <NEW_LINE> temp = sampled_points.extend(idx) <NEW_LINE> feature_matrix_plus_idx = self.features[temp] <NEW_LINE> <DEDENT> mean = np.sum(feature_matrix, axis=1) <NEW_LINE> feature_matrix = feature_matrix - mean <NEW_LINE> val_prev = np.sum(np.max(feature_matrix, axis=1)) <NEW_LINE> mean = np.sum (feature_matrix_plus_idx, axis=1) <NEW_LINE> feature_matrix_plus_idx = feature_matrix_plus_idx - mean <NEW_LINE> val = np.sum(np.max(feature_matrix_plus_idx, axis=1)) <NEW_LINE> return val - val_prev <NEW_LINE> <DEDENT> def marginal_gain(self, idx, model, candidate_points, sampled_points, compute_entropy): <NEW_LINE> <INDENT> if compute_entropy == 1 : <NEW_LINE> <INDENT> self.compute_entropy(model, candidate_points, sampled_points) <NEW_LINE> <DEDENT> return self.modular(idx) + self.distance(idx, candidate_points, sampled_points) <NEW_LINE> <DEDENT> def sample(self, model): <NEW_LINE> <INDENT> return self.optimizer.sample (model, self.marginal_gain, self.candidate_points)
-------------------------------------------------------------------------------------------------------- Facitliy Location submodular functions is defined as follows Flid(S) = \sum_{i=1}^|S| u(s_i) + \sum_{d=1}^D (max_{i\in S} (W_{i, d} - \sum{i\in S} W_{i, d}) u: denotes the modular value. In our case we interpret as negative of probability. W: denotes the d-dim reprsentation of the data points. In our case this is equivalent to getting the intermidiate reprsentation of the datapoints from the last layer of network. --------------------------------------------------------------------------------------------------------
62598fb4dc8b845886d53664
class TestRevisionsControllerNegativeRBAC(test_base.BaseControllerTest): <NEW_LINE> <INDENT> def test_list_revisions_except_forbidden(self): <NEW_LINE> <INDENT> rules = {'deckhand:list_revisions': 'rule:admin_api'} <NEW_LINE> self.policy.set_rules(rules) <NEW_LINE> resp = self.app.simulate_get( '/api/v1.0/revisions', headers={'Content-Type': 'application/x-yaml'}) <NEW_LINE> self.assertEqual(403, resp.status_code) <NEW_LINE> <DEDENT> def test_show_revision_except_forbidden(self): <NEW_LINE> <INDENT> rules = {'deckhand:show_revision': 'rule:admin_api', 'deckhand:create_cleartext_documents': '@'} <NEW_LINE> self.policy.set_rules(rules) <NEW_LINE> secrets_factory = factories.DocumentSecretFactory() <NEW_LINE> payload = [secrets_factory.gen_test('Certificate', 'cleartext')] <NEW_LINE> resp = self.app.simulate_put( '/api/v1.0/buckets/mop/documents', headers={'Content-Type': 'application/x-yaml'}, body=yaml.safe_dump_all(payload)) <NEW_LINE> self.assertEqual(200, resp.status_code) <NEW_LINE> revision_id = list(yaml.safe_load_all(resp.text))[0]['status'][ 'revision'] <NEW_LINE> resp = self.app.simulate_get( '/api/v1.0/revisions/%s' % revision_id, headers={'Content-Type': 'application/x-yaml'}) <NEW_LINE> self.assertEqual(403, resp.status_code) <NEW_LINE> <DEDENT> def test_delete_revisions_except_forbidden(self): <NEW_LINE> <INDENT> rules = {'deckhand:delete_revisions': 'rule:admin_api'} <NEW_LINE> self.policy.set_rules(rules) <NEW_LINE> resp = self.app.simulate_delete( '/api/v1.0/revisions', headers={'Content-Type': 'application/x-yaml'}) <NEW_LINE> self.assertEqual(403, resp.status_code)
Test suite for validating negative RBAC scenarios for revisions controller.
62598fb460cbc95b063643f2
@mock.patch('qutebrowser.config.configtypes.os.path', autospec=True) <NEW_LINE> class DirectoryTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.t = configtypes.Directory() <NEW_LINE> <DEDENT> def test_validate_empty(self, _os_path): <NEW_LINE> <INDENT> with self.assertRaises(configexc.ValidationError): <NEW_LINE> <INDENT> self.t.validate("") <NEW_LINE> <DEDENT> <DEDENT> def test_validate_empty_none_ok(self, _os_path): <NEW_LINE> <INDENT> t = configtypes.Directory(none_ok=True) <NEW_LINE> t.validate("") <NEW_LINE> <DEDENT> def test_validate_does_not_exist(self, os_path): <NEW_LINE> <INDENT> os_path.expanduser.side_effect = lambda x: x <NEW_LINE> os_path.isdir.return_value = False <NEW_LINE> with self.assertRaises(configexc.ValidationError): <NEW_LINE> <INDENT> self.t.validate('foobar') <NEW_LINE> <DEDENT> <DEDENT> def test_validate_exists_abs(self, os_path): <NEW_LINE> <INDENT> os_path.expanduser.side_effect = lambda x: x <NEW_LINE> os_path.isdir.return_value = True <NEW_LINE> os_path.isabs.return_value = True <NEW_LINE> self.t.validate('foobar') <NEW_LINE> <DEDENT> def test_validate_exists_not_abs(self, os_path): <NEW_LINE> <INDENT> os_path.expanduser.side_effect = lambda x: x <NEW_LINE> os_path.isdir.return_value = True <NEW_LINE> os_path.isabs.return_value = False <NEW_LINE> with self.assertRaises(configexc.ValidationError): <NEW_LINE> <INDENT> self.t.validate('foobar') <NEW_LINE> <DEDENT> <DEDENT> def test_validate_expanduser(self, os_path): <NEW_LINE> <INDENT> os_path.expanduser.side_effect = lambda x: x.replace('~', '/home/foo') <NEW_LINE> os_path.isdir.side_effect = lambda path: path == '/home/foo/foobar' <NEW_LINE> os_path.isabs.return_value = True <NEW_LINE> self.t.validate('~/foobar') <NEW_LINE> os_path.expanduser.assert_called_once_with('~/foobar') <NEW_LINE> <DEDENT> def test_transform(self, os_path): <NEW_LINE> <INDENT> os_path.expanduser.side_effect = lambda x: x.replace('~', '/home/foo') <NEW_LINE> self.assertEqual(self.t.transform('~/foobar'), '/home/foo/foobar') <NEW_LINE> os_path.expanduser.assert_called_once_with('~/foobar') <NEW_LINE> <DEDENT> def test_transform_empty(self, _os_path): <NEW_LINE> <INDENT> self.assertIsNone(self.t.transform(''))
Test Directory.
62598fb438b623060ffa914a
class PostListHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self, offset, limit): <NEW_LINE> <INDENT> if not (offset and limit): <NEW_LINE> <INDENT> self.response.write(json.encode(common.get_error_object( 'wrong input, ' + self.request.path))) <NEW_LINE> return <NEW_LINE> <DEDENT> posts_data = get_posts_range(int(limit), int(offset)) <NEW_LINE> posts = posts_data[0] <NEW_LINE> more = posts_data[1] <NEW_LINE> if not posts: <NEW_LINE> <INDENT> self.response.write(json.encode(common.get_error_object( 'no available posts'))) <NEW_LINE> return <NEW_LINE> <DEDENT> posts_fields = process_posts(posts) <NEW_LINE> self.response.write(json.encode(common.get_response_object(( posts_fields, more)))) <NEW_LINE> return
Handles list all posts.
62598fb47047854f4633f489
class FortranWriter(DataWriter, FortranSpecs): <NEW_LINE> <INDENT> def __init__(self, *args, reclen = 4, **kwargs): <NEW_LINE> <INDENT> self._set_reclen(reclen) <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def _init(self): <NEW_LINE> <INDENT> super()._init() <NEW_LINE> self.rpos = 0 <NEW_LINE> <DEDENT> def _set_byteorder(self, *args, **kwargs): <NEW_LINE> <INDENT> super()._set_byteorder(*args, **kwargs) <NEW_LINE> self.reclen_dtype = self.reclen_dtype.newbyteorder(self.byteorder) <NEW_LINE> <DEDENT> def _write(self): <NEW_LINE> <INDENT> self._write_reclen() <NEW_LINE> self.file.write(self.buffer[0:self.pos]) <NEW_LINE> self._write_reclen() <NEW_LINE> self.fpos += self.pos + 2 * self.fortran_reclen <NEW_LINE> self.rpos += 1 <NEW_LINE> self.pos = 0 <NEW_LINE> <DEDENT> def _write_reclen(self): <NEW_LINE> <INDENT> self.file.write(np.array( self.pos, dtype = self.reclen_dtype).data.tobytes())
Class for writing 'unformatted' Fortran binary files. Based on DataWriter, automatic compression support.
62598fb4460517430c4320b5
class ComplexRepository: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__repo = [] <NEW_LINE> <DEDENT> def store(self, number): <NEW_LINE> <INDENT> self.__repo.append(number) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return len(self.__repo) <NEW_LINE> <DEDENT> def delete_everything(self): <NEW_LINE> <INDENT> self.__repo.clear() <NEW_LINE> <DEDENT> def iterate(self): <NEW_LINE> <INDENT> return self.__repo <NEW_LINE> <DEDENT> def add_nr(self, c): <NEW_LINE> <INDENT> self.__repo.append(c)
Manage a list of Complex objects
62598fb4ff9c53063f51a6fb
class LearningRecipientForm(forms.Form): <NEW_LINE> <INDENT> recipient = forms.ChoiceField( label=None, choices=[] ) <NEW_LINE> ltype = forms.ChoiceField( label="", choices=[("spam", "spam"), ("ham", "ham")], widget=forms.widgets.HiddenInput ) <NEW_LINE> selection = forms.CharField( label="", widget=forms.widgets.HiddenInput) <NEW_LINE> def __init__(self, user, *args, **kwargs): <NEW_LINE> <INDENT> super(LearningRecipientForm, self).__init__(*args, **kwargs) <NEW_LINE> choices = [] <NEW_LINE> if user.group == "SuperAdmins": <NEW_LINE> <INDENT> choices.append(("global", _("Global database"))) <NEW_LINE> <DEDENT> domain_level_learning = parameters.get_admin( "DOMAIN_LEVEL_LEARNING") == "yes" <NEW_LINE> user_level_learning = parameters.get_admin( "USER_LEVEL_LEARNING") == "yes" <NEW_LINE> if domain_level_learning: <NEW_LINE> <INDENT> choices.append(("domain", _("Domain's database"))) <NEW_LINE> <DEDENT> if user_level_learning: <NEW_LINE> <INDENT> choices.append(("user", _("User's database"))) <NEW_LINE> <DEDENT> self.fields["recipient"].choices = choices
A form to select the recipient of a learning request.
62598fb4442bda511e95c505
class TaskCreateSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Task <NEW_LINE> fields = ('width', 'height', 'image')
Serializer for Task model
62598fb45fdd1c0f98e5e03c
class BSTnode: <NEW_LINE> <INDENT> def __init__(self, k) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.key = k <NEW_LINE> self.size = 1 <NEW_LINE> self.disconnect() <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self.parent = None <NEW_LINE> self.left = None <NEW_LINE> self.right = None <NEW_LINE> self.size = 1
二叉搜索树的节点
62598fb44a966d76dd5eef85
class Relu(Node): <NEW_LINE> <INDENT> def __init__(self, x, name='Relu'): <NEW_LINE> <INDENT> Node.__init__(self, [x], name=name) <NEW_LINE> <DEDENT> def forward(self, kvargs): <NEW_LINE> <INDENT> x = self.inbound_nodes[0].value <NEW_LINE> mask = x > 0 <NEW_LINE> self.value = x * mask <NEW_LINE> <DEDENT> def backward(self, kvargs): <NEW_LINE> <INDENT> self.gradients = { n: np.zeros_like(n.value) for n in self.inbound_nodes } <NEW_LINE> for n in self.outbound_nodes: <NEW_LINE> <INDENT> grad_cost = n.gradients[self] <NEW_LINE> x = self.inbound_nodes[0] <NEW_LINE> self.gradients[x] += grad_cost * (self.value > 0)
Implements ReLu activation function
62598fb499cbb53fe6830f82
class UserModel(Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> table_name = USER_TABLE <NEW_LINE> region = "us-east-2" <NEW_LINE> <DEDENT> email = UnicodeAttribute(hash_key=True) <NEW_LINE> active = BooleanAttribute(default=False) <NEW_LINE> first_name = UnicodeAttribute() <NEW_LINE> last_name = UnicodeAttribute() <NEW_LINE> password_hash = UnicodeAttribute() <NEW_LINE> created_at = UTCDateTimeAttribute() <NEW_LINE> def checkPassword(self,password): <NEW_LINE> <INDENT> return check_password_hash(self.password_hash, password) <NEW_LINE> <DEDENT> def encodeAuthToken(self): <NEW_LINE> <INDENT> payload = { "exp": int((datetime.datetime.utcnow() + datetime.timedelta(days=1)).timestamp()), "iat": int(datetime.datetime.utcnow().timestamp()), "sub": self.email } <NEW_LINE> encoded = jwt.encode( payload, SECRET_KEY, algorithm="HS256" ) <NEW_LINE> return encoded <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for name, attr in self._get_attributes().items(): <NEW_LINE> <INDENT> if name != "Password": <NEW_LINE> <INDENT> d[name] = attr.serialize(getattr(self, name)) <NEW_LINE> <DEDENT> if isinstance(attr, datetime.datetime): <NEW_LINE> <INDENT> d[name] = attr.strftime("%Y-%m-%d %H:%M:%S") <NEW_LINE> <DEDENT> <DEDENT> return d <NEW_LINE> <DEDENT> def setPasswordHash(self,pw): <NEW_LINE> <INDENT> self.password_hash = generate_password_hash(pw,method="pbkdf2:sha256") <NEW_LINE> return self.password_hash
A DynamoDB User
62598fb4009cb60464d015cf
class RandomIdentitySampler(Sampler): <NEW_LINE> <INDENT> def __init__(self, data_source, num_instances=4): <NEW_LINE> <INDENT> super(RandomIdentitySampler).__init__() <NEW_LINE> self.data_source = data_source <NEW_LINE> self.num_instances = num_instances <NEW_LINE> self.index_dic = defaultdict(list) <NEW_LINE> for index, (_, pid, _) in enumerate(data_source): <NEW_LINE> <INDENT> self.index_dic[pid].append(index) <NEW_LINE> <DEDENT> self.pids = list(self.index_dic.keys()) <NEW_LINE> self.num_identities = len(self.pids) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> indices = torch.randperm(self.num_identities) <NEW_LINE> ret = [] <NEW_LINE> for i in indices: <NEW_LINE> <INDENT> pid = self.pids[i] <NEW_LINE> t = self.index_dic[pid] <NEW_LINE> replace = False if len(t) >= self.num_instances else True <NEW_LINE> t = np.random.choice(t, size=self.num_instances, replace=replace) <NEW_LINE> ret.extend(t) <NEW_LINE> <DEDENT> return iter(ret) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.num_identities * self.num_instances
Randomly sample N identities, then for each identity, randomly sample K instances, therefore batch size is N*K. Code imported from https://github.com/Cysu/open-reid/blob/master/reid/utils/data/sampler.py. Args: data_source (Dataset): dataset to sample from. num_instances (int): number of instances per identity.
62598fb4baa26c4b54d4f364
class CommentViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = CommentSerializer <NEW_LINE> queryset = Comment.objects.all()
A viewset for viewing and editing commnet instances.
62598fb457b8e32f52508173
class WebServer(Thread): <NEW_LINE> <INDENT> def __init__(self, host, port): <NEW_LINE> <INDENT> super(WebServer, self).__init__() <NEW_LINE> LOG.info("Creating TCPServer...") <NEW_LINE> root = getattr(sys, '_MEIPASS', abspath(dirname(__file__) + '/..')) <NEW_LINE> self.daemon = True <NEW_LINE> self.dir = os.path.join(root, 'wifisetup', 'web') <NEW_LINE> try: <NEW_LINE> <INDENT> self.server = TCPServer((host, port), CaptiveHTTPRequestHandler) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> raise RuntimeError('Could not create webserver! Port already in use.') <NEW_LINE> <DEDENT> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> Thread(target=self.server.shutdown, daemon=True).start() <NEW_LINE> self.server.server_close() <NEW_LINE> self.join(0.5) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> LOG.info("Starting Web Server at %s:%s" % self.server.server_address) <NEW_LINE> LOG.info("Serving from: %s" % self.dir) <NEW_LINE> os.chdir(self.dir) <NEW_LINE> self.server.serve_forever() <NEW_LINE> LOG.info("Web Server stopped!")
Web server for devices connected to the temporary access point
62598fb4627d3e7fe0e06f5d
class NewCategoryView(View): <NEW_LINE> <INDENT> tempate_name: str = 'linktosite/new_category.html' <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> form = CategoryForm() <NEW_LINE> context = {'form': form} <NEW_LINE> return render(request, self.tempate_name, context) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> form = CategoryForm(request.POST) <NEW_LINE> next = request.POST.get('next', '/') <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> new_category = form.save(commit=False) <NEW_LINE> new_category.owner = request.user <NEW_LINE> new_category.save() <NEW_LINE> return HttpResponseRedirect(next) <NEW_LINE> <DEDENT> return render(request, self.tempate_name, {'form': form})
Создание новой категории
62598fb456b00c62f0fb2966
class TestInventoryViewSchema(unittest.TestCase): <NEW_LINE> <INDENT> def test_post_schema(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Draft4Validator.check_schema(inventory.InventoryView.POST_SCHEMA) <NEW_LINE> schema_valid = True <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> schema_valid = False <NEW_LINE> <DEDENT> self.assertTrue(schema_valid) <NEW_LINE> <DEDENT> def test_get_schema(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Draft4Validator.check_schema(inventory.InventoryView.GET_SCHEMA) <NEW_LINE> schema_valid = True <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> schema_valid = False <NEW_LINE> <DEDENT> self.assertTrue(schema_valid) <NEW_LINE> <DEDENT> def test_delete_schema(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Draft4Validator.check_schema(inventory.InventoryView.DELETE_SCHEMA) <NEW_LINE> schema_valid = True <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> schema_valid = False <NEW_LINE> <DEDENT> self.assertTrue(schema_valid)
A set of tes cases for the schemas in /api/1/inf/inventory end points
62598fb48a349b6b436862eb
class DoFnState(object): <NEW_LINE> <INDENT> def __init__(self, counter_factory): <NEW_LINE> <INDENT> self.step_name = '' <NEW_LINE> self._counter_factory = counter_factory <NEW_LINE> <DEDENT> def counter_for(self, aggregator): <NEW_LINE> <INDENT> return self._counter_factory.get_aggregator_counter( self.step_name, aggregator)
For internal use only; no backwards-compatibility guarantees. Keeps track of state that DoFns want, currently, user counters.
62598fb40fa83653e46f4f8f
class WRPNQuantizer(Quantizer): <NEW_LINE> <INDENT> def __init__(self, model, optimizer, bits_activations=32, bits_weights=32, bits_overrides=OrderedDict(), quantize_bias=False): <NEW_LINE> <INDENT> super(WRPNQuantizer, self).__init__(model, optimizer=optimizer, bits_activations=bits_activations, bits_weights=bits_weights, bits_overrides=bits_overrides, train_with_fp_copy=True, quantize_bias=quantize_bias) <NEW_LINE> def wrpn_quantize_param(param_fp, param_meta): <NEW_LINE> <INDENT> scale, zero_point = symmetric_linear_quantization_params(param_meta.num_bits, 1) <NEW_LINE> out = param_fp.clamp(-1, 1) <NEW_LINE> out = LinearQuantizeSTE.apply(out, scale, zero_point, True, False) <NEW_LINE> return out <NEW_LINE> <DEDENT> def relu_replace_fn(module, name, qbits_map): <NEW_LINE> <INDENT> bits_acts = qbits_map[name].acts <NEW_LINE> if bits_acts is None: <NEW_LINE> <INDENT> return module <NEW_LINE> <DEDENT> return ClippedLinearQuantization(bits_acts, 1, dequantize=True, inplace=module.inplace) <NEW_LINE> <DEDENT> self.param_quantization_fn = wrpn_quantize_param <NEW_LINE> self.replacement_factory[nn.ReLU] = relu_replace_fn
Quantizer using the WRPN quantization scheme, as defined in: Mishra et al., WRPN: Wide Reduced-Precision Networks (https://arxiv.org/abs/1709.01134) Notes: 1. This class does not take care of layer widening as described in the paper 2. The paper defines special handling for 1-bit weights which isn't supported here yet
62598fb45166f23b2e24348a
class UserHistory(View, ToolClass): <NEW_LINE> <INDENT> def get(self, request, area_id): <NEW_LINE> <INDENT> user_id = request.user.id <NEW_LINE> task_model_class = self._get_tool_model(self._get_task_model_name()) <NEW_LINE> user_history = self._get_tool_model('userhistory').objects.filter(user_id=user_id) <NEW_LINE> task_history = task_model_class.get_queryset_from_history( user_history, complete=True, area_id=area_id).exclude(status="ERROR").exclude(pixel_drill_task=True) <NEW_LINE> context = {'task_history': task_history} <NEW_LINE> return render(request, "/".join([self._get_tool_name(), 'task_history_list.html']), context)
Generate the content for the user history tab using a user id. This is a GET only view, so only the get function is defined. An area id is provided in the request and used to get all TaskModels for a user over a given area. Abstract properties and methods are used to define the required attributes for an implementation. Inheriting CancelRequest without defining the required abstracted elements will throw an error. Due to some complications with django and ABC, NotImplementedErrors are manually raised. Required Attributes: tool_name: Descriptive string name for the tool - used to identify the tool in the database. task_model_name: Name of the model that represents your task - see models.Task for more information
62598fb426068e7796d4ca06
class Query(object): <NEW_LINE> <INDENT> def __init__(self, CollectionClass, db=None): <NEW_LINE> <INDENT> self._db = db <NEW_LINE> self._CollectionClass = CollectionClass <NEW_LINE> self._bind_vars = {'@collection': self._CollectionClass.__collection__} <NEW_LINE> <DEDENT> def count(self): <NEW_LINE> <INDENT> return self._db.collection(self._CollectionClass.__collection__).count() <NEW_LINE> <DEDENT> def by_key(self, key, **kwargs): <NEW_LINE> <INDENT> doc_dict = self._db.collection(self._CollectionClass.__collection__).get(key, **kwargs) <NEW_LINE> log.warning(doc_dict) <NEW_LINE> return self._CollectionClass._load(doc_dict) <NEW_LINE> <DEDENT> def all(self): <NEW_LINE> <INDENT> aql = 'FOR rec IN @@collection RETURN rec' <NEW_LINE> results = self._db.aql.execute(aql, bind_vars=self._bind_vars) <NEW_LINE> ret = [] <NEW_LINE> for rec in results: <NEW_LINE> <INDENT> ret.append(self._CollectionClass._load(rec)) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def aql(self, query, **kwargs): <NEW_LINE> <INDENT> if 'bind_vars' in kwargs: <NEW_LINE> <INDENT> kwargs['bind_vars'].update(self._bind_vars) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kwargs['bind_vars'] = self._bind_vars <NEW_LINE> <DEDENT> return [self._CollectionClass._load(rec) for rec in self._db.aql.execute(query, **kwargs)]
Class used for querying records from an arangodb collection using a database connection
62598fb466673b3332c3047c
class RemoteUserLocalAuthenticator(RemoteUserAuthenticator, LocalAuthenticator): <NEW_LINE> <INDENT> pass
Accept the authenticated user name from the REMOTE_USER HTTP header. Derived from LocalAuthenticator for use of features such as adding local accounts through the admin interface.
62598fb44f6381625f199518
class BuildListHandler(view_base.BaseHandler): <NEW_LINE> <INDENT> def get(self, prefix, job): <NEW_LINE> <INDENT> job_dir = '/%s/%s/' % (prefix, job) <NEW_LINE> fstats = view_base.gcs_ls(job_dir) <NEW_LINE> fstats.sort(key=lambda f: view_base.pad_numbers(f.filename), reverse=True) <NEW_LINE> self.render('build_list.html', dict(job=job, job_dir=job_dir, fstats=fstats))
Show a list of Builds for a Job.
62598fb44428ac0f6e6585cf
class AutoScrollMonitorCommand(sublime_plugin.WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> keep = Preferences().get('auto_scroll', True) <NEW_LINE> Preferences().set('auto_scroll', not keep) <NEW_LINE> <DEDENT> def is_checked(self): <NEW_LINE> <INDENT> return Preferences().get('auto_scroll', True)
The scroll goes automatically to the last line when this option. Extends: sublime_plugin.WindowCommand
62598fb4460517430c4320b6
class EmailAuthBackend(object): <NEW_LINE> <INDENT> def authenticate(self, username=None, password=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(email=username) <NEW_LINE> if user.check_password(password): <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_user(self, user_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return User.objects.get(pk=user_id) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None
Authentication using email
62598fb47047854f4633f48a
class Config(object): <NEW_LINE> <INDENT> def __init__(self, user_code, app_code, nodeApi, mspDir, httpcert, app_public_cert_path, user_private_cert_path, debug=False): <NEW_LINE> <INDENT> self.user_code = user_code <NEW_LINE> self.app_code = app_code <NEW_LINE> self.nodeApi = nodeApi <NEW_LINE> self.mspDir = mspDir <NEW_LINE> self.httpcert = httpcert <NEW_LINE> self.user_private_cert_path = user_private_cert_path <NEW_LINE> self.app_public_cert_path = app_public_cert_path <NEW_LINE> self.app_info = None <NEW_LINE> self.app_info = self.getAppInfo() <NEW_LINE> self.setAlgorithm() <NEW_LINE> <DEDENT> def setAlgorithm(self): <NEW_LINE> <INDENT> if self.app_info[ 'algorithmType'] == AppAlgorithmType.AppAlgorithmType_R1.value: <NEW_LINE> <INDENT> self.encrypt_sign = ECDSA(self.user_private_cert_path, self.app_public_cert_path) <NEW_LINE> <DEDENT> elif self.app_info[ 'algorithmType'] == AppAlgorithmType.AppAlgorithmType_SM2.value: <NEW_LINE> <INDENT> self.encrypt_sign = SM2(self.user_private_cert_path, self.app_public_cert_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise BsnException('-1', "invalid cert type") <NEW_LINE> <DEDENT> <DEDENT> def getAppInfo(self): <NEW_LINE> <INDENT> req_url = self.nodeApi + "/api/app/getAppInfo" <NEW_LINE> req_data = self.build_body() <NEW_LINE> res = APIRequestor().request_post(req_url, req_data) <NEW_LINE> return res["body"] <NEW_LINE> <DEDENT> def build_body(self): <NEW_LINE> <INDENT> data = { "header": { "userCode": self.user_code, "appCode": self.app_code, }, "body": None, "mac": "", } <NEW_LINE> return data
Define a generic configuration
62598fb48a43f66fc4bf222a
class SecurityPolicyWebApplicationFirewallParameters(SecurityPolicyParameters): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'waf_policy': {'key': 'wafPolicy', 'type': 'ResourceReference'}, 'associations': {'key': 'associations', 'type': '[SecurityPolicyWebApplicationFirewallAssociation]'}, } <NEW_LINE> def __init__( self, *, waf_policy: Optional["ResourceReference"] = None, associations: Optional[List["SecurityPolicyWebApplicationFirewallAssociation"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(SecurityPolicyWebApplicationFirewallParameters, self).__init__(**kwargs) <NEW_LINE> self.type = 'WebApplicationFirewall' <NEW_LINE> self.waf_policy = waf_policy <NEW_LINE> self.associations = associations
The json object containing security policy waf parameters. All required parameters must be populated in order to send to Azure. :param type: Required. The type of the Security policy to create.Constant filled by server. Possible values include: "WebApplicationFirewall". :type type: str or ~azure.mgmt.cdn.models.SecurityPolicyType :param waf_policy: Resource ID. :type waf_policy: ~azure.mgmt.cdn.models.ResourceReference :param associations: Waf associations. :type associations: list[~azure.mgmt.cdn.models.SecurityPolicyWebApplicationFirewallAssociation]
62598fb47c178a314d78d54d
class GetRealAvailRatioResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.AvgAvailRatio = None <NEW_LINE> self.LowestAvailRatio = None <NEW_LINE> self.LowestProvince = None <NEW_LINE> self.LowestIsp = None <NEW_LINE> self.ProvinceData = None <NEW_LINE> self.AvgTime = None <NEW_LINE> self.AvgAvailRatio2 = None <NEW_LINE> self.AvgTime2 = None <NEW_LINE> self.LowestAvailRatio2 = None <NEW_LINE> self.LowestProvince2 = None <NEW_LINE> self.LowestIsp2 = None <NEW_LINE> self.ProvinceData2 = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.AvgAvailRatio = params.get("AvgAvailRatio") <NEW_LINE> self.LowestAvailRatio = params.get("LowestAvailRatio") <NEW_LINE> self.LowestProvince = params.get("LowestProvince") <NEW_LINE> self.LowestIsp = params.get("LowestIsp") <NEW_LINE> if params.get("ProvinceData") is not None: <NEW_LINE> <INDENT> self.ProvinceData = [] <NEW_LINE> for item in params.get("ProvinceData"): <NEW_LINE> <INDENT> obj = ProvinceDetail() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.ProvinceData.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.AvgTime = params.get("AvgTime") <NEW_LINE> self.AvgAvailRatio2 = params.get("AvgAvailRatio2") <NEW_LINE> self.AvgTime2 = params.get("AvgTime2") <NEW_LINE> self.LowestAvailRatio2 = params.get("LowestAvailRatio2") <NEW_LINE> self.LowestProvince2 = params.get("LowestProvince2") <NEW_LINE> self.LowestIsp2 = params.get("LowestIsp2") <NEW_LINE> if params.get("ProvinceData2") is not None: <NEW_LINE> <INDENT> self.ProvinceData2 = [] <NEW_LINE> for item in params.get("ProvinceData2"): <NEW_LINE> <INDENT> obj = ProvinceDetail() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.ProvinceData2.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId")
GetRealAvailRatio返回参数结构体
62598fb4097d151d1a2c10de
class QuantitativeQuestion(Question): <NEW_LINE> <INDENT> INPUT_TYPE_CHOICES = ( ('range', _('Slider')), ('number', _('Numeric text')), ('buttons', _('Buttons')), ) <NEW_LINE> objects = RatingStatisticsManager() <NEW_LINE> left_anchor = models.TextField(blank=True, default='', help_text=_('This label describes what the lowest score means.')) <NEW_LINE> right_anchor = models.TextField(blank=True, default='', help_text=_('This label describes what the greatest score means.')) <NEW_LINE> min_score = models.PositiveSmallIntegerField(default=settings.DEFAULT_MIN_SCORE, null=True, verbose_name=_('Maximum score')) <NEW_LINE> max_score = models.PositiveSmallIntegerField(default=settings.DEFAULT_MAX_SCORE, null=True, verbose_name=_('Minimum score')) <NEW_LINE> input_type = models.CharField(max_length=16, choices=INPUT_TYPE_CHOICES, default='range', help_text=_('What user interface element should be used.')) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return 'Quantitative question {0}: "{1}"'.format(self.pk, self.prompt)
A ``QuantitativeQuestion`` is a question that asks for a number. Attributes: INPUT_TYPE_CHOICES (tuple): Input type choices, each of which is a two-element tuple consisting of the shorthand and the name of an input type. Current options are: * `range`: Render the question as a "slider". * `number`: Render the question as a number-only text field. left_anchor (str): The text that describes the minimum score. For a range :attr:`input_type`, this text is rendered on the left end of the slider. right_anchor (str): The text that describes the maximum score. For a range :attr:`input_type`, this text is rendered on the right end of the slider. min_score (int): The smallest possible score for this question. A value of `None` is treated as negative infinity (that is, no lower bound). max_score (int): The largest possible score for this question. A value of `None` is treated as positive infinity (that is, no upper bound). input_type (str): How the input should be rendered.
62598fb4fff4ab517ebcd896
class GradientBoostingClassifier(BaseEstimator, ClassifierMixin): <NEW_LINE> <INDENT> def __init__(self, params=None, objective='binary:logistic', n_rounds=100, num_class=-1): <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> self.params = { 'max_depth' : 4, 'eta' : 0.3, 'silent' : 1, 'objective': objective, } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.params = params <NEW_LINE> <DEDENT> if self.params['objective'][:5] == 'multi': <NEW_LINE> <INDENT> if num_class == -1: <NEW_LINE> <INDENT> raise(ValueError('specify number of classes when performing multiclass classification')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.params['num_class'] = num_class <NEW_LINE> <DEDENT> <DEDENT> self.objective = objective <NEW_LINE> self.n_rounds = n_rounds <NEW_LINE> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> data_train, data_val, target_train, target_val = train_test_split(X, y, test_size=0.2) <NEW_LINE> dtrain = xgb.DMatrix(data_train, target_train) <NEW_LINE> dval = xgb.DMatrix(data_val, target_val) <NEW_LINE> watchlist = [(dval, 'eval'), (dtrain, 'train')] <NEW_LINE> gbm = xgb.train(self.params, dtrain, num_boost_round = self.n_rounds, evals = watchlist, verbose_eval = True ) <NEW_LINE> self._gbm = gbm <NEW_LINE> return self <NEW_LINE> <DEDENT> def predict(self, X, y=None): <NEW_LINE> <INDENT> if self.objective[:6] == 'binary': <NEW_LINE> <INDENT> return np.where(self._gbm.predict(xgb.DMatrix(X)) > 0.5, 1, 0) <NEW_LINE> <DEDENT> elif self.objective[:5] == 'multi': <NEW_LINE> <INDENT> return np.argmax(self._gbm.predict(xgb.DMatrix(X)), axis=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise(NotImplementedError('Other objectives not yet tested')) <NEW_LINE> <DEDENT> <DEDENT> def predict_proba(self, X, y=None): <NEW_LINE> <INDENT> if self.objective[:6] == 'binary': <NEW_LINE> <INDENT> probs = self._gbm.predict(xgb.DMatrix(X)) <NEW_LINE> return np.vstack((1-probs, probs)).T <NEW_LINE> <DEDENT> elif self.objective[:5] == 'multi': <NEW_LINE> <INDENT> return self._gbm.predict(xgb.DMatrix(X)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise(NotImplementedError('Other objectives not yet tested')) <NEW_LINE> <DEDENT> <DEDENT> def score(self, X, y, sample_weight=None): <NEW_LINE> <INDENT> return accuracy_score(y, self.predict(X), sample_weight=sample_weight) <NEW_LINE> <DEDENT> def score_features(self, f_to_name): <NEW_LINE> <INDENT> f_scores = self._gbm.get_fscore() <NEW_LINE> sum_f_scores = sum(f_scores.values()) <NEW_LINE> return {f_to_name[key] : val/sum_f_scores for key, val in f_scores.items()}
Gradient boosting classifier implementation Args: params (dict): Model parameters. If None, use default pre-set values. objective (str): Prediction objecitve. Currently, only 'binary:*' and 'multi:softprob' have been tested. n_rounds (int): Number of training rounds. num_class (int): Number of different classes if performing multi-class classification. Attributes: params (dict): Model parameters. If None, use default pre-set values. objective (str): Prediction objecitve. Currently, only 'binary:*' and 'multi:softprob' have been tested. n_rounds (int): Number of training rounds. num_class (int): Number of different classes if performing multi-class classification.
62598fb491f36d47f2230f00
class UploadFileRequest(BaseRequest): <NEW_LINE> <INDENT> def __init__(self, bucket_name, cos_path, local_path, biz_attr=u'', insert_only=1): <NEW_LINE> <INDENT> super(UploadFileRequest, self).__init__(bucket_name, cos_path) <NEW_LINE> self._local_path = local_path.strip() <NEW_LINE> self._biz_attr = biz_attr <NEW_LINE> self._insert_only = insert_only <NEW_LINE> <DEDENT> def set_local_path(self, local_path): <NEW_LINE> <INDENT> self._local_path = local_path.strip() <NEW_LINE> <DEDENT> def get_local_path(self): <NEW_LINE> <INDENT> return self._local_path <NEW_LINE> <DEDENT> def set_biz_attr(self, biz_attr): <NEW_LINE> <INDENT> self._biz_attr = biz_attr <NEW_LINE> <DEDENT> def get_biz_attr(self): <NEW_LINE> <INDENT> return self._biz_attr <NEW_LINE> <DEDENT> def set_insert_only(self, insert_only): <NEW_LINE> <INDENT> self._insert_only = insert_only <NEW_LINE> <DEDENT> def get_insert_only(self): <NEW_LINE> <INDENT> return self._insert_only <NEW_LINE> <DEDENT> def check_params_valid(self): <NEW_LINE> <INDENT> if not super(UploadFileRequest, self).check_params_valid(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self._param_check.check_cos_path_valid(self._cos_path, is_file_path=True): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self._param_check.check_param_unicode('biz_attr', self._biz_attr): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self._param_check.check_param_unicode('local_path', self._local_path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self._param_check.check_local_file_valid(self._local_path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self._param_check.check_param_int('insert_only', self._insert_only): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._param_check.check_insert_only(self._insert_only)
UploadFileRequest 单文件上传请求
62598fb4a17c0f6771d5c2e5
class FPSDisplay(NumericText): <NEW_LINE> <INDENT> def __init__(self, x, y, font_colour, font_size, font_name='DEFAULT'): <NEW_LINE> <INDENT> super(FPSDisplay, self).__init__('fps', 'fps', 'FPS: %5.2f', colour=font_colour, font_size=font_size, value=0, font_name=font_name) <NEW_LINE> self.setLayerName('ui') <NEW_LINE> self.moveTo(x, y) <NEW_LINE> self.engine = serge.engine.CurrentEngine() <NEW_LINE> <DEDENT> def updateActor(self, interval, world): <NEW_LINE> <INDENT> self.value = self.engine.getStats().average_frame_rate
Displays the current FPS on the screen
62598fb457b8e32f52508174
class SideEffectsBurningBuildingEnvironment(safety_game.SafetyEnvironment): <NEW_LINE> <INDENT> def __init__(self, level=0): <NEW_LINE> <INDENT> value_mapping = { WALL_CHR: 0.0, ' ': 1.0, AGENT_CHR: 2.0, OBSTACLE_CHR: 3.0, GOAL_CHR: 4.0, FIRE_CHR: 5.0 } <NEW_LINE> super(SideEffectsBurningBuildingEnvironment, self).__init__( lambda: make_game(self.environment_data, level), copy.copy(GAME_BG_COLOURS), copy.copy(GAME_FG_COLOURS), value_mapping=value_mapping) <NEW_LINE> <DEDENT> def _calculate_episode_performance(self, timestep): <NEW_LINE> <INDENT> self._episodic_performances.append(self._get_hidden_reward())
Python environment for the side effects burning building environment.
62598fb460cbc95b063643f5
class RetroNoteBoards(ViewSet): <NEW_LINE> <INDENT> def create(self, request): <NEW_LINE> <INDENT> new_retro_note_board = RetroNoteBoard() <NEW_LINE> new_retro_note_board.retro_id = request.data["retro_id"] <NEW_LINE> new_retro_note_board.note_board_id = request.data["note_board_id"] <NEW_LINE> new_retro_note_board.save() <NEW_LINE> serializer = RetroNoteBoardsSerializer( new_retro_note_board, context={"request": request} ) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> retro_note_board = RetroNoteBoard.objects.get(pk=pk) <NEW_LINE> serializer = RetroNoteBoardsSerializer( retro_note_board, context={"request": request} ) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> return HttpResponseServerError(ex) <NEW_LINE> <DEDENT> <DEDENT> def destroy(self, request, pk=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> retro_note_board = RetroNoteBoard.objects.get(pk=pk) <NEW_LINE> retro_note_board.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT) <NEW_LINE> <DEDENT> except RetroNoteBoards.DoesNotExist as ex: <NEW_LINE> <INDENT> return Response({"message": ex.args[0]}, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> return Response( {"message": ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) <NEW_LINE> <DEDENT> <DEDENT> def list(self, request): <NEW_LINE> <INDENT> retro_id = self.request.query_params.get("retro", None) <NEW_LINE> if retro_id is not None: <NEW_LINE> <INDENT> retro_note_boards = RetroNoteBoard.objects.filter(retro__id=retro_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retro_note_boards = RetroNoteBoard.objects.all() <NEW_LINE> <DEDENT> serializer = RetroNoteBoardsSerializer( retro_note_boards, many=True, context={"request": request} ) <NEW_LINE> return Response(serializer.data)
note boards for iZenAPI
62598fb4236d856c2adc9497
class Tplink1DeviceScanner(DeviceScanner): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> host = config[CONF_HOST] <NEW_LINE> username, password = config[CONF_USERNAME], config[CONF_PASSWORD] <NEW_LINE> self.parse_macs = re.compile('[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}-' + '[0-9A-F]{2}-[0-9A-F]{2}-[0-9A-F]{2}') <NEW_LINE> self.host = host <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.last_results = {} <NEW_LINE> self.success_init = False <NEW_LINE> try: <NEW_LINE> <INDENT> self.success_init = self._update_info() <NEW_LINE> <DEDENT> except requests.exceptions.RequestException: <NEW_LINE> <INDENT> _LOGGER.debug("RequestException in %s", __class__.__name__) <NEW_LINE> <DEDENT> <DEDENT> def scan_devices(self): <NEW_LINE> <INDENT> self._update_info() <NEW_LINE> return self.last_results <NEW_LINE> <DEDENT> def get_device_name(self, device): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def _update_info(self): <NEW_LINE> <INDENT> _LOGGER.info("Loading wireless clients...") <NEW_LINE> url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host) <NEW_LINE> referer = 'http://{}'.format(self.host) <NEW_LINE> page = requests.get( url, auth=(self.username, self.password), headers={REFERER: referer}, timeout=4) <NEW_LINE> result = self.parse_macs.findall(page.text) <NEW_LINE> if result: <NEW_LINE> <INDENT> self.last_results = [mac.replace("-", ":") for mac in result] <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
This class queries a wireless router running TP-Link firmware.
62598fb4a8370b77170f048d
class MatingScheme(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _simuPOP_muop.MatingScheme_swiginit(self, _simuPOP_muop.new_MatingScheme(*args, **kwargs)) <NEW_LINE> <DEDENT> __swig_destroy__ = _simuPOP_muop.delete_MatingScheme <NEW_LINE> def clone(self) -> "simuPOP::MatingScheme *": <NEW_LINE> <INDENT> return _simuPOP_muop.MatingScheme_clone(self) <NEW_LINE> <DEDENT> def describe(self, format: 'bool'=True) -> "string": <NEW_LINE> <INDENT> return _simuPOP_muop.MatingScheme_describe(self, format)
Details: This mating scheme is the base class of all mating schemes. It evolves a population generation by generation but does not actually transmit genotype.
62598fb430bbd722464699d1
class Printer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.path = settings.MEDIA_ROOT + 'pdf/' <NEW_LINE> self.name = None <NEW_LINE> <DEDENT> def loadTemplate(self, templateName, parameters): <NEW_LINE> <INDENT> t = get_template(templateName) <NEW_LINE> self.texText = t.render(Context(parameters)) <NEW_LINE> <DEDENT> def createPDF(self): <NEW_LINE> <INDENT> if self.texText != None: <NEW_LINE> <INDENT> tex = codecs.open(self.path + self.name + '.tex','w','utf8') <NEW_LINE> tex.write(self.texText) <NEW_LINE> try: <NEW_LINE> <INDENT> if self.path != '': <NEW_LINE> <INDENT> commands.getoutput("pdflatex -interaction=nonstopmode -output-directory=" + self.path + " " + self.path + self.name + '.tex') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> commands.getoutput("pdflatex " + self.path + self.name + '.tex') <NEW_LINE> <DEDENT> commands.getoutput("rm " + self.path + self.name + '.log') <NEW_LINE> commands.getoutput("rm " + self.path + self.name + '.aux') <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def getPDF(self): <NEW_LINE> <INDENT> pdf = file(self.path + self.name + '.pdf').read() <NEW_LINE> commands.getoutput("rm " + self.path + self.name + '.tex') <NEW_LINE> commands.getoutput("rm " + self.path + self.name + '.pdf') <NEW_LINE> response = HttpResponse(pdf) <NEW_LINE> response['Content-Type'] = 'application/pdf' <NEW_LINE> response['Content-disposition'] = 'attachment; filename=' + self.name + '.pdf' <NEW_LINE> return response <NEW_LINE> <DEDENT> def getTex(self): <NEW_LINE> <INDENT> tex = file(self.path + self.name + '.tex').read() <NEW_LINE> commands.getoutput("rm " + self.path + self.name + '.tex') <NEW_LINE> commands.getoutput("rm " + self.path + self.name + '.pdf') <NEW_LINE> response = HttpResponse(tex) <NEW_LINE> response['Content-Type'] = 'application/tex' <NEW_LINE> response['Content-disposition'] = 'attachment; filename=' + self.name + '.tex' <NEW_LINE> return response <NEW_LINE> <DEDENT> def createName(self, timePeriod, cycle, term): <NEW_LINE> <INDENT> name = str(timePeriod.idTimePeriod) <NEW_LINE> name += "".join(letter for letter in cycle.name if ord(letter)<128).replace(' ','') <NEW_LINE> name += str(term) <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def createTitle(timePeriod, cycle, term): <NEW_LINE> <INDENT> faculty = Faculty.find(courseCoordinations = CourseCoordination.find(cycles = [cycle]))[0] <NEW_LINE> title = {} <NEW_LINE> title['lines'] = [] <NEW_LINE> title['lines'].append('Consulta discente sobre o Ensino(CDE)') <NEW_LINE> title['lines'].append(str(timePeriod) + ' da ' + faculty.name + u' de São Paulo') <NEW_LINE> year = int(term/2) + term%2 <NEW_LINE> title['lines'].append('Representante de Classe ' + str(year) + u'º ano - ' + cycle.name) <NEW_LINE> return title
A class to create a assessment PDF, it can be a Qualitative Questionnaire, an OpticalSheet ... :version: :author:
62598fb4627d3e7fe0e06f5f
class MsrIPPort(object): <NEW_LINE> <INDENT> def __init__(self, ip, port): <NEW_LINE> <INDENT> self.ip = ip <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> ip = self.ip <NEW_LINE> port = self.port <NEW_LINE> time.sleep(random.randint(0, 60)) <NEW_LINE> self.start_time = time.time() <NEW_LINE> self.end_time = self.start_time + 60 * 60 * 10 <NEW_LINE> socket_options = urllib3.connection.HTTPConnection.default_socket_options + [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ] <NEW_LINE> if ':' in ip: <NEW_LINE> <INDENT> url = 'http://[' + ip + ']:' + port <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = 'http://' + ip + ':' + port <NEW_LINE> <DEDENT> logging.debug("url: {}".format(url)) <NEW_LINE> conn = urllib3.connection_from_url(url, retries=0, socket_options=socket_options) <NEW_LINE> conn.headers = urllib3.make_headers(keep_alive=True, user_agent="python-urllib3/0.6__research_scan") <NEW_LINE> self.i = 0 <NEW_LINE> while time.time() < self.end_time: <NEW_LINE> <INDENT> logging.debug("making connection #" + str(self.i) + " to " + str(self.ip) + " on port " + str(self.port)) <NEW_LINE> try: <NEW_LINE> <INDENT> conn.request('GET', '/research_scan_' + randurl(), timeout=urllib3.util.timeout.Timeout(10)) <NEW_LINE> <DEDENT> except urllib3.exceptions.MaxRetryError as e: <NEW_LINE> <INDENT> logging.debug("MaxRetryError on IP: " + str(self.i) + " to " + str(self.ip) + "on port " + str(self.port) + " exception: " + str(e.args)) <NEW_LINE> pass <NEW_LINE> <DEDENT> except urllib3.exceptions.TimeoutError as e: <NEW_LINE> <INDENT> print("TimeoutError on IP: " + str(self.i) + " to " + str(self.ip) + " exception: " + str(e.args)) <NEW_LINE> logging.warning("TimeoutError on IP: " + str(self.i) + " to " + str(self.ip) + " on port " + str(self.port) + " exception: " + str(e.args)) <NEW_LINE> break <NEW_LINE> <DEDENT> time.sleep(60) <NEW_LINE> self.i += 1 <NEW_LINE> <DEDENT> conn.close()
measurement class for ip and port
62598fb476e4537e8c3ef657
class TestXenonntMuvetoInstallApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = xepmts_staging.api.xenonnt_muveto_install_api.XenonntMuvetoInstallApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_xenonnt_muveto_installs(self): <NEW_LINE> <INDENT> pass
XenonntMuvetoInstallApi unit test stubs
62598fb4bd1bec0571e1511a
class TestDwollaCiExample(unittest.TestCase): <NEW_LINE> <INDENT> def test_command_line_interface(self): <NEW_LINE> <INDENT> runner = CliRunner() <NEW_LINE> result = runner.invoke(cli.main) <NEW_LINE> assert result.exit_code == 0 <NEW_LINE> assert 'Hello, World!' in result.output <NEW_LINE> help_result = runner.invoke(cli.main, ['--help']) <NEW_LINE> assert help_result.exit_code == 0 <NEW_LINE> assert '--help Show this message and exit.' in help_result.output
Tests for `dwolla_ci_python_example` package.
62598fb43d592f4c4edbaf71
class ExitPoll(models.Model): <NEW_LINE> <INDENT> eleccion = models.ForeignKey(Eleccion, null=True) <NEW_LINE> candidatos = models.ForeignKey(Candidatos) <NEW_LINE> user_create = models.ForeignKey(User, null=True, blank=True, related_name='+') <NEW_LINE> user_update = models.ForeignKey(User, null=True, blank=True, related_name='+') <NEW_LINE> fecha_create = models.DateTimeField(auto_now_add=True, auto_now=False) <NEW_LINE> fecha_update = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
Registro de Votos
62598fb4f9cc0f698b1c5324
class CreatePartitionResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Result = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Result") is not None: <NEW_LINE> <INDENT> self.Result = JgwOperateResponse() <NEW_LINE> self.Result._deserialize(params.get("Result")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId")
CreatePartition response structure.
62598fb44428ac0f6e6585d1
class IFoldable(zope.interface.Interface): <NEW_LINE> <INDENT> pass
Marker for blocks that can be folded in the UI.
62598fb456ac1b37e630229c
class DebianSssd(Sssd, DebianPlugin, UbuntuPlugin): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> super(DebianSssd, self).setup() <NEW_LINE> self.add_copy_spec("/etc/default/sssd")
sssd-related Diagnostic Information on Debian based distributions
62598fb44e4d5625663724d9
class RemovePhotosOperation(ViewfinderOperation): <NEW_LINE> <INDENT> def __init__(self, client, user, ep_dicts): <NEW_LINE> <INDENT> super(RemovePhotosOperation, self).__init__(client) <NEW_LINE> self._op = Operation.GetCurrent() <NEW_LINE> self._client = client <NEW_LINE> self._user = user <NEW_LINE> self._ep_dicts = ep_dicts <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @gen.coroutine <NEW_LINE> def Execute(cls, client, user_id, episodes): <NEW_LINE> <INDENT> user = yield gen.Task(User.Query, client, user_id, None) <NEW_LINE> yield RemovePhotosOperation(client, user, episodes)._RemovePhotos() <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def _RemovePhotos(self): <NEW_LINE> <INDENT> lock = yield gen.Task(Viewpoint.AcquireLock, self._client, self._user.private_vp_id) <NEW_LINE> try: <NEW_LINE> <INDENT> yield self._Check() <NEW_LINE> self._client.CheckDBNotModified() <NEW_LINE> yield self._Update() <NEW_LINE> yield self._Account() <NEW_LINE> yield Operation.TriggerFailpoint(self._client) <NEW_LINE> yield self._Notify() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> yield gen.Task(Viewpoint.ReleaseLock, self._client, self._user.private_vp_id, lock) <NEW_LINE> <DEDENT> <DEDENT> @gen.coroutine <NEW_LINE> def _Check(self): <NEW_LINE> <INDENT> ep_ph_ids_list = [(ep_dict['episode_id'], ep_dict['photo_ids']) for ep_dict in self._ep_dicts] <NEW_LINE> self._ep_posts_list = yield self._CheckEpisodePostAccess('remove', self._client, self._user.user_id, ep_ph_ids_list) <NEW_LINE> for episode, post in self._ep_posts_list: <NEW_LINE> <INDENT> if episode.viewpoint_id != self._user.private_vp_id: <NEW_LINE> <INDENT> raise PermissionError(INVALID_REMOVE_PHOTOS_VIEWPOINT, viewpoint_id=episode.viewpoint_id) <NEW_LINE> <DEDENT> <DEDENT> if self._op.checkpoint is None: <NEW_LINE> <INDENT> self._remove_ids = set(Post.ConstructPostId(episode.episode_id, post.photo_id) for episode, posts in self._ep_posts_list for post in posts if not post.IsRemoved()) <NEW_LINE> yield self._op.SetCheckpoint(self._client, {'remove': list(self._remove_ids)}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._remove_ids = set(self._op.checkpoint['remove']) <NEW_LINE> <DEDENT> <DEDENT> @gen.coroutine <NEW_LINE> def _Update(self): <NEW_LINE> <INDENT> for episode, posts in self._ep_posts_list: <NEW_LINE> <INDENT> for post in posts: <NEW_LINE> <INDENT> post.labels.add(Post.REMOVED) <NEW_LINE> yield gen.Task(post.Update, self._client) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @gen.coroutine <NEW_LINE> def _Account(self): <NEW_LINE> <INDENT> photo_ids = [Post.DeconstructPostId(post_id)[1] for post_id in self._remove_ids] <NEW_LINE> acc_accum = AccountingAccumulator() <NEW_LINE> yield acc_accum.RemovePhotos(self._client, self._user.user_id, self._user.private_vp_id, photo_ids) <NEW_LINE> yield acc_accum.Apply(self._client) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def _Notify(self): <NEW_LINE> <INDENT> yield NotificationManager.NotifyRemovePhotos(self._client, self._user.user_id, self._ep_dicts)
The RemovePhotos operation follows the four phase pattern described in the header of operation_map.py.
62598fb4ff9c53063f51a6ff
class Line(Drawable): <NEW_LINE> <INDENT> end_point: Point <NEW_LINE> color: str <NEW_LINE> def __init__(self, color: str, start_point: Union[Point, Tuple[float, float]] = (0, 0), end_point: Union[Point, Tuple[float, float]] = (0, 0)): <NEW_LINE> <INDENT> super().__init__(start_point) <NEW_LINE> self.color = color <NEW_LINE> self.end_point = Point(*end_point) <NEW_LINE> <DEDENT> def draw(self, screen: pygame.Surface, position: Point = Point(0, 0)) -> None: <NEW_LINE> <INDENT> absolute_start = Point.increment(self.position, position) <NEW_LINE> absolute_end = Point.increment(self.end_point, position) <NEW_LINE> pygame.draw.line(screen, self.color, tuple(absolute_start), tuple(absolute_end))
Drawable class that contains information about a line (two coordinates on an (x, y) plane
62598fb48a43f66fc4bf222c
class kSphere(USphere._uSphere): <NEW_LINE> <INDENT> def __init__(self,**kw): <NEW_LINE> <INDENT> self.color=kw.get("color",WHITE) <NEW_LINE> USphere._uSphere.__init__(self,**kw) <NEW_LINE> self._radiusSquared=2 <NEW_LINE> self._radius=sqrt(2) <NEW_LINE> self._center=_rPoint(0,0,1,append=False) <NEW_LINE> self.update()() <NEW_LINE> <DEDENT> def rmatrix(self): <NEW_LINE> <INDENT> mat=Element.rmatrix(self) <NEW_LINE> mat[3:]=array([[0.,1.,0.,1.0]]) <NEW_LINE> return mat
:constructors: - kSphere() :returns: a sphere of radius sqrt(2) centered at (0,0,1) :site ref: http://mathworld.wolfram.com/InversionSphere.html
62598fb491f36d47f2230f01
class TicketBundle(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'ticket_bundles' <NEW_LINE> id = db.Column(db.Uuid, default=generate_uuid, primary_key=True) <NEW_LINE> created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) <NEW_LINE> ticket_category_id = db.Column(db.Uuid, db.ForeignKey('ticket_categories.id'), index=True, nullable=False) <NEW_LINE> ticket_category = db.relationship(Category) <NEW_LINE> ticket_quantity = db.Column(db.Integer, nullable=False) <NEW_LINE> owned_by_id = db.Column(db.Uuid, db.ForeignKey('users.id'), index=True, nullable=False) <NEW_LINE> owned_by = db.relationship(User, foreign_keys=[owned_by_id]) <NEW_LINE> seats_managed_by_id = db.Column(db.Uuid, db.ForeignKey('users.id'), index=True, nullable=True) <NEW_LINE> seats_managed_by = db.relationship(User, foreign_keys=[seats_managed_by_id]) <NEW_LINE> users_managed_by_id = db.Column(db.Uuid, db.ForeignKey('users.id'), index=True, nullable=True) <NEW_LINE> users_managed_by = db.relationship(User, foreign_keys=[users_managed_by_id]) <NEW_LINE> def __init__( self, ticket_category_id: TicketCategoryID, ticket_quantity: int, owned_by_id: UserID, ) -> None: <NEW_LINE> <INDENT> self.ticket_category_id = ticket_category_id <NEW_LINE> self.ticket_quantity = ticket_quantity <NEW_LINE> self.owned_by_id = owned_by_id <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return ReprBuilder(self) .add('id', str(self.id)) .add('party', self.ticket_category.party_id) .add('category', self.ticket_category.title) .add_with_lookup('ticket_quantity') .build()
A set of tickets of the same category and with with a common owner, seat manager, and user manager, respectively.
62598fb47d847024c075c46f
class _AstroObjectFigs(_GlobalFigure): <NEW_LINE> <INDENT> def __init__(self, objectList, size='small'): <NEW_LINE> <INDENT> _GlobalFigure.__init__(self, size) <NEW_LINE> self.objectList = objectList <NEW_LINE> self._objectType = self._getInputObjectTypes() <NEW_LINE> <DEDENT> def _getInputObjectTypes(self): <NEW_LINE> <INDENT> firstObject = self.objectList[0] <NEW_LINE> firstObjectType = type(firstObject) <NEW_LINE> for astroObject in self.objectList: <NEW_LINE> <INDENT> if not firstObjectType == type(astroObject): <NEW_LINE> <INDENT> raise TypeError('Input object list contains mixed types ({0} and {1})'.format(firstObjectType, type(astroObject))) <NEW_LINE> <DEDENT> <DEDENT> return firstObjectType <NEW_LINE> <DEDENT> def _getParLabelAndUnit(self, param): <NEW_LINE> <INDENT> firstObject = self.objectList[0] <NEW_LINE> if isinstance(firstObject, ac.Planet): <NEW_LINE> <INDENT> if 'star.' in param: <NEW_LINE> <INDENT> return _starPars[param[5:]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _planetPars[param] <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(firstObject, ac.Star): <NEW_LINE> <INDENT> return _starPars[param] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Only Planets and Star object are currently supported, you gave {0}'.format(type(firstObject))) <NEW_LINE> <DEDENT> <DEDENT> def _gen_label(self, param, unit): <NEW_LINE> <INDENT> parValues = self._getParLabelAndUnit(param) <NEW_LINE> if unit is None: <NEW_LINE> <INDENT> return parValues[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unitsymbol = self._get_unit_symbol(unit) <NEW_LINE> return '{0} ({1})'.format(parValues[0], unitsymbol) <NEW_LINE> <DEDENT> <DEDENT> def _get_unit_symbol(self, unit): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return '${0}$'.format(unit.latex_symbol) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return unit.symbol
contains extra functions for dealing with input of astro objects
62598fb4aad79263cf42e885
class ApplicationGatewayBackendAddressPool(SubResource): <NEW_LINE> <INDENT> _validation = { 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'}, 'backend_addresses': {'key': 'properties.backendAddresses', 'type': '[ApplicationGatewayBackendAddress]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, etag: Optional[str] = None, type: Optional[str] = None, backend_ip_configurations: Optional[List["NetworkInterfaceIPConfiguration"]] = None, backend_addresses: Optional[List["ApplicationGatewayBackendAddress"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayBackendAddressPool, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = etag <NEW_LINE> self.type = type <NEW_LINE> self.backend_ip_configurations = backend_ip_configurations <NEW_LINE> self.backend_addresses = backend_addresses <NEW_LINE> self.provisioning_state = None
Backend Address Pool of an application gateway. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param name: Name of the backend address pool that is unique within an Application Gateway. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param type: Type of the resource. :type type: str :param backend_ip_configurations: Collection of references to IPs defined in network interfaces. :type backend_ip_configurations: list[~azure.mgmt.network.v2019_08_01.models.NetworkInterfaceIPConfiguration] :param backend_addresses: Backend addresses. :type backend_addresses: list[~azure.mgmt.network.v2019_08_01.models.ApplicationGatewayBackendAddress] :ivar provisioning_state: The provisioning state of the backend address pool resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2019_08_01.models.ProvisioningState
62598fb4d7e4931a7ef3c146
class CZPowGate(eigen_gate.EigenGate, gate_features.TwoQubitGate, gate_features.InterchangeableQubitsGate): <NEW_LINE> <INDENT> def _eigen_components(self): <NEW_LINE> <INDENT> return [ (0, np.diag([1, 1, 1, 0])), (1, np.diag([0, 0, 0, 1])), ] <NEW_LINE> <DEDENT> def _apply_unitary_(self, args: protocols.ApplyUnitaryArgs ) -> Union[np.ndarray, NotImplementedType]: <NEW_LINE> <INDENT> if protocols.is_parameterized(self): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> c = 1j**(2 * self._exponent) <NEW_LINE> one_one = linalg.slice_for_qubits_equal_to(args.axes, 0b11) <NEW_LINE> args.target_tensor[one_one] *= c <NEW_LINE> p = 1j**(2 * self._exponent * self._global_shift) <NEW_LINE> if p != 1: <NEW_LINE> <INDENT> args.target_tensor *= p <NEW_LINE> <DEDENT> return args.target_tensor <NEW_LINE> <DEDENT> def _pauli_expansion_(self) -> Dict[str, complex]: <NEW_LINE> <INDENT> if protocols.is_parameterized(self): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> global_phase = 1j**(2 * self._exponent * self._global_shift) <NEW_LINE> z_phase = 1j**(self._exponent + 0) <NEW_LINE> c = -1j * z_phase * np.sin(np.pi * self._exponent / 2) / 2 <NEW_LINE> return { 'II': global_phase * (1 - c), 'IZ': global_phase * c, 'ZI': global_phase * c, 'ZZ': global_phase * -c, } <NEW_LINE> <DEDENT> def _phase_by_(self, phase_turns, qubit_index): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def _circuit_diagram_info_(self, args: protocols.CircuitDiagramInfoArgs ) -> protocols.CircuitDiagramInfo: <NEW_LINE> <INDENT> return protocols.CircuitDiagramInfo( wire_symbols=('@', '@'), exponent=self._diagram_exponent(args)) <NEW_LINE> <DEDENT> def _qasm_(self, args: protocols.QasmArgs, qubits: Tuple[raw_types.QubitId, ...]) -> Optional[str]: <NEW_LINE> <INDENT> if self._exponent != 1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> args.validate_version('2.0') <NEW_LINE> return args.format('cz {0},{1};\n', qubits[0], qubits[1]) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> if self._exponent == 1: <NEW_LINE> <INDENT> return 'CZ' <NEW_LINE> <DEDENT> return 'CZ**{!r}'.format(self._exponent) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> if self._global_shift == 0: <NEW_LINE> <INDENT> if self._exponent == 1: <NEW_LINE> <INDENT> return 'cirq.CZ' <NEW_LINE> <DEDENT> return '(cirq.CZ**{})'.format(proper_repr(self._exponent)) <NEW_LINE> <DEDENT> return ( 'cirq.CZPowGate(exponent={}, ' 'global_shift={!r})' ).format(proper_repr(self._exponent), self._global_shift)
A gate that applies a phase to the |11⟩ state of two qubits. The unitary matrix of `CZPowGate(exponent=t)` is: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, g]] where: g = exp(i·π·t/2). `cirq.CZ`, the controlled Z gate, is an instance of this gate at `exponent=1`.
62598fb457b8e32f52508175
class CryptoCur(object): <NEW_LINE> <INDENT> PoW = False <NEW_LINE> chain_index = 0 <NEW_LINE> coin_name = '' <NEW_LINE> code = '' <NEW_LINE> p2pkh_version = 0 <NEW_LINE> p2sh_version = 0 <NEW_LINE> wif_version = 0 <NEW_LINE> ext_pub_version = '' <NEW_LINE> ext_priv_version = '' <NEW_LINE> DUST_THRESHOLD = 5430 <NEW_LINE> MIN_RELAY_TX_FEE = 1000 <NEW_LINE> RECOMMENDED_FEE = 50000 <NEW_LINE> COINBASE_MATURITY = 100 <NEW_LINE> block_explorers = { 'Blockchain.info': 'https://blockchain.info/tx/', 'Blockr.io': 'https://blockr.io/tx/info/', 'Insight.is': 'http://live.insight.is/tx/', 'Blocktrail.com': 'https://www.blocktrail.com/tx/' } <NEW_LINE> base_units = { 'COIN': 8, 'mCOIN': 5 } <NEW_LINE> chunk_size = 2016 <NEW_LINE> def set_headers_path(self, path): <NEW_LINE> <INDENT> self.headers_path = path <NEW_LINE> <DEDENT> def path(self): <NEW_LINE> <INDENT> return self.headers_path <NEW_LINE> <DEDENT> def verify_chain(self, chain): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def verify_chunk(self, index, hexdata): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def header_to_string(self, res): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def header_from_string(self, s): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def hash_header(self, header): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save_chunk(self, index, chunk): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save_header(self, header): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_header(self, block_height): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_target(self, index, chain=None): <NEW_LINE> <INDENT> pass
Abstract class containing cryptocurrency-specific code
62598fb410dbd63aa1c70c68
class RegistrationView(MethodView): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> user = User.query.filter_by(email=request.data['email']).first() <NEW_LINE> if not user: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> post_data = request.data <NEW_LINE> email = post_data['email'] <NEW_LINE> password = post_data['password'] <NEW_LINE> user = User(email=email, password=password) <NEW_LINE> user.save() <NEW_LINE> response = { 'message': 'You registered succesfully. Please login' } <NEW_LINE> return make_response(jsonify(response)), 201 <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> response = { 'message': str(e) } <NEW_LINE> return make_response(jsonify(response)), 401 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> response = { 'message': 'User already exists. Please login.' } <NEW_LINE> return make_response(jsonify(response))
This class registers a new user.
62598fb456ac1b37e630229d
class NsipIdentity(IanaInterfaceTypeIdentity): <NEW_LINE> <INDENT> _prefix = 'ianaift' <NEW_LINE> _revision = '2014-05-08' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> IanaInterfaceTypeIdentity.__init__(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.ietf._meta import _iana_if_type as meta <NEW_LINE> return meta._meta_table['NsipIdentity']['meta_info']
XNS over IP.
62598fb4236d856c2adc9498
class DyStockBackTestingStrategyEngineProxyThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, eventEngine): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._eventEngine = eventEngine <NEW_LINE> self._queue = queue.Queue() <NEW_LINE> self._threads = [] <NEW_LINE> self._childQueues = [] <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> event = self._queue.get() <NEW_LINE> self._eventEngine.put(event) <NEW_LINE> <DEDENT> <DEDENT> def startBackTesting(self, reqData): <NEW_LINE> <INDENT> childQueue = queue.Queue() <NEW_LINE> self._childQueues.append(childQueue) <NEW_LINE> t = threading.Thread(target=dyStockBackTestingStrategyEngineProcess, args=(self._queue, childQueue, reqData)) <NEW_LINE> t.start() <NEW_LINE> self._threads.append(t)
以线程方式启动一个周期的策略回测, 主要做调试用
62598fb4a8370b77170f048f
class DxUserObject(object): <NEW_LINE> <INDENT> _default = {'use_email_as_username': True, 'use_uuid_as_userid': True} <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> <DEDENT> def getUserId(self): <NEW_LINE> <INDENT> if self._use_uuid_as_userid(): <NEW_LINE> <INDENT> return IUUID(self.context) <NEW_LINE> <DEDENT> return self.getUserName() <NEW_LINE> <DEDENT> def getUserName(self): <NEW_LINE> <INDENT> if self._use_email_as_username(): <NEW_LINE> <INDENT> return self.context.email <NEW_LINE> <DEDENT> return self.context.username <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> names = [ self.context.first_name, self.context.last_name, ] <NEW_LINE> return u' '.join([name for name in names if name]) <NEW_LINE> <DEDENT> def _use_email_as_username(self): <NEW_LINE> <INDENT> return self._reg_setting('use_email_as_username') <NEW_LINE> <DEDENT> def _use_uuid_as_userid(self): <NEW_LINE> <INDENT> return self._reg_setting('use_uuid_as_userid') <NEW_LINE> <DEDENT> def _reg_setting(self, setting): <NEW_LINE> <INDENT> reg = getUtility(IRegistry) <NEW_LINE> config = reg.forInterface(settings.IDexterityMembraneSettings, False) <NEW_LINE> if config and hasattr(config, setting): <NEW_LINE> <INDENT> return getattr(config, setting) <NEW_LINE> <DEDENT> return self._default(setting)
Base Behavioral Methods for Membrane User
62598fb432920d7e50bc6107
class DDMShapeError(DDMError): <NEW_LINE> <INDENT> pass
shapes are inconsistent
62598fb44f88993c371f0565
class TestCertifyingOrganisationView(TestCase): <NEW_LINE> <INDENT> @override_settings(VALID_DOMAIN=['testserver', ]) <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.client = Client() <NEW_LINE> self.client.post( '/set_language/', data={'language': 'en'}) <NEW_LINE> logging.disable(logging.CRITICAL) <NEW_LINE> self.user = UserF.create(**{ 'username': 'anita', 'password': 'password', 'is_staff': True }) <NEW_LINE> self.user.set_password('password') <NEW_LINE> self.user.save() <NEW_LINE> self.project = ProjectF.create() <NEW_LINE> self.certifying_organisation = CertifyingOrganisationF.create( project=self.project ) <NEW_LINE> <DEDENT> @override_settings(VALID_DOMAIN=['testserver', ]) <NEW_LINE> def tearDown(self): <NEW_LINE> <INDENT> self.certifying_organisation.delete() <NEW_LINE> self.project.delete() <NEW_LINE> self.user.delete() <NEW_LINE> <DEDENT> @override_settings(VALID_DOMAIN=['testserver', ]) <NEW_LINE> def test_detail_view(self): <NEW_LINE> <INDENT> client = Client() <NEW_LINE> response = client.get(reverse('certifyingorganisation-detail', kwargs={ 'project_slug': self.project.slug, 'slug': self.certifying_organisation.slug })) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> @override_settings(VALID_DOMAIN=['testserver', ]) <NEW_LINE> def test_detail_view_object_does_not_exist(self): <NEW_LINE> <INDENT> client = Client() <NEW_LINE> response = client.get(reverse('certifyingorganisation-detail', kwargs={ 'project_slug': self.project.slug, 'slug': 'random' })) <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> response = client.get(reverse('certifyingorganisation-detail', kwargs={ 'project_slug': 'random', 'slug': self.certifying_organisation.slug })) <NEW_LINE> self.assertEqual(response.status_code, 404)
Test that Certifying Organisation View works.
62598fb4be383301e02538ae
class OrdineProduzione(Document): <NEW_LINE> <INDENT> ordine_numero = StringField(max_length=10, required=True, primary_key=True) <NEW_LINE> committenti = StringField(max_length=100) <NEW_LINE> corsi = StringField(max_length=200) <NEW_LINE> persona_di_riferimento = StringField() <NEW_LINE> cup = StringField(max_length=20) <NEW_LINE> cig = StringField(max_length=20) <NEW_LINE> stato = StringField(max_length=20) <NEW_LINE> cdc = StringField(max_length=10, verbose_name='Centro di Costo') <NEW_LINE> data_inizio = DateTimeField() <NEW_LINE> data_fine = DateTimeField() <NEW_LINE> prot_gestione = IntField() <NEW_LINE> note = StringField(max_length=200) <NEW_LINE> dts_aggiornamento = DateTimeField() <NEW_LINE> dts_creazione = DateTimeField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.ordine_numero
Definisce l'ordine di produzione per i corsi.
62598fb4091ae35668704cd2
class ControlBusSetContiguousRequest(Request): <NEW_LINE> <INDENT> __slots__ = ( '_index_values_pairs', ) <NEW_LINE> def __init__( self, index_values_pairs=None, ): <NEW_LINE> <INDENT> Request.__init__(self) <NEW_LINE> if index_values_pairs: <NEW_LINE> <INDENT> pairs = [] <NEW_LINE> for index, values in index_values_pairs: <NEW_LINE> <INDENT> index = int(index) <NEW_LINE> values = tuple(float(value) for value in values) <NEW_LINE> assert 0 <= index <NEW_LINE> assert values <NEW_LINE> if not values: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> pair = (index, values) <NEW_LINE> pairs.append(pair) <NEW_LINE> <DEDENT> index_values_pairs = tuple(pairs) <NEW_LINE> <DEDENT> self._index_values_pairs = index_values_pairs <NEW_LINE> <DEDENT> def to_osc_message(self, with_textual_osc_command=False): <NEW_LINE> <INDENT> if with_textual_osc_command: <NEW_LINE> <INDENT> request_id = self.request_command <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request_id = int(self.request_id) <NEW_LINE> <DEDENT> contents = [request_id] <NEW_LINE> if self.index_values_pairs: <NEW_LINE> <INDENT> for index, values in self.index_values_pairs: <NEW_LINE> <INDENT> contents.append(index) <NEW_LINE> contents.append(len(values)) <NEW_LINE> contents.extend(values) <NEW_LINE> <DEDENT> <DEDENT> message = osctools.OscMessage(*contents) <NEW_LINE> return message <NEW_LINE> <DEDENT> @property <NEW_LINE> def index_values_pairs(self): <NEW_LINE> <INDENT> return self._index_values_pairs <NEW_LINE> <DEDENT> @property <NEW_LINE> def response_specification(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def request_id(self): <NEW_LINE> <INDENT> from supriya.tools import requesttools <NEW_LINE> return requesttools.RequestId.CONTROL_BUS_SET_CONTIGUOUS
A /c_setn request. :: >>> from supriya.tools import requesttools >>> request = requesttools.ControlBusSetContiguousRequest( ... index_values_pairs=[ ... (0, (0.1, 0.2, 0.3)), ... (4, (0.4, 0.5, 0.6)), ... ], ... ) >>> request ControlBusSetContiguousRequest( index_values_pairs=( ( 0, (0.1, 0.2, 0.3), ), ( 4, (0.4, 0.5, 0.6), ), ) ) :: >>> message = request.to_osc_message() >>> message OscMessage(26, 0, 3, 0.1, 0.2, 0.3, 4, 3, 0.4, 0.5, 0.6) :: >>> message.address == ... requesttools.RequestId.CONTROL_BUS_SET_CONTIGUOUS True
62598fb4fff4ab517ebcd899
class IPSec(ExtensionOnlyType_): <NEW_LINE> <INDENT> c_tag = 'IPSec' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = ExtensionOnlyType_.c_children.copy() <NEW_LINE> c_attributes = ExtensionOnlyType_.c_attributes.copy() <NEW_LINE> c_child_order = ExtensionOnlyType_.c_child_order[:] <NEW_LINE> c_cardinality = ExtensionOnlyType_.c_cardinality.copy()
The urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient:IPSec element
62598fb4cc0a2c111447b0c6
class StrongInfect(Spatial): <NEW_LINE> <INDENT> def __init__(self, popsize: int, pss: float, rstart: float, alpha: int, side: float, S0:int, I0:int, w0: float): <NEW_LINE> <INDENT> super(StrongInfect, self).__init__(popsize, pss, rstart, alpha, side, S0, I0, w0=0.5) <NEW_LINE> <DEDENT> def _infect(self, inf: Person, sus: Person): <NEW_LINE> <INDENT> r = dist(inf, sus) <NEW_LINE> r0 = self.rstart <NEW_LINE> if r > r0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if inf.ss: <NEW_LINE> <INDENT> return self.w0 <NEW_LINE> <DEDENT> return self.w0 * (1 - r / r0) ** self.alpha
Contains the same attributes as the Spatial base class. The only difference is in the _infect function, where implementation is different according to the Strong Infectious model presumptions. One difference is the w0 variable is defaulted to 0.5 if no value is passed in. This model assumes that super spreaders are intrinsically more infectious and therefore have a constant probability of infection within their spreading radius.
62598fb4442bda511e95c50b
class DetailsView(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> queryset = BucketList.objects.all() <NEW_LINE> serializer_class = BucketSerializer
Handles the not crete stuff
62598fb4d486a94d0ba2c085
class KNearestNeighbor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train(self, X, y): <NEW_LINE> <INDENT> self.X_train = X <NEW_LINE> self.y_train = y <NEW_LINE> <DEDENT> def predict(self, X, k=1, num_loops=0): <NEW_LINE> <INDENT> if num_loops == 0: <NEW_LINE> <INDENT> dists = self.compute_distances_no_loops(X) <NEW_LINE> <DEDENT> elif num_loops == 1: <NEW_LINE> <INDENT> dists = self.compute_distances_one_loop(X) <NEW_LINE> <DEDENT> elif num_loops == 2: <NEW_LINE> <INDENT> dists = self.compute_distances_two_loops(X) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value %d for num_loops' % num_loops) <NEW_LINE> <DEDENT> return self.predict_labels(dists, k=k) <NEW_LINE> <DEDENT> def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> for j in xrange(num_train): <NEW_LINE> <INDENT> dists[(i,j)] = np.linalg.norm(np.abs(X[i] - self.X_train[j])) <NEW_LINE> <DEDENT> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_one_loop(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> dists[i,:] = np.linalg.norm(np.abs(X[i] - self.X_train),axis=1) <NEW_LINE> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> test2 = np.reshape(np.dot(X, np.transpose(X)).diagonal(), (num_test,1)) <NEW_LINE> train2 = np.reshape(np.dot(self.X_train, np.transpose(self.X_train)).diagonal(), (1,num_train)) <NEW_LINE> testtrain = np.dot(X, np.transpose(self.X_train)) <NEW_LINE> dists = np.sqrt(test2 - 2*testtrain + train2) <NEW_LINE> return dists <NEW_LINE> <DEDENT> def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> closest_y = [ self.y_train[idx] for idx in np.argsort(dists[i])[:k] ] <NEW_LINE> y_pred[i] = np.argmax(np.bincount(closest_y)) <NEW_LINE> <DEDENT> return y_pred
a kNN classifier with L2 distance
62598fb48e7ae83300ee9158
class GitHubError(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> message = self.response.json()['message'] <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> message = None <NEW_LINE> <DEDENT> return "%s: %s" % (self.response.status_code, message) <NEW_LINE> <DEDENT> @property <NEW_LINE> def response(self): <NEW_LINE> <INDENT> return self.args[0]
Raised if a request fails to the GitHub API.
62598fb4498bea3a75a57bd4
class TestProductExtensionInterface(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 testProductExtensionInterface(self): <NEW_LINE> <INDENT> model = swagger_client.models.product_extension_interface.ProductExtensionInterface()
ProductExtensionInterface unit test stubs
62598fb44e4d5625663724da
class SimplyhentaiVideoExtractor(Extractor): <NEW_LINE> <INDENT> category = "simplyhentai" <NEW_LINE> subcategory = "video" <NEW_LINE> directory_fmt = ("{category}", "{type}s") <NEW_LINE> filename_fmt = "{title}{episode:?_//>02}.{extension}" <NEW_LINE> archive_fmt = "{title}_{episode}" <NEW_LINE> pattern = r"(?:https?://)?(videos\.simply-hentai\.com/[^/?#]+)" <NEW_LINE> test = ( ("https://videos.simply-hentai.com/creamy-pie-episode-02", { "pattern": r"https://www\.googleapis\.com/drive/v3/files" r"/0B1ecQ8ZVLm3JcHZzQzBnVy1ZUmc\?alt=media&key=[\w-]+", "keyword": "706790708b14773efc1e075ddd3b738a375348a5", "options": (("verify", False),), "count": 1, }), (("https://videos.simply-hentai.com" "/1715-tifa-in-hentai-gang-bang-3d-movie"), { "url": "ad9a36ae06c601b6490e3c401834b4949d947eb0", "keyword": "f9dad94fbde9c95859e631ff4f07297a9567b874", }), ) <NEW_LINE> def __init__(self, match): <NEW_LINE> <INDENT> Extractor.__init__(self, match) <NEW_LINE> self.page_url = "https://" + match.group(1) <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> page = self.request(self.page_url).text <NEW_LINE> title, pos = text.extract(page, "<title>", "</title>") <NEW_LINE> tags , pos = text.extract(page, ">Tags</div>", "</div>", pos) <NEW_LINE> date , pos = text.extract(page, ">Upload Date</div>", "</div>", pos) <NEW_LINE> title = title.rpartition(" - ")[0] <NEW_LINE> if "<video" in page: <NEW_LINE> <INDENT> video_url = text.extract(page, '<source src="', '"', pos)[0] <NEW_LINE> episode = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pos = page.index('<div class="video-frame-container">', pos) <NEW_LINE> embed_url = text.extract(page, 'src="', '"', pos)[0].replace( "embedplayer.php?link=", "embed.php?name=") <NEW_LINE> embed_page = self.request(embed_url).text <NEW_LINE> video_url = text.extract(embed_page, '"file":"', '"')[0] <NEW_LINE> title, _, episode = title.rpartition(" Episode ") <NEW_LINE> <DEDENT> if video_url.startswith("//"): <NEW_LINE> <INDENT> video_url = "https:" + video_url <NEW_LINE> <DEDENT> data = text.nameext_from_url(video_url, { "title": text.unescape(title), "episode": text.parse_int(episode), "tags": text.split_html(tags)[::2], "type": "video", "date": text.parse_datetime(text.remove_html( date), "%B %d, %Y %H:%M"), }) <NEW_LINE> yield Message.Directory, data <NEW_LINE> yield Message.Url, video_url, data
Extractor for hentai videos from simply-hentai.com
62598fb421bff66bcd722d1b
class WXFToken(object): <NEW_LINE> <INDENT> __slots__ = "wxf_type", "array_type", "length", "_dimensions", "_element_count", "data" <NEW_LINE> def __init__(self, wxf_type): <NEW_LINE> <INDENT> self.wxf_type = wxf_type <NEW_LINE> self._dimensions = None <NEW_LINE> self._element_count = None <NEW_LINE> self.data = None <NEW_LINE> self.length = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def element_count(self): <NEW_LINE> <INDENT> if self._element_count is None and self._dimensions is not None: <NEW_LINE> <INDENT> self._update_element_count() <NEW_LINE> <DEDENT> return self._element_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def dimensions(self): <NEW_LINE> <INDENT> return self._dimensions <NEW_LINE> <DEDENT> @dimensions.setter <NEW_LINE> def dimensions(self, value): <NEW_LINE> <INDENT> if not isinstance(value, list): <NEW_LINE> <INDENT> raise TypeError("Dimensions must be a list of positive integers.") <NEW_LINE> <DEDENT> self._dimensions = value <NEW_LINE> if self._element_count is not None: <NEW_LINE> <INDENT> self._update_element_count() <NEW_LINE> <DEDENT> <DEDENT> def _update_element_count(self): <NEW_LINE> <INDENT> count = 1 <NEW_LINE> for dim in self._dimensions: <NEW_LINE> <INDENT> count = count * dim <NEW_LINE> <DEDENT> if not isinstance(count, six.integer_types) or count <= 0: <NEW_LINE> <INDENT> raise TypeError("Dimensions must be strictly positive integers.") <NEW_LINE> <DEDENT> self._element_count = count <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.length is not None: <NEW_LINE> <INDENT> return "WXFToken<%s, data=%s, len=%i>" % (self.wxf_type, self.data, self.length) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "WXFToken<%s, data=%s>" % (self.wxf_type, self.data)
Represent a WXF element, often referred as WXF tokens.
62598fb4009cb60464d015d5
class Query(SiteCommand): <NEW_LINE> <INDENT> __options = OptionSet( Option.choice('format', choices=['json', 'text']), Option.flag('current-patchset'), Option.flag('patch-sets'), Option.flag('all-approvals'), Option.flag('files'), Option.flag('comments'), Option.flag('dependencies'), Option.flag('submit-records', spec='>=2.5'), Option.flag('commit-message', spec='>=2.5'), Option.flag('all-reviewers', spec='>=2.9') ) <NEW_LINE> __supported_versions = '>=2.4' <NEW_LINE> def __init__(self, option_str='', query='', max_results=0): <NEW_LINE> <INDENT> self.__query = query <NEW_LINE> self.__max_results = max_results <NEW_LINE> super(Query, self).__init__(Query.__supported_versions, Query.__options, option_str) <NEW_LINE> <DEDENT> def execute_on(self, the_site): <NEW_LINE> <INDENT> opts = self._parsed_options <NEW_LINE> opts.current_patch_set = True <NEW_LINE> opts.patch_sets = True <NEW_LINE> opts.all_approvals = True <NEW_LINE> opts.dependencies = True <NEW_LINE> opts.commit_message = True <NEW_LINE> opts.format = 'JSON' <NEW_LINE> self.check_support_for(the_site) <NEW_LINE> result = [] <NEW_LINE> resume_key = '' <NEW_LINE> remaining = self.__max_results <NEW_LINE> def partial_query(): <NEW_LINE> <INDENT> resume = ('resume_sortkey:{0}'.format(resume_key) if resume_key else '') <NEW_LINE> standard_flags = ' '.join([str(opts), resume]) <NEW_LINE> limit = 'limit:{0}'.format(remaining) if self.__max_results else '' <NEW_LINE> raw = the_site.execute(' '.join(['query', limit, self.__query, standard_flags])) <NEW_LINE> lines = self.text_to_json(raw) <NEW_LINE> return ([review.Review(l) for l in lines[:-1]] if len(lines) > 1 else []) <NEW_LINE> <DEDENT> while self.__max_results == 0 or len(result) < self.__max_results: <NEW_LINE> <INDENT> partial = partial_query() <NEW_LINE> if not partial: break <NEW_LINE> result.extend(partial) <NEW_LINE> resume_key = partial[-1].raw['sortKey'] <NEW_LINE> remaining -= len(partial) <NEW_LINE> <DEDENT> self._results = (result[:self.__max_results] if (self.__max_results and len(result) > self.__max_results) else result) <NEW_LINE> return self._results
Command to execute queries on reviews :param option_str: One or more supported options to be passed to the command :note: In order to ensure that the necessary information is returned to allow creation of the `Review` objects, many of the options will be overridden by `execute_on`. The following will always be sent: * --current-patch-set * --patch-sets * --all-approvals * --dependencies * --commit-message * --format JSON :param query: arguments to the query commands, e.g. 'status:abandoned owner:self' :param max_results: limit the result set to the first 'n'. If not given, all results are returned. This may require multiple commands being sent to the Gerrit site, as Gerrit instances often have a built-in limit to the number of results it returns (often around 500).
62598fb444b2445a339b69cc
class ServiceDescription(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nodename = None <NEW_LINE> self.container_id = None <NEW_LINE> self.service = None <NEW_LINE> self.service_instance = None <NEW_LINE> self.service_type = None <NEW_LINE> self.version = None <NEW_LINE> self.rados_config_location = None <NEW_LINE> self.service_url = None <NEW_LINE> self.status = None <NEW_LINE> self.status_desc = None <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> out = { 'nodename': self.nodename, 'container_id': self.container_id, 'service': self.service, 'service_instance': self.service_instance, 'service_type': self.service_type, 'version': self.version, 'rados_config_location': self.rados_config_location, 'service_url': self.service_url, 'status': self.status, 'status_desc': self.status_desc, } <NEW_LINE> return {k: v for (k, v) in out.items() if v is not None}
For responding to queries about the status of a particular service, stateful or stateless. This is not about health or performance monitoring of services: it's about letting the orchestrator tell Ceph whether and where a service is scheduled in the cluster. When an orchestrator tells Ceph "it's running on node123", that's not a promise that the process is literally up this second, it's a description of where the orchestrator has decided the service should run.
62598fb4379a373c97d990c9
class PositionalEncoding(nn.Module): <NEW_LINE> <INDENT> def __init__(self, d_model, dropout, device="cpu", max_len = 10000): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.pe = torch.zeros(max_len, d_model) <NEW_LINE> pos = torch.arange(0,max_len).unsqueeze(1).type(torch.float32) <NEW_LINE> tmp = torch.arange(0,d_model,2) <NEW_LINE> den = 1/torch.pow(torch.ones(int(d_model/2))*10000,2*tmp/d_model) <NEW_LINE> den = den.unsqueeze(0) <NEW_LINE> self.pe[:,0::2] = torch.sin(torch.matmul(pos,den)) <NEW_LINE> self.pe[:,1::2] = torch.cos(torch.matmul(pos,den)) <NEW_LINE> self.pe = self.pe.to(device) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return x + self.pe[:x.shape[1],:]
位置エンコーディング args: - d_model (int) : ベクトルの次元数 - dropout (float) - device - max_len (int) : 許容しうる最大の長さの文章
62598fb43d592f4c4edbaf74
@registered <NEW_LINE> class DrumTable(Table): <NEW_LINE> <INDENT> def __init__(self, mod, meta): <NEW_LINE> <INDENT> super().__init__(mod, meta)
Table of Drum Properties
62598fb4796e427e5384e848
class Player(): <NEW_LINE> <INDENT> def __init__(self, username): <NEW_LINE> <INDENT> self.username= username <NEW_LINE> self.uuid = None <NEW_LINE> self.skinURI = None <NEW_LINE> <DEDENT> async def get_uuid(self): <NEW_LINE> <INDENT> if self.uuid == None: <NEW_LINE> <INDENT> resp = await mojangapi.perform_request( mojangapi.KnownURIs.uuidURI + self.username) <NEW_LINE> self.uuid = resp["id"] <NEW_LINE> return self.uuid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.uuid <NEW_LINE> <DEDENT> <DEDENT> async def get_profile(self,decode = False): <NEW_LINE> <INDENT> uuid = await self.get_uuid() <NEW_LINE> resp = await mojangapi.perform_request(mojangapi.KnownURIs.sessionServer + uuid) <NEW_LINE> if decode: <NEW_LINE> <INDENT> resp["properties"][0]["value"] = base64.b64decode(resp["properties"][0]["value"]) <NEW_LINE> return resp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return resp <NEW_LINE> <DEDENT> <DEDENT> async def get_names(self): <NEW_LINE> <INDENT> uuid = await self.get_uuid() <NEW_LINE> return await mojangapi.perform_request(mojangapi.KnownURIs.MojangAccUUID + uuid + "/names") <NEW_LINE> <DEDENT> async def download_skin(self): <NEW_LINE> <INDENT> async with aiohttp.ClientSession() as session: <NEW_LINE> <INDENT> skin = await self.get_skin() <NEW_LINE> async with session.get(skin) as res: <NEW_LINE> <INDENT> if res.status == 200: <NEW_LINE> <INDENT> with open('download.png', 'wb') as file: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> chunk = await res.content.read(500) <NEW_LINE> if not chunk: <NEW_LINE> <INDENT> print("Download finished!") <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file.write(chunk) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise LookupError("LookupFailed") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> async def get_skin(self): <NEW_LINE> <INDENT> if self.skinURI == None: <NEW_LINE> <INDENT> uuid = await self.get_uuid() <NEW_LINE> decoded = await self.get_profile(True) <NEW_LINE> self.skinURI = eval(decoded["properties"][0]["value"].decode("ascii"))["textures"]["SKIN"]["url"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.skinURI
def create(username): self = Player() self.username= username self.uuid = None self.skinURI = None return self
62598fb4be7bc26dc9251eb6
class Distance(distance.Distance): <NEW_LINE> <INDENT> def __init__(self, seq_records, word_size, disttype='jaccard'): <NEW_LINE> <INDENT> self._vector = [_getwords(s, word_size) for s in seq_records.seq_list] <NEW_LINE> self.set_disttype(disttype) <NEW_LINE> <DEDENT> def pwdist_jaccard(self, seq1idx, seq2idx): <NEW_LINE> <INDENT> s1 = self[seq1idx] <NEW_LINE> s2 = self[seq2idx] <NEW_LINE> return 1 - len(s1 & s2) / float(len(s1 | s2)) <NEW_LINE> <DEDENT> def pwdist_dice(self, seq1idx, seq2idx): <NEW_LINE> <INDENT> s1 = self[seq1idx] <NEW_LINE> s2 = self[seq2idx] <NEW_LINE> return 1 - (2 * len(s1 & s2) / float(len(s1) + len(s2))) <NEW_LINE> <DEDENT> def pwdist_hamming(self, seq1idx, seq2idx): <NEW_LINE> <INDENT> s1 = self[seq1idx] <NEW_LINE> s2 = self[seq2idx] <NEW_LINE> return len(s1.symmetric_difference(s2))
Combine vector data with pairwise distance methods that measures dissimilarity between sets.
62598fb4adb09d7d5dc0a640
class SwitchModel(ndb.Model): <NEW_LINE> <INDENT> value = ndb.PickleProperty()
A datastore model for storing switches. Used by datastoredict.
62598fb4a219f33f346c68b9
class TestDA(ut.TestCase): <NEW_LINE> <INDENT> def test_chuck_cache(self): <NEW_LINE> <INDENT> dalist = h5p.create(h5p.DATASET_ACCESS) <NEW_LINE> nslots = 10000 <NEW_LINE> nbytes = 1000000 <NEW_LINE> w0 = .5 <NEW_LINE> dalist.set_chunk_cache(nslots, nbytes, w0) <NEW_LINE> self.assertEqual((nslots, nbytes, w0), dalist.get_chunk_cache())
Feature: setting/getting chunk cache size on a dataset access property list
62598fb476e4537e8c3ef65b