code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class UserRoleAssignmentRequest(object): <NEW_LINE> <INDENT> openapi_types = { 'role_id': 'str', 'tag_id': 'str' } <NEW_LINE> attribute_map = { 'role_id': 'roleId', 'tag_id': 'tagId' } <NEW_LINE> def __init__(self, role_id=None, tag_id=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._role_id = None <NEW_LINE> self._tag_id = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.role_id = role_id <NEW_LINE> if tag_id is not None: <NEW_LINE> <INDENT> self.tag_id = tag_id <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def role_id(self): <NEW_LINE> <INDENT> return self._role_id <NEW_LINE> <DEDENT> @role_id.setter <NEW_LINE> def role_id(self, role_id): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and role_id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `role_id`, must not be `None`") <NEW_LINE> <DEDENT> self._role_id = role_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def tag_id(self): <NEW_LINE> <INDENT> return self._tag_id <NEW_LINE> <DEDENT> @tag_id.setter <NEW_LINE> def tag_id(self, tag_id): <NEW_LINE> <INDENT> self._tag_id = tag_id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserRoleAssignmentRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserRoleAssignmentRequest): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62599082ec188e330fdfa3a2
class ApplicationGatewayBackendHealthPool(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'backend_address_pool': {'key': 'backendAddressPool', 'type': 'ApplicationGatewayBackendAddressPool'}, 'backend_http_settings_collection': {'key': 'backendHttpSettingsCollection', 'type': '[ApplicationGatewayBackendHealthHttpSettings]'}, } <NEW_LINE> def __init__( self, *, backend_address_pool: Optional["ApplicationGatewayBackendAddressPool"] = None, backend_http_settings_collection: Optional[List["ApplicationGatewayBackendHealthHttpSettings"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayBackendHealthPool, self).__init__(**kwargs) <NEW_LINE> self.backend_address_pool = backend_address_pool <NEW_LINE> self.backend_http_settings_collection = backend_http_settings_collection
Application gateway BackendHealth pool. :param backend_address_pool: Reference of an ApplicationGatewayBackendAddressPool resource. :type backend_address_pool: ~azure.mgmt.network.v2018_12_01.models.ApplicationGatewayBackendAddressPool :param backend_http_settings_collection: List of ApplicationGatewayBackendHealthHttpSettings resources. :type backend_http_settings_collection: list[~azure.mgmt.network.v2018_12_01.models.ApplicationGatewayBackendHealthHttpSettings]
625990827b180e01f3e49de0
class Route(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'next_hop_type': {'key': 'properties.nextHopType', 'type': 'str'}, 'next_hop_ip_address': {'key': 'properties.nextHopIpAddress', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, address_prefix: Optional[str] = None, next_hop_type: Optional[Union[str, "RouteNextHopType"]] = None, next_hop_ip_address: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(Route, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.address_prefix = address_prefix <NEW_LINE> self.next_hop_type = next_hop_type <NEW_LINE> self.next_hop_ip_address = next_hop_ip_address <NEW_LINE> self.provisioning_state = None
Route resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :param address_prefix: The destination CIDR to which the route applies. :type address_prefix: str :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values include: "VirtualNetworkGateway", "VnetLocal", "Internet", "VirtualAppliance", "None". :type next_hop_type: str or ~azure.mgmt.network.v2020_07_01.models.RouteNextHopType :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. :type next_hop_ip_address: str :ivar provisioning_state: The provisioning state of the route resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2020_07_01.models.ProvisioningState
625990824f88993c371f129e
class TransportException(api_errors.TransportError): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.count = 1 <NEW_LINE> self.rcount = 1 <NEW_LINE> self.retryable = False <NEW_LINE> self.verbose = False <NEW_LINE> <DEDENT> def simple_cmp(self, other): <NEW_LINE> <INDENT> return self.__cmp__(other) <NEW_LINE> <DEDENT> def simple_str(self): <NEW_LINE> <INDENT> return self.__str__()
Base class for various exceptions thrown by code in transport package.
625990827cff6e4e811b7539
class test_Attribute(ClassChecker): <NEW_LINE> <INDENT> _cls = frontend.Attribute <NEW_LINE> def test_class(self): <NEW_LINE> <INDENT> assert self.cls.__bases__ == (plugable.Plugin,) <NEW_LINE> assert type(self.cls.obj) is property <NEW_LINE> assert type(self.cls.obj_name) is property <NEW_LINE> assert type(self.cls.attr_name) is property <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> user_obj = 'The user frontend.Object instance' <NEW_LINE> class api: <NEW_LINE> <INDENT> Object = {("user", "1"): user_obj} <NEW_LINE> @staticmethod <NEW_LINE> def is_production_mode(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> class user_add(self.cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> o = user_add(api) <NEW_LINE> assert read_only(o, 'api') is api <NEW_LINE> assert read_only(o, 'obj') is user_obj <NEW_LINE> assert read_only(o, 'obj_name') == 'user' <NEW_LINE> assert read_only(o, 'attr_name') == 'add'
Test the `ipalib.frontend.Attribute` class.
6259908260cbc95b06365ae8
class Inbox(): <NEW_LINE> <INDENT> def __init__(self, items={}): <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> def add(self, text, created=None): <NEW_LINE> <INDENT> item = { 'title': text, } <NEW_LINE> quickstart.save_g_task(item, 'inbox') <NEW_LINE> <DEDENT> def print(self): <NEW_LINE> <INDENT> for _, item in self.items.items(): <NEW_LINE> <INDENT> print(item['title']) <NEW_LINE> <DEDENT> <DEDENT> def quickadd(self): <NEW_LINE> <INDENT> text = input('INBOX> ') <NEW_LINE> self.add(text) <NEW_LINE> <DEDENT> def paste(self): <NEW_LINE> <INDENT> self.add(pyperclip.paste())
Create Inbox container object. Stores collection of Inbox items and associated actions. Dequeue is used as most common operation will be FIFO processing of items.
625990827047854f46340ead
class OldStanfordLibParser(Parser): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.parser = StanfordParser() <NEW_LINE> <DEDENT> def parse(self, line): <NEW_LINE> <INDENT> tree = list(self.parser.raw_parse(line))[0] <NEW_LINE> tree = tree[0] <NEW_LINE> return tree
For StanfordParser < 3.6.0
6259908263b5f9789fe86c61
class HTTPNonAuthoritativeInformation(HTTPOk): <NEW_LINE> <INDENT> code = 203 <NEW_LINE> title = 'Non-Authoritative Information'
subclass of :class:`~HTTPOk` This indicates that the returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy. code: 203, title: Non-Authoritative Information
6259908299fddb7c1ca63b56
class FileProbe(ProbeBase): <NEW_LINE> <INDENT> ConfigSchema = FileProbeSchema <NEW_LINE> def __init__(self, config, ctx, emit=None): <NEW_LINE> <INDENT> super().__init__(config, ctx, emit) <NEW_LINE> self.path = self.pluginmgr_config.get("path") <NEW_LINE> self.run_level = 0 <NEW_LINE> self.backlog = int(self.pluginmgr_config.get("backlog", 0)) <NEW_LINE> self.max_lines = int(self.pluginmgr_config.get("max_lines", 1000)) <NEW_LINE> if self.path: <NEW_LINE> <INDENT> self.fh = open(self.path) <NEW_LINE> self.fh.seek(0, 2) <NEW_LINE> if self.backlog: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.fh.seek(self.fh.tell() - self.backlog, os.SEEK_SET) <NEW_LINE> <DEDENT> except ValueError as exc: <NEW_LINE> <INDENT> if str(exc).find("negative seek position") > -1: <NEW_LINE> <INDENT> self.fh.seek(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> async def _run(self): <NEW_LINE> <INDENT> self.run_level = 1 <NEW_LINE> while self.run_level: <NEW_LINE> <INDENT> self.send_emission() <NEW_LINE> for msg in self.probe(): <NEW_LINE> <INDENT> await self.queue_emission(msg) <NEW_LINE> <DEDENT> await vaping.io.sleep(0.1) <NEW_LINE> <DEDENT> <DEDENT> def validate_file_handler(self): <NEW_LINE> <INDENT> if self.fh.closed: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.fh = open(self.path) <NEW_LINE> self.fh.seek(0, 2) <NEW_LINE> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> logging.error(f"Could not reopen file: {err}") <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> open_stat = os.fstat(self.fh.fileno()) <NEW_LINE> try: <NEW_LINE> <INDENT> file_stat = os.stat(self.path) <NEW_LINE> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> logging.error(f"Could not stat file: {err}") <NEW_LINE> return False <NEW_LINE> <DEDENT> if open_stat != file_stat: <NEW_LINE> <INDENT> self.log <NEW_LINE> self.fh.close() <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def probe(self): <NEW_LINE> <INDENT> if not self.validate_file_handler(): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> messages = [] <NEW_LINE> for line in self.fh.readlines(self.max_lines): <NEW_LINE> <INDENT> data = {"path": self.path} <NEW_LINE> msg = self.new_message() <NEW_LINE> parsed = self.process_line(line, data) <NEW_LINE> if not parsed: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> data.update(parsed) <NEW_LINE> data = self.process_probe(data) <NEW_LINE> msg["data"] = [data] <NEW_LINE> messages.append(msg) <NEW_LINE> <DEDENT> messages = self.process_messages(messages) <NEW_LINE> return messages <NEW_LINE> <DEDENT> def process_line(self, line, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def process_probe(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def process_messages(self, messages): <NEW_LINE> <INDENT> return messages
Probes a file and emits everytime a new line is read # Config - path (`str`): path to file - backlog (`int=0`): number of bytes to read from backlog - max_lines (`int=1000`): maximum number of lines to read during probe # Instanced Attributes - path (`str`): path to file - backlog (`int`): number of bytes to read from backlog - max_lines (`int`): maximum number of liens to read during probe - fh (`filehandler`): file handler for opened file (only available if `path` is set)
625990823346ee7daa3383de
class MovingObjectPotential(Potential): <NEW_LINE> <INDENT> def __init__(self,orbit,amp=1.,GM=.06,normalize=False, softening=None, softening_model='plummer',softening_length=0.01): <NEW_LINE> <INDENT> Potential.__init__(self,amp=amp) <NEW_LINE> self._gm= GM <NEW_LINE> self._orb= orbit <NEW_LINE> if softening is None: <NEW_LINE> <INDENT> if softening_model.lower() == 'plummer': <NEW_LINE> <INDENT> self._softening= PlummerSoftening(softening_length=softening_length) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._softening= softening <NEW_LINE> <DEDENT> if normalize: <NEW_LINE> <INDENT> self.normalize(normalize) <NEW_LINE> <DEDENT> <DEDENT> def _evaluate(self,R,z,phi=0.,t=0.,dR=0,dphi=0): <NEW_LINE> <INDENT> if dR == 0 and dphi == 0: <NEW_LINE> <INDENT> dist= _cyldist(R,phi,z, self._orb.R(t),self._orb.phi(t),self._orb.z(t)) <NEW_LINE> return -self._gm*self._softening.potential(dist) <NEW_LINE> <DEDENT> elif dR == 1 and dphi == 0: <NEW_LINE> <INDENT> return -self._Rforce(R,z,phi=phi,t=t) <NEW_LINE> <DEDENT> elif dR == 0 and dphi == 1: <NEW_LINE> <INDENT> return -self._phiforce(R,z,phi=phi,t=t) <NEW_LINE> <DEDENT> <DEDENT> def _Rforce(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> (xd,yd,zd,dist)= _cyldiffdist(self._orb.R(t),self._orb.phi(t), self._orb.z(t), R,phi,z) <NEW_LINE> return self._gm*(nu.cos(phi)*xd+nu.sin(phi)*yd)/dist *self._softening(dist) <NEW_LINE> <DEDENT> def _zforce(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> (xd,yd,zd,dist)= _cyldiffdist(self._orb.R(t),self._orb.phi(t), self._orb.z(t), R,phi,z) <NEW_LINE> return self._gm*zd/dist*self._softening(dist) <NEW_LINE> <DEDENT> def _phiforce(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> (xd,yd,zd,dist)= _cyldiffdist(self._orb.R(t),self._orb.phi(t), self._orb.z(t), R,phi,z) <NEW_LINE> return self._gm*R*(nu.cos(phi)*yd-nu.sin(phi)*xd)/dist *self._softening(dist) <NEW_LINE> <DEDENT> def _dens(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> dist= _cyldist(R,phi,z, self._orb.R(t),self._orb.phi(t),self._orb.z(t)) <NEW_LINE> return self._gm*self._softening.density(dist)
Class that implements the potential coming from a moving object GM phi(R,z) = - --------------------------------- distance
62599082ec188e330fdfa3a4
class Compound(Mapping): <NEW_LINE> <INDENT> def __init__(self, mapping1, mapping2): <NEW_LINE> <INDENT> assert(mapping1.output_dim==mapping2.input_dim) <NEW_LINE> input_dim, output_dim = mapping1.input_dim, mapping2.output_dim <NEW_LINE> Mapping.__init__(self, input_dim=input_dim, output_dim=output_dim) <NEW_LINE> self.mapping1 = mapping1 <NEW_LINE> self.mapping2 = mapping2 <NEW_LINE> self.link_parameters(self.mapping1, self.mapping2) <NEW_LINE> <DEDENT> def f(self, X): <NEW_LINE> <INDENT> return self.mapping2.f(self.mapping1.f(X)) <NEW_LINE> <DEDENT> def update_gradients(self, dL_dF, X): <NEW_LINE> <INDENT> hidden = self.mapping1.f(X) <NEW_LINE> self.mapping2.update_gradients(dL_dF, hidden) <NEW_LINE> self.mapping1.update_gradients(self.mapping2.gradients_X(dL_dF, hidden), X) <NEW_LINE> <DEDENT> def gradients_X(self, dL_dF, X): <NEW_LINE> <INDENT> hidden = self.mapping1.f(X) <NEW_LINE> return self.mapping1.gradients_X(self.mapping2.gradients_X(dL_dF, hidden), X)
Mapping based on passing one mapping through another .. math:: f(\mathbf{x}) = f_2(f_1(\mathbf{x})) :param mapping1: first mapping :type mapping1: GPy.mappings.Mapping :param mapping2: second mapping :type mapping2: GPy.mappings.Mapping
6259908292d797404e3898d9
class ResolveDomainRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Domain = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Domain = params.get("Domain")
ResolveDomain请求参数结构体
625990824f6381625f19a22c
class CCBattery(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.positive = [1, '+'] <NEW_LINE> self.negative = [1, '-'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' |\n | {}\n ------------- {}\n ---------\n | {}\n |\n' .format(self.positive[1], self.name, self.negative[1])
Class to define a Battery.
6259908276e4537e8c3f1079
class GoogleCloudVisionV1p4beta1ReferenceImage(_messages.Message): <NEW_LINE> <INDENT> boundingPolys = _messages.MessageField('GoogleCloudVisionV1p4beta1BoundingPoly', 1, repeated=True) <NEW_LINE> name = _messages.StringField(2) <NEW_LINE> uri = _messages.StringField(3)
A `ReferenceImage` represents a product image and its associated metadata, such as bounding boxes. Fields: boundingPolys: Bounding polygons around the areas of interest in the reference image. Optional. If this field is empty, the system will try to detect regions of interest. At most 10 bounding polygons will be used. The provided shape is converted into a non-rotated rectangle. Once converted, the small edge of the rectangle must be greater than or equal to 300 pixels. The aspect ratio must be 1:4 or less (i.e. 1:3 is ok; 1:5 is not). name: The resource name of the reference image. Format is: `projects/PRO JECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. This field is ignored when creating a reference image. uri: The Google Cloud Storage URI of the reference image. The URI must start with `gs://`. Required.
6259908297e22403b383c9f9
class ClassAlias(ComplexModel): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def add_to_schema(cls, schema_dict): <NEW_LINE> <INDENT> if not schema_dict.has_class(cls._target): <NEW_LINE> <INDENT> cls._target.add_to_schema(schema_dict) <NEW_LINE> <DEDENT> element = etree.Element('{%s}element' % soaplib.ns_xsd) <NEW_LINE> element.set('name',cls.get_type_name()) <NEW_LINE> element.set('type',cls._target.get_type_name_ns(schema_dict.app)) <NEW_LINE> schema_dict.add_element(cls, element)
New type_name, same type_info.
62599082fff4ab517ebcf311
class Retire(Message): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "Retired: %s" % (self.sender.actor_urn)
A notice that the crawler is hit by sever problems.
6259908299fddb7c1ca63b57
class CommentTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.new_comment = Comment(id =1, usernames = 'nicole',comment= 'I love this post',blog_id=3,user_id= 2) <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.new_comment,Comment))
Test Class to test the behaviour of the comment class
6259908297e22403b383c9fa
class CumulativeRater(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._found_commands_and_results = [] <NEW_LINE> <DEDENT> def AddFoundCommand(self, command, result): <NEW_LINE> <INDENT> self._found_commands_and_results.append((command, result)) <NEW_LINE> <DEDENT> def RateAll(self): <NEW_LINE> <INDENT> all_commands = [command for (command, _) in self._found_commands_and_results] <NEW_LINE> for command, results in self._found_commands_and_results: <NEW_LINE> <INDENT> rating = CommandRater(results, command, all_commands).Rate() <NEW_LINE> command[lookup.RELEVANCE] = rating
Rates all found commands for relevance.
625990824f88993c371f12a0
class Bike(Engine): <NEW_LINE> <INDENT> def __init__(self, fuelInLitre): <NEW_LINE> <INDENT> self.fuelInLitre = fuelInLitre <NEW_LINE> <DEDENT> def mileage(self): <NEW_LINE> <INDENT> self.mileage = 50 * self.fuelInLitre <NEW_LINE> return self.mileage
assuming the bike travels 50KM per Litre of Fuel
62599082f548e778e596d087
class CreateUser(Base): <NEW_LINE> <INDENT> def __init__(self, last_name, first_name, email_address, title=None, teams=None, roles=None, requires_token=None, phone=None, login_enabled=None, is_saml_user=None, custom_id=None, ): <NEW_LINE> <INDENT> super(CreateUser, self).__init__( module='admin', cls='CreateUser', fn='get', args={ 'last_name':last_name, 'first_name':first_name, 'email_address':email_address, 'title':title, 'teams':teams, 'roles':roles, 'requires_token':requires_token, 'phone':phone, 'login_enabled':login_enabled, 'is_saml_user':is_saml_user, 'custom_id':custom_id, })
class: veracode.SDK.admin.CreateUser params: last_name: required first_name: required email_address: required title: optional teams: optional roles: optional requires_token: optional phone: optional login_enabled: optional is_saml_user: optional custom_id: optional returns: A python object that represents the returned API data.
625990825fdd1c0f98e5fa7b
class FlagList(ListView): <NEW_LINE> <INDENT> model = PostMarkType <NEW_LINE> template_name = 'admin/flag-list.html' <NEW_LINE> @method_decorator(user_passes_test(lambda u: u.is_superuser)) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(FlagList, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> return super(FlagList, self).get_queryset().filter(reviewed=True)
List of flagged posts.
62599082656771135c48adae
class GatewayRouteListResult(Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[GatewayRoute]'}, } <NEW_LINE> def __init__(self, *, value=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(GatewayRouteListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value
List of virtual network gateway routes. :param value: List of gateway routes :type value: list[~azure.mgmt.network.v2018_08_01.models.GatewayRoute]
625990827c178a314d78e968
class Singleton(object): <NEW_LINE> <INDENT> def __init__(self, klass): <NEW_LINE> <INDENT> self.klass = klass <NEW_LINE> self.instance = None <NEW_LINE> <DEDENT> def __call__(self, *args, **kwds): <NEW_LINE> <INDENT> if self.instance is None: <NEW_LINE> <INDENT> self.instance = self.klass(*args, **kwds) <NEW_LINE> <DEDENT> return self.instance
Singleton class so we dont have to keep specifing host and port
6259908266673b3332c31efb
class AccelerandoSpanner(TempoChangeSpanner): <NEW_LINE> <INDENT> pass
Spanner representing a speeding up.
62599082fff4ab517ebcf313
class RawFeedIndicator(dict): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(RawFeedIndicator, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, RawFeedIndicator): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259908250812a4eaa621943
class Reservation(models.Model): <NEW_LINE> <INDENT> spot = models.ForeignKey(Spot, on_delete=models.CASCADE) <NEW_LINE> price = models.IntegerField() <NEW_LINE> buyer = models.ForeignKey(User, related_name="buyer_user") <NEW_LINE> seller = models.ForeignKey(User, related_name="seller_user") <NEW_LINE> start = models.DateTimeField(blank=True) <NEW_LINE> end = models.DateTimeField(blank=True, null=True) <NEW_LINE> def checkout(self): <NEW_LINE> <INDENT> self.end = datetime.datetime.now() <NEW_LINE> self.spot.available = True <NEW_LINE> self.spot.in_use = False <NEW_LINE> self.spot.save() <NEW_LINE> <DEDENT> def closed(self): <NEW_LINE> <INDENT> if self.end == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.end <= timezone.now()
A reservation is created when a user books a spot. Holds info about a certain transaction.
62599082099cdd3c63676178
class SharedRoot(resource.Resource): <NEW_LINE> <INDENT> WSGI = None <NEW_LINE> def getChild(self, child, request): <NEW_LINE> <INDENT> request.prepath.pop() <NEW_LINE> request.postpath.insert(0, child) <NEW_LINE> return self.WSGI <NEW_LINE> <DEDENT> def render(self, request): <NEW_LINE> <INDENT> return self.WSGI.render(request)
Root resource that combines the two sites/entry points
62599082283ffb24f3cf539d
class ComplexData(object): <NEW_LINE> <INDENT> def __init__(self, mimeType=None, encoding=None, schema=None, maximumMegaBytes=None): <NEW_LINE> <INDENT> self.mimeType = mimeType <NEW_LINE> self.encoding = encoding <NEW_LINE> self.schema = schema <NEW_LINE> self.maximumMegabytes = maximumMegaBytes
Class that represents a ComplexData element in a WPS document
62599082796e427e53850277
class OperationListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[Operation]'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["Operation"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(OperationListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value
A list of resource provider operations. :param value: The list of resource provider operations. :type value: list[~azure.mgmt.rdbms.postgresql.models.Operation]
625990827d847024c075deda
class Flow(flow.Flow): <NEW_LINE> <INDENT> def __init__(self, name, retry=None): <NEW_LINE> <INDENT> super(Flow, self).__init__(name, retry) <NEW_LINE> self._graph = gr.Graph(name=name) <NEW_LINE> <DEDENT> def add(self, *items): <NEW_LINE> <INDENT> for item in items: <NEW_LINE> <INDENT> if not self._graph.has_node(item): <NEW_LINE> <INDENT> self._graph.add_node(item) <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._graph) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for item in self._graph: <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> <DEDENT> def iter_links(self): <NEW_LINE> <INDENT> for (u, v, e_data) in self._graph.edges_iter(data=True): <NEW_LINE> <INDENT> yield (u, v, e_data) <NEW_LINE> <DEDENT> <DEDENT> def iter_nodes(self): <NEW_LINE> <INDENT> for n, n_data in self._graph.nodes_iter(data=True): <NEW_LINE> <INDENT> yield (n, n_data) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> requires = set() <NEW_LINE> retry_provides = set() <NEW_LINE> if self._retry is not None: <NEW_LINE> <INDENT> requires.update(self._retry.requires) <NEW_LINE> retry_provides.update(self._retry.provides) <NEW_LINE> <DEDENT> for item in self: <NEW_LINE> <INDENT> item_requires = item.requires - retry_provides <NEW_LINE> requires.update(item_requires) <NEW_LINE> <DEDENT> return frozenset(requires)
Unordered flow pattern. A unordered (potentially nested) flow of *tasks/flows* that can be executed in any order as one unit and rolled back as one unit.
62599082a8370b77170f1ec9
class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'regressiontests.admin_scripts']) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.remove_settings('settings.py') <NEW_LINE> <DEDENT> def test_builtin_command(self): <NEW_LINE> <INDENT> args = ['sqlall', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, 'environment variable DJANGO_SETTINGS_MODULE is undefined') <NEW_LINE> <DEDENT> def test_builtin_with_settings(self): <NEW_LINE> <INDENT> args = ['sqlall', '--settings=regressiontests.settings', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertOutput(out, 'CREATE TABLE') <NEW_LINE> <DEDENT> def test_builtin_with_environment(self): <NEW_LINE> <INDENT> args = ['sqlall', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args, 'regressiontests.settings') <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertOutput(out, 'CREATE TABLE') <NEW_LINE> <DEDENT> def test_builtin_with_bad_settings(self): <NEW_LINE> <INDENT> args = ['sqlall', '--settings=bad_settings', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, "Could not import settings 'bad_settings'") <NEW_LINE> <DEDENT> def test_builtin_with_bad_environment(self): <NEW_LINE> <INDENT> args = ['sqlall', 'admin_scripts'] <NEW_LINE> out, err = self.run_django_admin(args, 'bad_settings') <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, "Could not import settings 'bad_settings'") <NEW_LINE> <DEDENT> def test_custom_command(self): <NEW_LINE> <INDENT> args = ['noargs_command'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(out) <NEW_LINE> self.assertOutput(err, "Unknown command: 'noargs_command'") <NEW_LINE> <DEDENT> def test_custom_command_with_settings(self): <NEW_LINE> <INDENT> args = ['noargs_command', '--settings=regressiontests.settings'] <NEW_LINE> out, err = self.run_django_admin(args) <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertOutput(out, "EXECUTE:NoArgsCommand") <NEW_LINE> <DEDENT> def test_custom_command_with_environment(self): <NEW_LINE> <INDENT> args = ['noargs_command'] <NEW_LINE> out, err = self.run_django_admin(args, 'regressiontests.settings') <NEW_LINE> self.assertNoOutput(err) <NEW_LINE> self.assertOutput(out, "EXECUTE:NoArgsCommand")
A series of tests for django-admin.py when using a settings.py file that contains the test application specified using a full path.
62599082e1aae11d1e7cf591
class MiniAlexNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MiniAlexNet, self).__init__() <NEW_LINE> self.conv = nn.Sequential( nn.Conv2d(3, 96, kernel_size=11, stride=4), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(96, 256, kernel_size=5, padding=2, groups=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(256, 384, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 384, kernel_size=3, padding=1, groups=2), nn.ReLU(inplace=True), nn.Conv2d(384, 1024, kernel_size=3, padding=1, groups=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), ) <NEW_LINE> self.fc = nn.Sequential( nn.Linear(1024, 1024), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(1024, 1024), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(1024, 100), ) <NEW_LINE> self.init_model() <NEW_LINE> <DEDENT> def init_model(self): <NEW_LINE> <INDENT> def weights_init(m): <NEW_LINE> <INDENT> classname = m.__class__.__name__ <NEW_LINE> if classname.find('Conv') != -1: <NEW_LINE> <INDENT> nn.init.kaiming_normal(m.weight.data) <NEW_LINE> if m.bias is not None: <NEW_LINE> <INDENT> m.bias.data.zero_() <NEW_LINE> <DEDENT> <DEDENT> elif classname == 'Linear': <NEW_LINE> <INDENT> nn.init.normal(m.weight.data, std=0.005) <NEW_LINE> if m.bias is not None: <NEW_LINE> <INDENT> m.bias.data.zero_() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.apply(weights_init) <NEW_LINE> return self <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> features = self.conv(input) <NEW_LINE> features = features.view(input.size(0), -1) <NEW_LINE> return self.fc(features)
A variant of AlexNet. The changes with respect to the original AlexNet are: - LRN (local response normalization) layers are not included - The Fully Connected (FC) layers (fc6 and fc7) have smaller dimensions due to the lower resolution of mini-places images (128x128) compared with ImageNet images (usually resized to 256x256)
62599082167d2b6e312b8314
class TriangleShape( Shape ): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._name = "Triangle" <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def drow(self): <NEW_LINE> <INDENT> print( self._name, "drow." )
三角形
625990824f88993c371f12a1
class MemberAddressTest(SteamTestCase): <NEW_LINE> <INDENT> __interfaceName__ = "/member-service/address/memberId" <NEW_LINE> @initInputService( services = [], curser = MemberAddressService ) <NEW_LINE> def __init__(self, methodName='runTest', param=None): <NEW_LINE> <INDENT> super(MemberAddressTest,self).__init__(methodName,param)
微信端用户进入地址管理,获取地址列表
62599082283ffb24f3cf539f
class BentIdentPar(nn.Module): <NEW_LINE> <INDENT> def __init__(self, b=1.0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.b = b <NEW_LINE> <DEDENT> def forward(self, x, a): <NEW_LINE> <INDENT> return (1.0 - a)/2.0 * (torch.sqrt(x*x + 4.0*self.b*self.b) - 2.0*self.b) + (1.0 + a)/2.0 * x
BentIdent parametric activation
62599082aad79263cf4302b9
class AverageMeter(object): <NEW_LINE> <INDENT> def __init__(self, relative=False): <NEW_LINE> <INDENT> self.relative = relative <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.val = 0 <NEW_LINE> self.avg = 0 <NEW_LINE> self.sum = 0 <NEW_LINE> self.count = 0 <NEW_LINE> <DEDENT> def update(self, val, n=1): <NEW_LINE> <INDENT> if self.relative: <NEW_LINE> <INDENT> if not self.count: <NEW_LINE> <INDENT> self.scale = 100 / abs(val) <NEW_LINE> <DEDENT> val *= self.scale <NEW_LINE> <DEDENT> self.val = val <NEW_LINE> self.sum += val * n <NEW_LINE> self.count += n <NEW_LINE> self.avg = self.sum / self.count
Computes and stores the average and current value Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
625990825fcc89381b266edc
class BatchServiceClient(ServiceClient): <NEW_LINE> <INDENT> pass
Batch Service Client Service Client for batch / head-less processes
62599082091ae3566870673f
class UpdateGainForm(FlaskForm): <NEW_LINE> <INDENT> id = HiddenField('A hidden field'); <NEW_LINE> gain = FloatField('New gain:', [DataRequired(), NumberRange(0)]) <NEW_LINE> submit = SubmitField('Update gain')
The form for updateing the gain of the Arduino
62599082656771135c48adb0
class ReplyKeyboardRemove(ReplyMarkup): <NEW_LINE> <INDENT> __slots__ = ('selective', 'remove_keyboard') <NEW_LINE> def __init__(self, selective: bool = False, **_kwargs: Any): <NEW_LINE> <INDENT> self.remove_keyboard = True <NEW_LINE> self.selective = bool(selective)
Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see :class:`telegram.ReplyKeyboardMarkup`). Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet. Note: User will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use :attr:`telegram.ReplyKeyboardMarkup.one_time_keyboard`. Args: selective (:obj:`bool`, optional): Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) Users that are @mentioned in the text of the :class:`telegram.Message` object. 2) If the bot's message is a reply (has `reply_to_message_id`), sender of the original message. **kwargs (:obj:`dict`): Arbitrary keyword arguments. Attributes: remove_keyboard (:obj:`True`): Requests clients to remove the custom keyboard. selective (:obj:`bool`): Optional. Use this parameter if you want to remove the keyboard for specific users only.
6259908297e22403b383c9ff
class itkMaximumProjectionImageFilterIF3IF2(itkMaximumProjectionImageFilterIF3IF2_Superclass): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> InputPixelTypeGreaterThanComparable = _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIF3IF2_InputPixelTypeGreaterThanComparable <NEW_LINE> InputHasNumericTraitsCheck = _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIF3IF2_InputHasNumericTraitsCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIF3IF2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> __swig_destroy__ = _itkMaximumProjectionImageFilterPython.delete_itkMaximumProjectionImageFilterIF3IF2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIF3IF2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkMaximumProjectionImageFilterPython.itkMaximumProjectionImageFilterIF3IF2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMaximumProjectionImageFilterIF3IF2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkMaximumProjectionImageFilterIF3IF2 class
625990824a966d76dd5f09e6
class LoginView(APIView): <NEW_LINE> <INDENT> def get_serializer_class(self): <NEW_LINE> <INDENT> return LoginSerializer <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> next_url = self.request.GET['next'] if 'next' in self.request.GET else '/' <NEW_LINE> return next_url <NEW_LINE> <DEDENT> def get(self, request): <NEW_LINE> <INDENT> if request.is_ajax(): <NEW_LINE> <INDENT> username = request.data['username'] <NEW_LINE> password = request.data['password'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> if request.is_ajax(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> serializer = self.get_serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> BaseAuth.login(request, login=serializer.data['username'], password=serializer.data['password']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except MyAuthException as error: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> response = Response(status=status.HTTP_200_OK, content_type='application/json') <NEW_LINE> response.set_cookie("user_id", request.user.id) <NEW_LINE> return response <NEW_LINE> <DEDENT> return Response(status=status.HTTP_400_BAD_REQUEST)
По логину и пароль осуществляет аутентификацию пользователя
6259908263b5f9789fe86c69
class VerticalBar(Bar): <NEW_LINE> <INDENT> def updateGraph(self): <NEW_LINE> <INDENT> barWidth = self.xscale * 0.9 <NEW_LINE> barMargin = self.xscale * (1.0 - 0.9) / 2 <NEW_LINE> self.bars = [] <NEW_LINE> i = 0 <NEW_LINE> keys = self.datas.keys() <NEW_LINE> keys.sort() <NEW_LINE> for xfield in keys: <NEW_LINE> <INDENT> j = 0 <NEW_LINE> barWidthForSet = barWidth / len(self.datas[xfield]) <NEW_LINE> for yfield in self._getDatasKeys(): <NEW_LINE> <INDENT> xval = i <NEW_LINE> yval = self.datas[xfield][yfield] <NEW_LINE> x = (xval - self.minxval) * self.xscale + barMargin + (j * barWidthForSet) <NEW_LINE> y = 1.0 - (yval - self.minyval) * self.yscale <NEW_LINE> w = barWidthForSet <NEW_LINE> h = yval * self.yscale <NEW_LINE> if h < 0: <NEW_LINE> <INDENT> h = abs(h) <NEW_LINE> y -= h <NEW_LINE> <DEDENT> rect = Rect(x, y, w, h, xval, yval, xfield, yfield) <NEW_LINE> if (0.0 <= rect.x <= 1.0) and (0.0 <= rect.y <= 1.0): <NEW_LINE> <INDENT> self.bars.append(rect) <NEW_LINE> <DEDENT> j += 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> <DEDENT> def XLabels(self): <NEW_LINE> <INDENT> xlabels = super(VerticalBar, self).XLabels() <NEW_LINE> return [(x[0] + (self.xscale / 2), x[1]) for x in xlabels] <NEW_LINE> <DEDENT> def YLabels(self): <NEW_LINE> <INDENT> ylabels = super(VerticalBar, self).YLabels() <NEW_LINE> if all('timedelta' in f for f in self.yfields): <NEW_LINE> <INDENT> converter = {f.get('timedelta') for f in self.yfields} <NEW_LINE> if len(converter) == 1: <NEW_LINE> <INDENT> converter = rpc.CONTEXT.get(converter.pop()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> converter = None <NEW_LINE> <DEDENT> return [ (x[0], common.timedelta.format( datetime.timedelta(seconds=locale.atof(x[1])), converter)) for x in ylabels] <NEW_LINE> <DEDENT> return ylabels
Vertical Bar Graph
625990827d847024c075dede
class Supplement(object): <NEW_LINE> <INDENT> def __init__(self, middleware, environ): <NEW_LINE> <INDENT> self.middleware = middleware <NEW_LINE> self.environ = environ <NEW_LINE> self.source_url = request.construct_url(environ) <NEW_LINE> <DEDENT> def extraData(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> cgi_vars = data[('extra', 'CGI Variables')] = {} <NEW_LINE> wsgi_vars = data[('extra', 'WSGI Variables')] = {} <NEW_LINE> hide_vars = ['paste.config', 'wsgi.errors', 'wsgi.input', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.run_once', 'wsgi.version', 'wsgi.url_scheme'] <NEW_LINE> for name, value in list(self.environ.items()): <NEW_LINE> <INDENT> if name.upper() == name: <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> cgi_vars[name] = value <NEW_LINE> <DEDENT> <DEDENT> elif name not in hide_vars: <NEW_LINE> <INDENT> wsgi_vars[name] = value <NEW_LINE> <DEDENT> <DEDENT> if self.environ['wsgi.version'] != (1, 0): <NEW_LINE> <INDENT> wsgi_vars['wsgi.version'] = self.environ['wsgi.version'] <NEW_LINE> <DEDENT> proc_desc = tuple([int(bool(self.environ[key])) for key in ('wsgi.multiprocess', 'wsgi.multithread', 'wsgi.run_once')]) <NEW_LINE> wsgi_vars['wsgi process'] = self.process_combos[proc_desc] <NEW_LINE> wsgi_vars['application'] = self.middleware.application <NEW_LINE> if 'paste.config' in self.environ: <NEW_LINE> <INDENT> data[('extra', 'Configuration')] = dict(self.environ['paste.config']) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> process_combos = { (0, 0, 0): 'Non-concurrent server', (0, 1, 0): 'Multithreaded', (1, 0, 0): 'Multiprocess', (1, 1, 0): 'Multi process AND threads (?)', (0, 0, 1): 'Non-concurrent CGI', (0, 1, 1): 'Multithread CGI (?)', (1, 0, 1): 'CGI', (1, 1, 1): 'Multi thread/process CGI (?)', }
This is a supplement used to display standard WSGI information in the traceback.
625990825fcc89381b266edd
class TestX264Ref(unittest.TestCase): <NEW_LINE> <INDENT> def test_ref(self): <NEW_LINE> <INDENT> x264 = X264() <NEW_LINE> self._test_ref_normal_values(x264) <NEW_LINE> self._test_ref_abnormal_values(x264) <NEW_LINE> <DEDENT> def _test_ref_normal_values(self, x264): <NEW_LINE> <INDENT> x264.ref = 0 <NEW_LINE> self.assertEqual(x264.ref, 0) <NEW_LINE> x264.ref = 1 <NEW_LINE> self.assertEqual(x264.ref, 1) <NEW_LINE> x264.ref = 500 <NEW_LINE> self.assertEqual(x264.ref, 500) <NEW_LINE> <DEDENT> def _test_ref_abnormal_values(self, x264): <NEW_LINE> <INDENT> x264.ref = -1 <NEW_LINE> self.assertEqual(x264.ref, 3) <NEW_LINE> x264.ref = -500 <NEW_LINE> self.assertEqual(x264.ref, 3) <NEW_LINE> x264.ref = None <NEW_LINE> self.assertEqual(x264.ref, 3)
Tests all Reference Frames option values for the x264 codec.
625990824527f215b58eb720
class KidsFeed(object): <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.feed = feedparser.parse(self.url) <NEW_LINE> self.kids_list = self.feed['items'] <NEW_LINE> self._missing_kids = [] <NEW_LINE> self._missing_kids_ids = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def missing_kids_ids(self): <NEW_LINE> <INDENT> if not self._missing_kids_ids: <NEW_LINE> <INDENT> self._missing_kids_ids = self.kids_ids() <NEW_LINE> <DEDENT> return self._missing_kids_ids <NEW_LINE> <DEDENT> @property <NEW_LINE> def missing_kids(self): <NEW_LINE> <INDENT> if not self._missing_kids: <NEW_LINE> <INDENT> self._missing_kids = self.kids() <NEW_LINE> <DEDENT> return self._missing_kids <NEW_LINE> <DEDENT> def kids_ids(self): <NEW_LINE> <INDENT> for kid_data in self.kids_list: <NEW_LINE> <INDENT> href = kid_data['links'][0]['href'] <NEW_LINE> id_raw = re.search(ID_RE, href) <NEW_LINE> id = int(id_raw.group('id')) <NEW_LINE> self._missing_kids_ids.append(id) <NEW_LINE> <DEDENT> return self._missing_kids_ids <NEW_LINE> <DEDENT> def kids(self): <NEW_LINE> <INDENT> for kid_data in self.kids_list: <NEW_LINE> <INDENT> missing_kid = MissingKid(kid_data) <NEW_LINE> self._missing_kids.append(missing_kid) <NEW_LINE> <DEDENT> return self._missing_kids
Takes a url and makes a list of MissingKids :pram url: the url from missingkids.com :type url: str :var missing_kids: :vartype missing_kids: list of MissingKid
625990822c8b7c6e89bd52e7
class UserScore(ScoreBase): <NEW_LINE> <INDENT> __score_info = None <NEW_LINE> __db_name = "" <NEW_LINE> __score_helper = None <NEW_LINE> __channel_name = "" <NEW_LINE> __my_business_logic = None <NEW_LINE> __invoke_function_map = {} <NEW_LINE> __query_function_map = {} <NEW_LINE> def __init__(self, score_info=None): <NEW_LINE> <INDENT> self.__db_name = "YOUR_SCORE_DB" <NEW_LINE> ScoreBase.__init__(self, score_info) <NEW_LINE> self.__score_info = None <NEW_LINE> if self.__score_info is None: <NEW_LINE> <INDENT> with open(join(dirname(__file__), ScoreBase.PACKAGE_FILE), "r") as f: <NEW_LINE> <INDENT> self.__score_info = json.loads(f.read()) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.__score_info = score_info <NEW_LINE> <DEDENT> self.__score_helper = ScoreHelper() <NEW_LINE> self.__my_business_logic = SCOREBusinessLogic() <NEW_LINE> for e in self.__score_info["function"]["invoke"]: <NEW_LINE> <INDENT> function_name = e["method"] <NEW_LINE> self.__invoke_function_map[function_name] = getattr(self.__my_business_logic, function_name) <NEW_LINE> <DEDENT> for e in self.__score_info["function"]["query"]: <NEW_LINE> <INDENT> function_name = e["method"] <NEW_LINE> self.__query_function_map[function_name] = getattr(self.__my_business_logic, function_name) <NEW_LINE> <DEDENT> <DEDENT> def invoke(self, transaction, block=None): <NEW_LINE> <INDENT> if block is None: <NEW_LINE> <INDENT> return SCOREResponse.exception("No block!!!") <NEW_LINE> <DEDENT> log_func = partial(self.__score_helper.log, block.channel_name) <NEW_LINE> self.__channel_name = block.channel_name <NEW_LINE> log_func("Invoke() begin.") <NEW_LINE> try: <NEW_LINE> <INDENT> tx_data = json.loads(transaction.get_data_string()) <NEW_LINE> id = tx_data["id"] <NEW_LINE> function_name = tx_data["method"] <NEW_LINE> params = tx_data["params"] <NEW_LINE> r = self.__invoke_function_map[function_name](log_func, id, params) <NEW_LINE> log_func("End Invoke()") <NEW_LINE> return r <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> log_func("Unknown function call requested!! Cannot run invoke(). ") <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def query(self, query_request): <NEW_LINE> <INDENT> log_func = partial(self.__score_helper.log, self.__channel_name) <NEW_LINE> log_func("Query() begin.") <NEW_LINE> try: <NEW_LINE> <INDENT> req = json.loads(query_request) <NEW_LINE> function_name = req["method"] <NEW_LINE> id = req['id'] <NEW_LINE> params = req['params'] <NEW_LINE> r = self.__query_function_map[function_name](log_func, id, params) <NEW_LINE> log_func("End Query()") <NEW_LINE> return json.dumps(r) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> log_func("Unknown error happen!! Cannot run query().") <NEW_LINE> raise <NEW_LINE> <DEDENT> return json.dumps(r) <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> return self.__score_info
Basic module of SCORE. DO NOT CHANGE THE NAME OF THIS MODULE.
62599082be7bc26dc9252bd6
class DeactivateProjectRedirectView(AccessControlMixin, ActionReloadView): <NEW_LINE> <INDENT> membership = 'owner' <NEW_LINE> def get_group_required(self): <NEW_LINE> <INDENT> self.project = Project.objects.get(slug=self.kwargs.get('slug')) <NEW_LINE> return super(DeactivateProjectRedirectView, self).get_group_required( self.membership, self.project) <NEW_LINE> <DEDENT> def perform_action(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.project.deactivate() <NEW_LINE> <DEDENT> def get_redirect_url(self, *args, **kwargs): <NEW_LINE> <INDENT> return reverse('pm_project_detail', args=(self.project.slug,))
Sets the specified project to inactive.
62599082aad79263cf4302bc
class NewThreadForm(forms.Form): <NEW_LINE> <INDENT> title = StrippedCharField(min_length=5, max_length=255, label=_lazy(u'Title:'), widget=forms.TextInput(attrs={'size': 80}), error_messages={'required': MSG_TITLE_REQUIRED, 'min_length': MSG_TITLE_SHORT, 'max_length': MSG_TITLE_LONG}) <NEW_LINE> content = StrippedCharField( label=_lazy(u'Content:'), min_length=5, max_length=10000, widget=forms.Textarea(attrs={'rows': 30, 'cols': 76}), error_messages={'required': MSG_CONTENT_REQUIRED, 'min_length': MSG_CONTENT_SHORT, 'max_length': MSG_CONTENT_LONG})
Form to start a new thread.
6259908244b2445a339b76dd
class Benchmark8(IRISHEP_ADLBenchmark): <NEW_LINE> <INDENT> def definePlots(self, tree, noSel, sample=None, sampleCfg=None): <NEW_LINE> <INDENT> from bamboo.plots import Plot, SummedPlot <NEW_LINE> from bamboo.plots import EquidistantBinning as EqBin <NEW_LINE> from bamboo import treefunctions as op <NEW_LINE> plots = [] <NEW_LINE> lepColl = { "El" : tree.Electron, "Mu" : tree.Muon } <NEW_LINE> mt3lPlots = [] <NEW_LINE> for dlNm,dlCol in lepColl.items(): <NEW_LINE> <INDENT> dilep = op.combine(dlCol, N=2, pred=(lambda l1,l2 : op.AND(l1.charge != l2.charge))) <NEW_LINE> hasDiLep = noSel.refine("hasDilep{0}{0}".format(dlNm), cut=(op.rng_len(dilep) > 0)) <NEW_LINE> dilepZ = op.rng_min_element_by(dilep, fun=lambda ll : op.abs(op.invariant_mass(ll[0].p4, ll[1].p4)-91.2)) <NEW_LINE> for tlNm,tlCol in lepColl.items(): <NEW_LINE> <INDENT> if tlCol == dlCol: <NEW_LINE> <INDENT> hasTriLep = hasDiLep.refine("hasTrilep{0}{0}{1}".format(dlNm,tlNm), cut=(op.rng_len(tlCol) > 2)) <NEW_LINE> residLep = op.select(tlCol, lambda l : op.AND(l.idx != dilepZ[0].idx, l.idx != dilepZ[1].idx)) <NEW_LINE> l3 = op.rng_max_element_by(residLep, lambda l : l.pt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hasTriLep = hasDiLep.refine("hasTriLep{0}{0}{1}".format(dlNm,tlNm), cut=(op.rng_len(tlCol) > 0)) <NEW_LINE> l3 = op.rng_max_element_by(tlCol, lambda l : l.pt) <NEW_LINE> <DEDENT> mtPlot = Plot.make1D("3lMT_{0}{0}{1}".format(dlNm,tlNm), op.sqrt(2*l3.pt*tree.MET.pt*(1-op.cos(l3.phi-tree.MET.phi))), hasTriLep, EqBin(100, 15., 250.), title="M_{T} (GeV/c^2)") <NEW_LINE> mt3lPlots.append(mtPlot) <NEW_LINE> plots.append(mtPlot) <NEW_LINE> <DEDENT> <DEDENT> plots.append(SummedPlot("3lMT", mt3lPlots)) <NEW_LINE> return plots
For events with at least three leptons and a same-flavor opposite-sign lepton pair, find the same-flavor opposite-sign lepton pair with the mass closest to 91.2 GeV and plot the transverse mass of the missing energy and the leading other lepton.
62599082283ffb24f3cf53a2
class CreationOfCourse(Resource): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> def post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> response = create_course.creation_of_courses(data["data"]) <NEW_LINE> return get_response(data=response) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return {"error": str(e)}
To create the course only admin can create the courses
625990827b180e01f3e49de5
class LLScardDevice(object): <NEW_LINE> <INDENT> def __init__(self, context, card, protocol): <NEW_LINE> <INDENT> self._context = context <NEW_LINE> self._card = card <NEW_LINE> self._protocol = protocol <NEW_LINE> <DEDENT> def send_apdu(self, cl, ins, p1, p2, data): <NEW_LINE> <INDENT> apdu = [cl, ins, p1, p2, len(data)] + map(ord, data) <NEW_LINE> hresult, response = SCardTransmit(self._card, self._protocol, apdu) <NEW_LINE> if hresult != SCARD_S_SUCCESS: <NEW_LINE> <INDENT> raise Exception('Failed to transmit: ' + SCardGetErrorMessage(hresult)) <NEW_LINE> <DEDENT> status = response[-2] << 8 | response[-1] <NEW_LINE> return ''.join(map(chr, response[:-2])), status <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> SCardDisconnect(self._card, SCARD_UNPOWER_CARD) <NEW_LINE> SCardReleaseContext(self._context)
Low level pyscard based backend (Windows chokes on the high level one whenever you remove the key and re-insert it).
625990824428ac0f6e65a030
class PackedVertex(base.MappedArray): <NEW_LINE> <INDENT> x: int <NEW_LINE> y: int <NEW_LINE> z: int <NEW_LINE> _mapping = [*"xyz"] <NEW_LINE> _format = "3h"
a point in 3D space
6259908223849d37ff852bbb
class ComplexCubical3Euclidian3(ComplexCubical): <NEW_LINE> <INDENT> def plot_slice(self, affine, ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def as_regular(self): <NEW_LINE> <INDENT> from pycomplex.complex.regular import ComplexRegular3 <NEW_LINE> return ComplexRegular3(vertices=self.vertices, topology=self.topology)
3-Cubes in 3d euclidian space
6259908292d797404e3898dd
class Reservation(core_models.TimeStampedModel): <NEW_LINE> <INDENT> STATUS_PENDING = "pending" <NEW_LINE> STATUS_CONFIRMED = "confirmed" <NEW_LINE> STATUS_CANCELED = "canceled" <NEW_LINE> STATUS_CHOICES = ( (STATUS_PENDING, "Pending"), (STATUS_CONFIRMED, "Confirmed"), (STATUS_CANCELED, "Canceled"), ) <NEW_LINE> status = models.CharField( max_length=12, choices=STATUS_CHOICES, default=STATUS_PENDING, ) <NEW_LINE> check_in = models.DateField() <NEW_LINE> check_out = models.DateField() <NEW_LINE> guest = models.ForeignKey( "users.User", related_name="reservations", on_delete=models.CASCADE ) <NEW_LINE> room = models.ForeignKey( "rooms.Room", related_name="reservations", on_delete=models.CASCADE ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"{self.room} - {self.check_in}" <NEW_LINE> <DEDENT> def in_progress(self): <NEW_LINE> <INDENT> now = timezone.now().date() <NEW_LINE> return now >= self.check_in and now <= self.check_out <NEW_LINE> <DEDENT> in_progress.boolean = True <NEW_LINE> def is_finished(self): <NEW_LINE> <INDENT> now = timezone.now().date() <NEW_LINE> is_finished = now > self.check_out <NEW_LINE> if is_finished: <NEW_LINE> <INDENT> BookedDay.objects.filter(reservation=self).delete() <NEW_LINE> <DEDENT> return is_finished <NEW_LINE> <DEDENT> is_finished.boolean = True <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.pk is None: <NEW_LINE> <INDENT> start = self.check_in <NEW_LINE> end = self.check_out <NEW_LINE> difference = end - start <NEW_LINE> existing_booked_day = BookedDay.objects.filter( reservation__room=self.room, day__range=(start, end) ).exists() <NEW_LINE> if not existing_booked_day: <NEW_LINE> <INDENT> super().save(*args, **kwargs) <NEW_LINE> for i in range(difference.days + 1): <NEW_LINE> <INDENT> day = start + datetime.timedelta(days=i) <NEW_LINE> BookedDay.objects.create(day=day, reservation=self) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> <DEDENT> return super().save(*args, **kwargs)
Resrvation Model Definition
625990827c178a314d78e96b
class BaseMorphAction: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.core = CoreScript() <NEW_LINE> self.name = "" <NEW_LINE> self.title = "" <NEW_LINE> self.description = "" <NEW_LINE> self.structure = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def settings(self) -> MorphActionModel: <NEW_LINE> <INDENT> morph_settings = { "name": self.name, "title": self.title, "type": "morph", "description": self.description, "structure": self.structure, } <NEW_LINE> return MorphActionModel(**morph_settings) <NEW_LINE> <DEDENT> def transform(self, df: pd.DataFrame, rows: List[int], columns: List[ColumnModel]) -> pd.DataFrame: <NEW_LINE> <INDENT> return df <NEW_LINE> <DEDENT> def _column_renames_to_index(self, df: pd.DataFrame, columns: str, hex: str) -> pd.DataFrame: <NEW_LINE> <INDENT> renames = {c: c.replace(hex, f"idx_{df.columns.get_loc(c)}") for c in columns} <NEW_LINE> return df.rename(index=str, columns=renames) <NEW_LINE> <DEDENT> def _generate_hex(self): <NEW_LINE> <INDENT> return str(uuid4().hex)[:4]
Morphs differ from Actions in that they normally act to reshape entire tables rather than manipulate columns. * Morph actions are not permitted to be nested, i.e. they are stand-alone ActionScripts. * May result in changes to column or row references that must be accounted for in other actions. Morphs inherit from this base class which describes the core functions and methodology for a Morph. They should redefine `name`, `title`, `description`, and `structure`, as well as produce a `transform` function. Everything else will probably remain as defined, but particularly complex Morphs should modify as required. `structure` can be an empty list, but a morph may be defined by these parameters: * `rows`: the specific rows effected by the morph, a `list` of `int` * `columns`: the specific columns effected by the morph, a `list` of `ColumnModel` or `FieldModel`. A standard script is:: "ACTION > [columns] < [rows]" Where: * the presence and order of the arrays is set by `structure`, * `columns` are indicated by `>`, and * `rows` are indicated by `<`.
6259908276e4537e8c3f1081
class Explosion (pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__ (self, x, y): <NEW_LINE> <INDENT> super(Explosion, self).__init__() <NEW_LINE> self.e1 = pygame.image.load(image_paths["e1"]).convert() <NEW_LINE> self.e2 = pygame.image.load(image_paths["e2"]).convert() <NEW_LINE> self.e3 = pygame.image.load(image_paths["e3"]).convert() <NEW_LINE> self.e4 = pygame.image.load(image_paths["e4"]).convert() <NEW_LINE> self.e5 = pygame.image.load(image_paths["e5"]).convert() <NEW_LINE> self.e1.set_colorkey(BLACK) <NEW_LINE> self.e2.set_colorkey(BLACK) <NEW_LINE> self.e3.set_colorkey(BLACK) <NEW_LINE> self.e4.set_colorkey(BLACK) <NEW_LINE> self.e5.set_colorkey(BLACK) <NEW_LINE> self.image_list = [self.e1, self.e2, self.e3, self.e4, self.e5] <NEW_LINE> self.frame = 0 <NEW_LINE> self.exp_num = 0 <NEW_LINE> self.image = self.e1 <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = x <NEW_LINE> self.rect.y = y <NEW_LINE> <DEDENT> def update (self): <NEW_LINE> <INDENT> if self.frame == 16: <NEW_LINE> <INDENT> self.kill() <NEW_LINE> <DEDENT> elif self.frame % 4 == 0: <NEW_LINE> <INDENT> self.exp_num += 1 <NEW_LINE> <DEDENT> self.frame += 1 <NEW_LINE> self.image = self.image_list[self.exp_num] <NEW_LINE> <DEDENT> def get_x (self): <NEW_LINE> <INDENT> return self.rect.x <NEW_LINE> <DEDENT> def get_y (self): <NEW_LINE> <INDENT> return self.rect.y <NEW_LINE> <DEDENT> def set_x (self, new_x): <NEW_LINE> <INDENT> self.rect.x = new_x <NEW_LINE> <DEDENT> def set_y (self, new_y): <NEW_LINE> <INDENT> self.rect.y = new_y
Spawns an explosion at the given location. Attributes: e1 (pygame.image): Image path for frame 1/5 of the explosion. e2 (pygame.image): Image path for frame 2/5 of the explosion. e3 (pygame.image): Image path for frame 3/5 of the explosion. e4 (pygame.image): Image path for frame 4/5 of the explosion. e5 (pygame.image): Image path for frame 5/5 of the explosion. image_list (list): A subscriptable list for easily parsing the frames. frame (int): The total frames elapsed in the explosion. exp_num (int): Index of currently showing frame. image (pygame.image): The image object that gets blited by front end. rect (pygame.image.rect): Position, height, width values for image.
6259908297e22403b383ca01
class Bullet1(PlaneGame): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("./images/bullet1.png", -6) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> super().update() <NEW_LINE> if self.rect.bottom < 0: <NEW_LINE> <INDENT> self.kill()
子弹精灵类
6259908263b5f9789fe86c6b
class GroupTopic(Topic): <NEW_LINE> <INDENT> parent_group = models.ForeignKey(BaseGroup, related_name="topics", verbose_name=_('parent')) <NEW_LINE> send_as_email = models.BooleanField(_('send as email'), default=False) <NEW_LINE> whiteboard = models.ForeignKey(Article, related_name="topic", verbose_name=_('whiteboard'), null=True) <NEW_LINE> objects = GroupTopicManager() <NEW_LINE> def get_absolute_url(self, group=None): <NEW_LINE> <INDENT> kwargs = {"topic_id": self.pk} <NEW_LINE> return reverse("topic_detail", kwargs=kwargs) <NEW_LINE> <DEDENT> def is_visible(self, user): <NEW_LINE> <INDENT> if self.creator == user: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.parent_group.is_visible(user) <NEW_LINE> <DEDENT> <DEDENT> def is_editable(self, user): <NEW_LINE> <INDENT> return user == self.creator or self.parent_group.user_is_admin(user) <NEW_LINE> <DEDENT> def save(self, force_insert=False, force_update=False): <NEW_LINE> <INDENT> self.body = clean_html(self.body) <NEW_LINE> self.body = autolink_html(self.body) <NEW_LINE> group = BaseGroup.objects.get(id=self.object_id) <NEW_LINE> self.parent_group = group <NEW_LINE> super(GroupTopic, self).save(force_insert, force_update) <NEW_LINE> post_save.send(sender=Topic, instance=GroupTopic.objects.get(id=self.id)) <NEW_LINE> <DEDENT> def send_email(self, sender=None): <NEW_LINE> <INDENT> attachments = Attachment.objects.attachments_for_object(self) <NEW_LINE> tmpl = loader.get_template("email_template.html") <NEW_LINE> c = Context({'group': self.group, 'title': self.title, 'body': self.body, 'topic_id': self.pk, 'attachments': attachments }) <NEW_LINE> message = tmpl.render(c) <NEW_LINE> if self.send_as_email: <NEW_LINE> <INDENT> self.group.send_mail_to_members(self.title, message, sender=sender) <NEW_LINE> <DEDENT> for list in self.watchlists: <NEW_LINE> <INDENT> user = list.owner <NEW_LINE> sender = 'myEWB <[email protected]>' <NEW_LINE> msg = EmailMessage(subject=self.title, body=message, from_email=sender, to=user.email ) <NEW_LINE> msg.send(fail_silently=False) <NEW_LINE> <DEDENT> <DEDENT> def num_whiteboard_edits(self): <NEW_LINE> <INDENT> if self.whiteboard: <NEW_LINE> <INDENT> return self.whiteboard.changeset_set.count() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def intro(self): <NEW_LINE> <INDENT> if len(self.body) < 600: <NEW_LINE> <INDENT> return self.body <NEW_LINE> <DEDENT> intro = self.body[:600].rsplit(' ', 1)[0] <NEW_LINE> intro = Cleaner(scripts=False, javascript=False, comments=False, links=False, meta=False, embedded=False, frames=False, forms=False, annoying_tags=False, remove_unknown_tags=False, safe_attrs_only=False).clean_html(intro) <NEW_LINE> intro += "..." <NEW_LINE> return intro <NEW_LINE> <DEDENT> def intro_has_more(self): <NEW_LINE> <INDENT> return (len(self.body) >= 600) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('-modified', )
a discussion topic for a BaseGroup.
625990828a349b6b43687d60
class YouTube(Workload): <NEW_LINE> <INDENT> package = 'com.google.android.youtube' <NEW_LINE> action = 'android.intent.action.VIEW' <NEW_LINE> def __init__(self, test_env): <NEW_LINE> <INDENT> super(YouTube, self).__init__(test_env) <NEW_LINE> self._log = logging.getLogger('YouTube') <NEW_LINE> self._log.debug('Workload created') <NEW_LINE> self.db_file = None <NEW_LINE> <DEDENT> def run(self, out_dir, video_url, video_duration_s, collect=''): <NEW_LINE> <INDENT> self.out_dir = out_dir <NEW_LINE> self.collect = collect <NEW_LINE> Screen.unlock(self._target) <NEW_LINE> System.force_stop(self._target, self.package) <NEW_LINE> System.monkey(self._target, self.package) <NEW_LINE> Screen.set_orientation(self._target, portrait=False) <NEW_LINE> Screen.set_brightness(self._target, auto=False, percent=0) <NEW_LINE> System.gfxinfo_reset(self._target, self.package) <NEW_LINE> sleep(1) <NEW_LINE> System.start_action(self._target, self.action, video_url) <NEW_LINE> sleep(1) <NEW_LINE> self.tracingStart() <NEW_LINE> self._log.info('Play video for %d [s]', video_duration_s) <NEW_LINE> sleep(video_duration_s) <NEW_LINE> self.tracingStop() <NEW_LINE> self.db_file = os.path.join(out_dir, "framestats.txt") <NEW_LINE> System.gfxinfo_get(self._target, self.package, self.db_file) <NEW_LINE> System.force_stop(self._target, self.package, clear=False) <NEW_LINE> System.home(self._target) <NEW_LINE> Screen.set_orientation(self._target, auto=True) <NEW_LINE> Screen.set_brightness(self._target, auto=True)
Android YouTube workload
625990823346ee7daa3383e3
class CropForm(forms.Form): <NEW_LINE> <INDENT> scale = forms.CharField(widget=forms.Textarea( attrs={'style': 'display:none'})) <NEW_LINE> angle = forms.CharField(widget=forms.Textarea( attrs={'style': 'display:none'})) <NEW_LINE> x = forms.CharField(widget=forms.Textarea(attrs={'style': 'display:none'})) <NEW_LINE> y = forms.CharField(widget=forms.Textarea(attrs={'style': 'display:none'})) <NEW_LINE> w = forms.CharField(widget=forms.Textarea(attrs={'style': 'display:none'})) <NEW_LINE> h = forms.CharField(widget=forms.Textarea(attrs={'style': 'display:none'}))
Hide a fields to hold the coordinates chosen by the user
625990825fcc89381b266ede
class ShallowDiffer(Differ): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ShallowDiffer, self).__init__(u'sd') <NEW_LINE> <DEDENT> def can_diff(self, data): <NEW_LINE> <INDENT> return all(not isinstance(value, dict) for value in data.values()) <NEW_LINE> <DEDENT> def diff(self, old, new, ignore=None): <NEW_LINE> <INDENT> diff = {} <NEW_LINE> if ignore is None: <NEW_LINE> <INDENT> ignore = [] <NEW_LINE> <DEDENT> new_keys = set(new.keys()) - set(ignore) <NEW_LINE> removes = set(old.keys()) - new_keys <NEW_LINE> if removes: <NEW_LINE> <INDENT> diff[u'r'] = list(removes) <NEW_LINE> <DEDENT> changes = {} <NEW_LINE> for key in new_keys: <NEW_LINE> <INDENT> if key in old: <NEW_LINE> <INDENT> if old[key] != new[key]: <NEW_LINE> <INDENT> changes[key] = new[key] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> changes[key] = new[key] <NEW_LINE> <DEDENT> <DEDENT> if changes: <NEW_LINE> <INDENT> diff[u'c'] = changes <NEW_LINE> <DEDENT> return diff <NEW_LINE> <DEDENT> def patch(self, diff_result, old, in_place=False): <NEW_LINE> <INDENT> if not in_place: <NEW_LINE> <INDENT> old = marshal.loads(marshal.dumps(old)) <NEW_LINE> <DEDENT> for key in diff_result.get(u'r', []): <NEW_LINE> <INDENT> del old[key] <NEW_LINE> <DEDENT> old.update(diff_result.get(u'c', {})) <NEW_LINE> return old
A Differ that only works on dicts that don't have nested dicts. Assuming this allows it to use dict.update to patch the old data dict to the new which is really quick! The ID used for this differ is 'sd'.
62599082be7bc26dc9252bd7
class BuildDatabase: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.environ = self.set_environment_from_terminal() <NEW_LINE> <DEDENT> def create_table(self, schema: str, table: str): <NEW_LINE> <INDENT> db_connection = psycopg2.connect(self.environ['dbname'], sslmode='require') <NEW_LINE> self.run_syntax(db_connection=db_connection, syntax=f"CREATE TABLE IF NOT EXISTS {table}({schema})") <NEW_LINE> db_connection.commit() <NEW_LINE> db_connection.close() <NEW_LINE> return(None) <NEW_LINE> <DEDENT> def populate_table(self, table_name: str, df: pd.DataFrame): <NEW_LINE> <INDENT> db_connection = psycopg2.connect(self.environ['dbname'], sslmode='require') <NEW_LINE> cur = db_connection.cursor() <NEW_LINE> cur.execute(f"SELECT * FROM {table_name} LIMIT 0") <NEW_LINE> cur.close() <NEW_LINE> col_names = [i[0] for i in cur.description] <NEW_LINE> df["row_timestamp"] = [datetime.now().strftime("%m-%d-%Y %H:%M:%S")] * len(df.index) <NEW_LINE> missing_columns = set(col_names).difference(df.columns) <NEW_LINE> assert not missing_columns, f"The following columns are missing in your CSV file: {','.join(missing_columns)}" <NEW_LINE> df = df[col_names] <NEW_LINE> for index, row in df.iterrows(): <NEW_LINE> <INDENT> self.run_syntax(db_connection=db_connection, syntax=f"INSERT INTO {table_name} VALUES{tuple(row.values)}") <NEW_LINE> <DEDENT> db_connection.commit() <NEW_LINE> db_connection.close() <NEW_LINE> return(None) <NEW_LINE> <DEDENT> def run_syntax(self, db_connection: psycopg2, syntax: str): <NEW_LINE> <INDENT> cur = db_connection.cursor() <NEW_LINE> cur.execute(syntax) <NEW_LINE> cur.close() <NEW_LINE> return(None) <NEW_LINE> <DEDENT> def set_environment_from_terminal(self): <NEW_LINE> <INDENT> if os.getenv("database_type") == "Heroku" or os.getenv("database_type") == "local": <NEW_LINE> <INDENT> environ = { 'dbname' : os.getenv("database_uri"), 'dbtype' : os.getenv("database_type") } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit("Host name not valid. Check environment variables.") <NEW_LINE> <DEDENT> return(environ)
build relational database from csv file with Python and Heroku (https://dashboard.heroku.com/apps)
62599082aad79263cf4302be
class RvalGetattr(object): <NEW_LINE> <INDENT> def __init__(self, info): <NEW_LINE> <INDENT> self.info = info <NEW_LINE> <DEDENT> def __call__(self, name, objs=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.info[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise InferenceError(name)
See `lmap_info`
62599082a8370b77170f1ece
class ValueSpecifier(BoundFunctionBase): <NEW_LINE> <INDENT> def setup_impl(self, call_info: FunctionCallInfo): <NEW_LINE> <INDENT> old_callable: BoundFunctionBase = self.bound_expression <NEW_LINE> new_callable: BoundFunctionBase = old_callable <NEW_LINE> new_callable.value = call_info.arguments[0] <NEW_LINE> new_callable.bound_cfg >>= CfgSimple.concatenate(*call_info.arguments_cfgs) <NEW_LINE> self.flattened_expression_values = [new_callable] <NEW_LINE> self.cfg = CfgSimple.empty()
Callable value specifier (as in `this.my_func.value(1 ether)()`) C.f. remarks for [[GasSpecifier]]
625990827b180e01f3e49de6
class ToonGasMeterDeviceEntity(ToonEntity): <NEW_LINE> <INDENT> @property <NEW_LINE> def device_info(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> via_hub = 'meter_adapter' <NEW_LINE> if self.toon.gas.is_smart: <NEW_LINE> <INDENT> via_hub = 'electricity' <NEW_LINE> <DEDENT> return { 'name': 'Gas Meter', 'identifiers': { (DOMAIN, self.toon.agreement.id, 'gas'), }, 'via_hub': (DOMAIN, self.toon.agreement.id, via_hub), }
Defines a Gas Meter device entity.
625990825166f23b2e244ede
class CDSResult: <NEW_LINE> <INDENT> def __init__(self, domain_hmms: List[HMMResult], motif_hmms: List[HMMResult], feature_type: str, modules: List[Module], ks_subtypes: List[str]) -> None: <NEW_LINE> <INDENT> self.domain_hmms = domain_hmms <NEW_LINE> self.motif_hmms = motif_hmms <NEW_LINE> self.type = feature_type <NEW_LINE> self.modules = modules <NEW_LINE> self.ks_subtypes = ks_subtypes <NEW_LINE> self.domain_features = {} <NEW_LINE> ks_count = sum(dom.hit_id == "PKS_KS" for dom in self.domain_hmms) <NEW_LINE> if len(ks_subtypes) != ks_count: <NEW_LINE> <INDENT> raise ValueError("mismatching KS subtypes and PKS_KS counts: %d %d" % (len(ks_subtypes), ks_count)) <NEW_LINE> <DEDENT> <DEDENT> def to_json(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> return { "domain_hmms": [hmm.to_json() for hmm in self.domain_hmms], "motif_hmms": [hmm.to_json() for hmm in self.motif_hmms], "modules": [module.to_json() for module in self.modules], "type": self.type, "ks_subtypes": self.ks_subtypes, } <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(data: Dict[str, Any]) -> "CDSResult": <NEW_LINE> <INDENT> domain_hmms = [HMMResult.from_json(hmm) for hmm in data["domain_hmms"]] <NEW_LINE> motif_hmms = [HMMResult.from_json(hmm) for hmm in data["motif_hmms"]] <NEW_LINE> modules = [Module.from_json(module) for module in data["modules"]] <NEW_LINE> return CDSResult(domain_hmms, motif_hmms, data["type"], modules, data["ks_subtypes"]) <NEW_LINE> <DEDENT> def annotate_domains(self, record: Record, cds: CDSFeature) -> None: <NEW_LINE> <INDENT> if not self.domain_hmms: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cds.nrps_pks.type = self.type <NEW_LINE> self.domain_features = generate_domain_features(cds, self.domain_hmms) <NEW_LINE> ks_sub = iter(self.ks_subtypes) <NEW_LINE> for domain, domain_feature in self.domain_features.items(): <NEW_LINE> <INDENT> if domain.hit_id == "PKS_KS": <NEW_LINE> <INDENT> sub = next(ks_sub) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sub = "" <NEW_LINE> <DEDENT> record.add_antismash_domain(domain_feature) <NEW_LINE> cds.nrps_pks.add_domain(domain, domain_feature.get_name(), sub) <NEW_LINE> <DEDENT> if not self.motif_hmms: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> motif_features = generate_motif_features(cds, self.motif_hmms) <NEW_LINE> for motif in motif_features: <NEW_LINE> <INDENT> record.add_cds_motif(motif) <NEW_LINE> <DEDENT> cds.motifs.extend(motif_features)
Stores and enables reconstruction of all results for a single CDS
62599082ec188e330fdfa3b0
class PlainPythonRepr(ObjectReprABC): <NEW_LINE> <INDENT> def __call__(self, obj, p, cycle): <NEW_LINE> <INDENT> klass = _safe_getattr(obj, '__class__', None) or type(obj) <NEW_LINE> klass_repr = _safe_getattr(klass, '__repr__', None) <NEW_LINE> if klass_repr in _baseclass_reprs: <NEW_LINE> <INDENT> p.text(klass_repr(obj)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = repr(obj) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> import sys, traceback <NEW_LINE> objrepr = object.__repr__(obj).replace("object at", "at") <NEW_LINE> exc = traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]) <NEW_LINE> exc = (''.join(exc)).strip() <NEW_LINE> output = "<repr({}) failed: {}>".format(objrepr, exc) <NEW_LINE> <DEDENT> for idx, output_line in enumerate(output.split('\n')): <NEW_LINE> <INDENT> if idx: <NEW_LINE> <INDENT> p.break_() <NEW_LINE> <DEDENT> p.text(output_line) <NEW_LINE> <DEDENT> <DEDENT> return True
The ordinary Python representation .. automethod:: __call__
6259908226068e7796d4e446
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email
Database model for users in the system
625990823617ad0b5ee07c54
class ThugCtrl(object): <NEW_LINE> <INDENT> def __init__(self, configfile, extensive = False, threshold = 0, referer = None, proxy = None, timeout = None): <NEW_LINE> <INDENT> self.host = "localhost" <NEW_LINE> self.queue = "thugctrl" <NEW_LINE> self.username = "guest" <NEW_LINE> self.password = "guest" <NEW_LINE> self.extensive = extensive <NEW_LINE> self.threshold = threshold <NEW_LINE> self.referer = referer <NEW_LINE> self.proxy = proxy <NEW_LINE> self.timeout = timeout <NEW_LINE> self.configfile = configfile <NEW_LINE> self.read_config() <NEW_LINE> <DEDENT> def read_config(self): <NEW_LINE> <INDENT> conf = ConfigParser.ConfigParser() <NEW_LINE> conf.read(self.configfile) <NEW_LINE> self.host = conf.get("jobs", "host") <NEW_LINE> self.queue = conf.get("jobs", "queue") <NEW_LINE> self.username = conf.get("credentials", "username") <NEW_LINE> self.password = conf.get("credentials", "password") <NEW_LINE> <DEDENT> def send_command(self, data): <NEW_LINE> <INDENT> credentials = pika.PlainCredentials(self.username, self.password) <NEW_LINE> connection = pika.BlockingConnection(pika.ConnectionParameters( host=self.host, credentials = credentials)) <NEW_LINE> channel = connection.channel() <NEW_LINE> channel.queue_declare(queue=self.queue, durable=True) <NEW_LINE> message = json.dumps(data) <NEW_LINE> channel.basic_publish(exchange='', routing_key=self.queue, body=message, properties=pika.BasicProperties( delivery_mode=2, )) <NEW_LINE> print(" [x] Sent %r" % (message,)) <NEW_LINE> connection.close() <NEW_LINE> <DEDENT> def process(self, url): <NEW_LINE> <INDENT> if url.find("://") < 0: <NEW_LINE> <INDENT> url = "http://" + url <NEW_LINE> <DEDENT> o = urlparse.urlparse(url) <NEW_LINE> jid = o.netloc + "_" + datetime.datetime.now().strftime( "%Y_%m_%d__%H_%M_%S") <NEW_LINE> data = {"url": url, "id": jid, "threshold": self.threshold, "extensive": self.extensive, "referer": self.referer, "proxy": self.proxy, "timeout": self.timeout } <NEW_LINE> print(data) <NEW_LINE> self.send_command(data)
Thug remote control
625990825fc7496912d48fed
class TeamEnergyGoalTest(TransactionTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> test_utils.set_competition_round() <NEW_LINE> group = Group.objects.create(name="Test Group") <NEW_LINE> group.save() <NEW_LINE> self.team = Team.objects.create( group=group, name="A" ) <NEW_LINE> self.user = User.objects.create_user("user", "[email protected]") <NEW_LINE> profile = self.user.get_profile() <NEW_LINE> profile.team = self.team <NEW_LINE> profile.save() <NEW_LINE> <DEDENT> def testTeamEnergyGoal(self): <NEW_LINE> <INDENT> profile = self.user.get_profile() <NEW_LINE> points = profile.points() <NEW_LINE> goal_settings = EnergyGoalSetting.objects.filter(team=self.team) <NEW_LINE> if not goal_settings: <NEW_LINE> <INDENT> goal_settings = EnergyGoalSetting(team=self.team, goal_percent_reduction=5, goal_points=20, baseline_method="Fixed", manual_entry=True, manual_entry_time=datetime.time(hour=15), ) <NEW_LINE> goal_settings.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> goal_settings = goal_settings[0] <NEW_LINE> <DEDENT> goal_baseline = EnergyBaselineDaily( team=self.team, day=datetime.date.today().weekday(), usage=150, ) <NEW_LINE> goal_baseline.save() <NEW_LINE> energy_data = EnergyUsage( team=self.team, date=datetime.date.today(), time=datetime.time(hour=15), usage=100, ) <NEW_LINE> energy_data.save() <NEW_LINE> today = datetime.date.today() <NEW_LINE> resource_goal.check_team_resource_goal("energy", self.team, today) <NEW_LINE> profile = Profile.objects.get(user__username="user") <NEW_LINE> self.assertEqual(profile.points(), points, "User that did not complete the setup process should not be awarded points.") <NEW_LINE> profile.setup_complete = True <NEW_LINE> profile.save() <NEW_LINE> energy_data.usage = 150 <NEW_LINE> energy_data.save() <NEW_LINE> EnergyGoal.objects.filter(team=self.team, date=today).delete() <NEW_LINE> resource_goal.check_team_resource_goal("energy", self.team, today) <NEW_LINE> profile = Profile.objects.get(user__username="user") <NEW_LINE> self.assertEqual(profile.points(), points, "Team that failed the goal should not be awarded any points.") <NEW_LINE> energy_data.usage = 100 <NEW_LINE> energy_data.save() <NEW_LINE> EnergyGoal.objects.filter(team=self.team, date=today).delete() <NEW_LINE> resource_goal.check_team_resource_goal("energy", self.team, today) <NEW_LINE> profile = Profile.objects.get(user__username="user") <NEW_LINE> self.assertEqual(profile.points(), points + goal_settings.goal_points, "User that setup their profile should be awarded points.")
Team Energy Goal Test
625990825fdd1c0f98e5fa85
class Player(object): <NEW_LINE> <INDENT> def __init__(self, cards): <NEW_LINE> <INDENT> self.board_state = cards <NEW_LINE> self.hand = [generate_random_card() for i in range(14)] <NEW_LINE> for card in cards: <NEW_LINE> <INDENT> board.legal(card) <NEW_LINE> <DEDENT> <DEDENT> def play(self): <NEW_LINE> <INDENT> return scientist(self.hand, game_ended) <NEW_LINE> <DEDENT> def update_card_to_boardstate(self,card,result): <NEW_LINE> <INDENT> if result: <NEW_LINE> <INDENT> board.legal(card) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> board.illegal(card) <NEW_LINE> <DEDENT> self.board_state.append(card)
'cards' is a list of three valid cards to be given by the dealer at the beginning of the game.
6259908276e4537e8c3f1085
class Gtlink_scrmaps(Gtlink): <NEW_LINE> <INDENT> appname = 'gtscrmaps' <NEW_LINE> linkname_default = 'gtscrmaps' <NEW_LINE> usage = '%s [options]' % (appname) <NEW_LINE> description = "Link to run %s" % (appname) <NEW_LINE> default_options = dict(irfs=diffuse_defaults.gtopts['irfs'], expcube=diffuse_defaults.gtopts['expcube'], bexpmap=diffuse_defaults.gtopts['bexpmap'], cmap=diffuse_defaults.gtopts['cmap'], srcmdl=diffuse_defaults.gtopts['srcmdl'], outfile=diffuse_defaults.gtopts['outfile']) <NEW_LINE> default_file_args = dict(expcube=FileFlags.input_mask, cmap=FileFlags.input_mask, bexpmap=FileFlags.input_mask, srcmdl=FileFlags.input_mask, outfile=FileFlags.output_mask) <NEW_LINE> __doc__ += Link.construct_docstring(default_options)
Small wrapper to run gtscrmaps
62599082a8370b77170f1ed2
class DummyWorkspace(object): <NEW_LINE> <INDENT> zope.interface.implements(IWorkspace) <NEW_LINE> def __init__(self, id_): <NEW_LINE> <INDENT> self.id = id_ <NEW_LINE> self.storage = None <NEW_LINE> <DEDENT> def restrictedTraverse(self, path): <NEW_LINE> <INDENT> return DummyWorkspace(path)
To avoid dealing with the vocab and the rest of Plone Archetypes.
62599082283ffb24f3cf53a7
class TestResult(object): <NEW_LINE> <INDENT> def __init__(self, name, status, time, output_file_name): <NEW_LINE> <INDENT> assert status in (PASSED, FAILED, SKIPPED) <NEW_LINE> self.name = name <NEW_LINE> self._status = status <NEW_LINE> self.time = time <NEW_LINE> self._output_file_name = output_file_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def output(self): <NEW_LINE> <INDENT> file_exists = os.path.isfile(self._output_file_name) <NEW_LINE> is_readable = os.access(self._output_file_name, os.R_OK) <NEW_LINE> if file_exists and is_readable: <NEW_LINE> <INDENT> return read_file(self._output_file_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Failed to read output file: %s" % self._output_file_name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def passed(self): <NEW_LINE> <INDENT> return self._status == PASSED <NEW_LINE> <DEDENT> @property <NEW_LINE> def skipped(self): <NEW_LINE> <INDENT> return self._status == SKIPPED <NEW_LINE> <DEDENT> @property <NEW_LINE> def failed(self): <NEW_LINE> <INDENT> return self._status == FAILED <NEW_LINE> <DEDENT> def print_status(self, printer, padding=0): <NEW_LINE> <INDENT> if self.passed: <NEW_LINE> <INDENT> printer.write("pass", fg='gi') <NEW_LINE> printer.write(" ") <NEW_LINE> <DEDENT> elif self.failed: <NEW_LINE> <INDENT> printer.write("fail", fg='ri') <NEW_LINE> printer.write(" ") <NEW_LINE> <DEDENT> elif self.skipped: <NEW_LINE> <INDENT> printer.write("skip", fg='rgi') <NEW_LINE> printer.write(" ") <NEW_LINE> <DEDENT> my_padding = max(padding - len(self.name), 0) <NEW_LINE> printer.write("%s (%.1f seconds)\n" % (self.name + (" " * my_padding), self.time)) <NEW_LINE> <DEDENT> def to_xml(self): <NEW_LINE> <INDENT> test = ElementTree.Element("testcase") <NEW_LINE> match = re.search(r"(.+)\.([^.]+)$", self.name) <NEW_LINE> if match: <NEW_LINE> <INDENT> test.attrib["classname"] = match.group(1) <NEW_LINE> test.attrib["name"] = match.group(2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> test.attrib["name"] = self.name <NEW_LINE> <DEDENT> test.attrib["time"] = "%.1f" % self.time <NEW_LINE> if self.failed: <NEW_LINE> <INDENT> failure = ElementTree.SubElement(test, "failure") <NEW_LINE> failure.attrib["message"] = "Failed" <NEW_LINE> <DEDENT> elif self.skipped: <NEW_LINE> <INDENT> skipped = ElementTree.SubElement(test, "skipped") <NEW_LINE> skipped.attrib["message"] = "Skipped" <NEW_LINE> <DEDENT> system_out = ElementTree.SubElement(test, "system-out") <NEW_LINE> system_out.text = self.output <NEW_LINE> return test
Represents the result of a single test case
62599082796e427e53850281
class ModerationSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Moderation <NEW_LINE> fields = ['id', 'user', 'status', 'info_result'] <NEW_LINE> <DEDENT> def save(self, **kwargs): <NEW_LINE> <INDENT> announcement = self.validated_data['announcement'] <NEW_LINE> status = self.validated_data['status'] <NEW_LINE> if announcement.status != 'on_moderation': <NEW_LINE> <INDENT> raise serializers.ValidationError({'announcement': 'Announcement has bad status'}) <NEW_LINE> <DEDENT> if status == 'publish': <NEW_LINE> <INDENT> announcement.status = 'active' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> announcement.status = 'rejected' <NEW_LINE> <DEDENT> announcement.save() <NEW_LINE> return super().save(**kwargs)
Сериализатор для модерации
62599082aad79263cf4302c1
class tree_2_lineal(object): <NEW_LINE> <INDENT> def __init__(self, phl_obj_lst): <NEW_LINE> <INDENT> self.lst_obj = [] <NEW_LINE> self.deep_in_recurs(phl_obj_lst) <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> self.build_data() <NEW_LINE> return self.lst_dict <NEW_LINE> <DEDENT> def deep_in_recurs(self, phl_obj_lst): <NEW_LINE> <INDENT> for single_obj in phl_obj_lst: <NEW_LINE> <INDENT> if single_obj.name == "output": <NEW_LINE> <INDENT> print(" << output >> should be handled by DUI") <NEW_LINE> <DEDENT> elif single_obj.is_definition: <NEW_LINE> <INDENT> self.lst_obj.append(single_obj) <NEW_LINE> <DEDENT> elif single_obj.is_scope and single_obj.name != "output": <NEW_LINE> <INDENT> self.lst_obj.append(single_obj) <NEW_LINE> self.deep_in_recurs(single_obj.objects) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("\n", single_obj.name, "\n WARNING neither definition or scope\n") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def build_data(self): <NEW_LINE> <INDENT> self.lst_dict = [] <NEW_LINE> for single_obj in self.lst_obj: <NEW_LINE> <INDENT> if single_obj.is_definition: <NEW_LINE> <INDENT> param_info = { "name" :str(single_obj.name), "full_path" :str(single_obj.full_path()), "short_caption" :str(single_obj.short_caption), "help" :str(single_obj.help), "indent" :int(str(single_obj.full_path()).count(".")), "type" :None, "opt_lst" :None, "default" :None } <NEW_LINE> if single_obj.type.phil_type == "bool": <NEW_LINE> <INDENT> param_info["type"] = "bool" <NEW_LINE> param_info["opt_lst"] = ["True", "False", "Auto"] <NEW_LINE> if str(single_obj.extract()) == "True": <NEW_LINE> <INDENT> param_info["default"] = 0 <NEW_LINE> <DEDENT> elif str(single_obj.extract()) == "False": <NEW_LINE> <INDENT> param_info["default"] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> param_info["default"] = 2 <NEW_LINE> <DEDENT> <DEDENT> elif single_obj.type.phil_type == "choice": <NEW_LINE> <INDENT> param_info["type"] = "choice" <NEW_LINE> param_info["opt_lst"] = [] <NEW_LINE> for num, opt in enumerate(single_obj.words): <NEW_LINE> <INDENT> opt = str(opt) <NEW_LINE> if opt[0] == "*": <NEW_LINE> <INDENT> opt = opt[1:] <NEW_LINE> param_info["default"] = num <NEW_LINE> <DEDENT> param_info["opt_lst"].append(opt) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> param_info["type"] = "other(s)" <NEW_LINE> param_info["default"] = str(single_obj.extract()) <NEW_LINE> <DEDENT> <DEDENT> elif single_obj.is_scope: <NEW_LINE> <INDENT> param_info = { "name" :str(single_obj.name), "full_path" :str(single_obj.full_path()), "short_caption" :str(single_obj.short_caption), "help" :str(single_obj.help), "indent" :int(str(single_obj.full_path()).count(".")), "type" :"scope" } <NEW_LINE> <DEDENT> self.lst_dict.append(param_info)
Recursively navigates the Phil objects in a way that the final self.lst_obj is a lineal list without ramifications, then another list is created with the info about parameters
625990825fcc89381b266ee0
class TemplateError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, token): <NEW_LINE> <INDENT> if not isinstance(token, Token): <NEW_LINE> <INDENT> token = Token(token, 0) <NEW_LINE> <DEDENT> self.msg = msg <NEW_LINE> self.token = safe_native(token) <NEW_LINE> self.offset = getattr(token, "pos", 0) <NEW_LINE> self.filename = token.filename <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> inst = Exception.__new__(type(self)) <NEW_LINE> inst.__dict__ = self.__dict__.copy() <NEW_LINE> return inst <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return reconstruct_exc, (type(self), self.__dict__) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> text = "%s\n\n" % self.msg <NEW_LINE> text += " - String: \"%s\"" % self.token <NEW_LINE> if self.filename: <NEW_LINE> <INDENT> text += "\n" <NEW_LINE> text += " - Filename: %s" % self.filename <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> line, column = self.token.location <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text += "\n" <NEW_LINE> text += " - Location: (%d:%d)" % (line, column) <NEW_LINE> <DEDENT> return text <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return "%s('%s', '%s')" % ( self.__class__.__name__, self.msg, self.token ) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return object.__repr__(self)
An error raised by Chameleon. >>> from chameleon.tokenize import Token >>> token = Token('token') >>> message = 'message' Make sure the exceptions can be copied: >>> from copy import copy >>> copy(TemplateError(message, token)) TemplateError('message', 'token') And pickle/unpickled: >>> from pickle import dumps, loads >>> loads(dumps(TemplateError(message, token))) TemplateError('message', 'token')
6259908297e22403b383ca05
class BaseCache(object): <NEW_LINE> <INDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set(self, key, value, ttl=60): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def delete(self, key): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> pass
Abstract class to be used as a base class for other Cache classes.
62599082fff4ab517ebcf31d
class InformationAlgorithm(object): <NEW_LINE> <INDENT> INFO_PROVIDED = [] <NEW_LINE> def __init__(self, info=[], **kwargs): <NEW_LINE> <INDENT> super(InformationAlgorithm, self).__init__(**kwargs) <NEW_LINE> if not isinstance(info, (list, tuple)): <NEW_LINE> <INDENT> self.info = [info] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.info = list(info) <NEW_LINE> <DEDENT> self.info_ret = dict() <NEW_LINE> self.check_info_compatibility(self.info) <NEW_LINE> <DEDENT> def info_get(self, nfo=None): <NEW_LINE> <INDENT> if nfo is None: <NEW_LINE> <INDENT> return self.info_ret <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.info_ret[nfo] <NEW_LINE> <DEDENT> <DEDENT> def info_set(self, nfo, value): <NEW_LINE> <INDENT> self.info_ret[nfo] = value <NEW_LINE> <DEDENT> def info_provided(self, nfo): <NEW_LINE> <INDENT> return nfo in self.INFO_PROVIDED <NEW_LINE> <DEDENT> def info_requested(self, nfo): <NEW_LINE> <INDENT> return nfo in self.info <NEW_LINE> <DEDENT> def info_reset(self): <NEW_LINE> <INDENT> self.info_ret.clear() <NEW_LINE> <DEDENT> def info_copy(self): <NEW_LINE> <INDENT> return list(self.info) <NEW_LINE> <DEDENT> def check_info_compatibility(self, info): <NEW_LINE> <INDENT> for i in info: <NEW_LINE> <INDENT> if not self.info_provided(i): <NEW_LINE> <INDENT> raise ValueError("Requested information not provided.")
Algorithms that produce information about their run. Implementing classes should update the INFO_PROVIDED class variable with the information provided by the algorithm. Defauls to an empty list. ALL algorithms that inherit from InformationAlgorithm MUST add force_reset as a decorator to the run method. Fields ------ info_ret : Dictionary. The algorithm outputs are collected in this dictionary. info : List of utils.Info. The identifiers for the requested information outputs. The algorithms will store the requested outputs in self.info. INFO_PROVIDED : List of utils.Info. The allowed output identifiers. The implementing class should update this list with the provided/allowed outputs. Examples -------- >>> import parsimony.algorithms as algorithms >>> from parsimony.algorithms.utils import Info >>> from parsimony.functions.losses import LinearRegression >>> import numpy as np >>> np.random.seed(42) >>> gd = algorithms.gradient.GradientDescent(info=[Info.fvalue]) >>> gd.info_copy() ['fvalue'] >>> lr = LinearRegression(X=np.random.rand(10,15), y=np.random.rand(10,1)) >>> beta = gd.run(lr, np.random.rand(15, 1)) >>> fvalue = gd.info_get(Info.fvalue) >>> round(fvalue[0], 10) 0.068510926 >>> round(fvalue[-1], 15) 1.886e-12
625990823317a56b869bf2c7
class Affix(list): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def descend(self): <NEW_LINE> <INDENT> return self.append("") <NEW_LINE> <DEDENT> def ascend(self): <NEW_LINE> <INDENT> return self.pop() <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return "".join(self) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> from rdf.language import errors <NEW_LINE> raise ( {True: errors.MorphemeExchangeError( "Cannot Pre/Ap-pend a Suf/Pre-fix"), False: TypeError("Can only add strings to this list sub")}[ isinstance(other, basestring) ] ) <NEW_LINE> <DEDENT> __radd__ = __add__
The Affix is an abstract base class. It implements the: descend/asend methods for traversing the IFT It is callable: Given a key, it will do what morphemes do and make as new key per the RDF spec. Sub classes use operator overloads to do their thing
62599082ec188e330fdfa3b2
@attr.s(cmp=False, hash=True) <NEW_LINE> class MediaRange(object): <NEW_LINE> <INDENT> type = attr.ib(default=STAR) <NEW_LINE> subtype = attr.ib(default=STAR) <NEW_LINE> parameters = attr.ib(default=m()) <NEW_LINE> quality = attr.ib(default=1.0) <NEW_LINE> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return attr.astuple(self) == attr.astuple(other) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return not self == other <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> if self.quality < other.quality: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.quality > other.quality: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.type != other.type: <NEW_LINE> <INDENT> return self.type is STAR <NEW_LINE> <DEDENT> if self.subtype != other.subtype: <NEW_LINE> <INDENT> return self.subtype is STAR <NEW_LINE> <DEDENT> return viewkeys(self.parameters) < viewkeys(other.parameters)
A media range. Open ranges (e.g. ``text/*`` or ``*/*``\ ) are represented by :attr:`type` and / or :attr:`subtype` being ``None``\ .
62599082091ae35668706747
class DaosAgentManager(SubprocessManager): <NEW_LINE> <INDENT> def __init__(self, agent_command, manager="Orterun"): <NEW_LINE> <INDENT> super(DaosAgentManager, self).__init__(agent_command, manager) <NEW_LINE> env_vars = { "D_LOG_MASK": "DEBUG,RPC=ERR", "DD_MASK": "mgmt,io,md,epc,rebuild" } <NEW_LINE> self.manager.assign_environment_default(EnvironmentVariables(env_vars)) <NEW_LINE> <DEDENT> def _set_hosts(self, hosts, path, slots): <NEW_LINE> <INDENT> super(DaosAgentManager, self)._set_hosts(hosts, path, slots) <NEW_LINE> self.manager.job.pattern_count = len(self._hosts) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.log.info( "<AGENT> Starting daos_agent on %s with %s", self._hosts, self.manager.command) <NEW_LINE> self.manager.job.copy_certificates( get_log_file("daosCA/certs"), self._hosts) <NEW_LINE> super(DaosAgentManager, self).start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.log.info("<AGENT> Stopping agent %s command", self.manager.command) <NEW_LINE> messages = [] <NEW_LINE> try: <NEW_LINE> <INDENT> super(DaosAgentManager, self).stop() <NEW_LINE> <DEDENT> except CommandFailure as error: <NEW_LINE> <INDENT> messages.append( "Error stopping the {} subprocess: {}".format( self.manager.command, error)) <NEW_LINE> <DEDENT> self.kill() <NEW_LINE> if messages: <NEW_LINE> <INDENT> raise CommandFailure( "Failed to stop agents:\n {}".format("\n ".join(messages))) <NEW_LINE> <DEDENT> <DEDENT> def get_user_file(self): <NEW_LINE> <INDENT> return self.get_config_value("runtime_dir")
Manages the daos_agent execution on one or more hosts.
625990828a349b6b43687d64
class ContactCardView(BrowserView): <NEW_LINE> <INDENT> def __call__(self, **kw): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.params.update(kw) <NEW_LINE> return self.render() <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return self.index() <NEW_LINE> <DEDENT> def has_image(self): <NEW_LINE> <INDENT> context = aq_inner(self.context) <NEW_LINE> try: <NEW_LINE> <INDENT> lead_img = context.image <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> lead_img = None <NEW_LINE> <DEDENT> if lead_img is not None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def has_address_info(self): <NEW_LINE> <INDENT> context = aq_inner(self.context) <NEW_LINE> if context.address or context.city: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def has_position_info(self): <NEW_LINE> <INDENT> context = aq_inner(self.context) <NEW_LINE> if context.position or context.department: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def get_image_data(self, uuid): <NEW_LINE> <INDENT> tool = getUtility(IContactImagesTool) <NEW_LINE> return tool.create(uuid) <NEW_LINE> <DEDENT> def get_inquiry_form_link(self): <NEW_LINE> <INDENT> context = aq_inner(self.context) <NEW_LINE> assignment_context_uid = self.params.get('uuid', None) <NEW_LINE> if assignment_context_uid: <NEW_LINE> <INDENT> assignment_context = api.content.get(UID=assignment_context_uid) <NEW_LINE> uri = '{0}/@@inquiry-form/{1}'.format( assignment_context.absolute_url(), context.UID() ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> uri = '{0}/@@inquiry-form/{1}'.format( context.absolute_url(), context.UID() ) <NEW_LINE> <DEDENT> return uri
Card view for contact objects
625990834f6381625f19a233
class Forall(BeginStatement): <NEW_LINE> <INDENT> end_stmt_cls = EndForall <NEW_LINE> match = re.compile(r'forall\s*\(.*\)\Z', re.I).match <NEW_LINE> name = '' <NEW_LINE> def process_item(self): <NEW_LINE> <INDENT> self.specs = self.item.get_line()[6:].lstrip()[1:-1].strip() <NEW_LINE> return BeginStatement.process_item(self) <NEW_LINE> <DEDENT> def tostr(self): <NEW_LINE> <INDENT> return 'forall (%s)' % (self.specs) <NEW_LINE> <DEDENT> def get_classes(self): <NEW_LINE> <INDENT> return [GeneralAssignment, WhereStmt, WhereConstruct, ForallConstruct, ForallStmt]
[ <forall-construct-name> : ] FORALL <forall-header> [ <forall-body-construct> ]... <forall-body-construct> = <forall-assignment-stmt> | <where-stmt> | <where-construct> | <forall-construct> | <forall-stmt> <forall-header> = ( <forall-triplet-spec-list> [ , <scalar-mask-expr> ] ) <forall-triplet-spec> = <index-name> = <subscript> : <subscript> [ : <stride> ] <subscript|stride> = <scalar-int-expr> <forall-assignment-stmt> = <assignment-stmt> | <pointer-assignment-stmt>
625990837c178a314d78e96e
class FinnishLanguage: <NEW_LINE> <INDENT> def _message(self): <NEW_LINE> <INDENT> return 'Hei maailma!'
Implement english message.
625990833346ee7daa3383e6
class KerasCNNBuilder(Builder): <NEW_LINE> <INDENT> def __init__(self, name, learning_rate, num_dense, units=3, seed=42): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._learning_rate = learning_rate <NEW_LINE> self._num_dense = num_dense <NEW_LINE> self._units = units <NEW_LINE> self._seed = seed <NEW_LINE> <DEDENT> def build_subnetwork(self, features, logits_dimension, training, iteration_step, summary, previous_ensemble=None): <NEW_LINE> <INDENT> seed = self._seed <NEW_LINE> if previous_ensemble: <NEW_LINE> <INDENT> seed += len(previous_ensemble.weighted_subnetworks) <NEW_LINE> <DEDENT> images = list(features.values())[0] <NEW_LINE> images = tf.reshape(images, [-1, 2, 2, 1]) <NEW_LINE> kernel_initializer = tf_compat.v1.keras.initializers.he_normal(seed=seed) <NEW_LINE> x = images <NEW_LINE> x = tf.keras.layers.Conv2D( filters=3, kernel_size=1, padding="same", activation="relu", kernel_initializer=kernel_initializer)( x) <NEW_LINE> x = tf.keras.layers.MaxPool2D(pool_size=1, strides=1)(x) <NEW_LINE> x = tf.keras.layers.Flatten()(x) <NEW_LINE> for _ in range(self._num_dense): <NEW_LINE> <INDENT> x = tf_compat.v1.layers.Dense( units=self._units, activation="relu", kernel_initializer=kernel_initializer)( x) <NEW_LINE> <DEDENT> logits = tf.keras.layers.Dense( units=1, activation=None, kernel_initializer=kernel_initializer)( x) <NEW_LINE> complexity = tf.constant(1) <NEW_LINE> return Subnetwork( last_layer=x, logits=logits, complexity=complexity, shared={}) <NEW_LINE> <DEDENT> def build_subnetwork_train_op(self, subnetwork, loss, var_list, labels, iteration_step, summary, previous_ensemble=None): <NEW_LINE> <INDENT> optimizer = tf_compat.v1.train.GradientDescentOptimizer(self._learning_rate) <NEW_LINE> return optimizer.minimize(loss=loss, var_list=var_list) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name
Builds a CNN subnetwork for AdaNet.
625990834a966d76dd5f09ee
class ReviewDecline(CommandDescription, Review, ReviewChangeStateOptions): <NEW_LINE> <INDENT> cmd = 'decline' <NEW_LINE> args = 'api://reqid' <NEW_LINE> func = call(ReviewController.change_review_state) <NEW_LINE> func_defaults = {'method': 'decline'}
Decline a specific review. If no message is specified $EDITOR is opened. Example: osc review decline api://reqid [--message MESSAGE] --user <user>
62599083aad79263cf4302c3
class MonoWorker(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pool = ThreadPoolExecutor(max_workers=1) <NEW_LINE> self.futures = deque([], 2) <NEW_LINE> <DEDENT> def submit(self, func, *args, **kwargs): <NEW_LINE> <INDENT> futures = self.futures <NEW_LINE> if len(futures) == futures.maxlen: <NEW_LINE> <INDENT> running = futures.popleft() <NEW_LINE> if not running.done(): <NEW_LINE> <INDENT> if len(futures): <NEW_LINE> <INDENT> waiting = futures.pop() <NEW_LINE> waiting.cancel() <NEW_LINE> <DEDENT> futures.appendleft(running) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> waiting = self.pool.submit(func, *args, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> tqdm_auto.write(str(e)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> futures.append(waiting) <NEW_LINE> return waiting
Supports one running task and one waiting task. The waiting task is the most recent submitted (others are discarded).
625990833617ad0b5ee07c58
class NestedListsI32x2(object): <NEW_LINE> <INDENT> def __init__(self, integerlist=None,): <NEW_LINE> <INDENT> self.integerlist = integerlist <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.integerlist = [] <NEW_LINE> (_etype150, _size147) = iprot.readListBegin() <NEW_LINE> for _i151 in range(_size147): <NEW_LINE> <INDENT> _elem152 = [] <NEW_LINE> (_etype156, _size153) = iprot.readListBegin() <NEW_LINE> for _i157 in range(_size153): <NEW_LINE> <INDENT> _elem158 = iprot.readI32() <NEW_LINE> _elem152.append(_elem158) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> self.integerlist.append(_elem152) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('NestedListsI32x2') <NEW_LINE> if self.integerlist is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('integerlist', TType.LIST, 1) <NEW_LINE> oprot.writeListBegin(TType.LIST, len(self.integerlist)) <NEW_LINE> for iter159 in self.integerlist: <NEW_LINE> <INDENT> oprot.writeListBegin(TType.I32, len(iter159)) <NEW_LINE> for iter160 in iter159: <NEW_LINE> <INDENT> oprot.writeI32(iter160) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - integerlist
62599083091ae35668706749
class Comment(object): <NEW_LINE> <INDENT> def __init__(self, tid, channel_id, cid, add_datetime, publish_datetime, ip_address, location_country, location_region, location_city, author_id, author_name, content, reply_author_id, read_count, like_count, reply_count, dislike_count): <NEW_LINE> <INDENT> self.tid = tid <NEW_LINE> self.channel_id = channel_id <NEW_LINE> self.cid = cid <NEW_LINE> self.add_datetime = add_datetime <NEW_LINE> self.publish_datetime = publish_datetime <NEW_LINE> self.ip_address = ip_address <NEW_LINE> self.location_country = location_country <NEW_LINE> self.location_region = location_region <NEW_LINE> self.location_city = location_city <NEW_LINE> self.author_id = author_id <NEW_LINE> self.author_name = author_name <NEW_LINE> self.content = content <NEW_LINE> self.reply_author_id = reply_author_id <NEW_LINE> self.read_count = read_count <NEW_LINE> self.like_count = like_count <NEW_LINE> self.reply_count = reply_count <NEW_LINE> self.dislike_count = dislike_count
classdocs
6259908397e22403b383ca08
class Hetero(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> if type(data) != type(""): <NEW_LINE> <INDENT> raise CrystalError('Hetero data must be an alphameric string') <NEW_LINE> <DEDENT> if data.isalnum() == 0: <NEW_LINE> <INDENT> raise CrystalError('Hetero data must be an alphameric string') <NEW_LINE> <DEDENT> if len(data) > 3: <NEW_LINE> <INDENT> raise CrystalError('Hetero data may contain up to 3 characters') <NEW_LINE> <DEDENT> if len(data) < 1: <NEW_LINE> <INDENT> raise CrystalError('Hetero data must not be empty') <NEW_LINE> <DEDENT> self.data = data[:].lower() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.data == other.data <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s" % self.data <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s" % self.data <NEW_LINE> <DEDENT> def __len__(self): return len(self.data)
This class exists to support the PDB hetero codes. Supports only the 3 alphameric code. The annotation is available from http://alpha2.bmc.uu.se/hicup/
625990837c178a314d78e96f
class Attachment(db.Model): <NEW_LINE> <INDENT> __tablename__ = "attachment" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> filename_original = db.Column(db.String) <NEW_LINE> filename = db.Column(db.String) <NEW_LINE> message = db.relationship("Message", uselist=False, back_populates="attachment") <NEW_LINE> def __init__(self, url=None, stream=None): <NEW_LINE> <INDENT> assert url is not None or stream is not None <NEW_LINE> self.filename = str(uuid.uuid4()) <NEW_LINE> path = os.path.join(current_app.config.get('MMS_STORAGE'), self.filename) <NEW_LINE> if url is not None: <NEW_LINE> <INDENT> current_app.logger.debug("Downloading %s to %s", url, path) <NEW_LINE> r = requests.get(url, stream=True) <NEW_LINE> stream = r.raw <NEW_LINE> <DEDENT> with open(path, 'wb') as f: <NEW_LINE> <INDENT> copyfileobj(stream, f) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def static_path(self): <NEW_LINE> <INDENT> return url_for('static', filename="mms-files/{}".format(self.filename)) <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for column in self.__table__.columns: <NEW_LINE> <INDENT> d[column.name] = str(getattr(self, column.name)) <NEW_LINE> <DEDENT> return d
An attachment to an MMS.
62599083adb09d7d5dc0c063
class XMLException(Exception): <NEW_LINE> <INDENT> pass
Class for all XML related errors that can occur in this module.
625990832c8b7c6e89bd52f0
class RemoteMonitor(Callback): <NEW_LINE> <INDENT> def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None): <NEW_LINE> <INDENT> super(RemoteMonitor, self).__init__() <NEW_LINE> self.root = root <NEW_LINE> self.path = path <NEW_LINE> self.field = field <NEW_LINE> self.headers = headers <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch, logs=None): <NEW_LINE> <INDENT> if requests is None: <NEW_LINE> <INDENT> raise ImportError('RemoteMonitor requires ' 'the `requests` library.') <NEW_LINE> <DEDENT> logs = logs or {} <NEW_LINE> send = {} <NEW_LINE> send['epoch'] = epoch <NEW_LINE> for k, v in logs.items(): <NEW_LINE> <INDENT> if isinstance(v, (np.ndarray, np.generic)): <NEW_LINE> <INDENT> send[k] = v.item() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> send[k] = v <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> requests.post(self.root + self.path, {self.field: json.dumps(send)}, headers=self.headers) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException: <NEW_LINE> <INDENT> warnings.warn('Warning: could not reach RemoteMonitor ' 'root server at ' + str(self.root))
Callback used to stream events to a server. Requires the `requests` library. Events are sent to `root + '/publish/epoch/end/'` by default. Calls are HTTP POST, with a `data` argument which is a JSON-encoded dictionary of event data. # Arguments root: String; root url of the target server. path: String; path relative to `root` to which the events will be sent. field: String; JSON field under which the data will be stored. headers: Dictionary; optional custom HTTP headers.
625990834a966d76dd5f09f0
class TimeScapeParser(object): <NEW_LINE> <INDENT> def __init__(self, pdb, loc, traj_id, dcd=None, traj=None, uniqueid=False): <NEW_LINE> <INDENT> self.pdb = pdb <NEW_LINE> if dcd is None: <NEW_LINE> <INDENT> self.dcd = os.path.join(loc, traj_id + '.dcd') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dcd = dcd <NEW_LINE> <DEDENT> self.out = loc <NEW_LINE> self.traj = traj <NEW_LINE> self.traj_id = traj_id <NEW_LINE> self.basins = [] <NEW_LINE> self.unique_basin_id = uniqueid <NEW_LINE> <DEDENT> def load_traj(self): <NEW_LINE> <INDENT> self.traj = md.load(self.dcd, top=self.pdb) <NEW_LINE> <DEDENT> def load_basins(self, frame_ratio=1, force_load=False): <NEW_LINE> <INDENT> if self.traj is None and force_load: <NEW_LINE> <INDENT> self.load_traj() <NEW_LINE> <DEDENT> window_list = self.get_windows() <NEW_LINE> minima_list = [i*frame_ratio for i in self.get_minima()] <NEW_LINE> basin_index = 0 <NEW_LINE> last = None <NEW_LINE> while basin_index < len(minima_list): <NEW_LINE> <INDENT> window = window_list[basin_index] <NEW_LINE> minima = minima_list[basin_index] <NEW_LINE> if self.unique_basin_id: <NEW_LINE> <INDENT> basin_id = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> basin_id = str(self.traj_id) + '_' + str(basin_index) <NEW_LINE> <DEDENT> basin = Basin(self.traj_id, window, minima, traj=self.traj, uid=basin_id) <NEW_LINE> if last is not None: <NEW_LINE> <INDENT> basin.prev = last.id <NEW_LINE> self.basins[-1].next = basin.id <NEW_LINE> <DEDENT> self.basins.append(basin) <NEW_LINE> last = basin <NEW_LINE> basin_index += 1 <NEW_LINE> <DEDENT> return self.basins <NEW_LINE> <DEDENT> def correlation_matrix(self): <NEW_LINE> <INDENT> protein = self.traj.atom_slice(self.traj.top.select('protein')) <NEW_LINE> nframes, nresid = protein.n_frames, protein.n_residues <NEW_LINE> fname = self.out + '_events.log' <NEW_LINE> return TimeScape.correlation_matrix(fname, nresid, nframes) <NEW_LINE> <DEDENT> def get_minima(self): <NEW_LINE> <INDENT> minima_file = self.out + '_minima.log' <NEW_LINE> return TimeScape.read_log(minima_file) <NEW_LINE> <DEDENT> def get_windows(self): <NEW_LINE> <INDENT> trans_file = self.out + '_transitions.log' <NEW_LINE> return TimeScape.windows(trans_file)
Class to parse and manage TimeScape Output. Use of this class assumes that the TimeScape program has already run. Ergo the Trajectory passed in and processed is the FULL underlying trajectory -- a frame_rate is provided to the load_basin program to convert indexing from a pre-processed file (found in output) to a full tranjectory (for follow on manipulation)
62599083aad79263cf4302c6
class CaracterizacionPoliticaView(LoginRequeridoPerAuth, TemplateView): <NEW_LINE> <INDENT> template_name = "caracterizacion.politica.html" <NEW_LINE> group_required = [u"Administradores", u"Voceros", u"Integrantes"]
! Clase que muestra el templates de la caracterización política de la comunidad @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> @date 30-005-2017 @version 1.0.0
62599083d8ef3951e32c8be4
class TextureInfo: <NEW_LINE> <INDENT> def __init__(self, tex, f=1, sRect=None): <NEW_LINE> <INDENT> self.texture = tex <NEW_LINE> self.frames = f <NEW_LINE> self.current_frame = 0 <NEW_LINE> self.src_rect = sRect <NEW_LINE> self.frame_1 = sRect.x <NEW_LINE> self.anim_finished_event = Event() <NEW_LINE> <DEDENT> def get_anim_event(self): <NEW_LINE> <INDENT> return self.anim_finished_event <NEW_LINE> <DEDENT> def get_src_rect(self): <NEW_LINE> <INDENT> pos_x = self.frame_1+(self.current_frame*self.src_rect.width) <NEW_LINE> pos_y = self.src_rect.y <NEW_LINE> width = self.src_rect.width <NEW_LINE> height = self.src_rect.height <NEW_LINE> return Rect(pos_x, pos_y, width, height) <NEW_LINE> <DEDENT> def reset_anim(self): <NEW_LINE> <INDENT> self.current_frame = 0 <NEW_LINE> <DEDENT> def next_frame(self): <NEW_LINE> <INDENT> if self.current_frame+1 == self.frames: <NEW_LINE> <INDENT> self.current_frame = 0 <NEW_LINE> self.anim_finished_event() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.current_frame += 1 <NEW_LINE> <DEDENT> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self.texture
Class Describing a Texture, it's source rectangle and animation frames.
625990838a349b6b43687d68
class AWSHelper(object): <NEW_LINE> <INDENT> def __init__(self, aws_profile=None, logger=False, verbose=False): <NEW_LINE> <INDENT> self.aws_profile = aws_profile <NEW_LINE> self.print_func = lambda x: print(x, flush=True) <NEW_LINE> if logger: <NEW_LINE> <INDENT> self.print_func = logger.info <NEW_LINE> <DEDENT> self.session = self._create_aws_session() <NEW_LINE> if not logger and not verbose: <NEW_LINE> <INDENT> self.print_func = lambda x: None <NEW_LINE> <DEDENT> self.verbose = verbose <NEW_LINE> <DEDENT> def _create_aws_session(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.aws_profile: <NEW_LINE> <INDENT> session = boto3.session.Session(profile_name=self.aws_profile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> session = boto3.session.Session() <NEW_LINE> <DEDENT> <DEDENT> except botocore.exceptions.ProfileNotFound: <NEW_LINE> <INDENT> self.print_func('Please supply a valid AWS profile name.') <NEW_LINE> raise <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.print_func(traceback.format_exc()) <NEW_LINE> self.print_func('Exiting. Unable to establish AWS session with the following profile name: {}'.format(self.aws_profile)) <NEW_LINE> raise <NEW_LINE> <DEDENT> return session
Helper class for connecting to AWS.
62599083a05bb46b3848bead
class NetworkRuleSetListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[NetworkRuleSet]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["NetworkRuleSet"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(NetworkRuleSetListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
The response of the List NetworkRuleSet operation. :param value: Result of the List NetworkRuleSet operation. :type value: list[~azure.mgmt.servicebus.v2021_01_01_preview.models.NetworkRuleSet] :param next_link: Link to the next set of results. Not empty if Value contains incomplete list of NetworkRuleSet. :type next_link: str
6259908355399d3f0562801f
class WrongDimensionError(MrFilterError): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(WrongDimensionError, self).__init__("Unexpected error: the output FITS file should contain a 2D array.")
Exception raised when trying to save a FITS with more than 3 dimensions or less than 2 dimensions. Attributes: message -- explanation of the error
6259908376e4537e8c3f108b