code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class AptRemoteViewSet(RemoteViewSet): <NEW_LINE> <INDENT> endpoint_name = "apt" <NEW_LINE> queryset = models.AptRemote.objects.all() <NEW_LINE> serializer_class = serializers.AptRemoteSerializer | An AptRemote represents an external APT repository content source.
It contains the location of the upstream APT repository, as well as the user options that are
applied when using the remote to synchronize the upstream repository to Pulp. | 62599079be7bc26dc9252b3b |
class SearchView(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> queryset = Area.objects.all() <NEW_LINE> point_string = request.query_params.get('point', None) <NEW_LINE> if point_string: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (x, y) = (float(n) for n in point_string.split(',')) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ParseError('Invalid geometry string supplied for parameter {0}'.format(self.point_param)) <NEW_LINE> <DEDENT> p = Point(x, y) <NEW_LINE> queryset = queryset.filter(Q(**{'polygon__dwithin': (p, 0)})) <NEW_LINE> <DEDENT> service_string = request.query_params.get('service', None) <NEW_LINE> if point_string: <NEW_LINE> <INDENT> queryset = queryset.filter(service_id=service_string) <NEW_LINE> <DEDENT> serializer = SearchSerializer(queryset, many=True) <NEW_LINE> return Response(serializer.data) | Поиск по услуге и точке на карте
Формат поисковой строки: ?service=1&point=12,20
(id услуги и широта,долгота точки в которой ищем поставщиков) | 6259907991f36d47f2231b75 |
class DBManager: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.path = os.environ.get("DATABASE_URL") <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.conn = psycopg2.connect(self.path, sslmode="prefer") <NEW_LINE> self.cur = self.conn.cursor() <NEW_LINE> return self.cur <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.conn.commit() <NEW_LINE> self.conn.close() | Контекстный менеджер, который открывает, закрывает соединение с бд, коммитит изменения | 625990793317a56b869bf22c |
class SlavedIdTracker(AbstractStreamIdTracker): <NEW_LINE> <INDENT> def __init__( self, db_conn: LoggingDatabaseConnection, table: str, column: str, extra_tables: Optional[List[Tuple[str, str]]] = None, step: int = 1, ): <NEW_LINE> <INDENT> self.step = step <NEW_LINE> self._current = _load_current_id(db_conn, table, column, step) <NEW_LINE> if extra_tables: <NEW_LINE> <INDENT> for table, column in extra_tables: <NEW_LINE> <INDENT> self.advance(None, _load_current_id(db_conn, table, column)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def advance(self, instance_name: Optional[str], new_id: int) -> None: <NEW_LINE> <INDENT> self._current = (max if self.step > 0 else min)(self._current, new_id) <NEW_LINE> <DEDENT> def get_current_token(self) -> int: <NEW_LINE> <INDENT> return self._current <NEW_LINE> <DEDENT> def get_current_token_for_writer(self, instance_name: str) -> int: <NEW_LINE> <INDENT> return self.get_current_token() | Tracks the "current" stream ID of a stream with a single writer.
See `AbstractStreamIdTracker` for more details.
Note that this class does not work correctly when there are multiple
writers. | 6259907932920d7e50bc7a15 |
class ObjectWithSlugMixin: <NEW_LINE> <INDENT> pass | This class is obsolete but required because referenced in migrations. | 6259907901c39578d7f1441b |
class Rates(BaseModel): <NEW_LINE> <INDENT> HKD: confloat(gt=0) = None <NEW_LINE> ISK: confloat(gt=0) = None <NEW_LINE> PHP: confloat(gt=0) = None <NEW_LINE> DKK: confloat(gt=0) = None <NEW_LINE> HUF: confloat(gt=0) = None <NEW_LINE> CZK: confloat(gt=0) = None <NEW_LINE> GBP: confloat(gt=0) = None <NEW_LINE> RON: confloat(gt=0) = None <NEW_LINE> SEK: confloat(gt=0) = None <NEW_LINE> IDR: confloat(gt=0) = None <NEW_LINE> INR: confloat(gt=0) = None <NEW_LINE> BRL: confloat(gt=0) = None <NEW_LINE> RUB: confloat(gt=0) = None <NEW_LINE> HRK: confloat(gt=0) = None <NEW_LINE> JPY: confloat(gt=0) = None <NEW_LINE> THB: confloat(gt=0) = None <NEW_LINE> CHF: confloat(gt=0) = None <NEW_LINE> EUR: confloat(gt=0) = None <NEW_LINE> MYR: confloat(gt=0) = None <NEW_LINE> BGN: confloat(gt=0) = None <NEW_LINE> TRY: confloat(gt=0) = None <NEW_LINE> CNY: confloat(gt=0) = None <NEW_LINE> NOK: confloat(gt=0) = None <NEW_LINE> NZD: confloat(gt=0) = None <NEW_LINE> ZAR: confloat(gt=0) = None <NEW_LINE> USD: confloat(gt=0) = None <NEW_LINE> MXN: confloat(gt=0) = None <NEW_LINE> SGD: confloat(gt=0) = None <NEW_LINE> AUD: confloat(gt=0) = None <NEW_LINE> ILS: confloat(gt=0) = None <NEW_LINE> KRW: confloat(gt=0) = None <NEW_LINE> PLN: confloat(gt=0) = None | Pydantic model to store conversion rates in
| 62599079a05bb46b3848be10 |
class cloudapi_disks(j.tools.code.classGetBase()): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> self._te={} <NEW_LINE> self.actorname="disks" <NEW_LINE> self.appname="cloudapi" <NEW_LINE> <DEDENT> def create(self, accountId, locationId, name, description, iops, size=10, type='B', ssdSize=0, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError ("not implemented method create") <NEW_LINE> <DEDENT> def delete(self, diskId, detach, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError ("not implemented method delete") <NEW_LINE> <DEDENT> def get(self, diskId, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError ("not implemented method get") <NEW_LINE> <DEDENT> def limitIO(self, diskId, iops, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError ("not implemented method limitIO") <NEW_LINE> <DEDENT> def list(self, accountId, type, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError ("not implemented method list") | API Actor api, this actor is the final api a enduser uses to manage his resources | 625990794428ac0f6e659efd |
class SecondModule(object): <NEW_LINE> <INDENT> def __init__(self, name, age): <NEW_LINE> <INDENT> self._logger = logging.getLogger(__name__) <NEW_LINE> self._name = name <NEW_LINE> if not isinstance(age, int): <NEW_LINE> <INDENT> raise TypeError('age must be an integer') <NEW_LINE> <DEDENT> self._age = age <NEW_LINE> <DEDENT> def print_name(self): <NEW_LINE> <INDENT> self._logger.info(self._name) <NEW_LINE> <DEDENT> def print_year_of_birth(self): <NEW_LINE> <INDENT> year = datetime.datetime.now() <NEW_LINE> self._logger.info('year of birth: %s', year.year - self._age) <NEW_LINE> <DEDENT> def print_all(self): <NEW_LINE> <INDENT> self.print_name() <NEW_LINE> self.print_year_of_birth() <NEW_LINE> <DEDENT> def use_other_modules_sum(self, first_value, second_value): <NEW_LINE> <INDENT> result = first_module.basic_sum(first_value, second_value) <NEW_LINE> self._logger.debug('the sum result is %d', result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def use_other_modules_division(self, first_value, second_value): <NEW_LINE> <INDENT> result = utproject.first_module.basic_division(first_value, second_value) <NEW_LINE> self._logger.debug('the division result is %d', result) <NEW_LINE> return result | Python basic class | 62599079009cb60464d02f0b |
class Function(Element): <NEW_LINE> <INDENT> def stretch(self, *stretches): <NEW_LINE> <INDENT> return stretch(self, *stretches) <NEW_LINE> <DEDENT> def shift(self, *amounts): <NEW_LINE> <INDENT> return shift(self, *amounts) <NEW_LINE> <DEDENT> def select(self, *dims): <NEW_LINE> <INDENT> return select(self, *dims) <NEW_LINE> <DEDENT> def transform(self, *fs): <NEW_LINE> <INDENT> return transform(self, *fs) <NEW_LINE> <DEDENT> def diff(self, *derivs): <NEW_LINE> <INDENT> return diff(self, *derivs) <NEW_LINE> <DEDENT> def __reversed__(self): <NEW_LINE> <INDENT> return reverse(self) | A elements. | 625990794f88993c371f1208 |
class ListParser(Parser): <NEW_LINE> <INDENT> def __init__(self, grammar, source): <NEW_LINE> <INDENT> super(ListParser, self).__init__(grammar, source) <NEW_LINE> self._result = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def result(self): <NEW_LINE> <INDENT> return self._result <NEW_LINE> <DEDENT> def operate(self, operation, token): <NEW_LINE> <INDENT> if operation == 'add': <NEW_LINE> <INDENT> number = int(''.join(self._stacks[''])) <NEW_LINE> self._result.append(number) <NEW_LINE> <DEDENT> elif operation == 'save': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('The "{}" is an invalid operation!'.format(operation)) <NEW_LINE> <DEDENT> <DEDENT> def show_error(self, message, token): <NEW_LINE> <INDENT> raise ValueError(message) | Parse the input text and print the words | 625990795fcc89381b266e41 |
class SearchedContent(object): <NEW_LINE> <INDENT> def __init__( self, content_namespace: str, content_id: int, label: str, slug: str, status: str, content_type: str, workspace: SearchedDigestWorkspace, path: List[SearchedDigestContent], comments: List[SearchedDigestComment], comment_count: int, author: SearchedDigestUser, last_modifier: SearchedDigestUser, sub_content_types: List[str], is_archived: bool, is_deleted: bool, is_editable: bool, show_in_ui: bool, file_extension: str, filename: str, modified: datetime, created: datetime, score: float, current_revision_id: int, current_revision_type: str, workspace_id: int, active_shares: int, content_size: int, tags: Optional[List[str]] = None, tag_count: int = 0, parent_id: Optional[int] = None, ) -> None: <NEW_LINE> <INDENT> self.current_revision_id = current_revision_id <NEW_LINE> self.current_revision_type = current_revision_type <NEW_LINE> self.content_namespace = content_namespace <NEW_LINE> self.content_id = content_id <NEW_LINE> self.label = label <NEW_LINE> self.slug = slug <NEW_LINE> self.status = status <NEW_LINE> self.content_type = content_type <NEW_LINE> self.workspace = workspace <NEW_LINE> self.parent_id = parent_id <NEW_LINE> self.workspace_id = workspace_id <NEW_LINE> self.path = path <NEW_LINE> self.comments = comments <NEW_LINE> self.comment_count = comment_count <NEW_LINE> self.author = author <NEW_LINE> self.last_modifier = last_modifier <NEW_LINE> self.sub_content_types = sub_content_types <NEW_LINE> self.is_archived = is_archived <NEW_LINE> self.is_deleted = is_deleted <NEW_LINE> self.is_editable = is_editable <NEW_LINE> self.show_in_ui = show_in_ui <NEW_LINE> self.file_extension = file_extension <NEW_LINE> self.filename = filename <NEW_LINE> self.modified = modified <NEW_LINE> self.created = created <NEW_LINE> self.score = score <NEW_LINE> self.active_shares = active_shares <NEW_LINE> self.content_size = content_size <NEW_LINE> self.tags = tags or [] <NEW_LINE> self.tag_count = tag_count | Content-Like object return by LibSearch.
This class does not contain any logic, it's just needed to
store data. | 62599079dc8b845886d54f88 |
class PyqueryMiddleware: <NEW_LINE> <INDENT> def process_response(self, request, response, spider): <NEW_LINE> <INDENT> response.dom = PyQuery(response.text).make_links_absolute( 'https://www.ptt.cc/bbs/') <NEW_LINE> return response | Inject pyquery object into Scrapy `response`. | 625990797cff6e4e811b740d |
class imageos(object): <NEW_LINE> <INDENT> creds = get_keystone_creds() <NEW_LINE> keystone = ksclient.Client(**creds) <NEW_LINE> creds1 = get_nova_creds() <NEW_LINE> nova = nvclient.Client(**creds1) <NEW_LINE> def add(self,x,y): <NEW_LINE> <INDENT> return x+y <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_image(cls,name): <NEW_LINE> <INDENT> glance_endpoint = cls.keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL') <NEW_LINE> glance = glanceclient.Client('1', endpoint=glance_endpoint, token=cls.keystone.auth_token) <NEW_LINE> with open('/home/cloud/Downloads/precise-server-cloudimg-amd64-disk1.img', 'rb') as fimage: <NEW_LINE> <INDENT> image = glance.images.create(name=name, is_public=True, disk_format="qcow2", container_format="bare", data=fimage) <NEW_LINE> return image <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def delete_image(cls,i): <NEW_LINE> <INDENT> im = cls.nova.images.find(name=i) <NEW_LINE> im.delete() <NEW_LINE> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_image_list(cls): <NEW_LINE> <INDENT> images = cls.nova.images.list(detailed=True) <NEW_LINE> image_list = {} <NEW_LINE> for v in images: <NEW_LINE> <INDENT> image = {} <NEW_LINE> image["id"] = v.id <NEW_LINE> image["name"] = v.name <NEW_LINE> image["status"] = v.status <NEW_LINE> image_list[v.name] = image <NEW_LINE> <DEDENT> return image_list | docstring for imageos | 625990799c8ee82313040e6e |
class GetMessagesViews(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["peer", "id", "increment"] <NEW_LINE> ID = 0x5784d3e1 <NEW_LINE> QUALNAME = "functions.messages.GetMessagesViews" <NEW_LINE> def __init__(self, *, peer: "raw.base.InputPeer", id: List[int], increment: bool) -> None: <NEW_LINE> <INDENT> self.peer = peer <NEW_LINE> self.id = id <NEW_LINE> self.increment = increment <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "GetMessagesViews": <NEW_LINE> <INDENT> peer = TLObject.read(data) <NEW_LINE> id = TLObject.read(data, Int) <NEW_LINE> increment = Bool.read(data) <NEW_LINE> return GetMessagesViews(peer=peer, id=id, increment=increment) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> data.write(self.peer.write()) <NEW_LINE> data.write(Vector(self.id, Int)) <NEW_LINE> data.write(Bool(self.increment)) <NEW_LINE> return data.getvalue() | Telegram API method.
Details:
- Layer: ``122``
- ID: ``0x5784d3e1``
Parameters:
peer: :obj:`InputPeer <pyrogram.raw.base.InputPeer>`
id: List of ``int`` ``32-bit``
increment: ``bool``
Returns:
:obj:`messages.MessageViews <pyrogram.raw.base.messages.MessageViews>` | 62599079283ffb24f3cf526e |
@implementer(ILocalRoleProvider) <NEW_LINE> @adapter(IFactoryTempFolder) <NEW_LINE> class FactoryTempFolderProvider(object): <NEW_LINE> <INDENT> def __init__(self, obj): <NEW_LINE> <INDENT> self.folder = obj <NEW_LINE> <DEDENT> def getRoles(self, principal_id): <NEW_LINE> <INDENT> uf = aq_inner(getToolByName(self.folder, 'acl_users')) <NEW_LINE> user = aq_inner(uf.getUserById(principal_id, default=None)) <NEW_LINE> source = aq_parent(aq_parent(self.folder)) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> return user.getRolesInContext(source) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> def getAllRoles(self): <NEW_LINE> <INDENT> return {} | A simple local role provider which just gathers the roles from
the desired context::
>>> from zope.component import provideAdapter
>>> from zope.interface import Interface, implementer, directlyProvides
>>> from borg.localrole.workspace import WorkspaceLocalRoleManager
>>> rm = WorkspaceLocalRoleManager('rm', 'A Role Manager')
>>> from Acquisition import Implicit
>>> @implementer(Interface)
... class DummyObject(Implicit):
... pass
>>> root = DummyObject()
Let's construct a hierarchy similar to the way portal factory is used::
root --> folder -------|
|------------> PortalFactory --> TempFolder --> NewObject
>>> fold = DummyObject().__of__(root)
>>> factory = DummyObject().__of__(root)
>>> wrapped_factory = factory.__of__(fold)
>>> temp = DummyObject().__of__(wrapped_factory)
>>> newob = DummyObject().__of__(temp)
>>> from borg.localrole.tests import SimpleLocalRoleProvider
>>> from borg.localrole.tests import DummyUser
>>> user1 = DummyUser('bogus_user1')
To test our adapter we need an acl_users, and our user needs a
getRolesInContext method::
>>> class FakeUF(object):
... def getUserById(self, userid, default=None):
... if userid == user1.getId():
... return user1
... return None
>>> root.acl_users = FakeUF()
>>> def getRolesInContext(user, context):
... return rm.getRolesInContext(user, context)
>>> from types import MethodType
>>> user1.getRolesInContext = MethodType(getRolesInContext, user1)
We add special interface to our Folder which allows us to provide
some local roles, these roles will be inherited by any contained
objects but not by our 'newob' because though the folder is its
acquisition chain it is not contained by it::
>>> class ISpecialInterface(Interface):
... pass
>>> directlyProvides(fold, ISpecialInterface)
>>> provideAdapter(
... SimpleLocalRoleProvider,
... adapts=(ISpecialInterface,)
... )
>>> rm.getRolesInContext(user1, fold)
['Foo']
>>> contained = DummyObject().__of__(fold)
>>> rm.getRolesInContext(user1, contained)
['Foo']
>>> rm.getRolesInContext(user1, newob)
[]
Now we mark our TempFolder, and check that roles are now inherited
from the intended location ('fold')::
>>> directlyProvides(temp, IFactoryTempFolder)
>>> provideAdapter(FactoryTempFolderProvider)
>>> rm.getRolesInContext(user1, newob)
['Foo']
The getAllRoles method always returns an empty dict, becuas it is
only used for thing which are irrelevant for temporary objects::
>>> rm.getAllLocalRolesInContext(newob)
{} | 62599079627d3e7fe0e08855 |
class Tag(models.Model): <NEW_LINE> <INDENT> name = models.CharField('标签名', max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '标签' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | 标签tag | 625990792c8b7c6e89bd51b9 |
class GraphLRUEdgeCache: <NEW_LINE> <INDENT> class Node: <NEW_LINE> <INDENT> def __init__(self, key, val): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.val = val <NEW_LINE> self.prev = None <NEW_LINE> self.next = None <NEW_LINE> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.cache = {} <NEW_LINE> self.head = self.Node(None, None) <NEW_LINE> self.tail = self.Node(None, None) <NEW_LINE> self.head.next = self.tail <NEW_LINE> self.tail.next = self.head <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> if key not in self.cache: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current = self.cache[key] <NEW_LINE> current.prev.next = current.next <NEW_LINE> current.next.prev = current.prev <NEW_LINE> self.move_to_tail(current) <NEW_LINE> return current.val <NEW_LINE> <DEDENT> <DEDENT> def set(self, key, value): <NEW_LINE> <INDENT> if None != self.get(key): <NEW_LINE> <INDENT> self.cache.get(key).val = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current = self.Node(key, value) <NEW_LINE> if 0 == len(self.cache): <NEW_LINE> <INDENT> self.head.next = current <NEW_LINE> current.prev = self.head <NEW_LINE> current.next = self.tail <NEW_LINE> self.tail.prev = current <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.move_to_tail(current) <NEW_LINE> <DEDENT> self.cache[key] = current <NEW_LINE> <DEDENT> <DEDENT> def move_to_tail(self, current): <NEW_LINE> <INDENT> self.tail.prev.next = current <NEW_LINE> current.prev = self.tail.prev <NEW_LINE> current.next = self.tail <NEW_LINE> self.tail.prev = current <NEW_LINE> <DEDENT> def set_hashtag_pair_list(self, hashtag_pair_list, time): <NEW_LINE> <INDENT> for hashtag_pair in hashtag_pair_list: <NEW_LINE> <INDENT> self.set(hashtag_pair, time) <NEW_LINE> <DEDENT> return self.remove_old_hashtag_pair(time) <NEW_LINE> <DEDENT> def remove_old_hashtag_pair(self, current_time): <NEW_LINE> <INDENT> remove_list = [] <NEW_LINE> compare_time = current_time - timedelta(seconds = 60) <NEW_LINE> current = self.head.next <NEW_LINE> while (current != self.tail and current.val < compare_time): <NEW_LINE> <INDENT> self.head.next = current.next <NEW_LINE> current.next.prev = self.head <NEW_LINE> remove_list.append(current.key) <NEW_LINE> del self.cache[current.key] <NEW_LINE> current = current.next <NEW_LINE> <DEDENT> return remove_list <NEW_LINE> <DEDENT> def list_to_string(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> if 0 != len(self.cache): <NEW_LINE> <INDENT> current = self.head.next <NEW_LINE> while current != self.tail: <NEW_LINE> <INDENT> result += str(current.key) + ', (' + str(current.val) + ')\n' <NEW_LINE> current = current.next <NEW_LINE> <DEDENT> <DEDENT> return result | Store graph edges with LRU (least recently used) algorithm.
Implement LRU algorithm with HashMap and Double LinkedList.
The key of the HashMap is a hashtag_pair (e.g. ('#apache', '#hadoop')),
while the value is a doubly LinkedList Node which contains the same hashtag_pair,
the datetime of the tweet and the two linked list pointers, Next and Previous.
The Double LinkedList is sorted in ascending order with datetime,
which would be helpful to remove timeout hashtag_pair..
This data structure aims to calculate the average degree with tweets in latest 60s
and remove the timeout tweets. It also provides the edge number of every node. | 62599079bf627c535bcb2e9d |
class NameNodeMaster(NameNode, SSHRelation): <NEW_LINE> <INDENT> relation_name = 'datanode' <NEW_LINE> ssh_user = 'hdfs' <NEW_LINE> require_slave = False | Alternate NameNode relation for DataNodes. | 625990797d43ff24874280fc |
class TextNode(Node): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = self.value.replace('\n', '\\n') <NEW_LINE> if len(s) < 20: <NEW_LINE> <INDENT> return '\'' + s + '\'\n' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '\'' + s[:10] + '...' + s[-10:] + '\'\n' <NEW_LINE> <DEDENT> <DEDENT> def evaluate(self, context): <NEW_LINE> <INDENT> return str(self.value) | thisText = TextNode("Value of the thisText")
thisText.evaluate() | 62599079796e427e53850149 |
class AdvertAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> inlines = [AdvertImage, ] <NEW_LINE> fieldsets = ( (None, { 'fields': ('title', 'description', 'location', 'type', 'estate', 'size', 'plot_size', 'price', 'tags') }), ('Więcej', { 'classes': ('collapse',), 'fields': ('heating', 'windows', 'furniture', 'balcony') }) ) <NEW_LINE> prepopulated_fields = {'tags': ('type', 'estate',)} <NEW_LINE> ordering = ['-updated'] <NEW_LINE> list_filter = ('type', 'estate', 'heating', 'furniture') <NEW_LINE> search_fields = ('location', ) <NEW_LINE> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> form.cleaned_data['tags'] = form.cleaned_data['tags'][0].split('-') <NEW_LINE> obj.save() | Advert models admin | 625990793539df3088ecdc66 |
@with_metaclass(utils.MetaClassForClassesWithEnums) <NEW_LINE> class DataType(object): <NEW_LINE> <INDENT> BOOL = internals.DATATYPE_BOOL <NEW_LINE> CHAR = internals.DATATYPE_CHAR <NEW_LINE> BYTE = internals.DATATYPE_BYTE <NEW_LINE> INT32 = internals.DATATYPE_INT32 <NEW_LINE> INT64 = internals.DATATYPE_INT64 <NEW_LINE> FLOAT32 = internals.DATATYPE_FLOAT32 <NEW_LINE> FLOAT64 = internals.DATATYPE_FLOAT64 <NEW_LINE> STRING = internals.DATATYPE_STRING <NEW_LINE> BYTEARRAY = internals.DATATYPE_BYTEARRAY <NEW_LINE> DATE = internals.DATATYPE_DATE <NEW_LINE> TIME = internals.DATATYPE_TIME <NEW_LINE> DECIMAL = internals.DATATYPE_DECIMAL <NEW_LINE> DATETIME = internals.DATATYPE_DATETIME <NEW_LINE> ENUMERATION = internals.DATATYPE_ENUMERATION <NEW_LINE> SEQUENCE = internals.DATATYPE_SEQUENCE <NEW_LINE> CHOICE = internals.DATATYPE_CHOICE <NEW_LINE> CORRELATION_ID = internals.DATATYPE_CORRELATION_ID | Contains the possible data types which can be represented in an Element.
Class attributes:
BOOL Boolean
CHAR Char
BYTE Unsigned 8 bit value
INT32 32 bit Integer
INT64 64 bit Integer
FLOAT32 32 bit Floating point
FLOAT64 64 bit Floating point
STRING ASCIIZ string
BYTEARRAY Opaque binary data
DATE Date
TIME Timestamp
DECIMAL Currently Unsuppored
DATETIME Date and time
ENUMERATION An opaque enumeration
SEQUENCE Sequence type
CHOICE Choice type
CORRELATION_ID Used for some internal messages | 62599079a8370b77170f1d9c |
class DutyCycleCorrection(ivi.IviContainer): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._channel_count = 1 <NEW_LINE> super(DutyCycleCorrection, self).__init__(*args, **kwargs) <NEW_LINE> cls = 'IviPwrMeter' <NEW_LINE> grp = 'DutyCycleCorrection' <NEW_LINE> ivi.add_group_capability(self, cls+grp) <NEW_LINE> self._channel_duty_cycle_enabled = list() <NEW_LINE> self._channel_duty_cycle_value = list() <NEW_LINE> self._add_property('channels[].duty_cycle.enabled', self._get_channel_duty_cycle_enabled, self._set_channel_duty_cycle_enabled) <NEW_LINE> self._add_property('channels[].duty_cycle.value', self._get_channel_duty_cycle_value, self._set_channel_duty_cycle_value) <NEW_LINE> self._add_method('channels[].duty_cycle.configure', self._channel_duty_cycle_configure) <NEW_LINE> self._init_channels() <NEW_LINE> <DEDENT> def _init_channels(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(DutyCycleCorrection, self)._init_channels() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._channel_duty_cycle_enabled = list() <NEW_LINE> self._channel_duty_cycle_value = list() <NEW_LINE> for i in range(self._channel_count): <NEW_LINE> <INDENT> self._channel_duty_cycle_enabled.append(True) <NEW_LINE> self._channel_duty_cycle_value.append(50.0) <NEW_LINE> <DEDENT> self.channels._set_list(self._channel_name) <NEW_LINE> <DEDENT> def _get_channel_duty_cycle_enabled(self, index): <NEW_LINE> <INDENT> index = ivi.get_index(self._channel_name, index) <NEW_LINE> return self._channel_duty_cycle_enabled[index] <NEW_LINE> <DEDENT> def _set_channel_duty_cycle_enabled(self, index, value): <NEW_LINE> <INDENT> index = ivi.get_index(self._channel_name, index) <NEW_LINE> value = bool(value) <NEW_LINE> self._channel_duty_cycle_enabled[index] = value <NEW_LINE> <DEDENT> def _get_channel_duty_cycle_value(self, index): <NEW_LINE> <INDENT> index = ivi.get_index(self._channel_name, index) <NEW_LINE> return self._channel_duty_cycle_value[index] <NEW_LINE> <DEDENT> def _set_channel_duty_cycle_value(self, index, value): <NEW_LINE> <INDENT> index = ivi.get_index(self._channel_name, index) <NEW_LINE> value = float(value) <NEW_LINE> self._channel_duty_cycle_value[index] = value <NEW_LINE> <DEDENT> def _channel_duty_cycle_configure(self, index, enabled, correction): <NEW_LINE> <INDENT> self._set_channel_duty_cycle_enabled(enabled) <NEW_LINE> self._set_channel_duty_cycle_value(correction) | Extension IVI methods for RF power meters supporting duty cycle correction of pulse modulated signals | 62599079460517430c432d41 |
class BaseGeoAdmin(BaseAdmin, GeoModelAdmin): <NEW_LINE> <INDENT> if GEODJANGO_IMPROVED_WIDGETS: <NEW_LINE> <INDENT> lat, lng = _get_geodjango_map_coords() <NEW_LINE> options = { 'layers': [ 'osm.mapnik', 'google.streets', 'google.physical', 'google.satellite', 'google.hybrid', ], 'default_lat': lat, 'default_lon': lng, 'default_zoom': _get_geodjango_map_zoom(), } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> default_lon, default_lat = _get_geodjango_map_coords() <NEW_LINE> default_zoom = _get_geodjango_map_zoom() | BaseAdmin + Geodjango support | 6259907932920d7e50bc7a17 |
class JsonResponse(HttpResponse): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> super(JsonResponse, self).__init__(content=simplejson.dumps(data,ensure_ascii=False, cls = MyJSONEncoder), mimetype='application/json') | HttpResponse descendant, which return response with ``application/json`` mimetype. | 62599079d486a94d0ba2d986 |
class VSFlags: <NEW_LINE> <INDENT> UserValue = "UserValue" <NEW_LINE> UserIgnored = "UserIgnored" <NEW_LINE> UserRequired = "UserRequired" <NEW_LINE> Continue = "Continue" <NEW_LINE> SemicolonAppendable = "SemicolonAppendable" <NEW_LINE> UserFollowing = "UserFollowing" <NEW_LINE> CaseInsensitive = "CaseInsensitive" <NEW_LINE> UserValueIgnored = [UserValue, UserIgnored] <NEW_LINE> UserValueRequired = [UserValue, UserRequired] | Flags corresponding to cmIDEFlagTable. | 6259907960cbc95b06365a55 |
class MaterialHiddenInput(MaterialComponent, widgets.HiddenInput): <NEW_LINE> <INDENT> template_name = 'material_widgets/widgets/material_hidden.html' | Material HiddenInput
Parameters
----------
initial : varies depending on field, optional
Initial value to populate the hidden input in the form.
Examples
--------
>>> hidden_input = forms.CharField(
>>> initial='hidden_value',
>>> widget=widgets.HiddenInput(),
>>> ) | 62599079627d3e7fe0e08857 |
class Variant(object): <NEW_LINE> <INDENT> Text, Pattern, VarRef, VarDef, Separator = range(5) | Supported language constructs. | 625990795166f23b2e244da7 |
class FormulaPropertiesFromVm(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'lab_vm_id': {'key': 'labVmId', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, lab_vm_id: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(FormulaPropertiesFromVm, self).__init__(**kwargs) <NEW_LINE> self.lab_vm_id = lab_vm_id | Information about a VM from which a formula is to be created.
:param lab_vm_id: The identifier of the VM from which a formula is to be created.
:type lab_vm_id: str | 6259907976e4537e8c3f0f4f |
class WorkerTest(IonTestCase): <NEW_LINE> <INDENT> @defer.inlineCallbacks <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> yield self._start_container() <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def tearDown(self): <NEW_LINE> <INDENT> yield self._stop_container() <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_worker_queue(self): <NEW_LINE> <INDENT> workers = [ {'name':'workerProc1','module':'ion.core.process.worker','spawnargs':{'receiver-name':'worker1','scope':'system','receiver-type':'worker'}}, {'name':'workerProc2','module':'ion.core.process.worker','spawnargs':{'receiver-name':'worker1','scope':'system','receiver-type':'worker'}}, ] <NEW_LINE> sup = yield self._spawn_processes(workers) <NEW_LINE> log.info("Supervisor: "+repr(sup)) <NEW_LINE> wc = WorkerClient() <NEW_LINE> wcId = yield self._spawn_process(wc) <NEW_LINE> wq_name = ioninit.sys_name + ".worker1" <NEW_LINE> for i in range(1,5): <NEW_LINE> <INDENT> yield wc.submit_work(wq_name, i, 0.3) <NEW_LINE> <DEDENT> yield pu.asleep(1.5) <NEW_LINE> log.info("Work results: %s" % (wc.workresult)) <NEW_LINE> log.info("Worker results: %s" % (wc.worker)) <NEW_LINE> sum = 0 <NEW_LINE> for w,v in wc.worker.items(): <NEW_LINE> <INDENT> sum += v <NEW_LINE> <DEDENT> self.assertEqual(sum, 4) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_fanout(self): <NEW_LINE> <INDENT> workers = [ {'name':'fanoutProc1','module':'ion.core.process.worker','spawnargs':{'receiver-name':'fanout1','scope':'system','receiver-type':'fanout'}}, {'name':'fanoutProc2','module':'ion.core.process.worker','spawnargs':{'receiver-name':'fanout1','scope':'system','receiver-type':'fanout'}}, ] <NEW_LINE> sup = yield self._spawn_processes(workers) <NEW_LINE> log.info("Supervisor: "+repr(sup)) <NEW_LINE> wc = WorkerClient() <NEW_LINE> wcId = yield self._spawn_process(wc) <NEW_LINE> wq_name = ioninit.sys_name + ".fanout1" <NEW_LINE> for i in range(1,3): <NEW_LINE> <INDENT> yield wc.submit_work(wq_name, i, 0.3) <NEW_LINE> <DEDENT> yield pu.asleep(1.5) <NEW_LINE> log.info("Work results: "+str(wc.workresult)) <NEW_LINE> log.info("Worker results: "+str(wc.worker)) <NEW_LINE> sum = 0 <NEW_LINE> for w,v in wc.worker.items(): <NEW_LINE> <INDENT> sum += v <NEW_LINE> <DEDENT> self.assertEqual(sum, 4) | Testing worker processes | 625990798a349b6b43687c2b |
class Component(ApplicationSession): <NEW_LINE> <INDENT> @inlineCallbacks <NEW_LINE> def onJoin(self, details): <NEW_LINE> <INDENT> res = yield self.call('com.myapp.add_complex', 2, 3, 4, 5) <NEW_LINE> print("Result: {} + {}i".format(res.kwresults['c'], res.kwresults['ci'])) <NEW_LINE> res = yield self.call('com.myapp.split_name', 'Homer Simpson') <NEW_LINE> print("Forname: {}, Surname: {}".format(res.results[0], res.results[1])) <NEW_LINE> self.leave() <NEW_LINE> <DEDENT> def onDisconnect(self): <NEW_LINE> <INDENT> reactor.stop() | Application component that calls procedures which
produce complex results and showing how to access those. | 625990797047854f46340d8b |
class lazyT(object): <NEW_LINE> <INDENT> m = s = T = f = t = None <NEW_LINE> M = is_copy = False <NEW_LINE> def __init__( self, message, symbols={}, T=None, filter=None, ftag=None, M=False ): <NEW_LINE> <INDENT> if isinstance(message, lazyT): <NEW_LINE> <INDENT> self.m = message.m <NEW_LINE> self.s = message.s <NEW_LINE> self.T = message.T <NEW_LINE> self.f = message.f <NEW_LINE> self.t = message.t <NEW_LINE> self.M = message.M <NEW_LINE> self.is_copy = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.m = message <NEW_LINE> self.s = symbols <NEW_LINE> self.T = T <NEW_LINE> self.f = filter <NEW_LINE> self.t = ftag <NEW_LINE> self.M = M <NEW_LINE> self.is_copy = False <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<lazyT %s>" % (repr(Utf8(self.m)), ) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.T.apply_filter(self.m, self.s, self.f, self.t) if self.M else self.T.translate(self.m, self.s)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return str(self) == str(other) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return str(self) != str(other) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return '%s%s' % (self, other) <NEW_LINE> <DEDENT> def __radd__(self, other): <NEW_LINE> <INDENT> return '%s%s' % (other, self) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return str(self) * other <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> return cmp(str(self), str(other)) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(str(self)) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(str(self), name) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> return str(self)[i] <NEW_LINE> <DEDENT> def __getslice__(self, i, j): <NEW_LINE> <INDENT> return str(self)[i:j] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for c in str(self): <NEW_LINE> <INDENT> yield c <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(str(self)) <NEW_LINE> <DEDENT> def xml(self): <NEW_LINE> <INDENT> return str(self) if self.M else xmlescape(str(self), quote=False) <NEW_LINE> <DEDENT> def encode(self, *a, **b): <NEW_LINE> <INDENT> if PY2 and a[0] != 'utf8': <NEW_LINE> <INDENT> return to_unicode(str(self)).encode(*a, **b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> <DEDENT> def decode(self, *a, **b): <NEW_LINE> <INDENT> if PY2: <NEW_LINE> <INDENT> return str(self).decode(*a, **b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> <DEDENT> def read(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def __mod__(self, symbols): <NEW_LINE> <INDENT> if self.is_copy: <NEW_LINE> <INDENT> return lazyT(self) <NEW_LINE> <DEDENT> return lazyT(self.m, symbols, self.T, self.f, self.t, self.M) | Never to be called explicitly, returned by
translator.__call__() or translator.M() | 6259907992d797404e389844 |
class VirtualWanVpnProfileParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'vpn_server_configuration_resource_id': {'key': 'vpnServerConfigurationResourceId', 'type': 'str'}, 'authentication_method': {'key': 'authenticationMethod', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VirtualWanVpnProfileParameters, self).__init__(**kwargs) <NEW_LINE> self.vpn_server_configuration_resource_id = kwargs.get('vpn_server_configuration_resource_id', None) <NEW_LINE> self.authentication_method = kwargs.get('authentication_method', None) | Virtual Wan Vpn profile parameters Vpn profile generation.
:param vpn_server_configuration_resource_id: VpnServerConfiguration partial resource uri with
which VirtualWan is associated to.
:type vpn_server_configuration_resource_id: str
:param authentication_method: VPN client authentication method. Possible values include:
"EAPTLS", "EAPMSCHAPv2".
:type authentication_method: str or ~azure.mgmt.network.v2019_11_01.models.AuthenticationMethod | 6259907901c39578d7f1441d |
@navigator.register(ProvisioningTemplateEntity, 'New') <NEW_LINE> class AddNewProvisioningTemplate(NavigateStep): <NEW_LINE> <INDENT> VIEW = ProvisioningTemplateCreateView <NEW_LINE> prerequisite = NavigateToSibling('All') <NEW_LINE> def step(self, *args, **kwargs): <NEW_LINE> <INDENT> self.parent.new.click() | Navigate to Create new Provisioning Template screen. | 6259907967a9b606de54778e |
class WriteFileCommand(Command): <NEW_LINE> <INDENT> def __init__(self, filename = None, tmpl_list = None, srcloc = None): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> if tmpl_list is None: <NEW_LINE> <INDENT> self.tmpl_list = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Command.__init__(self, srcloc) <NEW_LINE> self.tmpl_list = tmpl_list <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.filename: <NEW_LINE> <INDENT> return 'WriteFileCommand(\"'+self.filename+'\")' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'WriteFileCommand(NULL)' <NEW_LINE> <DEDENT> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> tmpl_list = [] <NEW_LINE> CopyTmplList(self.tmpl_list, tmpl_list) <NEW_LINE> return WriteFileCommand(self.filename, tmpl_list, self.srcloc) | WriteFileCommand
filename This is the name of the file that will be written to
when the command is executed.
tmpl_list This is the contents of what will be written to the file.
Text strings are often simple strings, however more
generally, they can be strings which include other variables
(ie templates). In general, templates are lists of alternating
TextBlocks and VarRefs, (with additional tags and data to
identify where they occur in in the original user's files).
| 625990792c8b7c6e89bd51bc |
class XSSSS_ice(XSMultiplicativeModel): <NEW_LINE> <INDENT> __function__ = "xssssi" <NEW_LINE> def __init__(self, name='sss_ice'): <NEW_LINE> <INDENT> self.clumps = Parameter(name, 'clumps', 0.0, 0., 10., 0.0, hugeval) <NEW_LINE> XSMultiplicativeModel.__init__(self, name, (self.clumps,)) | The XSPEC sss_ice model: Einstein SSS ice absorption.
The model is described at [1]_.
Attributes
----------
clumps
The ice thickness parameter.
References
----------
.. [1] https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/XSmodelSssice.html | 62599079627d3e7fe0e08859 |
class PullAudioInputStreamCallback(impl.PullAudioInputStreamCallback): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def read(self, buffer: memoryview) -> int: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def close(self) -> None: <NEW_LINE> <INDENT> pass | An interface that defines callback methods for an audio input stream.
Derive from this class and implement its function to provide your own
data as an audio input stream. | 62599079be8e80087fbc0a67 |
class ATMClient(object): <NEW_LINE> <INDENT> def __init__(self, host, port): <NEW_LINE> <INDENT> address = (host, port) <NEW_LINE> self.server = socket(AF_INET, SOCK_STREAM) <NEW_LINE> self.server.connect(address) <NEW_LINE> message = decode(self.server.recv(BUFSIZE), CODE) <NEW_LINE> <DEDENT> def get(self, name, pin): <NEW_LINE> <INDENT> self.server.send(bytes(name + "\n" + pin, CODE)) <NEW_LINE> message = decode(self.server.recv(BUFSIZE), CODE) <NEW_LINE> if message == "success": <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def getBalance(self): <NEW_LINE> <INDENT> self.server.send(bytes("balance\n" + "nada", CODE)) <NEW_LINE> message = decode(self.server.recv(BUFSIZE), CODE) <NEW_LINE> return float(message) <NEW_LINE> <DEDENT> def deposit(self, amount): <NEW_LINE> <INDENT> self.server.send(bytes("deposit\n" + str(amount), CODE)) <NEW_LINE> message = decode(self.server.recv(BUFSIZE), CODE) <NEW_LINE> if message == "success": return None <NEW_LINE> else: return message <NEW_LINE> <DEDENT> def withdraw(self, amount): <NEW_LINE> <INDENT> self.server.send(bytes("withdraw\n" + str(amount), CODE)) <NEW_LINE> message = decode(self.server.recv(BUFSIZE), CODE) <NEW_LINE> if message == "success": return None <NEW_LINE> else: return message | Represents the client for a bank ATM. Behaves like a Bank with the
get method and an account with the getBalance, deposit, and withdraw
methods. | 6259907926068e7796d4e310 |
class SlackWebhook(base_notification.BaseNotification): <NEW_LINE> <INDENT> def _dump_slack_output(self, data, indent=0): <NEW_LINE> <INDENT> output = '' <NEW_LINE> if not isinstance(data, dict): <NEW_LINE> <INDENT> LOGGER.debug('Violation data is not a dictionary type. ' f'Violation data: {data}') <NEW_LINE> return '\t' * (indent + 1) + '`' + str(data) + '`\n' <NEW_LINE> <DEDENT> for key, value in sorted(data.items()): <NEW_LINE> <INDENT> output += '\t' * indent + '*' + str(key) + '*:' <NEW_LINE> if isinstance(value, dict): <NEW_LINE> <INDENT> output += '\n' + self._dump_slack_output(value, indent + 1) + '\n' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> value = 'n/a' <NEW_LINE> <DEDENT> output += '\t' * (indent + 1) + '`' + str(value) + '`\n' <NEW_LINE> <DEDENT> <DEDENT> return output <NEW_LINE> <DEDENT> def _compose(self, violation): <NEW_LINE> <INDENT> return ('*type*:\t`{}`\n*details*:\n'.format(self.resource) + self._dump_slack_output(violation.get('violation_data'), 1)) <NEW_LINE> <DEDENT> @retry(retry_on_exception=retryable_exceptions.is_retryable_exception, wait_exponential_multiplier=30000, wait_exponential_max=60000, stop_max_attempt_number=2) <NEW_LINE> def _send(self, payload): <NEW_LINE> <INDENT> url = self.notification_config.get('webhook_url') <NEW_LINE> response = requests.post(url, json={'text': payload}) <NEW_LINE> LOGGER.info(response) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if not self.notification_config.get('webhook_url'): <NEW_LINE> <INDENT> LOGGER.warning('No url found, not running Slack notifier.') <NEW_LINE> return <NEW_LINE> <DEDENT> for violation in self.violations: <NEW_LINE> <INDENT> webhook_payload = self._compose(violation=violation) <NEW_LINE> try: <NEW_LINE> <INDENT> self._send(payload=webhook_payload) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOGGER.exception('Failed to send a message to a channel.') | Slack webhook notifier to perform notifications | 6259907921bff66bcd72463b |
class Decorator(DecoratorBase): <NEW_LINE> <INDENT> def add_scale( self, color_def, font=None, size=None, fill="black", outline=None, outline_width=1, bg="white", extend=False, unit="", margins=None, minortick=0.0, nan_color=(0, 0, 0), nan_check_color=(1, 1, 1), nan_check_size=0, ): <NEW_LINE> <INDENT> self._add_scale( color_def, font=font, size=size, fill=fill, outline=outline, outline_widht=outline_width, bg=bg, extend=extend, unit=unit, margins=margins, minortick=minortick, nan_color=nan_color, nan_check_color=nan_check_color, nan_check_size=nan_check_size, ) <NEW_LINE> <DEDENT> def _load_default_font(self): <NEW_LINE> <INDENT> return ImageFont.load_default() <NEW_LINE> <DEDENT> def add_text(self, txt, **kwargs): <NEW_LINE> <INDENT> self._add_text(txt, **kwargs) <NEW_LINE> <DEDENT> def add_logo(self, logo_path, **kwargs): <NEW_LINE> <INDENT> self._add_logo(logo_path, **kwargs) <NEW_LINE> <DEDENT> def _get_canvas(self, image): <NEW_LINE> <INDENT> return ImageDraw.Draw(image) | PIL-based image decoration class. | 62599079a8370b77170f1da0 |
class ComponentConfig: <NEW_LINE> <INDENT> def __init__(self, realm = None, extra = None): <NEW_LINE> <INDENT> if six.PY2 and type(realm) == str: <NEW_LINE> <INDENT> realm = six.u(realm) <NEW_LINE> <DEDENT> self.realm = realm <NEW_LINE> self.extra = extra <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "ComponentConfig(realm = {}, extra = {})".format(self.realm, self.extra) | WAMP application component configuration. An instance of this class is
provided to the constructor of :class:`autobahn.wamp.protocol.ApplicationSession`. | 6259907971ff763f4b5e917e |
class Flanks(object): <NEW_LINE> <INDENT> flank_re = re.compile(r"(\s*)(.*\S)(\s*)\Z", flags=re.DOTALL) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.left, self.right = None, None <NEW_LINE> <DEDENT> def split_flanks(self, _, result): <NEW_LINE> <INDENT> if not result.strip(): <NEW_LINE> <INDENT> self.left, self.right = "", "" <NEW_LINE> return result <NEW_LINE> <DEDENT> match = self.flank_re.match(result) <NEW_LINE> if not match: <NEW_LINE> <INDENT> raise RuntimeError( "Flank regexp unexpectedly did not match result: " "{!r} (type: {})" .format(result, type(result))) <NEW_LINE> <DEDENT> self.left, self.right = match.group(1), match.group(3) <NEW_LINE> return match.group(2) <NEW_LINE> <DEDENT> def join_flanks(self, _, result): <NEW_LINE> <INDENT> return self.left + result + self.right | A pair of processors that split and rejoin flanking whitespace.
| 6259907916aa5153ce401eac |
class Wavefront(object): <NEW_LINE> <INDENT> def __init__(self, file_name): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> self.materials = {} <NEW_LINE> self.meshes = {} <NEW_LINE> self.mesh_list = [] <NEW_LINE> self.group = None <NEW_LINE> ObjParser(self, self.file_name) <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> for this_mesh in self.mesh_list: <NEW_LINE> <INDENT> this_mesh.draw() <NEW_LINE> <DEDENT> <DEDENT> def add_mesh(self, the_mesh): <NEW_LINE> <INDENT> self.mesh_list.append(the_mesh) <NEW_LINE> if not the_mesh.name: return <NEW_LINE> self.meshes[the_mesh.name] = the_mesh | Import a wavefront .obj file. | 6259907997e22403b383c8d4 |
class coverageAnalysis(IonPlugin): <NEW_LINE> <INDENT> version = "4.4.2.2" <NEW_LINE> major_block = True <NEW_LINE> runtypes = [ RunType.FULLCHIP, RunType.THUMB, RunType.COMPOSITE ] <NEW_LINE> runlevels = [ RunLevel.DEFAULT ] <NEW_LINE> def launch(self,data=None): <NEW_LINE> <INDENT> plugin = Popen([ '%s/coverageAnalysis_plugin.py' % os.environ['DIRNAME'], '-V', self.version, '-d', '-B', os.environ['TSP_FILEPATH_BAM'], '-P', os.environ['TSP_FILEPATH_OUTPUT_STEM'], '-Q', os.environ['TSP_URLPATH_GENOME_FASTA'], '-R', os.environ['TSP_FILEPATH_GENOME_FASTA'], '-U', os.environ['TSP_URLPATH_PLUGIN_DIR'], '%s/startplugin.json' % os.environ['TSP_FILEPATH_PLUGIN_DIR'] ], stdout=PIPE, shell=False ) <NEW_LINE> plugin.communicate() <NEW_LINE> sys.exit(plugin.poll()) | Genome and Targeted Re-sequencing Coverage Analysis. (Ion supprted) | 6259907997e22403b383c8d5 |
class CombatCmdSet(CmdSet): <NEW_LINE> <INDENT> key = "combatcmdset" <NEW_LINE> mergetype = "Merge" <NEW_LINE> priority = 10 <NEW_LINE> no_exits = True <NEW_LINE> def at_cmdset_creation(self): <NEW_LINE> <INDENT> self.add(self.CmdFlee()) <NEW_LINE> <DEDENT> class CmdFlee(COMMAND_DEFAULT_CLASS): <NEW_LINE> <INDENT> key = "flee" <NEW_LINE> aliases = ["run"] <NEW_LINE> help_category = "General" <NEW_LINE> def func(self): <NEW_LINE> <INDENT> self.caller.ndb.combat_handler.at_flee(self.caller) <NEW_LINE> return | Contains response commands | 62599079009cb60464d02f11 |
class GoogleCalendarData(object): <NEW_LINE> <INDENT> def __init__(self, calendar_service, calendar_id, search, ignore_availability): <NEW_LINE> <INDENT> self.calendar_service = calendar_service <NEW_LINE> self.calendar_id = calendar_id <NEW_LINE> self.search = search <NEW_LINE> self.ignore_availability = ignore_availability <NEW_LINE> self.event = None <NEW_LINE> <DEDENT> def _prepare_query(self): <NEW_LINE> <INDENT> from httplib2 import ServerNotFoundError <NEW_LINE> try: <NEW_LINE> <INDENT> service = self.calendar_service.get() <NEW_LINE> <DEDENT> except ServerNotFoundError: <NEW_LINE> <INDENT> _LOGGER.warning("Unable to connect to Google, using cached data") <NEW_LINE> return False <NEW_LINE> <DEDENT> params = dict(DEFAULT_GOOGLE_SEARCH_PARAMS) <NEW_LINE> params['calendarId'] = self.calendar_id <NEW_LINE> if self.search: <NEW_LINE> <INDENT> params['q'] = self.search <NEW_LINE> <DEDENT> return service, params <NEW_LINE> <DEDENT> async def async_get_events(self, hass, start_date, end_date): <NEW_LINE> <INDENT> service, params = await hass.async_add_job(self._prepare_query) <NEW_LINE> params['timeMin'] = start_date.isoformat('T') <NEW_LINE> params['timeMax'] = end_date.isoformat('T') <NEW_LINE> events = await hass.async_add_job(service.events) <NEW_LINE> result = await hass.async_add_job(events.list(**params).execute) <NEW_LINE> items = result.get('items', []) <NEW_LINE> event_list = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if (not self.ignore_availability and 'transparency' in item.keys()): <NEW_LINE> <INDENT> if item['transparency'] == 'opaque': <NEW_LINE> <INDENT> event_list.append(item) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> event_list.append(item) <NEW_LINE> <DEDENT> <DEDENT> return event_list <NEW_LINE> <DEDENT> @Throttle(MIN_TIME_BETWEEN_UPDATES) <NEW_LINE> def update(self): <NEW_LINE> <INDENT> service, params = self._prepare_query() <NEW_LINE> params['timeMin'] = dt.now().isoformat('T') <NEW_LINE> events = service.events() <NEW_LINE> result = events.list(**params).execute() <NEW_LINE> items = result.get('items', []) <NEW_LINE> new_event = None <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if (not self.ignore_availability and 'transparency' in item.keys()): <NEW_LINE> <INDENT> if item['transparency'] == 'opaque': <NEW_LINE> <INDENT> new_event = item <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> new_event = item <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self.event = new_event <NEW_LINE> return True | Class to utilize calendar service object to get next event. | 625990794f88993c371f120b |
class TrainingMonitor(object): <NEW_LINE> <INDENT> def __init__(self, loss_key='loss', max_epochs=float('inf'), patience=20): <NEW_LINE> <INDENT> self.loss_key = loss_key <NEW_LINE> self.best_loss = float('inf') <NEW_LINE> self.best_epoch = None <NEW_LINE> self.max_epochs = max_epochs <NEW_LINE> self.epoch = 0 <NEW_LINE> self.patience = patience <NEW_LINE> self.frustration = 0 <NEW_LINE> self.improved = False <NEW_LINE> self.converged = False <NEW_LINE> self.monitors = defaultdict(list) <NEW_LINE> self.start_time = time.time() <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.monitors[key] <NEW_LINE> <DEDENT> def update(self, **kwargs): <NEW_LINE> <INDENT> timestamp = time.time() <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> self.monitors[key].append([timestamp, self.epoch, value]) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> curr_loss = kwargs[self.loss_key] <NEW_LINE> if curr_loss < self.best_loss: <NEW_LINE> <INDENT> self.improved = True <NEW_LINE> self.frustration = 0 <NEW_LINE> self.best_loss = curr_loss <NEW_LINE> self.best_epoch = self.epoch <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.improved = False <NEW_LINE> self.frustration += 1 <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.epoch += 1 <NEW_LINE> self.converged = ( self.patience < self.frustration or self.epoch >= self.max_epochs) <NEW_LINE> <DEDENT> def numpy(self, key): <NEW_LINE> <INDENT> n_fields = 3 <NEW_LINE> items = self.monitors[key] <NEW_LINE> mat = np.zeros((n_fields, len(items))) <NEW_LINE> for i in range(n_fields): <NEW_LINE> <INDENT> mat[i] = [x[i] for x in items] <NEW_LINE> <DEDENT> return mat | Utility class to monitor training progress.
Usage
-----
monitor = TrainingMonitor('nll')
while not train_monitor.converged:
nll, train_error, valid_error = train_step(net, train_data, valid_data)
train_monitor.observe(nll=nll, train_error=train_error, valid_error=valid_error) | 62599079baa26c4b54d50c85 |
class OveruseDetector: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.hypothesis = BandwidthUsage.NORMAL <NEW_LINE> self.last_update_ms: Optional[int] = None <NEW_LINE> self.k_up = 0.0087 <NEW_LINE> self.k_down = 0.039 <NEW_LINE> self.overuse_counter = 0 <NEW_LINE> self.overuse_time: Optional[float] = None <NEW_LINE> self.overuse_time_threshold = 10 <NEW_LINE> self.previous_offset = 0.0 <NEW_LINE> self.threshold = 12.5 <NEW_LINE> <DEDENT> def detect( self, offset: float, timestamp_delta_ms: float, num_of_deltas: int, now_ms: int ) -> BandwidthUsage: <NEW_LINE> <INDENT> if num_of_deltas < 2: <NEW_LINE> <INDENT> return BandwidthUsage.NORMAL <NEW_LINE> <DEDENT> T = min(num_of_deltas, MIN_NUM_DELTAS) * offset <NEW_LINE> if T > self.threshold: <NEW_LINE> <INDENT> if self.overuse_time is None: <NEW_LINE> <INDENT> self.overuse_time = timestamp_delta_ms / 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.overuse_time += timestamp_delta_ms <NEW_LINE> <DEDENT> self.overuse_counter += 1 <NEW_LINE> if ( self.overuse_time > self.overuse_time_threshold and self.overuse_counter > 1 and offset >= self.previous_offset ): <NEW_LINE> <INDENT> self.overuse_counter = 0 <NEW_LINE> self.overuse_time = 0 <NEW_LINE> self.hypothesis = BandwidthUsage.OVERUSING <NEW_LINE> <DEDENT> <DEDENT> elif T < -self.threshold: <NEW_LINE> <INDENT> self.overuse_counter = 0 <NEW_LINE> self.overuse_time = None <NEW_LINE> self.hypothesis = BandwidthUsage.UNDERUSING <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.overuse_counter = 0 <NEW_LINE> self.overuse_time = None <NEW_LINE> self.hypothesis = BandwidthUsage.NORMAL <NEW_LINE> <DEDENT> self.previous_offset = offset <NEW_LINE> self.update_threshold(T, now_ms) <NEW_LINE> return self.hypothesis <NEW_LINE> <DEDENT> def state(self) -> BandwidthUsage: <NEW_LINE> <INDENT> return self.hypothesis <NEW_LINE> <DEDENT> def update_threshold(self, modified_offset: float, now_ms: int) -> None: <NEW_LINE> <INDENT> if self.last_update_ms is None: <NEW_LINE> <INDENT> self.last_update_ms = now_ms <NEW_LINE> <DEDENT> if abs(modified_offset) > self.threshold + MAX_ADAPT_OFFSET_MS: <NEW_LINE> <INDENT> self.last_update_ms = now_ms <NEW_LINE> return <NEW_LINE> <DEDENT> k = self.k_down if abs(modified_offset) < self.threshold else self.k_up <NEW_LINE> time_delta_ms = min(now_ms - self.last_update_ms, 100) <NEW_LINE> self.threshold += k * (abs(modified_offset) - self.threshold) * time_delta_ms <NEW_LINE> self.threshold = max(6, min(self.threshold, 600)) <NEW_LINE> self.last_update_ms = now_ms | Bandwidth overuse detector.
Adapted from the webrtc.org codebase. | 62599079627d3e7fe0e0885b |
class DataSort(object): <NEW_LINE> <INDENT> def __init__(self,survey_id,uuid,aggregate): <NEW_LINE> <INDENT> self.sid= survey_id <NEW_LINE> self.uuid= uuid <NEW_LINE> self.agg= aggregate <NEW_LINE> <DEDENT> def get_survey(self): <NEW_LINE> <INDENT> survey= db.survey.find({"_id":ObjectId(self.sid)}) <NEW_LINE> return d(survey) <NEW_LINE> <DEDENT> def get_response(self): <NEW_LINE> <INDENT> response= db.response.find({"parent_survey":ObjectId(self.sid)}) <NEW_LINE> return d(response) <NEW_LINE> <DEDENT> def flag(self): <NEW_LINE> <INDENT> dat = SurveyUnit.objects(referenced = self.sid) <NEW_LINE> js= [_.repr for _ in dat if not _.hidden] <NEW_LINE> if len(js)!=0: <NEW_LINE> <INDENT> children=[] <NEW_LINE> for i in js: <NEW_LINE> <INDENT> children.append(i['id']) <NEW_LINE> <DEDENT> return children <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get_multi_data(self,aList): <NEW_LINE> <INDENT> js=[] <NEW_LINE> for i in aList: <NEW_LINE> <INDENT> i= HashId.decode(i) <NEW_LINE> raw= db.response.find({"parent_survey":ObjectId(i)}) <NEW_LINE> js= js +d(raw) <NEW_LINE> <DEDENT> return js <NEW_LINE> <DEDENT> def get_child_data(self,survey_id): <NEW_LINE> <INDENT> raw= db.survey.find({"_id":ObjectId(self.sid)}) <NEW_LINE> return d(raw) <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> dat = SurveyUnit.objects(referenced = self.sid) <NEW_LINE> flag= self.flag() <NEW_LINE> if flag==False: <NEW_LINE> <INDENT> raw= db.response.find({"parent_survey":ObjectId(self.sid)}) <NEW_LINE> js= d(raw) <NEW_LINE> return js <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.agg=="true": <NEW_LINE> <INDENT> raw= db.response.find({"parent_survey":ObjectId(self.sid)}) <NEW_LINE> js= d(raw) <NEW_LINE> js = js+ self.get_multi_data(flag) <NEW_LINE> return js <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raw= db.response.find({"parent_survey":ObjectId(self.sid)}) <NEW_LINE> js= d(raw) <NEW_LINE> return js <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_uuid_label(self): <NEW_LINE> <INDENT> raw_label=db.survey.find() <NEW_LINE> raw_label=db.survey.find({"_id":ObjectId(self.sid)}) <NEW_LINE> aList= d(raw_label)[0]['structure']['fields'] <NEW_LINE> for i in aList: <NEW_LINE> <INDENT> if i['cid']==self.uuid: <NEW_LINE> <INDENT> return i | docstring for DataSort | 62599079ec188e330fdfa27b |
class Error(GlazierError): <NEW_LINE> <INDENT> def __init__(self, exception: Optional[Exception] = None, replacements: Optional[List[Union[bool, int, str]]] = None): <NEW_LINE> <INDENT> super().__init__(exception, replacements) <NEW_LINE> self.code: int = code <NEW_LINE> if message and replacements: <NEW_LINE> <INDENT> self.message: str = f'{message.format(*replacements)}' <NEW_LINE> <DEDENT> elif message: <NEW_LINE> <INDENT> self.message: str = message | Stores error information used in GlazierError. | 62599079097d151d1a2c2a4b |
class NicSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Nic <NEW_LINE> fields = "__all__" | 网卡序列化类 | 62599079f9cc0f698b1c5fb6 |
class MLField(object): <NEW_LINE> <INDENT> _role_types = dict((str(e.name).upper(), e) for e in FieldRole) <NEW_LINE> def __init__(self, name, field_type, role, continuity=None, is_append=False, is_partition=False, kv_config=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = field_type.lower() <NEW_LINE> if role is None: <NEW_LINE> <INDENT> role = set() <NEW_LINE> <DEDENT> self.role = set(role) if isinstance(role, Iterable) else set([role, ]) <NEW_LINE> if continuity is not None: <NEW_LINE> <INDENT> self.continuity = continuity <NEW_LINE> <DEDENT> elif self.type == 'double' or self.type == 'bigint': <NEW_LINE> <INDENT> self.continuity = FieldContinuity.CONTINUOUS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.continuity = FieldContinuity.DISCRETE <NEW_LINE> <DEDENT> self.is_append = is_append <NEW_LINE> self.is_partition = is_partition <NEW_LINE> self.kv_config = kv_config <NEW_LINE> <DEDENT> def copy(self, role=None): <NEW_LINE> <INDENT> if role is None: <NEW_LINE> <INDENT> role = set() <NEW_LINE> <DEDENT> ret = deepcopy(self) <NEW_LINE> new_roles = role if isinstance(role, Iterable) else set([role, ]) <NEW_LINE> ret.role = ret.role | new_roles <NEW_LINE> return ret <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_column(cls, column, role=None): <NEW_LINE> <INDENT> return cls(column.name, str(column.type).lower(), role) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, col_str): <NEW_LINE> <INDENT> sparts = col_str.split(':') <NEW_LINE> role = cls.translate_role_name(sparts[2].strip()) if len(sparts) > 2 else None <NEW_LINE> return cls(sparts[0].strip(), sparts[1].strip().lower(), role) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def translate_role_name(cls, role_name): <NEW_LINE> <INDENT> role_name = role_name.strip() <NEW_LINE> if not role_name: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(role_name, FieldRole): <NEW_LINE> <INDENT> return role_name <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> role_name = str(role_name).strip().upper() <NEW_LINE> return cls._role_types[role_name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError('Role name ' + role_name + ' not registered. ' + 'Consider fixing the name or importing the right algorithm packages.') <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def register_roles(cls, new_enums): <NEW_LINE> <INDENT> cls._role_types.update(dict((str(e.name).upper(), e) for e in new_enums)) <NEW_LINE> <DEDENT> def _repr_type_(self): <NEW_LINE> <INDENT> return "KV('%s', '%s')" % (self.kv_config.kv_delimiter, self.kv_config.item_delimiter) if self.kv_config else self.type <NEW_LINE> <DEDENT> def _repr_role_(self): <NEW_LINE> <INDENT> return '+'.join(v.name for v in self.role) if self.role else 'None' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '[%s]%s (%s) -> %s' % (self.continuity.name[0] if self.continuity is not None else 'N', self.name, self._repr_type_(), self._repr_role_()) | Represent table field definition
:type continuity: FieldContinuity | None | 625990798a349b6b43687c2f |
@keras_export('keras.utils.OrderedEnqueuer') <NEW_LINE> class OrderedEnqueuer(SequenceEnqueuer): <NEW_LINE> <INDENT> def __init__(self, sequence, use_multiprocessing=False, shuffle=False): <NEW_LINE> <INDENT> super(OrderedEnqueuer, self).__init__(sequence, use_multiprocessing) <NEW_LINE> self.shuffle = shuffle <NEW_LINE> <DEDENT> def _get_executor_init(self, workers): <NEW_LINE> <INDENT> def pool_fn(seqs): <NEW_LINE> <INDENT> pool = get_pool_class(True)( workers, initializer=init_pool_generator, initargs=(seqs, None, get_worker_id_queue())) <NEW_LINE> _DATA_POOLS.add(pool) <NEW_LINE> return pool <NEW_LINE> <DEDENT> return pool_fn <NEW_LINE> <DEDENT> def _wait_queue(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> if self.queue.unfinished_tasks == 0 or self.stop_signal.is_set(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _run(self): <NEW_LINE> <INDENT> sequence = list(range(len(self.sequence))) <NEW_LINE> self._send_sequence() <NEW_LINE> while True: <NEW_LINE> <INDENT> if self.shuffle: <NEW_LINE> <INDENT> random.shuffle(sequence) <NEW_LINE> <DEDENT> with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor: <NEW_LINE> <INDENT> for i in sequence: <NEW_LINE> <INDENT> if self.stop_signal.is_set(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.queue.put( executor.apply_async(get_index, (self.uid, i)), block=True) <NEW_LINE> <DEDENT> self._wait_queue() <NEW_LINE> if self.stop_signal.is_set(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> self.sequence.on_epoch_end() <NEW_LINE> self._send_sequence() <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> while self.is_running(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> inputs = self.queue.get(block=True, timeout=5).get() <NEW_LINE> if self.is_running(): <NEW_LINE> <INDENT> self.queue.task_done() <NEW_LINE> <DEDENT> if inputs is not None: <NEW_LINE> <INDENT> yield inputs <NEW_LINE> <DEDENT> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> six.reraise(*sys.exc_info()) | Builds a Enqueuer from a Sequence.
Used in `fit_generator`, `evaluate_generator`, `predict_generator`.
Arguments:
sequence: A `tf.keras.utils.data_utils.Sequence` object.
use_multiprocessing: use multiprocessing if True, otherwise threading
shuffle: whether to shuffle the data at the beginning of each epoch | 6259907926068e7796d4e312 |
@Seq2SeqEncoder.register("feedforward") <NEW_LINE> class FeedForwardEncoder(Seq2SeqEncoder): <NEW_LINE> <INDENT> def __init__(self, feedforward: FeedForward) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._feedforward = feedforward <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def get_input_dim(self) -> int: <NEW_LINE> <INDENT> return self._feedforward.get_input_dim() <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def get_output_dim(self) -> int: <NEW_LINE> <INDENT> return self._feedforward.get_output_dim() <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def is_bidirectional(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def forward(self, inputs: torch.Tensor, mask: torch.LongTensor = None) -> torch.Tensor: <NEW_LINE> <INDENT> if mask is None: <NEW_LINE> <INDENT> return self._feedforward(inputs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> outputs = self._feedforward(inputs) <NEW_LINE> return outputs * mask.unsqueeze(dim=-1).float() | This class applies the `FeedForward` to each item in sequences. | 625990792c8b7c6e89bd51bf |
class TextsListScreen(Screen): <NEW_LINE> <INDENT> cards_list: list <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.cards_list = [] <NEW_LINE> <DEDENT> def clear_texts(self) -> None: <NEW_LINE> <INDENT> self.ids.texts_layout.clear_widgets() <NEW_LINE> self.cards_list.clear() <NEW_LINE> <DEDENT> def add_text(self, base_text: BaseText) -> None: <NEW_LINE> <INDENT> text_card = TextCard(self) <NEW_LINE> text_card.assign_base_text(base_text) <NEW_LINE> self.ids.texts_layout.add_widget(text_card) <NEW_LINE> self.cards_list.append(text_card) <NEW_LINE> <DEDENT> def refresh_texts(self, texts_data_list: dict) -> None: <NEW_LINE> <INDENT> self.clear_texts() <NEW_LINE> for id, text_data in texts_data_list.items(): <NEW_LINE> <INDENT> base_text = BaseText(id=id, **text_data) <NEW_LINE> self.add_text(base_text) <NEW_LINE> <DEDENT> self.ids.texts_layout.add_widget(BoxLayout(size_hint_y=None, height=dp(120))) <NEW_LINE> <DEDENT> def remove_card(self, card: TextCard) -> None: <NEW_LINE> <INDENT> self.cards_list.remove(card) <NEW_LINE> self.ids.texts_layout.remove_widget(card) | Главный экран со списком всех карточек (текстов). | 625990797d43ff24874280ff |
class Properties(util.ComparableMixin): <NEW_LINE> <INDENT> compare_attrs = ('properties',) <NEW_LINE> implements(IProperties) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.properties = {} <NEW_LINE> self.runtime = set() <NEW_LINE> self.build = None <NEW_LINE> if kwargs: self.update(kwargs, "TEST") <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> d = self.__dict__.copy() <NEW_LINE> d['build'] = None <NEW_LINE> return d <NEW_LINE> <DEDENT> def __setstate__(self, d): <NEW_LINE> <INDENT> self.__dict__ = d <NEW_LINE> if not hasattr(self, 'runtime'): <NEW_LINE> <INDENT> self.runtime = set() <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, name): <NEW_LINE> <INDENT> return name in self.properties <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> rv = self.properties[name][0] <NEW_LINE> return rv <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return not not self.properties <NEW_LINE> <DEDENT> def getPropertySource(self, name): <NEW_LINE> <INDENT> return self.properties[name][1] <NEW_LINE> <DEDENT> def asList(self): <NEW_LINE> <INDENT> l = [ (k, v[0], v[1]) for k,v in self.properties.iteritems() ] <NEW_LINE> l.sort() <NEW_LINE> return l <NEW_LINE> <DEDENT> def asDict(self): <NEW_LINE> <INDENT> return dict(self.properties) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('Properties(**' + repr(dict((k,v[0]) for k,v in self.properties.iteritems())) + ')') <NEW_LINE> <DEDENT> def update(self, dict, source, runtime=False): <NEW_LINE> <INDENT> for k, v in dict.items(): <NEW_LINE> <INDENT> self.properties[k] = (v, source) <NEW_LINE> if runtime: <NEW_LINE> <INDENT> self.runtime.add(k) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def updateFromProperties(self, other): <NEW_LINE> <INDENT> self.properties.update(other.properties) <NEW_LINE> self.runtime.update(other.runtime) <NEW_LINE> <DEDENT> def updateFromPropertiesNoRuntime(self, other): <NEW_LINE> <INDENT> for k,v in other.properties.iteritems(): <NEW_LINE> <INDENT> if k not in other.runtime: <NEW_LINE> <INDENT> self.properties[k] = v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getProperty(self, name, default=None): <NEW_LINE> <INDENT> return self.properties.get(name, (default,))[0] <NEW_LINE> <DEDENT> def hasProperty(self, name): <NEW_LINE> <INDENT> return self.properties.has_key(name) <NEW_LINE> <DEDENT> has_key = hasProperty <NEW_LINE> def setProperty(self, name, value, source, runtime=False): <NEW_LINE> <INDENT> self.properties[name] = (value, source) <NEW_LINE> if runtime: <NEW_LINE> <INDENT> self.runtime.add(name) <NEW_LINE> <DEDENT> <DEDENT> def getProperties(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def getBuild(self): <NEW_LINE> <INDENT> return self.build <NEW_LINE> <DEDENT> def render(self, value): <NEW_LINE> <INDENT> renderable = IRenderable(value) <NEW_LINE> return defer.maybeDeferred(renderable.getRenderingFor, self) | I represent a set of properties that can be interpolated into various
strings in buildsteps.
@ivar properties: dictionary mapping property values to tuples
(value, source), where source is a string identifing the source
of the property.
Objects of this class can be read like a dictionary -- in this case,
only the property value is returned.
As a special case, a property value of None is returned as an empty
string when used as a mapping. | 6259907932920d7e50bc7a1c |
class DatabaseIDManager(models.Manager): <NEW_LINE> <INDENT> def create(self, **kwargs): <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> DatabaseIDModel.objects.update(current=False) <NEW_LINE> return super(DatabaseIDManager, self).create(**kwargs) | We override ``model.Manager`` in order to wrap creating a new database ID model within a transaction. With the
creation of a new database ID model, we set all previously created models current flag to False. | 6259907944b2445a339b7648 |
class VerifyLoginHandler(BaseHandler): <NEW_LINE> <INDENT> def check_xsrf_cookie(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def post(self): <NEW_LINE> <INDENT> if 'error' in self.request.arguments: <NEW_LINE> <INDENT> error = self.get_argument('error') <NEW_LINE> description = self.get_argument('error_description') <NEW_LINE> raise minigrid.error.LoginError( reason=f'Broker Error: {error}: {description}') <NEW_LINE> <DEDENT> token = self.get_argument('id_token') <NEW_LINE> try: <NEW_LINE> <INDENT> email, next_page = await get_verified_email( broker_url, token, options.minigrid_website_url, broker_url, cache) <NEW_LINE> <DEDENT> except ValueError as exc: <NEW_LINE> <INDENT> raise minigrid.error.LoginError( reason=f'ValueError: {exc}') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user = ( self.session .query(models.User) .filter_by(email=email) .one()) <NEW_LINE> <DEDENT> except NoResultFound: <NEW_LINE> <INDENT> raise minigrid.error.LoginError( reason=f'There is no account for {email}') <NEW_LINE> <DEDENT> self.set_secure_cookie( 'user', str(user.user_id), httponly=True, secure=options.minigrid_https) <NEW_LINE> self.redirect(next_page) | Handlers for portier verification. | 625990797d847024c075ddb2 |
class ResourceSchema(colander.MappingSchema): <NEW_LINE> <INDENT> class Options: <NEW_LINE> <INDENT> readonly_fields = tuple() <NEW_LINE> preserve_unknown = True <NEW_LINE> <DEDENT> def get_option(self, attr): <NEW_LINE> <INDENT> default_value = getattr(ResourceSchema.Options, attr) <NEW_LINE> return getattr(self.Options, attr, default_value) <NEW_LINE> <DEDENT> def is_readonly(self, field): <NEW_LINE> <INDENT> return field in self.get_option("readonly_fields") <NEW_LINE> <DEDENT> def schema_type(self, **kw): <NEW_LINE> <INDENT> if self.get_option("preserve_unknown") is True: <NEW_LINE> <INDENT> unknown = 'preserve' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unknown = 'ignore' <NEW_LINE> <DEDENT> return colander.Mapping(unknown=unknown) | Base resource schema, with *Cliquet* specific built-in options. | 625990794f6381625f19a197 |
class InputInlineQueryResult(Object): <NEW_LINE> <INDENT> ID = "inputInlineQueryResult" <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(q: dict, *args) -> "InputInlineQueryResultVideo or InputInlineQueryResultAudio or InputInlineQueryResultAnimatedGif or InputInlineQueryResultAnimatedMpeg4 or InputInlineQueryResultDocument or InputInlineQueryResultVoiceNote or InputInlineQueryResultContact or InputInlineQueryResultGame or InputInlineQueryResultLocation or InputInlineQueryResultSticker or InputInlineQueryResultArticle or InputInlineQueryResultPhoto or InputInlineQueryResultVenue": <NEW_LINE> <INDENT> if q.get("@type"): <NEW_LINE> <INDENT> return Object.read(q) <NEW_LINE> <DEDENT> return InputInlineQueryResult() | Represents a single result of an inline query; for bots only
No parameters required. | 62599079e1aae11d1e7cf4fb |
class ExploreHandler(AuthBaseHandler): <NEW_LINE> <INDENT> @tornado.web.authenticated <NEW_LINE> def get(self,*args,**kwargs): <NEW_LINE> <INDENT> os.chdir('static') <NEW_LINE> image_urls = photo.get_images("uploads/thumbs") <NEW_LINE> os.chdir("..") <NEW_LINE> self.render('explore.html',image_urls=image_urls) | Explore page,photo of other users 发现页-----发现或最近上传的图片页面 | 62599079f9cc0f698b1c5fb7 |
class Card: <NEW_LINE> <INDENT> def __init__(self, rank, color): <NEW_LINE> <INDENT> self.rank = rank <NEW_LINE> self.color = color <NEW_LINE> self.numrank = rank2int(self.rank) <NEW_LINE> if self.rank == '10': <NEW_LINE> <INDENT> self.filename = self.rank + self.color[0] + '.png' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filename = self.rank[0] + self.color[0] + '.png' | Card class represents an individual card in the deck and
has useful attributes of the cards themselves | 625990793d592f4c4edbc849 |
class Cot(TrigonometricUnary): <NEW_LINE> <INDENT> pass | Returns the cotangent of x | 62599079a8370b77170f1da4 |
class UC(BBIO, I2C, _1WIRE, RawWire, SPI, UART): <NEW_LINE> <INDENT> pass | This class brings together all of the modules under a single class, allowing you to switch
to other modules, do a function, and then switch back transparently. The class will keep track
of where you are and raise an Error if you do something wrong.
The variables bp_port, bp_dir, and bp_config store the values that it sees in each respective mode,
and the variable mode stores which mode the bus pirate is in.
IMPORTANT: Keep in mind that switching modes always makes the pins go to HiZ and the power supplies
turn off. This can suck for certain applications (like if you are manualy wiggling a clock
or reset signal), but you can design around it with external pullups and external inverters.
YOU HAVE TO RECONFIGURE ALL SETTINGS WHENEVER YOU SWITCH MODES.
Note: current tested versions are only BBIO and I2C, but the other ones should work. Go to
________________.com and post any errors, problems or helpful revisions so that the code
can be updated | 625990795fdd1c0f98e5f955 |
class EmitterMeta(type): <NEW_LINE> <INDENT> def __init__(cls, name, bases, dict_): <NEW_LINE> <INDENT> super(EmitterMeta, cls).__init__(name, bases, dict_) <NEW_LINE> cls.__handlers__ = collections.defaultdict(set) <NEW_LINE> try: <NEW_LINE> <INDENT> propnames = set(prop.__name__ for prop in cls.property_list()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> propnames = set() <NEW_LINE> <DEDENT> for attr in dict_: <NEW_LINE> <INDENT> if attr in propnames: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> attr = dict_[attr] <NEW_LINE> if not ishandler(attr): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for event in attr.ha_events: <NEW_LINE> <INDENT> cls.__handlers__[event].add(attr) | Metaclass for :py:class:`Emitter` | 62599079d486a94d0ba2d98e |
class BasicCache(BaseCaching): <NEW_LINE> <INDENT> def put(self, key, item): <NEW_LINE> <INDENT> if key is not None and item is not None: <NEW_LINE> <INDENT> self.cache_data[key] = item <NEW_LINE> <DEDENT> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> if key not in self.cache_data or not key: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.cache_data[key] | BasicCache puts and gets items into a cache | 62599079009cb60464d02f15 |
@skipIf(not HAS_LIBNACL, 'skipping test_nacl, libnacl is unavailable') <NEW_LINE> class NaclTest(ModuleCase): <NEW_LINE> <INDENT> def test_keygen(self): <NEW_LINE> <INDENT> ret = self.run_function( 'nacl.keygen', ) <NEW_LINE> self.assertIn('pk', ret) <NEW_LINE> self.assertIn('sk', ret) <NEW_LINE> <DEDENT> def test_enc_dec(self): <NEW_LINE> <INDENT> ret = self.run_function( 'nacl.keygen', ) <NEW_LINE> self.assertIn('pk', ret) <NEW_LINE> self.assertIn('sk', ret) <NEW_LINE> pk = ret['pk'] <NEW_LINE> sk = ret['sk'] <NEW_LINE> unencrypted_data = salt.utils.stringutils.to_bytes('hello') <NEW_LINE> ret = self.run_function( 'nacl.enc', data=unencrypted_data, pk=pk, ) <NEW_LINE> encrypted_data = ret <NEW_LINE> ret = self.run_function( 'nacl.dec', data=encrypted_data, sk=sk, ) <NEW_LINE> self.assertEqual(unencrypted_data, ret) <NEW_LINE> <DEDENT> def test_sealedbox_enc_dec(self): <NEW_LINE> <INDENT> ret = self.run_function( 'nacl.keygen', ) <NEW_LINE> self.assertIn('pk', ret) <NEW_LINE> self.assertIn('sk', ret) <NEW_LINE> pk = ret['pk'] <NEW_LINE> sk = ret['sk'] <NEW_LINE> unencrypted_data = salt.utils.stringutils.to_bytes('hello') <NEW_LINE> ret = self.run_function( 'nacl.sealedbox_encrypt', data=unencrypted_data, pk=pk, ) <NEW_LINE> encrypted_data = ret <NEW_LINE> ret = self.run_function( 'nacl.sealedbox_decrypt', data=encrypted_data, sk=sk, ) <NEW_LINE> self.assertEqual(unencrypted_data, ret) <NEW_LINE> <DEDENT> def test_secretbox_enc_dec(self): <NEW_LINE> <INDENT> ret = self.run_function( 'nacl.keygen', ) <NEW_LINE> self.assertIn('pk', ret) <NEW_LINE> self.assertIn('sk', ret) <NEW_LINE> pk = ret['pk'] <NEW_LINE> sk = ret['sk'] <NEW_LINE> unencrypted_data = salt.utils.stringutils.to_bytes('hello') <NEW_LINE> ret = self.run_function( 'nacl.secretbox_encrypt', data=unencrypted_data, sk=sk, ) <NEW_LINE> encrypted_data = ret <NEW_LINE> ret = self.run_function( 'nacl.secretbox_decrypt', data=encrypted_data, sk=sk, ) <NEW_LINE> self.assertEqual(unencrypted_data, ret) | Test the nacl runner | 62599079167d2b6e312b827e |
class Questions(Resource): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> def post(self): <NEW_LINE> <INDENT> current_user = get_jwt_identity() <NEW_LINE> user_data = request.get_json() <NEW_LINE> data = validate(user_data, required_fields=[ 'title', 'body', 'meetup_id']) <NEW_LINE> if type(data) == list: <NEW_LINE> <INDENT> return {"status": 400, "errors": data}, 400 <NEW_LINE> <DEDENT> title = data["title"] <NEW_LINE> body = data['body'] <NEW_LINE> meetup_id = data['meetup_id'] <NEW_LINE> if not re.match(r"^[A-Za-z][a-zA-Z]", title): <NEW_LINE> <INDENT> return {"status": 400, "message": "Title should contain alphanumeric characters!"}, 400 <NEW_LINE> <DEDENT> if not re.match(r"^[A-Za-z][a-zA-Z]", body): <NEW_LINE> <INDENT> return {"status": 400, "message": "Body should contain alphanumeric characters"}, 400 <NEW_LINE> <DEDENT> if not re.match(r"^[0-9]", meetup_id): <NEW_LINE> <INDENT> return {"status": 400, "message": "Body should contain alphanumeric characters"}, 400 <NEW_LINE> <DEDENT> meetup = meetup_db.get_one_meetup(meetup_id) <NEW_LINE> if not meetup: <NEW_LINE> <INDENT> return {"status": 400, "message": "No meetup with id {}".format(meetup_id)}, 400 <NEW_LINE> <DEDENT> created_question = questions_db.create_question( title, body, meetup_id, current_user) <NEW_LINE> if (created_question): <NEW_LINE> <INDENT> return {"status": 201, "data": created_question}, 201 <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> all_questions = questions_db.fetch_all_questions() <NEW_LINE> return {"status": 200, "data": all_questions}, 200 | This class handles the questions endpoints | 6259907960cbc95b06365a59 |
class ToneAnalyzerV3(WatsonDeveloperCloudService): <NEW_LINE> <INDENT> default_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' <NEW_LINE> latest_version = '2016-05-19' <NEW_LINE> def __init__(self, version, url=default_url, **kwargs): <NEW_LINE> <INDENT> WatsonDeveloperCloudService.__init__(self, 'tone_analyzer', url, **kwargs) <NEW_LINE> self.version = version <NEW_LINE> <DEDENT> def tone(self, text, tones=None, sentences=None): <NEW_LINE> <INDENT> params = {'version': self.version} <NEW_LINE> if tones is not None: <NEW_LINE> <INDENT> params['tones'] = tones <NEW_LINE> <DEDENT> if sentences is not None: <NEW_LINE> <INDENT> params['sentences'] = str( sentences).lower() <NEW_LINE> <DEDENT> data = {'text': text} <NEW_LINE> return self.request(method='POST', url='/v3/tone', params=params, json=data, accept_json=True) <NEW_LINE> <DEDENT> def tone_chat(self, utterances): <NEW_LINE> <INDENT> params = {'version': self.version} <NEW_LINE> data = {'utterances': utterances} <NEW_LINE> return self.request( method='POST', url='/v3/tone_chat', params=params, json=data, accept_json=True) | Client for the ToneAnalyzer service. | 6259907955399d3f05627eeb |
class Page(object): <NEW_LINE> <INDENT> bbs_url='https://www.hujiang.com' <NEW_LINE> def __init__(self,selenium_driver,base_url=bbs_url,parent=None): <NEW_LINE> <INDENT> self.base_url=base_url <NEW_LINE> self.driver=selenium_driver <NEW_LINE> self.timeout=30 <NEW_LINE> self.parent=parent <NEW_LINE> <DEDENT> def _open(self,url): <NEW_LINE> <INDENT> url=self.base_url+url <NEW_LINE> self.driver.get(url) <NEW_LINE> assert self.on_page(),'Did not land on %s' %url <NEW_LINE> <DEDENT> def find_element(self,*loc): <NEW_LINE> <INDENT> return self.driver.find_element(*loc) <NEW_LINE> <DEDENT> def find_elements(self,*loc): <NEW_LINE> <INDENT> return self.driver.find_elements(*loc) <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> self._open(self.url) <NEW_LINE> <DEDENT> def on_page(self): <NEW_LINE> <INDENT> return self.driver.current_url==(self.base_url+self.url) <NEW_LINE> <DEDENT> def script(self,src): <NEW_LINE> <INDENT> return self.driver.execute_script(src) | 页面基础类,用于所有页面的继承 | 62599079ec188e330fdfa27f |
@add_status_code(408) <NEW_LINE> class RequestTimeout(NecktieException): <NEW_LINE> <INDENT> pass | The Web server (running the Web site) thinks that there has been too
long an interval of time between 1) the establishment of an IP
connection (socket) between the client and the server and
2) the receipt of any data on that socket, so the server has dropped
the connection. The socket connection has actually been lost - the Web
server has 'timed out' on that particular socket connection. | 625990795fdd1c0f98e5f956 |
class RamsayE(RobustNorm): <NEW_LINE> <INDENT> def __init__(self, a = .3): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> <DEDENT> def rho(self, z): <NEW_LINE> <INDENT> z = np.asarray(z) <NEW_LINE> return (1 - np.exp(-self.a * np.fabs(z)) * (1 + self.a * np.fabs(z))) / self.a**2 <NEW_LINE> <DEDENT> def psi(self, z): <NEW_LINE> <INDENT> z = np.asarray(z) <NEW_LINE> return z * np.exp(-self.a * np.fabs(z)) <NEW_LINE> <DEDENT> def weights(self, z): <NEW_LINE> <INDENT> z = np.asarray(z) <NEW_LINE> return np.exp(-self.a * np.fabs(z)) <NEW_LINE> <DEDENT> def psi_deriv(self, z): <NEW_LINE> <INDENT> return np.exp(-self.a * np.fabs(z)) + z**2* np.exp(-self.a*np.fabs(z))*-self.a/np.fabs(z) | Ramsay's Ea for M estimation.
Parameters
----------
a : float, optional
The tuning constant for Ramsay's Ea function. The default value is
0.3.
See also
--------
scikits.statsmodels.robust.norms.RobustNorm | 62599079ad47b63b2c5a9227 |
class BaseHitRecord(object): <NEW_LINE> <INDENT> HEADER_LEN = 10 <NEW_LINE> def __init__(self, base_time, hdr, data, offset): <NEW_LINE> <INDENT> self.__flags = hdr[2] <NEW_LINE> self.__chan_id = hdr[3] <NEW_LINE> self.__utime = base_time + hdr[4] <NEW_LINE> if hdr[0] == self.HEADER_LEN: <NEW_LINE> <INDENT> self.__data = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__data = data[offset+10:offset+hdr[0]] <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.HEADER_LEN + len(self.__data) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%d@%d[flags %x]" % (self.__chan_id, self.__utime, self.__flags) <NEW_LINE> <DEDENT> @property <NEW_LINE> def channel_id(self): <NEW_LINE> <INDENT> return self.__chan_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def flags(self): <NEW_LINE> <INDENT> return self.__flags <NEW_LINE> <DEDENT> @property <NEW_LINE> def timestamp(self): <NEW_LINE> <INDENT> return self.__utime | Generic hit record class | 62599079be7bc26dc9252b41 |
class Int8Bit(IntVal): <NEW_LINE> <INDENT> def __init__(self, value, signed=False): <NEW_LINE> <INDENT> super(Int8Bit, self).__init__(value, 8, signed) | Represent an 8-bit integer, unsigned by default | 6259907999cbb53fe68328be |
class SyncThruOutputTraySensor(SyncThruSensor): <NEW_LINE> <INDENT> def __init__(self, syncthru, name, number): <NEW_LINE> <INDENT> super().__init__(syncthru, name) <NEW_LINE> self._name = "{} Output Tray {}".format(name, number) <NEW_LINE> self._number = number <NEW_LINE> self._id_suffix = '_output_tray_{}'.format(number) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.syncthru.is_online(): <NEW_LINE> <INDENT> self._attributes = self.syncthru.output_tray_status( ).get(self._number, {}) <NEW_LINE> self._state = self._attributes.get('status') <NEW_LINE> if self._state == '': <NEW_LINE> <INDENT> self._state = 'Ready' | Implementation of a Samsung Printer input tray sensor platform. | 625990797b180e01f3e49d51 |
class TaskPanelOpPage(PathProfileGui.TaskPanelOpPage): <NEW_LINE> <INDENT> pass | Psuedo page controller class for Profile operation,
allowing for backward compatibility with pre-existing "Profile Edges" operations. | 6259907926068e7796d4e316 |
class BaseWeightedStrategy(MultiDecoderCombinationStrategy): <NEW_LINE> <INDENT> def __init__( self, out_embed_dims, vocab_size, vocab_reduction_module=None, fixed_weights=None, hidden_layer_size=32, activation_fn=torch.nn.ReLU, logit_fn=torch.exp, ): <NEW_LINE> <INDENT> super().__init__(out_embed_dims, vocab_size, vocab_reduction_module) <NEW_LINE> if fixed_weights is None: <NEW_LINE> <INDENT> self.fixed_weights = None <NEW_LINE> self.gating_network = nn.Sequential( Linear(sum(out_embed_dims), hidden_layer_size, bias=True), activation_fn(), Linear(hidden_layer_size, len(out_embed_dims), bias=True), ) <NEW_LINE> self.logit_fn = logit_fn <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert len(fixed_weights) == len(out_embed_dims) <NEW_LINE> self.fixed_weights = maybe_cuda(torch.Tensor(fixed_weights).view(1, 1, -1)) <NEW_LINE> <DEDENT> <DEDENT> def compute_weights(self, unprojected_outs, select_single=None): <NEW_LINE> <INDENT> if select_single is not None: <NEW_LINE> <INDENT> sz = unprojected_outs[0].size() <NEW_LINE> ret = maybe_cuda(torch.zeros((sz[0], sz[1], len(unprojected_outs)))) <NEW_LINE> ret[:, :, select_single] = 1.0 <NEW_LINE> return ret <NEW_LINE> <DEDENT> if self.fixed_weights is not None: <NEW_LINE> <INDENT> return self.fixed_weights <NEW_LINE> <DEDENT> logits = self.logit_fn(self.gating_network(torch.cat(unprojected_outs, 2))) <NEW_LINE> return torch.clamp(logits / torch.sum(logits, dim=2, keepdim=True), 0.0, 1.0) | Base class for strategies with explicitly learned weights. | 6259907921bff66bcd724641 |
class MaildirSource(MaildirService, util.ComparableMixin): <NEW_LINE> <INDENT> implements(IChangeSource) <NEW_LINE> compare_attrs = ["basedir", "pollinterval", "prefix"] <NEW_LINE> name = None <NEW_LINE> def __init__(self, maildir, prefix=None): <NEW_LINE> <INDENT> MaildirService.__init__(self, maildir) <NEW_LINE> self.prefix = prefix <NEW_LINE> if prefix and not prefix.endswith("/"): <NEW_LINE> <INDENT> log.msg("%s: you probably want your prefix=('%s') to end with " "a slash") <NEW_LINE> <DEDENT> <DEDENT> def describe(self): <NEW_LINE> <INDENT> return "%s mailing list in maildir %s" % (self.name, self.basedir) <NEW_LINE> <DEDENT> def messageReceived(self, filename): <NEW_LINE> <INDENT> path = os.path.join(self.basedir, "new", filename) <NEW_LINE> change = self.parse_file(open(path, "r"), self.prefix) <NEW_LINE> if change: <NEW_LINE> <INDENT> self.parent.addChange(change) <NEW_LINE> <DEDENT> os.rename(os.path.join(self.basedir, "new", filename), os.path.join(self.basedir, "cur", filename)) <NEW_LINE> <DEDENT> def parse_file(self, fd, prefix=None): <NEW_LINE> <INDENT> m = message_from_file(fd) <NEW_LINE> return self.parse(m, prefix) | This source will watch a maildir that is subscribed to a FreshCVS
change-announcement mailing list. | 6259907916aa5153ce401eb2 |
class PiglowLight(Light): <NEW_LINE> <INDENT> def __init__(self, piglow, name): <NEW_LINE> <INDENT> self._piglow = piglow <NEW_LINE> self._name = name <NEW_LINE> self._is_on = False <NEW_LINE> self._brightness = 255 <NEW_LINE> self._hs_color = [0, 0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> return self._brightness <NEW_LINE> <DEDENT> @property <NEW_LINE> def hs_color(self): <NEW_LINE> <INDENT> return self._hs_color <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> return SUPPORT_PIGLOW <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def assumed_state(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._is_on <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> self._piglow.clear() <NEW_LINE> if ATTR_BRIGHTNESS in kwargs: <NEW_LINE> <INDENT> self._brightness = kwargs[ATTR_BRIGHTNESS] <NEW_LINE> <DEDENT> if ATTR_HS_COLOR in kwargs: <NEW_LINE> <INDENT> self._hs_color = kwargs[ATTR_HS_COLOR] <NEW_LINE> <DEDENT> rgb = color_util.color_hsv_to_RGB( self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100) <NEW_LINE> self._piglow.red(rgb[0]) <NEW_LINE> self._piglow.green(rgb[1]) <NEW_LINE> self._piglow.blue(rgb[2]) <NEW_LINE> self._piglow.show() <NEW_LINE> self._is_on = True <NEW_LINE> self.schedule_update_ha_state() <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._piglow.clear() <NEW_LINE> self._piglow.show() <NEW_LINE> self._is_on = False <NEW_LINE> self.schedule_update_ha_state() | Representation of an Piglow Light. | 6259907923849d37ff852a91 |
class CheckLogin(APIView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> student = StudentModel.objects.get(user=request.user) <NEW_LINE> read_serializer = StudentModelSerializer(student, context={'request': request}) <NEW_LINE> return Response( {'error': False, 'isAuthenticated': True, 'message': 'Logged in as {}'.format(request.user.username), 'username': request.user.username, 'object': read_serializer.data}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response({'error': False, 'isAuthenticated': False, 'message': 'Not Logged In'}) | Request Type: GET
Allows you to check whether a token is still valid. Should be done at the time of the app being opened
Request:
Header: <Should contain authorization token>
Parameters: <None>
Response:
Error=True/False
isAuthenticated=True/False
Message=xxxxxxxxxxxxxxxxxxxxx | 625990797d847024c075ddb6 |
class CourseSummaryEnrollmentRecord(Record): <NEW_LINE> <INDENT> course_id = StringField(nullable=False, length=255, description='A unique identifier of the course') <NEW_LINE> catalog_course_title = StringField(nullable=True, length=255, normalize_whitespace=True, description='The name of the course') <NEW_LINE> catalog_course = StringField(nullable=True, length=255, description='Course identifier without run') <NEW_LINE> start_time = DateTimeField(nullable=True, description='The date and time that the course begins') <NEW_LINE> end_time = DateTimeField(nullable=True, description='The date and time that the course ends') <NEW_LINE> pacing_type = StringField(nullable=True, length=255, description='The type of pacing for this course') <NEW_LINE> availability = StringField(nullable=True, length=255, description='Availability status of the course') <NEW_LINE> enrollment_mode = StringField(length=100, nullable=False, description='Enrollment mode for the enrollment counts') <NEW_LINE> count = IntegerField(nullable=True, description='The count of currently enrolled learners') <NEW_LINE> count_change_7_days = IntegerField(nullable=True, description='Difference in enrollment counts over the past 7 days') <NEW_LINE> cumulative_count = IntegerField(nullable=True, description='The cumulative total of all users ever enrolled') <NEW_LINE> passing_users = IntegerField(nullable=True, description='The count of currently passing learners') | Recent enrollment summary and metadata for a course. | 625990791f5feb6acb1645d0 |
class NeuralNetwork: <NEW_LINE> <INDENT> def __init__(self, nx, nodes): <NEW_LINE> <INDENT> if type(nx) is not int: <NEW_LINE> <INDENT> raise TypeError("nx must be an integer") <NEW_LINE> <DEDENT> if nx < 1: <NEW_LINE> <INDENT> raise ValueError("nx must be a positive integer") <NEW_LINE> <DEDENT> if type(nodes) is not int: <NEW_LINE> <INDENT> raise TypeError("nodes must be an integer") <NEW_LINE> <DEDENT> if nodes < 1: <NEW_LINE> <INDENT> raise ValueError("nodes must be a positive integer") <NEW_LINE> <DEDENT> self.__b1 = np.zeros((nodes, 1)) <NEW_LINE> self.__A1 = 0 <NEW_LINE> self.__W1 = np.random.randn(nodes, nx) <NEW_LINE> self.__b2 = 0 <NEW_LINE> self.__A2 = 0 <NEW_LINE> self.__W2 = np.random.randn(nodes).reshape(1, nodes) <NEW_LINE> <DEDENT> @property <NEW_LINE> def b1(self): <NEW_LINE> <INDENT> return self.__b1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def A1(self): <NEW_LINE> <INDENT> return self.__A1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def W1(self): <NEW_LINE> <INDENT> return self.__W1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def b2(self): <NEW_LINE> <INDENT> return self.__b2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def A2(self): <NEW_LINE> <INDENT> return self.__A2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def W2(self): <NEW_LINE> <INDENT> return self.__W2 <NEW_LINE> <DEDENT> def forward_prop(self, X): <NEW_LINE> <INDENT> XT = np.transpose(X) <NEW_LINE> W1T = np.transpose(self.W1) <NEW_LINE> A_1 = np.transpose(np.matmul(XT, W1T)) + self.__b1 <NEW_LINE> self.__A1 = 1 / (1 + np.exp(-1 * A_1)) <NEW_LINE> A1T = np.transpose(self.A1) <NEW_LINE> W2T = np.transpose(self.W2) <NEW_LINE> A_2 = np.transpose(np.matmul(A1T, W2T)) + self.__b2 <NEW_LINE> self.__A2 = 1 / (1 + np.exp(-1 * A_2)) <NEW_LINE> return self.__A1, self.__A2 <NEW_LINE> <DEDENT> def cost(self, Y, A): <NEW_LINE> <INDENT> m = np.shape(Y) <NEW_LINE> j1 = -1 * (1 / m[1]) <NEW_LINE> j3 = np.multiply(Y, np.log(A)) <NEW_LINE> j4 = np.multiply(1 - Y, np.log(1.0000001 - A)) <NEW_LINE> j = j1 * np.sum(j3 + j4) <NEW_LINE> return j <NEW_LINE> <DEDENT> def evaluate(self, X, Y): <NEW_LINE> <INDENT> self.forward_prop(X) <NEW_LINE> j = self.cost(Y, self.__A2) <NEW_LINE> p = np.where(self.__A2 >= 0.5, 1, 0) <NEW_LINE> return p, j | Class NeuralNetwork | 62599079ec188e330fdfa281 |
class ArchiveMenuItem(z3c.menu.ready2go.item.SiteMenuItem): <NEW_LINE> <INDENT> pass | Menu item for the archive tab in the site menu. | 62599079627d3e7fe0e08861 |
class GitSubmodulesConfig(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "FetchSubmodules": (boolean, True), } | `GitSubmodulesConfig <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-gitsubmodulesconfig.html>`__ | 62599079be8e80087fbc0a6f |
class BSTreeNode(object): <NEW_LINE> <INDENT> def __init__(self, k, v, nil=None): <NEW_LINE> <INDENT> self.key = k <NEW_LINE> self.value = v <NEW_LINE> self.left = nil <NEW_LINE> self.right = nil <NEW_LINE> self.parent = nil | Abstract implementation of a binary search tree node. | 625990795fdd1c0f98e5f958 |
class Student: <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self, attrs=None): <NEW_LINE> <INDENT> if (type(attrs) == list and all(type(ele) == str for ele in attrs)): <NEW_LINE> <INDENT> return {k: getattr(self, k) for k in attrs if hasattr(self, k)} <NEW_LINE> <DEDENT> return self.__dict__ | A class representation of a student.
| 62599079aad79263cf430193 |
class Q3Processor(processor.ProcessorABC): <NEW_LINE> <INDENT> def process(self, events): <NEW_LINE> <INDENT> return ( hist.Hist.new.Reg(100, 0, 200, name="ptj", label="Jet $p_{T}$ [GeV]") .Double() .fill(ak.flatten(events.Jet[abs(events.Jet.eta) < 1].pt)) ) <NEW_LINE> <DEDENT> def postprocess(self, accumulator): <NEW_LINE> <INDENT> return accumulator | Plot the <i>p</i><sub>T</sub> of jets with |<i>η</i>| < 1. | 6259907976e4537e8c3f0f59 |
class Argtable(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "http://argtable.sourceforge.net/" <NEW_LINE> url = "https://sourceforge.net/projects/argtable/files/argtable/argtable-2.13/argtable2-13.tar.gz/download" <NEW_LINE> version('2-13', sha256='8f77e8a7ced5301af6e22f47302fdbc3b1ff41f2b83c43c77ae5ca041771ddbf') | Argtable is an ANSI C library for parsing GNU style command line
options with a minimum of fuss. | 625990795fc7496912d48f57 |
class DatasetSplit(DataBundleAdvanced): <NEW_LINE> <INDENT> def __init__(self, images: np.ndarray, labels: np.ndarray, bottlenecks=None, probability_distribution=None): <NEW_LINE> <INDENT> super(DatasetSplit, self).__init__(images, labels, bottlenecks) <NEW_LINE> self.set_probability_distribution(probability_distribution) <NEW_LINE> <DEDENT> def set_bottlenecks(self, bottlenecks: np.ndarray): <NEW_LINE> <INDENT> log.log("Replacing the split's current bottlenecks (old shape: {}, new shape: {}).".format( self.bottlenecks.shape if self.bottlenecks is not None else None, bottlenecks.shape if bottlenecks is not None else None, )) <NEW_LINE> self._bottlenecks = bottlenecks <NEW_LINE> <DEDENT> def set_probability_distribution(self, probability_distribution: np.ndarray): <NEW_LINE> <INDENT> self._probability_distribution = probability_distribution <NEW_LINE> if self._probability_distribution is None: <NEW_LINE> <INDENT> self._positive_proportion = float(self.n_positive_samples) / float(self.n_samples) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._positive_proportion = 0 <NEW_LINE> for i in range(self.n_samples): <NEW_LINE> <INDENT> if self.labels[i] == IID_FOREGROUND: <NEW_LINE> <INDENT> self._positive_proportion += self._probability_distribution[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def new_default_iterator(self, batch_size=None) -> DataBundleIterator: <NEW_LINE> <INDENT> if self._probability_distribution is None: <NEW_LINE> <INDENT> return DeterministicIterator(self, batch_size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return RandomizedIterator(self, self._probability_distribution, batch_size) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def positive_proportion(self) -> float: <NEW_LINE> <INDENT> return self._positive_proportion | A DatasetSplit is a smaller portion of a larger Dataset object. | 625990797b180e01f3e49d52 |
class MediaCreator(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def create_media(cls, suggestion, team_reference, preferred_references=[]): <NEW_LINE> <INDENT> media_type_enum = suggestion.contents['media_type_enum'] <NEW_LINE> return Media( id=Media.render_key_name(media_type_enum, suggestion.contents['foreign_key']), foreign_key=suggestion.contents['foreign_key'], media_type_enum=media_type_enum, details_json=suggestion.contents.get('details_json', None), private_details_json=suggestion.contents.get('private_details_json', None), year=int(suggestion.contents['year']) if not suggestion.contents.get('is_social', False) else None, references=[team_reference], preferred_references=preferred_references, ) | Used to create a Media object from an accepted Suggestion | 6259907921bff66bcd724643 |
class TeslaSmart(Driver): <NEW_LINE> <INDENT> __SET_CHANNEL = b"\xAA\xBB\x03\x01%b\xEE" <NEW_LINE> def __init__(self, config: Dict[str, Any]): <NEW_LINE> <INDENT> super().__init__(config, 0) <NEW_LINE> validate_value("maxInputs" in self.config, "Missing `maxInputs` for Tesla-Smart switch") <NEW_LINE> validate_value("tty" in self.config or "host" in self.config, "Missing `tty` or `host` for Extron switch") <NEW_LINE> self.max_inputs = int(self.config['maxInputs']) <NEW_LINE> if "tty" in self.config: <NEW_LINE> <INDENT> tty_path = os.path.realpath(os.path.join(os.path.sep, "dev", self.config["tty"])) <NEW_LINE> self.host = None <NEW_LINE> self.serial = serial.Serial(tty_path, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.host = self.config["host"] <NEW_LINE> self.serial = None <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.serial is not None: <NEW_LINE> <INDENT> self.serial.close() <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def register() -> DriverRegistration: <NEW_LINE> <INDENT> return DriverRegistration("tesla-smart", "Tesla-Smart", lambda config: TeslaSmart(config)) <NEW_LINE> <DEDENT> def set_tie(self, input_channel: int, video_output_channel: int, audio_output_channel: int) -> None: <NEW_LINE> <INDENT> validate_value(1 <= input_channel <= self.max_inputs, "Input channel is out of range") <NEW_LINE> validate_value(video_output_channel == 0, 'Video output channel is out of range') <NEW_LINE> validate_value(audio_output_channel == 0, 'Audio output channel is out of range') <NEW_LINE> self.__send_command(TeslaSmart.__SET_CHANNEL % input_channel.to_bytes(1, "big", signed=False)) <NEW_LINE> <DEDENT> def __send_command(self, command: bytes) -> None: <NEW_LINE> <INDENT> if self.serial is not None: <NEW_LINE> <INDENT> self.serial.write(command) <NEW_LINE> self.serial.reset_input_buffer() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with socket.create_connection((self.host, 5000)) as connection: <NEW_LINE> <INDENT> with connection.makefile(mode='wb') as stream: <NEW_LINE> <INDENT> stream.write(command) <NEW_LINE> stream.flush() | Tesla-Smart HDMI and SDI switch driver. | 625990797d43ff2487428102 |
class brect: <NEW_LINE> <INDENT> def __init__(self, l_pt, rsize, imsize): <NEW_LINE> <INDENT> self.Set_l_pt(l_pt) <NEW_LINE> self.Set_size(rsize) <NEW_LINE> self.image_size = imsize <NEW_LINE> <DEDENT> def Set_l_pt(self, l_pt): self.l_pt = TupleToList(l_pt) <NEW_LINE> def Set_size(self, rsize): self.size = TupleToList(rsize) <NEW_LINE> def RectOnImage(self, image): <NEW_LINE> <INDENT> pt1, pt2 = self.TwoPnt() <NEW_LINE> return image[pt1[1]:pt2[1], pt1[0]:pt2[0]] <NEW_LINE> <DEDENT> def TwoPnt(self): <NEW_LINE> <INDENT> return (self.l_pt), (self.l_pt[0] + self.size[0], self.l_pt[1] + self.size[1]) <NEW_LINE> <DEDENT> def Rect(self): <NEW_LINE> <INDENT> return (self.l_pt[0], self.l_pt[1], self.size[0], self.size[1]) <NEW_LINE> <DEDENT> def Check_Boundary(self): <NEW_LINE> <INDENT> return ( self.l_pt[0] >= 0 and self.l_pt[1] >= 0 and self.l_pt[0] + self.size[0] < self.image_size[0] and self.l_pt[1] + self.size[1] < self.image_size[1] ) <NEW_LINE> <DEDENT> def Correct_Boundary(self): <NEW_LINE> <INDENT> if self.Check_Boundary(): return False <NEW_LINE> if self.l_pt[0] < 0: self.l_pt[0] = 0 <NEW_LINE> if self.l_pt[1] < 0: self.l_pt[1] = 0 <NEW_LINE> tmp = self.l_pt[0] + self.size[0] - self.image_size[0] <NEW_LINE> if tmp >= 0: self.l_pt[0] -= tmp + 1 <NEW_LINE> tmp = self.l_pt[1] + self.size[1] - self.image_size[1] <NEW_LINE> if tmp >= 0: self.l_pt[1] -= tmp + 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> def Center(self): <NEW_LINE> <INDENT> return (self.l_pt[0] + self.size[0] // 2, self.l_pt[1] + self.size[1] // 2) | This is rect | 62599079adb09d7d5dc0bf44 |
class FamaMacBethResults(PanelResults): <NEW_LINE> <INDENT> def __init__(self, res: AttrDict): <NEW_LINE> <INDENT> super().__init__(res) <NEW_LINE> self._all_params = res.all_params <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_params(self) -> DataFrame: <NEW_LINE> <INDENT> return self._all_params | Results container for Fama MacBeth panel data models | 6259907923849d37ff852a93 |
class IPagesDirective(IBasicViewInformation): <NEW_LINE> <INDENT> for_ = GlobalObject( title=u"The interface or class this view is for.", required=False ) <NEW_LINE> permission = Permission( title=u"Permission", description=u"The permission needed to use the view.", required=True ) | Define multiple pages without repeating all of the parameters.
The pages directive allows multiple page views to be defined
without repeating the 'for', 'permission', 'class', 'layer',
'allowed_attributes', and 'allowed_interface' attributes. | 62599079009cb60464d02f19 |
class ZslJwtInvalidAudienceError(ZslJwtError): <NEW_LINE> <INDENT> pass | When the audience of the token does not match the
audience of the profile used to decode the token. | 6259907966673b3332c31dda |
class Node(): <NEW_LINE> <INDENT> def __init__(self, port, version, color): <NEW_LINE> <INDENT> key = Key() <NEW_LINE> self.pri_key = key.private_key <NEW_LINE> self.pub_key = key.public_key <NEW_LINE> self.port = port <NEW_LINE> self.version = version <NEW_LINE> self.color = color <NEW_LINE> self.peers = {} <NEW_LINE> self.mempool = [] <NEW_LINE> self.msg_cache = {} <NEW_LINE> self.interaction = Interaction(self) <NEW_LINE> <DEDENT> def connect_to(self, peer): <NEW_LINE> <INDENT> self.peers[peer['port']] = peer['pub_key'] <NEW_LINE> <DEDENT> def disconnect_from(self, peer_port): <NEW_LINE> <INDENT> if peer_port in self.peers: <NEW_LINE> <INDENT> self.peers.pop(peer_port, None) <NEW_LINE> <DEDENT> <DEDENT> def signed_trx(self, from_, to_, amount, pri_key): <NEW_LINE> <INDENT> trx = Transaction(from_, to_, amount) <NEW_LINE> trx.sign(pri_key) <NEW_LINE> return trx <NEW_LINE> <DEDENT> def transfer(self, from_=None, to_=None, amount=None): <NEW_LINE> <INDENT> if from_ is None and to_ is None and amount is None: <NEW_LINE> <INDENT> amount = random.randint(100, 700) <NEW_LINE> from_ = self.pub_key <NEW_LINE> if self.peers: <NEW_LINE> <INDENT> peer_port = random.choice(list(self.peers.keys())) <NEW_LINE> to_ = self.peers[peer_port] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_ = self.pub_key <NEW_LINE> <DEDENT> <DEDENT> trx = self.signed_trx(from_, to_, amount, self.pri_key) <NEW_LINE> self.mempool.append(trx) <NEW_LINE> return trx <NEW_LINE> <DEDENT> def check_msg(self, msg): <NEW_LINE> <INDENT> msg.elapse_ttl() <NEW_LINE> msg.visited(self.port) <NEW_LINE> return msg.ttl > 0 and msg.uuid not in self.msg_cache <NEW_LINE> <DEDENT> def receive_trx(self, msg): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def receive_blockchain(self, msg): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def serialize_id(port, pub_key): <NEW_LINE> <INDENT> return json.dumps( {'port': port, 'pub_key': pub_key.to_pem().decode('utf-8', 'ignore')}) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def deserialize_id(id_): <NEW_LINE> <INDENT> id_['pub_key'] = VerifyingKey.from_pem( id_['pub_key'].encode('utf-8', 'ignore')) <NEW_LINE> return id_ <NEW_LINE> <DEDENT> def routine(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def status(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> raise NotImplementedError | Generic node class | 62599079f9cc0f698b1c5fba |
class ProcessRequestItem(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_type = Field("ProcessRequestItem", const=True) <NEW_LINE> sequenceLinkId: fhirtypes.Integer = Field( None, alias="sequenceLinkId", title="Service instance", description="A service line number.", element_property=True, element_required=True, ) <NEW_LINE> sequenceLinkId__ext: fhirtypes.FHIRPrimitiveExtensionType = Field( None, alias="_sequenceLinkId", title="Extension field for ``sequenceLinkId``." ) <NEW_LINE> @classmethod <NEW_LINE> def elements_sequence(cls): <NEW_LINE> <INDENT> return ["id", "extension", "modifierExtension", "sequenceLinkId"] <NEW_LINE> <DEDENT> @root_validator(pre=True, allow_reuse=True) <NEW_LINE> def validate_required_primitive_elements_2068( cls, values: typing.Dict[str, typing.Any] ) -> typing.Dict[str, typing.Any]: <NEW_LINE> <INDENT> required_fields = [("sequenceLinkId", "sequenceLinkId__ext")] <NEW_LINE> _missing = object() <NEW_LINE> def _fallback(): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> errors: typing.List["ErrorWrapper"] = [] <NEW_LINE> for name, ext in required_fields: <NEW_LINE> <INDENT> field = cls.__fields__[name] <NEW_LINE> ext_field = cls.__fields__[ext] <NEW_LINE> value = values.get(field.alias, _missing) <NEW_LINE> if value not in (_missing, None): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ext_value = values.get(ext_field.alias, _missing) <NEW_LINE> missing_ext = True <NEW_LINE> if ext_value not in (_missing, None): <NEW_LINE> <INDENT> if isinstance(ext_value, dict): <NEW_LINE> <INDENT> missing_ext = len(ext_value.get("extension", [])) == 0 <NEW_LINE> <DEDENT> elif ( getattr(ext_value.__class__, "get_resource_type", _fallback)() == "FHIRPrimitiveExtension" ): <NEW_LINE> <INDENT> if ext_value.extension and len(ext_value.extension) > 0: <NEW_LINE> <INDENT> missing_ext = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> validate_pass = True <NEW_LINE> for validator in ext_field.type_.__get_validators__(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ext_value = validator(v=ext_value) <NEW_LINE> <DEDENT> except ValidationError as exc: <NEW_LINE> <INDENT> errors.append(ErrorWrapper(exc, loc=ext_field.alias)) <NEW_LINE> validate_pass = False <NEW_LINE> <DEDENT> <DEDENT> if not validate_pass: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if ext_value.extension and len(ext_value.extension) > 0: <NEW_LINE> <INDENT> missing_ext = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if missing_ext: <NEW_LINE> <INDENT> if value is _missing: <NEW_LINE> <INDENT> errors.append(ErrorWrapper(MissingError(), loc=field.alias)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> errors.append( ErrorWrapper(NoneIsNotAllowedError(), loc=field.alias) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(errors) > 0: <NEW_LINE> <INDENT> raise ValidationError(errors, cls) <NEW_LINE> <DEDENT> return values | Disclaimer: Any field name ends with ``__ext`` doesn't part of
Resource StructureDefinition, instead used to enable Extensibility feature
for FHIR Primitive Data Types.
Items to re-adjudicate.
List of top level items to be re-adjudicated, if none specified then the
entire submission is re-adjudicated. | 62599079aad79263cf430195 |
class CodeDict(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.code_dict = {} <NEW_LINE> self.schema = Schema({Extra: dict}) <NEW_LINE> self.schema(self.code_dict) <NEW_LINE> <DEDENT> def update(self,arg): <NEW_LINE> <INDENT> self.schema(arg.code_dict) <NEW_LINE> self.code_dict.update(arg.code_dict) <NEW_LINE> <DEDENT> def update_entry(self,dim_name,dim_short_id,dim_long_id): <NEW_LINE> <INDENT> if dim_name in self.code_dict: <NEW_LINE> <INDENT> if not dim_long_id: <NEW_LINE> <INDENT> dim_short_id = 'None' <NEW_LINE> if 'None' not in self.code_dict[dim_name]: <NEW_LINE> <INDENT> self.code_dict[dim_name].update({'None': 'None'}) <NEW_LINE> <DEDENT> <DEDENT> elif not dim_short_id: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dim_short_id = next(key for key,value in self.code_dict[dim_name].items() if value == dim_long_id) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> dim_short_id = str(len(self.code_dict[dim_name])) <NEW_LINE> self.code_dict[dim_name].update({dim_short_id: dim_long_id}) <NEW_LINE> <DEDENT> <DEDENT> elif not dim_short_id in self.code_dict[dim_name]: <NEW_LINE> <INDENT> self.code_dict[dim_name].update({dim_short_id: dim_long_id}) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not dim_short_id: <NEW_LINE> <INDENT> dim_short_id = '0' <NEW_LINE> <DEDENT> self.code_dict[dim_name] = OrderedDict({dim_short_id: dim_long_id}) <NEW_LINE> <DEDENT> return(dim_short_id) <NEW_LINE> <DEDENT> def get_dict(self): <NEW_LINE> <INDENT> return(self.code_dict) <NEW_LINE> <DEDENT> def get_list(self): <NEW_LINE> <INDENT> return({d1: list(d2.items()) for d1,d2 in self.code_dict.items()}) <NEW_LINE> <DEDENT> def set_dict(self,arg): <NEW_LINE> <INDENT> self.code_dict = arg <NEW_LINE> <DEDENT> def set_from_list(self,dimension_list): <NEW_LINE> <INDENT> self.code_dict = {d1: OrderedDict(d2) for d1,d2 in dimension_list.items()} | Class for handling code lists
>>> code_list = {'Country': {'FR': 'France'}}
>>> print(code_list)
{'Country': {'FR': 'France'}} | 6259907992d797404e38984a |
class Response(object): <NEW_LINE> <INDENT> STATUS_ACK = (1 << 0) <NEW_LINE> STATUS_WAIT = (1 << 1) <NEW_LINE> STATUS_FAULT = (1 << 2) <NEW_LINE> STATUS_INVALID = -1 <NEW_LINE> def __init__(self, status, data=None): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def ack(self): <NEW_LINE> <INDENT> return (self.status == self.STATUS_ACK) <NEW_LINE> <DEDENT> def wait(self): <NEW_LINE> <INDENT> return (self.status == self.STATUS_WAIT) <NEW_LINE> <DEDENT> def fault(self): <NEW_LINE> <INDENT> return (self.status == self.STATUS_FAULT) <NEW_LINE> <DEDENT> def invalid(self): <NEW_LINE> <INDENT> return (self.status == self.STATUS_INVALID) | Response class to hold the response from the send of a SWD request. | 625990795fdd1c0f98e5f95b |
class getCritChance(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.pkmn = BuildPokemonBattleWrapper() <NEW_LINE> self.crit = CritDelegate(0) <NEW_LINE> <DEDENT> def checkMods(self): <NEW_LINE> <INDENT> self.crit = CritDelegate(0) <NEW_LINE> for mod in range(0, len(CritDelegate.critMods)): <NEW_LINE> <INDENT> self.pkmn.statMods["CRT"] = mod <NEW_LINE> chance = self.crit.getCritChance(self.pkmn) <NEW_LINE> assert chance == CritDelegate.critMods[mod], "The Pkmn's crit mod should get the corresponding crit chance" <NEW_LINE> <DEDENT> <DEDENT> def checkBase(self): <NEW_LINE> <INDENT> self.pkmn.statMods["CRT"] = 0 <NEW_LINE> for base in range(0, len(CritDelegate.critMods)): <NEW_LINE> <INDENT> crit = CritDelegate(base) <NEW_LINE> chance = crit.getCritChance(self.pkmn) <NEW_LINE> assert chance == CritDelegate.critMods[base], "The Crit Delegate's base should get the corresponding crit chance" <NEW_LINE> <DEDENT> <DEDENT> def checkBaseAndMod(self): <NEW_LINE> <INDENT> base = 2 <NEW_LINE> mod = 2 <NEW_LINE> self.crit = CritDelegate(base) <NEW_LINE> self.pkmn.statMods["CRT"] = mod <NEW_LINE> chance = self.crit.getCritChance(self.pkmn) <NEW_LINE> assert chance == CritDelegate.critMods[base+mod], "The base and mod should compound to get the crit chance" | Test cases of getCritChance | 625990793317a56b869bf234 |
class User(namedtuple('User', ( 'id', 'slug', 'name', ))): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def from_api_object(obj): <NEW_LINE> <INDENT> user = User(id=obj['id'], name=obj['name'], slug=obj['slug']) <NEW_LINE> django_cache.set(('wp_user_by_id', user.id), user, _CACHE_TTL) <NEW_LINE> return user | Represents a WordPress user, i.e. the author of a post. | 6259907932920d7e50bc7a25 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.