code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class AgentService(service.MultiService): <NEW_LINE> <INDENT> def __init__(self, web_ui_port): <NEW_LINE> <INDENT> service.MultiService.__init__(self) <NEW_LINE> director = Director() <NEW_LINE> self.scheduler_service = SchedulerService(director) <NEW_LINE> self.scheduler_service.setServiceParent(self) <NEW_LINE> if not config.advanced.disabled_webui: <NEW_LINE> <INDENT> self.web_ui_service = WebUIService(director, self.scheduler_service, web_ui_port) <NEW_LINE> self.web_ui_service.setServiceParent(self) <NEW_LINE> <DEDENT> <DEDENT> def startService(self): <NEW_LINE> <INDENT> service.MultiService.startService(self) <NEW_LINE> <DEDENT> def stopService(self): <NEW_LINE> <INDENT> service.MultiService.stopService(self)
Manage all services related to the ooniprobe-agent daemon.
62599071adb09d7d5dc0be43
class CountableWidgetTestCase(FacetedTestCase): <NEW_LINE> <INDENT> def afterSetUp(self): <NEW_LINE> <INDENT> self.request = self.app.REQUEST <NEW_LINE> <DEDENT> def test_widget_empty_count(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> widget = CountableWidget(self.portal, self.request, data=data) <NEW_LINE> self.assertEqual(widget.count([]), {}) <NEW_LINE> <DEDENT> def test_widget_solr_count(self): <NEW_LINE> <INDENT> data = {'index': 'tags'} <NEW_LINE> widget = CountableWidget(self.portal, self.request, data=data) <NEW_LINE> dummyresponse = DummySolrResponse({'tags': {'foo': 10, 'bar': 7}}) <NEW_LINE> self.assertEqual(widget.count(dummyresponse), {'': 1, 'all': 1, u'bar': 7, u'foo': 10})
Test
6259907160cbc95b063659da
class BaseType(TypeMeta('BaseTypeBase', (object, ), {})): <NEW_LINE> <INDENT> MESSAGES = { 'required': u"This field is required.", 'choices': u"Value must be one of {0}.", } <NEW_LINE> def __init__(self, required=False, default=None, serialized_name=None, choices=None, validators=None, deserialize_from=None, serialize_when_none=None, messages=None): <NEW_LINE> <INDENT> self.required = required <NEW_LINE> self._default = default <NEW_LINE> self.serialized_name = serialized_name <NEW_LINE> self.choices = choices <NEW_LINE> self.deserialize_from = deserialize_from <NEW_LINE> self.validators = [functools.partial(v, self) for v in self._validators] <NEW_LINE> if validators: <NEW_LINE> <INDENT> self.validators += validators <NEW_LINE> <DEDENT> self.serialize_when_none = serialize_when_none <NEW_LINE> self.messages = dict(self.MESSAGES, **(messages or {})) <NEW_LINE> self._position_hint = next(_next_position_hint) <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> return self.to_native(value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def default(self): <NEW_LINE> <INDENT> default = self._default <NEW_LINE> if callable(self._default): <NEW_LINE> <INDENT> default = self._default() <NEW_LINE> <DEDENT> return default <NEW_LINE> <DEDENT> def to_primitive(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def to_native(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def allow_none(self): <NEW_LINE> <INDENT> if hasattr(self, 'owner_model'): <NEW_LINE> <INDENT> return self.owner_model.allow_none(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.serialize_when_none <NEW_LINE> <DEDENT> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> for validator in self.validators: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validator(value) <NEW_LINE> <DEDENT> except ValidationError as e: <NEW_LINE> <INDENT> errors.extend(e.messages) <NEW_LINE> if isinstance(e, StopValidation): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if errors: <NEW_LINE> <INDENT> raise ValidationError(errors) <NEW_LINE> <DEDENT> <DEDENT> def validate_required(self, value): <NEW_LINE> <INDENT> if self.required and value is None: <NEW_LINE> <INDENT> raise ValidationError(self.messages['required']) <NEW_LINE> <DEDENT> <DEDENT> def validate_choices(self, value): <NEW_LINE> <INDENT> if self.choices is not None: <NEW_LINE> <INDENT> if value not in self.choices: <NEW_LINE> <INDENT> raise ValidationError(self.messages['choices'] .format(unicode(self.choices)))
A base class for Types in a Schematics model. Instances of this class may be added to subclasses of ``Model`` to define a model schema. Validators that need to access variables on the instance can be defined be implementing methods whose names start with ``validate_`` and accept one parameter (in addition to ``self``) :param required: Invalidate field when value is None or is not supplied. Default: False. :param default: When no data is provided default to this value. May be a callable. Default: None. :param serialized_name: The name of this field defaults to the class attribute used in the model. However if the field has another name in foreign data set this argument. Serialized data will use this value for the key name too. :param deserialize_from: A name or list of named fields for which foreign data sets are searched to provide a value for the given field. This only effects inbound data. :param choices: An iterable of valid choices. This is the last step of the validator chain. :param validators: A list of callables. Each callable receives the value after it has been converted into a rich python type. Default: [] :param serialize_when_none: Dictates if the field should appear in the serialized data even if the value is None. Default: True :param messages: Override the error messages with a dict. You can also do this by subclassing the Type and defining a `MESSAGES` dict attribute on the class. A metaclass will merge all the `MESSAGES` and override the resulting dict with instance level `messages` and assign to `self.messages`.
625990712ae34c7f260ac9c3
class OpenTagError(NestingError): <NEW_LINE> <INDENT> def __init__(self, tagstack, tag, position=(None, None)): <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> msg = 'Tag <%s> is not allowed in <%s>' % (tag, tagstack[-1]) <NEW_LINE> HTMLParseError.__init__(self, msg, position)
Exception raised when a tag is not allowed in another tag.
62599071fff4ab517ebcf0f3
class SessionStore(SessionBase): <NEW_LINE> <INDENT> def __init__(self, session_key=None): <NEW_LINE> <INDENT> self.redis = redis.Redis( host=getattr(settings, "REDIS_HOST", None), port=getattr(settings, "REDIS_PORT", None), db=getattr(settings, "REDIS_DB", None)) <NEW_LINE> super(SessionStore, self).__init__(session_key) <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> session_data = self.redis.get(self.session_key) <NEW_LINE> if session_data is not None: <NEW_LINE> <INDENT> return loads(session_data) <NEW_LINE> <DEDENT> self.create() <NEW_LINE> return {} <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.session_key = self._get_new_session_key() <NEW_LINE> try: <NEW_LINE> <INDENT> self.save(must_create=True) <NEW_LINE> <DEDENT> except CreateError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.modified = True <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> def save(self, must_create=False): <NEW_LINE> <INDENT> if must_create: <NEW_LINE> <INDENT> result = self.redis.set( self.session_key, dumps(self._get_session(no_load=must_create)), preserve=True) <NEW_LINE> if result == 0: <NEW_LINE> <INDENT> raise CreateError <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.redis.set(self.session_key, dumps(self._get_session(no_load=must_create)),) <NEW_LINE> <DEDENT> <DEDENT> def exists(self, session_key): <NEW_LINE> <INDENT> if self.redis.exists(session_key): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def delete(self, session_key=None): <NEW_LINE> <INDENT> if session_key is None: <NEW_LINE> <INDENT> if self._session_key is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> session_key = self._session_key <NEW_LINE> <DEDENT> self.redis.delete(session_key)
A redis-based session store.
625990714527f215b58eb60c
class TestClusterInstanceInfo(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testClusterInstanceInfo(self): <NEW_LINE> <INDENT> pass
ClusterInstanceInfo unit test stubs
62599071f548e778e596ce66
class echoList_args(TBase): <NEW_LINE> <INDENT> def __init__(self, lst=None,): <NEW_LINE> <INDENT> self.lst = lst <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - lst
62599071009cb60464d02e11
class StdoutRedirect(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, queue): <NEW_LINE> <INDENT> super(StdoutRedirect, self).__init__() <NEW_LINE> stringio = io.StringIO('') <NEW_LINE> self.sys_module = sys.modules['sys'] <NEW_LINE> setattr(self.sys_module, 'stdout', stringio) <NEW_LINE> self.queue = queue <NEW_LINE> self.daemon = True <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> time.sleep(.1) <NEW_LINE> try: <NEW_LINE> <INDENT> item = self.queue.get_nowait() <NEW_LINE> self.queue.put(item) <NEW_LINE> self.sys_module = io.StringIO('') <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> pass
This shunts stdout data to a queue that feeds a tkinter.Text window.
62599071bf627c535bcb2da5
class Comment(CharacterData): <NEW_LINE> <INDENT> nodeName = '#comment' <NEW_LINE> nodeType = Node.COMMENT_NODE <NEW_LINE> __slots__ = Node.TEXT_SLOTS
Comment http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-1728279322
625990717c178a314d78e858
class TobyStandardWorker(TobyBaseWorker): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> class Executor(TobyBaseExecutor): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.kwargs['sample_object_instance'] = None <NEW_LINE> <DEDENT> <DEDENT> TobyBaseWorker.__init__(self, *args, executor=Executor, **kwargs)
The standard Toby Worker
625990718a43f66fc4bf3a6e
class RetryTaskError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, exc, *args, **kwargs): <NEW_LINE> <INDENT> self.exc = exc <NEW_LINE> Exception.__init__(self, message, exc, *args, **kwargs)
The task is to be retried later.
625990714c3428357761bb8e
class DomainQueuer: <NEW_LINE> <INDENT> def __init__(self, service, authenticated=False): <NEW_LINE> <INDENT> self.service = service <NEW_LINE> self.authed = authenticated <NEW_LINE> <DEDENT> def exists(self, user): <NEW_LINE> <INDENT> if self.willRelay(user.dest, user.protocol): <NEW_LINE> <INDENT> orig = filter(None, str(user.orig).split('@', 1)) <NEW_LINE> dest = filter(None, str(user.dest).split('@', 1)) <NEW_LINE> if len(orig) == 2 and len(dest) == 2: <NEW_LINE> <INDENT> return lambda: self.startMessage(user) <NEW_LINE> <DEDENT> <DEDENT> raise smtp.SMTPBadRcpt(user) <NEW_LINE> <DEDENT> def willRelay(self, address, protocol): <NEW_LINE> <INDENT> peer = protocol.transport.getPeer() <NEW_LINE> return (self.authed or isinstance(peer, UNIXAddress) or peer.host == '127.0.0.1') <NEW_LINE> <DEDENT> def startMessage(self, user): <NEW_LINE> <INDENT> queue = self.service.queue <NEW_LINE> envelopeFile, smtpMessage = queue.createNewMessage() <NEW_LINE> try: <NEW_LINE> <INDENT> log.msg('Queueing mail %r -> %r' % (str(user.orig), str(user.dest))) <NEW_LINE> pickle.dump([str(user.orig), str(user.dest)], envelopeFile) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> envelopeFile.close() <NEW_LINE> <DEDENT> return smtpMessage
An SMTP domain which add messages to a queue intended for relaying.
62599071a8370b77170f1ca4
class MaximalRectangleImplStack(MaximalRectangle): <NEW_LINE> <INDENT> def maximal_rectangle(self, matrix): <NEW_LINE> <INDENT> histograms = self.construct_histograms_from_matrix(matrix) <NEW_LINE> return max(self.largest_rectangle_area_in_histogram(heights) for heights in histograms) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def construct_histograms_from_matrix(matrix): <NEW_LINE> <INDENT> rows, cols = len(matrix), len(matrix[0]) <NEW_LINE> histogram_cur_row = [int(x) for x in matrix[0]] <NEW_LINE> histograms = [histogram_cur_row] <NEW_LINE> for r in xrange(1, rows): <NEW_LINE> <INDENT> histogram_cur_row = [] <NEW_LINE> for c in xrange(cols): <NEW_LINE> <INDENT> histogram_cur_row.append(histograms[-1][c] + 1 if matrix[r][c] == '1' else 0) <NEW_LINE> <DEDENT> histograms.append(histogram_cur_row) <NEW_LINE> <DEDENT> return histograms <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def largest_rectangle_area_in_histogram(heights): <NEW_LINE> <INDENT> max_rect = 0 <NEW_LINE> index_stack = [] <NEW_LINE> for i, h in enumerate(heights + [0]): <NEW_LINE> <INDENT> while index_stack and heights[index_stack[-1]] > h: <NEW_LINE> <INDENT> max_rect = max(max_rect, heights[index_stack.pop()] * (i - index_stack[-1] - 1 if index_stack else i)) <NEW_LINE> <DEDENT> index_stack.append(i) <NEW_LINE> <DEDENT> return max_rect
Time: O(nm) Space: O(nm) 采用算法强化班中讲到的单调栈。 要做这个题之前先做直方图最大矩阵(Largest Rectangle in Histogram) 这个题。 这个题其实就是包了一层皮而已。一行一行的计算以当前行为矩阵的下边界时,最大矩阵是什么。 计算某一行为下边界时的情况,就可以转换为直方图最大矩阵问题了。
62599071be8e80087fbc096a
class CsvResultDescriptor(object): <NEW_LINE> <INDENT> def __init__(self, file_path): <NEW_LINE> <INDENT> self.file_path = file_path <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'CSV results at %s' % os.path.join(os.path.abspath('.'), self.file_path) <NEW_LINE> <DEDENT> def _repr_html_(self): <NEW_LINE> <INDENT> return '<a href="%s">CSV results</a>' % os.path.join('.', 'files', self.file_path)
Provides IPython Notebook-friendly output for the feedback after a ``.csv`` called.
6259907123849d37ff852991
class WinFileTestCase(TestCase, LoaderModuleMockMixin): <NEW_LINE> <INDENT> FAKE_RET = {'fake': 'ret data'} <NEW_LINE> if salt.utils.platform.is_windows(): <NEW_LINE> <INDENT> FAKE_PATH = os.sep.join(['C:', 'path', 'does', 'not', 'exist']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> FAKE_PATH = os.sep.join(['path', 'does', 'not', 'exist']) <NEW_LINE> <DEDENT> def setup_loader_modules(self): <NEW_LINE> <INDENT> return { win_file: { '__utils__': {'dacl.set_perms': win_dacl.set_perms}, '__salt__': {'cmd.run_stdout': cmdmod.run_stdout} } } <NEW_LINE> <DEDENT> def test_issue_43328_stats(self): <NEW_LINE> <INDENT> with patch('os.path.exists', return_value=False): <NEW_LINE> <INDENT> self.assertRaises(CommandExecutionError, win_file.stats, self.FAKE_PATH) <NEW_LINE> <DEDENT> <DEDENT> def test_issue_43328_check_perms_no_ret(self): <NEW_LINE> <INDENT> with patch('os.path.exists', return_value=False): <NEW_LINE> <INDENT> self.assertRaises( CommandExecutionError, win_file.check_perms, self.FAKE_PATH) <NEW_LINE> <DEDENT> <DEDENT> @skipIf(not salt.utils.platform.is_windows(), 'Skip on Non-Windows systems') <NEW_LINE> @skipIf(WIN_VER < 6, 'Symlinks not supported on Vista an lower') <NEW_LINE> def test_issue_52002_check_file_remove_symlink(self): <NEW_LINE> <INDENT> base = temp.dir(prefix='base-', parent=RUNTIME_VARS.TMP) <NEW_LINE> target = os.path.join(base, 'child 1', 'target\\') <NEW_LINE> symlink = os.path.join(base, 'child 2', 'link') <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertFalse(win_file.directory_exists(target)) <NEW_LINE> self.assertFalse(win_file.directory_exists(symlink)) <NEW_LINE> self.assertTrue(win_file.makedirs_(target)) <NEW_LINE> self.assertTrue(win_file.makedirs_(symlink)) <NEW_LINE> self.assertTrue(win_file.symlink(target, symlink)) <NEW_LINE> self.assertTrue(win_file.directory_exists(symlink)) <NEW_LINE> self.assertTrue(win_file.is_link(symlink)) <NEW_LINE> self.assertTrue(win_file.remove(base)) <NEW_LINE> self.assertFalse(win_file.directory_exists(base)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if os.path.exists(base): <NEW_LINE> <INDENT> win_file.remove(base)
Test cases for salt.modules.win_file
62599071442bda511e95d9c5
class getBootstrapInfo_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (BootstrapInfo, BootstrapInfo.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = BootstrapInfo() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getBootstrapInfo_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success
625990714428ac0f6e659e0f
class CookiePostHandlerMiddleware(object): <NEW_LINE> <INDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> if hasattr(request, '_orig_cookies') and request.COOKIES != request._orig_cookies: <NEW_LINE> <INDENT> for k,v in request.COOKIES.iteritems(): <NEW_LINE> <INDENT> if request._orig_cookies.get(k) != v: <NEW_LINE> <INDENT> dict.__setitem__(response.cookies, k, v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return response
This middleware modifies updates the response will all modified cookies. This should be the last middleware you load.
6259907116aa5153ce401db4
class PRAC2D(CrackProperty): <NEW_LINE> <INDENT> type = 'PRAC2D' <NEW_LINE> _field_map = { 1: 'pid', 2:'mid', 3:'thick', 4:'iPlane', 5:'nsm', 6:'gamma', 7:'phi', } <NEW_LINE> def __init__(self, card=None, data=None, comment=''): <NEW_LINE> <INDENT> CrackProperty.__init__(self, card, data) <NEW_LINE> if comment: <NEW_LINE> <INDENT> self._comment = comment <NEW_LINE> <DEDENT> if card: <NEW_LINE> <INDENT> self.pid = integer(card, 1, 'pid') <NEW_LINE> self.mid = integer(card, 2, 'mid') <NEW_LINE> self.thick = double(card, 3, 'thick') <NEW_LINE> self.iPlane = integer(card, 4, 'iPlane') <NEW_LINE> if self.iPlane not in [0, 1]: <NEW_LINE> <INDENT> raise RuntimeError('Invalid value for iPlane on PRAC2D, can ' 'only be 0,1 iPlane=|%s|' % self.iPlane) <NEW_LINE> <DEDENT> self.nsm = double_or_blank(card, 5, 'nsm', 0.) <NEW_LINE> self.gamma = double_or_blank(card, 6, 'gamma', 0.5) <NEW_LINE> self.phi = double_or_blank(card, 7, 'phi', 180.) <NEW_LINE> assert len(card) <= 8, 'len(PRAC2D card) = %i' % len(card) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError(data) <NEW_LINE> <DEDENT> <DEDENT> def _verify(self, xref=True): <NEW_LINE> <INDENT> pid = self.Pid() <NEW_LINE> assert isinstance(pid, int) <NEW_LINE> <DEDENT> def cross_reference(self, model): <NEW_LINE> <INDENT> msg = ' which is required by PRAC2D pid=%s' % self.pid <NEW_LINE> self.mid = model.Material(self.mid, msg) <NEW_LINE> <DEDENT> def raw_fields(self): <NEW_LINE> <INDENT> fields = ['PRAC2D', self.pid, self.Mid(), self.thick, self.iPlane, self.nsm, self.gamma, self.phi] <NEW_LINE> return fields <NEW_LINE> <DEDENT> def repr_fields(self): <NEW_LINE> <INDENT> nsm = set_blank_if_default(self.nsm, 0.) <NEW_LINE> gamma = set_blank_if_default(self.gamma, 0.5) <NEW_LINE> phi = set_blank_if_default(self.phi, 180.) <NEW_LINE> fields = ['PRAC2D', self.pid, self.Mid(), self.thick, self.iPlane, nsm, gamma, phi] <NEW_LINE> return fields
CRAC2D Element Property Defines the properties and stress evaluation techniques to be used with the CRAC2D structural element.
625990714f88993c371f118e
class BaseView(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> raise NotImplementedError('This interface cannot be instantiated.') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load_builder_file(cls, path_parts, root=None, domain=''): <NEW_LINE> <INDENT> _id = "/".join(path_parts) <NEW_LINE> if _id in _builders: <NEW_LINE> <INDENT> return _builders[_id] <NEW_LINE> <DEDENT> buildername = pan_app.get_abs_data_filename(path_parts) <NEW_LINE> builder = Builder() <NEW_LINE> builder.add_from_file(buildername) <NEW_LINE> builder.set_translation_domain(domain) <NEW_LINE> _builders[_id] = builder <NEW_LINE> return builder <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> raise NotImplementedError('This method needs to be implemented by all sub-classes.')
Interface for views.
62599071bf627c535bcb2da7
class RevertButton(Button): <NEW_LINE> <INDENT> _id = _wx.ID_REVERT <NEW_LINE> _default_label = _(u'Revert')
A button with the label 'Revert'. Resets pending changes back to the default state or undoes any alterations made by the user. See Button for documentation on button events.
625990714e4d562566373ce2
class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): <NEW_LINE> <INDENT> _sendfile_compatible = constants._SendfileMode.TRY_NATIVE <NEW_LINE> def __init__(self, loop, sock, protocol, waiter=None, extra=None, server=None): <NEW_LINE> <INDENT> super().__init__(loop, sock, protocol, waiter, extra, server) <NEW_LINE> base_events._set_nodelay(sock) <NEW_LINE> <DEDENT> def _set_extra(self, sock): <NEW_LINE> <INDENT> self._extra['socket'] = sock <NEW_LINE> try: <NEW_LINE> <INDENT> self._extra['sockname'] = sock.getsockname() <NEW_LINE> <DEDENT> except (socket.error, AttributeError): <NEW_LINE> <INDENT> if self._loop.get_debug(): <NEW_LINE> <INDENT> logger.warning( "getsockname() failed on %r", sock, exc_info=True) <NEW_LINE> <DEDENT> <DEDENT> if 'peername' not in self._extra: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._extra['peername'] = sock.getpeername() <NEW_LINE> <DEDENT> except (socket.error, AttributeError): <NEW_LINE> <INDENT> if self._loop.get_debug(): <NEW_LINE> <INDENT> logger.warning("getpeername() failed on %r", sock, exc_info=True) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def can_write_eof(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def write_eof(self): <NEW_LINE> <INDENT> if self._closing or self._eof_written: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._eof_written = True <NEW_LINE> if self._write_fut is None: <NEW_LINE> <INDENT> self._sock.shutdown(socket.SHUT_WR)
Transport for connected sockets.
625990711b99ca40022901a3
class Model: <NEW_LINE> <INDENT> def __init__(self, world_path, robot_path, motion_path, output_path, model_path): <NEW_LINE> <INDENT> self.world = World(world_path) <NEW_LINE> self.robot = Robot(robot_path) <NEW_LINE> self.planner = Planner(self.robot, self.world, motion_path, output_path, model_path) <NEW_LINE> <DEDENT> def handle_start(self): <NEW_LINE> <INDENT> self.planner.handle_start() <NEW_LINE> <DEDENT> def handle_reset(self): <NEW_LINE> <INDENT> self.world.handle_reset() <NEW_LINE> self.planner.handle_reset() <NEW_LINE> <DEDENT> def handle_pause(self): <NEW_LINE> <INDENT> self.planner.handle_pause() <NEW_LINE> <DEDENT> def handle_increase_fps(self): <NEW_LINE> <INDENT> self.planner.handle_increase_fps() <NEW_LINE> <DEDENT> def handle_decrease_fps(self): <NEW_LINE> <INDENT> self.planner.handle_decrease_fps() <NEW_LINE> <DEDENT> def handle_toggle_view(self): <NEW_LINE> <INDENT> self.planner.handle_toggle_view() <NEW_LINE> <DEDENT> def update(self, delta_time, is_training=False): <NEW_LINE> <INDENT> self.planner.update(delta_time, is_training) <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> self.planner.draw()
The governing class for the simulation model. Represents all the data within the simulation, which can be manipulated and interacted with.
6259907191f36d47f2231afc
class EventActionLoader(BaseEweLoader): <NEW_LINE> <INDENT> input_parameters_out = Identity() <NEW_LINE> output_parameters_out = Identity()
EventItem and Action item loaders. In addition to BaseEweLoader, it keeps the list of input and output parameters in the output.
6259907167a9b606de547711
class Psi3SPTest(GenericSPTest): <NEW_LINE> <INDENT> b3lyp_energy = -10300 <NEW_LINE> @unittest.skip('atommasses not implemented yet') <NEW_LINE> def testatommasses(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @unittest.skip('Psi3 did not print partial atomic charges') <NEW_LINE> def testatomcharges(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @unittest.skip('MO coefficients are printed separately for each SALC') <NEW_LINE> def testfornoormo(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @unittest.skip('MO coefficients are printed separately for each SALC') <NEW_LINE> def testdimmocoeffs(self): <NEW_LINE> <INDENT> pass
Customized restricted single point HF/KS unittest
625990717d847024c075dcb4
class Square(Rectangle): <NEW_LINE> <INDENT> def __init__(self, size, x=0, y=0, id=None): <NEW_LINE> <INDENT> super().__init__(size, size, x, y, id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.width <NEW_LINE> <DEDENT> @size.setter <NEW_LINE> def size(self, value): <NEW_LINE> <INDENT> self.width = value <NEW_LINE> self.height = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[Square] ({:d}) {:d}/{:d} - {:d}".format(self.id, self.x, self.y, self.width) <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args): <NEW_LINE> <INDENT> for i, arg in enumerate(args): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> self.id = arg <NEW_LINE> <DEDENT> elif i == 1: <NEW_LINE> <INDENT> self.size = arg <NEW_LINE> <DEDENT> elif i == 2: <NEW_LINE> <INDENT> self.x = arg <NEW_LINE> <DEDENT> elif i == 3: <NEW_LINE> <INDENT> self.y = arg <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for key, value in kwargs.items(): <NEW_LINE> <INDENT> if hasattr(self, key) is True: <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def to_dictionary(self): <NEW_LINE> <INDENT> return { "id": self.id, "size": self.size, "x": self.x, "y": self.y }
Module Representation of Square
625990714a966d76dd5f07c6
class All(CAReduce): <NEW_LINE> <INDENT> __props__ = ("axis",) <NEW_LINE> def __init__(self, axis=None): <NEW_LINE> <INDENT> CAReduce.__init__(self, scalar.and_, axis) <NEW_LINE> <DEDENT> def _output_dtype(self, idtype): <NEW_LINE> <INDENT> return "bool" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.axis is None: <NEW_LINE> <INDENT> return "All" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "All{%s}" % ", ".join(map(str, self.axis)) <NEW_LINE> <DEDENT> <DEDENT> def make_node(self, input): <NEW_LINE> <INDENT> input = as_tensor_variable(input) <NEW_LINE> if input.dtype != "bool": <NEW_LINE> <INDENT> input = theano.tensor.neq(input, 0) <NEW_LINE> <DEDENT> ret = super(All, self).make_node(input) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def grad(self, inp, grads): <NEW_LINE> <INDENT> x, = inp <NEW_LINE> return [x.zeros_like(theano.config.floatX)]
Applies `logical and` to all the values of a tensor along the specified axis(es).
625990711f5feb6acb1644ce
class UserModel(_db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = _db.Column(_db.Integer, primary_key=True) <NEW_LINE> user = _db.Column(_db.String(20), unique=True) <NEW_LINE> password = _db.Column(_db.String(30)) <NEW_LINE> def __init__(self,user,password): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def save_db(self): <NEW_LINE> <INDENT> _db.session.add(self) <NEW_LINE> _db.session.commit() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def find_by_user(cls, user): <NEW_LINE> <INDENT> return cls.query.filter_by(user=user).first() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def find_by_id(cls,id_user): <NEW_LINE> <INDENT> return cls.query.filter_by(id=id_user).first()
Model para los usuarios registrados
62599071baa26c4b54d50b87
class Solution: <NEW_LINE> <INDENT> def fourSum(self, numbers, target): <NEW_LINE> <INDENT> numLen, res, d = len(numbers), set(), {} <NEW_LINE> if numLen < 4: return [] <NEW_LINE> numbers.sort() <NEW_LINE> for p in xrange(numLen): <NEW_LINE> <INDENT> if p != numbers.index(numbers[p]): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for q in xrange(p + 1, numLen): <NEW_LINE> <INDENT> if q > numbers.index(numbers[q]) + 1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if numbers[p] + numbers[q] not in d: <NEW_LINE> <INDENT> d[numbers[p] + numbers[q]] = [[p, q]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d[numbers[p] + numbers[q]].append([p, q]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for p in xrange(numLen): <NEW_LINE> <INDENT> for q in xrange(p + 1, numLen): <NEW_LINE> <INDENT> if (target - numbers[p] - numbers[q]) in d: <NEW_LINE> <INDENT> for pairs in d[target - numbers[p] - numbers[q]]: <NEW_LINE> <INDENT> if p in pairs or q in pairs: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> temp = [numbers[i] for i in pairs] + [numbers[p], numbers[q]] <NEW_LINE> temp.sort() <NEW_LINE> res.add(tuple(temp)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return [list(i) for i in res]
@param numbersbers : Give an array numbersbersbers of n integer @param target : you need to find four elements that's sum of target @return : Find all unique quadruplets in the array which gives the sum of zero.
6259907197e22403b383c7df
class UpdatePlanetInput(graphene.InputObjectType, PlanetAttribute): <NEW_LINE> <INDENT> id = graphene.ID(required=True, description="Global Id of the planet.")
Arguments to update a planet.
625990717047854f46340c92
class TestTrackerDjangoInstantiation(TestCase): <NEW_LINE> <INDENT> @override_settings(TRACKING_BACKENDS=SIMPLE_SETTINGS.copy()) <NEW_LINE> def test_django_simple_settings(self): <NEW_LINE> <INDENT> backends = self._reload_backends() <NEW_LINE> assert len(backends) == 1 <NEW_LINE> tracker.send({}) <NEW_LINE> assert list(backends.values())[0].count == 1 <NEW_LINE> <DEDENT> @override_settings(TRACKING_BACKENDS=MULTI_SETTINGS.copy()) <NEW_LINE> def test_django_multi_settings(self): <NEW_LINE> <INDENT> backends = list(self._reload_backends().values()) <NEW_LINE> assert len(backends) == 2 <NEW_LINE> event_count = 10 <NEW_LINE> for _ in range(event_count): <NEW_LINE> <INDENT> tracker.send({}) <NEW_LINE> <DEDENT> assert backends[0].count == event_count <NEW_LINE> assert backends[1].count == event_count <NEW_LINE> <DEDENT> @override_settings(TRACKING_BACKENDS=MULTI_SETTINGS.copy()) <NEW_LINE> def test_django_remove_settings(self): <NEW_LINE> <INDENT> settings.TRACKING_BACKENDS.update({'second': None}) <NEW_LINE> backends = self._reload_backends() <NEW_LINE> assert len(backends) == 1 <NEW_LINE> <DEDENT> def _reload_backends(self): <NEW_LINE> <INDENT> tracker._initialize_backends_from_django_settings() <NEW_LINE> return tracker.backends
Test if backends are initialized properly from Django settings.
625990712c8b7c6e89bd50c3
class NotCorrectTileError(Exception): <NEW_LINE> <INDENT> pass
Used to indicate that a tile is not the type of tile expected
62599071435de62698e9d6e2
class _Feature(object): <NEW_LINE> <INDENT> _type = None <NEW_LINE> _coordinates = () <NEW_LINE> @property <NEW_LINE> def __geo_interface__(self): <NEW_LINE> <INDENT> return { 'type': self._type, 'coordinates': tuple(self._coordinates) } <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.to_wkt() <NEW_LINE> <DEDENT> @property <NEW_LINE> def wkt(self): <NEW_LINE> <INDENT> return self.to_wkt() <NEW_LINE> <DEDENT> def to_wkt(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def geom_type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @property <NEW_LINE> def bounds(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base class
62599071e1aae11d1e7cf47b
class OpenApiDocument(Document): <NEW_LINE> <INDENT> def __init__(self, version, url=None, title=None, description=None, media_type=None, content=None): <NEW_LINE> <INDENT> super(OpenApiDocument, self).__init__( url=url, title=title, description=description, media_type=media_type, content=content ) <NEW_LINE> self._version = version <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return self._version
OpenAPI-compliant document provides: - Versioning information
62599071796e427e53850054
class gui: <NEW_LINE> <INDENT> label = 'Gui' <NEW_LINE> stock_id = 'gtk-new' <NEW_LINE> __order__ = ['uses', 'location'] <NEW_LINE> class uses: <NEW_LINE> <INDENT> rtype = types.boolean <NEW_LINE> label = 'Uses Gui' <NEW_LINE> default = True <NEW_LINE> <DEDENT> class location: <NEW_LINE> <INDENT> label = 'File location' <NEW_LINE> rtype = types.directory <NEW_LINE> sensitive_attr = 'gui__uses' <NEW_LINE> default = '/'
Options relating to graphical user interfaces
625990713539df3088ecdb72
class Deck(object): <NEW_LINE> <INDENT> def __init__(self, n_decks=1): <NEW_LINE> <INDENT> simple_cards = list(itertools.product(RANKS, SUITS)) <NEW_LINE> self.cards = [Card(*tuple) for tuple in simple_cards] * n_decks <NEW_LINE> self.shuffle() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' '.join([str(card) for card in self.cards]) if self.cards else 'empty Deck' <NEW_LINE> <DEDENT> def shuffle(self): <NEW_LINE> <INDENT> random.shuffle(self.cards) <NEW_LINE> <DEDENT> def draw_cards(self, n_cards=1): <NEW_LINE> <INDENT> return [self.cards.pop() for _ in range(n_cards)] <NEW_LINE> <DEDENT> def cards_left(self): <NEW_LINE> <INDENT> return len(self.cards)
One or multiple decks of playing cards
62599071cc0a2c111447c73f
class RHContributionACLMessage(RHManageContributionBase): <NEW_LINE> <INDENT> def _process(self): <NEW_LINE> <INDENT> mode = ProtectionMode[request.args['mode']] <NEW_LINE> return jsonify_template('forms/protection_field_acl_message.html', object=self.contrib, mode=mode, endpoint='contributions.acl')
Render the inheriting ACL message
62599071be8e80087fbc096c
@attrs.define(kw_only=True) <NEW_LINE> class CharacterScopedArtifact: <NEW_LINE> <INDENT> hash: int <NEW_LINE> points_used: int <NEW_LINE> reset_count: int <NEW_LINE> tiers: colelctions.Sequence[ArtifactTier]
Represetns per-character artifact data.
62599071d486a94d0ba2d89b
class SklearnWrapper(BaseBiclusteringAlgorithm, metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, constructor, **kwargs): <NEW_LINE> <INDENT> self.wrapped_algorithm = constructor(**kwargs) <NEW_LINE> <DEDENT> def run(self, data): <NEW_LINE> <INDENT> self.wrapped_algorithm.fit(data) <NEW_LINE> biclusters = [] <NEW_LINE> for rows, cols in zip(*self.wrapped_algorithm.biclusters_): <NEW_LINE> <INDENT> b = self._get_bicluster(rows, cols) <NEW_LINE> biclusters.append(b) <NEW_LINE> <DEDENT> return Biclustering(biclusters) <NEW_LINE> <DEDENT> def _get_bicluster(self, rows, cols): <NEW_LINE> <INDENT> return Bicluster(rows, cols)
This class defines the skeleton of a wrapper for the scikit-learn package.
625990714e4d562566373ce3
class CI(RegistroDecomp): <NEW_LINE> <INDENT> mnemonico = "CI" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__(CI.mnemonico, True) <NEW_LINE> self._dados = [ 0, 0, "", 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] <NEW_LINE> <DEDENT> def le(self): <NEW_LINE> <INDENT> reg_contrato = RegistroIn(3) <NEW_LINE> reg_subsis = RegistroIn(2) <NEW_LINE> reg_nome = RegistroAn(10) <NEW_LINE> reg_estagio = RegistroIn(2) <NEW_LINE> reg_limite = RegistroFn(5) <NEW_LINE> reg_custo = RegistroFn(10) <NEW_LINE> reg_fator = RegistroFn(5) <NEW_LINE> self._dados[0] = reg_contrato.le_registro(self._linha, 4) <NEW_LINE> self._dados[1] = reg_subsis.le_registro(self._linha, 8) <NEW_LINE> self._dados[2] = reg_nome.le_registro(self._linha, 11) <NEW_LINE> self._dados[3] = reg_estagio.le_registro(self._linha, 24) <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> self._dados[4 + i * 3] = reg_limite.le_registro( self._linha, 29 + i * 20 ) <NEW_LINE> self._dados[5 + i * 3] = reg_limite.le_registro( self._linha, 34 + i * 20 ) <NEW_LINE> self._dados[6 + i * 3] = reg_custo.le_registro( self._linha, 39 + i * 20 ) <NEW_LINE> <DEDENT> if self._linha[89:94].strip().isnumeric(): <NEW_LINE> <INDENT> self._dados[13] = reg_fator.le_registro(self._linha, 89) <NEW_LINE> <DEDENT> <DEDENT> def escreve(self, arq: IO): <NEW_LINE> <INDENT> linha = ( f"{CI.mnemonico}".ljust(4) + f"{self._dados[0]}".zfill(3) + " " + f"{self._dados[1]}".rjust(2) + " " + f"{self._dados[2]}".ljust(10) + " " + f"{self._dados[3]}".rjust(2) + " " ) <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> linha += f"{round(self._dados[4 + i * 3], 1)}".rjust(5) <NEW_LINE> linha += f"{round(self._dados[5 + i * 3], 1)}".rjust(5) <NEW_LINE> linha += f"{round(self._dados[6 + i * 3], 2)}".rjust(10) <NEW_LINE> <DEDENT> if self._dados[13] != 0.0: <NEW_LINE> <INDENT> linha += f"{round(self._dados[13], 2)}".rjust(5) <NEW_LINE> <DEDENT> linha += "\n" <NEW_LINE> arq.write(linha)
Registro que define contratos de importação de energia.
62599071e76e3b2f99fda2df
class UserManager(UserManager): <NEW_LINE> <INDENT> def _create_user(self, first_name, last_name, password, is_staff, is_superuser, **extra_fields): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> user = self.model(first_name=first_name, last_name=last_name, is_staff=is_staff, is_superuser=is_superuser, is_active=True, last_login=now, **extra_fields) <NEW_LINE> if password is not None: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> <DEDENT> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_user(self, first_name, last_name, password, **extra_fields): <NEW_LINE> <INDENT> return self._create_user(first_name, last_name, password, False, False, **extra_fields) <NEW_LINE> <DEDENT> def create_superuser(self, first_name, last_name, password, **extra_fields): <NEW_LINE> <INDENT> return self._create_user(first_name, last_name, password, True, True, **extra_fields) <NEW_LINE> <DEDENT> def check_user(self, number): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return User.objects.get(mobile_number=number) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def make_user_inactive(self, user): <NEW_LINE> <INDENT> user.is_active = False <NEW_LINE> user.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> def remove_user_from_pool(self, user): <NEW_LINE> <INDENT> user.admin_of_pools.clear() <NEW_LINE> user.member_of_pools.clear()
- Custom Manager for the User Model
6259907156b00c62f0fb41ac
class HelloApiView(APIView): <NEW_LINE> <INDENT> serializer_class = serializers.HelloSerializer <NEW_LINE> def get(self,request,format=None): <NEW_LINE> <INDENT> an_apiview =[ 'Uses http methods as functions (get,post,put,patch,delete)', 'It is similar to a traditional django view' 'Gives you the most control over your logic', 'Is mapped manually to urls' ] <NEW_LINE> return Response({'message':'Hello!','an_apiview':an_apiview}) <NEW_LINE> <DEDENT> def post(get,request): <NEW_LINE> <INDENT> serializer = serializers.HelloSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.data.get('name') <NEW_LINE> message = 'hello {0}'.format(name) <NEW_LINE> return Response({'message':message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors,status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def put(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'put'}) <NEW_LINE> <DEDENT> def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'patch'}) <NEW_LINE> <DEDENT> def delete(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'delete'})
Test API view
6259907132920d7e50bc7924
class FieldsFromTextFile(PipelineAction): <NEW_LINE> <INDENT> def __init__(self, output): <NEW_LINE> <INDENT> PipelineAction.__init__(self, 'FieldsFromTextFile', output) <NEW_LINE> <DEDENT> def _execute(self, ifiles, pipeline=None): <NEW_LINE> <INDENT> if len(ifiles) > 1: <NEW_LINE> <INDENT> env.logger.warning( 'Only the format of the first input file would be outputted.') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if ifiles[0].endswith('.vcf') or ifiles[0].endswith('.vcf.gz'): <NEW_LINE> <INDENT> showTrack(ifiles[0], self.output[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with open(self.output[0], 'w') as fo: <NEW_LINE> <INDENT> csv_dialect = csv.Sniffer().sniff( open(ifiles[0], 'rU').read(8192)) <NEW_LINE> fo.write('delimiter="{}"\n\n'.format( csv_dialect.delimiter.replace('\t', r'\t'))) <NEW_LINE> values = [] <NEW_LINE> with open(ifiles[0], 'rU') as fi: <NEW_LINE> <INDENT> reader = csv.reader(fi, dialect=csv_dialect) <NEW_LINE> headers = reader.next() <NEW_LINE> values = [[] for x in headers] <NEW_LINE> for line in reader: <NEW_LINE> <INDENT> for idx in range(len(headers)): <NEW_LINE> <INDENT> values[idx].append(line[idx]) <NEW_LINE> <DEDENT> if len(values[0]) > 100: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for idx, header in enumerate(headers): <NEW_LINE> <INDENT> fo.write('[{}]\n'.format(validFieldName(header))) <NEW_LINE> fo.write('index={}\n'.format(idx + 1)) <NEW_LINE> fo.write('type={}\n\n'.format( typeOfValues(values[idx]))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise RuntimeError('Failed to guess fields from {}: {}'.format( ifiles[0], e)) <NEW_LINE> <DEDENT> return True
Read a text file, guess its delimeter, field name (from header) and create field descriptions. If a vcf file is encountered, all fields will be exported. File Flow: extract format of input and output format. INPUT ==> Get Format ==> OUTPUT Raises: Raise a RuntimeError if this action failed to guess format (fields) from the input file. Examples: action=FieldsFromTextFile('format.txt')
62599071f548e778e596ce6b
class EventTime: <NEW_LINE> <INDENT> def __init__(self,year, daqTime): <NEW_LINE> <INDENT> self.year = year <NEW_LINE> self.daqTime = daqTime <NEW_LINE> dtpair = self._make_datetime_pair() <NEW_LINE> self.dateTime = dtpair[0] <NEW_LINE> self.utcTenthNanoSecond = dtpair[1] <NEW_LINE> <DEDENT> def _make_datetime_pair(self): <NEW_LINE> <INDENT> if (sys.version_info < (3, 0)): <NEW_LINE> <INDENT> microsec = long(self.daqTime * 10**-4) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> microsec = int(self.daqTime * 10**-4) <NEW_LINE> <DEDENT> utcTenthNanoSecond = self.daqTime % 10000 <NEW_LINE> dt = timedelta(microseconds = microsec) <NEW_LINE> dateTime = datetime(year = self.year, month = 1, day = 1) + dt <NEW_LINE> return (dateTime,utcTenthNanoSecond) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> date_str = "" <NEW_LINE> dateTime,tenthns = self._make_datetime_pair() <NEW_LINE> if dateTime.microsecond == 0. : <NEW_LINE> <INDENT> date_str = "%s.%010d" % (str(dateTime),tenthns) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> date_str = "%s%d" % (str(dateTime),tenthns) <NEW_LINE> <DEDENT> return date_str
The EventTime class. The purpose of this class is to translate IceCube time, which constist of the year and tenths of nanoseconds since the beginning of the year, to a format that is more user-friendly. This class uses python's datetime module. @todo: Implement math operations. @todo: Clean up the interface so the tenths of nanoseconds and datetime is more unified and integrated.
6259907176e4537e8c3f0e5c
class BuildSequence(BuildSteps): <NEW_LINE> <INDENT> def run(self, *args, **kwargs): <NEW_LINE> <INDENT> logger.info('running jobs in a build sequence.') <NEW_LINE> for job in self.stage: <NEW_LINE> <INDENT> logger.info('running {0}'.format(job[0].__name__)) <NEW_LINE> job[0](*job[1]) <NEW_LINE> <DEDENT> return True
A subclass of :class:~stages.BuildSteps` that executes jobs in the order they were added to the :class:~stages.BuildSteps` object. :returns: ``True`` upon completion.
62599071aad79263cf430093
class Model(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.product_set = set() <NEW_LINE> <DEDENT> @property <NEW_LINE> def products(self): <NEW_LINE> <INDENT> return list(self.product_set) <NEW_LINE> <DEDENT> @property <NEW_LINE> def variables(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def required_variables(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def eval(self, dataset, variables=None, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError
Base model source class.
625990711b99ca40022901a4
class UserViewSet(ViewSetModelMixin, viewsets.ViewSet): <NEW_LINE> <INDENT> serializer_class = UserSerializer
User profiles CRUD operations
6259907167a9b606de547712
class TokenAuthBackend(BasicAuthBackend): <NEW_LINE> <INDENT> def __init__(self, user_loader, auth_header_prefix='Token'): <NEW_LINE> <INDENT> super(TokenAuthBackend, self).__init__(user_loader, auth_header_prefix) <NEW_LINE> <DEDENT> def _extract_credentials(self, req): <NEW_LINE> <INDENT> auth = req.get_header('Authorization') <NEW_LINE> return self.parse_auth_token_from_request(auth_header=auth) <NEW_LINE> <DEDENT> def authenticate(self, req, resp, resource): <NEW_LINE> <INDENT> token = self._extract_credentials(req) <NEW_LINE> return { 'user': self.load_user(req, resp, resource, token), } <NEW_LINE> <DEDENT> def get_auth_token(self, user_payload): <NEW_LINE> <INDENT> token = user_payload.get('token') or None <NEW_LINE> if not token: <NEW_LINE> <INDENT> raise ValueError('`user_payload` must provide api token') <NEW_LINE> <DEDENT> return '{auth_header_prefix} {token}'.format( auth_header_prefix=self.auth_header_prefix, token=token)
Implements Simple Token Based Authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a Args: user_loader(function, required): A callback function that is called with the token extracted from the `Authorization` header. Returns an `authenticated user` if user exists matching the credentials or return `None` to indicate if no user found or credentials mismatch. auth_header_prefix(string, optional): A prefix that is used with the token in the `Authorization` header. Default is ``basic``
62599071baa26c4b54d50b89
@Packet(type='request') <NEW_LINE> class PacketQueryUser(NamedTuple): <NEW_LINE> <INDENT> user: str <NEW_LINE> query_password_hash: bool <NEW_LINE> def handle(self, conn: Connection) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pw = getpwnam(self.user) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gid = int(self.user) <NEW_LINE> pw = getpwuid(gid) <NEW_LINE> <DEDENT> except (KeyError, ValueError): <NEW_LINE> <INDENT> conn.write_packet(PacketInvalidField("user", "The user does not exist")) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> pw_hash: Optional[str] = None <NEW_LINE> if self.query_password_hash: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pw_hash = getspnam(pw.pw_name).sp_pwdp <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> conn.write_packet(PacketInvalidField("user", "The user has no shadow entry, or it is inaccessible.")) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> groups = [g.gr_name for g in getgrall() if pw.pw_name in g.gr_mem] <NEW_LINE> try: <NEW_LINE> <INDENT> conn.write_packet(PacketUserEntry( name=pw.pw_name, uid=i64(pw.pw_uid), group=getgrgid(pw.pw_gid).gr_name, gid=i64(pw.pw_gid), groups=groups, password_hash=pw_hash, gecos=pw.pw_gecos, home=pw.pw_dir, shell=pw.pw_shell)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> conn.write_packet(PacketInvalidField("user", "The user's primary group doesn't exist")) <NEW_LINE> return
This packet is used to get information about a group via pwd.getpw*.
625990719c8ee82313040df6
@plugins.register <NEW_LINE> class AtmosphericTidesComParser(LineParser): <NEW_LINE> <INDENT> def setup_parser(self): <NEW_LINE> <INDENT> return dict(comments="#", names=("xyz", "A1", "B1", "A2", "B2"), dtype=("U2", "f8", "f8", "f8", "f8"))
A parser for reading coefficents for atmospheric tides center of mass corrections
6259907197e22403b383c7e1
class ValueTypeNotDefinedError(FeatureError): <NEW_LINE> <INDENT> pass
Exception raised when a feature value's type isn't defined.
6259907199cbb53fe68327c7
class Action16(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> raise NotImplementedError('%s not implemented' % ( str(self)))
Set Transparency->Toggle Parameters: 0: ((unknown 25022))
625990712ae34c7f260ac9c8
class AsciiMap(object): <NEW_LINE> <INDENT> def __init__(self, lattice=None): <NEW_LINE> <INDENT> self.lattice = lattice or {} <NEW_LINE> <DEDENT> def readMap(self, text): <NEW_LINE> <INDENT> self.lattice = {} <NEW_LINE> for row, line in enumerate(reversed(text.strip().splitlines())): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> base = self._getRowBase(row) <NEW_LINE> for col, char in enumerate(line.split()): <NEW_LINE> <INDENT> i, j = self._getIndices(base, col) <NEW_LINE> self.lattice[i, j] = char <NEW_LINE> <DEDENT> <DEDENT> self.lattice = {k: v for k, v in self.lattice.items() if v != PLACEHOLDER} <NEW_LINE> return self.lattice <NEW_LINE> <DEDENT> def writeMap(self, stream): <NEW_LINE> <INDENT> colI, rowJ = zip(*sorted(self.lattice.keys(), key=lambda ij: ([ij[1], ij[0]]))) <NEW_LINE> line = [] <NEW_LINE> for i, j in zip(colI, reversed(rowJ)): <NEW_LINE> <INDENT> if line and i == 0: <NEW_LINE> <INDENT> stream.write(" ".join(line) + "\n") <NEW_LINE> line = [] <NEW_LINE> <DEDENT> line.append(f"{self.lattice.get((i,j), PLACEHOLDER)}") <NEW_LINE> <DEDENT> stream.write(" ".join(line) + "\n") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _getRowBase(row): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _getIndices(base, col): <NEW_LINE> <INDENT> raise NotImplementedError()
Base class for maps. These should be able to read and write ASCII maps.
625990717b180e01f3e49cd3
class VersionInfo(tuple): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _fields = ('major', 'minor', 'micro', 'modifier') <NEW_LINE> def __new__(cls, major, minor=0, micro=0, modifier='release'): <NEW_LINE> <INDENT> assert isinstance(major, int) <NEW_LINE> assert isinstance(minor, int) <NEW_LINE> assert isinstance(micro, int) <NEW_LINE> assert isinstance(modifier, str) <NEW_LINE> return tuple.__new__(cls, (major, minor, micro, modifier)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'VersionInfo(major=%r, minor=%r, micro=%r, modifier=%r)' % self <NEW_LINE> <DEDENT> def _asdict(self): <NEW_LINE> <INDENT> from combi._python_toolbox.nifty_collections import OrderedDict <NEW_LINE> return OrderedDict(zip(self._fields, self)) <NEW_LINE> <DEDENT> def __getnewargs__(self): <NEW_LINE> <INDENT> return tuple(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def version_text(self): <NEW_LINE> <INDENT> version_text = '%s.%s.%s' % (self.major, self.minor, self.micro) <NEW_LINE> if self.modifier != 'release': <NEW_LINE> <INDENT> version_text += ' %s' % self.modifier <NEW_LINE> <DEDENT> return version_text <NEW_LINE> <DEDENT> major = property(_itemgetter(0)) <NEW_LINE> minor = property(_itemgetter(1)) <NEW_LINE> micro = property(_itemgetter(2)) <NEW_LINE> modifier = property(_itemgetter(3))
Version number. This is a variation on a `namedtuple`. Example: VersionInfo(1, 2, 0) == VersionInfo(major=1, minor=2, micro=0, modifier='release') == (1, 2, 0)
6259907244b2445a339b75cd
class BaseProductImage(models.Model, metaclass=deferred.ForeignKeyBuilder): <NEW_LINE> <INDENT> image = image.FilerImageField(on_delete=models.CASCADE) <NEW_LINE> product = deferred.ForeignKey( BaseProduct, on_delete=models.CASCADE, ) <NEW_LINE> order = models.SmallIntegerField(default=0) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> verbose_name = _("Product Image") <NEW_LINE> verbose_name_plural = _("Product Images") <NEW_LINE> ordering = ['order']
ManyToMany relation from the polymorphic Product to a set of images.
6259907256ac1b37e6303951
class createChat_args(object): <NEW_LINE> <INDENT> def __init__(self, request=None,): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.request = CreateChatRequest() <NEW_LINE> self.request.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('createChat_args') <NEW_LINE> if self.request is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('request', TType.STRUCT, 1) <NEW_LINE> self.request.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - request
6259907260cbc95b063659dd
class Consumer(object): <NEW_LINE> <INDENT> def __init__(self, key, secret, callback_uri=None): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.secret = secret <NEW_LINE> self.callback_uri = callback_uri
Represents a client key, or a record of credentials for API access. Public instance variables: key -- The API client key secret -- The API client secret callback_uri -- (optional) The URI to the callback for the application, to which the end user will be redirected to once they have granted the application access to their data.
6259907223849d37ff852995
class Revolve(Srf): <NEW_LINE> <INDENT> def __init__(self, curve, pnt=(0., 0., 0.), vector=(1., 0., 0.), theta=2.*math.pi): <NEW_LINE> <INDENT> if not isinstance(curve, crv.Crv): <NEW_LINE> <INDENT> raise NURBSError('Input curve not derived from Crv class!') <NEW_LINE> <DEDENT> T = translate(-np.asarray(pnt, np.float)) <NEW_LINE> vector = np.asarray(vector, np.float) <NEW_LINE> len_ = np.sqrt(np.add.reduce(vector*vector)) <NEW_LINE> if len_ == 0: <NEW_LINE> <INDENT> raise ZeroDivisionError("Can't normalize a zero-length vector") <NEW_LINE> <DEDENT> vector = vector/len_ <NEW_LINE> if vector[0] == 0.: <NEW_LINE> <INDENT> angx = 0. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> angx = math.atan2(vector[0], vector[2]) <NEW_LINE> <DEDENT> RY = roty(-angx) <NEW_LINE> vectmp = np.ones((4,), np.float) <NEW_LINE> vectmp[0:3] = vector <NEW_LINE> vectmp = np.dot(RY, vectmp) <NEW_LINE> if vectmp[1] == 0.: <NEW_LINE> <INDENT> angy = 0. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> angy = math.atan2(vector[1], vector[2]) <NEW_LINE> <DEDENT> RX = rotx(angy) <NEW_LINE> curve.trans(np.dot(RX, np.dot(RY, T))) <NEW_LINE> arc = crv.Arc(1., [0., 0., 0.], 0., theta) <NEW_LINE> narc = arc.cntrl.shape[1] <NEW_LINE> ncrv = curve.cntrl.shape[1] <NEW_LINE> coefs = np.zeros((4, narc, ncrv), np.float) <NEW_LINE> angle = np.arctan2(curve.cntrl[1,:], curve.cntrl[0,:]) <NEW_LINE> vectmp = curve.cntrl[0:2,:] <NEW_LINE> radius = np.sqrt(np.add.reduce(vectmp*vectmp)) <NEW_LINE> for i in range(0, ncrv): <NEW_LINE> <INDENT> coefs[:,:,i] = np.dot(rotz(angle[i]), np.dot(translate((0., 0., curve.cntrl[2,i])), np.dot(scale((radius[i], radius[i])), arc.cntrl))) <NEW_LINE> coefs[3,:,i] = coefs[3,:,i] * curve.cntrl[3,i] <NEW_LINE> <DEDENT> super().__init__(self, coefs, arc.uknots, curve.uknots) <NEW_LINE> T = translate(pnt) <NEW_LINE> RX = rotx(-angy) <NEW_LINE> RY = roty(angx) <NEW_LINE> self.trans(np.dot(T, np.dot(RY, RX)))
Construct a surface by revolving the profile curve around an axis defined by a point and a unit vector. srf = nrbrevolve(curve,point,vector[,theta]) INPUT: curve - NURB profile curve. pnt - coordinate of the point. (default: [0, 0, 0]) vector - rotation axis. (default: [1, 0, 0]) theta - angle to revolve curve (default: 2*pi).
625990724e4d562566373ce5
class Share(models.Model): <NEW_LINE> <INDENT> shared_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='problem_builder_shared_by') <NEW_LINE> submission_uid = models.CharField(max_length=32) <NEW_LINE> block_id = models.CharField(max_length=255, db_index=True) <NEW_LINE> shared_with = models.ForeignKey(User, on_delete=models.CASCADE, related_name='problem_builder_shared_with') <NEW_LINE> notified = models.BooleanField(default=False, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'problem_builder' <NEW_LINE> unique_together = (('shared_by', 'shared_with', 'block_id'),)
The XBlock User Service does not permit XBlocks instantiated with non-staff users to query for arbitrary anonymous user IDs. In order to make sharing work, we have to store them here.
625990724f88993c371f1190
class NPointMessyCrossoverOperator(CrossoverOperator): <NEW_LINE> <INDENT> def __init__(self, points=2): <NEW_LINE> <INDENT> self._points = int(points) <NEW_LINE> <DEDENT> @property <NEW_LINE> def points(self): <NEW_LINE> <INDENT> return self._points <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_total_weight(parent_weight_map, include=None): <NEW_LINE> <INDENT> if include is None: <NEW_LINE> <INDENT> include = parent_weight_map <NEW_LINE> <DEDENT> return float(sum(parent_weight_map[parent] for parent in include)) <NEW_LINE> <DEDENT> def select_parents(self, candidates, parent_weight_map, total_weight=None): <NEW_LINE> <INDENT> if total_weight is None: <NEW_LINE> <INDENT> total_weight = self.get_total_weight(parent_weight_map, candidates) <NEW_LINE> <DEDENT> selected_parents = [] <NEW_LINE> while len(selected_parents) <= self._points: <NEW_LINE> <INDENT> selected_parents.append( select_proportionately(parent_weight_map, total_weight) ) <NEW_LINE> <DEDENT> return selected_parents <NEW_LINE> <DEDENT> def determine_crossover_points(self, selected_parents, chromosome_id): <NEW_LINE> <INDENT> points = {} <NEW_LINE> for parent in selected_parents: <NEW_LINE> <INDENT> points[parent] = sorted( random.randint(0, len(parent.get_chromosome(chromosome_id))) for _ in range(self._points) ) <NEW_LINE> <DEDENT> return points <NEW_LINE> <DEDENT> def perform_crossover(self, selected_parents, points, chromosome_id): <NEW_LINE> <INDENT> child_codons = () <NEW_LINE> start = 0 <NEW_LINE> for index in range(self._points): <NEW_LINE> <INDENT> parent = selected_parents[index] <NEW_LINE> end = points[parent][index] <NEW_LINE> child_codons += parent.get_chromosome(chromosome_id).codons[start:end] <NEW_LINE> start = end <NEW_LINE> <DEDENT> parent = selected_parents[-1] <NEW_LINE> child_codons += parent.get_chromosome(chromosome_id).codons[end:] <NEW_LINE> return Chromosome(child_codons) <NEW_LINE> <DEDENT> def new_chromosome(self, chromosome_id, parent_weight_map, total_weight=None): <NEW_LINE> <INDENT> if total_weight is None: <NEW_LINE> <INDENT> total_weight = self.get_total_weight(parent_weight_map) <NEW_LINE> <DEDENT> parents_with_chromosome = [ parent for parent in parent_weight_map if parent.has_chromosome_id(chromosome_id) ] <NEW_LINE> total_included_weight = self.get_total_weight( parent_weight_map, parents_with_chromosome ) <NEW_LINE> if random.uniform(0.0, total_weight) >= total_included_weight: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> selected_parents = self.select_parents( parents_with_chromosome, parent_weight_map, total_included_weight ) <NEW_LINE> points = self.determine_crossover_points( selected_parents, chromosome_id ) <NEW_LINE> return self.perform_crossover( selected_parents, points, chromosome_id ) <NEW_LINE> <DEDENT> def __call__(self, parent_weight_map): <NEW_LINE> <INDENT> if not isinstance(parent_weight_map, dict): <NEW_LINE> <INDENT> parent_weight_map = dict(parent_weight_map) <NEW_LINE> <DEDENT> total_weight = self.get_total_weight(parent_weight_map) <NEW_LINE> chromosome_ids = set() <NEW_LINE> for parent in parent_weight_map: <NEW_LINE> <INDENT> chromosome_ids |= set(parent.iter_chromosom_ids()) <NEW_LINE> <DEDENT> child_chromosomes = {} <NEW_LINE> for chromosome_id in chromosome_ids: <NEW_LINE> <INDENT> chromosome = self.new_chromosome( chromosome_id, parent_weight_map, total_weight ) <NEW_LINE> if chromosome is not None: <NEW_LINE> <INDENT> child_chromosomes[chromosome_id] = chromosome <NEW_LINE> <DEDENT> <DEDENT> return (Genotype(child_chromosomes),)
N-point variable-length crossover.
6259907276e4537e8c3f0e5e
class SupportsQasmWithArgsAndQubits(Protocol): <NEW_LINE> <INDENT> def _qasm_(self, qubits: Tuple['cirq.Qid'], args: QasmArgs) -> Union[None, NotImplementedType, str]: <NEW_LINE> <INDENT> pass
An object that can be turned into QASM code if it knows its qubits. Returning `NotImplemented` or `None` means "don't know how to turn into QASM". In that case fallbacks based on decomposition and known unitaries will be used instead.
6259907216aa5153ce401db8
class Taxi(Car): <NEW_LINE> <INDENT> def __init__(self, name, fuel, price_per_km): <NEW_LINE> <INDENT> super().__init__(name, fuel) <NEW_LINE> self.price_per_km = price_per_km <NEW_LINE> self.current_fare_distance = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{}, {}km on current fare, ${:.2f}/km".format(super().__str__(), self.current_fare_distance, self.price_per_km) <NEW_LINE> <DEDENT> def get_fare(self): <NEW_LINE> <INDENT> return self.price_per_km * self.current_fare_distance <NEW_LINE> <DEDENT> def start_fare(self): <NEW_LINE> <INDENT> self.current_fare_distance = 0 <NEW_LINE> <DEDENT> def drive(self, distance): <NEW_LINE> <INDENT> distance_driven = super().drive(distance) <NEW_LINE> self.current_fare_distance += distance_driven <NEW_LINE> return distance_driven
Specialised version of a Car that includes fare costs.
6259907266673b3332c31cde
class SingleCycleLinkList(object): <NEW_LINE> <INDENT> def __init__(self, node=None): <NEW_LINE> <INDENT> self.__head = node <NEW_LINE> if node: <NEW_LINE> <INDENT> node.next = node <NEW_LINE> <DEDENT> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self.__head is None <NEW_LINE> <DEDENT> def length(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return 0; <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> count = 1 <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> return count <NEW_LINE> <DEDENT> def travel(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> print(cur.elem, end=" ") <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> print(cur.elem) <NEW_LINE> <DEDENT> def add(self, item): <NEW_LINE> <INDENT> node = SingleNode(item) <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> self.__head = node <NEW_LINE> node.next = node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur = self.__head <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> node.next = self.__head <NEW_LINE> self.__head = node <NEW_LINE> cur.next = node <NEW_LINE> <DEDENT> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> node = SingleNode(item) <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> self.__head = node <NEW_LINE> node.next = node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur = self.__head <NEW_LINE> while cur.next is not None: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> node.next = self.__head <NEW_LINE> cur.next = node <NEW_LINE> <DEDENT> <DEDENT> def insert(self, pos, item): <NEW_LINE> <INDENT> if pos <= 0: <NEW_LINE> <INDENT> self.add(item) <NEW_LINE> <DEDENT> elif pos >= (self.length()): <NEW_LINE> <INDENT> self.append(item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> pre = self.__head <NEW_LINE> while count < (pos-1): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> pre = pre.next <NEW_LINE> <DEDENT> node = SingleNode(item) <NEW_LINE> node.next = pre.next <NEW_LINE> pre.next = node <NEW_LINE> <DEDENT> <DEDENT> def remove(self, item): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> pre = None <NEW_LINE> while cur.next != self.__head: <NEW_LINE> <INDENT> if cur.elem == item: <NEW_LINE> <INDENT> if cur == self.__head: <NEW_LINE> <INDENT> rear = self.__head <NEW_LINE> while rear.next != self.__head: <NEW_LINE> <INDENT> rear = rear.next <NEW_LINE> <DEDENT> self.__head = cur.next <NEW_LINE> rear.next = self.__head <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre.next = cur.next <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre = cur <NEW_LINE> cur = cur.next <NEW_LINE> <DEDENT> <DEDENT> if cur.elem == item: <NEW_LINE> <INDENT> if cur == self.__head: <NEW_LINE> <INDENT> self.__head = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pre.next = cur.next <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def search(self, item): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> cur = self.__head <NEW_LINE> while cur != self.__head: <NEW_LINE> <INDENT> if cur.elem == item: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> <DEDENT> if cur.elem == item: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
单向循环链表功能的实现
625990727d847024c075dcb8
class classifyLinesOperation(abstractFilterOperation): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def apply(self, img, paramDict): <NEW_LINE> <INDENT> horizontal = [paramDict['h' + str(i)] for i in (1,2,3,4)] <NEW_LINE> verticals = [paramDict['v' + str(i)] for i in (1,2,3,4)] <NEW_LINE> height, width = img.shape[0], img.shape[1] <NEW_LINE> h1,h2,h3,h4 = [int(h/1000.0 * (height-1)) for h in horizontal] <NEW_LINE> v1,v2,v3,v4 = [int(v/1000.0 * (width-1) ) for v in verticals ] <NEW_LINE> labels_rows = [] <NEW_LINE> labels_columns = [] <NEW_LINE> for row in range(img.shape[0]): <NEW_LINE> <INDENT> labels_rows.append(1.0 if (((row <= h2) and (row >= h1)) or ((row <= h4) and (row >= h3))) else 0.0) <NEW_LINE> <DEDENT> for col in range(img.shape[1]): <NEW_LINE> <INDENT> labels_columns.append(1.0 if (((col <= v2) and (col >= v1)) or ((col <= v4) and (col >= v3))) else 0.0) <NEW_LINE> <DEDENT> return labels_rows, labels_columns
Classify rows and columns as one or zero. One stands for 'yes there is a mouse in this line', zero stands for 'there is no mouse in this line'. The return type is a list containing two lists. The first with the classification of the rows and the second with classification of columns. Naturaly, the size of the first list should be img.shape[0] and the size of the second img.shape[0]. A line is split by 4 points l1,l2,l3 and l4. If a point x in the line is between l1 and l2(inclusive) or(inclisve or) between l3 and l4(inclusive) then x is of class one, else it is class zero.
6259907267a9b606de547713
class XMLEncoder(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.bits = list() <NEW_LINE> <DEDENT> def encode(self, data, wrapper=None): <NEW_LINE> <INDENT> if wrapper: <NEW_LINE> <INDENT> self.bits.append('<%s>' % wrapper) <NEW_LINE> <DEDENT> self.toxml(data) <NEW_LINE> if wrapper: <NEW_LINE> <INDENT> self.bits.append('</%s>' % wrapper) <NEW_LINE> <DEDENT> return str(''.join(self.bits)) <NEW_LINE> <DEDENT> def toxml(self, data): <NEW_LINE> <INDENT> if hasattr(data, 'getPublicFeed'): self._encodefeed(data) <NEW_LINE> elif isinstance(data, (list, tuple)): self._encodelist(data) <NEW_LINE> elif isinstance(data, (dict,)): self._encodedict(data) <NEW_LINE> else: self._encodedata(data) <NEW_LINE> <DEDENT> def _encodelist(self, data): <NEW_LINE> <INDENT> if all(isinstance(x, (int,str)) for x in data): <NEW_LINE> <INDENT> self.bits.append(escape(','.join(map(str, data)))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for v in data: <NEW_LINE> <INDENT> self.toxml(v) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _encodedict(self, data): <NEW_LINE> <INDENT> tag = data.get('_type', None) <NEW_LINE> if tag: <NEW_LINE> <INDENT> self.bits.append('<%s>' % tag) <NEW_LINE> <DEDENT> for k,v in sorted(data.items()): <NEW_LINE> <INDENT> if len(k) > 0 and k[0] == '_': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.bits.append('<%s>' % k) <NEW_LINE> self.toxml(v) <NEW_LINE> self.bits.append('</%s>' % k) <NEW_LINE> <DEDENT> if tag: <NEW_LINE> <INDENT> self.bits.append('</%s>' % tag) <NEW_LINE> <DEDENT> <DEDENT> def _encodefeed(self, data): <NEW_LINE> <INDENT> self.bits.append('<%s>' % data.__class__.__name__) <NEW_LINE> self._encodedict(data.getPublicFeed()) <NEW_LINE> self.bits.append('</%s>' % data.__class__.__name__) <NEW_LINE> <DEDENT> def _encodedata(self, data): <NEW_LINE> <INDENT> self.bits.append(escape(str(data)))
XML in python doesn't have easy encoding or custom getter options like JSONEncoder so we do it ourselves.
62599072dd821e528d6da5f1
class Solution: <NEW_LINE> <INDENT> def isValidBST(self, root: TreeNode) -> bool: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not self.compare(root.left, root.val, True) or not self.compare(root.right, root.val, False): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.isValidBST(root.left) and self.isValidBST(root.right) <NEW_LINE> <DEDENT> def compare(self, root: TreeNode, base: int, left: bool) -> bool: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if left and base <= root.val: <NEW_LINE> <INDENT> print('%s,%s,%s' % (left, base, root.val)) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not left and base >= root.val: <NEW_LINE> <INDENT> print('%s,%s,%s' % (left, base, root.val)) <NEW_LINE> return False <NEW_LINE> <DEDENT> return self.compare(root.left, base, left) and self.compare(root.right, base, left)
cost: 180ms >5.03 https://leetcode.com/submissions/detail/212553748/
62599072627d3e7fe0e08767
class Trip: <NEW_LINE> <INDENT> VIEW = "view_trip" <NEW_LINE> EDIT = "change_trip" <NEW_LINE> CREATE = "add_trip" <NEW_LINE> DELETE = "delete_trip"
Trip permissions
625990722ae34c7f260ac9ca
class Post: <NEW_LINE> <INDENT> class Body(RefsBody): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class Header(Schema): <NEW_LINE> <INDENT> X_GitHub_Media_Type = fields.String(data_key='X-GitHub-Media-Type', description='You can check the current version of media type in responses.\n') <NEW_LINE> Accept = fields.String(description='Is used to set specified media type.') <NEW_LINE> X_RateLimit_Limit = fields.Integer(data_key='X-RateLimit-Limit') <NEW_LINE> X_RateLimit_Remaining = fields.Integer(data_key='X-RateLimit-Remaining') <NEW_LINE> X_RateLimit_Reset = fields.Integer(data_key='X-RateLimit-Reset') <NEW_LINE> X_GitHub_Request_Id = fields.Integer(data_key='X-GitHub-Request-Id') <NEW_LINE> <DEDENT> class Path(Schema): <NEW_LINE> <INDENT> owner = fields.String(required=True, description='Name of repository owner.') <NEW_LINE> repo = fields.String(required=True, description='Name of repository.')
Create a Reference
625990725fcc89381b266dc7
class DatestampedLogFile(BaseLogFile, object): <NEW_LINE> <INDENT> datestampFormat = DATE_FORMAT <NEW_LINE> def __init__(self, name, directory, defaultMode=None): <NEW_LINE> <INDENT> self.basePath = os.path.join(directory, name) <NEW_LINE> BaseLogFile.__init__(self, name, directory, defaultMode) <NEW_LINE> self.lastPath = self.path <NEW_LINE> <DEDENT> def _getPath(self): <NEW_LINE> <INDENT> return '%s.%s' % (self.basePath, self.suffix()) <NEW_LINE> <DEDENT> def _setPath(self, ignored): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> path = property(_getPath, _setPath) <NEW_LINE> def shouldRotate(self): <NEW_LINE> <INDENT> return self.path != self.lastPath <NEW_LINE> <DEDENT> def rotate(self): <NEW_LINE> <INDENT> self.reopen() <NEW_LINE> <DEDENT> def suffix(self, when=None): <NEW_LINE> <INDENT> if when is None: <NEW_LINE> <INDENT> when = datetime.datetime.now() <NEW_LINE> <DEDENT> return when.strftime(self.datestampFormat)
A LogFile which always logs to files suffixed with the current date. The date format used as a suffix is controlled by the `datestampFormat` attribute.
6259907263b5f9789fe86a43
class ValuesEqual(MapEqual): <NEW_LINE> <INDENT> transform = attrgetter('value')
Validates that the values of multiple elements are equal. A :class:`MapEqual` that compares the :attr:`~flatland.schema.base.Element.value` of each element. Example: .. testcode:: from flatland import Schema, String from flatland.validation import ValuesEqual class MyForm(Schema): password = String password_again = String validators = [ValuesEqual('password', 'password_again')] .. attribute:: transform() attrgetter('value')
62599072435de62698e9d6e6
class WinRMListener(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'protocol': {'key': 'protocol', 'type': 'str'}, 'certificate_url': {'key': 'certificateUrl', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, protocol: Optional[Union[str, "ProtocolTypes"]] = None, certificate_url: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(WinRMListener, self).__init__(**kwargs) <NEW_LINE> self.protocol = protocol <NEW_LINE> self.certificate_url = certificate_url
Describes Protocol and thumbprint of Windows Remote Management listener. :ivar protocol: Specifies the protocol of listener. :code:`<br>`:code:`<br>` Possible values are: :code:`<br>`\ **http** :code:`<br>`:code:`<br>` **https**. Possible values include: "Http", "Https". :vartype protocol: str or ~azure.mgmt.compute.v2017_12_01.models.ProtocolTypes :ivar certificate_url: This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, see `Add a key or secret to the key vault <https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add>`_. In this case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8: :code:`<br>`:code:`<br>` {:code:`<br>` "data":":code:`<Base64-encoded-certificate>`",:code:`<br>` "dataType":"pfx",:code:`<br>` "password":":code:`<pfx-file-password>`":code:`<br>`}. :vartype certificate_url: str
625990727b180e01f3e49cd4
class SelectButtonModeSelector(ModeSelectorComponent): <NEW_LINE> <INDENT> def __init__(self, mixer, buttons): <NEW_LINE> <INDENT> assert isinstance(mixer, MixerComponent) <NEW_LINE> assert isinstance(buttons, tuple) <NEW_LINE> assert len(buttons) == 8 <NEW_LINE> ModeSelectorComponent.__init__(self) <NEW_LINE> self._mixer = mixer <NEW_LINE> self._buttons = buttons <NEW_LINE> self._mode_display = None <NEW_LINE> self._mode_index = 0 <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self._mixer = None <NEW_LINE> self._buttons = None <NEW_LINE> self._mode_display = None <NEW_LINE> <DEDENT> def set_mode_display(self, display): <NEW_LINE> <INDENT> assert isinstance(display, PhysicalDisplayElement) <NEW_LINE> self._mode_display = display <NEW_LINE> <DEDENT> def number_of_modes(self): <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> super(SelectButtonModeSelector, self).update() <NEW_LINE> if self.is_enabled(): <NEW_LINE> <INDENT> for index in range(len(self._buttons)): <NEW_LINE> <INDENT> if self._mode_index == 0: <NEW_LINE> <INDENT> self._mixer.channel_strip(index).set_select_button(self._buttons[index]) <NEW_LINE> self._mixer.channel_strip(index).set_arm_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_mute_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_solo_button(None) <NEW_LINE> <DEDENT> elif self._mode_index == 1: <NEW_LINE> <INDENT> self._mixer.channel_strip(index).set_select_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_arm_button(self._buttons[index]) <NEW_LINE> self._mixer.channel_strip(index).set_mute_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_solo_button(None) <NEW_LINE> <DEDENT> elif self._mode_index == 2: <NEW_LINE> <INDENT> self._mixer.channel_strip(index).set_select_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_arm_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_mute_button(self._buttons[index]) <NEW_LINE> self._mixer.channel_strip(index).set_solo_button(None) <NEW_LINE> <DEDENT> elif self._mode_index == 3: <NEW_LINE> <INDENT> self._mixer.channel_strip(index).set_select_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_arm_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_mute_button(None) <NEW_LINE> self._mixer.channel_strip(index).set_solo_button(self._buttons[index]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(u'Invalid mode index') <NEW_LINE> assert False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _toggle_value(self, value): <NEW_LINE> <INDENT> assert self._mode_toggle.is_momentary() <NEW_LINE> ModeSelectorComponent._toggle_value(self, value) <NEW_LINE> if value != 0 and self._mode_display is not None: <NEW_LINE> <INDENT> mode_name = u'' <NEW_LINE> if self._mode_index == 0: <NEW_LINE> <INDENT> mode_name = u'Select' <NEW_LINE> <DEDENT> elif self._mode_index == 1: <NEW_LINE> <INDENT> mode_name = u'Arm' <NEW_LINE> <DEDENT> elif self._mode_index == 2: <NEW_LINE> <INDENT> mode_name = u'Mute' <NEW_LINE> <DEDENT> elif self._mode_index == 3: <NEW_LINE> <INDENT> mode_name = u'Solo' <NEW_LINE> <DEDENT> self._mode_display.display_message(mode_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._mode_display.update()
Class that reassigns buttons on the AxiomPro to different mixer functions
62599072796e427e53850058
class Index(Resource): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> return set_response_headers(jsonify(get_doc().entrypoint.get()))
Class for the EntryPoint.
6259907232920d7e50bc7927
class FacultyMemberSerializer(BaseFacultyMemberSerializer): <NEW_LINE> <INDENT> designation = serializers.CharField( source='get_designation_display', read_only=True, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = swapper.load_model('kernel', 'FacultyMember') <NEW_LINE> fields = [ 'id', 'person', 'department', 'employee_id', 'designation', ]
Serializer for FacultyMember objects
62599072cc0a2c111447c741
class Mower: <NEW_LINE> <INDENT> def __init__(self, position: Position, orientation: Orientation, grid_size: Tuple[int, int]): <NEW_LINE> <INDENT> self._position = position <NEW_LINE> self._orientation = orientation <NEW_LINE> self._grid_size = grid_size <NEW_LINE> self._position.restrict_to_grid(self._grid_size) <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self._position.x <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self._position.y <NEW_LINE> <DEDENT> @property <NEW_LINE> def orientation(self): <NEW_LINE> <INDENT> return self._orientation.orientation <NEW_LINE> <DEDENT> def step(self, move: str): <NEW_LINE> <INDENT> if move == 'L': <NEW_LINE> <INDENT> self._orientation.rotate_left() <NEW_LINE> <DEDENT> elif move == 'R': <NEW_LINE> <INDENT> self._orientation.rotate_right() <NEW_LINE> <DEDENT> elif move == 'F': <NEW_LINE> <INDENT> self._position.forward(self._orientation, self._grid_size) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError(f'Invalid move: "{move}"') <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self._position} {self._orientation}'
A structure that encapsulates a mower's position and orientation.
6259907244b2445a339b75ce
class GraphConvolution(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_features, out_features, adjmat, bias=True): <NEW_LINE> <INDENT> super(GraphConvolution, self).__init__() <NEW_LINE> self.in_features = in_features <NEW_LINE> self.out_features = out_features <NEW_LINE> self.adjmat = adjmat <NEW_LINE> self.weight = nn.Parameter(torch.FloatTensor(in_features, out_features)) <NEW_LINE> if bias: <NEW_LINE> <INDENT> self.bias = nn.Parameter(torch.FloatTensor(out_features)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.register_parameter('bias', None) <NEW_LINE> <DEDENT> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> stdv = 6. / math.sqrt(self.weight.size(0) + self.weight.size(1)) <NEW_LINE> self.weight.data.uniform_(-stdv, stdv) <NEW_LINE> if self.bias is not None: <NEW_LINE> <INDENT> self.bias.data.uniform_(-stdv, stdv) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> if x.ndimension() == 2: <NEW_LINE> <INDENT> support = torch.matmul(x, self.weight) <NEW_LINE> output = torch.matmul(self.adjmat, support) <NEW_LINE> if self.bias is not None: <NEW_LINE> <INDENT> output = output + self.bias <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output = [] <NEW_LINE> for i in range(x.shape[0]): <NEW_LINE> <INDENT> support = torch.matmul(x[i], self.weight) <NEW_LINE> output.append(spmm(self.adjmat, support)) <NEW_LINE> <DEDENT> output = torch.stack(output, dim=0) <NEW_LINE> if self.bias is not None: <NEW_LINE> <INDENT> output = output + self.bias <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907.
625990723d592f4c4edbc7c2
class ZenodoJSONSerializer(JSONSerializer): <NEW_LINE> <INDENT> def preprocess_record(self, pid, record, links_factory=None): <NEW_LINE> <INDENT> result = super(ZenodoJSONSerializer, self).preprocess_record( pid, record, links_factory=links_factory ) <NEW_LINE> if isinstance(record, Record) and '_files' in record: <NEW_LINE> <INDENT> if not has_request_context() or has_read_files_permission( current_user, record): <NEW_LINE> <INDENT> result['files'] = record['_files'] <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def dump(self, obj, context=None): <NEW_LINE> <INDENT> return self.schema_class(context=context).dump(obj).data <NEW_LINE> <DEDENT> def transform_record(self, pid, record, links_factory=None): <NEW_LINE> <INDENT> return self.dump( self.preprocess_record(pid, record, links_factory=links_factory), context={'pid': pid} ) <NEW_LINE> <DEDENT> def transform_search_hit(self, pid, record_hit, links_factory=None): <NEW_LINE> <INDENT> return self.dump( self.preprocess_search_hit( pid, record_hit, links_factory=links_factory), context={'pid': pid} )
Zenodo JSON serializer. Adds or removes files from depending on access rights and provides a context to the request serializer.
6259907221bff66bcd724548
class ChainComplexes(Category_module): <NEW_LINE> <INDENT> def super_categories(self): <NEW_LINE> <INDENT> from sage.categories.all import Fields, FreeModules, VectorSpaces <NEW_LINE> base_ring = self.base_ring() <NEW_LINE> if base_ring in Fields(): <NEW_LINE> <INDENT> return [VectorSpaces(base_ring)] <NEW_LINE> <DEDENT> return [FreeModules(base_ring)]
The category of all chain complexes over a base ring. EXAMPLES:: sage: ChainComplexes(RationalField()) Category of chain complexes over Rational Field sage: ChainComplexes(Integers(9)) Category of chain complexes over Ring of integers modulo 9 TESTS:: sage: TestSuite(ChainComplexes(RationalField())).run()
62599072a8370b77170f1cab
class SocialSerializer(serializers.Serializer): <NEW_LINE> <INDENT> code = serializers.CharField(allow_blank=False, trim_whitespace=True,)
Serializer which accepts an OAuth2 code.
6259907255399d3f05627dfa
class Tag(models.Model): <NEW_LINE> <INDENT> STATUS_NORMAL = 1 <NEW_LINE> STATUS_DELETE = 0 <NEW_LINE> STATUS_ITEMS = ( (STATUS_NORMAL, '正常'), (STATUS_DELETE, '删除'), ) <NEW_LINE> name = models.CharField(max_length=10, verbose_name="名称") <NEW_LINE> status = models.PositiveIntegerField(default=STATUS_NORMAL, choices=STATUS_ITEMS, verbose_name="状态") <NEW_LINE> owner = models.ForeignKey(User, verbose_name='作者') <NEW_LINE> created_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = verbose_name_plural = "标签" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
Docstring for Tag.
6259907267a9b606de547714
class PasswordUpdateView(LoginRequiredMixin, NextMixin , FormMessageMixin, generic.FormView): <NEW_LINE> <INDENT> template_name = 'account/password_update.html' <NEW_LINE> form_class = PasswordChangeForm <NEW_LINE> default_next_url = reverse_lazy('kdo-profile-update') <NEW_LINE> form_valid_message = _("Your password has been changed successfully.") <NEW_LINE> def get_form_kwargs(self): <NEW_LINE> <INDENT> kwargs = super(PasswordUpdateView, self).get_form_kwargs() <NEW_LINE> kwargs['user'] = self.request.user <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> self.object = form.save() <NEW_LINE> return super(PasswordUpdateView, self).form_valid(form)
Update the current user's password.
6259907297e22403b383c7e4
class XToolTimeoutError(AssertionError): <NEW_LINE> <INDENT> def __init__(self, value="Timed Out"): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value)
Thrown when a timeout occurs in the `timeout` context manager.
62599072097d151d1a2c2954
class TypeOfApp(models.Model): <NEW_LINE> <INDENT> app_name = models.CharField(u'应用名字',max_length=255) <NEW_LINE> update_time = models.DateTimeField(u'更新时间', auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.app_name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = '应用类型' <NEW_LINE> verbose_name_plural = '应用类型'
记录app信息到
625990725fcc89381b266dc8
class EcbMode(object): <NEW_LINE> <INDENT> def __init__(self, block_cipher): <NEW_LINE> <INDENT> self._state = VoidPointer() <NEW_LINE> result = raw_ecb_lib.ECB_start_operation(block_cipher.get(), self._state.address_of()) <NEW_LINE> if result: <NEW_LINE> <INDENT> raise ValueError("Error %d while instatiating the ECB mode" % result) <NEW_LINE> <DEDENT> self._state = SmartPointer(self._state.get(), raw_ecb_lib.ECB_stop_operation) <NEW_LINE> block_cipher.release() <NEW_LINE> <DEDENT> def encrypt(self, plaintext): <NEW_LINE> <INDENT> expect_byte_string(plaintext) <NEW_LINE> ciphertext = create_string_buffer(len(plaintext)) <NEW_LINE> result = raw_ecb_lib.ECB_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) <NEW_LINE> if result: <NEW_LINE> <INDENT> raise ValueError("Error %d while encrypting in ECB mode" % result) <NEW_LINE> <DEDENT> return get_raw_buffer(ciphertext) <NEW_LINE> <DEDENT> def decrypt(self, ciphertext): <NEW_LINE> <INDENT> expect_byte_string(ciphertext) <NEW_LINE> plaintext = create_string_buffer(len(ciphertext)) <NEW_LINE> result = raw_ecb_lib.ECB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) <NEW_LINE> if result: <NEW_LINE> <INDENT> raise ValueError("Error %d while decrypting in ECB mode" % result) <NEW_LINE> <DEDENT> return get_raw_buffer(plaintext)
*Electronic Code Book (ECB)*. This is the simplest encryption mode. Each of the plaintext blocks is directly encrypted into a ciphertext block, independently of any other block. This mode is dangerous because it exposes frequency of symbols in your plaintext. Other modes (e.g. *CBC*) should be used instead. See `NIST SP800-38A`_ , Section 6.1. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
625990723346ee7daa3382d0
class UndeclaredKeyError(Exception): <NEW_LINE> <INDENT> pass
Indicates that a key was required but not predeclared.
62599072435de62698e9d6e8
class _ServingEnvToAsync(AsyncVectorEnv): <NEW_LINE> <INDENT> def __init__(self, serving_env, preprocessor=None): <NEW_LINE> <INDENT> self.serving_env = serving_env <NEW_LINE> self.prep = preprocessor <NEW_LINE> self.action_space = serving_env.action_space <NEW_LINE> if preprocessor: <NEW_LINE> <INDENT> self.observation_space = preprocessor.observation_space <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.observation_space = serving_env.observation_space <NEW_LINE> <DEDENT> serving_env.start() <NEW_LINE> <DEDENT> def poll(self): <NEW_LINE> <INDENT> with self.serving_env._results_avail_condition: <NEW_LINE> <INDENT> results = self._poll() <NEW_LINE> while len(results[0]) == 0: <NEW_LINE> <INDENT> self.serving_env._results_avail_condition.wait() <NEW_LINE> results = self._poll() <NEW_LINE> if not self.serving_env.isAlive(): <NEW_LINE> <INDENT> raise Exception("Serving thread has stopped.") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> limit = self.serving_env._max_concurrent_episodes <NEW_LINE> assert len(results[0]) < limit, ("Too many concurrent episodes, were some leaked? This ServingEnv " "was created with max_concurrent={}".format(limit)) <NEW_LINE> return results <NEW_LINE> <DEDENT> def _poll(self): <NEW_LINE> <INDENT> all_obs, all_rewards, all_dones, all_infos = {}, {}, {}, {} <NEW_LINE> off_policy_actions = {} <NEW_LINE> for eid, episode in self.serving_env._episodes.copy().items(): <NEW_LINE> <INDENT> data = episode.get_data() <NEW_LINE> if episode.cur_done: <NEW_LINE> <INDENT> del self.serving_env._episodes[eid] <NEW_LINE> <DEDENT> if data: <NEW_LINE> <INDENT> if self.prep: <NEW_LINE> <INDENT> all_obs[eid] = self.prep.transform(data["obs"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all_obs[eid] = data["obs"] <NEW_LINE> <DEDENT> all_rewards[eid] = data["reward"] <NEW_LINE> all_dones[eid] = data["done"] <NEW_LINE> all_infos[eid] = data["info"] <NEW_LINE> if "off_policy_action" in data: <NEW_LINE> <INDENT> off_policy_actions[eid] = data["off_policy_action"] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return _with_dummy_agent_id(all_obs), _with_dummy_agent_id(all_rewards), _with_dummy_agent_id(all_dones, "__all__"), _with_dummy_agent_id(all_infos), _with_dummy_agent_id(off_policy_actions) <NEW_LINE> <DEDENT> def send_actions(self, action_dict): <NEW_LINE> <INDENT> for eid, action in action_dict.items(): <NEW_LINE> <INDENT> self.serving_env._episodes[eid].action_queue.put( action[_DUMMY_AGENT_ID])
Internal adapter of ServingEnv to AsyncVectorEnv.
6259907238b623060ffaa4c5
class TestEnvSetup(unittest.TestCase): <NEW_LINE> <INDENT> def test_init(self): <NEW_LINE> <INDENT> venv = Environment("testName") <NEW_LINE> self.assertEqual(venv.name, "testName") <NEW_LINE> <DEDENT> def test_foo(self): <NEW_LINE> <INDENT> pass
Test the environment properly initialises
62599072167d2b6e312b8200
class Object(Visitable): <NEW_LINE> <INDENT> def __init__(self, name, type): <NEW_LINE> <INDENT> self._visitorName = 'visit_object' <NEW_LINE> self.name = name <NEW_LINE> self.typeName = type
This class represents the AST node for a pddl object.
62599072379a373c97d9a902
class Tag(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True)
tag model
625990727b180e01f3e49cd5
class Stopwatch: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.elapsed = datetime.timedelta(0) <NEW_LINE> with contextlib.suppress(AttributeError): <NEW_LINE> <INDENT> del self.start_time <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.start_time = datetime.datetime.utcnow() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> stop_time = datetime.datetime.utcnow() <NEW_LINE> self.elapsed += stop_time - self.start_time <NEW_LINE> del self.start_time <NEW_LINE> return self.elapsed <NEW_LINE> <DEDENT> def split(self): <NEW_LINE> <INDENT> local_duration = datetime.datetime.utcnow() - self.start_time <NEW_LINE> return self.elapsed + local_duration <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.start() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.stop()
A simple stopwatch which starts automatically. >>> w = Stopwatch() >>> _1_sec = datetime.timedelta(seconds=1) >>> w.split() < _1_sec True >>> import time >>> time.sleep(1.0) >>> w.split() >= _1_sec True >>> w.stop() >= _1_sec True >>> w.reset() >>> w.start() >>> w.split() < _1_sec True It should be possible to launch the Stopwatch in a context: >>> with Stopwatch() as watch: ... assert isinstance(watch.split(), datetime.timedelta) In that case, the watch is stopped when the context is exited, so to read the elapsed time: >>> watch.elapsed datetime.timedelta(...) >>> watch.elapsed.seconds 0
62599072aad79263cf430098
class Schemas(object): <NEW_LINE> <INDENT> IMAGE_SCHEMA = '/v2/schemas/image' <NEW_LINE> IMAGES_SCHEMA = '/v2/schemas/images' <NEW_LINE> IMAGE_MEMBER_SCHEMA = '/v2/schemas/member' <NEW_LINE> IMAGE_MEMBERS_SCHEMA = '/v2/schemas/members' <NEW_LINE> TASK_SCHEMA = '/v2/schemas/task' <NEW_LINE> TASKS_SCHEMA = '/v2/schemas/tasks'
@summary: Types denoting a schema
625990724f6381625f19a11a
class GetVideoResultSet(ResultSet): <NEW_LINE> <INDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None)
Retrieve the value for the "Response" output from this choreography execution. ((json) The response from Khan Academy.)
62599072ac7a0e7691f73dcc
@attrs(auto_attribs=True) <NEW_LINE> class MeasureValuePair(object): <NEW_LINE> <INDENT> measure: Measure <NEW_LINE> value: CheaperFraction <NEW_LINE> @classmethod <NEW_LINE> def from_string_list(cls, string_pairs: str): <NEW_LINE> <INDENT> result = ( value.split('=')[:2] for value in string_pairs ) <NEW_LINE> return [ cls(Beat(beat).as_measure, value) for beat, value in result ]
A duplet, usually used for scripting a chart with freeform data.
6259907256b00c62f0fb41b2
class TestBaseReporter(unittest.TestCase): <NEW_LINE> <INDENT> def test_report_mongo_command_raises_not_implemented_error(self): <NEW_LINE> <INDENT> reporter = mongodog.reporters.BaseReporter() <NEW_LINE> self.assertRaises(NotImplementedError, reporter.report_mongo_command, {})
Unit tests for BaseReporter class
62599072a8370b77170f1cad
class Registro0001(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', '0001'), Campo(2, 'IND_MOV'), ]
ABERTURA DO BLOCO 0
625990724428ac0f6e659e17
class Server(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, port): <NEW_LINE> <INDENT> self.chunk_queue = Queue.Queue() <NEW_LINE> self.port = port <NEW_LINE> self._abort = False <NEW_LINE> threading.Thread.__init__(self) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> print('Server is Running') <NEW_LINE> self.bst = helpers._Broadcast_Server_Thread(MULTICAST_GROUP_IP, MULTICAST_PORT, self.chunk_queue) <NEW_LINE> self.bst.start() <NEW_LINE> self.sstr = helpers._Server_Socket_Thread_Receive(IP_ADDRESS, self.port, self.chunk_queue) <NEW_LINE> self.sstr.start() <NEW_LINE> while not self._abort: <NEW_LINE> <INDENT> time.sleep(0.01) <NEW_LINE> if not self.chunk_queue.empty(): <NEW_LINE> <INDENT> full_chunk = self.chunk_queue.get() <NEW_LINE> dict_received = pickle.loads(full_chunk[0]) <NEW_LINE> chunk = dict_received['chunk'] <NEW_LINE> func = dict_received['func'] <NEW_LINE> op = dict_received['op'] <NEW_LINE> if op == 'map': <NEW_LINE> <INDENT> processed_chunk = helpers._single_map(func, chunk) <NEW_LINE> <DEDENT> elif op == 'filter': <NEW_LINE> <INDENT> processed_chunk = helpers._single_filter(func, chunk) <NEW_LINE> <DEDENT> elif op == 'reduce': <NEW_LINE> <INDENT> processed_chunk = helpers._single_reduce(func, chunk) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> processed_chunk = 'This operation does not exist.' <NEW_LINE> <DEDENT> dict_sent = { 'chunk': processed_chunk, 'index': dict_received['index'] } <NEW_LINE> self.ssts = threading.Thread( target = helpers._server_socket_thread_send, args = (full_chunk[1], self.port + 1, pickle.dumps(dict_sent)) ) <NEW_LINE> self.ssts.start() <NEW_LINE> <DEDENT> <DEDENT> self.sstr.stop() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> print('Server Stopped') <NEW_LINE> self._abort = True
Server class that should be run on each machine that wants to act as a computational entity for the system. Extends threading. Thread to make the server threaded and thus nonblocking
62599072a219f33f346c80ed
class AutoMinorLocator(Locator): <NEW_LINE> <INDENT> def __init__(self, n=None): <NEW_LINE> <INDENT> self.ndivs = n <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> if self.axis.get_scale() == 'log': <NEW_LINE> <INDENT> warnings.warn('AutoMinorLocator does not work with logarithmic ' 'scale') <NEW_LINE> return [] <NEW_LINE> <DEDENT> majorlocs = self.axis.get_majorticklocs() <NEW_LINE> try: <NEW_LINE> <INDENT> majorstep = majorlocs[1] - majorlocs[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> majorstep = 0 <NEW_LINE> <DEDENT> if self.ndivs is None: <NEW_LINE> <INDENT> if majorstep == 0: <NEW_LINE> <INDENT> ndivs = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = int(np.round(10 ** (np.log10(majorstep) % 1))) <NEW_LINE> if x in [1, 5, 10]: <NEW_LINE> <INDENT> ndivs = 5 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ndivs = 4 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ndivs = self.ndivs <NEW_LINE> <DEDENT> minorstep = majorstep / ndivs <NEW_LINE> vmin, vmax = self.axis.get_view_interval() <NEW_LINE> if vmin > vmax: <NEW_LINE> <INDENT> vmin, vmax = vmax, vmin <NEW_LINE> <DEDENT> if len(majorlocs) > 0: <NEW_LINE> <INDENT> t0 = majorlocs[0] <NEW_LINE> tmin = ((vmin - t0) // minorstep + 1) * minorstep <NEW_LINE> tmax = ((vmax - t0) // minorstep + 1) * minorstep <NEW_LINE> locs = np.arange(tmin, tmax, minorstep) + t0 <NEW_LINE> cond = np.abs((locs - t0) % majorstep) > minorstep / 10.0 <NEW_LINE> locs = locs.compress(cond) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> locs = [] <NEW_LINE> <DEDENT> return self.raise_if_exceeds(np.array(locs)) <NEW_LINE> <DEDENT> def tick_values(self, vmin, vmax): <NEW_LINE> <INDENT> raise NotImplementedError('Cannot get tick locations for a ' '%s type.' % type(self))
Dynamically find minor tick positions based on the positions of major ticks. The scale must be linear with major ticks evenly spaced.
62599072f548e778e596ce70
class TestVarUnitsToKelvin(BaseTest): <NEW_LINE> <INDENT> def test_subprocess_called_correctly(self): <NEW_LINE> <INDENT> fix = VarUnitsToKelvin('ts_components.nc', '/a') <NEW_LINE> fix.apply_fix() <NEW_LINE> self.mock_subprocess.assert_called_once_with( "ncatted -h -a units,ts,o,c,'K' " "/a/ts_components.nc", stderr=subprocess.STDOUT, shell=True )
Test VarUnitsToKelvin
6259907255399d3f05627dfc
class NullAction (Action): <NEW_LINE> <INDENT> def __init__ (self, manager, prop_set): <NEW_LINE> <INDENT> assert isinstance(prop_set, property_set.PropertySet) <NEW_LINE> Action.__init__ (self, manager, [], None, prop_set) <NEW_LINE> <DEDENT> def actualize (self): <NEW_LINE> <INDENT> if not self.actualized_: <NEW_LINE> <INDENT> self.actualized_ = True <NEW_LINE> for i in self.targets (): <NEW_LINE> <INDENT> i.actualize ()
Action class which does nothing --- it produces the targets with specific properties out of nowhere. It's needed to distinguish virtual targets with different properties that are known to exist, and have no actions which create them.
625990724f88993c371f1192
class StdOutListener(StreamListener): <NEW_LINE> <INDENT> def on_status(self, status): <NEW_LINE> <INDENT> text = status.text <NEW_LINE> try: <NEW_LINE> <INDENT> Coords.update(status.coordinates) <NEW_LINE> XY = (Coords.get('coordinates')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> Box = status.place.bounding_box.coordinates[0] <NEW_LINE> XY = [(Box[0][0] + Box[2][0]) / 2, (Box[0][1] + Box[2][1]) / 2] <NEW_LINE> pass <NEW_LINE> <DEDENT> today = str(date.today()) <NEW_LINE> try: <NEW_LINE> <INDENT> with open('tweets_' + today + '.json', 'a') as f: <NEW_LINE> <INDENT> f.write(json.dumps(status._json)) <NEW_LINE> f.write('\n') <NEW_LINE> <DEDENT> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> print("Error on_data: %s" % str(e))
A listener handles tweets that are the received from the stream. This is a basic listener that inserts tweets into MySQLdb.
6259907291f36d47f2231b00
class HTTPTransparentRedirect(Exception): <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> super(HTTPTransparentRedirect, self).__init__(url) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "url=%r" % self.args[0] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s(url=%r)" % (self.__class__.__name__, self.args[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self.args[0]
Raising an instance of HTTPTransparentRedirect will cause the Application to silently redirect a request to a new URL.
6259907297e22403b383c7e6