code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class LiveTornadoTestCase(TransactionTestCase): <NEW_LINE> <INDENT> static_handler = None <NEW_LINE> @property <NEW_LINE> def live_server_url(self): <NEW_LINE> <INDENT> return 'http://%s:%s' % ( self.server_thread.host, self.server_thread.port) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> connections_override = {} <NEW_LINE> for conn in connections.all(): <NEW_LINE> <INDENT> if (conn.vendor == 'sqlite' and conn.settings_dict['NAME'] == ':memory:'): <NEW_LINE> <INDENT> conn.allow_thread_sharing = True <NEW_LINE> connections_override[conn.alias] = conn <NEW_LINE> <DEDENT> <DEDENT> specified_address = os.environ.get( 'DJANGO_LIVE_TEST_SERVER_ADDRESS', 'localhost:8081') <NEW_LINE> possible_ports = [] <NEW_LINE> try: <NEW_LINE> <INDENT> host, port_ranges = specified_address.split(':') <NEW_LINE> for port_range in port_ranges.split(','): <NEW_LINE> <INDENT> extremes = list(map(int, port_range.split('-'))) <NEW_LINE> assert len(extremes) in [1, 2] <NEW_LINE> if len(extremes) == 1: <NEW_LINE> <INDENT> possible_ports.append(extremes[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for port in range(extremes[0], extremes[1] + 1): <NEW_LINE> <INDENT> possible_ports.append(port) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> msg = 'Invalid address ("%s") for live server.' % specified_address <NEW_LINE> six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg), sys.exc_info()[2]) <NEW_LINE> <DEDENT> cls.server_thread = LiveTornadoThread( host, possible_ports, cls.static_handler, connections_override=connections_override ) <NEW_LINE> cls.server_thread.daemon = True <NEW_LINE> cls.server_thread.start() <NEW_LINE> cls.server_thread.is_ready.wait() <NEW_LINE> if cls.server_thread.error: <NEW_LINE> <INDENT> cls._tearDownClassInternal() <NEW_LINE> raise cls.server_thread.error <NEW_LINE> <DEDENT> super(LiveTornadoTestCase, cls).setUpClass() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _tearDownClassInternal(cls): <NEW_LINE> <INDENT> if hasattr(cls, 'server_thread'): <NEW_LINE> <INDENT> cls.server_thread.terminate() <NEW_LINE> cls.server_thread.join() <NEW_LINE> <DEDENT> for conn in connections.all(): <NEW_LINE> <INDENT> if (conn.vendor == 'sqlite' and conn.settings_dict['NAME'] == ':memory:'): <NEW_LINE> <INDENT> conn.allow_thread_sharing = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls._tearDownClassInternal() <NEW_LINE> super(LiveTornadoTestCase, cls).tearDownClass()
Does basically the same as TransactionTestCase but also launches a live http server in a separate thread so that the tests may use another testing framework, such as Selenium for example, instead of the built-in dummy client. Note that it inherits from TransactionTestCase instead of TestCase because the threads do not share the same transactions (unless if using in-memory sqlite) and each thread needs to commit all their transactions so that the other thread can see the changes.
625990601f5feb6acb16428a
class GaussianBlur(albu.GaussianBlur): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> blur_limit = args[0]["blur_limit"] if "blur_limit" in args[0].keys() else (3, 7) <NEW_LINE> sigma_limit = args[0]["blur_limit"] if "blur_limit" in args[0].keys() else 0 <NEW_LINE> always_apply = bool(args[0]["always_apply"]) if "always_apply" in args[0].keys() else False <NEW_LINE> p = float(args[0]["prob"]) if "prob" in args[0].keys() else 0.5 <NEW_LINE> super(GaussianBlur, self).__init__(blur_limit, sigma_limit, always_apply, p)
Blur the input image using using a Gaussian filter with a random kernel size. Args: blur_limit (int, (int, int)): maximum Gaussian kernel size for blurring the input image. Must be zero or odd and in range [0, inf). If set to 0 it will be computed from sigma as `round(sigma * (3 if img.dtype == np.uint8 else 4) * 2 + 1) + 1`. If set single value `blur_limit` will be in range (0, blur_limit). Default: (3, 7). sigma_limit (float, (float, float)): Gaussian kernel standard deviation. Must be greater in range [0, inf). If set single value `sigma_limit` will be in range (0, sigma_limit). If set to 0 sigma will be computed as `sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. Default: 0. p (float): probability of applying the transform. Default: 0.5. Targets: image Image types: uint8, float32
625990608a43f66fc4bf382e
class DescribeRuleSetsResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.L4RuleSets = None <NEW_LINE> self.L7RuleSets = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("L4RuleSets") is not None: <NEW_LINE> <INDENT> self.L4RuleSets = [] <NEW_LINE> for item in params.get("L4RuleSets"): <NEW_LINE> <INDENT> obj = KeyValueRecord() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.L4RuleSets.append(obj) <NEW_LINE> <DEDENT> <DEDENT> if params.get("L7RuleSets") is not None: <NEW_LINE> <INDENT> self.L7RuleSets = [] <NEW_LINE> for item in params.get("L7RuleSets"): <NEW_LINE> <INDENT> obj = KeyValueRecord() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.L7RuleSets.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId")
DescribeRuleSets返回参数结构体
625990602ae34c7f260ac786
class UnknownProtocolError(BaseWsException): <NEW_LINE> <INDENT> _message = "Unknown protocol"
An exception for denoting that a network protocol is not known.
62599060adb09d7d5dc0bc0a
class ConnectionPool(object): <NEW_LINE> <INDENT> scheme = None <NEW_LINE> QueueCls = LifoQueue <NEW_LINE> def __init__(self, host, port=None): <NEW_LINE> <INDENT> if not host: <NEW_LINE> <INDENT> raise LocationValueError("No host specified.") <NEW_LINE> <DEDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s(host=%r, port=%r)' % (type(self).__name__, self.host, self.port) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.close() <NEW_LINE> return False <NEW_LINE> <DEDENT> def close(): <NEW_LINE> <INDENT> pass
Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
62599060097d151d1a2c270f
class NetScience(DataSet): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _process(self): <NEW_LINE> <INDENT> V = {} <NEW_LINE> tree = ET.parse("datasets/netscience.xml") <NEW_LINE> for node in tree.iter("node"): <NEW_LINE> <INDENT> attrs = node.attrib <NEW_LINE> V[attrs['id']] = attrs['title'] <NEW_LINE> <DEDENT> N = len(V) <NEW_LINE> E = Set() <NEW_LINE> for link in tree.iter("link"): <NEW_LINE> <INDENT> attrs = link.attrib <NEW_LINE> E.add((int(attrs['target']), int(attrs['source']))) <NEW_LINE> <DEDENT> return Data(V, E, N)
Process netscience data set
6259906038b623060ffaa3a0
class TimeoutLock(object): <NEW_LINE> <INDENT> def __init__(self, lock, timeout): <NEW_LINE> <INDENT> self.lock = lock <NEW_LINE> self.timeout = timeout <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.acquire() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, tb): <NEW_LINE> <INDENT> self.release() <NEW_LINE> <DEDENT> def acquire(self): <NEW_LINE> <INDENT> if not self._waitLock(): <NEW_LINE> <INDENT> raise TimeoutExceededSerialLockError( 'Timeout exceeded whilst waiting for agent communications') <NEW_LINE> <DEDENT> <DEDENT> def release(self): <NEW_LINE> <INDENT> self.lock.release() <NEW_LINE> <DEDENT> def _waitLock(self): <NEW_LINE> <INDENT> with self.lock.cond: <NEW_LINE> <INDENT> current_time = start_time = time.time() <NEW_LINE> while current_time < start_time + self.timeout: <NEW_LINE> <INDENT> if self.lock.lock.acquire(False): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lock.cond.wait(self.timeout - current_time + start_time) <NEW_LINE> current_time = time.time() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
Provide lock functionality with a timeout.
625990601f037a2d8b9e53bb
class TestNodeTestcase(NodeTestCase): <NEW_LINE> <INDENT> def test_snapshots_work(self): <NEW_LINE> <INDENT> has_kernel = lambda: "kernel" in self.node.ssh("rpm -q kernel") <NEW_LINE> self.assertTrue(has_kernel()) <NEW_LINE> with self.node.snapshot().context(): <NEW_LINE> <INDENT> self.node.ssh("rpm -e --nodeps kernel") <NEW_LINE> with self.assertRaises(sh.ErrorReturnCode_1): <NEW_LINE> <INDENT> has_kernel() <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(has_kernel()) <NEW_LINE> <DEDENT> def test_ssh_works(self): <NEW_LINE> <INDENT> self.node.ssh("pwd") <NEW_LINE> <DEDENT> def test_reboot_works(self): <NEW_LINE> <INDENT> with self.assertRaises(sh.ErrorReturnCode_255): <NEW_LINE> <INDENT> self.node.ssh("reboot") <NEW_LINE> <DEDENT> self.node.wait_reboot(timeout=60) <NEW_LINE> self.node.ssh("pwd")
Let's ensure that the basic functionality is working
62599060379a373c97d9a6c4
class LogMessage: <NEW_LINE> <INDENT> def __init__(self, tstamp: datetime.datetime, sender: str, msg: str, own: bool = False) -> None: <NEW_LINE> <INDENT> self.tstamp = tstamp <NEW_LINE> self.sender = sender <NEW_LINE> self.own = own <NEW_LINE> self.msg = msg <NEW_LINE> self.is_read = False <NEW_LINE> <DEDENT> def get_short_sender(self) -> str: <NEW_LINE> <INDENT> return self.sender.split("@")[0] <NEW_LINE> <DEDENT> def read(self, mark_read: bool = True) -> str: <NEW_LINE> <INDENT> tstamp_str = self.tstamp.strftime("%H:%M:%S") <NEW_LINE> msg = f"{tstamp_str} {self.get_short_sender()}: {self.msg}" <NEW_LINE> if mark_read: <NEW_LINE> <INDENT> self.is_read = True <NEW_LINE> <DEDENT> return msg <NEW_LINE> <DEDENT> def is_equal(self, other: "LogMessage") -> bool: <NEW_LINE> <INDENT> if self.tstamp != other.tstamp: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.sender != other.sender: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.msg != other.msg: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Class for log messages to be displayed in LogWins
6259906024f1403a9268641e
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_game): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = ai_game.screen <NEW_LINE> self.settings = ai_game.settings <NEW_LINE> self.image = pygame.image.load('/Users/mahdieh/Desktop/Alien_game/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right or self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.settings.alien_speed * self.settings.fleet_direction) <NEW_LINE> self.rect.x = self.x
A class to represent a single alien in the fleet.
62599060baa26c4b54d50942
@dataclasses.dataclass(frozen=True) <NEW_LINE> class ResolvedMutationSpec(MutationSpec): <NEW_LINE> <INDENT> start_pos: Tuple[int, int] <NEW_LINE> end_pos: Tuple[int, int] <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> super().__post_init__() <NEW_LINE> if self.start_pos[0] > self.end_pos[0]: <NEW_LINE> <INDENT> raise ValueError("Start line must not be after end line") <NEW_LINE> <DEDENT> if self.start_pos[0] == self.end_pos[0]: <NEW_LINE> <INDENT> if self.start_pos[1] >= self.end_pos[1]: <NEW_LINE> <INDENT> raise ValueError("End position must come after start position.")
A MutationSpec with the location of the mutation resolved.
6259906032920d7e50bc76e6
class Sample(Model): <NEW_LINE> <INDENT> def __init__(self, center_code: int=None, id: str=None, collection_method: str=None, typing: List[Typing]=None): <NEW_LINE> <INDENT> self.swagger_types = { 'center_code': int, 'id': str, 'collection_method': str, 'typing': List[Typing], 'seq_records': Dict } <NEW_LINE> self.attribute_map = { 'center_code': 'center_code', 'id': 'id', 'collection_method': 'collection_method', 'typing': 'typing', 'seq_records': 'seq_records' } <NEW_LINE> self._center_code = center_code <NEW_LINE> self._id = id <NEW_LINE> self._collection_method = collection_method <NEW_LINE> self._typing = typing <NEW_LINE> self._seq_records = {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'Sample': <NEW_LINE> <INDENT> return deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def center_code(self) -> int: <NEW_LINE> <INDENT> return self._center_code <NEW_LINE> <DEDENT> @center_code.setter <NEW_LINE> def center_code(self, center_code: int): <NEW_LINE> <INDENT> self._center_code = center_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self) -> str: <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id: str): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def collection_method(self) -> str: <NEW_LINE> <INDENT> return self._collection_method <NEW_LINE> <DEDENT> @collection_method.setter <NEW_LINE> def collection_method(self, collection_method: str): <NEW_LINE> <INDENT> self._collection_method = collection_method <NEW_LINE> <DEDENT> @property <NEW_LINE> def typing(self) -> List[Typing]: <NEW_LINE> <INDENT> return self._typing <NEW_LINE> <DEDENT> @typing.setter <NEW_LINE> def typing(self, typing: List[Typing]): <NEW_LINE> <INDENT> self._typing = typing <NEW_LINE> <DEDENT> @property <NEW_LINE> def seq_records(self) -> Dict: <NEW_LINE> <INDENT> return self._seq_records <NEW_LINE> <DEDENT> def create_seqrecords(self): <NEW_LINE> <INDENT> records = {} <NEW_LINE> subid = self.id <NEW_LINE> for typing in self.typing: <NEW_LINE> <INDENT> loc, seq_rec = typing.create_seqrecord(subid) <NEW_LINE> if loc not in records: <NEW_LINE> <INDENT> records.update({loc: seq_rec}) <NEW_LINE> <DEDENT> <DEDENT> self._seq_records = records
Examples: >>> from pyhml.models.typing import Typing >>> from pyhml.models.sample import Sample
62599060a8370b77170f1a6f
class ListLevel(AbstractLevel, QtGui.QListView): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(ListLevel, self).__init__(parent) <NEW_LINE> <DEDENT> def model_changed(self, model): <NEW_LINE> <INDENT> self.setModel(model) <NEW_LINE> if model is not None: <NEW_LINE> <INDENT> self.setCurrentIndex(self.model().index(0, 0)) <NEW_LINE> <DEDENT> <DEDENT> def set_root(self, index): <NEW_LINE> <INDENT> if not index.isValid(): <NEW_LINE> <INDENT> self.setModel(None) <NEW_LINE> self.setCurrentIndex(QtCore.QModelIndex()) <NEW_LINE> self.new_root.emit(QtCore.QModelIndex()) <NEW_LINE> return <NEW_LINE> <DEDENT> self.setRootIndex(index) <NEW_LINE> if self.model().hasChildren(index): <NEW_LINE> <INDENT> self.setCurrentIndex(self.model().index(0, 0, index)) <NEW_LINE> self.new_root.emit(self.model().index(0, 0, index)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setCurrentIndex(QtCore.QModelIndex()) <NEW_LINE> self.new_root.emit(QtCore.QModelIndex()) <NEW_LINE> <DEDENT> <DEDENT> def selected_indexes(self, ): <NEW_LINE> <INDENT> return [self.currentIndex()] <NEW_LINE> <DEDENT> def currentChanged(self, current, prev): <NEW_LINE> <INDENT> m = self.model() <NEW_LINE> p = current.parent() <NEW_LINE> index = m.index(current.row(), 0, p) <NEW_LINE> self.new_root.emit(index) <NEW_LINE> return super(ListLevel, self).currentChanged(current, prev) <NEW_LINE> <DEDENT> def set_index(self, index): <NEW_LINE> <INDENT> self.setCurrentIndex(index) <NEW_LINE> self.new_root.emit(index) <NEW_LINE> self.scrollTo(index) <NEW_LINE> <DEDENT> def resizeEvent(self, event): <NEW_LINE> <INDENT> if self.resizeMode() == self.Adjust: <NEW_LINE> <INDENT> self.scheduleDelayedItemsLayout() <NEW_LINE> <DEDENT> return super(ListLevel, self).resizeEvent(event)
A level that consists of a listview to be used in a CascadeView
62599060a79ad1619776b60d
class Solution: <NEW_LINE> <INDENT> def reorderList(self, head): <NEW_LINE> <INDENT> if head==None or head.next==None: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> dummy = ListNode(0,None) <NEW_LINE> fast_node = dummy <NEW_LINE> pivot = dummy <NEW_LINE> dummy.next = head <NEW_LINE> while fast_node != None and fast_node.next != None: <NEW_LINE> <INDENT> fast_node = fast_node.next.next <NEW_LINE> pivot = pivot.next <NEW_LINE> <DEDENT> right_list = pivot.next <NEW_LINE> pivot.next = None <NEW_LINE> left_list = head <NEW_LINE> prev_node = right_list <NEW_LINE> next_node = right_list.next <NEW_LINE> prev_node.next = None <NEW_LINE> while next_node != None: <NEW_LINE> <INDENT> tmp_point = next_node.next <NEW_LINE> next_node.next = prev_node <NEW_LINE> prev_node = next_node <NEW_LINE> next_node = tmp_point <NEW_LINE> <DEDENT> right_list = prev_node <NEW_LINE> dummy.next = left_list <NEW_LINE> while left_list != None and right_list != None: <NEW_LINE> <INDENT> next_left = left_list.next <NEW_LINE> left_list.next = right_list <NEW_LINE> next_right = right_list.next <NEW_LINE> right_list.next = next_left <NEW_LINE> left_list = next_left <NEW_LINE> right_list = next_right <NEW_LINE> <DEDENT> return dummy.next
@param head: The first node of the linked list. @return: nothing
6259906097e22403b383c5ad
class keyi_data_frm(object): <NEW_LINE> <INDENT> implements(IVocabularyFactory) <NEW_LINE> def __call__(self, context=None): <NEW_LINE> <INDENT> items = ( SimpleTerm(value='dga', title=u'數位典藏'), SimpleTerm(value='dnt', title=u'捐贈'), SimpleTerm(value='cwk', title=u'合作'), SimpleTerm(value='fdw', title=u'田野調查'), ) <NEW_LINE> return SimpleVocabulary(items)
KeYi
625990606e29344779b01cef
class TrainReservationSchema(SchemaObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.schema = 'TrainReservation'
Schema Mixin for TrainReservation Usage: place after django model in class definition, schema will return the schema.org url for the object A reservation for train travel.
625990607cff6e4e811b70e6
class SharedLinker(config.compile.processor.Processor): <NEW_LINE> <INDENT> def __init__(self, argDB): <NEW_LINE> <INDENT> self.compiler = Compiler(argDB, usePreprocessorFlags = False) <NEW_LINE> self.configLibraries = config.libraries.Configure(config.framework.Framework(clArgs = '', argDB = argDB, tmpDir = os.getcwd())) <NEW_LINE> config.compile.processor.Processor.__init__(self, argDB, ['LD_SHARED', self.compiler.name], ['LDFLAGS', 'sharedLibraryFlags'], '.o', None) <NEW_LINE> self.outputFlag = '-o' <NEW_LINE> self.libraries = sets.Set() <NEW_LINE> return <NEW_LINE> <DEDENT> def setArgDB(self, argDB): <NEW_LINE> <INDENT> args.ArgumentProcessor.setArgDB(self, argDB) <NEW_LINE> self.compiler.argDB = argDB <NEW_LINE> self.configLibraries.argDB = argDB <NEW_LINE> self.configLibraries.framework.argDB = argDB <NEW_LINE> return <NEW_LINE> <DEDENT> argDB = property(args.ArgumentProcessor.getArgDB, setArgDB, doc = 'The RDict argument database') <NEW_LINE> def copy(self, other): <NEW_LINE> <INDENT> other.compiler = self.compiler <NEW_LINE> other.configLibraries = self.configLibraries <NEW_LINE> other.outputFlag = self.outputFlag <NEW_LINE> other.libraries = sets.Set(self.libraries) <NEW_LINE> return <NEW_LINE> <DEDENT> def getFlags(self): <NEW_LINE> <INDENT> if not hasattr(self, '_flags'): <NEW_LINE> <INDENT> flagsName = self.flagsName[:] <NEW_LINE> if hasattr(self, 'configCompilers'): <NEW_LINE> <INDENT> self.compiler.configCompilers = self.configCompilers <NEW_LINE> <DEDENT> if self.getProcessor() == self.compiler.getProcessor(): <NEW_LINE> <INDENT> flagsName.extend(self.compiler.flagsName) <NEW_LINE> <DEDENT> if hasattr(self, 'configCompilers'): <NEW_LINE> <INDENT> flags = [getattr(self.configCompilers, name) for name in flagsName] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flags = [self.argDB[name] for name in flagsName] <NEW_LINE> <DEDENT> return ' '.join(flags) <NEW_LINE> <DEDENT> return self._flags <NEW_LINE> <DEDENT> flags = property(getFlags, config.compile.processor.Processor.setFlags, doc = 'The flags for the executable') <NEW_LINE> def getExtraArguments(self): <NEW_LINE> <INDENT> if not hasattr(self, '_extraArguments'): <NEW_LINE> <INDENT> return self.configCompilers.LIBS <NEW_LINE> <DEDENT> return self._extraArguments <NEW_LINE> <DEDENT> extraArguments = property(getExtraArguments, config.compile.processor.Processor.setExtraArguments, doc = 'Optional arguments for the end of the command') <NEW_LINE> def getTarget(self, source, shared, prefix = 'lib'): <NEW_LINE> <INDENT> dirname, basename = os.path.split(source) <NEW_LINE> base, ext = os.path.splitext(basename) <NEW_LINE> if prefix: <NEW_LINE> <INDENT> if not (len(base) > len(prefix) and base[:len(prefix)] == prefix): <NEW_LINE> <INDENT> base = prefix+base <NEW_LINE> <DEDENT> <DEDENT> if hasattr(self, 'configCompilers'): <NEW_LINE> <INDENT> base += '.'+self.configCompilers.setCompilers.sharedLibraryExt <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base += '.'+self.argDB['LD_SHARED_SUFFIX'] <NEW_LINE> <DEDENT> return os.path.join(dirname, base)
The C linker
62599060009cb60464d02bd7
class CryptoMixin(models.Model): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def encrypted_fields(cls): <NEW_LINE> <INDENT> return [fld.name for fld in cls._meta.fields if isinstance(fld, BaseField)] <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True
Model mixin for a user model that need to list it's encrypted fields.
62599060d268445f2663a6ad
class RawHook(Hook): <NEW_LINE> <INDENT> def __init__(self, plugin, irc_raw_hook): <NEW_LINE> <INDENT> super().__init__("irc_raw", plugin, irc_raw_hook) <NEW_LINE> self.triggers = irc_raw_hook.triggers <NEW_LINE> <DEDENT> def is_catch_all(self): <NEW_LINE> <INDENT> return "*" in self.triggers <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Raw[triggers: {}, {}]".format(list(self.triggers), Hook.__repr__(self)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "irc raw {} ({}) from {}".format(self.function_name, ",".join(self.triggers), self.plugin.file_name)
:type triggers: set[str]
6259906099cbb53fe6832582
class WebPage(object): <NEW_LINE> <INDENT> html = None <NEW_LINE> def fetch(self, url): <NEW_LINE> <INDENT> req = urllib2.Request(url) <NEW_LINE> response = urllib2.urlopen(req) <NEW_LINE> self.html = response.read() <NEW_LINE> if not self.html: <NEW_LINE> <INDENT> raise Exception('Unable to fetch the webpage HTML')
Provides the fecth method to other classes
6259906007f4c71912bb0adf
class ProcessViewer(object): <NEW_LINE> <INDENT> def __init__(self, children): <NEW_LINE> <INDENT> self.children = children <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> import ipywidgets as widgets <NEW_LINE> a = widgets.Tab() <NEW_LINE> for i in range(len(self.children)): <NEW_LINE> <INDENT> a.set_title(i, "Process " + str(i)) <NEW_LINE> <DEDENT> a.children = [children.create() for children in self.children if children is not None] <NEW_LINE> return a <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> import ipywidgets as widgets <NEW_LINE> from IPython.core.display import display <NEW_LINE> if len(self.children) > 0: <NEW_LINE> <INDENT> a = self.create() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = widgets.HTML("<strong>Calculation list empty. Nothing to show.</strong>") <NEW_LINE> <DEDENT> display(a)
A widget to summarize all the infromation from different processes. Must be filled with the widgets of the single processes
625990607047854f46340a5f
class Ship: <NEW_LINE> <INDENT> ship_types = {'Carrier': 5, 'Battleship': 4, 'Cruiser': 3, 'Submarine': 3, 'Destroyer': 2} <NEW_LINE> def __init__(self, name, position, is_vertical=False): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.positions = [] <NEW_LINE> self.squares = [] <NEW_LINE> self.positions.append(position) <NEW_LINE> column = position[0] <NEW_LINE> row = position[1] <NEW_LINE> self.squares.append(Square(column, row)) <NEW_LINE> for i in range(Ship.ship_types[name] - 1): <NEW_LINE> <INDENT> if is_vertical: <NEW_LINE> <INDENT> row += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> column += 1 <NEW_LINE> <DEDENT> self.squares.append(Square(column, row)) <NEW_LINE> self.positions.append((column, row)) <NEW_LINE> <DEDENT> <DEDENT> def is_sunk(self): <NEW_LINE> <INDENT> sunk = True <NEW_LINE> for square in self.squares: <NEW_LINE> <INDENT> if not square.is_marked: <NEW_LINE> <INDENT> sunk = False <NEW_LINE> <DEDENT> <DEDENT> return sunk
Class has methods to create and manage single Ship object. Attributes: ships_types : dict Keys with ships names and values with corresponding lengths. name : str One of 5 possible ship names. positions : list of tuples of ints Carries all positions of ship squares. squares : list of Square objects Carries all ship's parts. is_vertical : bool Indicates ship direction. True if vertical, False if horizontal.
625990608a43f66fc4bf3830
class Base(): <NEW_LINE> <INDENT> __nb_objects = 0 <NEW_LINE> def __init__(self, id=None): <NEW_LINE> <INDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Base.__nb_objects += 1 <NEW_LINE> self.id = Base.__nb_objects <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def to_json_string(list_dictionaries): <NEW_LINE> <INDENT> if (list_dictionaries is None or len(list_dictionaries) == 0): <NEW_LINE> <INDENT> return "[]" <NEW_LINE> <DEDENT> return json.dumps(list_dictionaries) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def save_to_file(cls, list_objs): <NEW_LINE> <INDENT> my_list = [] <NEW_LINE> fname = cls.__name__ + ".json" <NEW_LINE> if (list_objs is not None): <NEW_LINE> <INDENT> for indx in list_objs: <NEW_LINE> <INDENT> my_list.append(indx.to_dictionary()) <NEW_LINE> <DEDENT> <DEDENT> jstr = cls.to_json_string(my_list) <NEW_LINE> with open(fname, "w") as f: <NEW_LINE> <INDENT> f.write(jstr) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def from_json_string(json_string): <NEW_LINE> <INDENT> if (json_string is None or len(json_string) == 0): <NEW_LINE> <INDENT> return ([]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (json.loads(json_string)) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def create(cls, **dictionary): <NEW_LINE> <INDENT> if (cls.__name__ == "Rectangle"): <NEW_LINE> <INDENT> dummy = cls(1, 1) <NEW_LINE> <DEDENT> elif (cls.__name__ == "Square"): <NEW_LINE> <INDENT> dummy = cls(1) <NEW_LINE> <DEDENT> dummy.update(**dictionary) <NEW_LINE> return (dummy) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load_from_file(cls): <NEW_LINE> <INDENT> my_list = [] <NEW_LINE> fname = str(cls.__name__) + ".json" <NEW_LINE> try: <NEW_LINE> <INDENT> with open(fname, "r") as jsonfile: <NEW_LINE> <INDENT> listJson = Base.from_json_string(jsonfile.read()) <NEW_LINE> return [cls.create(**d) for d in listJson] <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def save_to_file_csv(cls, list_objs): <NEW_LINE> <INDENT> if list_objs is None or list_objs == []: <NEW_LINE> <INDENT> my_list = "[]" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> my_list = cls.to_json_string( [o.to_dictionary() for o in list_objs]) <NEW_LINE> <DEDENT> new_file = cls.__name__ + ".csv" <NEW_LINE> with open(new_file, "w") as f: <NEW_LINE> <INDENT> f.write(my_list) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def load_from_file_csv(cls): <NEW_LINE> <INDENT> fname = cls.__name__ + ".csv" <NEW_LINE> if not os.path.exists(fname): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> list_dict = [] <NEW_LINE> with open(fname, "r") as f: <NEW_LINE> <INDENT> str1 = f.read() <NEW_LINE> list_dict = cls.from_json_string(str1) <NEW_LINE> <DEDENT> return [cls.create(**d) for d in list_dict]
first class Base
62599060cb5e8a47e493ccd6
class Pixel(object): <NEW_LINE> <INDENT> def __init__(self, state, x, y, colour_on, colour_off): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.colour_on = colour_on <NEW_LINE> self.colour_off = colour_off <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def set_colour_on(self, rgb): <NEW_LINE> <INDENT> self.colour_on = rgb <NEW_LINE> <DEDENT> def get_colour_on(self): <NEW_LINE> <INDENT> return self.colour_on <NEW_LINE> <DEDENT> def set_state(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> <DEDENT> def get_state(self): <NEW_LINE> <INDENT> return self.state
A pixel describes one pixel in the matrix of the WordClock. It holds information about its color, state and position in the WordClock matrix.
62599060462c4b4f79dbd0a7
class IsolationPlugin(Plugin): <NEW_LINE> <INDENT> score = 10 <NEW_LINE> name = 'isolation' <NEW_LINE> def configure(self, options, conf): <NEW_LINE> <INDENT> Plugin.configure(self, options, conf) <NEW_LINE> self._mod_stack = [] <NEW_LINE> <DEDENT> def beforeContext(self): <NEW_LINE> <INDENT> mods = sys.modules.copy() <NEW_LINE> self._mod_stack.append(mods) <NEW_LINE> <DEDENT> def afterContext(self): <NEW_LINE> <INDENT> mods = self._mod_stack.pop() <NEW_LINE> to_del = [ m for m in sys.modules.keys() if m not in mods ] <NEW_LINE> if to_del: <NEW_LINE> <INDENT> log.debug('removing sys modules entries: %s', to_del) <NEW_LINE> for mod in to_del: <NEW_LINE> <INDENT> del sys.modules[mod] <NEW_LINE> <DEDENT> <DEDENT> sys.modules.update(mods) <NEW_LINE> <DEDENT> def loadTestsFromNames(self, names, module=None): <NEW_LINE> <INDENT> if not names or len(names) == 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> loader = self.loader <NEW_LINE> plugins = self.conf.plugins <NEW_LINE> def lazy(): <NEW_LINE> <INDENT> for name in names: <NEW_LINE> <INDENT> plugins.beforeContext() <NEW_LINE> yield loader.loadTestsFromName(name, module=module) <NEW_LINE> plugins.afterContext() <NEW_LINE> <DEDENT> <DEDENT> return (loader.suiteClass(lazy), []) <NEW_LINE> <DEDENT> def prepareTestLoader(self, loader): <NEW_LINE> <INDENT> self.loader = loader
Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin should not be used with the coverage plugin in any other case where module reloading may produce undesirable side-effects.
62599060e76e3b2f99fda0a2
class memoize_invalidate(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> <DEDENT> def __get__(self, obj, objtype=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self.func <NEW_LINE> <DEDENT> return functools.partial(self, obj) <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> obj = args[0] <NEW_LINE> obj._cache = {} <NEW_LINE> return self.func(*args, **kwargs)
Use in conjunction with @memoize decorator when you want to reset instance cache when calling a specific method
62599060f548e778e596cc2b
class AppEngineTestCase(TransactionTestCase): <NEW_LINE> <INDENT> @property <NEW_LINE> def default_datastore_v3_stub_kwargs(self): <NEW_LINE> <INDENT> cp = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=1) <NEW_LINE> return { "use_sqlite": True, "require_indexes": True, "consistency_policy": cp, "auto_id_policy": datastore_stub_util.SCATTERED, } <NEW_LINE> <DEDENT> def _pre_setup(self): <NEW_LINE> <INDENT> self.testbed = testbed.Testbed() <NEW_LINE> self.testbed.activate() <NEW_LINE> for service_name, stub_method_name in testbed.INIT_STUB_METHOD_NAMES.items(): <NEW_LINE> <INDENT> default_kwargs_attr_name = "default_{}_stub_kwargs".format(service_name) <NEW_LINE> kwargs_attr_name = "{}_stub_kwargs".format(service_name) <NEW_LINE> default_kwargs = getattr(self, default_kwargs_attr_name, {}) <NEW_LINE> kwargs = getattr(self, kwargs_attr_name, {}) <NEW_LINE> default_kwargs.update(kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> getattr(self.testbed, stub_method_name, lambda: None)() <NEW_LINE> <DEDENT> except testbed.StubNotSupportedError as e: <NEW_LINE> <INDENT> log.warning( "Couldn't initialise stub with error {}. Continuing..." .format(str(e)) ) <NEW_LINE> <DEDENT> <DEDENT> self.clear_datastore() <NEW_LINE> <DEDENT> def _post_teardown(self): <NEW_LINE> <INDENT> self.clear_datastore() <NEW_LINE> self.testbed.deactivate() <NEW_LINE> <DEDENT> def clear_datastore(self): <NEW_LINE> <INDENT> datastore_stub = self.testbed.get_stub(testbed.DATASTORE_SERVICE_NAME) <NEW_LINE> datastore_stub.Clear() <NEW_LINE> <DEDENT> def users_login(self, email, user_id=None, is_admin=False): <NEW_LINE> <INDENT> self.testbed.setup_env( USER_EMAIL=email, USER_ID=user_id or '98211821748316341', USER_IS_ADMIN=str(int(is_admin)), AUTH_DOMAIN='testbed', overwrite=True, )
Common test setup required for testing App Engine-related things. You can provide your own default and specific keyword arguments for each service stub by implementing properties of the names `default_{service_name}_stub_kwargs` and `{service_name}_stub_kwargs` where {service_name} is one of the names defined in google.appengine.ext.testbed
62599060379a373c97d9a6c7
class BertForSequenceClassification(BertPreTrainedModel): <NEW_LINE> <INDENT> def __init__(self, config, num_labels): <NEW_LINE> <INDENT> super(BertForSequenceClassification, self).__init__(config) <NEW_LINE> self.num_labels = num_labels <NEW_LINE> self.bert = BertModel(config) <NEW_LINE> self.dropout = nn.Dropout(config.hidden_dropout_prob) <NEW_LINE> self.classifier = nn.Linear(config.hidden_size, num_labels) <NEW_LINE> self.apply(self.init_bert_weights) <NEW_LINE> <DEDENT> def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None): <NEW_LINE> <INDENT> _, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False) <NEW_LINE> pooled_output = self.dropout(pooled_output) <NEW_LINE> logits = self.classifier(pooled_output) <NEW_LINE> if labels is not None: <NEW_LINE> <INDENT> loss_fct = CrossEntropyLoss() <NEW_LINE> loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) <NEW_LINE> return loss <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return logits
BERT models for classification. This module is composed of the BERT models with a linear layer on top of the pooled output. Params: `config`: a BertConfig class instance with the configuration to build a new models. `num_labels`: the number of classes for the classifier. Default = 2. Inputs: `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length] with the word token indices in the vocabulary. Items in the batch should begin with the special "CLS" token. (see the tokens preprocessing logic in the scripts `extract_features.py`, `run_classifier.py` and `run_squad.py`) `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to a `sentence B` token (see BERT paper for more details). `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max input sequence length in the current batch. It's the mask that we typically use for attention when a batch has varying length sentences. `labels`: labels for the classification output: torch.LongTensor of shape [batch_size] with indices selected in [0, ..., num_labels]. Outputs: if `labels` is not `None`: Outputs the CrossEntropy classification loss of the output with the labels. if `labels` is `None`: Outputs the classification logits of shape [batch_size, num_labels]. Example usage: ```python # Already been converted into WordPiece token ids input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]]) input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]]) token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]]) config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072) num_labels = 2 models = BertForSequenceClassification(config, num_labels) logits = models(input_ids, token_type_ids, input_mask) ```
62599060435de62698e9d4a9
class AuthenticatorABC(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def _authenticate_packet(self, pkt: "Packet", **kwargs) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _on_pass(self, sock: "SSLSocket", pkt: "Packet", **kwargs) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _on_fail(self, sock: "SSLSocket", pkt: "Packet", **kwargs) -> None: <NEW_LINE> <INDENT> pass
Authenticator Absctract Class The absctract class for implementation.
625990608e71fb1e983bd16e
class MyTCPServer(socketserver.BaseRequestHandler): <NEW_LINE> <INDENT> def handle(self): <NEW_LINE> <INDENT> self.data = self.request.recv(1024).strip() <NEW_LINE> log.info(f"got data: {self.data}") <NEW_LINE> self.request.sendall(self.data.upper()+b"\n")
Simplest TCP server that echoes back the message.
625990609c8ee82313040cdb
class Breed(Base): <NEW_LINE> <INDENT> __tablename__ = 'breed' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String, nullable=False) <NEW_LINE> species_id = Column(Integer, ForeignKey('species.id'), nullable=False ) <NEW_LINE> pets = relationship('Pet', backref="breed") <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "{}: {}".format(self.name, self.species)
domain model class for a Breed has a with many-to-one relationship withSpecies
625990603539df3088ecd93f
class Department(models.Model): <NEW_LINE> <INDENT> name = models.CharField( "Nombre del Departamento", max_length=100, ) <NEW_LINE> department_chief = models.OneToOneField( 'Profile', related_name='+', on_delete=models.CASCADE, null=True, blank=True, verbose_name="Encargado del Departamento", ) <NEW_LINE> management = models.ForeignKey( Management, on_delete=models.CASCADE, verbose_name="Dirección a la que Pertenece", ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name + " -> " + self.management.name
Comments
62599060498bea3a75a59150
class XmlDump(object): <NEW_LINE> <INDENT> def __init__(self, filename, allrevisions=False): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> if allrevisions: <NEW_LINE> <INDENT> self._parse = self._parse_all <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._parse = self._parse_only_latest <NEW_LINE> <DEDENT> <DEDENT> def parse(self): <NEW_LINE> <INDENT> with open_compressed(self.filename) as source: <NEW_LINE> <INDENT> context = iterparse(source, events=(str('start'), str('end'), str('start-ns'))) <NEW_LINE> self.root = None <NEW_LINE> for event, elem in context: <NEW_LINE> <INDENT> if event == "start-ns" and elem[0] == "": <NEW_LINE> <INDENT> self.uri = elem[1] <NEW_LINE> continue <NEW_LINE> <DEDENT> if event == "start" and self.root is None: <NEW_LINE> <INDENT> self.root = elem <NEW_LINE> continue <NEW_LINE> <DEDENT> for rev in self._parse(event, elem): <NEW_LINE> <INDENT> yield rev <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _parse_only_latest(self, event, elem): <NEW_LINE> <INDENT> if event == "end" and elem.tag == "{%s}page" % self.uri: <NEW_LINE> <INDENT> self._headers(elem) <NEW_LINE> revision = elem.find("{%s}revision" % self.uri) <NEW_LINE> yield self._create_revision(revision) <NEW_LINE> elem.clear() <NEW_LINE> self.root.clear() <NEW_LINE> <DEDENT> <DEDENT> def _parse_all(self, event, elem): <NEW_LINE> <INDENT> if event == "start" and elem.tag == "{%s}page" % self.uri: <NEW_LINE> <INDENT> self._headers(elem) <NEW_LINE> <DEDENT> if event == "end" and elem.tag == "{%s}revision" % self.uri: <NEW_LINE> <INDENT> yield self._create_revision(elem) <NEW_LINE> elem.clear() <NEW_LINE> self.root.clear() <NEW_LINE> <DEDENT> <DEDENT> def _headers(self, elem): <NEW_LINE> <INDENT> self.title = elem.findtext("{%s}title" % self.uri) <NEW_LINE> self.ns = elem.findtext("{%s}ns" % self.uri) <NEW_LINE> self.pageid = elem.findtext("{%s}id" % self.uri) <NEW_LINE> self.restrictions = elem.findtext("{%s}restrictions" % self.uri) <NEW_LINE> self.isredirect = elem.findtext("{%s}redirect" % self.uri) is not None <NEW_LINE> self.editRestriction, self.moveRestriction = parseRestrictions( self.restrictions) <NEW_LINE> <DEDENT> def _create_revision(self, revision): <NEW_LINE> <INDENT> revisionid = revision.findtext("{%s}id" % self.uri) <NEW_LINE> timestamp = revision.findtext("{%s}timestamp" % self.uri) <NEW_LINE> comment = revision.findtext("{%s}comment" % self.uri) <NEW_LINE> contributor = revision.find("{%s}contributor" % self.uri) <NEW_LINE> ipeditor = contributor.findtext("{%s}ip" % self.uri) <NEW_LINE> username = ipeditor or contributor.findtext("{%s}username" % self.uri) <NEW_LINE> text = revision.findtext("{%s}text" % self.uri) <NEW_LINE> return XmlEntry(title=self.title, ns=self.ns, id=self.pageid, text=text or u'', username=username or u'', ipedit=bool(ipeditor), timestamp=timestamp, editRestriction=self.editRestriction, moveRestriction=self.moveRestriction, revisionid=revisionid, comment=comment, redirect=self.isredirect )
Represents an XML dump file. Reads the local file at initialization, parses it, and offers access to the resulting XmlEntries via a generator. @param allrevisions: boolean If True, parse all revisions instead of only the latest one. Default: False.
62599060fff4ab517ebceeca
class Integrator: <NEW_LINE> <INDENT> def __init__(self, dt, f): <NEW_LINE> <INDENT> self.dt = dt <NEW_LINE> self.f = f <NEW_LINE> <DEDENT> def step(self, t, x, u): <NEW_LINE> <INDENT> raise NotImplementedError
Integrator for a system of first-order ordinary differential equations of the form \dot x = f(t, x, u).
625990608e7ae83300eea731
class AudioApp(object): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> self.narrator = pyttsx.init() <NEW_LINE> self.narrator.setProperty('rate', 500) <NEW_LINE> self.synth = fluidsynth.Synth() <NEW_LINE> self.synth.start() <NEW_LINE> example = self.synth.sfload('example.sf2') <NEW_LINE> self.synth.program_select(0, example, 0, 0) <NEW_LINE> <DEDENT> def speak(self, phrase): <NEW_LINE> <INDENT> if phrase: <NEW_LINE> <INDENT> self.narrator.say(phrase) <NEW_LINE> self.narrator.runAndWait() <NEW_LINE> <DEDENT> <DEDENT> def speak_char(self, char): <NEW_LINE> <INDENT> mapping = { 'y': 'why', '.': 'dot', ' ': 'space', ',': 'comma', ';': 'semicolon', '-': 'dash', ':': 'colon', '/': 'slash', '\\': 'backslash', '?': 'question mark', '!': 'bang', '@': 'at', '#': 'pound', '$': 'dollar', '%': 'percent', '*': 'star', '^': 'caret', '~': 'squiggle' } <NEW_LINE> speakable = char.lower() <NEW_LINE> if speakable in mapping: <NEW_LINE> <INDENT> speakable = mapping[speakable] <NEW_LINE> <DEDENT> elif char.isalpha(): <NEW_LINE> <INDENT> speakable = char <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> speakable = 'splork' <NEW_LINE> <DEDENT> return self.speak(speakable) <NEW_LINE> <DEDENT> def play_interval(self, size, duration, root=80, delay=0, intensity=30, channel=0): <NEW_LINE> <INDENT> self.synth.noteon(channel, root, intensity) <NEW_LINE> time.sleep(delay) <NEW_LINE> self.synth.noteon(channel, root + size, intensity) <NEW_LINE> time.sleep(duration) <NEW_LINE> self.synth.noteoff(channel, root) <NEW_LINE> self.synth.noteoff(channel, root + size) <NEW_LINE> <DEDENT> def handle_key(self, key): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stdscr = curses.initscr() <NEW_LINE> curses.noecho() <NEW_LINE> curses.cbreak() <NEW_LINE> stdscr.keypad(1) <NEW_LINE> while True: <NEW_LINE> <INDENT> c = stdscr.getch() <NEW_LINE> if not self.handle_key(c): break <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> curses.nocbreak() <NEW_LINE> stdscr.keypad(0) <NEW_LINE> curses.echo() <NEW_LINE> curses.endwin() <NEW_LINE> <DEDENT> <DEDENT> def simulate_keystroke(self, key): <NEW_LINE> <INDENT> self.handle_key(key) <NEW_LINE> <DEDENT> def simulate_typing(self, string): <NEW_LINE> <INDENT> for char in string: <NEW_LINE> <INDENT> self.simulate_keystroke(ord(char))
Base class for auditory UI.
625990605166f23b2e244a75
class BaseNavigation(object): <NEW_LINE> <INDENT> pass
description of class
6259906099cbb53fe6832585
class TestExportRunFile(TestCase): <NEW_LINE> <INDENT> fixtures = ("osm_provider.json",) <NEW_LINE> def test_create_export_run_file(self): <NEW_LINE> <INDENT> file_mock = MagicMock(spec=File) <NEW_LINE> file_mock.name = "test.pdf" <NEW_LINE> directory = "test" <NEW_LINE> provider = DataProvider.objects.first() <NEW_LINE> file_model = ExportRunFile.objects.create(file=file_mock, directory=directory, provider=provider) <NEW_LINE> self.assertEqual(file_mock.name, file_model.file.name) <NEW_LINE> self.assertEqual(directory, file_model.directory) <NEW_LINE> self.assertEqual(provider, file_model.provider) <NEW_LINE> file_model.file.delete() <NEW_LINE> <DEDENT> def test_delete_export_run_file(self): <NEW_LINE> <INDENT> file_mock = MagicMock(spec=File) <NEW_LINE> file_mock.name = "test.pdf" <NEW_LINE> directory = "test" <NEW_LINE> provider = DataProvider.objects.first() <NEW_LINE> file_model = ExportRunFile.objects.create(file=file_mock, directory=directory, provider=provider) <NEW_LINE> files = ExportRunFile.objects.all() <NEW_LINE> self.assertEqual(1, files.count()) <NEW_LINE> file_model.file.delete() <NEW_LINE> file_model.delete() <NEW_LINE> self.assertEqual(0, files.count())
Test cases for ExportRunFile model
625990607047854f46340a61
class Envelope(object): <NEW_LINE> <INDENT> _version = MPLANE_VERSION <NEW_LINE> _content_type = None <NEW_LINE> _messages = None <NEW_LINE> def __init__(self, dictval=None, content_type=ENVELOPE_MESSAGE): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if dictval is not None: <NEW_LINE> <INDENT> self._from_dict(dictval) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._content_type = content_type <NEW_LINE> self._messages = [] <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Envelope "+self._content_type+ " ("+str(len(self._messages))+"): "+ " ".join(map(repr, self._messages))+">" <NEW_LINE> <DEDENT> def append_message(self, msg): <NEW_LINE> <INDENT> self._messages.append(msg) <NEW_LINE> <DEDENT> def messages(self): <NEW_LINE> <INDENT> return iter(self._messages) <NEW_LINE> <DEDENT> def kind_str(self): <NEW_LINE> <INDENT> return KIND_ENVELOPE <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> d[self.kind_str()] = self._content_type <NEW_LINE> d[KEY_VERSION] = self._version <NEW_LINE> d[KEY_CONTENTS] = [m.to_dict() for m in self.messages()] <NEW_LINE> return d <NEW_LINE> <DEDENT> def _from_dict(self, d): <NEW_LINE> <INDENT> self._content_type = d[self.kind_str()] <NEW_LINE> if KEY_VERSION in d: <NEW_LINE> <INDENT> if int(d[KEY_VERSION]) > MPLANE_VERSION: <NEW_LINE> <INDENT> raise ValueError("Version mismatch") <NEW_LINE> <DEDENT> <DEDENT> for md in self[KEY_CONTENTS]: <NEW_LINE> <INDENT> self.append_message(message_from_dict(md))
Envelopes are used to contain other Messages.
6259906066673b3332c31aa0
class Switches(FilePath): <NEW_LINE> <INDENT> def __init__(self, text, col=None): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.col = col <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Switches({0})".format(repr(self.text)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.text <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, Switches) and self.text == other.text
AST for argument switches (arguments beginning with "-", as on a UNIX command line).
625990604428ac0f6e659bd6
class ConfdAsyncUDPClient(daemon.AsyncUDPSocket): <NEW_LINE> <INDENT> def __init__(self, client, family): <NEW_LINE> <INDENT> daemon.AsyncUDPSocket.__init__(self, family) <NEW_LINE> self.client = client <NEW_LINE> <DEDENT> def handle_datagram(self, payload, ip, port): <NEW_LINE> <INDENT> self.client.HandleResponse(payload, ip, port)
Confd udp asyncore client This is kept separate from the main ConfdClient to make sure it's easy to implement a non-asyncore based client library.
6259906045492302aabfdb7e
class IDParser(HTMLParser.HTMLParser): <NEW_LINE> <INDENT> def __init__(self, id): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.result = None <NEW_LINE> self.started = False <NEW_LINE> self.depth = {} <NEW_LINE> self.html = None <NEW_LINE> self.watch_startpos = False <NEW_LINE> HTMLParser.HTMLParser.__init__(self) <NEW_LINE> <DEDENT> def loads(self, html): <NEW_LINE> <INDENT> self.html = html <NEW_LINE> self.feed(html) <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def handle_starttag(self, tag, attrs): <NEW_LINE> <INDENT> attrs = dict(attrs) <NEW_LINE> if self.started: <NEW_LINE> <INDENT> self.find_startpos(None) <NEW_LINE> <DEDENT> if 'id' in attrs and attrs['id'] == self.id: <NEW_LINE> <INDENT> self.result = [tag] <NEW_LINE> self.started = True <NEW_LINE> self.watch_startpos = True <NEW_LINE> <DEDENT> if self.started: <NEW_LINE> <INDENT> if not tag in self.depth: self.depth[tag] = 0 <NEW_LINE> self.depth[tag] += 1 <NEW_LINE> <DEDENT> <DEDENT> def handle_endtag(self, tag): <NEW_LINE> <INDENT> if self.started: <NEW_LINE> <INDENT> if tag in self.depth: self.depth[tag] -= 1 <NEW_LINE> if self.depth[self.result[0]] == 0: <NEW_LINE> <INDENT> self.started = False <NEW_LINE> self.result.append(self.getpos()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def find_startpos(self, x): <NEW_LINE> <INDENT> if self.watch_startpos: <NEW_LINE> <INDENT> self.watch_startpos = False <NEW_LINE> self.result.append(self.getpos()) <NEW_LINE> <DEDENT> <DEDENT> handle_entityref = handle_charref = handle_data = handle_comment = handle_decl = handle_pi = unknown_decl = find_startpos <NEW_LINE> def get_result(self): <NEW_LINE> <INDENT> if self.result == None: return None <NEW_LINE> if len(self.result) != 3: return None <NEW_LINE> lines = self.html.split('\n') <NEW_LINE> lines = lines[self.result[1][0] - 1:self.result[2][0]] <NEW_LINE> lines[0] = lines[0][self.result[1][1]:] <NEW_LINE> if len(lines) == 1: <NEW_LINE> <INDENT> lines[-1] = lines[-1][:self.result[2][1] - self.result[1][1]] <NEW_LINE> <DEDENT> lines[-1] = lines[-1][:self.result[2][1]] <NEW_LINE> return '\n'.join(lines).strip()
Modified HTMLParser that isolates a tag with the specified id
6259906024f1403a92686420
class ProfileEditTextForm(FlaskForm, __TitleAndContent): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> csrf = True
If the user wants to edit the title and/or content of their profile.
625990608e71fb1e983bd16f
class VIEW3D_OT_ccdelta_sub(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "view3d.ccdelta_sub" <NEW_LINE> bl_label = "Subtract delta vector to 3D cursor" <NEW_LINE> bl_options = {'REGISTER'} <NEW_LINE> def modal(self, context, event): <NEW_LINE> <INDENT> return {'FINISHED'} <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> cc = context.scene.cursor_control <NEW_LINE> cc.subDeltaVectorToCursor() <NEW_LINE> return {'FINISHED'}
Subtract delta vector to 3D cursor
6259906091af0d3eaad3b4cc
class Config: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> for key, value in kwargs.items(): <NEW_LINE> <INDENT> self.set_value(key, value) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def load_from_yaml(cls, path: str): <NEW_LINE> <INDENT> with open(path, 'r') as file: <NEW_LINE> <INDENT> file_dict = yaml.load(file, Loader=yaml.FullLoader) <NEW_LINE> <DEDENT> if file_dict: <NEW_LINE> <INDENT> return cls(**file_dict) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> <DEDENT> def _return_option_instance(self, option_name: str) -> ConfigOption: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return next( filter(lambda i: i.attribute == option_name, self.options) ) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> raise OptionNotValid(f"{option_name} is not a valid configuration " f"option.") <NEW_LINE> <DEDENT> <DEDENT> def set_value(self, option_name: str, value): <NEW_LINE> <INDENT> option = self._return_option_instance(option_name) <NEW_LINE> option.set(value=value) <NEW_LINE> <DEDENT> def get_value(self, option_name: str): <NEW_LINE> <INDENT> option = self._return_option_instance(option_name) <NEW_LINE> return option.get() <NEW_LINE> <DEDENT> def get_dict(self) -> dict: <NEW_LINE> <INDENT> return_dict = {} <NEW_LINE> for option in self.options: <NEW_LINE> <INDENT> return_dict.update({option.attribute: option.get()}) <NEW_LINE> <DEDENT> return return_dict <NEW_LINE> <DEDENT> def generate_config(self, path: str) -> None: <NEW_LINE> <INDENT> with open(path, 'w') as file: <NEW_LINE> <INDENT> file.write(self.generate_yaml()) <NEW_LINE> <DEDENT> <DEDENT> def generate_yaml(self) -> str: <NEW_LINE> <INDENT> default_option_dict = {} <NEW_LINE> for option in self.options: <NEW_LINE> <INDENT> option_value = option.get() <NEW_LINE> if PosixPath in option.valid_types: <NEW_LINE> <INDENT> option_value = str(option.get()) <NEW_LINE> <DEDENT> default_option_dict.update( {option.attribute: option_value} ) <NEW_LINE> <DEDENT> return yaml.dump(default_option_dict)
Configuration options and yaml file loading and saving. When creating from a .yaml file, use the .load_from_yaml() class method, which will return an instance with values populated from the file path provided.
625990606e29344779b01cf3
class PTPhoneNumberField(Field): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': _('Phone numbers have at least 3 and at most 9 digits and may optionally be prefixed with \'00351\' or \'+351\'.'), } <NEW_LINE> def clean(self, value): <NEW_LINE> <INDENT> super(PTPhoneNumberField, self).clean(value) <NEW_LINE> if value in EMPTY_VALUES: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> value = regex_replace('(\.|\s)', '', force_text(value)) <NEW_LINE> match = PHONE_NUMBER_REGEX.search(value) <NEW_LINE> if not match: <NEW_LINE> <INDENT> raise ValidationError(self.error_messages['invalid']) <NEW_LINE> <DEDENT> return '{0}'.format(value)
A field which validates Portuguese phone numbers. - Phone numbers have at least 3 and at most 9 digits and may optionally be prefixed with '00351' or '+351'. - The input string is allowed to contain spaces (though they will be stripped).
62599060f7d966606f74940b
class EMA(): <NEW_LINE> <INDENT> def __init__(self, momentum): <NEW_LINE> <INDENT> self.momentum = momentum <NEW_LINE> self.shadow = {} <NEW_LINE> <DEDENT> def register(self, name, val): <NEW_LINE> <INDENT> self.shadow[name] = val.clone() <NEW_LINE> <DEDENT> def __call__(self, name, x): <NEW_LINE> <INDENT> assert name in self.shadow <NEW_LINE> new_average = (1.0 - self.momentum) * x + self.momentum * self.shadow[name] <NEW_LINE> self.shadow[name] = new_average.clone() <NEW_LINE> return new_average <NEW_LINE> <DEDENT> def get(self, name): <NEW_LINE> <INDENT> assert name in self.shadow <NEW_LINE> return self.shadow[name]
Use moving avg for the models. Examples: >>> ema = EMA(0.999) >>> for name, param in model.named_parameters(): >>> if param.requires_grad: >>> ema.register(name, param.data) >>> >>> # during training: >>> # optimizer.step() >>> for name, param in model.named_parameters(): >>> # Sometime I also use the moving average of non-trainable parameters, just according to the model structure >>> if param.requires_grad: >>> ema(name, param.data) >>> >>> # during eval or test >>> import copy >>> model_test = copy.deepcopy(model) >>> for name, param in model_test.named_parameters(): >>> # Sometime I also use the moving average of non-trainable parameters, just according to the model structure >>> if param.requires_grad: >>> param.data = ema.get(name) >>> # Then use model_test for eval.
625990603539df3088ecd941
class LegacyWidgetRegistryTests(TestCase): <NEW_LINE> <INDENT> def tearDown(self): <NEW_LINE> <INDENT> super(LegacyWidgetRegistryTests, self).tearDown() <NEW_LINE> if MyLegacyWidget in admin_widgets_registry: <NEW_LINE> <INDENT> admin_widgets_registry.unregister(MyLegacyWidget) <NEW_LINE> <DEDENT> <DEDENT> def test_register_admin_widget(self): <NEW_LINE> <INDENT> message = ( 'reviewboard.admin.widgets.register_admin_widget() is ' 'deprecated and will be removed in Review Board 5.0. Use ' 'reviewboard.admin.widgets.admin_widgets_registry.register() ' 'to register %r instead.' % MyLegacyWidget ) <NEW_LINE> with self.assertWarns(RemovedInReviewBoard50Warning, message): <NEW_LINE> <INDENT> register_admin_widget(MyLegacyWidget) <NEW_LINE> <DEDENT> self.assertIn(MyLegacyWidget, admin_widgets_registry) <NEW_LINE> self.assertIs(admin_widgets_registry.get_widget('my-legacy-widget'), MyLegacyWidget) <NEW_LINE> admin_widgets_registry.unregister(MyLegacyWidget) <NEW_LINE> <DEDENT> def test_unregister_admin_widget(self): <NEW_LINE> <INDENT> admin_widgets_registry.register(MyLegacyWidget) <NEW_LINE> message = ( 'reviewboard.admin.widgets.unregister_admin_widget() is ' 'deprecated and will be removed in Review Board 5.0. Use ' 'reviewboard.admin.widgets.admin_widgets_registry.unregister() ' 'to unregister %r instead.' % MyLegacyWidget ) <NEW_LINE> with self.assertWarns(RemovedInReviewBoard50Warning, message): <NEW_LINE> <INDENT> unregister_admin_widget(MyLegacyWidget) <NEW_LINE> <DEDENT> self.assertNotIn(MyLegacyWidget, admin_widgets_registry)
Unit tests for legacy Widget registration functions.
625990609c8ee82313040cdc
class XLNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, model_name_or_path: str, max_seq_length: int = 128, do_lower_case: Optional[bool] = None, model_args: Dict = {}, tokenizer_args: Dict = {}): <NEW_LINE> <INDENT> super(XLNet, self).__init__() <NEW_LINE> self.config_keys = ['max_seq_length', 'do_lower_case'] <NEW_LINE> self.max_seq_length = max_seq_length <NEW_LINE> self.do_lower_case = do_lower_case <NEW_LINE> if self.do_lower_case is not None: <NEW_LINE> <INDENT> tokenizer_args['do_lower_case'] = do_lower_case <NEW_LINE> <DEDENT> self.xlnet = XLNetModel.from_pretrained(model_name_or_path, **model_args) <NEW_LINE> self.tokenizer = XLNetTokenizer.from_pretrained(model_name_or_path, **tokenizer_args) <NEW_LINE> self.cls_token_id = self.tokenizer.convert_tokens_to_ids([self.tokenizer.cls_token])[0] <NEW_LINE> self.sep_token_id = self.tokenizer.convert_tokens_to_ids([self.tokenizer.sep_token])[0] <NEW_LINE> <DEDENT> def forward(self, features): <NEW_LINE> <INDENT> output_states = self.xlnet(**features) <NEW_LINE> output_tokens = output_states[0] <NEW_LINE> cls_tokens = output_tokens[:, -1, :] <NEW_LINE> features.update({'token_embeddings': output_tokens, 'cls_token_embeddings': cls_tokens, 'attention_mask': features['attention_mask']}) <NEW_LINE> if self.xlnet.config.output_hidden_states: <NEW_LINE> <INDENT> hidden_states = output_states[2] <NEW_LINE> features.update({'all_layer_embeddings': hidden_states}) <NEW_LINE> <DEDENT> return features <NEW_LINE> <DEDENT> def get_word_embedding_dimension(self) -> int: <NEW_LINE> <INDENT> return self.xlnet.config.d_model <NEW_LINE> <DEDENT> def tokenize(self, text: str) -> List[int]: <NEW_LINE> <INDENT> return self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(text)) <NEW_LINE> <DEDENT> def get_sentence_features(self, tokens: List[int], pad_seq_length: int) -> Dict[str, Tensor]: <NEW_LINE> <INDENT> pad_seq_length = min(pad_seq_length, self.max_seq_length) + 3 <NEW_LINE> return self.tokenizer.prepare_for_model(tokens, max_length=pad_seq_length, pad_to_max_length=True, return_tensors='pt', truncation=True) <NEW_LINE> <DEDENT> def get_config_dict(self): <NEW_LINE> <INDENT> return {key: self.__dict__[key] for key in self.config_keys} <NEW_LINE> <DEDENT> def save(self, output_path: str): <NEW_LINE> <INDENT> self.xlnet.save_pretrained(output_path) <NEW_LINE> self.tokenizer.save_pretrained(output_path) <NEW_LINE> with open(os.path.join(output_path, 'sentence_xlnet_config.json'), 'w') as fOut: <NEW_LINE> <INDENT> json.dump(self.get_config_dict(), fOut, indent=2) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def load(input_path: str): <NEW_LINE> <INDENT> with open(os.path.join(input_path, 'sentence_xlnet_config.json')) as fIn: <NEW_LINE> <INDENT> config = json.load(fIn) <NEW_LINE> <DEDENT> return XLNet(model_name_or_path=input_path, **config)
XLNet model to generate token embeddings. Each token is mapped to an output vector from XLNet.
625990602ae34c7f260ac78b
class csvFuturesInstrumentData(futuresInstrumentData): <NEW_LINE> <INDENT> def __init__( self, datapath=arg_not_supplied, log=logtoscreen("csvFuturesInstrumentData"), ): <NEW_LINE> <INDENT> super().__init__(log=log) <NEW_LINE> if datapath is arg_not_supplied: <NEW_LINE> <INDENT> datapath = INSTRUMENT_CONFIG_PATH <NEW_LINE> <DEDENT> config_file = get_filename_for_package(datapath, CONFIG_FILE_NAME) <NEW_LINE> self._config_file = config_file <NEW_LINE> <DEDENT> @property <NEW_LINE> def config_file(self): <NEW_LINE> <INDENT> return self._config_file <NEW_LINE> <DEDENT> def _load_instrument_csv_as_df(self) -> pd.DataFrame: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> config_data = pd.read_csv(self.config_file) <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> raise Exception("Can't read file %s" % self.config_file) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> config_data.index = config_data.Instrument <NEW_LINE> config_data.drop(labels="Instrument", axis=1, inplace=True) <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> raise Exception("Badly configured file %s" % (self._config_file)) <NEW_LINE> <DEDENT> return config_data <NEW_LINE> <DEDENT> def get_all_instrument_data_as_df(self) -> pd.DataFrame: <NEW_LINE> <INDENT> config_data = self._load_instrument_csv_as_df() <NEW_LINE> return config_data <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Instruments data from %s" % self._config_file <NEW_LINE> <DEDENT> def get_list_of_instruments(self) -> list: <NEW_LINE> <INDENT> return list(self.get_all_instrument_data_as_df().index) <NEW_LINE> <DEDENT> def _get_instrument_data_without_checking( self, instrument_code: str ) -> futuresInstrumentWithMetaData: <NEW_LINE> <INDENT> all_instrument_data = self.get_all_instrument_data_as_df() <NEW_LINE> instrument_with_meta_data = get_instrument_with_meta_data_object( all_instrument_data, instrument_code ) <NEW_LINE> return instrument_with_meta_data <NEW_LINE> <DEDENT> def _delete_instrument_data_without_any_warning_be_careful( self, instrument_code: str ): <NEW_LINE> <INDENT> raise NotImplementedError( "Can't overwrite part of .csv use write_all_instrument_data_from_df" ) <NEW_LINE> <DEDENT> def _add_instrument_data_without_checking_for_existing_entry( self, instrument_object: futuresInstrumentWithMetaData ): <NEW_LINE> <INDENT> raise NotImplementedError( "Can't overwrite part of .csv use write_all_instrument_data_from_df" ) <NEW_LINE> <DEDENT> def write_all_instrument_data_from_df(self, instrument_data_as_df: pd.DataFrame): <NEW_LINE> <INDENT> instrument_data_as_df.to_csv( self._config_file, index_label="Instrument", columns=[field.name for field in dataclasses.fields(instrumentMetaData)] )
Get data about instruments from a special configuration used for initialising the system
62599060d268445f2663a6af
class AddTripEntryView(AddApprovableEntryView): <NEW_LINE> <INDENT> entry_class = TripEntry <NEW_LINE> entry_form_class = TripEntryForm <NEW_LINE> transaction_formset_class = TripTransactionFormSet <NEW_LINE> verbose_name = 'Trip' <NEW_LINE> receipt_class = TripReceipt <NEW_LINE> receipt_entry_field = 'trip_entry' <NEW_LINE> list_entries_view = 'trips.views.list_trip_entries' <NEW_LINE> add_entry_view = 'trips.views.add_trip_entry' <NEW_LINE> show_entry_view = 'trips.views.show_trip_entry' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(AddTripEntryView, self).__init__() <NEW_LINE> self.store_transaction_formset = None <NEW_LINE> <DEDENT> def _get_form_initialize(self, request): <NEW_LINE> <INDENT> super(AddTripEntryView, self)._get_form_initialize(request) <NEW_LINE> self.store_transaction_formset = TripStoreTransactionFormSet( prefix='store-transaction', instance=self.entry) <NEW_LINE> <DEDENT> def _post_form_initialize(self, request): <NEW_LINE> <INDENT> super(AddTripEntryView, self)._post_form_initialize(request) <NEW_LINE> self.store_transaction_formset = TripStoreTransactionFormSet( request.POST, prefix='store-transaction', instance=self.entry) <NEW_LINE> <DEDENT> def _forms_valid(self): <NEW_LINE> <INDENT> return (super(AddTripEntryView, self)._forms_valid() and self.store_transaction_formset.is_valid()) <NEW_LINE> <DEDENT> def _post_form_save(self): <NEW_LINE> <INDENT> super(AddTripEntryView, self)._post_form_save() <NEW_LINE> self.store_transaction_formset.save() <NEW_LINE> <DEDENT> def _make_request_data(self): <NEW_LINE> <INDENT> context = super(AddTripEntryView, self)._make_request_data() <NEW_LINE> context['store_transaction_formset'] = self.store_transaction_formset <NEW_LINE> return context
Extend the AddApprovableEntryView to apply to TripEntries. This view adds an additional formset, the TripStoreTransactionFormSet.
62599060460517430c432ba5
class GetRuleRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RuleId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RuleId = params.get("RuleId") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
GetRule请求参数结构体
6259906016aa5153ce401b82
class time_limited: <NEW_LINE> <INDENT> def __init__(self, limit_seconds, iterable): <NEW_LINE> <INDENT> if limit_seconds < 0: <NEW_LINE> <INDENT> raise ValueError('limit_seconds must be positive') <NEW_LINE> <DEDENT> self.limit_seconds = limit_seconds <NEW_LINE> self._iterable = iter(iterable) <NEW_LINE> self._start_time = monotonic() <NEW_LINE> self.timed_out = False <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> item = next(self._iterable) <NEW_LINE> if monotonic() - self._start_time > self.limit_seconds: <NEW_LINE> <INDENT> self.timed_out = True <NEW_LINE> raise StopIteration <NEW_LINE> <DEDENT> return item
Yield items from *iterable* until *limit_seconds* have passed. If the time limit expires before all items have been yielded, the ``timed_out`` parameter will be set to ``True``. >>> from time import sleep >>> def generator(): ... yield 1 ... yield 2 ... sleep(0.2) ... yield 3 >>> iterable = time_limited(0.1, generator()) >>> list(iterable) [1, 2] >>> iterable.timed_out True Note that the time is checked before each item is yielded, and iteration stops if the time elapsed is greater than *limit_seconds*. If your time limit is 1 second, but it takes 2 seconds to generate the first item from the iterable, the function will run for 2 seconds and not yield anything.
625990602c8b7c6e89bd4e94
class Result(Generic[T, E], AbstractContextManager): <NEW_LINE> <INDENT> def __init__(self, ok: T = None, err: E = None) -> None: <NEW_LINE> <INDENT> self._variant = _ResultVariant.ERR <NEW_LINE> self._ok = None <NEW_LINE> self._err = None <NEW_LINE> if err is not None: <NEW_LINE> <INDENT> self._err = err <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._variant = _ResultVariant.OK <NEW_LINE> self._ok = ok <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> return Ok(self._ok.__enter__()) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> return self._ok.__exit__(exc_type, exc_val, exc_tb) <NEW_LINE> <DEDENT> <DEDENT> def is_ok(self) -> bool: <NEW_LINE> <INDENT> return self._variant == _ResultVariant.OK <NEW_LINE> <DEDENT> def is_err(self) -> bool: <NEW_LINE> <INDENT> return not self.is_ok() <NEW_LINE> <DEDENT> def ok(self) -> Optional[T]: <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> return self._ok <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def err(self) -> Optional[E]: <NEW_LINE> <INDENT> if self.is_err(): <NEW_LINE> <INDENT> return self._err <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def map(self, f): <NEW_LINE> <INDENT> if self.is_err(): <NEW_LINE> <INDENT> return Err(self._err) <NEW_LINE> <DEDENT> return Ok(f(self._ok)) <NEW_LINE> <DEDENT> def map_err(self, f): <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> return Ok(self._ok) <NEW_LINE> <DEDENT> return Err(f(self._err)) <NEW_LINE> <DEDENT> def and_then(self, f): <NEW_LINE> <INDENT> if self.is_err(): <NEW_LINE> <INDENT> return Err(self._err) <NEW_LINE> <DEDENT> return f(self._ok) <NEW_LINE> <DEDENT> def or_else(self, f): <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> return Ok(self._ok) <NEW_LINE> <DEDENT> return f(self._err) <NEW_LINE> <DEDENT> def conjunct(self, res): <NEW_LINE> <INDENT> if self.is_err(): <NEW_LINE> <INDENT> return Err(self._err) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def disjunct(self, res): <NEW_LINE> <INDENT> if self.is_ok(): <NEW_LINE> <INDENT> return Ok(self._ok) <NEW_LINE> <DEDENT> return res
A container for the result of functions that can produce errors. Instances should be constructed using either the `Ok` or `Err` functions.
625990607b25080760ed8833
class TestBasicFunctions(unittest.TestCase): <NEW_LINE> <INDENT> def test_instantiate(self): <NEW_LINE> <INDENT> m1 = instantiate('md5') <NEW_LINE> m2 = instantiate('sha256') <NEW_LINE> data = 'data'.encode('utf-8') <NEW_LINE> m1.update(data) <NEW_LINE> m2.update(data) <NEW_LINE> assert m1.hexdigest() == (hashlib.md5)(data).hexdigest() <NEW_LINE> assert m2.hexdigest() == (hashlib.sha256)(data).hexdigest() <NEW_LINE> with self.assertRaises(UnsupportedHashAlgorithm): <NEW_LINE> <INDENT> instantiate('unkownAlg') <NEW_LINE> <DEDENT> <DEDENT> @tempdir() <NEW_LINE> def test_calculate(self, filedir): <NEW_LINE> <INDENT> path = filedir.write('file.c4gh', c4gh_data.ENC_FILE.encode('utf-8')) <NEW_LINE> with open(path, 'rb') as file_data: <NEW_LINE> <INDENT> data = file_data.read() <NEW_LINE> file_hash = (hashlib.md5)(data).hexdigest() <NEW_LINE> <DEDENT> assert calculate(path, 'md5') == file_hash <NEW_LINE> filedir.cleanup() <NEW_LINE> <DEDENT> def test_calculate_error(self): <NEW_LINE> <INDENT> assert calculate('tests/resources/notexisting.file', 'md5') is None <NEW_LINE> <DEDENT> @mock.patch('lega.utils.checksum.calculate') <NEW_LINE> def test_is_valid(self, mock): <NEW_LINE> <INDENT> mock.return_value = '20655cb038a3e76e5f27749a028101e7' <NEW_LINE> assert is_valid('file/path', '20655cb038a3e76e5f27749a028101e7', 'md5') is True <NEW_LINE> <DEDENT> @tempdir() <NEW_LINE> def test_companion_not_found(self, filedir): <NEW_LINE> <INDENT> path = filedir.write('priv.file', 'content'.encode('utf-8')) <NEW_LINE> with self.assertRaises(CompanionNotFound): <NEW_LINE> <INDENT> get_from_companion(path) <NEW_LINE> <DEDENT> filedir.cleanup() <NEW_LINE> <DEDENT> @tempdir() <NEW_LINE> def test_companion_file(self, filedir): <NEW_LINE> <INDENT> path = filedir.write('priv.file', 'content'.encode('utf-8')) <NEW_LINE> filedir.write('priv.file.md5', 'md5content'.encode('utf-8')) <NEW_LINE> result = get_from_companion(path) <NEW_LINE> self.assertEqual(('md5content', 'md5'), result) <NEW_LINE> filedir.cleanup() <NEW_LINE> <DEDENT> def test_sanitize_user_id(self): <NEW_LINE> <INDENT> assert sanitize_user_id('[email protected]') == 'user_1245' <NEW_LINE> <DEDENT> def test_supported_algorithms(self): <NEW_LINE> <INDENT> result = supported_algorithms() <NEW_LINE> self.assertEqual(('md5', 'sha256'), result) <NEW_LINE> <DEDENT> def test_config_main(self): <NEW_LINE> <INDENT> with mock.patch('sys.stdout', new=StringIO()) as fake_stdout: <NEW_LINE> <INDENT> main() <NEW_LINE> self.assertTrue(fake_stdout.getvalue(), 'Configuration file:') <NEW_LINE> <DEDENT> with mock.patch('sys.stdout', new=StringIO()) as fake_stdout: <NEW_LINE> <INDENT> main(print_values=True) <NEW_LINE> self.assertTrue(fake_stdout.getvalue(), 'Configuration values:')
Basic Tests. Suite of basic tests for various functions.
6259906044b2445a339b74b3
class Square: <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> self.__size = size
square class
625990605166f23b2e244a77
class DummyService(Service): <NEW_LINE> <INDENT> def __init__(self, context, num_nodes): <NEW_LINE> <INDENT> super(DummyService, self).__init__(context, num_nodes) <NEW_LINE> self.started_count = 0 <NEW_LINE> self.cleaned_count = 0 <NEW_LINE> self.stopped_count = 0 <NEW_LINE> self.started_kwargs = {} <NEW_LINE> self.cleaned_kwargs = {} <NEW_LINE> self.stopped_kwargs = {} <NEW_LINE> <DEDENT> def idx(self, node): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def start_node(self, node, **kwargs): <NEW_LINE> <INDENT> super(DummyService, self).start_node(node, **kwargs) <NEW_LINE> self.started_count += 1 <NEW_LINE> self.started_kwargs = kwargs <NEW_LINE> <DEDENT> def clean_node(self, node, **kwargs): <NEW_LINE> <INDENT> super(DummyService, self).clean_node(node, **kwargs) <NEW_LINE> self.cleaned_count += 1 <NEW_LINE> self.cleaned_kwargs = kwargs <NEW_LINE> <DEDENT> def stop_node(self, node, **kwargs): <NEW_LINE> <INDENT> super(DummyService, self).stop_node(node, **kwargs) <NEW_LINE> self.stopped_count += 1 <NEW_LINE> self.stopped_kwargs = kwargs
Simple fake service class.
625990604428ac0f6e659bd8
class Song(ndb.Model): <NEW_LINE> <INDENT> artist = ndb.StringProperty() <NEW_LINE> title = ndb.StringProperty() <NEW_LINE> price = ndb.IntegerProperty() <NEW_LINE> album = ndb.StringProperty(indexed=False)
A main model for representing an individual Song entry.
62599060f548e778e596cc2e
class Config(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.network_hub = "all" <NEW_LINE> self.user_agent = "Social network mapper, monitored by /u/YourUserName" <NEW_LINE> self.post_limit = 100
Basic configuration
6259906076e4537e8c3f0c33
class FlipBitBigMutation(FlipBitMutation): <NEW_LINE> <INDENT> def __init__(self, pm, pbm, alpha): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(pm) <NEW_LINE> if not (0.0 < pbm < 1.0): <NEW_LINE> <INDENT> raise ValueError('Invalid big mutation probability') <NEW_LINE> <DEDENT> if pbm < 5*pm and mpi.is_master: <NEW_LINE> <INDENT> self.logger.warning('Relative low probability for big mutation') <NEW_LINE> <DEDENT> self.pbm = pbm <NEW_LINE> if not (0.5 < alpha < 1.0): <NEW_LINE> <INDENT> raise ValueError('Invalid intensive factor, should be in (0.5, 1.0)') <NEW_LINE> <DEDENT> self.alpha = alpha <NEW_LINE> <DEDENT> def mutate(self, individual, engine): <NEW_LINE> <INDENT> pm = self.pm <NEW_LINE> if engine.fmax*self.alpha < engine.fmean: <NEW_LINE> <INDENT> self.pm = self.pbm <NEW_LINE> <DEDENT> individual = super(self.__class__, self).mutate(individual, engine) <NEW_LINE> self.pm = pm <NEW_LINE> return individual
Mutation operator using Flip Bit mutation implementation with adaptive big mutation rate to overcome premature or local-best solution. :param pm: The probability of mutation (usually between 0.001 ~ 0.1) :type pm: float in (0.0, 1.0] :param pbm: The probability of big mutation, usually more than 5 times bigger than pm. :type pbm: float :param alpha: intensive factor :type alpha: float, in range (0.5, 1)
62599060baa26c4b54d50948
class Option(BaseOption): <NEW_LINE> <INDENT> TYPES = BaseOption.TYPES + ('regexp', 'csv', 'yn', 'named', 'password', 'multiple_choice', 'file', 'color', 'time', 'bytes') <NEW_LINE> ATTRS = BaseOption.ATTRS + ['hide', 'level'] <NEW_LINE> TYPE_CHECKER = copy(BaseOption.TYPE_CHECKER) <NEW_LINE> TYPE_CHECKER['regexp'] = check_regexp <NEW_LINE> TYPE_CHECKER['csv'] = check_csv <NEW_LINE> TYPE_CHECKER['yn'] = check_yn <NEW_LINE> TYPE_CHECKER['named'] = check_named <NEW_LINE> TYPE_CHECKER['multiple_choice'] = check_csv <NEW_LINE> TYPE_CHECKER['file'] = check_file <NEW_LINE> TYPE_CHECKER['color'] = check_color <NEW_LINE> TYPE_CHECKER['password'] = check_password <NEW_LINE> TYPE_CHECKER['time'] = check_time <NEW_LINE> TYPE_CHECKER['bytes'] = check_bytes <NEW_LINE> if HAS_MX_DATETIME: <NEW_LINE> <INDENT> TYPES += ('date',) <NEW_LINE> TYPE_CHECKER['date'] = check_date <NEW_LINE> <DEDENT> def __init__(self, *opts, **attrs): <NEW_LINE> <INDENT> BaseOption.__init__(self, *opts, **attrs) <NEW_LINE> if hasattr(self, "hide") and self.hide: <NEW_LINE> <INDENT> self.help = SUPPRESS_HELP <NEW_LINE> <DEDENT> <DEDENT> def _check_choice(self): <NEW_LINE> <INDENT> if self.type in ("choice", "multiple_choice"): <NEW_LINE> <INDENT> if self.choices is None: <NEW_LINE> <INDENT> raise OptionError( "must supply a list of choices for type 'choice'", self) <NEW_LINE> <DEDENT> elif not isinstance(self.choices, (tuple, list)): <NEW_LINE> <INDENT> raise OptionError( "choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self) <NEW_LINE> <DEDENT> <DEDENT> elif self.choices is not None: <NEW_LINE> <INDENT> raise OptionError( "must not supply choices for type %r" % self.type, self) <NEW_LINE> <DEDENT> <DEDENT> BaseOption.CHECK_METHODS[2] = _check_choice <NEW_LINE> def process(self, opt, value, values, parser): <NEW_LINE> <INDENT> value = self.convert_value(opt, value) <NEW_LINE> if self.type == 'named': <NEW_LINE> <INDENT> existant = getattr(values, self.dest) <NEW_LINE> if existant: <NEW_LINE> <INDENT> existant.update(value) <NEW_LINE> value = existant <NEW_LINE> <DEDENT> <DEDENT> return self.take_action( self.action, self.dest, opt, value, values, parser)
override optik.Option to add some new option types
625990601f037a2d8b9e53be
class FakeVolunteerFactory(Volunteer.Factory): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_persister(): <NEW_LINE> <INDENT> return FakeVolunteerPersister()
Fake class for testing
6259906024f1403a92686421
class OperationInfoDetail(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DisabledReason = None <NEW_LINE> self.Enabled = None <NEW_LINE> self.Supported = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DisabledReason = params.get("DisabledReason") <NEW_LINE> self.Enabled = params.get("Enabled") <NEW_LINE> self.Supported = params.get("Supported")
提供给前端控制按钮显示逻辑的字段
625990604f6381625f199ff6
class NoPlatformPolicyError(Error): <NEW_LINE> <INDENT> pass
Raised when a policy is received that doesn't support this platform.
62599060dd821e528d6da4d4
class TestAlsoAffectsLinks(BrowserTestCase): <NEW_LINE> <INDENT> layer = DatabaseFunctionalLayer <NEW_LINE> def test_also_affects_links_product_bug(self): <NEW_LINE> <INDENT> owner = self.factory.makePerson() <NEW_LINE> product = self.factory.makeProduct( bug_sharing_policy=BugSharingPolicy.PROPRIETARY) <NEW_LINE> bug = self.factory.makeBug( target=product, owner=owner, information_type=InformationType.PROPRIETARY) <NEW_LINE> url = canonical_url(bug, rootsite="bugs") <NEW_LINE> browser = self.getUserBrowser(url, user=owner) <NEW_LINE> also_affects = find_tag_by_id( browser.contents, 'also-affects-product') <NEW_LINE> self.assertIn( 'private-disallow', also_affects['class'].split(' ')) <NEW_LINE> also_affects = find_tag_by_id( browser.contents, 'also-affects-package') <NEW_LINE> self.assertIn( 'private-disallow', also_affects['class'].split(' ')) <NEW_LINE> <DEDENT> def test_also_affects_links_distro_bug(self): <NEW_LINE> <INDENT> distro = self.factory.makeDistribution() <NEW_LINE> owner = self.factory.makePerson() <NEW_LINE> bug = self.factory.makeBug( target=distro, information_type=InformationType.PRIVATESECURITY, owner=owner) <NEW_LINE> removeSecurityProxy(bug).information_type = ( InformationType.PROPRIETARY) <NEW_LINE> url = canonical_url(bug, rootsite="bugs") <NEW_LINE> browser = self.getUserBrowser(url, user=owner) <NEW_LINE> also_affects = find_tag_by_id( browser.contents, 'also-affects-product') <NEW_LINE> self.assertIn( 'private-disallow', also_affects['class'].split(' ')) <NEW_LINE> also_affects = find_tag_by_id( browser.contents, 'also-affects-package') <NEW_LINE> self.assertNotIn( 'private-disallow', also_affects['class'].split(' '))
Tests the rendering of the Also Affects links on the bug index view. The links are rendered with a css class 'private-disallow' if they are not valid for proprietary bugs.
625990603d592f4c4edbc583
class Environment: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> p = abs(50) <NEW_LINE> self.agent_position = Point(np.random.randint(-p,p) , np.random.randint(-p,p)) <NEW_LINE> self.plane_line = Line(np.random.randint(-p,p) , np.random.randint(-p,p), np.random.randint(-p,p)) <NEW_LINE> self.plane_sign = [-1,1][np.random.randint(0,2)] <NEW_LINE> while self.feedback() == True: <NEW_LINE> <INDENT> self.agent_position = Point(np.random.randint(-p,p) , np.random.randint(-p,p)) <NEW_LINE> <DEDENT> print("Environment initialized with:") <NEW_LINE> print("Agent position: ", self.agent_position) <NEW_LINE> print("Equation of the line: ", self.plane_line) <NEW_LINE> print("Sign of the Plane: ", self.plane_sign) <NEW_LINE> <DEDENT> def feedback(self): <NEW_LINE> <INDENT> if self.plane_line.getSignOfPoint(self.agent_position) == self.plane_sign: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def interact(self,action): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> direction = fetch_direction(action[0]) <NEW_LINE> distance = action[1] <NEW_LINE> if direction == 'x-axis': <NEW_LINE> <INDENT> self.agent_position.x += distance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.agent_position.y += distance <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("Interaction with environment failed.") <NEW_LINE> print("Please bithack! don't make mistakes while wirting Python code.") <NEW_LINE> sys.exit()
agent_position: This is the coordinate of the agent in a 2D cartesian plane. plane_line: The equation of the line which divides the plane into two halves where one of the halves is the plane. plane_sign: Takes on either of two values +1 or -1. Since any line divides a 2D plane in two halves, containing the points with negative and positive sign of points. The value of the plane_sign is to denote which side of the line the shore lies.
6259906097e22403b383c5b3
class Product(object): <NEW_LINE> <INDENT> self.id = 0 <NEW_LINE> self.name = '' <NEW_LINE> self.abbreviation = '' <NEW_LINE> self.resource = '' <NEW_LINE> self.description = '' <NEW_LINE> self.documentation = '' <NEW_LINE> self.tags = '' <NEW_LINE> self.species = '' <NEW_LINE> self.ontologies = [] <NEW_LINE> self.data_sets = [] <NEW_LINE> self.donors = [] <NEW_LINE> self.genes = [] <NEW_LINE> self.probes = [] <NEW_LINE> self.reference_spaces = [] <NEW_LINE> self.data_points = [] <NEW_LINE> self.documents = [] <NEW_LINE> def __init__(self, initialData={}): <NEW_LINE> <INDENT> for k,v in initData.iteritems(): <NEW_LINE> <INDENT> setattr(self, k, v)
aibs.model.product (autogen)
625990602ae34c7f260ac78d
class Circle: <NEW_LINE> <INDENT> def __init__(self, radius): <NEW_LINE> <INDENT> self.radius = radius <NEW_LINE> <DEDENT> @property <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return math.pi * self.radius ** 2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def diameter(self): <NEW_LINE> <INDENT> return self.radius * 2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def perimeter(self): <NEW_LINE> <INDENT> return 2 * math.pi * self.radius
property 还是一种定义动态计算 attribute 的方法。这种类型的 attributes 并不会 被实际的存储,而是在需要的时候计算出来
625990603cc13d1c6d466de9
class Config(): <NEW_LINE> <INDENT> TIMEZONE = 'Asia/Shanghai' <NEW_LINE> BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Basic config for demo02
62599060d486a94d0ba2d66f
class Multimap(MutableMapping): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Multimap, self).__init__() <NEW_LINE> self.__store = OrderedDict() <NEW_LINE> if args is not None and len(args) > 0: <NEW_LINE> <INDENT> for key, value in six.iteritems(args[0]): <NEW_LINE> <INDENT> self.__store[key] = MultimapValue(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.__store[key][len(self.__store[key]) - 1] <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self.__store[key] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.__store[key] = MultimapValue(value) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return sum([len(values) for values in six.itervalues(self.__store)]) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for key in six.iterkeys(self.__store): <NEW_LINE> <INDENT> yield key <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> str_repr = '{' <NEW_LINE> for key, value in self.items(): <NEW_LINE> <INDENT> str_repr += '%r: %r, ' % (key, value) <NEW_LINE> <DEDENT> str_repr = str_repr[:len(str_repr) - 2] + '}' <NEW_LINE> return six.ensure_binary(str_repr) if six.PY2 else str_repr <NEW_LINE> <DEDENT> def add_item(self, key, value): <NEW_LINE> <INDENT> if key in self.__store: <NEW_LINE> <INDENT> self.__store[key].append(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__setitem__(key, value) <NEW_LINE> <DEDENT> <DEDENT> def get_all_values(self, key): <NEW_LINE> <INDENT> return self.__store[key] <NEW_LINE> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> for key in self.__store: <NEW_LINE> <INDENT> for value in self.__store[key]: <NEW_LINE> <INDENT> yield (key, value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def items(self): <NEW_LINE> <INDENT> output = [] <NEW_LINE> for k, v in self.iteritems(): <NEW_LINE> <INDENT> output.append((k, v)) <NEW_LINE> <DEDENT> return output
Dictionary that can hold multiple values for the same key In order not to break existing customers, getting and inserting elements with ``[]`` keeps the same behaviour as the built-in dict. If multiple elements are already mapped to the key, ``[]` will return the newest one. To map multiple elements to a key, use the ``add_item`` operation. To retrieve all the values map to a key, use ``get_all_values``.
6259906045492302aabfdb81
class Data71: <NEW_LINE> <INDENT> hdr_dtype = np.dtype([('SoundSpeedCounter','H'),('SystemSerial#','H'), ('NumEntries','H')]) <NEW_LINE> data_dtype = np.dtype([('Time','d'),('SoundSpeed','f')]) <NEW_LINE> def __init__(self, datablock, POSIXtime, byteswap = False): <NEW_LINE> <INDENT> data_dtype = np.dtype([('Time','H'),('SoundSpeed','H')]) <NEW_LINE> hdr_sz = Data71.hdr_dtype.itemsize <NEW_LINE> data_sz = data_dtype.itemsize <NEW_LINE> self.header = np.frombuffer(datablock[:hdr_sz], dtype = Data71.hdr_dtype)[0] <NEW_LINE> self.data = np.frombuffer(datablock[hdr_sz:-1], dtype = data_dtype) <NEW_LINE> self.data = self.data.astype(Data71.data_dtype) <NEW_LINE> self.data['Time'] += POSIXtime <NEW_LINE> self.data['SoundSpeed'] *= 0.1 <NEW_LINE> <DEDENT> def display(self): <NEW_LINE> <INDENT> for n,name in enumerate(self.header.dtype.names): <NEW_LINE> <INDENT> print(name + ' : ' + str(self.header[n]))
Surface Sound Speed datagram 047h / 71d / 'G'. Time is in POSIX time and sound speed is in meters per second.
6259906067a9b606de5475f5
class UserFactory(factory.django.DjangoModelFactory): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> <DEDENT> first_name = factory.Faker('first_name') <NEW_LINE> last_name = factory.Faker('last_name') <NEW_LINE> username = first_name <NEW_LINE> password = make_password('test')
Creates an user
625990607d847024c075da7b
class Plan(object): <NEW_LINE> <INDENT> def __init__(self, groups): <NEW_LINE> <INDENT> self.result = {} <NEW_LINE> self.action_groups_dict = dict((name, ActionGroup()) for name in groups) <NEW_LINE> self.result["timeout"] = [] <NEW_LINE> <DEDENT> def action_done(self, action, result): <NEW_LINE> <INDENT> if result["state"].lower() == "success": <NEW_LINE> <INDENT> self.action_groups_dict[action.src].add_resource(action.ele.size) <NEW_LINE> <DEDENT> self.result["timeout"].remove(action) <NEW_LINE> self.result.setdefault(result["state"], []).append(action) <NEW_LINE> <DEDENT> def pop_actions(self): <NEW_LINE> <INDENT> actions = [] <NEW_LINE> for group in self.action_groups_dict.values(): <NEW_LINE> <INDENT> actions += group.pop_satisfied_actions() <NEW_LINE> <DEDENT> self.result["timeout"] += actions <NEW_LINE> return actions <NEW_LINE> <DEDENT> def add_resources(self, resources): <NEW_LINE> <INDENT> for r in resources: <NEW_LINE> <INDENT> self.action_groups_dict[r].add_resource(resources[r])
plan for action groups
62599060498bea3a75a59152
class MathFragment(Math): <NEW_LINE> <INDENT> def __init__( self, text: String, errors: Optional[Array[String]] = None, id: Optional[String] = None, mathLanguage: Optional[String] = None, meta: Optional[Object] = None ) -> None: <NEW_LINE> <INDENT> super().__init__( text=text, errors=errors, id=id, mathLanguage=mathLanguage, meta=meta )
A fragment of math, e.g a variable name, to be treated as inline content.
625990601f5feb6acb164292
class BaseTestCase(TestCase): <NEW_LINE> <INDENT> def create_app(self): <NEW_LINE> <INDENT> app.config.from_object('config.TestingConfig') <NEW_LINE> return app <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> db.create_all() <NEW_LINE> self.test_user = {"username": "moses", "password": "mango", "first_name": "Moses", "last_name": "Lawrence", "email": "[email protected]", "gender": "male"} <NEW_LINE> self.test_user2 = {"username": "mary", "password": "pineapple", "first_name":"Mary", "last_name": "Sally", "email": "[email protected]","gender": "female"} <NEW_LINE> self.businesses = [{ "business_name": "media studios", "business_category": "entertainment", "business_location": "kampala", "contact_number": "256781712929", "business_email": "[email protected]", "business_description": "This business gives the best wedding coverage" }, { "business_name": "real houses", "business_category": "real estate", "business_location": "kabale", "business_email": "[email protected]", "contact_number": "256781712978", "business_description": "This business will get you the best house" }] <NEW_LINE> <DEDENT> def register(self): <NEW_LINE> <INDENT> tester = app.test_client(self) <NEW_LINE> response = tester.post("/api/v2/auth/register", data=json.dumps(self.test_user), content_type="application/json") <NEW_LINE> return response <NEW_LINE> <DEDENT> def register2(self): <NEW_LINE> <INDENT> tester = app.test_client(self) <NEW_LINE> response = tester.post("/api/v2/auth/register", data=json.dumps(self.test_user2), content_type="application/json") <NEW_LINE> return response <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> user = {"username": 'moses', "password": "mango"} <NEW_LINE> response = self.client.post("/api/v2/login", data=json.dumps(user), content_type="application/json") <NEW_LINE> return response <NEW_LINE> <DEDENT> def login2(self): <NEW_LINE> <INDENT> user = {"username": 'mary', "password": "pineapple"} <NEW_LINE> response = self.client.post("/api/v2/login", data=json.dumps(user), content_type="application/json") <NEW_LINE> return response <NEW_LINE> <DEDENT> def register_business(self, json_result): <NEW_LINE> <INDENT> response = self.client.post("/api/v2/businesses", data=json.dumps(self.businesses[0]), headers={"access-token": json_result["Token"]}, content_type="application/json") <NEW_LINE> return response <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> db.session.remove() <NEW_LINE> db.drop_all()
Base test case to test the API
6259906007f4c71912bb0ae5
class StraightPolyomino( Tetrimino ): <NEW_LINE> <INDENT> def __init__( self, imageSurface, screenSurface ): <NEW_LINE> <INDENT> super( StraightPolyomino, self ).__init__( imageSurface, screenSurface ) <NEW_LINE> super( StraightPolyomino, self ).addRepresentation( 0, [ (0,0), (1,0), (2,0), (3,0) ] ) <NEW_LINE> super( StraightPolyomino, self ).addRepresentation( 1, [ (0,0), (0,1), (0,2), (0,3) ] ) <NEW_LINE> return
Class to represent a Straight Polyomino in the game
625990608a43f66fc4bf3836
class DB(object): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.conn = None <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.conn = sqlite3.connect(self.path) <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self.conn.close() <NEW_LINE> <DEDENT> def execute_and_commit(self, query): <NEW_LINE> <INDENT> c = self.conn.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> c.execute(query) <NEW_LINE> self.conn.commit() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> c.close()
SQLite3 wrapper.
62599060ac7a0e7691f73b8b
class DisableQuickuploadOverride(UpgradeStep): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.install_upgrade_profile()
Disable quickupload override and unique id. The override default in collective.quickupload was inconsistent in the default profile and in the upgrade step. Even though this setting does not affect us currently this upgrade-step makes sure that all of our installations have the same setting. You never know ... Also see https://github.com/collective/collective.quickupload/pull/60.
6259906066673b3332c31aa4
class KeyboardAgent(Agent): <NEW_LINE> <INDENT> WEST_KEY = 'a' <NEW_LINE> EAST_KEY = 'd' <NEW_LINE> NORTH_KEY = 'w' <NEW_LINE> SOUTH_KEY = 's' <NEW_LINE> STOP_KEY = 'q' <NEW_LINE> def __init__( self, index = 0 ): <NEW_LINE> <INDENT> self.lastMove = Directions.STOP <NEW_LINE> self.index = index <NEW_LINE> self.keys = [] <NEW_LINE> <DEDENT> def getAction( self, state): <NEW_LINE> <INDENT> from graphicsUtils import keys_waiting <NEW_LINE> from graphicsUtils import keys_pressed <NEW_LINE> keys = keys_waiting() <NEW_LINE> if keys != []: <NEW_LINE> <INDENT> self.keys = keys <NEW_LINE> <DEDENT> legal = state.getLegalActions(self.index) <NEW_LINE> move = self.getMove(legal) <NEW_LINE> if move == Directions.STOP: <NEW_LINE> <INDENT> if self.lastMove in legal: <NEW_LINE> <INDENT> move = self.lastMove <NEW_LINE> <DEDENT> <DEDENT> if (self.STOP_KEY in self.keys) and Directions.STOP in legal: move = Directions.STOP <NEW_LINE> if move not in legal: <NEW_LINE> <INDENT> move = random.choice(legal) <NEW_LINE> <DEDENT> self.lastMove = move <NEW_LINE> return move <NEW_LINE> <DEDENT> def getMove(self, legal): <NEW_LINE> <INDENT> move = Directions.STOP <NEW_LINE> if (self.WEST_KEY in self.keys or 'Left' in self.keys) and Directions.WEST in legal: move = Directions.WEST <NEW_LINE> if (self.EAST_KEY in self.keys or 'Right' in self.keys) and Directions.EAST in legal: move = Directions.EAST <NEW_LINE> if (self.NORTH_KEY in self.keys or 'Up' in self.keys) and Directions.NORTH in legal: move = Directions.NORTH <NEW_LINE> if (self.SOUTH_KEY in self.keys or 'Down' in self.keys) and Directions.SOUTH in legal: move = Directions.SOUTH <NEW_LINE> return move
An agent controlled by the keyboard.
62599060462c4b4f79dbd0ad
class Breakpoint: <NEW_LINE> <INDENT> next = 1 <NEW_LINE> bplist = {} <NEW_LINE> bpbynumber = [None] <NEW_LINE> def __init__(self, file, line, temporary=False, cond=None, funcname=None): <NEW_LINE> <INDENT> self.funcname = funcname <NEW_LINE> self.func_first_executable_line = None <NEW_LINE> self.file = file <NEW_LINE> self.line = line <NEW_LINE> self.temporary = temporary <NEW_LINE> self.cond = cond <NEW_LINE> self.enabled = True <NEW_LINE> self.ignore = 0 <NEW_LINE> self.hits = 0 <NEW_LINE> self.number = Breakpoint.next <NEW_LINE> Breakpoint.next += 1 <NEW_LINE> self.bpbynumber.append(self) <NEW_LINE> if (file, line) in self.bplist: <NEW_LINE> <INDENT> self.bplist[file, line].append(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bplist[file, line] = [self] <NEW_LINE> <DEDENT> <DEDENT> def deleteMe(self): <NEW_LINE> <INDENT> index = (self.file, self.line) <NEW_LINE> self.bpbynumber[self.number] = None <NEW_LINE> self.bplist[index].remove(self) <NEW_LINE> if not self.bplist[index]: <NEW_LINE> <INDENT> del self.bplist[index] <NEW_LINE> <DEDENT> <DEDENT> def enable(self): <NEW_LINE> <INDENT> self.enabled = True <NEW_LINE> <DEDENT> def disable(self): <NEW_LINE> <INDENT> self.enabled = False <NEW_LINE> <DEDENT> def bpprint(self, out=None): <NEW_LINE> <INDENT> if out is None: <NEW_LINE> <INDENT> out = sys.stdout <NEW_LINE> <DEDENT> print(self.bpformat(), file=out) <NEW_LINE> <DEDENT> def bpformat(self): <NEW_LINE> <INDENT> if self.temporary: <NEW_LINE> <INDENT> disp = 'del ' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> disp = 'keep ' <NEW_LINE> <DEDENT> if self.enabled: <NEW_LINE> <INDENT> disp = disp + 'yes ' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> disp = disp + 'no ' <NEW_LINE> <DEDENT> ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) <NEW_LINE> if self.cond: <NEW_LINE> <INDENT> ret += '\n\tstop only if %s' % (self.cond,) <NEW_LINE> <DEDENT> if self.ignore: <NEW_LINE> <INDENT> ret += '\n\tignore next %d hits' % (self.ignore,) <NEW_LINE> <DEDENT> if self.hits: <NEW_LINE> <INDENT> if self.hits > 1: <NEW_LINE> <INDENT> ss = 's' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ss = '' <NEW_LINE> <DEDENT> ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
Breakpoint class. Implements temporary breakpoints, ignore counts, disabling and (re)-enabling, and conditionals. Breakpoints are indexed by number through bpbynumber and by the (file, line) tuple using bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line. When creating a breakpoint, its associated filename should be in canonical form. If funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit.
6259906076e4537e8c3f0c35
class StubReactor(object): <NEW_LINE> <INDENT> implements(IReactorTCP) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.calls = [] <NEW_LINE> <DEDENT> def connectTCP(self, *args, **kwargs): <NEW_LINE> <INDENT> self.calls.append((args, kwargs)) <NEW_LINE> return StubConnector() <NEW_LINE> <DEDENT> def addSystemEventTrigger(self, *args, **kwds): <NEW_LINE> <INDENT> pass
A stub L{IReactorTCP} that records the calls to connectTCP. @ivar calls: A C{list} of tuples (args, kwargs) sent to connectTCP.
625990601f037a2d8b9e53bf
@interface.provider(IFormFieldProvider) <NEW_LINE> class IRelatedSites(model.Schema): <NEW_LINE> <INDENT> model.fieldset('settings', label=u"Settings", fields=['related_sites_links']) <NEW_LINE> related_sites_links = schema.List( title=_(u"Related sites"), required=False, value_type=DictRow( title=u"tablerow", required=False, schema=ITableRowSchema,), ) <NEW_LINE> form.widget(related_sites_links=CustomTableWidgetFactory)
Marker / Form interface for additional links
6259906021bff66bcd72430d
class PublishTranslations(hook.Hook): <NEW_LINE> <INDENT> __regid__ = "frarchives_edition.publish-translation" <NEW_LINE> __select__ = hook.Hook.__select__ & custom_on_fire_transition( CMS_I18N_OBJECTS, {"wft_cmsobject_publish"} ) <NEW_LINE> to_state = "wfs_cmsobject_published" <NEW_LINE> events = ("after_add_entity",) <NEW_LINE> category = "translation" <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> translation = self.entity.for_entity <NEW_LINE> if translation.original_entity: <NEW_LINE> <INDENT> if translation.original_entity_state() != self.to_state: <NEW_LINE> <INDENT> msg = self._cw._("The original entity is not published") <NEW_LINE> raise ForbiddenPublishedTransition(self._cw, msg) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> msg = self._cw._("No original entity found") <NEW_LINE> raise ForbiddenPublishedTransition(self._cw, msg)
Publish a Translation
625990604f6381625f199ff7
class Tool(benchexec.tools.template.BaseTool): <NEW_LINE> <INDENT> REQUIRED_PATHS = ["bin", "lib", "kluzzer"] <NEW_LINE> def program_files(self, executable): <NEW_LINE> <INDENT> return self._program_files_from_executable( executable, self.REQUIRED_PATHS, parent_dir=True ) <NEW_LINE> <DEDENT> def executable(self): <NEW_LINE> <INDENT> return util.find_executable("LibKluzzer", "bin/LibKluzzer") <NEW_LINE> <DEDENT> def version(self, executable): <NEW_LINE> <INDENT> return self._version_from_tool(executable) <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return "LibKluzzer"
Tool info for LibKluzzer (http://unihb.eu/kluzzer).
625990608e71fb1e983bd173
class ScreenShot: <NEW_LINE> <INDENT> __slots__ = {"__pixels", "__rgb", "pos", "raw", "size"} <NEW_LINE> def __init__(self, data, monitor, size=None): <NEW_LINE> <INDENT> self.__pixels = None <NEW_LINE> self.__rgb = None <NEW_LINE> self.raw = data <NEW_LINE> self.pos = Pos(monitor["left"], monitor["top"]) <NEW_LINE> if size is not None: <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.size = Size(monitor["width"], monitor["height"]) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ("<{!s} pos={cls.left},{cls.top} size={cls.width}x{cls.height}>").format( type(self).__name__, cls=self ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def __array_interface__(self): <NEW_LINE> <INDENT> return { "version": 3, "shape": (self.height, self.width, 4), "typestr": "|u1", "data": self.raw, } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_size(cls, data, width, height): <NEW_LINE> <INDENT> monitor = {"left": 0, "top": 0, "width": width, "height": height} <NEW_LINE> return cls(data, monitor) <NEW_LINE> <DEDENT> @property <NEW_LINE> def bgra(self): <NEW_LINE> <INDENT> return bytes(self.raw) <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.size.height <NEW_LINE> <DEDENT> @property <NEW_LINE> def left(self): <NEW_LINE> <INDENT> return self.pos.left <NEW_LINE> <DEDENT> @property <NEW_LINE> def pixels(self): <NEW_LINE> <INDENT> if not self.__pixels: <NEW_LINE> <INDENT> rgb_tuples = zip( self.raw[2::4], self.raw[1::4], self.raw[0::4] ) <NEW_LINE> self.__pixels = list(zip(*[iter(rgb_tuples)] * self.width)) <NEW_LINE> <DEDENT> return self.__pixels <NEW_LINE> <DEDENT> @property <NEW_LINE> def rgb(self): <NEW_LINE> <INDENT> if not self.__rgb: <NEW_LINE> <INDENT> rgb = bytearray(self.height * self.width * 3) <NEW_LINE> raw = self.raw <NEW_LINE> rgb[0::3] = raw[2::4] <NEW_LINE> rgb[1::3] = raw[1::4] <NEW_LINE> rgb[2::3] = raw[0::4] <NEW_LINE> self.__rgb = bytes(rgb) <NEW_LINE> <DEDENT> return self.__rgb <NEW_LINE> <DEDENT> @property <NEW_LINE> def top(self): <NEW_LINE> <INDENT> return self.pos.top <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.size.width <NEW_LINE> <DEDENT> def pixel(self, coord_x, coord_y): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.pixels[coord_y][coord_x] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise ScreenShotError( "Pixel location ({}, {}) is out of range.".format(coord_x, coord_y) )
Screen shot object. .. note:: A better name would have been *Image*, but to prevent collisions with PIL.Image, it has been decided to use *ScreenShot*.
625990609c8ee82313040cde
class RegistryConfiguration(BrowserView): <NEW_LINE> <INDENT> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> self.catalog_name = self.request.get('catalog_name', 'portal_catalog') <NEW_LINE> self.prefix = "bika.lims.%s_query" % self.catalog_name <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> registry = getUtility(IRegistry) <NEW_LINE> registryreader = IQuerystringRegistryReader(registry) <NEW_LINE> registryreader.prefix = "plone.app.querystring.operation" <NEW_LINE> op_config = registryreader.parseRegistry() <NEW_LINE> registryreader = IQuerystringRegistryReader(registry) <NEW_LINE> registryreader.prefix = self.prefix <NEW_LINE> config = registryreader.parseRegistry() <NEW_LINE> config = registryreader.getVocabularyValues(config) <NEW_LINE> config.update(op_config) <NEW_LINE> registryreader.mapOperations(config) <NEW_LINE> registryreader.mapSortableIndexes(config) <NEW_LINE> config = { 'indexes': config.get(self.prefix + '.field'), 'sortable_indexes': config.get('sortable'), } <NEW_LINE> return json.dumps(config)
Combine default operations from plone.app.query, with fields from registry key in prefix
62599060d7e4931a7ef3d6d9
class QBXProxyGenerator(ProxyGeneratorBase): <NEW_LINE> <INDENT> def get_radii_knl(self, actx: PyOpenCLArrayContext) -> lp.LoopKernel: <NEW_LINE> <INDENT> return make_compute_block_qbx_radii_knl(actx, self.ambient_dim) <NEW_LINE> <DEDENT> def __call__(self, actx: PyOpenCLArrayContext, source_dd, indices: BlockIndexRanges, **kwargs) -> BlockProxyPoints: <NEW_LINE> <INDENT> from pytential import bind, sym <NEW_LINE> source_dd = sym.as_dofdesc(source_dd) <NEW_LINE> radii = bind(self.places, sym.expansion_radii( self.ambient_dim, dofdesc=source_dd))(actx) <NEW_LINE> center_int = bind(self.places, sym.expansion_centers( self.ambient_dim, -1, dofdesc=source_dd))(actx) <NEW_LINE> center_ext = bind(self.places, sym.expansion_centers( self.ambient_dim, +1, dofdesc=source_dd))(actx) <NEW_LINE> return super().__call__(actx, source_dd, indices, expansion_radii=flatten(radii, actx), center_int=flatten(center_int, actx, leaf_class=DOFArray), center_ext=flatten(center_ext, actx, leaf_class=DOFArray), **kwargs)
A proxy point generator that also considers the QBX expansion when determining the radius of the proxy ball. Inherits from :class:`ProxyGeneratorBase`.
6259906016aa5153ce401b86
class AddoDialogHelper(AddoHelper): <NEW_LINE> <INDENT> _PROGRESS_DIALOD_MSG = 'Overviews computation.' <NEW_LINE> def __init__(self, app, tool): <NEW_LINE> <INDENT> super().__init__(app, tool) <NEW_LINE> self.dialog = None <NEW_LINE> <DEDENT> def target_levels(self, dataset): <NEW_LINE> <INDENT> return self.dialog.overviewWidget.levels() <NEW_LINE> <DEDENT> def start(self, item, dialog=None): <NEW_LINE> <INDENT> if dialog: <NEW_LINE> <INDENT> self.dialog = dialog <NEW_LINE> <DEDENT> if not self.dialog: <NEW_LINE> <INDENT> self.setup_progress_dialog(self.app.tr(self._PROGRESS_DIALOD_MSG)) <NEW_LINE> <DEDENT> super().start(item) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> super().reset() <NEW_LINE> self.dialog = None <NEW_LINE> <DEDENT> def do_finalize(self): <NEW_LINE> <INDENT> super().do_finalize() <NEW_LINE> self.dialog.updateOverviewInfo()
Helper class for overviews computation. .. seealso:: :class:`AddoHelper`
62599060498bea3a75a59153
class RefRatingScaleListCreateView(ListCreateAPIView): <NEW_LINE> <INDENT> lookup_field = 'id' <NEW_LINE> serializer_class = RefRatingScaleSerializer <NEW_LINE> permission_classes = (PermissionSettings.IS_ADMIN_OR_READ_ONLY, CustomDjangoModelPermissions) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return RefRatingScale.objects.filter(deleted_status=False)
This module contains the definition for LIST, CREATE operation for the Rating Scale Model.
62599060e5267d203ee6cf14
class EditVariationOptions(VariationOptions, EditProductPage): <NEW_LINE> <INDENT> class PageDataWithExistingData(PageData): <NEW_LINE> <INDENT> def __set__(self, instance, data): <NEW_LINE> <INDENT> existing_data = instance.manager.product_data[instance.EXISTING_VARIATIONS] <NEW_LINE> for option, value_list in existing_data.items(): <NEW_LINE> <INDENT> for value in value_list: <NEW_LINE> <INDENT> if value not in data[option]: <NEW_LINE> <INDENT> data[option].insert(0, value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> super().__set__(instance, data) <NEW_LINE> <DEDENT> <DEDENT> data = PageDataWithExistingData()
Page to select variations for new variation products.
625990603c8af77a43b68a96
class FBTakeChangeType (object): <NEW_LINE> <INDENT> kFBTakeChangeAdded=property(doc=" ") <NEW_LINE> kFBTakeChangeRemoved=property(doc=" ") <NEW_LINE> kFBTakeChangeOpened=property(doc=" ") <NEW_LINE> kFBTakeChangeClosed=property(doc=" ") <NEW_LINE> kFBTakeChangeRenamed=property(doc=" ") <NEW_LINE> kFBTakeChangeUpdated=property(doc=" ") <NEW_LINE> kFBTakeChangeMoved=property(doc=" ") <NEW_LINE> kFBTakeChangeNone=property(doc=" ") <NEW_LINE> pass
Types of take change events.
625990608e7ae83300eea736
class ConnectSerialDialog(simpledialog.Dialog): <NEW_LINE> <INDENT> def body(self, master): <NEW_LINE> <INDENT> Label(master, text="Choose the serial I/O port").grid(row=0) <NEW_LINE> self.cb = ttk.Combobox(master, values=available_ports()) <NEW_LINE> self.cb.grid(row=1) <NEW_LINE> return self.cb <NEW_LINE> <DEDENT> def apply(self): <NEW_LINE> <INDENT> port = str(self.cb.get()) <NEW_LINE> self.result = port
Simple dialog for selecting the serial I/O port you want to use
625990607d43ff2487427f64
class Vertice(object): <NEW_LINE> <INDENT> def __init__(self, label=None): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> self.lista_vecinos = [] <NEW_LINE> self.lista_pesos = [] <NEW_LINE> self.grado = 0 <NEW_LINE> self.estado = "NO VISITADO" <NEW_LINE> self.distancia = None <NEW_LINE> self.padre = None <NEW_LINE> self.totalDistance = float('Inf') <NEW_LINE> <DEDENT> def añadir_adyacentes(self, vecino, peso): <NEW_LINE> <INDENT> if vecino not in self.lista_vecinos: <NEW_LINE> <INDENT> self.lista_vecinos.append(vecino) <NEW_LINE> self.lista_pesos.append(peso) <NEW_LINE> self.grado += 1 <NEW_LINE> <DEDENT> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return int(self.label) < int(other.label)
Esta es una clase vértice que representa un nodo en un grafo.
625990608e7ae83300eea737
class HierarchicalLSTM(nn.Module): <NEW_LINE> <INDENT> def __init__(self, lstm_dim, score_dim, bidir, num_layers=2, drop_prob=0.20, method='max'): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> num_dirs = 2 if bidir else 1 <NEW_LINE> input_dim = lstm_dim*num_dirs <NEW_LINE> self.model = nn.Sequential( LSTMLower(lstm_dim, num_layers, bidir, drop_prob, method), LSTMHigher(input_dim, lstm_dim, num_layers, bidir, drop_prob), Score(input_dim, score_dim, out_dim=2, drop_prob=drop_prob) ) <NEW_LINE> <DEDENT> def forward(self, batch): <NEW_LINE> <INDENT> return self.model(batch)
Super class for taking an input batch of sentences from a Batch and computing the probability whether they end a segment or not
62599060e64d504609df9f23
class CopyrightCommand(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> def __init__(self, view): <NEW_LINE> <INDENT> self.settings = sublime.load_settings(AutoCopyright.constants.SETTINGS_FILE) <NEW_LINE> self.view = view <NEW_LINE> self.selected_owner = None <NEW_LINE> <DEDENT> def format_pattern(self, year, owner, fileName): <NEW_LINE> <INDENT> text = self.format_text("yyyear", "ooowner", "fffileName") <NEW_LINE> text = re.escape(text) <NEW_LINE> text = text.replace("yyyear", year) <NEW_LINE> text = text.replace("fffileName", fileName) <NEW_LINE> pattern = text.replace("ooowner", owner) <NEW_LINE> return pattern <NEW_LINE> <DEDENT> def format_text(self, year, owner, fileName): <NEW_LINE> <INDENT> if year is None: <NEW_LINE> <INDENT> raise TypeError("year cannot be None.") <NEW_LINE> <DEDENT> if len(owner) == 0: <NEW_LINE> <INDENT> raise TypeError("owner cannot be empty.") <NEW_LINE> <DEDENT> text = self.settings.get(AutoCopyright.constants.SETTING_COPYRIGHT_MESSAGE) <NEW_LINE> text = text.replace("%y", str(year)) <NEW_LINE> text = text.replace("%o", owner) <NEW_LINE> text = text.replace("%f", fileName) <NEW_LINE> return text <NEW_LINE> <DEDENT> def handle_missing_owner_exception(self): <NEW_LINE> <INDENT> fileName = sublime.active_window().active_view().file_name() <NEW_LINE> if fileName is not None and fileName.endswith(AutoCopyright.constants.SETTINGS_FILE): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> AutoCopyright.helper.error_message(AutoCopyright.constants.ERROR_MISSING_OWNER) <NEW_LINE> user_settings_path = os.path.join(sublime.packages_path(), AutoCopyright.constants.SETTINGS_PATH_USER) <NEW_LINE> user_settings_filename = os.path.join(user_settings_path, AutoCopyright.constants.SETTINGS_FILE) <NEW_LINE> if not os.path.exists(user_settings_path): <NEW_LINE> <INDENT> os.makedirs(user_settings_path) <NEW_LINE> <DEDENT> if not os.path.exists(user_settings_filename): <NEW_LINE> <INDENT> default_settings_filename = os.path.join(sublime.packages_path(), constants.PLUGIN_NAME, constants.SETTINGS_FILE) <NEW_LINE> shutil.copy(default_settings_filename, user_settings_filename) <NEW_LINE> <DEDENT> sublime.active_window().open_file(user_settings_filename)
Common functionality for the Auto Copyright command classes.
625990604428ac0f6e659bdc
class CaptchaFound(Exception): <NEW_LINE> <INDENT> pass
Raised when google fucks you with captcha.
6259906015baa7234946363d
class LibTIFFSeeker(Seeker): <NEW_LINE> <INDENT> NAME = 'libtiff' <NEW_LINE> VERSION_STRING = "LIBTIFF, Version " <NEW_LINE> SANITY_STRING = "TIFFRasterScanlineSize64" <NEW_LINE> def searchLib(self, logger): <NEW_LINE> <INDENT> self._version_strings = [] <NEW_LINE> self._sanity_exists = False <NEW_LINE> for bin_str in self._all_strings: <NEW_LINE> <INDENT> if self.VERSION_STRING in str(bin_str): <NEW_LINE> <INDENT> version_string = str(bin_str) <NEW_LINE> logger.debug("Located a version string of %s in address 0x%x", self.NAME, bin_str.ea) <NEW_LINE> self._version_strings.append(version_string) <NEW_LINE> <DEDENT> if self.SANITY_STRING in str(bin_str): <NEW_LINE> <INDENT> self._sanity_exists = True <NEW_LINE> <DEDENT> <DEDENT> if self._sanity_exists and len(self._version_strings) == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return len(self._version_strings) <NEW_LINE> <DEDENT> <DEDENT> def identifyVersions(self, logger): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for work_str in self._version_strings: <NEW_LINE> <INDENT> results.append(self.extractVersion(work_str, start_index=work_str.find(self.VERSION_STRING) + len(self.VERSION_STRING))) <NEW_LINE> <DEDENT> if len(results) == 0 and self._sanity_exists: <NEW_LINE> <INDENT> return [self.VERSION_UNKNOWN] <NEW_LINE> <DEDENT> return results
Seeker (Identifier) for the libtiff open source library.
625990608e71fb1e983bd175
class PointerType(Type): <NEW_LINE> <INDENT> is_pointer = True <NEW_LINE> null = 'null' <NEW_LINE> def __init__(self, pointee, addrspace=0): <NEW_LINE> <INDENT> assert not isinstance(pointee, VoidType) <NEW_LINE> self.pointee = pointee <NEW_LINE> self.addrspace = addrspace <NEW_LINE> <DEDENT> def _to_string(self): <NEW_LINE> <INDENT> if self.addrspace != 0: <NEW_LINE> <INDENT> return "{0} addrspace({1})*".format(self.pointee, self.addrspace) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "{0}*".format(self.pointee) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, PointerType): <NEW_LINE> <INDENT> return (self.pointee, self.addrspace) == (other.pointee, other.addrspace) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(PointerType) <NEW_LINE> <DEDENT> def gep(self, i): <NEW_LINE> <INDENT> if not isinstance(i.type, IntType): <NEW_LINE> <INDENT> raise TypeError(i.type) <NEW_LINE> <DEDENT> return self.pointee <NEW_LINE> <DEDENT> @property <NEW_LINE> def intrinsic_name(self): <NEW_LINE> <INDENT> return 'p%d%s' % (self.addrspace, self.pointee.intrinsic_name)
The type of all pointer values.
62599060f7d966606f74940e
class InviteListView(PaginationMixin, PaginateByMixin, SortableListMixin, CommonViewMixin, ListView): <NEW_LINE> <INDENT> model = Invite <NEW_LINE> nav_active_item = 'Admin' <NEW_LINE> dd_active_item = 'Invites' <NEW_LINE> valid_order_by = [ 'email', 'is_staff', 'is_superuser', 'created_at', 'created_by', 'notified', 'consumed_at' ] <NEW_LINE> default_order_by = 'created_at' <NEW_LINE> paginate_by = 20 <NEW_LINE> context_object_name = 'invites' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = super(InviteListView, self).get_queryset() <NEW_LINE> query = self.request.GET.get('q') <NEW_LINE> if query: <NEW_LINE> <INDENT> queryset = queryset.filter(email__icontains=query) <NEW_LINE> <DEDENT> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(InviteListView, self).get_context_data(**kwargs) <NEW_LINE> context['q'] = self.request.GET.get('q', '') <NEW_LINE> return context
View for listing invites.
6259906097e22403b383c5b8
class DynamicFieldsMixin: <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> allowed = kwargs.pop('fields', None) <NEW_LINE> excluded = kwargs.pop('excluded_fields', None) <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> request = self.context.get('request') <NEW_LINE> if allowed is None: <NEW_LINE> <INDENT> allowed = self.context.get('allowed_fields') <NEW_LINE> <DEDENT> if excluded is None: <NEW_LINE> <INDENT> excluded = self.context.get('excluded_fields') <NEW_LINE> <DEDENT> if not allowed and not excluded and request and request.method == 'GET': <NEW_LINE> <INDENT> allowed_fields = get_from_request_query_params(request, 'fields') <NEW_LINE> if allowed_fields: <NEW_LINE> <INDENT> allowed = set(allowed_fields.split(',', 64)) <NEW_LINE> <DEDENT> excluded_fields = get_from_request_query_params(request, 'excluded_fields') <NEW_LINE> if excluded_fields: <NEW_LINE> <INDENT> excluded = set(excluded_fields.split(',', 64)) <NEW_LINE> <DEDENT> <DEDENT> if allowed or excluded: <NEW_LINE> <INDENT> self.context['allowed_fields'] = allowed <NEW_LINE> self.context['excluded_fields'] = excluded <NEW_LINE> <DEDENT> <DEDENT> @cached_property <NEW_LINE> def _readable_fields(self): <NEW_LINE> <INDENT> obj = self <NEW_LINE> allowed = None <NEW_LINE> excluded = None <NEW_LINE> while obj is not None: <NEW_LINE> <INDENT> allowed = obj.context.get('allowed_fields') <NEW_LINE> excluded = obj.context.get('excluded_fields') <NEW_LINE> if allowed or excluded: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if self.parent is not obj: <NEW_LINE> <INDENT> obj = self.parent <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj = None <NEW_LINE> <DEDENT> <DEDENT> fields_to_remove = set() <NEW_LINE> existing = set(self.fields.keys()) <NEW_LINE> if allowed: <NEW_LINE> <INDENT> fields_to_remove = existing - allowed <NEW_LINE> <DEDENT> if excluded: <NEW_LINE> <INDENT> fields_to_remove = fields_to_remove | existing.intersection(excluded) <NEW_LINE> <DEDENT> fields = [] <NEW_LINE> for field_name, field in self.fields.items(): <NEW_LINE> <INDENT> if not field.write_only and field_name not in fields_to_remove: <NEW_LINE> <INDENT> fields.append(field) <NEW_LINE> <DEDENT> <DEDENT> return fields
A serializer mixin that takes an additional `fields` and `excluded_fields` arguments that controls which fields should be displayed. Usage:: class MySerializer(DynamicFieldsMixin, serializers.HyperlinkedModelSerializer): class Meta: model = MyModel
6259906099cbb53fe683258c
class DropDownCommandInput(CommandInput): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def cast(arg): <NEW_LINE> <INDENT> return DropDownCommandInput() <NEW_LINE> <DEDENT> @property <NEW_LINE> def dropDownStyle(self): <NEW_LINE> <INDENT> return DropDownStyles() <NEW_LINE> <DEDENT> @property <NEW_LINE> def listItems(self): <NEW_LINE> <INDENT> return ListItems() <NEW_LINE> <DEDENT> @property <NEW_LINE> def selectedItem(self): <NEW_LINE> <INDENT> return ListItem() <NEW_LINE> <DEDENT> @property <NEW_LINE> def maxVisibleItems(self): <NEW_LINE> <INDENT> return int() <NEW_LINE> <DEDENT> @maxVisibleItems.setter <NEW_LINE> def maxVisibleItems(self, maxVisibleItems): <NEW_LINE> <INDENT> pass
Provides a command input to get the choice in a dropdown list from the user.
625990603617ad0b5ee077f9