code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class DescriptionWindow(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{DAD5408A-CE79-4C22-9225-185C0F1D2F7B}') <NEW_LINE> _idlflags_ = [] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{C0FC1503-7E6F-11D2-AABF-00C04FA375F1}', 10, 2)
Provides access to memebers of DescriptionWindow.
6259906216aa5153ce401bbf
class Declare(Basic): <NEW_LINE> <INDENT> __slots__ = ('_dtype','_variable','_intent','_value', '_static','_passed_from_dotted', '_external', '_module_variable') <NEW_LINE> _attribute_nodes = ('_variable', '_value') <NEW_LINE> def __init__( self, dtype, variable, intent=None, value=None, static=False, passed_from_dotted = False, external = False, module_variable = False ): <NEW_LINE> <INDENT> if isinstance(dtype, str): <NEW_LINE> <INDENT> dtype = datatype(dtype) <NEW_LINE> <DEDENT> elif not isinstance(dtype, DataType): <NEW_LINE> <INDENT> raise TypeError('datatype must be an instance of DataType.') <NEW_LINE> <DEDENT> if not isinstance(variable, Variable): <NEW_LINE> <INDENT> raise TypeError('var must be of type Variable, given {0}'.format(variable)) <NEW_LINE> <DEDENT> if variable.dtype != dtype: <NEW_LINE> <INDENT> raise ValueError('All variables must have the same dtype') <NEW_LINE> <DEDENT> if intent: <NEW_LINE> <INDENT> if not intent in ['in', 'out', 'inout']: <NEW_LINE> <INDENT> raise ValueError("intent must be one among {'in', 'out', 'inout'}") <NEW_LINE> <DEDENT> <DEDENT> if not isinstance(static, bool): <NEW_LINE> <INDENT> raise TypeError('Expecting a boolean for static attribute') <NEW_LINE> <DEDENT> if not isinstance(passed_from_dotted, bool): <NEW_LINE> <INDENT> raise TypeError('Expecting a boolean for passed_from_dotted attribute') <NEW_LINE> <DEDENT> if not isinstance(external, bool): <NEW_LINE> <INDENT> raise TypeError('Expecting a boolean for external attribute') <NEW_LINE> <DEDENT> if not isinstance(module_variable, bool): <NEW_LINE> <INDENT> raise TypeError('Expecting a boolean for module_variable attribute') <NEW_LINE> <DEDENT> self._dtype = dtype <NEW_LINE> self._variable = variable <NEW_LINE> self._intent = intent <NEW_LINE> self._value = value <NEW_LINE> self._static = static <NEW_LINE> self._passed_from_dotted = passed_from_dotted <NEW_LINE> self._external = external <NEW_LINE> self._module_variable = module_variable <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self._dtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def variable(self): <NEW_LINE> <INDENT> return self._variable <NEW_LINE> <DEDENT> @property <NEW_LINE> def intent(self): <NEW_LINE> <INDENT> return self._intent <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @property <NEW_LINE> def static(self): <NEW_LINE> <INDENT> return self._static <NEW_LINE> <DEDENT> @property <NEW_LINE> def passed_from_dotted(self): <NEW_LINE> <INDENT> return self._passed_from_dotted <NEW_LINE> <DEDENT> @property <NEW_LINE> def external(self): <NEW_LINE> <INDENT> return self._external <NEW_LINE> <DEDENT> @property <NEW_LINE> def module_variable(self): <NEW_LINE> <INDENT> return self._module_variable <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Declare({})'.format(repr(self.variable))
Represents a variable declaration in the code. Parameters ---------- dtype : DataType The type for the declaration. variable(s) A single variable or an iterable of Variables. If iterable, all Variables must be of the same type. intent: None, str one among {'in', 'out', 'inout'} value: PyccelAstNode variable value static: bool True for a static declaration of an array. external: bool True for a function declared through a header module_variable : bool True for a variable which belongs to a module Examples -------- >>> from pyccel.ast.core import Declare, Variable >>> Declare('int', Variable('int', 'n')) Declare(NativeInteger(), (n,), None) >>> Declare('float', Variable('float', 'x'), intent='out') Declare(NativeFloat(), (x,), out)
6259906201c39578d7f142a6
class Solution(object): <NEW_LINE> <INDENT> def reverseKGroup(self, head, k): <NEW_LINE> <INDENT> dummy = ListNode() <NEW_LINE> curr_dummy = dummy <NEW_LINE> curr_dummy.next = head <NEW_LINE> ptr = head <NEW_LINE> while ptr: <NEW_LINE> <INDENT> stack = [] <NEW_LINE> for i in range(k): <NEW_LINE> <INDENT> if ptr: <NEW_LINE> <INDENT> stack.append(ptr) <NEW_LINE> ptr = ptr.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dummy.next <NEW_LINE> <DEDENT> <DEDENT> tmp = ptr <NEW_LINE> for i in range(k): <NEW_LINE> <INDENT> curr_dummy.next = stack.pop() <NEW_LINE> curr_dummy = curr_dummy.next <NEW_LINE> <DEDENT> curr_dummy.next = tmp <NEW_LINE> <DEDENT> return dummy.next
stack: use stack to reverse list time: O(n) space: O(k)
62599062796e427e5384fe59
class TrelloAPI(object): <NEW_LINE> <INDENT> def __init__(self, stats, config): <NEW_LINE> <INDENT> self.stats = stats <NEW_LINE> self.key = config['apikey'] <NEW_LINE> self.token = config['token'] <NEW_LINE> self.username = config['user'] if "user" in config else "me" <NEW_LINE> self.board_links = split(config['board_links']) <NEW_LINE> self.board_ids = self.board_links_to_ids() <NEW_LINE> <DEDENT> def get_actions(self, filters, since=None, before=None, limit=1000): <NEW_LINE> <INDENT> if limit > 1000: <NEW_LINE> <INDENT> raise NotImplementedError( "Fetching more than 1000 items is not implemented") <NEW_LINE> <DEDENT> resp = self.stats.session.open( "{0}/members/{1}/actions?{2}".format( self.stats.url, self.username, urllib.urlencode({ "key": self.key, "token": self.token, "filter": filters, "limit": limit, "since": str(since), "before": str(before)}))) <NEW_LINE> actions = json.loads(resp.read()) <NEW_LINE> log.data(pretty(actions)) <NEW_LINE> actions = [act for act in actions if act['data'] ['board']['id'] in self.board_ids] <NEW_LINE> return actions <NEW_LINE> <DEDENT> def board_links_to_ids(self): <NEW_LINE> <INDENT> resp = self.stats.session.open( "{0}/members/{1}/boards?{2}".format( self.stats.url, self.username, urllib.urlencode({ "key": self.key, "token": self.token, "fields": "shortLink"}))) <NEW_LINE> boards = json.loads(resp.read()) <NEW_LINE> return [board['id'] for board in boards if self.board_links == [""] or board['shortLink'] in self.board_links]
Trello API
62599062460517430c432bc5
class WorkspaceWidgetTest(GuiTest): <NEW_LINE> <INDENT> def test_widget_creation(self): <NEW_LINE> <INDENT> widget = WorkspaceTreeWidget() <NEW_LINE> self.assertTrue(widget is not None) <NEW_LINE> sip.delete(widget)
Minimal testing as it is exported from C++
625990628e7ae83300eea771
class GCSPersistor(Persistor): <NEW_LINE> <INDENT> def __init__(self, bucket_name): <NEW_LINE> <INDENT> from google.cloud import storage <NEW_LINE> super(GCSPersistor, self).__init__() <NEW_LINE> self.storage_client = storage.Client() <NEW_LINE> self._ensure_bucket_exists(bucket_name) <NEW_LINE> self.bucket_name = bucket_name <NEW_LINE> self.bucket = self.storage_client.bucket(bucket_name) <NEW_LINE> <DEDENT> def list_models(self, project): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blob_iterator = self.bucket.list_blobs( prefix=self._project_prefix(project)) <NEW_LINE> return [self._project_and_model_from_filename(b.name)[1] for b in blob_iterator] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.warn("Failed to list models for project {} in " "google cloud storage. {}".format(project, e)) <NEW_LINE> return [] <NEW_LINE> <DEDENT> <DEDENT> def list_projects(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blob_iterator = self.bucket.list_blobs() <NEW_LINE> projects_set = {self._project_and_model_from_filename(b.name)[0] for b in blob_iterator} <NEW_LINE> return list(projects_set) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.warning("Failed to list projects in " "google cloud storage. {}".format(e)) <NEW_LINE> return [] <NEW_LINE> <DEDENT> <DEDENT> def _ensure_bucket_exists(self, bucket_name): <NEW_LINE> <INDENT> from google.cloud import exceptions <NEW_LINE> try: <NEW_LINE> <INDENT> self.storage_client.create_bucket(bucket_name) <NEW_LINE> <DEDENT> except exceptions.Conflict: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def _persist_tar(self, file_key, tar_path): <NEW_LINE> <INDENT> blob = self.bucket.blob(file_key) <NEW_LINE> blob.upload_from_filename(tar_path) <NEW_LINE> <DEDENT> def _retrieve_tar(self, target_filename): <NEW_LINE> <INDENT> blob = self.bucket.blob(target_filename) <NEW_LINE> blob.download_to_filename(target_filename)
Store models on Google Cloud Storage. Fetches them when needed, instead of storing them on the local disk.
62599062fff4ab517ebcef0a
class loadCode(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.enabled = False <NEW_LINE> self.checked = False <NEW_LINE> <DEDENT> def onClick(self): <NEW_LINE> <INDENT> codhoja = "{}{}{}".format(getRow.value, getCol.value, getQuad.value) <NEW_LINE> if getRow.enabled: <NEW_LINE> <INDENT> getRow.enabled = False <NEW_LINE> getCol.enabled = False <NEW_LINE> getQuad.enabled = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = pythonaddins.MessageBox("Confirma que desea terminar el proyecto \n en la hoja {}".format(codhoja), "Advertencia", 4) <NEW_LINE> if r == u"Yes": <NEW_LINE> <INDENT> getRow.enabled = True <NEW_LINE> getCol.enabled = True <NEW_LINE> getQuad.enabled = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def disableLoad(self): <NEW_LINE> <INDENT> if getRow.value != "" and getCol.value != "" and getQuad.value != "": <NEW_LINE> <INDENT> loadCode.enabled = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loadCode.enabled = False
Implementation for addin_addin.loadCode (Button)
62599062be8e80087fbc076a
class SendMessageGeoLocationAction(TLObject): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> ID = 0x176f8ba1 <NEW_LINE> QUALNAME = "types.SendMessageGeoLocationAction" <NEW_LINE> def __init__(self, ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "SendMessageGeoLocationAction": <NEW_LINE> <INDENT> return SendMessageGeoLocationAction() <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> return b.getvalue()
Attributes: LAYER: ``112`` Attributes: ID: ``0x176f8ba1`` No parameters required.
6259906244b2445a339b74d2
class ApplicationGatewaySslPredefinedPolicy(SubResource): <NEW_LINE> <INDENT> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'}, 'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.cipher_suites = kwargs.get('cipher_suites', None) <NEW_LINE> self.min_protocol_version = kwargs.get('min_protocol_version', None)
An Ssl predefined policy. :param id: Resource ID. :type id: str :param name: Name of the Ssl predefined policy. :type name: str :param cipher_suites: Ssl cipher suites to be enabled in the specified order for application gateway. :type cipher_suites: list[str or ~azure.mgmt.network.v2021_02_01.models.ApplicationGatewaySslCipherSuite] :param min_protocol_version: Minimum version of Ssl protocol to be supported on application gateway. Possible values include: "TLSv1_0", "TLSv1_1", "TLSv1_2". :type min_protocol_version: str or ~azure.mgmt.network.v2021_02_01.models.ApplicationGatewaySslProtocol
62599062f548e778e596cc6d
class HistoryPage(Page): <NEW_LINE> <INDENT> def __init__(self, driver): <NEW_LINE> <INDENT> Page.__init__(self, driver) <NEW_LINE> self.driver = driver <NEW_LINE> self._history_dialog = (By.XPATH, '//UIAApplication[1]/UIAWindow[1]/UIACollectionView[1]/UIACollectionCell[3]') <NEW_LINE> <DEDENT> @property <NEW_LINE> def history_dialog(self): <NEW_LINE> <INDENT> return self.driver.find_element(*self._history_dialog)
ABP native dialog object which opened when user click on middle bottom button
625990627d847024c075dab9
class InputContactMessageContent(BaseType): <NEW_LINE> <INDENT> def __init__(self, phone_number, first_name, last_name=None, vcard=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.phone_number = phone_number <NEW_LINE> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.vcard = vcard
Represents the content of a contact message to be sent as the result of an inline query. Parameters ---------- phone_number : String Contact's phone number first_name : String Contact's first name last_name : String, optional Contact's last name vcard : String, optional Additional data about the contact in the form of a vCard, 0-2048 bytes
6259906232920d7e50bc772b
class Resize(object): <NEW_LINE> <INDENT> def __init__(self, output_size): <NEW_LINE> <INDENT> assert isinstance(output_size, (int, tuple)) <NEW_LINE> if isinstance(output_size, int): <NEW_LINE> <INDENT> self.output_size = (output_size,output_size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.output_size = output_size <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> img1 = sample['img1'] <NEW_LINE> h, w = img1.shape[:2] <NEW_LINE> if self.output_size == (h,w): <NEW_LINE> <INDENT> return sample <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size <NEW_LINE> <DEDENT> new_h, new_w = int(new_h), int(new_w) <NEW_LINE> for elem in sample.keys(): <NEW_LINE> <INDENT> if 'meta' in elem: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> tmp = sample[elem] <NEW_LINE> if elem=='img1' or elem=='img2' or elem=='ref_img': <NEW_LINE> <INDENT> flagval = cv2.INTER_CUBIC <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flagval = cv2.INTER_NEAREST <NEW_LINE> <DEDENT> tmp = cv2.resize(tmp,dsize=(new_w,new_h),interpolation=flagval) <NEW_LINE> sample[elem]=tmp <NEW_LINE> <DEDENT> return sample
Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same.
6259906266673b3332c31ae1
class RunScriptTest(cros_test_lib.MockTempDirTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.stats_module_mock = stats_unittest.StatsModuleMock() <NEW_LINE> self.StartPatcher(self.stats_module_mock) <NEW_LINE> self.PatchObject(cros, '_RunSubCommand', autospec=True) <NEW_LINE> <DEDENT> def testStatsUpload(self, upload_count=1, return_value=0): <NEW_LINE> <INDENT> return_value = cros.main(['chrome-sdk', '--board', 'lumpy']) <NEW_LINE> self.assertEquals(stats.StatsUploader._Upload.call_count, upload_count) <NEW_LINE> self.assertEquals(return_value, return_value) <NEW_LINE> <DEDENT> def testStatsUploadError(self): <NEW_LINE> <INDENT> self.stats_module_mock.stats_mock.init_exception = True <NEW_LINE> with cros_test_lib.LoggingCapturer(): <NEW_LINE> <INDENT> self.testStatsUpload(upload_count=0)
Test the main functionality.
6259906256ac1b37e6303859
class UnreachableRepositoryURLDetected(TwineException): <NEW_LINE> <INDENT> pass
An upload attempt was detected to a URL without a protocol prefix. All repository URLs must have a protocol (e.g., ``https://``).
62599062442bda511e95d8cc
class Attachment(EmbeddedDocument): <NEW_LINE> <INDENT> category = StringField(required=True) <NEW_LINE> aid = StringField(required=True)
Fields: * category: StringField **REQUIRED** * aid: StringField **REQUIRED** **category** is the name of the locationdata collection to which the attachment refers. **aid** is the id (not mongodb id, but the back-end's id) of the object to which the attachment refers ("foreignkey").
62599062627d3e7fe0e08570
class CookieMW(object): <NEW_LINE> <INDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> request.meta['cookiejar'] = 1
cookie middlewares
62599062be8e80087fbc076c
class VimLCode(NoneditableTextObject): <NEW_LINE> <INDENT> def __init__(self, parent, token): <NEW_LINE> <INDENT> self._code = token.code.replace("\\`", "`").strip() <NEW_LINE> NoneditableTextObject.__init__(self, parent, token) <NEW_LINE> <DEDENT> def _update(self, done): <NEW_LINE> <INDENT> self.overwrite(_vim.eval(self._code)) <NEW_LINE> return True
See module docstring.
62599062a8370b77170f1ab4
class PairwiseAlignment: <NEW_LINE> <INDENT> def __init__(self, query, hit, score): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> self.hit = hit <NEW_LINE> self.score = score
Structure to store the numbers associated with a Needleman Wunsch pairwise alignment. Keeps track of two sequence ids (represented by Sequence object) and associated alignment score (float)
625990621f5feb6acb1642d0
class AgentUser(Base): <NEW_LINE> <INDENT> __tablename__ = 'agent_users' <NEW_LINE> Id = Column(Integer, primary_key = True) <NEW_LINE> AADUserId = Column(String) <NEW_LINE> Description = Column(String) <NEW_LINE> Role = Column(String) <NEW_LINE> SubscriptionId = Column(String) <NEW_LINE> ObjectId = Column(String) <NEW_LINE> @staticmethod <NEW_LINE> def Create(user): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> session.add(user) <NEW_LINE> session.commit() <NEW_LINE> return <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ListAllUsers(): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> users = session.query(AgentUser).filter_by(Role = "User").all() <NEW_LINE> session.close() <NEW_LINE> return users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ListAllBySubscriptionId(subscriptionId): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> users = session.query(AgentUser).filter_by(SubscriptionId = subscriptionId).all() <NEW_LINE> session.close() <NEW_LINE> return users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def GetUser(subscriptionId, userId): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> users = session.query(AgentUser).filter_by(SubscriptionId = subscriptionId, AADUserId = userId).first() <NEW_LINE> session.close() <NEW_LINE> return users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ListAllAdmin(): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> users = session.query(AgentUser).filter_by(Role = "Admin").all() <NEW_LINE> session.close() <NEW_LINE> return users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def GetAdmin(userId): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> users = session.query(AgentUser).filter_by(AADUserId = userId, Role="Admin").first() <NEW_LINE> session.close() <NEW_LINE> return users <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def DeleteUser(subscriptionId, userId): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> user = AgentUser.GetUser(subscriptionId, userId) <NEW_LINE> session.delete(user) <NEW_LINE> session.commit() <NEW_LINE> session.close() <NEW_LINE> return <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def DeleteAdmin(userId): <NEW_LINE> <INDENT> session = Session() <NEW_LINE> admin = AgentUser.GetAdmin(userId) <NEW_LINE> session.delete(admin) <NEW_LINE> session.commit() <NEW_LINE> session.close() <NEW_LINE> return
description of class
6259906221bff66bcd72434b
class ComputeFirewallsDeleteRequest(_messages.Message): <NEW_LINE> <INDENT> firewall = _messages.StringField(1, required=True) <NEW_LINE> project = _messages.StringField(2, required=True)
A ComputeFirewallsDeleteRequest object. Fields: firewall: Name of the firewall resource to delete. project: Project ID for this request.
62599062adb09d7d5dc0bc50
class Association: <NEW_LINE> <INDENT> __slots__=['owner', 'peer_associator'] <NEW_LINE> def __init__(self, owner, peer_associator): <NEW_LINE> <INDENT> self.owner = owner <NEW_LINE> self.peer_associator = peer_associator
This base class provides the behaviour common to all types of association containers.
62599062d7e4931a7ef3d6f8
class ResolveResult(object): <NEW_LINE> <INDENT> def __init__(self, address_infos: List[AddressInfo], dns_infos: Optional[List[DNSInfo]]=None): <NEW_LINE> <INDENT> self._address_infos = address_infos <NEW_LINE> self._dns_infos = dns_infos <NEW_LINE> <DEDENT> @property <NEW_LINE> def addresses(self) -> Sequence[AddressInfo]: <NEW_LINE> <INDENT> return self._address_infos <NEW_LINE> <DEDENT> @property <NEW_LINE> def dns_infos(self) -> List[DNSInfo]: <NEW_LINE> <INDENT> return self._dns_infos <NEW_LINE> <DEDENT> @property <NEW_LINE> def first_ipv4(self) -> Optional[AddressInfo]: <NEW_LINE> <INDENT> for info in self._address_infos: <NEW_LINE> <INDENT> if info.family == socket.AF_INET: <NEW_LINE> <INDENT> return info <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def first_ipv6(self) -> Optional[AddressInfo]: <NEW_LINE> <INDENT> for info in self._address_infos: <NEW_LINE> <INDENT> if info.family == socket.AF_INET6: <NEW_LINE> <INDENT> return info <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def shuffle(self): <NEW_LINE> <INDENT> random.shuffle(self._address_infos) <NEW_LINE> <DEDENT> def rotate(self): <NEW_LINE> <INDENT> item = self._address_infos.pop(0) <NEW_LINE> self._address_infos.append(item)
DNS resolution information.
62599062379a373c97d9a70a
class Solution: <NEW_LINE> <INDENT> def searchRange(self, nums: 'List[int]', target: 'int') -> 'List[int]': <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return [-1, -1] <NEW_LINE> <DEDENT> self.nums = [float('-inf')]+nums+[float('inf')] <NEW_LINE> self.target = target <NEW_LINE> l = self.fl(0, len(self.nums)-1, target) <NEW_LINE> h = self.fh(0, len(self.nums)-1, target) <NEW_LINE> return [-1, -1] if l == -1 else [l-1, h-1] <NEW_LINE> <DEDENT> def fl(self, l, h, tg): <NEW_LINE> <INDENT> if l+1 == h: <NEW_LINE> <INDENT> if self.nums[h] == tg: <NEW_LINE> <INDENT> return h <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> if l <= h: <NEW_LINE> <INDENT> m = (l+h)//2 <NEW_LINE> if self.nums[m] < tg: <NEW_LINE> <INDENT> return self.fl(m, h, tg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.fl(l, m, tg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def fh(self, l, h, tg): <NEW_LINE> <INDENT> if l+1 == h: <NEW_LINE> <INDENT> if self.nums[l] == tg: <NEW_LINE> <INDENT> return l <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> if l <= h: <NEW_LINE> <INDENT> m = (l+h)//2 <NEW_LINE> if self.nums[m] > tg: <NEW_LINE> <INDENT> return self.fh(l, m, tg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.fh(m, h, tg)
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1].
62599062d486a94d0ba2d6af
class CasperTestCase(LiveServerTestCase): <NEW_LINE> <INDENT> use_phantom_disk_cache = False <NEW_LINE> no_colors = True <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CasperTestCase, self).__init__(*args, **kwargs) <NEW_LINE> if self.use_phantom_disk_cache: <NEW_LINE> <INDENT> StaticFilesHandler.serve = staticfiles_handler_serve <NEW_LINE> <DEDENT> <DEDENT> def casper(self, test_filename, **kwargs): <NEW_LINE> <INDENT> kwargs.update({ 'load-images': 'no', 'disk-cache': 'yes' if self.use_phantom_disk_cache else 'no', 'ignore-ssl-errors': 'yes', 'url-base': self.live_server_url, 'log-level': 'debug' if settings.DEBUG else 'error', }) <NEW_LINE> cn = settings.SESSION_COOKIE_NAME <NEW_LINE> if cn in self.client.cookies: <NEW_LINE> <INDENT> kwargs['cookie-' + cn] = self.client.cookies[cn].value <NEW_LINE> <DEDENT> cmd = ['casperjs', 'test'] <NEW_LINE> if self.no_colors: <NEW_LINE> <INDENT> cmd.append('--no-colors') <NEW_LINE> <DEDENT> if settings.DEBUG: <NEW_LINE> <INDENT> cmd.append('--verbose') <NEW_LINE> <DEDENT> cmd.extend([('--%s=%s' % i) for i in kwargs.iteritems()]) <NEW_LINE> cmd.append(test_filename) <NEW_LINE> p = Popen(cmd, stdout=PIPE, stderr=PIPE, cwd=os.path.dirname(test_filename)) <NEW_LINE> out, err = p.communicate() <NEW_LINE> if p.returncode != 0: <NEW_LINE> <INDENT> sys.stdout.write(out) <NEW_LINE> sys.stderr.write(err) <NEW_LINE> <DEDENT> return p.returncode == 0
LiveServerTestCase subclass that can invoke CasperJS tests.
625990622ae34c7f260ac7cd
class PresolvedQEnv2(BaseQEnv): <NEW_LINE> <INDENT> def __init__(self, hamiltonian: Sequence[HamiltonianData], t: float, N: int, initial_state: Qobj = None, target_state: Qobj = None, initial_h_x=-4): <NEW_LINE> <INDENT> super().__init__(initial_state, target_state) <NEW_LINE> self.hamiltonian = hamiltonian <NEW_LINE> self.initial_h_x = initial_h_x <NEW_LINE> self.N = N <NEW_LINE> self.t = t / 2 <NEW_LINE> self.dt = self.t / N <NEW_LINE> self.current_step: int = 0 <NEW_LINE> self.current_h_x = None <NEW_LINE> self.bloch_figure = None <NEW_LINE> self.current_protocol = [] <NEW_LINE> self.presolved_data = {} <NEW_LINE> logger.info(f"Created PresolvedQEnv2 with N: {N}, t: {t}") <NEW_LINE> <DEDENT> def step(self, action: int): <NEW_LINE> <INDENT> assert action == 0 or action == 1, 'Action has to be 0 or 1.' <NEW_LINE> self.current_h_x = self.current_h_x if action is 0 else -self.current_h_x <NEW_LINE> self.current_protocol.append(action) <NEW_LINE> reward = self.get_reward() <NEW_LINE> done = self.current_step == self.N - 1 <NEW_LINE> self.current_step += 1 <NEW_LINE> return self.get_state(), reward, done, {} <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_reward(self) -> float: <NEW_LINE> <INDENT> if self.current_step != self.N - 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> protocol_int = convert_bit_list_to_int(self.current_protocol) <NEW_LINE> if protocol_int in self.presolved_data: <NEW_LINE> <INDENT> return self.presolved_data[protocol_int] <NEW_LINE> <DEDENT> simulation = EnvSimulation(self.hamiltonian, psi0=self.initial_state, t_list=np.linspace(0, self.t, self.N * 10), e_ops=[sigmax(), sigmay(), sigmaz()]) <NEW_LINE> simulation.solve_with_actions(self.current_protocol, self.N) <NEW_LINE> final_state = simulation.result.states[-1] <NEW_LINE> _fidelity = fidelity(final_state, self.target_state) ** 2 <NEW_LINE> self.presolved_data[protocol_int] = _fidelity <NEW_LINE> return _fidelity <NEW_LINE> <DEDENT> def reset(self) -> np.ndarray: <NEW_LINE> <INDENT> self.current_step = 0 <NEW_LINE> self.current_h_x = self.initial_h_x <NEW_LINE> self.current_protocol = [] <NEW_LINE> self.simulation = 1 <NEW_LINE> return super().reset() <NEW_LINE> <DEDENT> def get_state(self) -> np.ndarray: <NEW_LINE> <INDENT> return np.array((self.current_step * self.dt, self.current_h_x)) <NEW_LINE> <DEDENT> def get_random_action(self): <NEW_LINE> <INDENT> return random.getrandbits(1)
state / observation: S = (t, h_x(t)) action: A = 0, 1; corresponding to stay (dh = 0), switch sign (dh = +-8).
6259906266673b3332c31ae3
class Settings(dict, DottedAccessMixin): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.update(*args, **kwargs) <NEW_LINE> <DEDENT> def __setitem__(self, name, value): <NEW_LINE> <INDENT> if isinstance(value, Mapping): <NEW_LINE> <INDENT> value = Settings(value) <NEW_LINE> <DEDENT> super().__setitem__(name, value) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self[name] = value <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self.__dict__.update(state) <NEW_LINE> <DEDENT> def setdefault(self, name, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self[name] = default <NEW_LINE> <DEDENT> return self[name] <NEW_LINE> <DEDENT> def update(*args, **kwargs): <NEW_LINE> <INDENT> if len(args) > 2: <NEW_LINE> <INDENT> raise TypeError( f"update() takes at most 2 positional arguments " f"({len(args)} given)" ) <NEW_LINE> <DEDENT> elif not args: <NEW_LINE> <INDENT> raise TypeError("update() takes at least 1 argument (0 given)") <NEW_LINE> <DEDENT> self = args[0] <NEW_LINE> other = args[1] if len(args) >= 2 else () <NEW_LINE> if isinstance(other, Mapping): <NEW_LINE> <INDENT> for name in other: <NEW_LINE> <INDENT> self[name] = other[name] <NEW_LINE> <DEDENT> <DEDENT> elif hasattr(other, "keys"): <NEW_LINE> <INDENT> for name in other.keys(): <NEW_LINE> <INDENT> self[name] = other[name] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for name, value in other: <NEW_LINE> <INDENT> self[name] = value <NEW_LINE> <DEDENT> <DEDENT> for name, value in kwargs.items(): <NEW_LINE> <INDENT> self[name] = value
Dict-ish container for settings. Provides access to settings via regular item access, attribute access, and dotted names:: >>> settings = Settings() >>> settings['name'] = 'name' >>> settings['name'] 'name' >>> settings.name = 'name' >>> settings.name 'name' >>> settings.set_dotted('NAMESPACE.name', 'nested name') >>> settings.get_dotted('NAMESPACE.name') 'nested name' These are all equivalent:: >>> settings['NAMESPACE']['name'] 'nested name' >>> settings.NAMESPACE.name 'nested name' >>> settings.get_dotted('NAMESPACE.name') 'nested name' Adding an item with a dotted name will create nested settings like so:: >>> settings = Settings() >>> settings.set_dotted('NAMESPACE.name', 'nested name') >>> settings {'NAMESPACE': {'name': 'nested name'}} Implementation Notes ==================== This is a subclass of dict because certain settings consumers, such as ``logging.dictConfig`` from the standard library, won't work with a non-dict mapping type because they do things like ``isinstance(something, dict)``. Where a setting has a name that's the same as an attribute name (e.g., ``get`` or ``update``), the attribute will take precedence. To get at such a setting, item access must be used. This is necessary because we can't allow settings to override the dict interface (because this might cause problems with outside consumers of the settings that aren't aware of the magic we're doing here).
62599062009cb60464d02c1e
class Migration(object): <NEW_LINE> <INDENT> timestamp = None <NEW_LINE> def run(self): <NEW_LINE> <INDENT> pass
App Engine data migration The timestamp is used to order migrations. No output is shown to the user, so make liberal use logging. Before running a migration on produciton data, download portitions of real data into an sample application using the bulk exporter
625990628e71fb1e983bd1b2
class MinimaxPlayer(IsolationPlayer): <NEW_LINE> <INDENT> def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.minimax(game, self.search_depth) <NEW_LINE> <DEDENT> except SearchTimeout: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return best_move <NEW_LINE> <DEDENT> def minimax(self, game, depth): <NEW_LINE> <INDENT> self.time_test() <NEW_LINE> best_score = float("-inf") <NEW_LINE> best_move = (-1, -1) <NEW_LINE> for m in game.get_legal_moves(): <NEW_LINE> <INDENT> v = self.min_value(game.forecast_move(m), depth - 1) <NEW_LINE> if v > best_score: <NEW_LINE> <INDENT> best_score = v <NEW_LINE> best_move = m <NEW_LINE> <DEDENT> <DEDENT> return best_move <NEW_LINE> <DEDENT> def min_value(self, gameState, depth): <NEW_LINE> <INDENT> self.time_test() <NEW_LINE> util = gameState.utility(gameState.active_player) <NEW_LINE> if (util != 0): <NEW_LINE> <INDENT> return util <NEW_LINE> <DEDENT> v = float("inf") <NEW_LINE> if depth <= 0: <NEW_LINE> <INDENT> return self.score(gameState, self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for m in gameState.get_legal_moves(): <NEW_LINE> <INDENT> v = min(v, self.max_value(gameState.forecast_move(m), depth - 1)) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> <DEDENT> def max_value(self, gameState, depth): <NEW_LINE> <INDENT> self.time_test() <NEW_LINE> util = gameState.utility(gameState.active_player) <NEW_LINE> if (util != 0): <NEW_LINE> <INDENT> return util <NEW_LINE> <DEDENT> v = float("-inf") <NEW_LINE> if depth <= 0: <NEW_LINE> <INDENT> return self.score(gameState, self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for m in gameState.get_legal_moves(): <NEW_LINE> <INDENT> v = max(v, self.min_value(gameState.forecast_move(m), depth - 1)) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> <DEDENT> def time_test(self): <NEW_LINE> <INDENT> if (self.time_left() < self.TIMER_THRESHOLD): <NEW_LINE> <INDENT> if Verbose: <NEW_LINE> <INDENT> print("Timeout") <NEW_LINE> <DEDENT> raise SearchTimeout()
Game-playing agent that chooses a move using depth-limited minimax search. You must finish and test this player to make sure it properly uses minimax to return a good move before the search time limit expires.
625990627d43ff2487427f83
@frozen_after_init <NEW_LINE> @dataclass(unsafe_hash=True) <NEW_LINE> class StyleRequest(Generic[_FS], metaclass=ABCMeta): <NEW_LINE> <INDENT> field_set_type: ClassVar[Type[_FS]] <NEW_LINE> field_sets: Collection[_FS] <NEW_LINE> prior_formatter_result: Optional[Snapshot] = None <NEW_LINE> def __init__( self, field_sets: Iterable[_FS], *, prior_formatter_result: Optional[Snapshot] = None, ) -> None: <NEW_LINE> <INDENT> self.field_sets = Collection[_FS](field_sets) <NEW_LINE> self.prior_formatter_result = prior_formatter_result
A request to style or lint a collection of `FieldSet`s. Should be subclassed for a particular style engine in order to support autoformatting or linting.
62599062d268445f2663a6d0
class AppleSignInAsyncApi(Shared): <NEW_LINE> <INDENT> def __init__(self, config: AppleConfig): <NEW_LINE> <INDENT> super().__init__(config) <NEW_LINE> self._session = ClientSession() <NEW_LINE> <DEDENT> async def try_auth( self, code: str ) -> Optional[Union[AppleSignInSuccessRet, AppleSignInFailureRet]]: <NEW_LINE> <INDENT> headers, data = self._make_up_data(code) <NEW_LINE> resp = await self._session.post( self.ACCESS_TOKEN_URL, data=data, headers=headers ) <NEW_LINE> if not (200 <= resp.status < 300): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ret = await resp.json() <NEW_LINE> assert isinstance(ret, dict) <NEW_LINE> if "error" in ret: <NEW_LINE> <INDENT> return AppleSignInFailureRet(**ret) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return AppleSignInSuccessRet(**ret)
苹果登陆异步处理接口 Apple SignIn async process interface
625990621f5feb6acb1642d2
@singleton <NEW_LINE> class TCOrderValuePerDay(TradingControl): <NEW_LINE> <INDENT> def __init__(self, default_max, max_amount_dict=None, on_fail=None): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(on_fail=on_fail) <NEW_LINE> self._max_amount_dict = max_amount_dict if max_amount_dict else {} <NEW_LINE> self._default_max = abs(default_max) <NEW_LINE> self.add_control({}) <NEW_LINE> self._asset_quota = dict((asset,0) for asset in self._max_amount_dict) <NEW_LINE> self._current_dt = None <NEW_LINE> <DEDENT> def add_control(self, max_amount_dict): <NEW_LINE> <INDENT> self._max_amount_dict = {**self._max_amount_dict, **max_amount_dict} <NEW_LINE> for asset in self._max_amount_dict: <NEW_LINE> <INDENT> self._max_amount_dict[asset] = abs(self._max_amount_dict[asset]) <NEW_LINE> <DEDENT> <DEDENT> def _reset_quota(self): <NEW_LINE> <INDENT> for asset in self._asset_quota: <NEW_LINE> <INDENT> self._asset_quota[asset] = 0 <NEW_LINE> <DEDENT> <DEDENT> def validate(self, order, dt, context, on_fail=noop): <NEW_LINE> <INDENT> amount = order.quantity <NEW_LINE> asset = order.asset <NEW_LINE> if self._current_dt != dt.date(): <NEW_LINE> <INDENT> self._reset_quota() <NEW_LINE> self._current_dt = dt.date() <NEW_LINE> <DEDENT> max_allowed = self._max_amount_dict.get(asset, self._default_max) <NEW_LINE> if not max_allowed: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> max_used = self._asset_quota.get(asset, 0) <NEW_LINE> price = context.data_portal.current(asset, 'close') <NEW_LINE> value = abs(amount*price) <NEW_LINE> estimated = abs(value)+max_used <NEW_LINE> if estimated < max_allowed: <NEW_LINE> <INDENT> self._asset_quota[asset] = estimated <NEW_LINE> return True <NEW_LINE> <DEDENT> self._metric = max_used <NEW_LINE> self._limit = max_allowed <NEW_LINE> if self._on_fail: <NEW_LINE> <INDENT> self._on_fail(self, asset, dt, amount, context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> on_fail(self, asset, dt, amount, context) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def get_error_msg(self, asset, dt): <NEW_LINE> <INDENT> msg = f"Failed per day trade value control for {asset}" <NEW_LINE> msg = msg + f", total value {self._metric}" <NEW_LINE> msg = msg + f" against limit {self._limit}, on {dt}" <NEW_LINE> return msg
Class implementing max order value per asset per day.
625990624e4d562566373aee
class DummyStafflineExtractor(object): <NEW_LINE> <INDENT> staffline_distance_multiple = 2 <NEW_LINE> target_height = 10
A placeholder for StafflineExtractor. It only contains the constants necessary to scale the x coordinates.
6259906221bff66bcd72434d
class DescribeCheckConfigDetailRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Id = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Id = params.get("Id")
DescribeCheckConfigDetail请求参数结构体
62599062f548e778e596cc70
class Layer2D(Layer): <NEW_LINE> <INDENT> def __init__(self, activation_params={}, activation_type="random", normalize=config.gan.normalization, use_dropout=False, skip_conn=False): <NEW_LINE> <INDENT> super().__init__(activation_params=activation_params, activation_type=activation_type, normalize=normalize, use_dropout=use_dropout) <NEW_LINE> self.skip_module = None <NEW_LINE> self.skip_conn = skip_conn <NEW_LINE> if skip_conn == "random": <NEW_LINE> <INDENT> self.skip_conn = bool(np.random.choice([False, True])) <NEW_LINE> <DEDENT> <DEDENT> def is_linear(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def _create_normalization(self): <NEW_LINE> <INDENT> if self.normalize == "pixelwise": <NEW_LINE> <INDENT> return PixelwiseNorm() <NEW_LINE> <DEDENT> elif self.normalize == "batch": <NEW_LINE> <INDENT> return nn.BatchNorm2d(self.out_channels) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def create_skip_module(self, module): <NEW_LINE> <INDENT> if self.skip_conn: <NEW_LINE> <INDENT> skip_module = SkipModule(module) <NEW_LINE> if self.skip_module is not None: <NEW_LINE> <INDENT> skip_module.conv = self.skip_module.conv <NEW_LINE> <DEDENT> self.skip_module = skip_module <NEW_LINE> <DEDENT> <DEDENT> def create_module(self): <NEW_LINE> <INDENT> if self.skip_module is not None: <NEW_LINE> <INDENT> return self.skip_module <NEW_LINE> <DEDENT> return super().create_module()
Represents an generic 2d layer in the evolving model.
62599062cc0a2c111447c643
class DominantColorsAnnotation(proto.Message): <NEW_LINE> <INDENT> colors = proto.RepeatedField(proto.MESSAGE, number=1, message="ColorInfo",)
Set of dominant colors and their corresponding scores. Attributes: colors (Sequence[google.cloud.vision_v1p1beta1.types.ColorInfo]): RGB color values with their score and pixel fraction.
625990620a50d4780f706933
class PinwheelDialog(wx.Dialog): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> wx.Dialog.__init__(self, parent, wx.ID_ANY, "Add Pinwheel Command", size = (400, 225)) <NEW_LINE> self.directionPanel = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> self.directionChoices = ['Clockwise', 'Counter-clockwise'] <NEW_LINE> self.directionChoicesValues = [0, 1] <NEW_LINE> self.directionRadioBox = wx.RadioBox(self, wx.ID_ANY, "Direction", choices = self.directionChoices, majorDimension = 2, style = wx.RA_SPECIFY_COLS) <NEW_LINE> self.directionRadioBox.SetSelection(0) <NEW_LINE> self.directionPanel.Add(self.directionRadioBox, 1) <NEW_LINE> self.lengthPanel = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> self.lengthLabel = wx.StaticText(self, wx.ID_ANY, "Length: ") <NEW_LINE> self.lengthText = wx.TextCtrl(self, wx.ID_ANY, "", size = (100, 25)) <NEW_LINE> self.lengthPanel.Add(self.lengthLabel, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTRE_VERTICAL) <NEW_LINE> self.lengthPanel.Add(self.lengthText) <NEW_LINE> self.okButton = wx.Button(self, wx.ID_OK, "Add Command") <NEW_LINE> self.okButton.SetDefault() <NEW_LINE> self.okButton.Bind(wx.EVT_BUTTON, self.OnOK) <NEW_LINE> self.cancelButton = wx.Button(self, wx.ID_CANCEL, "Cancel") <NEW_LINE> self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel) <NEW_LINE> self.buttonSizer = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> self.buttonSizer.Add((1,1), 1, wx.EXPAND) <NEW_LINE> self.buttonSizer.Add(self.okButton, 0, wx.ALIGN_CENTRE) <NEW_LINE> self.buttonSizer.Add((50,1), 0, wx.ALIGN_CENTRE) <NEW_LINE> self.buttonSizer.Add(self.cancelButton, 0, wx.ALIGN_CENTRE) <NEW_LINE> self.buttonSizer.Add((1,1), 1, wx.EXPAND) <NEW_LINE> self.panelSizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> self.panelSizer.Add((1,25), 0, wx.ALIGN_CENTRE) <NEW_LINE> self.panelSizer.Add(self.directionPanel, 0, wx.ALIGN_CENTRE) <NEW_LINE> self.panelSizer.Add((1,25), 0, wx.ALIGN_CENTRE) <NEW_LINE> self.panelSizer.Add(self.lengthPanel, 0, wx.ALIGN_CENTRE) <NEW_LINE> self.panelSizer.Add((1,25), 0, wx.ALIGN_CENTRE) <NEW_LINE> self.panelSizer.Add(self.buttonSizer, 0, wx.ALIGN_CENTRE) <NEW_LINE> self.SetSizer(self.panelSizer) <NEW_LINE> <DEDENT> def OnOK(self, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = int(self.lengthText.GetValue()) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> d = wx.MessageDialog(self, "Invalid entry for Length!", "Parse Error", wx.OK) <NEW_LINE> d.ShowModal() <NEW_LINE> d.Destroy() <NEW_LINE> return <NEW_LINE> <DEDENT> if (length < 0): <NEW_LINE> <INDENT> d = wx.MessageDialog(self, "Invalid entry for Length!", "Parse Error", wx.OK) <NEW_LINE> d.ShowModal() <NEW_LINE> d.Destroy() <NEW_LINE> return <NEW_LINE> <DEDENT> self.output = (self.directionChoicesValues[self.directionRadioBox.GetSelection()], length) <NEW_LINE> self.EndModal(0) <NEW_LINE> <DEDENT> def OnCancel(self, event): <NEW_LINE> <INDENT> self.EndModal(-1)
Dialog for specifying Pinwheel details.
625990623617ad0b5ee07837
class CertificateStatusInvalidOperation(exception.BarbicanHTTPException): <NEW_LINE> <INDENT> client_message = "" <NEW_LINE> status_code = 400 <NEW_LINE> def __init__(self, reason=u._('Unknown')): <NEW_LINE> <INDENT> super(CertificateStatusInvalidOperation, self).__init__( u._('Invalid operation requested - ' 'Reason: {reason}').format(reason=reason) ) <NEW_LINE> self.client_message = self.message
Raised when the CA has encountered an issue with request data.
6259906207f4c71912bb0b1f
class ImportTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_import_fail(self): <NEW_LINE> <INDENT> sys.modules['smbus'] = None <NEW_LINE> with self.assertRaisesRegex(ImportError, 'requires'): <NEW_LINE> <INDENT> import sn3218 <NEW_LINE> self.assertTrue(sn3218) <NEW_LINE> <DEDENT> del sys.modules['smbus'] <NEW_LINE> <DEDENT> def test_import_ok(self): <NEW_LINE> <INDENT> global sn3218 <NEW_LINE> import sn3218 <NEW_LINE> self.assertTrue(sn3218)
Test for import failure, and the actual module import
625990620c0af96317c578d3
class ImageInfoSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = { "CreateTime": fields.Int(required=False, load_from="CreateTime"), "DeployInfoList": fields.List(DeployImageInfoSchema()), "Gpu": fields.Int(required=False, load_from="Gpu"), "ImageDesc": fields.Str(required=False, load_from="ImageDesc"), "ImageId": fields.Str(required=False, load_from="ImageId"), "ImageName": fields.Str(required=False, load_from="ImageName"), "ImageSize": fields.Int(required=False, load_from="ImageSize"), "ImageType": fields.Int(required=False, load_from="ImageType"), "OcType": fields.Str(required=False, load_from="OcType"), "State": fields.Int(required=False, load_from="State"), }
ImageInfo - 镜像详情
6259906255399d3f05627c08
class PayloadProviderTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_list(self): <NEW_LINE> <INDENT> payloads = [ b'payload A', b'second payload' b'payload 3+' ] <NEW_LINE> res = [] <NEW_LINE> provider = payload_provider.List(payloads) <NEW_LINE> for payload in provider: <NEW_LINE> <INDENT> res.append(payload) <NEW_LINE> <DEDENT> for num, payload in enumerate(payloads): <NEW_LINE> <INDENT> self.assertEqual(res[num], payload, 'Payload not expected in position {0}'.format(num)) <NEW_LINE> <DEDENT> <DEDENT> def test_repeat(self): <NEW_LINE> <INDENT> pattern = b'this is a pattern' <NEW_LINE> count = 5 <NEW_LINE> provider = payload_provider.Repeat(pattern, count) <NEW_LINE> for payload in provider: <NEW_LINE> <INDENT> self.assertEqual(payload, pattern, 'Payload does not reflect the pattern') <NEW_LINE> count -= 1 <NEW_LINE> <DEDENT> self.assertEqual(count, 0, 'Generated a wrong number of payloads') <NEW_LINE> <DEDENT> def sweep_tester(self, pattern, start, end): <NEW_LINE> <INDENT> provider = payload_provider.Sweep(pattern, start, end) <NEW_LINE> payloads_generated = 0 <NEW_LINE> for payload in provider: <NEW_LINE> <INDENT> self.assertEqual(len(payload), start, 'Generated a payload with a wrong size') <NEW_LINE> start += 1 <NEW_LINE> payloads_generated += 1 <NEW_LINE> <DEDENT> self.assertEqual(start, end+1, 'Generated a wrong number of payloads') <NEW_LINE> return payloads_generated <NEW_LINE> <DEDENT> def test_sweep_normal(self): <NEW_LINE> <INDENT> self.sweep_tester(b'abc', 10, 20) <NEW_LINE> <DEDENT> def test_sweep_one(self): <NEW_LINE> <INDENT> self.assertEqual( self.sweep_tester(b'frog', 40, 40), 1, 'Unable to generate exactly 1 payload during a sweep') <NEW_LINE> <DEDENT> def test_sweep_reversed(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> payload_provider.Sweep(b'123', 100, 45) <NEW_LINE> <DEDENT> <DEDENT> def test_sweep_no_pattern(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> payload_provider.Sweep(b'', 1, 10)
Tests for PayloadProvider class
625990621f037a2d8b9e53df
class ServerDnsAliasAcquisition(Model): <NEW_LINE> <INDENT> _attribute_map = { 'old_server_dns_alias_id': {'key': 'oldServerDnsAliasId', 'type': 'str'}, } <NEW_LINE> def __init__(self, old_server_dns_alias_id=None): <NEW_LINE> <INDENT> super(ServerDnsAliasAcquisition, self).__init__() <NEW_LINE> self.old_server_dns_alias_id = old_server_dns_alias_id
A server DNS alias acquisition request. :param old_server_dns_alias_id: The id of the server alias that will be acquired to point to this server instead. :type old_server_dns_alias_id: str
6259906299cbb53fe68325cb
class ZhaGroupEntity(BaseZhaEntity): <NEW_LINE> <INDENT> def __init__( self, entity_ids: List[str], unique_id: str, group_id: int, zha_device, **kwargs ) -> None: <NEW_LINE> <INDENT> super().__init__(unique_id, zha_device, **kwargs) <NEW_LINE> self._name = ( f"{zha_device.gateway.groups.get(group_id).name}_zha_group_0x{group_id:04x}" ) <NEW_LINE> self._group_id: int = group_id <NEW_LINE> self._entity_ids: List[str] = entity_ids <NEW_LINE> self._async_unsub_state_changed: Optional[CALLBACK_TYPE] = None <NEW_LINE> <DEDENT> async def async_added_to_hass(self) -> None: <NEW_LINE> <INDENT> await super().async_added_to_hass() <NEW_LINE> await self.async_accept_signal( None, f"{SIGNAL_REMOVE_GROUP}_0x{self._group_id:04x}", self.async_remove, signal_override=True, ) <NEW_LINE> await self.async_accept_signal( None, f"{SIGNAL_GROUP_MEMBERSHIP_CHANGE}_0x{self._group_id:04x}", self._update_group_entities, signal_override=True, ) <NEW_LINE> self._async_unsub_state_changed = async_track_state_change( self.hass, self._entity_ids, self.async_state_changed_listener ) <NEW_LINE> await self.async_update() <NEW_LINE> <DEDENT> @callback <NEW_LINE> def async_state_changed_listener( self, entity_id: str, old_state: State, new_state: State ): <NEW_LINE> <INDENT> self.async_schedule_update_ha_state(True) <NEW_LINE> <DEDENT> def _update_group_entities(self): <NEW_LINE> <INDENT> group = self.zha_device.gateway.get_group(self._group_id) <NEW_LINE> self._entity_ids = group.get_domain_entity_ids(self.platform.domain) <NEW_LINE> if self._async_unsub_state_changed is not None: <NEW_LINE> <INDENT> self._async_unsub_state_changed() <NEW_LINE> <DEDENT> self._async_unsub_state_changed = async_track_state_change( self.hass, self._entity_ids, self.async_state_changed_listener ) <NEW_LINE> <DEDENT> async def async_will_remove_from_hass(self) -> None: <NEW_LINE> <INDENT> await super().async_will_remove_from_hass() <NEW_LINE> if self._async_unsub_state_changed is not None: <NEW_LINE> <INDENT> self._async_unsub_state_changed() <NEW_LINE> self._async_unsub_state_changed = None <NEW_LINE> <DEDENT> <DEDENT> async def async_update(self) -> None: <NEW_LINE> <INDENT> pass
A base class for ZHA group entities.
625990628da39b475be048d2
class CourseTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> CourseFactory() <NEW_LINE> <DEDENT> def test_duplicate_course_name_cannot_be_saved(self): <NEW_LINE> <INDENT> course = Course( name='appetizer', sequence_order=2 ) <NEW_LINE> self.assertRaises(ValidationError, course.save)
Tests the Course model.
625990622ae34c7f260ac7d0
class IxnBgpAigpListEmulation(IxnEmulationHost): <NEW_LINE> <INDENT> def __init__(self, ixnhttp): <NEW_LINE> <INDENT> super(IxnBgpAigpListEmulation, self).__init__(ixnhttp) <NEW_LINE> <DEDENT> def find(self, vport_name=None, emulation_host=None, **filters): <NEW_LINE> <INDENT> return super(IxnBgpAigpListEmulation, self).find(["topology","deviceGroup","networkGroup","macPools","ipv6PrefixPools","bgpIPRouteProperty","bgpAigpList"], vport_name, emulation_host, filters)
Generated NGPF bgpAigpList emulation host
62599062460517430c432bc8
class RequestParameters(dict): <NEW_LINE> <INDENT> def get(self, name: str, default: Any = None) -> Any: <NEW_LINE> <INDENT> return super().get(name, [default])[0] <NEW_LINE> <DEDENT> def getlist(self, name: str, default: Any = None) -> List[Any]: <NEW_LINE> <INDENT> return super().get(name, default)
Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang
625990628e7ae83300eea777
class InfoVersion(Api): <NEW_LINE> <INDENT> def __init__(self, *args, **kw): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> resp_json = super().request(self.__class__.__name__) <NEW_LINE> if resp_json: <NEW_LINE> <INDENT> print(resp_json.get('status').get('message'))
super(): http://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p07_calling_method_on_parent_class.html#id3
62599062435de62698e9d4f1
class SlugModel(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=255, db_index=True) <NEW_LINE> slug = models.SlugField(max_length=255, editable=False, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not hasattr(self, 'override_slug_save') and not self.slug: <NEW_LINE> <INDENT> self.slug = slugify(unidecode(self.title)) <NEW_LINE> <DEDENT> super(SlugModel, self).save(*args, **kwargs)
A mixin Model for creating unique Slugs
62599062ac7a0e7691f73bce
class CommentIfExtension(Extension): <NEW_LINE> <INDENT> tags = set(['commentif']) <NEW_LINE> def parse(self, parser): <NEW_LINE> <INDENT> lineno = next(parser.stream).lineno <NEW_LINE> args = [parser.parse_expression(), parser.parse_expression()] <NEW_LINE> body = parser.parse_statements(['name:endcommentif'], drop_needle=True) <NEW_LINE> return nodes.CallBlock(self.call_method('_comment_if', args), [], [], body).set_lineno(lineno) <NEW_LINE> <DEDENT> def _comment_if(self, escapestr, boolexpr, caller): <NEW_LINE> <INDENT> rawinput = caller() <NEW_LINE> if not boolexpr: <NEW_LINE> <INDENT> return rawinput <NEW_LINE> <DEDENT> lines = rawinput.splitlines() <NEW_LINE> output = '\n'.join(["%s%s" % (escapestr, l) for l in lines]) <NEW_LINE> return output
Put a string before each line to comment out a block based on a boolean expression. Example:: {% set comment=True %} {% commentif "#" comment %} My text should be comment if "comment" is True. {% endcommentif %}
625990620a50d4780f706934
class IntegerPreference(object): <NEW_LINE> <INDENT> def __init__(self, minval=None, maxval=None): <NEW_LINE> <INDENT> self.minval = minval <NEW_LINE> self.maxval = maxval
User interface info for an integer preference This signals that a preference should be displayed and edited as an integer, optionally limited by a range.
625990627cff6e4e811b7130
class VnsfOrchestratorUnreacheable(ExceptionMessage): <NEW_LINE> <INDENT> pass
vNSFO cannot be reached.
625990628a43f66fc4bf3879
class CheapMensClothingSpider(PageSpider): <NEW_LINE> <INDENT> name = 'cheapmensclothing' <NEW_LINE> config = Configuration('cheapmensclothing_spider') <NEW_LINE> start_urls = [PageSpider.home_url + 'lists/cheap-mens-clothing.aspx?cur=' + config.currency + '&pp=' + config.pp + '&o=lth&s=' + (config.size).replace(',','&s=')]
Spider that gets clothes on sale for men's from http://www.prodirectselect.com/
6259906245492302aabfdbc5
class Minimum(_NumericValue): <NEW_LINE> <INDENT> pass
Field transform: bound numeric field with specified value. See: https://cloud.google.com/firestore/docs/reference/rpc/google.firestore.v1#google.firestore.v1.DocumentTransform.FieldTransform.FIELDS.google.firestore.v1.ArrayValue.google.firestore.v1.DocumentTransform.FieldTransform.minimum Args: value (int | float): value used to bound the field.
625990621f037a2d8b9e53e0
class BaseAlgorithm(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.derivative_function = None <NEW_LINE> self.quadrature_function = None <NEW_LINE> self.boundarycondition_function = None <NEW_LINE> self.initial_cost_function = None <NEW_LINE> self.path_cost_function = None <NEW_LINE> self.terminal_cost_function = None <NEW_LINE> self.inequality_constraint_function = None <NEW_LINE> self.derivative_function_jac = None <NEW_LINE> self.boundarycondition_function_jac = None <NEW_LINE> if len(args) > 0: <NEW_LINE> <INDENT> self.derivative_function = args[0] <NEW_LINE> <DEDENT> if len(args) > 1: <NEW_LINE> <INDENT> self.quadrature_function = args[1] <NEW_LINE> <DEDENT> if len(args) > 2: <NEW_LINE> <INDENT> self.boundarycondition_function = args[2] <NEW_LINE> <DEDENT> self.bc_func_ms = None <NEW_LINE> self.stm_ode_func = None <NEW_LINE> <DEDENT> def set_boundarycondition_function(self, boundarycondition_function): <NEW_LINE> <INDENT> self.boundarycondition_function = boundarycondition_function <NEW_LINE> self.bc_func_ms = None <NEW_LINE> <DEDENT> def set_boundarycondition_jacobian(self, boundarycondition_jacobian): <NEW_LINE> <INDENT> self.boundarycondition_function_jac = boundarycondition_jacobian <NEW_LINE> <DEDENT> def set_derivative_function(self, derivative_function): <NEW_LINE> <INDENT> self.derivative_function = derivative_function <NEW_LINE> self.stm_ode_func = None <NEW_LINE> <DEDENT> def set_derivative_jacobian(self, derivative_jacobian): <NEW_LINE> <INDENT> self.derivative_function_jac = derivative_jacobian <NEW_LINE> <DEDENT> def set_quadrature_function(self, quadrature_function): <NEW_LINE> <INDENT> self.quadrature_function = quadrature_function <NEW_LINE> <DEDENT> def set_initial_cost_function(self, initial_cost): <NEW_LINE> <INDENT> self.initial_cost_function = initial_cost <NEW_LINE> <DEDENT> def set_path_cost_function(self, path_cost): <NEW_LINE> <INDENT> self.path_cost_function = path_cost <NEW_LINE> <DEDENT> def set_terminal_cost_function(self, terminal_cost): <NEW_LINE> <INDENT> self.terminal_cost_function = terminal_cost <NEW_LINE> <DEDENT> def set_inequality_constraint_function(self, inequality_constraint): <NEW_LINE> <INDENT> self.inequality_constraint_function = inequality_constraint <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def solve(self, solinit, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass
Object representing an algorithm that solves boundary valued problems. This object serves as a base class for other algorithms.
62599062462c4b4f79dbd0f0
class AgentMacroReference(BaseObject): <NEW_LINE> <INDENT> def __init__(self, api=None, id=None, macro_id=None, macro_title=None, type=None, via=None, **kwargs): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.id = id <NEW_LINE> self.macro_id = macro_id <NEW_LINE> self.macro_title = macro_title <NEW_LINE> self.type = type <NEW_LINE> self.via = via <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> for key in self.to_dict(): <NEW_LINE> <INDENT> if getattr(self, key) is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._dirty_attributes.remove(key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def macro(self): <NEW_LINE> <INDENT> if self.api and self.macro_id: <NEW_LINE> <INDENT> return self.api._get_macro(self.macro_id) <NEW_LINE> <DEDENT> <DEDENT> @macro.setter <NEW_LINE> def macro(self, macro): <NEW_LINE> <INDENT> if macro: <NEW_LINE> <INDENT> self.macro_id = macro.id <NEW_LINE> self._macro = macro
###################################################################### # Do not modify, this class is autogenerated by gen_classes.py # ######################################################################
6259906266673b3332c31ae7
class Browser: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.socket = HttpSocket() <NEW_LINE> self.state = BrowserState() <NEW_LINE> self.response = None <NEW_LINE> self.domain = None <NEW_LINE> <DEDENT> def request(self, method, file, body=None, headers=None, dest=None): <NEW_LINE> <INDENT> if self.domain is not None and dest is not None and dest != self.domain: <NEW_LINE> <INDENT> raise LockedDomainException(dest) <NEW_LINE> <DEDENT> elif self.domain is not None: <NEW_LINE> <INDENT> dest = self.domain <NEW_LINE> <DEDENT> elif dest is None and self.domain is None: <NEW_LINE> <INDENT> log.warn("Missing destination for request") <NEW_LINE> raise NoDestinationException() <NEW_LINE> <DEDENT> self.response = None <NEW_LINE> message = HttpClientMessage(method, file, body, headers) <NEW_LINE> self.state.apply_to(message) <NEW_LINE> self.state.visit(file) <NEW_LINE> log.debug("sending %s for %s", method, file) <NEW_LINE> while True: <NEW_LINE> <INDENT> self.socket.send(dest, message) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.get_response() <NEW_LINE> <DEDENT> except EmptySocketException: <NEW_LINE> <INDENT> log.warn("Encountered an empty socket") <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get(self, file, headers={}, dest=None): <NEW_LINE> <INDENT> return self.request("GET", file, None, headers, dest) <NEW_LINE> <DEDENT> def post(self, file, body=None, headers={}, dest=None): <NEW_LINE> <INDENT> return self.request("POST", file, body, headers, dest) <NEW_LINE> <DEDENT> def get_response(self): <NEW_LINE> <INDENT> if self.response is None: <NEW_LINE> <INDENT> self.response = HttpServerMessage(self.socket) <NEW_LINE> self.state.apply_from(self.response) <NEW_LINE> self.apply_response(self.response) <NEW_LINE> <DEDENT> return self.response <NEW_LINE> <DEDENT> def apply_response(self, response): <NEW_LINE> <INDENT> if response.safe_get_header("connection") == "close": <NEW_LINE> <INDENT> self.socket.close() <NEW_LINE> <DEDENT> <DEDENT> def get_cookie(self, key): <NEW_LINE> <INDENT> return self.state.get_cookie(key) <NEW_LINE> <DEDENT> def has_visited(self, link): <NEW_LINE> <INDENT> return self.state.has_visited(link) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.socket.close()
This class acts as an interface for the internet. Other classes may use it to request HTTP resources and get the responses.
625990622ae34c7f260ac7d2
class RentalItem(models.Model): <NEW_LINE> <INDENT> condition = models.TextField(max_length=500) <NEW_LINE> new_damage = models.BooleanField(default=False) <NEW_LINE> damage_fee = models.DecimalField(max_digits=10, decimal_places=2, null=True) <NEW_LINE> late_fee = models.DecimalField(max_digits=10, decimal_places=2, null=True) <NEW_LINE> due_date = models.DateField(null=True) <NEW_LINE> returned = models.BooleanField(default=False) <NEW_LINE> rental_return = models.ForeignKey(Return, null=True, related_name='items_returned') <NEW_LINE> rental = models.ForeignKey(Rental, null=True) <NEW_LINE> item = models.ForeignKey(Item, null=True)
DESCRIPTION: An association class that adds more information when a user rents an item. NOTES:
62599062460517430c432bc9
class StoryScraper(object): <NEW_LINE> <INDENT> FIELDS = { "created_at": "created_at", "title": "title", "url": "url", "author": "author", "points": "points", "story_text": "points", "timestamp": "created_at_i", "objectID": "story_id" } <NEW_LINE> @staticmethod <NEW_LINE> def getStories(since, until=None, timeout=None): <NEW_LINE> <INDENT> return Scraper().scrape("story", since, until=until, fields=StoryScraper.FIELDS, timeout=timeout)
hacker news story scraper. Example: StoryScraper.getStories("story", 1394901958) will return all stories since 15 Mar 2014 16:45:58 GMT.
62599062cc0a2c111447c645
class MiniTry(MiniAst): <NEW_LINE> <INDENT> def __init__(self, body, filters, low, high): <NEW_LINE> <INDENT> self.body = body <NEW_LINE> self.filters = filters <NEW_LINE> super(MiniTry, self).__init__(low, high) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "MiniTry({0}, {1})".format(self.body, self.filters) <NEW_LINE> <DEDENT> def asExpr(self, state): <NEW_LINE> <INDENT> if self.filters is None: <NEW_LINE> <INDENT> filters = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if any(not isinstance(x, (MiniDotName, MiniString)) and not (isinstance(x, MiniNumber) and isinstance(x.value, (int, long))) for x in self.filters): <NEW_LINE> <INDENT> raise PrettyPfaException("try filters must all be strings or integers, not {0}, at {1}".format(self.filters, self.pos)) <NEW_LINE> <DEDENT> filters = [x.name if isinstance(x, MiniDotName) else x.value for x in self.filters] <NEW_LINE> <DEDENT> if isinstance(self.body, MiniCall) and self.body.name == "do": <NEW_LINE> <INDENT> body = [x.asExpr(state) for x in self.body.args] <NEW_LINE> <DEDENT> elif isinstance(self.body, (list, tuple)): <NEW_LINE> <INDENT> body = [x.asExpr(state) for x in self.body] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> body = [self.body.asExpr(state)] <NEW_LINE> <DEDENT> return Try(body, filters, self.pos)
Mini-AST element representing a ``try`` expression.
62599062a219f33f346c7ef2
class Speaker(ndb.Model): <NEW_LINE> <INDENT> displayName = ndb.StringProperty(required=True) <NEW_LINE> mainEmail = ndb.StringProperty() <NEW_LINE> bio = ndb.StringProperty()
Speaker -- Speaker profile object
62599062adb09d7d5dc0bc56
class _Task(object): <NEW_LINE> <INDENT> def __init__(self, func, args, argd=None): <NEW_LINE> <INDENT> self._func = func <NEW_LINE> self._args = args <NEW_LINE> self._argd = {} if argd is None else argd <NEW_LINE> self._ret = None <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self._ret = self._func(*self._args, **self._argd) <NEW_LINE> return self._ret
Executor task
62599062f548e778e596cc75
class ScopedCenterViewSet(ModelViewSet): <NEW_LINE> <INDENT> queryset = ScopedCenter.objects.all() <NEW_LINE> serializer_class = ScopedCenterSerializer
This endpoint Represents the Centers with definite Scopes It presents the list of Current Centers with definite Scopes
625990628a43f66fc4bf387b
class SyntaxData(syndata.SyntaxDataBase): <NEW_LINE> <INDENT> def __init__(self, langid): <NEW_LINE> <INDENT> syndata.SyntaxDataBase.__init__(self, langid) <NEW_LINE> self.SetLexer(stc.STC_LEX_KIX) <NEW_LINE> <DEDENT> def GetKeywords(self): <NEW_LINE> <INDENT> return [COMMANDS, FUNCTIONS, MACROS] <NEW_LINE> <DEDENT> def GetSyntaxSpec(self): <NEW_LINE> <INDENT> return SYNTAX_ITEMS <NEW_LINE> <DEDENT> def GetCommentPattern(self): <NEW_LINE> <INDENT> return [u';']
SyntaxData object for Kix
625990627047854f46340aaa
class CaloriesTest(PluginTest, unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.test = self.load_plugin(calories) <NEW_LINE> <DEDENT> def test_calories(self): <NEW_LINE> <INDENT> gender = "m" <NEW_LINE> age = 20 <NEW_LINE> height = 165 <NEW_LINE> weight = 54 <NEW_LINE> exercise_level = 3 <NEW_LINE> result = self.test.calories(gender, age, height, weight, exercise_level) <NEW_LINE> self.assertEqual(result[0], 2096.4) <NEW_LINE> self.assertEqual(result[1], 1596.4) <NEW_LINE> self.assertEqual(result[2], 2596.4) <NEW_LINE> <DEDENT> def test_validate_gender_case1(self): <NEW_LINE> <INDENT> correct_input = "m" <NEW_LINE> self.assertTrue(self.test.validate_gender(correct_input)) <NEW_LINE> <DEDENT> def test_validate_gender_case2(self): <NEW_LINE> <INDENT> correct_input = "f" <NEW_LINE> self.assertTrue(self.test.validate_gender(correct_input)) <NEW_LINE> <DEDENT> def test_validate_gender_case2(self): <NEW_LINE> <INDENT> wrong_input = "l" <NEW_LINE> self.assertFalse(self.test.validate_gender(wrong_input)) <NEW_LINE> <DEDENT> def test_validate_age_correct_input(self): <NEW_LINE> <INDENT> correct_input = 21 <NEW_LINE> self.assertTrue(self.test.validate_age(correct_input)) <NEW_LINE> <DEDENT> def test_validate_age_wrong_input(self): <NEW_LINE> <INDENT> wrong_input1 = "age" <NEW_LINE> wrong_input2 = -21 <NEW_LINE> self.assertFalse(self.test.validate_age(wrong_input1)) <NEW_LINE> self.assertFalse(self.test.validate_age(wrong_input2)) <NEW_LINE> <DEDENT> def test_validate_height_correct_input(self): <NEW_LINE> <INDENT> correct_input = 170 <NEW_LINE> self.assertTrue(self.test.validate_height(correct_input)) <NEW_LINE> <DEDENT> def test_validate_height_wrong_input(self): <NEW_LINE> <INDENT> wrong_input1 = "height" <NEW_LINE> wrong_input2 = -170 <NEW_LINE> self.assertFalse(self.test.validate_height(wrong_input1)) <NEW_LINE> self.assertFalse(self.test.validate_height(wrong_input2)) <NEW_LINE> <DEDENT> def test_validate_weight_correct_input(self): <NEW_LINE> <INDENT> correct_input = 60 <NEW_LINE> self.assertTrue(self.test.validate_weight(correct_input)) <NEW_LINE> <DEDENT> def test_validate_height_wrong_input(self): <NEW_LINE> <INDENT> wrong_input1 = "weight" <NEW_LINE> wrong_input2 = -170 <NEW_LINE> self.assertFalse(self.test.validate_weight(wrong_input1)) <NEW_LINE> self.assertFalse(self.test.validate_weight(wrong_input2)) <NEW_LINE> <DEDENT> def test_validate_workout_level_correct_input(self): <NEW_LINE> <INDENT> correct_input = 1 <NEW_LINE> self.assertTrue(self.test.validate_workout_level(correct_input)) <NEW_LINE> <DEDENT> def test_validate_workout_level_wrong_input(self): <NEW_LINE> <INDENT> wrong_input1 = "workout_level" <NEW_LINE> wrong_input2 = -1 <NEW_LINE> self.assertFalse(self.test.validate_workout_level(wrong_input1)) <NEW_LINE> self.assertFalse(self.test.validate_workout_level(wrong_input2)) <NEW_LINE> <DEDENT> def test_exercise_level(self): <NEW_LINE> <INDENT> expected = 1.6 <NEW_LINE> result = self.test.exercise_level(3) <NEW_LINE> self.assertEqual(result, expected)
This class is testing the calories plugin
6259906245492302aabfdbc7
class TestQuestion(object): <NEW_LINE> <INDENT> def test___init___basic(self, questions): <NEW_LINE> <INDENT> question = WatsonQuestion(questions[0]['questionText']) <NEW_LINE> assert question.question_text == questions[0]['questionText'] <NEW_LINE> <DEDENT> def test___init___complete(self, questions): <NEW_LINE> <INDENT> q = questions[1] <NEW_LINE> er = q['evidenceRequest'] <NEW_LINE> evidence_request = EvidenceRequest(er['items'], er['profile']) <NEW_LINE> filters = tuple(Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']) <NEW_LINE> question = WatsonQuestion( question_text=q['questionText'], answer_assertion=q['answerAssertion'], category=q['category'], context=q['context'], evidence_request=evidence_request, filters=filters, formatted_answer=q['formattedAnswer'], items=q['items'], lat=q['lat'], passthru=q['passthru'], synonym_list=q['synonyms']) <NEW_LINE> assert question.question_text == q['questionText'] <NEW_LINE> assert question.answer_assertion == q['answerAssertion'] <NEW_LINE> assert question.category == q['category'] <NEW_LINE> assert question.context == q['context'] <NEW_LINE> assert question.evidence_request == evidence_request <NEW_LINE> assert question.filters == filters
Unit tests for the WatsonQuestion class
62599062dd821e528d6da4f7
class BurnMethod(ContractMethod): <NEW_LINE> <INDENT> def __init__( self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, contract_function: ContractFunction, validator: Validator = None, ): <NEW_LINE> <INDENT> super().__init__(web3_or_provider, contract_address, validator) <NEW_LINE> self._underlying_method = contract_function <NEW_LINE> <DEDENT> def validate_and_normalize_inputs( self, ids: List[int], amounts: List[int], data: Union[bytes, str] ): <NEW_LINE> <INDENT> self.validator.assert_valid( method_name="burn", parameter_name="_ids", argument_value=ids, ) <NEW_LINE> self.validator.assert_valid( method_name="burn", parameter_name="_amounts", argument_value=amounts, ) <NEW_LINE> self.validator.assert_valid( method_name="burn", parameter_name="_data", argument_value=data, ) <NEW_LINE> return (ids, amounts, data) <NEW_LINE> <DEDENT> def call( self, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None, ) -> None: <NEW_LINE> <INDENT> (ids, amounts, data) = self.validate_and_normalize_inputs(ids, amounts, data) <NEW_LINE> tx_params = super().normalize_tx_params(tx_params) <NEW_LINE> self._underlying_method(ids, amounts, data).call(tx_params.as_dict()) <NEW_LINE> <DEDENT> def send_transaction( self, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None, ) -> Union[HexBytes, bytes]: <NEW_LINE> <INDENT> (ids, amounts, data) = self.validate_and_normalize_inputs(ids, amounts, data) <NEW_LINE> tx_params = super().normalize_tx_params(tx_params) <NEW_LINE> return self._underlying_method(ids, amounts, data).transact(tx_params.as_dict()) <NEW_LINE> <DEDENT> def build_transaction( self, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None, ) -> dict: <NEW_LINE> <INDENT> (ids, amounts, data) = self.validate_and_normalize_inputs(ids, amounts, data) <NEW_LINE> tx_params = super().normalize_tx_params(tx_params) <NEW_LINE> return self._underlying_method(ids, amounts, data).buildTransaction( tx_params.as_dict() ) <NEW_LINE> <DEDENT> def estimate_gas( self, ids: List[int], amounts: List[int], data: Union[bytes, str], tx_params: Optional[TxParams] = None, ) -> int: <NEW_LINE> <INDENT> (ids, amounts, data) = self.validate_and_normalize_inputs(ids, amounts, data) <NEW_LINE> tx_params = super().normalize_tx_params(tx_params) <NEW_LINE> return self._underlying_method(ids, amounts, data).estimateGas( tx_params.as_dict() )
Various interfaces to the burn method.
625990622ae34c7f260ac7d3
class PassageDetectorChannel(FunctionalChannel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.leftCounter = 0 <NEW_LINE> self.leftRightCounterDelta = 0 <NEW_LINE> self.passageBlindtime = 0.0 <NEW_LINE> self.passageDirection = PassageDirection.RIGHT <NEW_LINE> self.passageSensorSensitivity = 0.0 <NEW_LINE> self.passageTimeout = 0.0 <NEW_LINE> self.rightCounter = 0 <NEW_LINE> <DEDENT> def from_json(self, js, groups: Iterable[Group]): <NEW_LINE> <INDENT> super().from_json(js, groups) <NEW_LINE> self.leftCounter = js["leftCounter"] <NEW_LINE> self.leftRightCounterDelta = js["leftRightCounterDelta"] <NEW_LINE> self.passageBlindtime = js["passageBlindtime"] <NEW_LINE> self.passageDirection = PassageDirection.from_str(js["passageDirection"]) <NEW_LINE> self.passageSensorSensitivity = js["passageSensorSensitivity"] <NEW_LINE> self.passageTimeout = js["passageTimeout"] <NEW_LINE> self.rightCounter = js["rightCounter"]
this is the representive of the PASSAGE_DETECTOR_CHANNEL channel
62599062009cb60464d02c24
class WorkerMessageResponse(_messages.Message): <NEW_LINE> <INDENT> workerHealthReportResponse = _messages.MessageField('WorkerHealthReportResponse', 1) <NEW_LINE> workerMetricsResponse = _messages.MessageField('ResourceUtilizationReportResponse', 2) <NEW_LINE> workerShutdownNoticeResponse = _messages.MessageField('WorkerShutdownNoticeResponse', 3)
A worker_message response allows the server to pass information to the sender. Fields: workerHealthReportResponse: The service's response to a worker's health report. workerMetricsResponse: Service's response to reporting worker metrics (currently empty). workerShutdownNoticeResponse: Service's response to shutdown notice (currently empty).
6259906256ac1b37e630385d
class Notification(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TopicName = None <NEW_LINE> self.EventConfigs = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TopicName = params.get("TopicName") <NEW_LINE> if params.get("EventConfigs") is not None: <NEW_LINE> <INDENT> self.EventConfigs = [] <NEW_LINE> for item in params.get("EventConfigs"): <NEW_LINE> <INDENT> obj = EventConfig() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.EventConfigs.append(obj)
通知信息
62599062442bda511e95d8d0
class MODE: <NEW_LINE> <INDENT> simulation = "SIMULATION" <NEW_LINE> hardware = "HARDWARE"
simulation mode: Use the hardware for the master side, and simulation for the ECM hardware mode: Use hardware for both the master side, and the ECM
625990622ae34c7f260ac7d4
class SetAttrSubCommand(CommonPoolSubCommand): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("set-attr") <NEW_LINE> self.attr = PositionalParameter(2) <NEW_LINE> self.value = PositionalParameter(3) <NEW_LINE> self.sys_name = FormattedParameter("--sys-name={}")
Defines an object for the daos pool set-attr command.
625990628e7ae83300eea77a
class InfoField(InputField): <NEW_LINE> <INDENT> def __init__(self, **options) -> None: <NEW_LINE> <INDENT> super().__init__(**options) <NEW_LINE> self._type(gui.InputField.INFO_TYPE)
Informational field (no input is done)
62599062d6c5a102081e3811
class ListExtender(list): <NEW_LINE> <INDENT> def read_all(self): <NEW_LINE> <INDENT> ret = simplejson.dumps([simplejson.loads(x) for x in self]) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def remove_old(self, delay): <NEW_LINE> <INDENT> pass
Class extends list class with necessary methods.
62599062fff4ab517ebcef14
class WriteSDO: <NEW_LINE> <INDENT> def __init__( self, nodeID, objectIndex, subIndex, data ): <NEW_LINE> <INDENT> self.nodeID, self.objectIndex, self.subIndex = nodeID, objectIndex, subIndex <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def update( self, packet ): <NEW_LINE> <INDENT> self.packet = packet <NEW_LINE> <DEDENT> def generator( self ): <NEW_LINE> <INDENT> remainingData = [] <NEW_LINE> if len(self.data) <= 4: <NEW_LINE> <INDENT> cmd = 0x23 | ((4-len(self.data))<<2) <NEW_LINE> d = self.data <NEW_LINE> d.extend( [0,0,0,0] ) <NEW_LINE> yield ( 0x600 + self.nodeID, [cmd, self.objectIndex&0xFF, self.objectIndex>>8, self.subIndex, d[0],d[1],d[2],d[3]] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = 0x21 <NEW_LINE> l = len(self.data) <NEW_LINE> yield ( 0x600 + self.nodeID, [cmd, self.objectIndex&0xFF, self.objectIndex>>8, self.subIndex, l&0xFF, (l>>8)&0xFF, (l>>16)&0xFF, (l>>24)&0xFF] ) <NEW_LINE> remainingData = self.data <NEW_LINE> <DEDENT> toggleBit = 0x00 <NEW_LINE> while True: <NEW_LINE> <INDENT> while self.packet is None: <NEW_LINE> <INDENT> yield None <NEW_LINE> <DEDENT> id,data = self.packet <NEW_LINE> self.packet = None <NEW_LINE> if id == 0x580 + self.nodeID: <NEW_LINE> <INDENT> assert( len(data) == 8 ) <NEW_LINE> if data[0] == 0x80: <NEW_LINE> <INDENT> printAbort( data[7], data[6], (data[5]<<8)|data[4] ) <NEW_LINE> return <NEW_LINE> <DEDENT> sendNextData = False <NEW_LINE> if data[0] == 0x60: <NEW_LINE> <INDENT> assert( ((data[2]<<8)|data[1]) == self.objectIndex ) <NEW_LINE> assert( data[3] == self.subIndex ) <NEW_LINE> sendNextData = True <NEW_LINE> <DEDENT> if data[0] == 0x20 or data[0] == 0x30: <NEW_LINE> <INDENT> assert( data[0] & 0x10 == toggleBit ) <NEW_LINE> toggleBit = 0x10 - toggleBit <NEW_LINE> sendNextData = True <NEW_LINE> <DEDENT> if sendNextData: <NEW_LINE> <INDENT> if len(remainingData) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if len(remainingData) > 7: <NEW_LINE> <INDENT> cmd = 0x00 | toggleBit <NEW_LINE> yield ( 0x600 + self.nodeID, [cmd] + remainingData[0:7] ) <NEW_LINE> remainingData = remainingData[7:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = 0x01 | toggleBit | ((7-len(remainingData))<<1) <NEW_LINE> d = remainingData <NEW_LINE> d.extend( [0,0,0,0,0,0,0] ) <NEW_LINE> yield ( 0x600 + self.nodeID, [cmd] + d[0:7] ) <NEW_LINE> remainingData = []
Write Dictionary Object via CANopen Service Data Objects (SDO)
625990624428ac0f6e659c20
class CharCNN(CharNN): <NEW_LINE> <INDENT> OPTIMIZER = 'adadelta' <NEW_LINE> def model_architecture(self): <NEW_LINE> <INDENT> embedding_size = 128 <NEW_LINE> conv1_filters = 128 <NEW_LINE> conv1_kernel_size = 3 <NEW_LINE> conv2_filters = 256 <NEW_LINE> conv2_kernel_size = 3 <NEW_LINE> hidden_units = 64 <NEW_LINE> output_units = 6 <NEW_LINE> inputs = Input((self.max_len,), name='input') <NEW_LINE> embedding = Embedding( self.vocab_size, embedding_size, name='embedding')(inputs) <NEW_LINE> conv1 = Conv1D(conv1_filters, conv1_kernel_size, strides=1, padding='valid', activation='relu')(embedding) <NEW_LINE> conv2 = Conv1D(conv2_filters, conv2_kernel_size, strides=1, padding='valid', activation='relu')(conv1) <NEW_LINE> pool = GlobalMaxPooling1D()(conv2) <NEW_LINE> hidden = Dense(hidden_units, activation='relu')(pool) <NEW_LINE> outputs = Dense(output_units, activation='sigmoid', name='final')(hidden) <NEW_LINE> return Model(inputs=inputs, outputs=outputs)
Convolutional neural network on char-level data.
62599062009cb60464d02c25
class NT_RS_SARSA(QTable): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.qvals = np.zeros(self.dims) <NEW_LINE> self.load_qvals() <NEW_LINE> if self.lmbda is not None: <NEW_LINE> <INDENT> self.el_traces = np.zeros(self.dims) <NEW_LINE> <DEDENT> <DEDENT> def feature_rep(self, cell, n_used): <NEW_LINE> <INDENT> return cell <NEW_LINE> <DEDENT> def update_qval(self, grid, cell, ch, reward, next_cell, next_ch, next_max_ch, discount): <NEW_LINE> <INDENT> assert type(ch) == np.int64 <NEW_LINE> assert ch is not None <NEW_LINE> self.qval_means.append(np.mean(self.qvals[cell])) <NEW_LINE> td_err = (reward - self.qvals[cell][ch]) <NEW_LINE> self.losses.append(td_err**2) <NEW_LINE> self.qvals[cell][ch] += self.alpha * td_err <NEW_LINE> self.alpha *= self.alpha_decay
No-target Reduced-state SARSA. State consists of cell coordinates only.
6259906276e4537e8c3f0c71
class Sensor(object): <NEW_LINE> <INDENT> def __init__(self, id, analog, interval): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.analog = analog <NEW_LINE> self.interval = interval <NEW_LINE> self.delay = None <NEW_LINE> self.verbose = False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def do_static(x, y): <NEW_LINE> <INDENT> return x + y <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def read_raw(self): <NEW_LINE> <INDENT> return sensors.adc.readadc(self.analog) <NEW_LINE> <DEDENT> def getDelayedReading(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def getDelay(self): <NEW_LINE> <INDENT> return self.interval <NEW_LINE> <DEDENT> def avgReadMS(self, ms): <NEW_LINE> <INDENT> avg2 = 0 <NEW_LINE> n2 = 0 <NEW_LINE> start_time = time.time() * 1000 <NEW_LINE> while time.time() * 1000 - start_time < ms: <NEW_LINE> <INDENT> x2 = self.read() <NEW_LINE> n2 += 1 <NEW_LINE> avg2 = (avg2 * (n2 - 1) + x2) / n2 <NEW_LINE> time.sleep(0.1) <NEW_LINE> <DEDENT> return avg2 <NEW_LINE> <DEDENT> def avgReadTimes(self, no_iter=30): <NEW_LINE> <INDENT> avg2 = 0 <NEW_LINE> n2 = 0 <NEW_LINE> start_time = time.time() * 1000 <NEW_LINE> while n2 < no_iter: <NEW_LINE> <INDENT> x2 = self.read() <NEW_LINE> n2 += 1 <NEW_LINE> avg2 = (avg2 * (n2 - 1) + x2) / n2 <NEW_LINE> time.sleep(0.1) <NEW_LINE> <DEDENT> return avg2
A Sensor have the following properties: Attributes: name: A string representing the sensor's name. id: int analog: An int tracking number of analog channels needed digital: An int tracking number of digital pins needed
62599062f548e778e596cc76
class TrainingCallbackHandler(CallbackHandler): <NEW_LINE> <INDENT> def __init__(self, optimizer, train_metrics, log, val_metrics=None, callbacks=None): <NEW_LINE> <INDENT> super().__init__(dict(log=log, optimizer=optimizer, train_metrics=train_metrics)) <NEW_LINE> if val_metrics: <NEW_LINE> <INDENT> self['val_metrics'] = val_metrics <NEW_LINE> <DEDENT> if callbacks is not None: <NEW_LINE> <INDENT> if type(callbacks) in (list, tuple, torchtuples.TupleTree): <NEW_LINE> <INDENT> for c in callbacks: <NEW_LINE> <INDENT> self.append(c) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for name, c in callbacks.items(): <NEW_LINE> <INDENT> self[name] = c <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def append(self, callback, name=None): <NEW_LINE> <INDENT> super().append(callback, name) <NEW_LINE> self.callbacks.move_to_end('log')
Object for holding all callbacks.
625990625fdd1c0f98e5f672
class Statistics(object): <NEW_LINE> <INDENT> def __init__(self, filename, match, mismatch, gap, extension): <NEW_LINE> <INDENT> self.matches = _fgrep_count('"SEQUENCE" %s' % match, filename) <NEW_LINE> self.mismatches = _fgrep_count('"SEQUENCE" %s' % mismatch, filename) <NEW_LINE> self.gaps = _fgrep_count('"INSERT" %s' % gap, filename) <NEW_LINE> if gap == extension: <NEW_LINE> <INDENT> self.extensions = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.extensions = _fgrep_count('"INSERT" %s' % extension, filename) <NEW_LINE> <DEDENT> self.score = (match*self.matches + mismatch*self.mismatches + gap*self.gaps + extension*self.extensions) <NEW_LINE> if _any([self.matches, self.mismatches, self.gaps, self.extensions]): <NEW_LINE> <INDENT> self.coords = _get_coords(filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.coords = [(0, 0), (0,0)] <NEW_LINE> <DEDENT> <DEDENT> def identity_fraction(self): <NEW_LINE> <INDENT> return self.matches/(self.matches+self.mismatches) <NEW_LINE> <DEDENT> header = "identity_fraction\tmatches\tmismatches\tgaps\textensions" <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "\t".join([str(x) for x in (self.identity_fraction(), self.matches, self.mismatches, self.gaps, self.extensions)])
Calculate statistics from an ALB report
62599062d7e4931a7ef3d6fc
class TestHeartbeat(RouteTest): <NEW_LINE> <INDENT> CONTROLLER_NAME = "heartbeat" <NEW_LINE> def test_heartbeat(self): <NEW_LINE> <INDENT> self.assert_request_calls("/heartbeat", self.controller.heartbeat)
Test routes that end up in the HeartbeatController.
625990627cff6e4e811b7134
class Pet(object): <NEW_LINE> <INDENT> def __init__(self, birthyear, weight, length, color, owner=None): <NEW_LINE> <INDENT> self.age = datetime.datetime.now().year - birthyear <NEW_LINE> self.birthyear = birthyear <NEW_LINE> self.weight = weight <NEW_LINE> self.length = length <NEW_LINE> self.color = color <NEW_LINE> self.owner = owner
A class that represents a generic Pet.
625990623539df3088ecd98b
class TestPiecewisePolynomial1DFit(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.poly = np.array([1.0, 2.0, 3.0, 4.0]) <NEW_LINE> self.x = np.linspace(-3.0, 2.0, 100) <NEW_LINE> self.y = np.polyval(self.poly, self.x) <NEW_LINE> <DEDENT> def test_fit_eval(self): <NEW_LINE> <INDENT> interp = PiecewisePolynomial1DFit(max_degree=3) <NEW_LINE> self.assertRaises(NotFittedError, interp, self.x) <NEW_LINE> self.assertRaises(ValueError, interp.fit, [0, 0], [1, 2]) <NEW_LINE> interp.fit(self.x[::2], self.y[::2]) <NEW_LINE> y = interp(self.x) <NEW_LINE> assert_almost_equal(y[5:-5], self.y[5:-5], decimal=10) <NEW_LINE> interp.fit(self.x[0], self.y[0]) <NEW_LINE> y = interp(self.x) <NEW_LINE> assert_equal(y, np.tile(self.y[0], self.x.shape)) <NEW_LINE> <DEDENT> def test_stepwise_interp(self): <NEW_LINE> <INDENT> x = np.sort(np.random.rand(100)) * 4. - 2.5 <NEW_LINE> y = np.random.randn(100) <NEW_LINE> interp = PiecewisePolynomial1DFit(max_degree=0) <NEW_LINE> interp.fit(x, y) <NEW_LINE> assert_almost_equal(interp(x), y, decimal=10) <NEW_LINE> assert_almost_equal(interp(x + 1e-15), y, decimal=10) <NEW_LINE> assert_almost_equal(interp(x - 1e-15), y, decimal=10) <NEW_LINE> assert_almost_equal(_stepwise_interp(x, y, x), y, decimal=10) <NEW_LINE> assert_almost_equal(interp(self.x), _stepwise_interp(x, y, self.x), decimal=10) <NEW_LINE> <DEDENT> def test_linear_interp(self): <NEW_LINE> <INDENT> x = np.sort(np.random.rand(100)) * 4. - 2.5 <NEW_LINE> y = np.random.randn(100) <NEW_LINE> interp = PiecewisePolynomial1DFit(max_degree=1) <NEW_LINE> interp.fit(x, y) <NEW_LINE> assert_almost_equal(interp(x), y, decimal=10) <NEW_LINE> assert_almost_equal(_linear_interp(x, y, x), y, decimal=10) <NEW_LINE> assert_almost_equal(interp(self.x), _linear_interp(x, y, self.x), decimal=10)
Fit a 1-D piecewise polynomial to data from a known polynomial.
6259906232920d7e50bc7734
class TestClass(unittest.TestCase): <NEW_LINE> <INDENT> My_Class = xtuml.MetaClass('My_Class') <NEW_LINE> def test_plus_operator(self): <NEW_LINE> <INDENT> inst1 = self.My_Class() <NEW_LINE> inst2 = self.My_Class() <NEW_LINE> q = inst1 + inst2 <NEW_LINE> self.assertEqual(2, len(q)) <NEW_LINE> self.assertIn(inst1, q) <NEW_LINE> self.assertIn(inst2, q) <NEW_LINE> <DEDENT> def test_minus_operator(self): <NEW_LINE> <INDENT> inst1 = self.My_Class() <NEW_LINE> inst2 = self.My_Class() <NEW_LINE> q = inst1 - inst2 <NEW_LINE> self.assertEqual(1, len(q)) <NEW_LINE> self.assertIn(inst1, q) <NEW_LINE> self.assertNotIn(inst2, q) <NEW_LINE> <DEDENT> def test_non_persisting_attribute(self): <NEW_LINE> <INDENT> inst = self.My_Class() <NEW_LINE> setattr(inst, 'test1', 1) <NEW_LINE> self.assertEqual(getattr(inst, 'test1'), 1) <NEW_LINE> self.assertEqual(inst.test1, 1) <NEW_LINE> inst.__dict__['test2'] = 2 <NEW_LINE> self.assertEqual(getattr(inst, 'test2'), 2) <NEW_LINE> self.assertEqual(inst.test2, 2) <NEW_LINE> inst.test3 = 3 <NEW_LINE> self.assertEqual(getattr(inst, 'test3'), 3) <NEW_LINE> self.assertEqual(inst.test3, 3) <NEW_LINE> <DEDENT> def test_gettattr_with_undefined_attribute(self): <NEW_LINE> <INDENT> inst = self.My_Class() <NEW_LINE> self.assertRaises(AttributeError, getattr, inst, 'test') <NEW_LINE> <DEDENT> def test_undefined_attribute_access(self): <NEW_LINE> <INDENT> inst = self.My_Class() <NEW_LINE> try: <NEW_LINE> <INDENT> _ = inst.test <NEW_LINE> self.fail('AttributeError expected') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass
Test suite for the class xtuml.Class
62599062e64d504609df9f45
class VIEW3D_TP_Wire_Off(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "tp_ops.wire_off" <NEW_LINE> bl_label = "Wire off" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> selection = bpy.context.selected_objects <NEW_LINE> if not(selection): <NEW_LINE> <INDENT> for obj in bpy.data.objects: <NEW_LINE> <INDENT> obj.show_wire = False <NEW_LINE> obj.show_all_edges = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for obj in selection: <NEW_LINE> <INDENT> obj.show_wire = False <NEW_LINE> obj.show_all_edges = False <NEW_LINE> <DEDENT> <DEDENT> return {'FINISHED'}
Wire off
625990623539df3088ecd98c
class itkNumericTraitsFASL2(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_destroy__ = _itkNumericTraitsPython.delete_itkNumericTraitsFASL2 <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> _itkNumericTraitsPython.itkNumericTraitsFASL2_swiginit(self,_itkNumericTraitsPython.new_itkNumericTraitsFASL2(*args)) <NEW_LINE> <DEDENT> def max(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsFASL2_max() <NEW_LINE> <DEDENT> max = staticmethod(max) <NEW_LINE> def min(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsFASL2_min() <NEW_LINE> <DEDENT> min = staticmethod(min) <NEW_LINE> def NonpositiveMin(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsFASL2_NonpositiveMin() <NEW_LINE> <DEDENT> NonpositiveMin = staticmethod(NonpositiveMin) <NEW_LINE> def ZeroValue(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsFASL2_ZeroValue() <NEW_LINE> <DEDENT> ZeroValue = staticmethod(ZeroValue) <NEW_LINE> def OneValue(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsFASL2_OneValue() <NEW_LINE> <DEDENT> OneValue = staticmethod(OneValue)
Proxy of C++ itkNumericTraitsFASL2 class
62599062a8ecb03325872906
class Sparse(Transform): <NEW_LINE> <INDENT> shape = ShapeParam("shape", length=2, low=1) <NEW_LINE> init = SparseInitParam("init") <NEW_LINE> def __init__(self, shape, indices=None, init=1.0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.shape = shape <NEW_LINE> if scipy_sparse and isinstance(init, scipy_sparse.spmatrix): <NEW_LINE> <INDENT> assert indices is None <NEW_LINE> assert init.shape == self.shape <NEW_LINE> self.init = init <NEW_LINE> <DEDENT> elif indices is not None: <NEW_LINE> <INDENT> self.init = SparseMatrix(indices, init, shape) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError( "Either `init` must be a `scipy.sparse.spmatrix`, " "or `indices` must be specified.", attr="init", ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _argreprs(self): <NEW_LINE> <INDENT> return [f"shape={self.shape!r}"] <NEW_LINE> <DEDENT> def sample(self, rng=np.random): <NEW_LINE> <INDENT> if scipy_sparse and isinstance(self.init, scipy_sparse.spmatrix): <NEW_LINE> <INDENT> return self.init <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.init.sample(rng=rng) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def size_in(self): <NEW_LINE> <INDENT> return self.shape[1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def size_out(self): <NEW_LINE> <INDENT> return self.shape[0]
A sparse matrix transformation between an input and output signal. .. versionadded:: 3.0.0 Parameters ---------- shape : tuple of int The full shape of the sparse matrix: ``(size_out, size_in)``. indices : array_like of int An Nx2 array of integers indicating the (row,col) coordinates for the N non-zero elements in the matrix. init : `.Distribution` or array_like, optional A Distribution used to initialize the transform matrix, or a concrete instantiation for the matrix. If the matrix is square we also allow a scalar (equivalent to ``np.eye(n) * init``) or a vector (equivalent to ``np.diag(init)``) to represent the matrix more compactly.
625990627b25080760ed8858
class _Type(object): <NEW_LINE> <INDENT> def _getdefault(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def convert(self, config_path, key, value): <NEW_LINE> <INDENT> raise NotImplementedError
An abstract type for the configuration file schema. Types convert low-level configuration file elements to more useful high-level values and they provide default values for missing elements.
625990627d847024c075dac4
class AsyncConfigEntryAuth(AbstractAuth): <NEW_LINE> <INDENT> def __init__( self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str, ) -> None: <NEW_LINE> <INDENT> super().__init__(websession, API_URL) <NEW_LINE> self._oauth_session = oauth_session <NEW_LINE> self._client_id = client_id <NEW_LINE> self._client_secret = client_secret <NEW_LINE> <DEDENT> async def async_get_access_token(self) -> str: <NEW_LINE> <INDENT> if not self._oauth_session.valid_token: <NEW_LINE> <INDENT> await self._oauth_session.async_ensure_token_valid() <NEW_LINE> <DEDENT> return cast(str, self._oauth_session.token["access_token"]) <NEW_LINE> <DEDENT> async def async_get_creds(self) -> Credentials: <NEW_LINE> <INDENT> token = self._oauth_session.token <NEW_LINE> creds = Credentials( token=token["access_token"], refresh_token=token["refresh_token"], token_uri=OAUTH2_TOKEN, client_id=self._client_id, client_secret=self._client_secret, scopes=SDM_SCOPES, ) <NEW_LINE> creds.expiry = datetime.datetime.fromtimestamp(token["expires_at"]) <NEW_LINE> return creds
Provide Google Nest Device Access authentication tied to an OAuth2 based config entry.
62599062442bda511e95d8d1
class PyDMDesignerPlugin(QtDesigner.QPyDesignerCustomWidgetPlugin): <NEW_LINE> <INDENT> def __init__(self, cls, is_container=False, group='PyDM Widgets', extensions=None): <NEW_LINE> <INDENT> QtDesigner.QPyDesignerCustomWidgetPlugin.__init__(self) <NEW_LINE> self.initialized = False <NEW_LINE> self.is_container = is_container <NEW_LINE> self.cls = cls <NEW_LINE> self._group = group <NEW_LINE> self.extensions = extensions <NEW_LINE> self.manager = None <NEW_LINE> <DEDENT> def initialize(self, core): <NEW_LINE> <INDENT> if self.initialized: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> designer_hooks = DesignerHooks() <NEW_LINE> designer_hooks.form_editor = core <NEW_LINE> if self.extensions is not None and len(self.extensions) > 0: <NEW_LINE> <INDENT> self.manager = core.extensionManager() <NEW_LINE> if self.manager: <NEW_LINE> <INDENT> factory = PyDMExtensionFactory(parent=self.manager) <NEW_LINE> self.manager.registerExtensions( factory, 'org.qt-project.Qt.Designer.TaskMenu') <NEW_LINE> <DEDENT> <DEDENT> self.initialized = True <NEW_LINE> <DEDENT> def isInitialized(self): <NEW_LINE> <INDENT> return self.initialized <NEW_LINE> <DEDENT> def createWidget(self, parent): <NEW_LINE> <INDENT> w = self.cls(parent=parent) <NEW_LINE> try: <NEW_LINE> <INDENT> setattr(w, "extensions", self.extensions) <NEW_LINE> w.init_for_designer() <NEW_LINE> <DEDENT> except (AttributeError, NameError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return w <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return self.cls.__name__ <NEW_LINE> <DEDENT> def group(self): <NEW_LINE> <INDENT> return self._group <NEW_LINE> <DEDENT> def toolTip(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def whatsThis(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def isContainer(self): <NEW_LINE> <INDENT> return self.is_container <NEW_LINE> <DEDENT> def icon(self): <NEW_LINE> <INDENT> return QtGui.QIcon() <NEW_LINE> <DEDENT> def domXml(self): <NEW_LINE> <INDENT> return ( "<widget class=\"{0}\" name=\"{0}\">\n" " <property name=\"toolTip\" >\n" " <string>{1}</string>\n" " </property>\n" "</widget>\n" ).format(self.name(), self.toolTip()) <NEW_LINE> <DEDENT> def includeFile(self): <NEW_LINE> <INDENT> return self.cls.__module__
Parent class to standardize how pydm plugins are accessed in qt designer. All functions have default returns that can be overriden as necessary.
6259906266673b3332c31aeb
class CaCfar(): <NEW_LINE> <INDENT> def __init__(self, numGuardBins, numAvgBins, scale=0): <NEW_LINE> <INDENT> self.back = np.arange(-numAvgBins, 0, 1) <NEW_LINE> self.front = np.arange(numAvgBins) <NEW_LINE> self.numGuardBins = numGuardBins <NEW_LINE> self.numAvgBins = numAvgBins <NEW_LINE> self.scale = scale <NEW_LINE> self.forwardCells = None <NEW_LINE> self.reverseCells = None <NEW_LINE> self.forwardMean = 0 <NEW_LINE> self.reverseMean = 0 <NEW_LINE> <DEDENT> def _initCells(self, data): <NEW_LINE> <INDENT> self.forwardCells = (self.front + self.numGuardBins) % len(data) <NEW_LINE> self.reverseCells = (self.back - self.numGuardBins) % len(data) <NEW_LINE> self.forwardMean = data[self.forwardCells].sum() <NEW_LINE> self.reverseMean = data[self.reverseCells].sum() <NEW_LINE> <DEDENT> def process(self, data): <NEW_LINE> <INDENT> thresh = np.zeros_like(data) <NEW_LINE> dets = np.zeros_like(data, dtype=bool) <NEW_LINE> numPoints = len(data) <NEW_LINE> self._initCells(data) <NEW_LINE> for idx, cut in enumerate(data): <NEW_LINE> <INDENT> thresh[idx] = (self.forwardMean + self.reverseMean)/(2*self.numAvgBins) + self.scale <NEW_LINE> dets[idx] = cut > thresh[idx] <NEW_LINE> self.forwardMean -= data[self.forwardCells[0]] <NEW_LINE> self.reverseMean -= data[self.reverseCells[0]] <NEW_LINE> self.forwardCells += 1 <NEW_LINE> self.forwardCells %= numPoints <NEW_LINE> self.reverseCells += 1 <NEW_LINE> self.reverseCells %= numPoints <NEW_LINE> self.forwardMean += data[self.forwardCells[-1]] <NEW_LINE> self.reverseMean += data[self.reverseCells[-1]] <NEW_LINE> <DEDENT> return thresh, dets
Cell averaging constant false alarm rate detector
625990622ae34c7f260ac7d6
class ChDir(object): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.old_dir = os.getcwd() <NEW_LINE> self.new_dir = path <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> os.chdir(self.new_dir) <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> os.chdir(self.old_dir)
Step into a directory context on which to operate on. https://pythonadventures.wordpress.com/2013/12/15/chdir-a-context-manager-for-switching-working-directories/
625990628e7ae83300eea77d
class TestRunner(WorkflowTestRunner, NoseTestSuiteRunner): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _loaddevdata(): <NEW_LINE> <INDENT> from django.core.management import call_command <NEW_LINE> call_command( 'loaddevdata', reset=False, interactive=False, commit=False, verbosity=0 ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _clear_graphs(): <NEW_LINE> <INDENT> from webui.cnmain.utils import get_virtuoso <NEW_LINE> get_virtuoso('default').clear_regex( settings.TRIPLE_DATABASE['PREFIXES']['graph'] ) <NEW_LINE> get_virtuoso('master').clear_regex( settings.TRIPLE_DATABASE['PREFIXES']['graph'] ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _clear_store(): <NEW_LINE> <INDENT> import sqlalchemy <NEW_LINE> args = dict(settings.TABULAR_DATABASE) <NEW_LINE> args['PORT'] = args.get('PORT') or 5432 <NEW_LINE> conn_string = "postgresql://{USER}:{PASSWORD}@{HOST}:" "{PORT}/postgres".format(**args) <NEW_LINE> engine = sqlalchemy.create_engine(conn_string) <NEW_LINE> conn = engine.connect() <NEW_LINE> conn.execute('commit') <NEW_LINE> conn.execute( 'drop database if exists "{0}";'.format( settings.TABULAR_DATABASE['NAME'] ) ) <NEW_LINE> conn.execute('commit') <NEW_LINE> conn.execute( 'create database "{0}";'.format(settings.TABULAR_DATABASE['NAME']) ) <NEW_LINE> <DEDENT> def setup_databases(self): <NEW_LINE> <INDENT> self._clear_store() <NEW_LINE> res = super(TestRunner, self).setup_databases() <NEW_LINE> self._loaddevdata() <NEW_LINE> return res
Our test runner: load data before execution
62599062a8370b77170f1abd
class TestSignalsBlocked(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.obj = QObject() <NEW_LINE> self.args = tuple() <NEW_LINE> self.called = False <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> del self.obj <NEW_LINE> del self.args <NEW_LINE> <DEDENT> def callback(self, *args): <NEW_LINE> <INDENT> if args == self.args: <NEW_LINE> <INDENT> self.called = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Invalid arguments") <NEW_LINE> <DEDENT> <DEDENT> def testShortCircuitSignals(self): <NEW_LINE> <INDENT> QObject.connect(self.obj, SIGNAL('mysignal'), self.callback) <NEW_LINE> self.obj.emit(SIGNAL('mysignal')) <NEW_LINE> self.assert_(self.called) <NEW_LINE> self.called = False <NEW_LINE> self.obj.blockSignals(True) <NEW_LINE> self.obj.emit(SIGNAL('mysignal')) <NEW_LINE> self.assert_(not self.called) <NEW_LINE> <DEDENT> def testPythonSignals(self): <NEW_LINE> <INDENT> QObject.connect(self.obj, SIGNAL('mysignal(int,int)'), self.callback) <NEW_LINE> self.args = (1, 3) <NEW_LINE> self.obj.emit(SIGNAL('mysignal(int,int)'), *self.args) <NEW_LINE> self.assert_(self.called) <NEW_LINE> self.called = False <NEW_LINE> self.obj.blockSignals(True) <NEW_LINE> self.obj.emit(SIGNAL('mysignal(int,int)'), *self.args) <NEW_LINE> self.assert_(not self.called)
Test case to check if the signals are really blocked
625990623cc13d1c6d466e31
class PointerTypeDescriptor(DerivedTypeDescriptor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> DerivedTypeDescriptor.__init__(self)
Points to another type descriptor
62599062f7d966606f749431
class add_item(Command): <NEW_LINE> <INDENT> def __init__(self, item, get_uid=None, outer_instance: "Repository" = None): <NEW_LINE> <INDENT> super().__init__(outer_instance, undo_enabled=True) <NEW_LINE> self.item = item <NEW_LINE> self.uid = 0 <NEW_LINE> self.get_uid = get_uid <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if self.get_uid is None: <NEW_LINE> <INDENT> self.uid = self.outer_instance.generate_uid() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.uid = self.get_uid(self.item) <NEW_LINE> <DEDENT> if self.uid in self.outer_instance._items: <NEW_LINE> <INDENT> raise RepositoryError('UID is already in the repository!') <NEW_LINE> <DEDENT> self.outer_instance._items[self.uid] = self.item <NEW_LINE> return self.uid <NEW_LINE> <DEDENT> def undo(self): <NEW_LINE> <INDENT> self.outer_instance._items.pop(self.uid)
Adds an item to the list. :param item: The item to add. :return uid: The uid of the added item.
6259906292d797404e3896d5
@tinctest.skipLoading('scenario') <NEW_LINE> class co_create_with_column_sub_part_small(SQLTestCase): <NEW_LINE> <INDENT> sql_dir = 'co_create_with_column_sub_part/small/' <NEW_LINE> ans_dir = 'expected/co_create_with_column_sub_part/' <NEW_LINE> out_dir = 'output/'
@description: Create tables with compression attributes in with clause at sub-partition level - CO tables @gucs gp_create_table_random_default_distribution=off @product_version gpdb: [4.3-]
62599062f548e778e596cc78
class MashCredentialsDatastoreException(MashException): <NEW_LINE> <INDENT> pass
Base exception for credentials datastore class.
625990625fdd1c0f98e5f674
class EchoHandler(socketserver.DatagramRequestHandler): <NEW_LINE> <INDENT> def handle(self): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> line = self.rfile.read() <NEW_LINE> if not line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elemento = line.decode('utf-8') <NEW_LINE> linea = elemento.split('\r\n') <NEW_LINE> print("El cliente nos manda " + elemento) <NEW_LINE> Evento = ' Recived from ' + ipProxy + ':' + portProxy <NEW_LINE> Evento += ':' + elemento <NEW_LINE> hora = time.time() <NEW_LINE> makeLog(pathLog, hora, Evento) <NEW_LINE> METHOD = elemento.split(' ')[0] <NEW_LINE> if METHOD == 'INVITE': <NEW_LINE> <INDENT> ipEmisor = linea[4].split(' ')[1] <NEW_LINE> LINE = "SIP/2.0 100 Trying" + "\r\n" <NEW_LINE> LINE += "SIP/2.0 180 Ring" + "\r\n" <NEW_LINE> LINE += "SIP/2.0 200 OK" + "\r\n" <NEW_LINE> LINE += "Content-Type: application/sdp\r\n\r\n" <NEW_LINE> LINE += "v=0\r\n" <NEW_LINE> LINE += "o=" + username + " " <NEW_LINE> LINE += ipServer + "\r\ns=misesion\r\n" <NEW_LINE> LINE += "t=0\r\n" <NEW_LINE> LINE += "m=audio " + portRtp + " RTP\r\n" <NEW_LINE> <DEDENT> elif METHOD == 'BYE': <NEW_LINE> <INDENT> LINE = "SIP/2.0 200 OK" + "\r\n\r\n" <NEW_LINE> <DEDENT> elif METHOD == 'ACK': <NEW_LINE> <INDENT> aEjecutarVLC = 'cvlc rtp://@127.0.0.1:' <NEW_LINE> aEjecutarVLC += portRtp + '2> /dev/null &' <NEW_LINE> os.system(aEjecutarVLC) <NEW_LINE> aEjecutar = './mp32rtp -i ' + ipServer <NEW_LINE> aEjecutar = aEjecutar + ' -p ' + portRtp + '< ' + pathAudio <NEW_LINE> print("Vamos a ejecutar", aEjecutar) <NEW_LINE> os.system(aEjecutar) <NEW_LINE> print("Ejecucion finalizada") <NEW_LINE> <DEDENT> elif METHOD not in ['INVITE', 'ACK', 'BYE']: <NEW_LINE> <INDENT> LINE = "SIP/2.0 405 Method Not Allowed" + "\r\n\r\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LINE = "SIP/2.0 400 Bad Request" + "\r\n\r\n" <NEW_LINE> <DEDENT> if METHOD != 'ACK': <NEW_LINE> <INDENT> print("Enviando: " + LINE) <NEW_LINE> self.wfile.write(bytes(LINE, "utf-8")) <NEW_LINE> Evento = ' Send to ' + ipProxy + ':' + portProxy <NEW_LINE> Evento += ':' + LINE <NEW_LINE> hora = time.time() <NEW_LINE> makeLog(pathLog, hora, Evento)
Echo server class
625990624e4d562566373af7
class S3GroupAggregate(object): <NEW_LINE> <INDENT> def __init__(self, method, key, values): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> self.key = key <NEW_LINE> self.values = values <NEW_LINE> self.result = self.__compute(method, values) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __compute(method, values): <NEW_LINE> <INDENT> if values is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> values = [v for v in values if v is not None] <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> result = None <NEW_LINE> if method == "count": <NEW_LINE> <INDENT> result = len(set(values)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values = [v for v in values if isinstance(v, INTEGER_TYPES + (float,))] <NEW_LINE> if method == "sum": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = round(math.fsum(values), 2) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> <DEDENT> elif method == "min": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = min(values) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> <DEDENT> elif method == "max": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = max(values) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> <DEDENT> elif method == "avg": <NEW_LINE> <INDENT> num = len(values) <NEW_LINE> if num: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = sum(values) / float(num) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def aggregate(cls, items): <NEW_LINE> <INDENT> method = None <NEW_LINE> key = None <NEW_LINE> values = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if method is None: <NEW_LINE> <INDENT> method = item.method <NEW_LINE> key = item.key <NEW_LINE> <DEDENT> elif key != item.key or method != item.method: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> if item.values: <NEW_LINE> <INDENT> values.extend(item.values) <NEW_LINE> <DEDENT> <DEDENT> return cls(method, key, values)
Class representing aggregated values
6259906267a9b606de54761a
class Utility(): <NEW_LINE> <INDENT> pass
Reusable utilities and logic go here At the moment I don't see the need for sub classes
6259906207f4c71912bb0b27
class Events(FitnessFunc): <NEW_LINE> <INDENT> def fitness(self, N_k, T_k): <NEW_LINE> <INDENT> return N_k * np.log(N_k / T_k) <NEW_LINE> <DEDENT> def prior(self, N, Ntot): <NEW_LINE> <INDENT> if self.gamma is not None: <NEW_LINE> <INDENT> return self.gamma_prior(N, Ntot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 4 - np.log(73.53 * self.p0 * (N ** -0.478))
Fitness for binned or unbinned events Parameters ---------- p0 : float False alarm probability, used to compute the prior on N (see eq. 21 of Scargle 2012). Default prior is for p0 = 0. gamma : float or None If specified, then use this gamma to compute the general prior form, p ~ gamma^N. If gamma is specified, p0 is ignored.
6259906245492302aabfdbcb