code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class TestINImage(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 make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return INImage( proto = 'nudityCheck' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return INImage( ) <NEW_LINE> <DEDENT> <DEDENT> def testINImage(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | INImage unit test stubs | 6259907f1f5feb6acb164680 |
class Bucketlist(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'bucketlists' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(255)) <NEW_LINE> date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) <NEW_LINE> date_modified = db.Column( db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp()) <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_all(): <NEW_LINE> <INDENT> return Bucketlist.query.all() <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> db.session.delete(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Bucketlist: {}>".format(self.name) | Bucketlist table db model | 6259907f656771135c48ad73 |
class NormalKLDivergence(BaseCost): <NEW_LINE> <INDENT> def __init__( self, elementwise=False, clip_max=1e+10, clip_min=1e-10, scope='NormalKLDivergence'): <NEW_LINE> <INDENT> super(NormalKLDivergence, self).__init__( elementwise=elementwise, clip_max=clip_max, clip_min=clip_min, scope=scope) <NEW_LINE> <DEDENT> def __call__(self, mean, stddev): <NEW_LINE> <INDENT> return self.build(mean, stddev) <NEW_LINE> <DEDENT> def build(self, mean, stddev): <NEW_LINE> <INDENT> _LG.info( ' Building cost %s with mean: %s and stddev: %s', type(self).__name__, mean, stddev ) <NEW_LINE> self.input = {'mean': mean, 'stddev': stddev} <NEW_LINE> with variable_scope(self.args['scope']): <NEW_LINE> <INDENT> self.output = self._build(mean, stddev) <NEW_LINE> return self.output <NEW_LINE> <DEDENT> <DEDENT> def _build(self, mean, stddev): <NEW_LINE> <INDENT> min_, max_ = self.args['clip_min'], self.args['clip_max'] <NEW_LINE> mean2, stddev2 = [ops.square(val) for val in [mean, stddev]] <NEW_LINE> clipped = ops.clip_by_value(stddev2, min_value=min_, max_value=max_) <NEW_LINE> kl = 0.5 * (mean2 + stddev2 - ops.log(clipped) - 1) <NEW_LINE> if self.args['elementwise']: <NEW_LINE> <INDENT> return kl <NEW_LINE> <DEDENT> return ops.reduce_sum(ops.reduce_mean(kl, axis=0)) | KL-Divegence against univariate normal distribution.
.. math::
loss = \frac{1}{2} (\mu^2 + \sigma^2 - \log(clip(\sigma^2)) -1)
Parameters
----------
elementwise : Bool
When True, the cost tesnor returned by `build` method has the same
shape as its input Tensors. When False, the cost tensor is reduced to
scalar shape by taking average over batch and sum over feature.
Defalut: False.
clip_max, clip_min : float
For numerical stability, :math:`\sigma^2` is clipped before fed to
:math:`\log`.
Notes
-----
The defalut values of clipping are chosen so as to prevent NaN and Inf
which can happend as a direct result of ``log`` function.
It can still generate huge gradients because the gradient of ``log``
involves inverse of the ``stddev``. This might cause NaN at somewhere
else in optimization process. When this occurs, you may want to narrow
down clipping range or apply clipping to gradient separately.
Reference; (ignoring ``mean``)
+----------+----------+-----------+
| stddev | cost | gradient |
+==========+==========+===========+
| 0 | inf | nan |
+----------+----------+-----------+
| 1.00e-05 | 1.10e+01 | -1.00e+05 |
+----------+----------+-----------+
| 1.00e-04 | 8.71e+00 | -1.00e+04 |
+----------+----------+-----------+
| 1.00e-03 | 6.41e+00 | -1.00e+03 |
+----------+----------+-----------+
| 1.00e-02 | 4.11e+00 | -1.00e+02 |
+----------+----------+-----------+
| 1.00e-01 | 1.81e+00 | -9.90e+00 |
+----------+----------+-----------+
| 1.00e+00 | 0.00e+00 | 0.00e+00 |
+----------+----------+-----------+
| 1.00e+01 | 4.72e+01 | 9.90e+00 |
+----------+----------+-----------+
| 1.00e+02 | 4.99e+03 | 1.00e+02 |
+----------+----------+-----------+
| 1.00e+03 | 5.00e+05 | 1.00e+03 |
+----------+----------+-----------+
| 1.00e+04 | 5.00e+07 | 1.00e+04 |
+----------+----------+-----------+
| 1.00e+05 | 5.00e+09 | 1.00e+05 |
+----------+----------+-----------+ | 6259907f55399d3f05627f9c |
class MultipleChoiceTask(Task): <NEW_LINE> <INDENT> def update_metrics(self, out, batch): <NEW_LINE> <INDENT> logits = out["logits"] <NEW_LINE> labels = batch["label"] <NEW_LINE> assert len(self.get_scorers()) > 0, "Please specify a score metric" <NEW_LINE> for scorer in self.get_scorers(): <NEW_LINE> <INDENT> scorer(logits, labels) | Generic task class for a multiple choice
where each example consists of a question and
a (possibly variable) number of possible answers | 6259907f99fddb7c1ca63b1c |
class DefaultConfig: <NEW_LINE> <INDENT> PORT = 12345 <NEW_LINE> DBFILE = "t-800.db" <NEW_LINE> APP_AUTHORITY = "https://login.microsoftonline.com" <NEW_LINE> APP_SCOPE = [ "https://graph.microsoft.com/.default" ] <NEW_LINE> APP_ID = os.environ.get("MicrosoftAppId", "95dc3706-fe69-4ee2-9879-750660f64753") <NEW_LINE> APP_PASSWORD = keyring.get_password("T800", "AppSecret") <NEW_LINE> APP_NGROK_ADDR = "https://34aae6ba15b8.ngrok.io" <NEW_LINE> PLAY_PROMPT = False <NEW_LINE> PLAY_PROMPT_HANGUP_AFTER = False | Bot Configuration | 6259907f167d2b6e312b82d8 |
class IoTHubPipelineConfig(BasePipelineConfig): <NEW_LINE> <INDENT> def __init__(self, hostname, device_id, module_id=None, product_info="", **kwargs): <NEW_LINE> <INDENT> super().__init__(hostname=hostname, **kwargs) <NEW_LINE> self.device_id = device_id <NEW_LINE> self.module_id = module_id <NEW_LINE> self.product_info = product_info <NEW_LINE> self.blob_upload = False <NEW_LINE> self.method_invoke = False | A class for storing all configurations/options for IoTHub clients in the Azure IoT Python Device Client Library. | 6259907f283ffb24f3cf5328 |
class WebWebAnswer(SearchResultsAnswer): <NEW_LINE> <INDENT> _validation = { '_type': {'required': True}, 'id': {'readonly': True}, 'web_search_url': {'readonly': True}, 'follow_up_queries': {'readonly': True}, 'query_context': {'readonly': True}, 'total_estimated_matches': {'readonly': True}, 'is_family_friendly': {'readonly': True}, 'value': {'required': True}, 'some_results_removed': {'readonly': True}, } <NEW_LINE> _attribute_map = { '_type': {'key': '_type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'}, 'follow_up_queries': {'key': 'followUpQueries', 'type': '[Query]'}, 'query_context': {'key': 'queryContext', 'type': 'QueryContext'}, 'total_estimated_matches': {'key': 'totalEstimatedMatches', 'type': 'long'}, 'is_family_friendly': {'key': 'isFamilyFriendly', 'type': 'bool'}, 'value': {'key': 'value', 'type': '[WebPage]'}, 'some_results_removed': {'key': 'someResultsRemoved', 'type': 'bool'}, } <NEW_LINE> def __init__(self, value): <NEW_LINE> <INDENT> super(WebWebAnswer, self).__init__() <NEW_LINE> self.value = value <NEW_LINE> self.some_results_removed = None <NEW_LINE> self._type = 'Web/WebAnswer' | Defines a list of relevant webpage links.
Variables are only populated by the server, and will be ignored when
sending a request.
:param _type: Constant filled by server.
:type _type: str
:ivar id: A String identifier.
:vartype id: str
:ivar web_search_url: The URL To Bing's search result for this item.
:vartype web_search_url: str
:ivar follow_up_queries:
:vartype follow_up_queries:
list[~azure.cognitiveservices.search.customsearch.models.Query]
:ivar query_context:
:vartype query_context:
~azure.cognitiveservices.search.customsearch.models.QueryContext
:ivar total_estimated_matches: The estimated number of webpages that are
relevant to the query. Use this number along with the count and offset
query parameters to page the results.
:vartype total_estimated_matches: long
:ivar is_family_friendly:
:vartype is_family_friendly: bool
:param value: A list of webpages that are relevant to the query.
:type value:
list[~azure.cognitiveservices.search.customsearch.models.WebPage]
:ivar some_results_removed: A Boolean value that indicates whether the
response excluded some results from the answer. If Bing excluded some
results, the value is true.
:vartype some_results_removed: bool | 6259907f67a9b606de5477ea |
class User(object): <NEW_LINE> <INDENT> def __init__(self, data=None): <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> self.first_name = data["first_name"] <NEW_LINE> self.last_name = data["last_name"] <NEW_LINE> if 'id' in data: <NEW_LINE> <INDENT> self.id = data["id"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.id = None <NEW_LINE> <DEDENT> if 'email' in data: <NEW_LINE> <INDENT> self.email = data["email"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.email = None <NEW_LINE> <DEDENT> if 'registration_status' in data: <NEW_LINE> <INDENT> self.registration_status = data["registration_status"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.registration_status = None <NEW_LINE> <DEDENT> if 'picture' in data: <NEW_LINE> <INDENT> self.picture = Picture(data["picture"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.picture = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getId(self): <NEW_LINE> <INDENT> return self.id <NEW_LINE> <DEDENT> def getFirstName(self): <NEW_LINE> <INDENT> return self.first_name <NEW_LINE> <DEDENT> def getLastName(self): <NEW_LINE> <INDENT> return self.last_name <NEW_LINE> <DEDENT> def getEmail(self): <NEW_LINE> <INDENT> return self.email <NEW_LINE> <DEDENT> def getRegistrationStatus(self): <NEW_LINE> <INDENT> return self.registration_status <NEW_LINE> <DEDENT> def getPicture(self): <NEW_LINE> <INDENT> return self.picture <NEW_LINE> <DEDENT> def setFirstName(self, first_name): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> <DEDENT> def setLastName(self, last_name): <NEW_LINE> <INDENT> self.last_name = last_name <NEW_LINE> <DEDENT> def setEmail(self, email): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> <DEDENT> def setId(self, id): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> return None | Contains basic user data.
Attributes:
id(long, optional): ID of the user
first_name(str, optional): First name of the user
last_name(str, optional): Last name of the user
email(str, optional): Email of the user
registration_status(str, optional): Registration status of the user
picture(:obj:`splitwise.picture.Picture`, optional): Profile picture of the user | 6259907f97e22403b383c988 |
class TblWSpacesAndDots(InternalBase): <NEW_LINE> <INDENT> __tablename__ = "this is.an AWFUL.name" <NEW_LINE> __table_args__ = {'schema': 'another AWFUL.name for.schema'} <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> geom = Column(String) | Dummy class to test names with dots and spaces.
No metadata is attached so the dialect is default SQL, not postgresql. | 6259907f7d43ff2487428159 |
class Logger(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def __new__(cls, filename): <NEW_LINE> <INDENT> if not filename: <NEW_LINE> <INDENT> return Printer() <NEW_LINE> <DEDENT> elif filename.endswith(".asc"): <NEW_LINE> <INDENT> return ASCWriter(filename) <NEW_LINE> <DEDENT> elif filename.endswith(".blf"): <NEW_LINE> <INDENT> return BLFWriter(filename) <NEW_LINE> <DEDENT> elif filename.endswith(".csv"): <NEW_LINE> <INDENT> return CSVWriter(filename) <NEW_LINE> <DEDENT> elif filename.endswith(".db"): <NEW_LINE> <INDENT> return SqliteWriter(filename) <NEW_LINE> <DEDENT> elif filename.endswith(".log"): <NEW_LINE> <INDENT> return CanutilsLogWriter(filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.info('unknown file type "%s", falling pack to can.Printer', filename) <NEW_LINE> return Printer(filename) | Logs CAN messages to a file.
The format is determined from the file format which can be one of:
* .asc: :class:`can.ASCWriter`
* .blf :class:`can.BLFWriter`
* .csv: :class:`can.CSVWriter`
* .db: :class:`can.SqliteWriter`
* .log :class:`can.CanutilsLogWriter`
* other: :class:`can.Printer`
Note this class itself is just a dispatcher,
an object that inherits from Listener will
be created when instantiating this class. | 6259907f5fdd1c0f98e5fa08 |
@implementer(IVocabularyFactory) <NEW_LINE> class GroupsVocabulary(object): <NEW_LINE> <INDENT> def __call__(self, context): <NEW_LINE> <INDENT> items = [] <NEW_LINE> site = getSite() <NEW_LINE> gtool = getToolByName(site, 'portal_groups', None) <NEW_LINE> if gtool is not None: <NEW_LINE> <INDENT> groups = gtool.listGroups() <NEW_LINE> items = [(g.getGroupId(), g.getGroupTitleOrName()) for g in groups] <NEW_LINE> items.sort() <NEW_LINE> items = [SimpleTerm(i[0], i[0], i[1]) for i in items] <NEW_LINE> <DEDENT> return SimpleVocabulary(items) | Vocabulary factory for groups in the portal
>>> from zope.component import queryUtility
>>> from plone.app.vocabularies.tests.base import create_context
>>> from plone.app.vocabularies.tests.base import DummyTool
>>> name = 'plone.app.vocabularies.Groups'
>>> util = queryUtility(IVocabularyFactory, name)
>>> context = create_context()
>>> len(util(context))
0
>>> class DummyGroup(object):
... def __init__(self, id, name):
... self.id = id
... self.name = name
...
... def getGroupId(self):
... return self.id
...
... def getGroupTitleOrName(self):
... return self.name
>>> tool = DummyTool('portal_groups')
>>> def listGroups():
... return (DummyGroup('editors', 'Editors'),
... DummyGroup('viewers', 'Viewers'))
>>> tool.listGroups = listGroups
>>> context.portal_groups = tool
>>> groups = util(context)
>>> groups
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> len(groups.by_token)
2
>>> editors = groups.by_token['editors']
>>> editors.title, editors.token, editors.value
('Editors', 'editors', 'editors') | 6259907f76e4537e8c3f1008 |
class PyConfigobj(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/DiffSK/configobj" <NEW_LINE> pypi = "configobj/configobj-5.0.6.tar.gz" <NEW_LINE> version('5.0.6', sha256='a2f5650770e1c87fb335af19a9b7eb73fc05ccf22144eb68db7d00cd2bcb0902') <NEW_LINE> version('4.7.2', sha256='515ff923462592e8321df8b48c47e3428f8d406ee22b8de77bef969d1af11171') <NEW_LINE> depends_on('py-six', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:2.8,3.4:', type=('build', 'run')) | Config file reading, writing and validation.
| 6259907f3346ee7daa3383a6 |
class _No: <NEW_LINE> <INDENT> def __init__(self, valor, proximo = None): <NEW_LINE> <INDENT> self.valor = valor <NEW_LINE> self.proximo = proximo <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "_No({})".format(self.valor.__repr__()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.valor.__str__() | Classe auxiliar Nó. | 6259907f099cdd3c6367613e |
class ValidateTestMixin(object): <NEW_LINE> <INDENT> def validate_tests(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> x = self.validate_tests(request, *args, **kwargs) <NEW_LINE> if x != None: <NEW_LINE> <INDENT> return HttpResponseRedirect(x) <NEW_LINE> <DEDENT> return super(ValidateTestMixin, self).dispatch(request, *args, **kwargs) | Mixin que permita la validacion de ciertos test antes de ingresar a una vista | 6259907fad47b63b2c5a92da |
class Ship(games.Sprite): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> if games.keyboard.is_pressed(games.K_RIGHT): <NEW_LINE> <INDENT> self.angle -= 1 <NEW_LINE> <DEDENT> if games.keyboard.is_pressed(games.K_LEFT): <NEW_LINE> <INDENT> self.angle += 1 <NEW_LINE> <DEDENT> if games.keyboard.is_pressed(games.K_1): <NEW_LINE> <INDENT> self.angle = 0 <NEW_LINE> <DEDENT> if games.keyboard.is_pressed(games.K_2): <NEW_LINE> <INDENT> self.angle = 90 <NEW_LINE> <DEDENT> if games.keyboard.is_pressed(games.K_3): <NEW_LINE> <INDENT> self.angle = 180 <NEW_LINE> <DEDENT> if games.keyboard.is_pressed(games.K_4): <NEW_LINE> <INDENT> self.angle = 270 | A moving ship. | 6259907f7cff6e4e811b74ca |
class RedisSpider(RedisMixin, Spider): <NEW_LINE> <INDENT> def __init__(self, life=None, proxy=None, *args, **kargs): <NEW_LINE> <INDENT> super(RedisSpider, self).__init__(*args, **kargs) <NEW_LINE> self.life = None if life is None else float(life) <NEW_LINE> self.proxy = None if proxy is None else proxy.decode('utf-8') <NEW_LINE> <DEDENT> def set_crawler(self, crawler): <NEW_LINE> <INDENT> super(RedisSpider, self).set_crawler(crawler) <NEW_LINE> self.setup_redis() | Spider that reads urls from redis queue when idle. | 6259907f283ffb24f3cf532a |
class UserList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> users = User.objects.all() <NEW_LINE> serializer = MobileSerializer(users, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = MobileSerializer(data=request.DATA) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | List all code reports, or create a new report. | 6259907faad79263cf430244 |
class ReconnectTestCase(TestCase): <NEW_LINE> <INDENT> @defer.inlineCallbacks <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> yield super(ReconnectTestCase, self).setUp() <NEW_LINE> self.called = [] <NEW_LINE> self.remote_obj = 'remote' <NEW_LINE> self.root_obj = FakeRootObject(self.called, self.remote_obj) <NEW_LINE> def fake_get_root_object(): <NEW_LINE> <INDENT> self.called.append('getRootObject') <NEW_LINE> return defer.succeed(self.root_obj) <NEW_LINE> <DEDENT> def fake_client_connect(factory, service_name, cmd, description): <NEW_LINE> <INDENT> self.called.append('client_connect') <NEW_LINE> self.patch(factory, 'getRootObject', fake_get_root_object) <NEW_LINE> return defer.succeed(True) <NEW_LINE> <DEDENT> self.patch(ipc, 'client_connect', fake_client_connect) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def test_reconnect_method(self): <NEW_LINE> <INDENT> clients = dict(first=FakeWorkingRemoteClient(self.called), second=FakeWorkingRemoteClient(self.called)) <NEW_LINE> base_client = ipc.BaseClient() <NEW_LINE> base_client.clients = clients <NEW_LINE> for name, client in clients.items(): <NEW_LINE> <INDENT> setattr(base_client, name, client) <NEW_LINE> <DEDENT> yield base_client.reconnect() <NEW_LINE> self.assertIn('client_connect', self.called) <NEW_LINE> self.assertIn('getRootObject', self.called) <NEW_LINE> for name in clients: <NEW_LINE> <INDENT> self.assertIn('get_%s' % name, self.called) <NEW_LINE> <DEDENT> self.assertEqual( len(clients), self.called.count('register_to_signals')) | Test the reconnection when service is dead. | 6259907f7d43ff248742815a |
class UserViewsTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @unittest.skip("test missing") <NEW_LINE> def testAccountSummary(self): <NEW_LINE> <INDENT> self.fail("Test not implemented") <NEW_LINE> <DEDENT> @unittest.skip("test missing") <NEW_LINE> def testGroupSummary(self): <NEW_LINE> <INDENT> self.fail("Test not implemented") <NEW_LINE> <DEDENT> @unittest.skip("test missing") <NEW_LINE> def testTransfer(self): <NEW_LINE> <INDENT> self.fail("Test not implemented") | Tests the views as an unprivileged user | 6259907f5fdd1c0f98e5fa0a |
class CancelarUs(UpdateView): <NEW_LINE> <INDENT> template_name = 'us/cancelar_us.html' <NEW_LINE> model = us <NEW_LINE> form_class = CancelarForm <NEW_LINE> @method_decorator(login_required) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(CancelarUs, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def get_form_kwargs(self, **kwargs): <NEW_LINE> <INDENT> kwargs = super(CancelarUs, self).get_form_kwargs(**kwargs) <NEW_LINE> userstorie = us.objects.get(pk=self.kwargs['pk']) <NEW_LINE> kwargs['initial']['estado_de_aprobacion'] = 'CAN' <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(CancelarUs, self).get_context_data(**kwargs) <NEW_LINE> userstorie = us.objects.get(pk=self.kwargs['pk']) <NEW_LINE> context['proyecto']= Proyecto.objects.get(pk=userstorie.proyecto.pk) <NEW_LINE> try: <NEW_LINE> <INDENT> context['lider'] = Usuario.objects.get(pk=self.request.user) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> context['lider'] = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> context['cliente'] = Cliente.objects.get(pk = self.request.user) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> context['cliente'] = None <NEW_LINE> <DEDENT> return context <NEW_LINE> <DEDENT> def get_success_url(self, **kwargs): <NEW_LINE> <INDENT> kwargs = super(CancelarUs, self).get_form_kwargs(**kwargs) <NEW_LINE> userstorie = us.objects.get(pk=self.kwargs['pk']) <NEW_LINE> return reverse('kanban',args=[userstorie.proyecto.pk]) | *Vista Basada en Clase para modificar un sprint:*
+*template_name*: template a ser renderizado
+*model*: modelo que se va modificar
+*form_class*:Formulario para actualizar el usuario
+*success_url*: url a ser redireccionada en caso de exito | 6259907f5fc7496912d48fb0 |
class ModelItems(TreeItems): <NEW_LINE> <INDENT> ITEM_CLASS = ModelItem <NEW_LINE> def item_by_named_path(self, named_path, match_column=0, sep='/', column=0): <NEW_LINE> <INDENT> items = self.row_by_named_path(named_path, match_column=match_column, sep=sep) <NEW_LINE> if items: <NEW_LINE> <INDENT> return items[column] <NEW_LINE> <DEDENT> <DEDENT> def row_by_named_path(self, named_path, match_column=0, sep='/'): <NEW_LINE> <INDENT> if isinstance(named_path, (list, tuple)): <NEW_LINE> <INDENT> parts = list(named_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parts = named_path.split(sep) <NEW_LINE> <DEDENT> item = self <NEW_LINE> while item and parts: <NEW_LINE> <INDENT> next_item = None <NEW_LINE> part = parts.pop(0) <NEW_LINE> for item_ in item.items: <NEW_LINE> <INDENT> if match_column == item_.column and item_.value == part: <NEW_LINE> <INDENT> if not parts: <NEW_LINE> <INDENT> row = [it for it in item.items if it.row == item_.row] <NEW_LINE> return sorted(row, key=lambda it: it.column) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> next_item = item_ <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> item = next_item <NEW_LINE> <DEDENT> return None | Allow to manipulate all modelitems in a QAbstractModelItem or derived.
:var items: list of :class:`ModelItem` | 6259907f5fcc89381b266ea1 |
@config_entries.HANDLERS.register('http2mqtt2hass') <NEW_LINE> class FlowHandler(config_entries.ConfigFlow): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH <NEW_LINE> _hassio_discovery = None <NEW_LINE> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> if self._async_current_entries(): <NEW_LINE> <INDENT> return self.async_abort(reason='single_instance_allowed') <NEW_LINE> <DEDENT> return await self.async_step_broker() <NEW_LINE> <DEDENT> async def async_step_broker(self, user_input=None): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> can_connect = await self.hass.async_add_executor_job( try_connection, user_input[CONF_BROKER], user_input[CONF_PORT], user_input.get(CONF_USERNAME), user_input.get(CONF_PASSWORD)) <NEW_LINE> if can_connect: <NEW_LINE> <INDENT> return self.async_create_entry( title=user_input[CONF_BROKER], data=user_input) <NEW_LINE> <DEDENT> errors['base'] = 'cannot_connect' <NEW_LINE> <DEDENT> fields = OrderedDict() <NEW_LINE> fields[vol.Required(CONF_BROKER)] = str <NEW_LINE> fields[vol.Required(CONF_PORT, default=1883)] = vol.Coerce(int) <NEW_LINE> fields[vol.Optional(CONF_USERNAME)] = str <NEW_LINE> fields[vol.Optional(CONF_PASSWORD)] = str <NEW_LINE> fields[vol.Optional(CONF_DISCOVERY, default=DEFAULT_DISCOVERY)] = bool <NEW_LINE> return self.async_show_form( step_id='broker', data_schema=vol.Schema(fields), errors=errors) <NEW_LINE> <DEDENT> async def async_step_import(self, user_input): <NEW_LINE> <INDENT> if self._async_current_entries(): <NEW_LINE> <INDENT> return self.async_abort(reason='single_instance_allowed') <NEW_LINE> <DEDENT> return self.async_create_entry(title='configuration.yaml', data={}) <NEW_LINE> <DEDENT> async def async_step_hassio(self, user_input=None): <NEW_LINE> <INDENT> if self._async_current_entries(): <NEW_LINE> <INDENT> return self.async_abort(reason='single_instance_allowed') <NEW_LINE> <DEDENT> self._hassio_discovery = user_input <NEW_LINE> return await self.async_step_hassio_confirm() <NEW_LINE> <DEDENT> async def async_step_hassio_confirm(self, user_input=None): <NEW_LINE> <INDENT> errors = {} <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> data = self._hassio_discovery <NEW_LINE> can_connect = await self.hass.async_add_executor_job( try_connection, data[CONF_HOST], data[CONF_PORT], data.get(CONF_USERNAME), data.get(CONF_PASSWORD), data.get(CONF_PROTOCOL) ) <NEW_LINE> if can_connect: <NEW_LINE> <INDENT> return self.async_create_entry( title=data['addon'], data={ CONF_BROKER: data[CONF_HOST], CONF_PORT: data[CONF_PORT], CONF_USERNAME: data.get(CONF_USERNAME), CONF_PASSWORD: data.get(CONF_PASSWORD), CONF_PROTOCOL: data.get(CONF_PROTOCOL), CONF_DISCOVERY: user_input[CONF_DISCOVERY], }) <NEW_LINE> <DEDENT> errors['base'] = 'cannot_connect' <NEW_LINE> <DEDENT> return self.async_show_form( step_id='hassio_confirm', description_placeholders={ 'addon': self._hassio_discovery['addon'] }, data_schema=vol.Schema({ vol.Optional(CONF_DISCOVERY, default=DEFAULT_DISCOVERY): bool }), errors=errors, ) | Handle a config flow. | 6259907fec188e330fdfa334 |
class MediaItemJSONLDSerializer(JSONLDSerializer): <NEW_LINE> <INDENT> jsonld_context = 'http://schema.org' <NEW_LINE> jsonld_type = 'VideoObject' <NEW_LINE> id = serializers.HyperlinkedIdentityField( view_name='api:media_item', help_text='Unique URL for the media', read_only=True) <NEW_LINE> name = serializers.CharField(source='title', help_text='Title of media') <NEW_LINE> description = serializers.CharField( help_text='Description of media', required=False, allow_blank=True) <NEW_LINE> duration = serializers.SerializerMethodField( help_text='Duration of the media in ISO 8601 format', read_only=True) <NEW_LINE> thumbnailUrl = serializers.SerializerMethodField( help_text='A URL of a thumbnail/poster image for the media', read_only=True) <NEW_LINE> uploadDate = serializers.DateTimeField( source='published_at', help_text='Publication time', read_only=True) <NEW_LINE> embedUrl = serializers.SerializerMethodField() <NEW_LINE> contentUrl = serializers.SerializerMethodField() <NEW_LINE> def get_duration(self, obj): <NEW_LINE> <INDENT> if obj.duration is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> hours, remainder = divmod(obj.duration, 3600) <NEW_LINE> minutes, seconds = divmod(remainder, 60) <NEW_LINE> return "PT{:d}H{:02d}M{:02.1f}S".format(int(hours), int(minutes), seconds) <NEW_LINE> <DEDENT> def get_thumbnailUrl(self, obj): <NEW_LINE> <INDENT> if not hasattr(obj, 'jwp'): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return [ jwplatform.Video({'key': obj.jwp.key}).get_poster_url(width=width) for width in [1920, 1280, 640, 320] ] <NEW_LINE> <DEDENT> def get_embedUrl(self, obj): <NEW_LINE> <INDENT> return self._reverse('ui:media_embed', kwargs={'pk': obj.id}) <NEW_LINE> <DEDENT> def get_contentUrl(self, obj): <NEW_LINE> <INDENT> if not obj.downloadable_by_user: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._reverse('api:media_source', kwargs={'pk': obj.id}) <NEW_LINE> <DEDENT> def _reverse(self, *args, **kwargs): <NEW_LINE> <INDENT> uri = reverse(*args, **kwargs) <NEW_LINE> if 'request' not in self.context: <NEW_LINE> <INDENT> return uri <NEW_LINE> <DEDENT> return self.context['request'].build_absolute_uri(uri) | Serialise media items as a JSON-LD VideoObject (https://schema.org/VideoObject) taking into
account Google's recommended fields:
https://developers.google.com/search/docs/data-types/video. | 6259907f92d797404e3898a1 |
class LogoutView(APIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,) <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if allauth_settings.LOGOUT_ON_GET: <NEW_LINE> <INDENT> response = self.logout(request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = self.http_method_not_allowed(request, *args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> response = self.handle_exception(exc) <NEW_LINE> <DEDENT> return self.finalize_response(request, response, *args, **kwargs) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> return self.logout(request) <NEW_LINE> <DEDENT> def logout(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request.user.auth_token.delete() <NEW_LINE> <DEDENT> except (AttributeError, ObjectDoesNotExist): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> django_logout(request) <NEW_LINE> return Response({"success": _("Successfully logged out.")}, status=status.HTTP_200_OK) | Calls Django logout method and delete the Token object
assigned to the current User object.
Accepts/Returns nothing. | 6259907f23849d37ff852b43 |
class GetListResultSet(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. (The response from LittleSis.org.) | 6259907ff548e778e596d01c |
class TestAnalyzeClientMemoryNonexistantPluginWithExisting( TestAnalyzeClientMemoryNonexistantPlugin): <NEW_LINE> <INDENT> def setUpRequest(self): <NEW_LINE> <INDENT> self.args["request"].plugins = [ rdf_rekall_types.PluginRequest(plugin="pslist"), rdf_rekall_types.PluginRequest(plugin="idontexist")] | Tests flow failure when failing and non failing plugins run together. | 6259907f1f5feb6acb164684 |
class TestXmlNs0AddDiagramPictureRequest(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 testXmlNs0AddDiagramPictureRequest(self): <NEW_LINE> <INDENT> pass | XmlNs0AddDiagramPictureRequest unit test stubs | 6259907f5166f23b2e244e63 |
class NdpHeader(object): <NEW_LINE> <INDENT> swagger_types = { 'dst_ip': 'str', 'msg_type': 'str' } <NEW_LINE> attribute_map = { 'dst_ip': 'dst_ip', 'msg_type': 'msg_type' } <NEW_LINE> def __init__(self, dst_ip=None, msg_type='NEIGHBOR_SOLICITATION'): <NEW_LINE> <INDENT> self._dst_ip = None <NEW_LINE> self._msg_type = None <NEW_LINE> self.discriminator = None <NEW_LINE> if dst_ip is not None: <NEW_LINE> <INDENT> self.dst_ip = dst_ip <NEW_LINE> <DEDENT> if msg_type is not None: <NEW_LINE> <INDENT> self.msg_type = msg_type <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def dst_ip(self): <NEW_LINE> <INDENT> return self._dst_ip <NEW_LINE> <DEDENT> @dst_ip.setter <NEW_LINE> def dst_ip(self, dst_ip): <NEW_LINE> <INDENT> self._dst_ip = dst_ip <NEW_LINE> <DEDENT> @property <NEW_LINE> def msg_type(self): <NEW_LINE> <INDENT> return self._msg_type <NEW_LINE> <DEDENT> @msg_type.setter <NEW_LINE> def msg_type(self, msg_type): <NEW_LINE> <INDENT> allowed_values = ["NEIGHBOR_SOLICITATION", "NEIGHBOR_ADVERTISEMENT"] <NEW_LINE> if msg_type not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `msg_type` ({0}), must be one of {1}" .format(msg_type, allowed_values) ) <NEW_LINE> <DEDENT> self._msg_type = msg_type <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(NdpHeader, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, NdpHeader): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907f656771135c48ad75 |
class Cos(nn.Module): <NEW_LINE> <INDENT> def __init__(self, shot_num=4, sim_channel=512): <NEW_LINE> <INDENT> super(Cos, self).__init__() <NEW_LINE> self.shot_num = shot_num <NEW_LINE> self.channel = sim_channel <NEW_LINE> self.conv1 = nn.Conv2d(1, self.channel, kernel_size=(self.shot_num//2, 1)) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = x.view(-1, 1, x.shape[2], x.shape[3]) <NEW_LINE> part1, part2 = torch.split(x, [self.shot_num // 2] * 2, dim=2) <NEW_LINE> part1 = self.conv1(part1).squeeze() <NEW_LINE> part2 = self.conv1(part2).squeeze() <NEW_LINE> x = F.cosine_similarity(part1, part2, dim=2) <NEW_LINE> return x | Cosine similarity | 6259907f3346ee7daa3383a7 |
class LxmertTokenizerFast(BertTokenizerFast): <NEW_LINE> <INDENT> vocab_files_names = VOCAB_FILES_NAMES <NEW_LINE> pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP <NEW_LINE> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES <NEW_LINE> pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION | Construct a "fast" LXMERT tokenizer (backed by HuggingFace's `tokenizers` library).
:class:`~transformers.LxmertTokenizerFast` is identical to :class:`~transformers.BertTokenizerFast` and runs
end-to-end tokenization: punctuation splitting and wordpiece.
Refer to superclass :class:`~transformers.BertTokenizerFast` for usage examples and documentation concerning
parameters. | 6259907fa8370b77170f1e5b |
class CommandTransformer(Transformer): <NEW_LINE> <INDENT> start = Command <NEW_LINE> command_imitate_user = lambda _, x: ("imitate_user", x[0].value[2:-1]) <NEW_LINE> arguments = lambda _, x: ("arguments", x) <NEW_LINE> argument_depth = lambda _, x: ("depth", int(x[0].value)) <NEW_LINE> argument_prompt = lambda _, x: ("prompt", str(x[0].value[1:-1])) | Transform parse tree. | 6259907ff548e778e596d01d |
class FileLineProgressBar(tqdm): <NEW_LINE> <INDENT> def __init__(self, infile, outfile, **kwargs): <NEW_LINE> <INDENT> disable = False if "disable" not in kwargs else kwargs["disable"] <NEW_LINE> if infile is not None and (infile.name == "<stdin>"): <NEW_LINE> <INDENT> disable = True <NEW_LINE> <DEDENT> if outfile is not None and (outfile.name == "<stdout>"): <NEW_LINE> <INDENT> disable = True <NEW_LINE> <DEDENT> kwargs["disable"] = disable <NEW_LINE> kwargs["miniters"] = 1 <NEW_LINE> kwargs[ "bar_format" ] = "{l_bar}{bar}| Processed {n_fmt}/{total_fmt} lines of input file [{elapsed}<{remaining}, {rate_fmt}{postfix}]" <NEW_LINE> if (os.stat(infile.name).st_size / (1024 * 1024 * 1024)) > 1: <NEW_LINE> <INDENT> click.echo( click.style( f"Input File Size is {os.stat(infile.name).st_size / (1024*1024):.2f} MB, it may take a while to process. CTRL+C to stop.", fg="yellow", bold=True, ), err=True, ) <NEW_LINE> <DEDENT> with open(infile.name, "r", encoding="utf-8", errors="ignore") as f: <NEW_LINE> <INDENT> total_lines = sum(1 for _ in f) <NEW_LINE> <DEDENT> kwargs["total"] = total_lines if not disable else 1 <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def update_with_result( self, result, field="id", error_resource_type=None, error_parameter="ids" ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if "data" in result: <NEW_LINE> <INDENT> for item in result["data"]: <NEW_LINE> <INDENT> self.update() <NEW_LINE> <DEDENT> <DEDENT> if error_resource_type and "errors" in result: <NEW_LINE> <INDENT> for error in result["errors"]: <NEW_LINE> <INDENT> if ( "resource_type" in error and error["resource_type"] == error_resource_type ): <NEW_LINE> <INDENT> if ( "parameter" in error and error["parameter"] == error_parameter ): <NEW_LINE> <INDENT> self.update() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.error(f"Failed to update progress bar: {e}") | A progress bar based on input file line count. Counts an input file by lines.
This tries to read the entire file and count newlines in a robust way. | 6259907fd268445f2663a8a4 |
class ModuleList(Module): <NEW_LINE> <INDENT> def __init__(self, modules=None): <NEW_LINE> <INDENT> super(ModuleList, self).__init__() <NEW_LINE> if modules is not None: <NEW_LINE> <INDENT> self += modules <NEW_LINE> <DEDENT> <DEDENT> def _get_abs_string_index(self, idx): <NEW_LINE> <INDENT> idx = operator.index(idx) <NEW_LINE> if not (-len(self) <= idx < len(self)): <NEW_LINE> <INDENT> raise IndexError('index {} is out of range'.format(idx)) <NEW_LINE> <DEDENT> if idx < 0: <NEW_LINE> <INDENT> idx += len(self) <NEW_LINE> <DEDENT> return str(idx) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> if isinstance(idx, slice): <NEW_LINE> <INDENT> return ModuleList(list(self._modules.values())[idx]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._modules[self._get_abs_string_index(idx)] <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, idx, module): <NEW_LINE> <INDENT> idx = operator.index(idx) <NEW_LINE> return setattr(self, str(idx), module) <NEW_LINE> <DEDENT> def __delitem__(self, idx): <NEW_LINE> <INDENT> if isinstance(idx, slice): <NEW_LINE> <INDENT> for k in range(len(self._modules))[idx]: <NEW_LINE> <INDENT> delattr(self, str(k)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> delattr(self, self._get_abs_string_index(idx)) <NEW_LINE> <DEDENT> str_indices = [str(i) for i in range(len(self._modules))] <NEW_LINE> self._modules = OrderedDict(list(zip(str_indices, self._modules.values()))) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._modules) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._modules.values()) <NEW_LINE> <DEDENT> def __iadd__(self, modules): <NEW_LINE> <INDENT> return self.extend(modules) <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> keys = super(ModuleList, self).__dir__() <NEW_LINE> keys = [key for key in keys if not key.isdigit()] <NEW_LINE> return keys <NEW_LINE> <DEDENT> def append(self, module): <NEW_LINE> <INDENT> self.add_module(str(len(self)), module) <NEW_LINE> return self <NEW_LINE> <DEDENT> def extend(self, modules): <NEW_LINE> <INDENT> if not isinstance(modules, Iterable): <NEW_LINE> <INDENT> raise TypeError("ModuleList.extend should be called with an " "iterable, but got " + type(modules).__name__) <NEW_LINE> <DEDENT> offset = len(self) <NEW_LINE> for i, module in enumerate(modules): <NEW_LINE> <INDENT> self.add_module(str(offset + i), module) <NEW_LINE> <DEDENT> return self | Holds submodules in a list.
ModuleList can be indexed like a regular Python list, but modules it
contains are properly registered, and will be visible by all Module methods.
Arguments:
modules (iterable, optional): an iterable of modules to add
Example::
class MyModule(nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
def forward(self, x):
# ModuleList can act as an iterable, or be indexed using ints
for i, l in enumerate(self.linears):
x = self.linears[i // 2](x) + l(x)
return x | 6259907f63b5f9789fe86bf4 |
class FlowLayout(Widget): <NEW_LINE> <INDENT> def __init__(self, name, desc=None, prop=None, style=None, css_cls=None): <NEW_LINE> <INDENT> Widget.__init__(self, name, desc=desc, tag='div', prop=prop, style=style, css_cls=css_cls) <NEW_LINE> self.add_css_class('ui-widget') <NEW_LINE> self.add_css_class('ui-widget-content') <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> main_content = self._render_pre_content('div') <NEW_LINE> for widget in self._child_widgets: <NEW_LINE> <INDENT> main_content += widget.render() <NEW_LINE> <DEDENT> self._widget_content = main_content + self._render_post_content('div') <NEW_LINE> return self._widget_content | The simplest layout to put the widgets one after another in the flow
| 6259907ff548e778e596d01e |
@attr.s <NEW_LINE> class CommandLineBinding(object): <NEW_LINE> <INDENT> position = attr.ib(default=None) <NEW_LINE> prefix = attr.ib(default=None) <NEW_LINE> separate = attr.ib(default=True, type=bool) <NEW_LINE> itemSeparator = attr.ib(default=None) <NEW_LINE> valueFrom = attr.ib(default=None) <NEW_LINE> shellQuote = attr.ib(default=True, type=bool) <NEW_LINE> def to_argv(self, default=None): <NEW_LINE> <INDENT> if self.valueFrom is not None: <NEW_LINE> <INDENT> if self.valueFrom.startswith('$('): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> value = self.valueFrom <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = default <NEW_LINE> <DEDENT> def _convert(value): <NEW_LINE> <INDENT> if self.prefix: <NEW_LINE> <INDENT> if self.separate: <NEW_LINE> <INDENT> return [self.prefix, str(value)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self.prefix + str(value)] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return [str(value)] <NEW_LINE> <DEDENT> <DEDENT> if self.prefix is None and not self.separate: <NEW_LINE> <INDENT> raise ValueError('Can not separate an empty prefix.') <NEW_LINE> <DEDENT> if isinstance(value, list): <NEW_LINE> <INDENT> if self.itemSeparator and value: <NEW_LINE> <INDENT> value = self.itemSeparator.join([str(v) for v in value]) <NEW_LINE> <DEDENT> elif value: <NEW_LINE> <INDENT> return [a for v in value for a in _convert(v)] <NEW_LINE> <DEDENT> <DEDENT> elif (value is True or value is None) and self.prefix: <NEW_LINE> <INDENT> return [self.prefix] <NEW_LINE> <DEDENT> elif value is False or value is None or ( value is True and not self.prefix ): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return _convert(value) | Define the binding behavior when building the command line. | 6259907f91f36d47f2231bd4 |
class ParamSchema(dict): <NEW_LINE> <INDENT> def __init__(self, schema): <NEW_LINE> <INDENT> super(ParamSchema, self).__init__(schema) <NEW_LINE> <DEDENT> def do_check(self, name, value, keys): <NEW_LINE> <INDENT> for k in keys: <NEW_LINE> <INDENT> check = self.check(k) <NEW_LINE> const = self.get(k) <NEW_LINE> if check is None or const is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> check(name, value, const) <NEW_LINE> <DEDENT> <DEDENT> def raise_error(self, name, message, desc=True): <NEW_LINE> <INDENT> if desc: <NEW_LINE> <INDENT> message = self.get(CONSTRAINT_DESCRIPTION) or message <NEW_LINE> <DEDENT> raise ValueError('%s %s' % (name, message)) <NEW_LINE> <DEDENT> def check_allowed_values(self, name, val, const, desc=None): <NEW_LINE> <INDENT> vals = list(const) <NEW_LINE> if val not in vals: <NEW_LINE> <INDENT> err = '"%s" not in %s "%s"' % (val, ALLOWED_VALUES, vals) <NEW_LINE> self.raise_error(name, desc or err) <NEW_LINE> <DEDENT> <DEDENT> def check_allowed_pattern(self, name, val, p, desc=None): <NEW_LINE> <INDENT> m = re.match(p, val) <NEW_LINE> if m is None or m.end() != len(val): <NEW_LINE> <INDENT> err = '"%s" does not match %s "%s"' % (val, ALLOWED_PATTERN, p) <NEW_LINE> self.raise_error(name, desc or err) <NEW_LINE> <DEDENT> <DEDENT> def check_max_length(self, name, val, const, desc=None): <NEW_LINE> <INDENT> max_len = int(const) <NEW_LINE> val_len = len(val) <NEW_LINE> if val_len > max_len: <NEW_LINE> <INDENT> err = 'length (%d) overflows %s (%d)' % (val_len, MAX_LENGTH, max_len) <NEW_LINE> self.raise_error(name, desc or err) <NEW_LINE> <DEDENT> <DEDENT> def check_min_length(self, name, val, const, desc=None): <NEW_LINE> <INDENT> min_len = int(const) <NEW_LINE> val_len = len(val) <NEW_LINE> if val_len < min_len: <NEW_LINE> <INDENT> err = 'length (%d) underflows %s (%d)' % (val_len, MIN_LENGTH, min_len) <NEW_LINE> self.raise_error(name, desc or err) <NEW_LINE> <DEDENT> <DEDENT> def check_max_value(self, name, val, const, desc=None): <NEW_LINE> <INDENT> max_val = float(const) <NEW_LINE> val = float(val) <NEW_LINE> if val > max_val: <NEW_LINE> <INDENT> err = '%d overflows %s %d' % (val, MAX_VALUE, max_val) <NEW_LINE> self.raise_error(name, desc or err) <NEW_LINE> <DEDENT> <DEDENT> def check_min_value(self, name, val, const, desc=None): <NEW_LINE> <INDENT> min_val = float(const) <NEW_LINE> val = float(val) <NEW_LINE> if val < min_val: <NEW_LINE> <INDENT> err = '%d underflows %s %d' % (val, MIN_VALUE, min_val) <NEW_LINE> self.raise_error(name, desc or err) <NEW_LINE> <DEDENT> <DEDENT> def check(self, const_key): <NEW_LINE> <INDENT> return {ALLOWED_VALUES: self.check_allowed_values, ALLOWED_PATTERN: self.check_allowed_pattern, MAX_LENGTH: self.check_max_length, MIN_LENGTH: self.check_min_length, MAX_VALUE: self.check_max_value, MIN_VALUE: self.check_min_value}.get(const_key) | Parameter schema. | 6259907ffff4ab517ebcf2a4 |
class CursorBase(MySQLCursorAbstract): <NEW_LINE> <INDENT> _raw = False <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._description = None <NEW_LINE> self._rowcount = -1 <NEW_LINE> self._last_insert_id = None <NEW_LINE> self.arraysize = 1 <NEW_LINE> super(CursorBase, self).__init__() <NEW_LINE> <DEDENT> def callproc(self, procname: object, args: object = ()) -> object: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def execute(self, operation, params=(), multi=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def executemany(self, operation, seqparams): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fetchone(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fetchmany(self, size=1): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fetchall(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def nextset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setinputsizes(self, sizes): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setoutputsize(self, size, column=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def reset(self, free=True): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @property <NEW_LINE> def rowcount(self): <NEW_LINE> <INDENT> return self._rowcount <NEW_LINE> <DEDENT> @property <NEW_LINE> def lastrowid(self): <NEW_LINE> <INDENT> return self._last_insert_id | Base for defining MySQLCursor. This class is a skeleton and defines
methods and members as required for the Python Database API
Specification v2.0.
It's better to inherite from MySQLCursor. | 6259907f656771135c48ad76 |
class StrategyMinimax(Strategy): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return "StrategyMinimax()" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, StrategyMinimax) <NEW_LINE> <DEDENT> def suggest_move(self, state): <NEW_LINE> <INDENT> self.maximizer = state.next_player <NEW_LINE> return self.best_move(state)[1] <NEW_LINE> <DEDENT> def best_move(self, state, alpha=-1, beta=-1): <NEW_LINE> <INDENT> value = -1.0 <NEW_LINE> move_list = state.possible_next_moves() <NEW_LINE> if not move_list: <NEW_LINE> <INDENT> return [state.outcome(), None] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = -1.0 <NEW_LINE> gather = [] <NEW_LINE> if state.next_player == self.maximizer: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < len(move_list) and (value < beta * -1.0): <NEW_LINE> <INDENT> move = move_list[i] <NEW_LINE> score = (self.best_move(state.apply_move(move), alpha, beta)[0] * -1) <NEW_LINE> value = max([score, value]) <NEW_LINE> alpha = max([alpha, value]) <NEW_LINE> gather.append([score, move]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < len(move_list) and (value < alpha * -1.0): <NEW_LINE> <INDENT> move = move_list[i] <NEW_LINE> score = (self.best_move(state.apply_move(move), alpha, beta)[0] * -1) <NEW_LINE> value = max([score, value]) <NEW_LINE> beta = max([beta, value]) <NEW_LINE> gather.append([score, move]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> move = gather[0] <NEW_LINE> for item in gather: <NEW_LINE> <INDENT> if move[0] < item[0]: <NEW_LINE> <INDENT> move = item <NEW_LINE> <DEDENT> <DEDENT> return move | Interface to suggest moves based on the Minimax Pruning algorithm. | 6259907f2c8b7c6e89bd5272 |
class RotYGate(eigen_gate.EigenGate, gate_features.TextDiagrammable, gate_features.SingleQubitGate, gate_features.QasmConvertibleGate): <NEW_LINE> <INDENT> def __init__(self, *, half_turns: Optional[Union[value.Symbol, float]] = None, rads: Optional[float] = None, degs: Optional[float] = None) -> None: <NEW_LINE> <INDENT> super().__init__(exponent=value.chosen_angle_to_half_turns( half_turns=half_turns, rads=rads, degs=degs)) <NEW_LINE> <DEDENT> def _eigen_components(self): <NEW_LINE> <INDENT> return [ (0, np.array([[0.5, -0.5j], [0.5j, 0.5]])), (1, np.array([[0.5, 0.5j], [-0.5j, 0.5]])), ] <NEW_LINE> <DEDENT> def _canonical_exponent_period(self) -> Optional[float]: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> def _with_exponent(self, exponent: Union[value.Symbol, float]) -> 'RotYGate': <NEW_LINE> <INDENT> return RotYGate(half_turns=exponent) <NEW_LINE> <DEDENT> @property <NEW_LINE> def half_turns(self) -> Union[value.Symbol, float]: <NEW_LINE> <INDENT> return self._exponent <NEW_LINE> <DEDENT> def text_diagram_info(self, args: gate_features.TextDiagramInfoArgs ) -> gate_features.TextDiagramInfo: <NEW_LINE> <INDENT> return gate_features.TextDiagramInfo( wire_symbols=('Y',), exponent=self._exponent) <NEW_LINE> <DEDENT> def known_qasm_output(self, qubits: Tuple[raw_types.QubitId, ...], args: gate_features.QasmOutputArgs) -> Optional[str]: <NEW_LINE> <INDENT> args.validate_version('2.0') <NEW_LINE> if self.half_turns == 1: <NEW_LINE> <INDENT> return args.format('y {0};\n', qubits[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return args.format('ry({0:half_turns}) {1};\n', self.half_turns, qubits[0]) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> if self.half_turns == 1: <NEW_LINE> <INDENT> return 'Y' <NEW_LINE> <DEDENT> return 'Y**{!r}'.format(self.half_turns) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> if self.half_turns == 1: <NEW_LINE> <INDENT> return 'cirq.Y' <NEW_LINE> <DEDENT> return '(cirq.Y**{!r})'.format(self.half_turns) | Fixed rotation around the Y axis of the Bloch sphere. | 6259907f099cdd3c63676140 |
@dataclass(init=True, repr=True, eq=True, order=False, frozen=True) <NEW_LINE> class Point: <NEW_LINE> <INDENT> x: int <NEW_LINE> y: int <NEW_LINE> def __add__(self, other: "Point") -> "Point": <NEW_LINE> <INDENT> return Point(self.x + other.x, self.y + other.y) <NEW_LINE> <DEDENT> def __sub__(self, other: "Point") -> "Point": <NEW_LINE> <INDENT> return Point(self.x - other.x, self.y - other.y) <NEW_LINE> <DEDENT> def __mul__(self, other: int) -> "Point": <NEW_LINE> <INDENT> return Point(self.x * other, self.y * other) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"({self.x}, {self.y})" <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator[int]: <NEW_LINE> <INDENT> yield self.x <NEW_LINE> yield self.y <NEW_LINE> <DEDENT> @property <NEW_LINE> def NW(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.NW.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def N(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.N.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def NE(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.NE.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def W(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.W.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def E(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.E.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def SW(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.SW.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def S(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.S.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def SE(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.SE.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ORIGIN(self) -> "Point": <NEW_LINE> <INDENT> return self._direction(Direction.ORIGIN.value) <NEW_LINE> <DEDENT> def _direction(self, point) -> "Point": <NEW_LINE> <INDENT> return Point(self.x + point.x, self.y + point.y) <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_neighbors(self) -> Generator[Point]: <NEW_LINE> <INDENT> for direction in [ self.N, self.NE, self.E, self.SE, self.S, self.SW, self.W, self.NW, ]: <NEW_LINE> <INDENT> yield direction <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def direct_neighbors(self) -> Point: <NEW_LINE> <INDENT> for direction in [self.N, self.E, self.S, self.W]: <NEW_LINE> <INDENT> yield direction <NEW_LINE> <DEDENT> <DEDENT> def distance_to(self, p2) -> float: <NEW_LINE> <INDENT> x, y = self - p2 <NEW_LINE> return math.sqrt(x ** 2 + y ** 2) | A simple container to represent a single point in the map's grid
added functionality for adding, subtracting, or comparing equality of two points
can be iterated to get x- and y-coordinates
Args:
x- and y-coordinate for the point | 6259907ff9cc0f698b1c6013 |
class Raindrop: <NEW_LINE> <INDENT> strSrf = 'Not defined' <NEW_LINE> def __init__(self,p3dLocation): <NEW_LINE> <INDENT> self.p3dLocation = p3dLocation <NEW_LINE> <DEDENT> def falls(): <NEW_LINE> <INDENT> p3dProjectedPt = rs.ProjectPointToSurface(self.p3dLocation,strSrf,(0,0,-1)) <NEW_LINE> self.p3dLocation = p3dProjectedPt | Implements a raindrop over a surface | 6259907f283ffb24f3cf532d |
class RAT6169(ratreleases.RatRelease6): <NEW_LINE> <INDENT> def __init__(self, system): <NEW_LINE> <INDENT> super(RAT6169, self).__init__('rat-6.16.9', system, 'root-5.34.36', '6.16.9') | Rat release-6.16.9, install package. | 6259907f4428ac0f6e659fbc |
class RSAPublicKey(_RSAKey): <NEW_LINE> <INDENT> def __init__(self, pub, pub_key): <NEW_LINE> <INDENT> super().__init__(pub) <NEW_LINE> self._pub_key = pub_key <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def construct(cls, n, e): <NEW_LINE> <INDENT> pub = rsa.RSAPublicNumbers(e, n) <NEW_LINE> pub_key = pub.public_key(default_backend()) <NEW_LINE> return cls(pub, pub_key) <NEW_LINE> <DEDENT> def verify(self, data, sig): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._pub_key.verify(sig, data, PKCS1v15(), SHA1()) <NEW_LINE> return True <NEW_LINE> <DEDENT> except InvalidSignature: <NEW_LINE> <INDENT> return False | A shim around PyCA for RSA public keys | 6259907f66673b3332c31e8d |
class SGDW(Optimizer): <NEW_LINE> <INDENT> def __init__(self, params, lr=0.01, momentum=0.9, dampening=0, weight_decay=0, nesterov=False): <NEW_LINE> <INDENT> if lr <= 0.0: <NEW_LINE> <INDENT> raise ValueError("Invalid learning rate: {}".format(lr)) <NEW_LINE> <DEDENT> if momentum < 0.0: <NEW_LINE> <INDENT> raise ValueError("Invalid momentum value: {}".format(momentum)) <NEW_LINE> <DEDENT> if weight_decay < 0.0: <NEW_LINE> <INDENT> raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) <NEW_LINE> <DEDENT> defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) <NEW_LINE> if nesterov and (momentum <= 0 or dampening != 0): <NEW_LINE> <INDENT> raise ValueError("Nesterov momentum requires a momentum and zero dampening") <NEW_LINE> <DEDENT> super(SGDW, self).__init__(params, defaults) <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> super(SGDW, self).__setstate__(state) <NEW_LINE> for group in self.param_groups: <NEW_LINE> <INDENT> group.setdefault('nesterov', False) <NEW_LINE> <DEDENT> <DEDENT> def step(self, closure=None): <NEW_LINE> <INDENT> loss = None <NEW_LINE> if closure is not None: <NEW_LINE> <INDENT> loss = closure() <NEW_LINE> <DEDENT> for group in self.param_groups: <NEW_LINE> <INDENT> weight_decay = group['weight_decay'] <NEW_LINE> momentum = group['momentum'] <NEW_LINE> dampening = group['dampening'] <NEW_LINE> nesterov = group['nesterov'] <NEW_LINE> for p in group['params']: <NEW_LINE> <INDENT> if p.grad is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> d_p = p.grad.data <NEW_LINE> if momentum != 0: <NEW_LINE> <INDENT> param_state = self.state[p] <NEW_LINE> if 'momentum_buffer' not in param_state: <NEW_LINE> <INDENT> buf = param_state['momentum_buffer'] = torch.zeros_like(p.data) <NEW_LINE> buf.mul_(momentum).add_(d_p) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buf = param_state['momentum_buffer'] <NEW_LINE> buf.mul_(momentum).add_(d_p, alpha=1 - dampening) <NEW_LINE> <DEDENT> if nesterov: <NEW_LINE> <INDENT> d_p = d_p.add(buf, alpha=momentum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d_p = buf <NEW_LINE> <DEDENT> <DEDENT> if weight_decay != 0: <NEW_LINE> <INDENT> p.data.add_(p.data, alpha=-weight_decay) <NEW_LINE> <DEDENT> p.data.add_(d_p, alpha=-group['lr']) <NEW_LINE> <DEDENT> <DEDENT> return loss | Implements stochastic gradient descent (optionally with momentum).
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
momentum (float, optional): momentum factor (default: 0)
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
dampening (float, optional): dampening for momentum (default: 0)
nesterov (bool, optional): enables Nesterov momentum (default: False) | 6259907fbe7bc26dc9252b9c |
class Users: <NEW_LINE> <INDENT> def __init__(self, commands_file): <NEW_LINE> <INDENT> self.users = None <NEW_LINE> self.users_file = commands_file <NEW_LINE> self.load() <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.users_file, 'r', encoding='utf-8') as f: <NEW_LINE> <INDENT> self.users = dill.load(f) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> self.users = defaultdict(lambda: {'grade': 0, 'gold': 0, 'is_ignored': False, 'is_admin': False}) <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> with open(self.users_file, 'w', encoding='utf-8') as f: <NEW_LINE> <INDENT> dill.dump(self.users, f) | 슬랙 그룹 내 유저들의 정보를 저장하는 클래스.
users: {'id': {'grade': Integer, 'gold': Integer, 'is_ignored': Boolean, 'is_admin': Boolean}} | 6259907f283ffb24f3cf532e |
class Other(Definition): <NEW_LINE> <INDENT> def __init__(self, definition: str) -> None: <NEW_LINE> <INDENT> self.definition = definition <NEW_LINE> super().__init__(DefinitionType.other, [definition]) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return self.definition | Other definitions. | 6259907f92d797404e3898a3 |
class Configure(object): <NEW_LINE> <INDENT> def __init__(self, **initial_values): <NEW_LINE> <INDENT> self._properties = dict() <NEW_LINE> for x in initial_values: <NEW_LINE> <INDENT> self._properties[x] = _C(initial_values[x]) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, pname, value): <NEW_LINE> <INDENT> if not isinstance(value, ConfigValue): <NEW_LINE> <INDENT> value = _C(value) <NEW_LINE> <DEDENT> if (pname in self._properties) and isinstance( self._properties[pname], _link): <NEW_LINE> <INDENT> for x in self._properties[pname].members: <NEW_LINE> <INDENT> self._properties[x] = value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._properties[pname] = value <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, pname): <NEW_LINE> <INDENT> return self._properties[pname].get() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._properties) <NEW_LINE> <DEDENT> def link(self, *names): <NEW_LINE> <INDENT> l = _link(names, self) <NEW_LINE> for n in names: <NEW_LINE> <INDENT> self._properties[n] = l <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, thing): <NEW_LINE> <INDENT> return (thing in self._properties) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{\n"+(",\n".join( "\"%s\" : \"%s\"" % (k, self._properties[k]) for k in self._properties)) + "\n}" <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._properties) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def open(cls, file_name): <NEW_LINE> <INDENT> import json <NEW_LINE> f = open(file_name) <NEW_LINE> c = Configure() <NEW_LINE> d = json.load(f) <NEW_LINE> for k in d: <NEW_LINE> <INDENT> value = d[k] <NEW_LINE> if isinstance(value, six.string_types): <NEW_LINE> <INDENT> if value.startswith("BASE/"): <NEW_LINE> <INDENT> from pkg_resources import Requirement, resource_filename <NEW_LINE> value = value[4:] <NEW_LINE> value = resource_filename( Requirement.parse('PyOpenWorm'), value) <NEW_LINE> d[k] = value <NEW_LINE> <DEDENT> <DEDENT> c[k] = _C(d[k]) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> c['configure.file_location'] = file_name <NEW_LINE> return c <NEW_LINE> <DEDENT> def copy(self, other): <NEW_LINE> <INDENT> if isinstance(other, Configure): <NEW_LINE> <INDENT> self._properties = dict(other._properties) <NEW_LINE> <DEDENT> elif isinstance(other, dict): <NEW_LINE> <INDENT> for x in other: <NEW_LINE> <INDENT> self[x] = other[x] <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def get(self, pname, default=False): <NEW_LINE> <INDENT> if pname in self._properties: <NEW_LINE> <INDENT> return self._properties[pname].get() <NEW_LINE> <DEDENT> elif default: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError(pname) | A simple configuration object. Enables setting and getting key-value pairs | 6259907f3317a56b869bf28d |
class ttHFatJetAnalyzer( Analyzer ): <NEW_LINE> <INDENT> def __init__(self, cfg_ana, cfg_comp, looperName): <NEW_LINE> <INDENT> super(ttHFatJetAnalyzer,self).__init__(cfg_ana, cfg_comp, looperName) <NEW_LINE> self.jetLepDR = self.cfg_ana.jetLepDR if hasattr(self.cfg_ana, 'jetLepDR') else 0.5 <NEW_LINE> self.lepPtMin = self.cfg_ana.minLepPt if hasattr(self.cfg_ana, 'minLepPt') else -1 <NEW_LINE> <DEDENT> def declareHandles(self): <NEW_LINE> <INDENT> super(ttHFatJetAnalyzer, self).declareHandles() <NEW_LINE> self.handles['jets'] = AutoHandle( self.cfg_ana.jetCol, 'std::vector<pat::Jet>' ) <NEW_LINE> <DEDENT> def beginLoop(self, setup): <NEW_LINE> <INDENT> super(ttHFatJetAnalyzer,self).beginLoop(setup) <NEW_LINE> <DEDENT> def process(self, event): <NEW_LINE> <INDENT> self.readCollections( event.input ) <NEW_LINE> allJets = map(Jet, self.handles['jets'].product()) <NEW_LINE> event.fatJets = [] <NEW_LINE> event.fatJetsNoID = [] <NEW_LINE> for jet in allJets: <NEW_LINE> <INDENT> if self.testJetNoID( jet ): <NEW_LINE> <INDENT> event.fatJetsNoID.append(jet) <NEW_LINE> if self.testJetID (jet ): <NEW_LINE> <INDENT> event.fatJets.append(jet) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def testJetID(self, jet): <NEW_LINE> <INDENT> jet.pfJetIdPassed = jet.jetID('POG_PFID_Loose') <NEW_LINE> if self.cfg_ana.relaxJetId: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return jet.pfJetIdPassed <NEW_LINE> <DEDENT> <DEDENT> def testJetNoID( self, jet ): <NEW_LINE> <INDENT> return jet.pt() > self.cfg_ana.jetPt and abs( jet.eta() ) < self.cfg_ana.jetEta; | Taken from RootTools.JetAnalyzer, simplified, modified, added corrections | 6259907f91f36d47f2231bd5 |
class root_locus_sketch_two_pole_locations(root_locus_sketch): <NEW_LINE> <INDENT> def __init__(self, G1, G2, label_offsets=[0.2+0.2j, 0.2+0.2j], markers=['bo','g^'], inds=[1,2], **kwargs): <NEW_LINE> <INDENT> root_locus_sketch.__init__(self, **kwargs) <NEW_LINE> self.G1 = G1 <NEW_LINE> self.G2 = G2 <NEW_LINE> self.label_offsets = label_offsets <NEW_LINE> self.markers = markers <NEW_LINE> self.inds = inds <NEW_LINE> <DEDENT> def draw_and_label_poles(self): <NEW_LINE> <INDENT> p1 = self.G1.pole()[0] <NEW_LINE> p2 = self.G2.pole()[0] <NEW_LINE> for p, m, lo, ind in zip([p1,p2], self.markers, self.label_offsets, self.inds): <NEW_LINE> <INDENT> p = np.real(p) + 1j*np.abs(np.imag(p)) <NEW_LINE> self.draw_marker(p, style=m) <NEW_LINE> self.draw_marker(np.conj(p), style=m) <NEW_LINE> mytext = '$G_{%i}$' % ind <NEW_LINE> self.add_text(p, mytext, xoffset=np.real(lo), yoffset=np.imag(lo)) <NEW_LINE> <DEDENT> <DEDENT> def main(self, ticks=True): <NEW_LINE> <INDENT> self.main_axis(ticks=ticks) <NEW_LINE> self.draw_and_label_poles() | A class for generating pole locations plots for comparing two
TFs and their step responses. | 6259907ffff4ab517ebcf2a6 |
class TestFunc(unittest.TestCase): <NEW_LINE> <INDENT> def test(self): <NEW_LINE> <INDENT> target = Solution() <NEW_LINE> expected = [2,3] <NEW_LINE> test = [4,3,2,7,8,2,3,1] <NEW_LINE> self.assertEqual(expected, target.findDuplicates(test)) | Test fuction | 6259907fe1aae11d1e7cf559 |
@ddt.ddt <NEW_LINE> @httpretty.activate <NEW_LINE> class TestAccessTokenExchangeView(ThirdPartyOAuthTestMixinGoogle, ThirdPartyOAuthTestMixin, _DispatchingViewTestCase): <NEW_LINE> <INDENT> view_class = views.AccessTokenExchangeView <NEW_LINE> url = reverse('exchange_access_token', kwargs={'backend': 'google-oauth2'}) <NEW_LINE> def _post_body(self, user, client, token_type=None): <NEW_LINE> <INDENT> return { 'client_id': client.client_id, 'access_token': self.access_token, } <NEW_LINE> <DEDENT> @ddt.data('dop_app', 'dot_app') <NEW_LINE> def test_access_token_exchange_calls_dispatched_view(self, client_attr): <NEW_LINE> <INDENT> client = getattr(self, client_attr) <NEW_LINE> self.oauth_client = client <NEW_LINE> self._setup_provider_response(success=True) <NEW_LINE> response = self._post_request(self.user, client) <NEW_LINE> self.assertEqual(response.status_code, 200) | Test class for AccessTokenExchangeView | 6259907f2c8b7c6e89bd5274 |
@pykka.traversable <NEW_LINE> class PlaybackProvider: <NEW_LINE> <INDENT> def __init__(self, audio: Any, backend: Backend) -> None: <NEW_LINE> <INDENT> self.audio = audio <NEW_LINE> self.backend = backend <NEW_LINE> <DEDENT> def pause(self) -> bool: <NEW_LINE> <INDENT> return self.audio.pause_playback().get() <NEW_LINE> <DEDENT> def play(self) -> bool: <NEW_LINE> <INDENT> return self.audio.start_playback().get() <NEW_LINE> <DEDENT> def prepare_change(self) -> None: <NEW_LINE> <INDENT> self.audio.prepare_change().get() <NEW_LINE> <DEDENT> def translate_uri(self, uri: Uri) -> Optional[Uri]: <NEW_LINE> <INDENT> return uri <NEW_LINE> <DEDENT> def is_live(self, uri: Uri) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def should_download(self, uri: Uri) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def change_track(self, track: Track) -> bool: <NEW_LINE> <INDENT> uri = self.translate_uri(track.uri) <NEW_LINE> if uri != track.uri: <NEW_LINE> <INDENT> logger.debug("Backend translated URI from %s to %s", track.uri, uri) <NEW_LINE> <DEDENT> if not uri: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.audio.set_uri( uri, live_stream=self.is_live(uri), download=self.should_download(uri), ).get() <NEW_LINE> return True <NEW_LINE> <DEDENT> def resume(self) -> bool: <NEW_LINE> <INDENT> return self.audio.start_playback().get() <NEW_LINE> <DEDENT> def seek(self, time_position: int) -> bool: <NEW_LINE> <INDENT> return self.audio.set_position(time_position).get() <NEW_LINE> <DEDENT> def stop(self) -> bool: <NEW_LINE> <INDENT> return self.audio.stop_playback().get() <NEW_LINE> <DEDENT> def get_time_position(self) -> int: <NEW_LINE> <INDENT> return self.audio.get_position().get() | :param audio: the audio actor
:type audio: actor proxy to an instance of :class:`mopidy.audio.Audio`
:param backend: the backend
:type backend: :class:`mopidy.backend.Backend` | 6259907f99fddb7c1ca63b20 |
class Project(AWSObject): <NEW_LINE> <INDENT> resource_type = "AWS::Rekognition::Project" <NEW_LINE> props: PropsDictType = { "ProjectName": (str, True), } | `Project <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rekognition-project.html>`__ | 6259907f8a349b6b43687cec |
class InlineModelFormList(InlineFieldList): <NEW_LINE> <INDENT> form_field_type = InlineModelFormField <NEW_LINE> def __init__(self, form, session, model, prop, inline_view, **kwargs): <NEW_LINE> <INDENT> self.form = form <NEW_LINE> self.session = session <NEW_LINE> self.model = model <NEW_LINE> self.prop = prop <NEW_LINE> self.inline_view = inline_view <NEW_LINE> self._pk = get_primary_key(model) <NEW_LINE> super(InlineModelFormList, self).__init__(self.form_field_type(form, self._pk), **kwargs) <NEW_LINE> <DEDENT> def display_row_controls(self, field): <NEW_LINE> <INDENT> return field.get_pk() is not None <NEW_LINE> <DEDENT> def populate_obj(self, obj, name): <NEW_LINE> <INDENT> values = getattr(obj, name, None) <NEW_LINE> if values is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pk_map = dict((str(getattr(v, self._pk)), v) for v in values) <NEW_LINE> for field in self.entries: <NEW_LINE> <INDENT> field_id = field.get_pk() <NEW_LINE> if field_id in pk_map: <NEW_LINE> <INDENT> model = pk_map[field_id] <NEW_LINE> if self.should_delete(field): <NEW_LINE> <INDENT> self.session.delete(model) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> model = self.model() <NEW_LINE> values.append(model) <NEW_LINE> <DEDENT> field.populate_obj(model, None) <NEW_LINE> self.inline_view.on_model_change(field, model) | Customized inline model form list field. | 6259907f7cff6e4e811b74d0 |
class ProtsimLine(object): <NEW_LINE> <INDENT> def __init__(self, text=None): <NEW_LINE> <INDENT> self.org = "" <NEW_LINE> self.protgi = "" <NEW_LINE> self.protid = "" <NEW_LINE> self.pct = "" <NEW_LINE> self.aln = "" <NEW_LINE> if text is not None: <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self._init_from_text(text) <NEW_LINE> <DEDENT> <DEDENT> def _init_from_text(self, text): <NEW_LINE> <INDENT> parts = text.split("; ") <NEW_LINE> for part in parts: <NEW_LINE> <INDENT> key, val = part.split("=") <NEW_LINE> setattr(self, key.lower(), val) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.text | Store the information for one PROTSIM line from a Unigene file.
Initialize with the text part of the PROTSIM line, or nothing.
Attributes and descriptions (access as LOWER CASE)
ORG= Organism
PROTGI= Sequence GI of protein
PROTID= Sequence ID of protein
PCT= Percent alignment
ALN= length of aligned region (aa) | 6259907f60cbc95b06365ab4 |
class MainViewTestCase(ListItem.ClickAppTestCase): <NEW_LINE> <INDENT> def test_initial_label(self): <NEW_LINE> <INDENT> app = self.launch_application() <NEW_LINE> label = app.main_view.select_single(objectName='label') <NEW_LINE> self.assertThat(label.text, Equals('Hello..')) <NEW_LINE> <DEDENT> def test_click_button_should_update_label(self): <NEW_LINE> <INDENT> app = self.launch_application() <NEW_LINE> button = app.main_view.select_single(objectName='button') <NEW_LINE> app.pointing_device.click_object(button) <NEW_LINE> label = app.main_view.select_single(objectName='label') <NEW_LINE> self.assertThat(label.text, Eventually(Equals('..world!'))) | Generic tests for the Hello World | 6259907f5fcc89381b266ea4 |
class TerminateType_(SamlBase): <NEW_LINE> <INDENT> c_tag = 'TerminateType' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = SamlBase.c_children.copy() <NEW_LINE> c_attributes = SamlBase.c_attributes.copy() <NEW_LINE> c_child_order = SamlBase.c_child_order[:] <NEW_LINE> c_cardinality = SamlBase.c_cardinality.copy() | The urn:oasis:names:tc:SAML:2.0:protocol:TerminateType element | 6259907fec188e330fdfa33a |
class DeleteMediaByID(RestServlet): <NEW_LINE> <INDENT> PATTERNS = admin_patterns("/media/(?P<server_name>[^/]+)/(?P<media_id>[^/]+)") <NEW_LINE> def __init__(self, hs: "HomeServer"): <NEW_LINE> <INDENT> self.store = hs.get_datastore() <NEW_LINE> self.auth = hs.get_auth() <NEW_LINE> self.server_name = hs.hostname <NEW_LINE> self.media_repository = hs.get_media_repository() <NEW_LINE> <DEDENT> async def on_DELETE( self, request: SynapseRequest, server_name: str, media_id: str ) -> Tuple[int, JsonDict]: <NEW_LINE> <INDENT> await assert_requester_is_admin(self.auth, request) <NEW_LINE> if self.server_name != server_name: <NEW_LINE> <INDENT> raise SynapseError(400, "Can only delete local media") <NEW_LINE> <DEDENT> if await self.store.get_local_media(media_id) is None: <NEW_LINE> <INDENT> raise NotFoundError("Unknown media") <NEW_LINE> <DEDENT> logging.info("Deleting local media by ID: %s", media_id) <NEW_LINE> deleted_media, total = await self.media_repository.delete_local_media(media_id) <NEW_LINE> return 200, {"deleted_media": deleted_media, "total": total} | Delete local media by a given ID. Removes it from this server. | 6259907f7d847024c075de6d |
class StudentBiasedCoinModel(SkillModel): <NEW_LINE> <INDENT> def __init__( self, history, filtered_history=None, name_of_user_id='student_id'): <NEW_LINE> <INDENT> self.history = history <NEW_LINE> if filtered_history is None: <NEW_LINE> <INDENT> _logger.warning( 'No filtered history available to train biased coin model. Using full history...') <NEW_LINE> self.filtered_history = history.data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filtered_history = filtered_history <NEW_LINE> <DEDENT> self.name_of_user_id = name_of_user_id <NEW_LINE> self.idx_of_user_id = {k: i for i, k in enumerate(self.history.data[self.name_of_user_id].unique())} <NEW_LINE> self._student_pass_likelihoods = np.zeros(len(self.idx_of_user_id)) <NEW_LINE> <DEDENT> def fit(self): <NEW_LINE> <INDENT> df = self.filtered_history[self.filtered_history['module_type'] == datatools.AssessmentInteraction.MODULETYPE] <NEW_LINE> df = df.groupby(self.name_of_user_id) <NEW_LINE> def student_pass_rate(student_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> outcomes = df.get_group(student_id)['outcome'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return 0.5 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> num_passes = outcomes.value_counts()[True] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> num_passes = 0 <NEW_LINE> <DEDENT> return (num_passes + 1) / (len(outcomes) + 2) <NEW_LINE> <DEDENT> for user_id, user_idx in self.idx_of_user_id.iteritems(): <NEW_LINE> <INDENT> self._student_pass_likelihoods[user_idx] = student_pass_rate(user_id) <NEW_LINE> <DEDENT> <DEDENT> def assessment_outcome_log_likelihood( self, interaction, outcome=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if outcome is None: <NEW_LINE> <INDENT> outcome = interaction['outcome'] <NEW_LINE> <DEDENT> user_id = interaction[self.name_of_user_id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError('Interaction is missing fields!') <NEW_LINE> <DEDENT> student_idx = self.idx_of_user_id[student_id] <NEW_LINE> pass_likelihood = self._student_pass_likelihoods[student_idx] <NEW_LINE> outcome_likelihood = pass_likelihood if outcome else (1 - pass_likelihood) <NEW_LINE> return math.log(outcome_likelihood) <NEW_LINE> <DEDENT> def assessment_pass_likelihoods(self, df): <NEW_LINE> <INDENT> return np.array([self._student_pass_likelihoods[user_idx] for user_idx in df[self.name_of_user_id].map(self.idx_of_user_id)]) | Class for simple skill model where students are modeled as biased
coins that flip to pass/fail assessments
Can be considered a zero-parameter logistic model from Item Response Theory (0PL IRT) | 6259907ff548e778e596d022 |
class LinuxRemovableDrivePlugin(RemovableDrivePlugin.RemovableDrivePlugin): <NEW_LINE> <INDENT> def checkRemovableDrives(self): <NEW_LINE> <INDENT> drives = {} <NEW_LINE> for volume in glob.glob("/media/*"): <NEW_LINE> <INDENT> if os.path.ismount(volume): <NEW_LINE> <INDENT> drives[volume] = os.path.basename(volume) <NEW_LINE> <DEDENT> elif volume == "/media/"+os.getenv("USER"): <NEW_LINE> <INDENT> for volume in glob.glob("/media/"+os.getenv("USER")+"/*"): <NEW_LINE> <INDENT> if os.path.ismount(volume): <NEW_LINE> <INDENT> drives[volume] = os.path.basename(volume) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for volume in glob.glob("/run/media/" + os.getenv("USER") + "/*"): <NEW_LINE> <INDENT> if os.path.ismount(volume): <NEW_LINE> <INDENT> drives[volume] = os.path.basename(volume) <NEW_LINE> <DEDENT> <DEDENT> return drives <NEW_LINE> <DEDENT> def performEjectDevice(self, device): <NEW_LINE> <INDENT> p = subprocess.Popen(["umount", device.getId()], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> output = p.communicate() <NEW_LINE> Logger.log("d", "umount returned: %s.", repr(output)) <NEW_LINE> return_code = p.wait() <NEW_LINE> if return_code != 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Support for removable devices on Linux.
TODO: This code uses the most basic interfaces for handling this.
We should instead use UDisks2 to handle mount/unmount and hotplugging events. | 6259907f3d592f4c4edbc8a7 |
class SongMetadataBase: <NEW_LINE> <INDENT> def __init__(self, title=None, url=None, query=None): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.search_query = query <NEW_LINE> self.URL = url <NEW_LINE> self.better_search_kw = [ ] <NEW_LINE> <DEDENT> def _add_better_search_words(self): <NEW_LINE> <INDENT> for kw in self.better_search_kw: <NEW_LINE> <INDENT> self.search_query += kw <NEW_LINE> <DEDENT> <DEDENT> def _remove_duplicates(self): <NEW_LINE> <INDENT> self.search_query = remove_duplicates(self.search_query) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"(title={self.title}, url={self.URL}, search_query={self.search_query})" <NEW_LINE> <DEDENT> def content(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() | Base class to store song metadata. | 6259907f2c8b7c6e89bd5276 |
class ShowtimeViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Showtime.objects.all() <NEW_LINE> serializer_class = ShowtimeSerializer <NEW_LINE> permission_classes = [IsThisTheaterAdminOrReadOnly] <NEW_LINE> def create(self, request): <NEW_LINE> <INDENT> serializer = ShowtimeSerializer(data=request.data, partial=True) <NEW_LINE> if not serializer.is_valid(): <NEW_LINE> <INDENT> return Response(serializer.errors, status=400) <NEW_LINE> <DEDENT> bookings = [] <NEW_LINE> seat_num = 1 <NEW_LINE> showtime = serializer.save() <NEW_LINE> auditorium = Auditorium.objects.get(id=request.data['auditorium']) <NEW_LINE> layout = auditorium.layout['layout'] <NEW_LINE> for row in layout: <NEW_LINE> <INDENT> for seat in row: <NEW_LINE> <INDENT> bookings.append(Booking(showtime_id=showtime.id, seat=seat_num, user_id=None)) <NEW_LINE> seat_num += 1 <NEW_LINE> <DEDENT> <DEDENT> Booking.objects.bulk_create(bookings) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def destroy(self, request, pk=None): <NEW_LINE> <INDENT> showtime = get_object_or_404(Showtime, id=pk) <NEW_LINE> self.check_object_permissions(request, showtime) <NEW_LINE> showtime.delete() <NEW_LINE> return Response({'message': 'Showtime successfully deleted'}) <NEW_LINE> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> showtime = get_object_or_404(Showtime, id=pk) <NEW_LINE> return Response(data=ShowtimeSerializer(showtime).data) <NEW_LINE> <DEDENT> def update(self, request, pk=None): <NEW_LINE> <INDENT> showtime = get_object_or_404(Showtime, id=pk) <NEW_LINE> self.check_object_permissions(request, showtime) <NEW_LINE> serializer = ShowtimeSerializer(showtime, data=request.data, partial=True) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> serializer.save() <NEW_LINE> return Response(data=serializer.data) | API endpoint that allows showtimes to be viewed or edited. | 6259907f099cdd3c63676142 |
class PyDepGraphItr(MayaToPyItr): <NEW_LINE> <INDENT> pass | This wraps MItDependencyGraph iterator and turns it into a python iterator | 6259907f99fddb7c1ca63b21 |
class MinimalAmount(Amount): <NEW_LINE> <INDENT> def __init__(self, nickels, pennies): <NEW_LINE> <INDENT> if pennies >4: <NEW_LINE> <INDENT> total_amount = Amount.value <NEW_LINE> self.pennies = (total_amount)%pennies <NEW_LINE> amount_without_pennies = total_amount-self.pennies <NEW_LINE> self.nickels = amount_without_pennies/5 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pennies = pennies <NEW_LINE> self.nickels = nickels <NEW_LINE> <DEDENT> Amount.__init__(self, self.nickels, self.pennies) | An amount of nickels and pennies that is initialized with no more than
four pennies, by converting excess pennies to nickels.
>>> a = MinimalAmount(3, 7)
>>> a.nickels
4
>>> a.pennies
2
>>> a.value
22 | 6259907f167d2b6e312b82dd |
class cBorder(Widget): <NEW_LINE> <INDENT> def __init__(self,**kwargs): <NEW_LINE> <INDENT> self.aBackGroundColor:List[float] = kwargs.get('background_color',[0.5,0.5,0.5,1.0]) <NEW_LINE> self.fLineWidth:float = float(kwargs.get('linewidth','1.0')) <NEW_LINE> self.oLine:Union[Line,None] = None <NEW_LINE> super(cBorder, self).__init__(**RemoveNoClassArgs(dInArgs=kwargs,oObject=cBorder)) <NEW_LINE> self.Create_Border() <NEW_LINE> self.bind(pos=self.update_graphics_pos,size=self.update_graphics_size) <NEW_LINE> <DEDENT> def Create_Border(self) -> None: <NEW_LINE> <INDENT> with self.canvas: <NEW_LINE> <INDENT> Color(self.aBackGroundColor[0],self.aBackGroundColor[1], self.aBackGroundColor[2],self.aBackGroundColor[3]) <NEW_LINE> self.oLine = Line(points=[self.pos[0],self.pos[1], self.pos[0]+self.width, self.pos[1],self.pos[0]+self.width,self.pos[1]+self.height,self.pos[0],self.pos[1]+self.height], close=True, width=self.fLineWidth, cap="none") <NEW_LINE> <DEDENT> <DEDENT> def update_graphics_pos(self, instance, value) -> None: <NEW_LINE> <INDENT> with self.canvas: <NEW_LINE> <INDENT> self.canvas.clear() <NEW_LINE> <DEDENT> self.Create_Border() <NEW_LINE> <DEDENT> def update_graphics_size(self, instance, value) -> None: <NEW_LINE> <INDENT> with self.canvas: <NEW_LINE> <INDENT> self.canvas.clear() <NEW_LINE> <DEDENT> self.Create_Border() <NEW_LINE> <DEDENT> def SetColor(self,aBackGroundColor:List[float]): <NEW_LINE> <INDENT> self.aBackGroundColor=aBackGroundColor <NEW_LINE> with self.canvas: <NEW_LINE> <INDENT> self.canvas.clear() <NEW_LINE> <DEDENT> self.Create_Border() | Core Widget which draws a border | 6259907ff9cc0f698b1c6015 |
class QTextObject(__PyQt4_QtCore.QObject): <NEW_LINE> <INDENT> def childEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def connectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def customEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def disconnectNotify(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def document(self): <NEW_LINE> <INDENT> return QTextDocument <NEW_LINE> <DEDENT> def format(self): <NEW_LINE> <INDENT> return QTextFormat <NEW_LINE> <DEDENT> def formatIndex(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def objectIndex(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def receivers(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sender(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def senderSignalIndex(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setFormat(self, QTextFormat): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def timerEvent(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, QTextDocument): <NEW_LINE> <INDENT> pass | QTextObject(QTextDocument) | 6259907f8a349b6b43687cee |
class connection(): <NEW_LINE> <INDENT> USER = "faridz" <NEW_LINE> PORT = "5432" <NEW_LINE> DATABASE = "utilisateur" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.connection = None <NEW_LINE> self.cursor = None <NEW_LINE> <DEDENT> def initialize_connection(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection = psycopg2.connect(user = connection.USER, port = connection.PORT, database = connection.DATABASE) <NEW_LINE> self.cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor) <NEW_LINE> <DEDENT> except (Exception, psycopg2.Error) as error : <NEW_LINE> <INDENT> print ("Error while connecting to PostgreSQL", error) <NEW_LINE> <DEDENT> <DEDENT> def close_connection(self): <NEW_LINE> <INDENT> if (self.connection): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.connection.close() | Class to manage the connection and the cursor to a database | 6259907f7cff6e4e811b74d2 |
class LscsoftAll(Package): <NEW_LINE> <INDENT> homepage = "https://wiki.ligo.org/DASWG" <NEW_LINE> url="file://" + join_path(dirname(dirname(dirname(__file__))), 'archives', 'empty.tar.gz') <NEW_LINE> version("0.1", "fbfe7b4acab1f9c5642388313270a616") <NEW_LINE> depends_on("lscsoft-internal", type='run') <NEW_LINE> depends_on("lscsoft-external", type='run') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> with open(join_path(spec.prefix, 'dummy.txt'), 'w') as out: <NEW_LINE> <INDENT> out.write('This is a bundle\n') | Description | 6259907f66673b3332c31e91 |
class AbstractDrs(object): <NEW_LINE> <INDENT> def applyto(self, other): <NEW_LINE> <INDENT> return DrtApplicationExpression(self, other) <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return DrtNegatedExpression(self) <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, AbstractDrs) <NEW_LINE> return DrtOrExpression(self, other) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, AbstractDrs) <NEW_LINE> if isinstance(self, DRS): <NEW_LINE> <INDENT> return DRS(self.refs, self.conds, other) <NEW_LINE> <DEDENT> if isinstance(self, DrtConcatenation): <NEW_LINE> <INDENT> return DrtConcatenation(self.first, self.second, other) <NEW_LINE> <DEDENT> raise Exception('Antecedent of implication must be a DRS') <NEW_LINE> <DEDENT> def equiv(self, other, prover=None): <NEW_LINE> <INDENT> assert isinstance(other, AbstractDrs) <NEW_LINE> f1 = self.simplify().fol(); <NEW_LINE> f2 = other.simplify().fol(); <NEW_LINE> return f1.equiv(f2, prover) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> raise AttributeError("'%s' object has no attribute 'type'" % self.__class__.__name__) <NEW_LINE> <DEDENT> def typecheck(self, signature=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return DrtConcatenation(self, other, None) <NEW_LINE> <DEDENT> def get_refs(self, recursive=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def is_pronoun_function(self): <NEW_LINE> <INDENT> return isinstance(self, DrtApplicationExpression) and isinstance(self.function, DrtAbstractVariableExpression) and self.function.variable.name == DrtTokens.PRONOUN and isinstance(self.argument, DrtIndividualVariableExpression) <NEW_LINE> <DEDENT> def make_EqualityExpression(self, first, second): <NEW_LINE> <INDENT> return DrtEqualityExpression(first, second) <NEW_LINE> <DEDENT> def make_VariableExpression(self, variable): <NEW_LINE> <INDENT> return DrtVariableExpression(variable) <NEW_LINE> <DEDENT> def resolve_anaphora(self): <NEW_LINE> <INDENT> return resolve_anaphora(self) <NEW_LINE> <DEDENT> def eliminate_equality(self): <NEW_LINE> <INDENT> return self.visit_structured(lambda e: e.eliminate_equality(), self.__class__) <NEW_LINE> <DEDENT> def pprint(self): <NEW_LINE> <INDENT> print(self.pretty()) <NEW_LINE> <DEDENT> def pretty(self): <NEW_LINE> <INDENT> return '\n'.join(self._pretty()) <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> DrsDrawer(self).draw() | This is the base abstract DRT Expression from which every DRT
Expression extends. | 6259907f283ffb24f3cf5332 |
class MissingError(except_orm): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> super(MissingError, self).__init__('Registro inexistente.', msg) | Missing record(s). | 6259907faad79263cf43024c |
class PublishTagsStep(publish_step.UnitModelPluginStep): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(PublishTagsStep, self).__init__(step_type=constants.PUBLISH_STEP_TAGS, model_classes=[models.Tag]) <NEW_LINE> self.description = _('Publishing Tags.') <NEW_LINE> self._tag_names = set() <NEW_LINE> <DEDENT> def process_main(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> manifest = models.Manifest.objects.get(digest=item.manifest_digest) <NEW_LINE> schema_version = manifest.schema_version <NEW_LINE> <DEDENT> except mongoengine.DoesNotExist: <NEW_LINE> <INDENT> manifest = models.ManifestList.objects.get(digest=item.manifest_digest) <NEW_LINE> schema_version = constants.MANIFEST_LIST_TYPE <NEW_LINE> <DEDENT> misc.create_symlink( manifest._storage_path, os.path.join(self.parent.publish_manifests_step.get_manifests_directory(), str(schema_version), item.name)) <NEW_LINE> self._tag_names.add(item.name) <NEW_LINE> self.parent.redirect_data[schema_version].add(item.name) <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> tags_path = os.path.join(self.parent.get_working_dir(), 'tags') <NEW_LINE> misc.mkdir(tags_path) <NEW_LINE> with open(os.path.join(tags_path, 'list'), 'w') as list_file: <NEW_LINE> <INDENT> tag_data = { 'name': configuration.get_repo_registry_id(self.get_repo(), self.get_config()), 'tags': list(self._tag_names)} <NEW_LINE> list_file.write(json.dumps(tag_data)) <NEW_LINE> <DEDENT> del self._tag_names | Publish Tags. | 6259907fa05bb46b3848be71 |
class Location(models.Model): <NEW_LINE> <INDENT> SCHOOL = 'S' <NEW_LINE> CLASS = 'C' <NEW_LINE> HOME = 'H' <NEW_LINE> WORK = 'W' <NEW_LINE> TYPE_CHOICES = ( (SCHOOL, 'School'), (CLASS, 'Class'), (HOME, 'Home'), (WORK, 'Work'), ) <NEW_LINE> address = AddressField( on_delete=models.CASCADE, ) <NEW_LINE> location_type = models.CharField( db_column="type", choices=TYPE_CHOICES, default=HOME, max_length=1, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Location' <NEW_LINE> verbose_name_plural = 'Locations' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> location_type = dict(self.TYPE_CHOICES).get(self.location_type) <NEW_LINE> return f'({location_type}) {self.address}' | Model definition for Location. | 6259907f5fc7496912d48fb4 |
class NetworkDeviceListResult(object): <NEW_LINE> <INDENT> swagger_types = { 'response': 'list[NetworkDeviceListResultResponse]', 'version': 'str' } <NEW_LINE> attribute_map = { 'response': 'response', 'version': 'version' } <NEW_LINE> def __init__(self, response=None, version=None): <NEW_LINE> <INDENT> self._response = None <NEW_LINE> self._version = None <NEW_LINE> self.discriminator = None <NEW_LINE> if response is not None: <NEW_LINE> <INDENT> self.response = response <NEW_LINE> <DEDENT> if version is not None: <NEW_LINE> <INDENT> self.version = version <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def response(self): <NEW_LINE> <INDENT> return self._response <NEW_LINE> <DEDENT> @response.setter <NEW_LINE> def response(self, response): <NEW_LINE> <INDENT> self._response = response <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return self._version <NEW_LINE> <DEDENT> @version.setter <NEW_LINE> def version(self, version): <NEW_LINE> <INDENT> self._version = version <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, NetworkDeviceListResult): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907f92d797404e3898a5 |
class MetroFirefoxProfile(Profile): <NEW_LINE> <INDENT> preferences = { 'app.update.enabled' : False, 'app.update.metro.enabled' : False, 'browser.firstrun-content.dismissed' : True, 'browser.sessionstore.resume_from_crash': False, 'browser.shell.checkDefaultBrowser' : False, 'datareporting.healthreport.documentServerURI' : 'http://%(server)s/healthreport/', 'extensions.defaultProviders.enabled' : True, 'extensions.enabledScopes' : 5, 'extensions.autoDisableScopes' : 10, 'extensions.getAddons.cache.enabled' : False, 'extensions.installDistroAddons' : False, 'extensions.showMismatchUI' : False, 'extensions.strictCompatibility' : False, 'extensions.update.enabled' : False, 'extensions.update.notifyUser' : False, 'focusmanager.testmode' : True, 'security.notification_enable_delay' : 0, 'toolkit.startup.max_resumed_crashes' : -1, 'toolkit.telemetry.enabled' : False, 'toolkit.telemetry.server' : 'http://%(server)s/telemetry-dummy/', } | Specialized Profile subclass for Firefox Metro | 6259907f1f5feb6acb16468c |
class EggCarton(sa.SimulatedAnnealing): <NEW_LINE> <INDENT> def __init__(self, M, N, K): <NEW_LINE> <INDENT> super(EggCarton, self).__init__() <NEW_LINE> self.M = M <NEW_LINE> self.N = N <NEW_LINE> self.K = K <NEW_LINE> maxEggs = max(M, N) * K <NEW_LINE> self.environment = Board(M, N, K, maxEggs) <NEW_LINE> self.Tmax = 1.0 <NEW_LINE> self.Tmin = 1e-2 <NEW_LINE> self.dT = 1e-5 <NEW_LINE> self.streakLimit = 1 <NEW_LINE> self.name = self.__repr__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "EggCarton({}, {}, {})".format(self.M, self.N, self.K) <NEW_LINE> <DEDENT> def schedule(self, temp): <NEW_LINE> <INDENT> return temp - self.dT | Egg Carton puzzle container | 6259907f7047854f46340e48 |
class LockableThreadPool(threadpool.ThreadPool): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._accept_new = True <NEW_LINE> threadpool.ThreadPool.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def lock(self): <NEW_LINE> <INDENT> self._accept_new = False <NEW_LINE> <DEDENT> def callInThread(self, func, *args, **kwargs): <NEW_LINE> <INDENT> if self._accept_new: <NEW_LINE> <INDENT> threadpool.ThreadPool.callInThread(self, func, *args, **kwargs) | Threadpool that can be locked from accepting new requests. | 6259907f2c8b7c6e89bd5278 |
class Engine: <NEW_LINE> <INDENT> def __init__(self, dialect, pool, dsn): <NEW_LINE> <INDENT> self._dialect = dialect <NEW_LINE> self._pool = pool <NEW_LINE> self._dsn = dsn <NEW_LINE> <DEDENT> @property <NEW_LINE> def dialect(self): <NEW_LINE> <INDENT> return self._dialect <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._dialect.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def driver(self): <NEW_LINE> <INDENT> return self._dialect.driver <NEW_LINE> <DEDENT> @property <NEW_LINE> def dsn(self): <NEW_LINE> <INDENT> return self._dsn <NEW_LINE> <DEDENT> @property <NEW_LINE> def timeout(self): <NEW_LINE> <INDENT> return self._pool.timeout <NEW_LINE> <DEDENT> @property <NEW_LINE> def minsize(self): <NEW_LINE> <INDENT> return self._pool.minsize <NEW_LINE> <DEDENT> @property <NEW_LINE> def maxsize(self): <NEW_LINE> <INDENT> return self._pool.maxsize <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self._pool.size <NEW_LINE> <DEDENT> @property <NEW_LINE> def freesize(self): <NEW_LINE> <INDENT> return self._pool.freesize <NEW_LINE> <DEDENT> @property <NEW_LINE> def closed(self): <NEW_LINE> <INDENT> return self._pool.closed <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._pool.close() <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> self._pool.terminate() <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def wait_closed(self): <NEW_LINE> <INDENT> yield from self._pool.wait_closed() <NEW_LINE> <DEDENT> def acquire(self): <NEW_LINE> <INDENT> coro = self._acquire() <NEW_LINE> return _EngineAcquireContextManager(coro, self) <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def _acquire(self): <NEW_LINE> <INDENT> raw = yield from self._pool.acquire() <NEW_LINE> conn = SAConnection(raw, self) <NEW_LINE> return conn <NEW_LINE> <DEDENT> def release(self, conn): <NEW_LINE> <INDENT> if conn.in_transaction: <NEW_LINE> <INDENT> raise InvalidRequestError("Cannot release a connection with " "not finished transaction") <NEW_LINE> <DEDENT> raw = conn.connection <NEW_LINE> fut = self._pool.release(raw) <NEW_LINE> return fut <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> raise RuntimeError( '"yield from" should be used as context manager expression') <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> conn = yield from self.acquire() <NEW_LINE> return _ConnectionContextManager(self, conn) <NEW_LINE> <DEDENT> if PY_35: <NEW_LINE> <INDENT> @asyncio.coroutine <NEW_LINE> def __aenter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def __aexit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.close() <NEW_LINE> yield from self.wait_closed() | Connects a aiopg.Pool and
sqlalchemy.engine.interfaces.Dialect together to provide a
source of database connectivity and behavior.
An Engine object is instantiated publicly using the
create_engine coroutine. | 6259907f167d2b6e312b82de |
class RadioField(SelectField): <NEW_LINE> <INDENT> widget = widgets.ListWidget(prefix_label=False) <NEW_LINE> option_widget = widgets.RadioInput() | Like a SelectField, except displays a list of radio buttons.
Iterating the field will produce subfields (each containing a label as
well) in order to allow custom rendering of the individual radio fields. | 6259907fbf627c535bcb2f65 |
class LSSController(pm.Controller): <NEW_LINE> <INDENT> public_settings = OrderedDict([("poles", [-3.1, -3.1, -3.1, -3.1]), ("source", "system_state"), ("steady state", [0, 0, 0, 0]), ("steady tau", 0), ("tick divider", 1) ]) <NEW_LINE> def __init__(self, settings): <NEW_LINE> <INDENT> settings.update(input_order=0) <NEW_LINE> settings.update(output_dim=1) <NEW_LINE> settings.update(input_type=settings["source"]) <NEW_LINE> pm.Controller.__init__(self, settings) <NEW_LINE> self._output = np.zeros((1, )) <NEW_LINE> a_mat, b_mat, c_mat = linearise_system(self._settings["steady state"], self._settings["steady tau"]) <NEW_LINE> self.K = pm.place_siso(a_mat, b_mat, self._settings["poles"]) <NEW_LINE> self.V = pm.calc_prefilter(a_mat, b_mat, c_mat, self.K) <NEW_LINE> <DEDENT> def _control(self, time, trajectory_values=None, feedforward_values=None, input_values=None, **kwargs): <NEW_LINE> <INDENT> yd = trajectory_values[:, 0] <NEW_LINE> self._output = -self.K @ input_values + yd * self.V <NEW_LINE> return self._output | Linear state space controller
This controller is based on the linearized system. The steady state is
given by :math:`(\boldsymbol{x}^e, \tau^e)` . | 6259907f283ffb24f3cf5334 |
class AreaMultipleFilter(ModelMultipleChoiceFilter): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> label = kwargs.pop("label", _("Area")) <NEW_LINE> required = kwargs.pop("required", False) <NEW_LINE> queryset = kwargs.pop("queryset", JednostkaAdministracyjna.objects.all()) <NEW_LINE> method = kwargs.pop("method", lambda q, _, v: q.area_in(v)) <NEW_LINE> super(ModelMultipleChoiceFilter, self).__init__( *args, label=label, required=required, queryset=queryset, method=method, **kwargs ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def filter_area_in(queryset, value, area_field=None): <NEW_LINE> <INDENT> def with_area_field(path): <NEW_LINE> <INDENT> if area_field is None: <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "{}__{}".format(area_field, path) <NEW_LINE> <DEDENT> <DEDENT> if not value: <NEW_LINE> <INDENT> return queryset.none() <NEW_LINE> <DEDENT> return queryset.filter( reduce( lambda x, y: x | y, [ Q( **{ with_area_field("tree_id"): jst.tree_id, with_area_field("lft__range"): (jst.lft, jst.rght), } ) for jst in value ], ) ) | Multiple choice filter for JSTs.
The queryset should implement a `area_in` method. | 6259907f5fdd1c0f98e5fa13 |
class CompileThrift(Command): <NEW_LINE> <INDENT> description = "compile thrift files into python modules" <NEW_LINE> user_options = [ ('input-root=', 'i', 'Root directory to look for *.thrift files'), ('output-root=', 'i', 'Root directory to output python modules to') ] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> self.input_root = 'thrifts' <NEW_LINE> self.output_root = '.' <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> thrift_files = self.find_thrift_files() <NEW_LINE> if not thrift_files: <NEW_LINE> <INDENT> log.warn('no thrift files found in ' + self.input_root) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.compile_thrift_files(thrift_files) <NEW_LINE> self.declare_namespaces() <NEW_LINE> <DEDENT> <DEDENT> def find_thrift_files(self): <NEW_LINE> <INDENT> thrift_files = [] <NEW_LINE> for root, dirs, files in os.walk(self.input_root): <NEW_LINE> <INDENT> for filename in fnmatch.filter(files, '*.thrift'): <NEW_LINE> <INDENT> thrift_files.append(os.path.join(self.input_root, filename)) <NEW_LINE> <DEDENT> <DEDENT> return thrift_files <NEW_LINE> <DEDENT> def compile_thrift_files(self, thrift_files): <NEW_LINE> <INDENT> for thrift_file in thrift_files: <NEW_LINE> <INDENT> log.info('compiling thrift file ' + thrift_file) <NEW_LINE> call(['thrift', '--gen', 'py', '-out', self.output_root, thrift_file]) <NEW_LINE> <DEDENT> <DEDENT> def declare_namespaces(self): <NEW_LINE> <INDENT> gen_root = 'gen-py' <NEW_LINE> init_filename = '__init__.py' <NEW_LINE> for root, dirs, files in os.walk(gen_root): <NEW_LINE> <INDENT> if files == [init_filename]: <NEW_LINE> <INDENT> with open(os.path.join(gen_root, init_filename), 'w') as init_file: <NEW_LINE> <INDENT> init_file.write(namespace_declaration) | Command to compile thrift files into python modules | 6259907f67a9b606de5477f0 |
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> date_joined = models.DateField(default=timezone.now) <NEW_LINE> objects = UserManager() <NEW_LINE> USERNAME_FIELD = 'email' | Custom user model that supports email instead of username | 6259907f76e4537e8c3f1014 |
class SNP(object): <NEW_LINE> <INDENT> def __init__(self, gene, snpinfo): <NEW_LINE> <INDENT> self.gene = gene <NEW_LINE> self.gene.snps.append(self) <NEW_LINE> (self.chrm, self.pos, ref, mat_gtyp, pat_gtyp, c_gtyp, phase, self.mat_allele, self.pat_allele, cA, cC, cG, cT, self.win, self.cls, pval, BindingSite, cnv) = snpinfo <NEW_LINE> self.pval = float(pval) <NEW_LINE> self.counts = {'A': int(cA), 'C': int(cC), 'G': int(cG), 'T': int(cT)} <NEW_LINE> self.mat_counts = self.counts[self.mat_allele] <NEW_LINE> self.pat_counts = self.counts[self.pat_allele] <NEW_LINE> count = list(self.counts) <NEW_LINE> count.remove(self.mat_allele) <NEW_LINE> count.remove(self.pat_allele) <NEW_LINE> self.other_counts = self.counts[count.pop()] + self.counts[count.pop()] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return numpy.sum(self.counts.values()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "SNP<(mat:{};pat:{};other:{})>".format( self.mat_counts, self.pat_counts, self.other_counts) | A SNP.
Contains::
chrm -- chromosome
pos -- position
mat_allele -- The maternal allele
pat_allele -- The paternal allele
counts -- Dict of raw counts for each base indexed by ATCG
win -- M/P/?
cls -- Sym/Asym/Weird -- Asym: ASE
pval -- binomial pvalue
gene -- the parent Gene class
mat_counts
pat_counts
other_counts | 6259907f3317a56b869bf290 |
class LAM(object): <NEW_LINE> <INDENT> def __init__(self, X=None, Y=None): <NEW_LINE> <INDENT> if X is None: <NEW_LINE> <INDENT> X = [] <NEW_LINE> <DEDENT> if Y is None: <NEW_LINE> <INDENT> Y = [] <NEW_LINE> <DEDENT> if len(X) > 0 and len(Y) == 0: <NEW_LINE> <INDENT> Y = X <NEW_LINE> <DEDENT> self._X = np.array(X) <NEW_LINE> self._Y = np.array(Y) <NEW_LINE> x_samps, x_vars = self._X.shape <NEW_LINE> y_samps, y_vars = self._Y.shape <NEW_LINE> if x_samps != y_samps: <NEW_LINE> <INDENT> err = 'Input and output dimensions mismatch' <NEW_LINE> log.error(err) <NEW_LINE> self.clear() <NEW_LINE> raise ValueError(err) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.__init__() <NEW_LINE> <DEDENT> def fit(self): <NEW_LINE> <INDENT> x_samps, x_vars = self._X.shape <NEW_LINE> y_samps, y_vars = self._Y.shape <NEW_LINE> self.W_ = np.zeros(y_vars, x_vars) <NEW_LINE> self.M_ = np.zeros(y_vars, x_vars) <NEW_LINE> for b in range(y_vars): <NEW_LINE> <INDENT> for c in range(x_vars): <NEW_LINE> <INDENT> product = self._Y[:, b] - self._X[:, c] <NEW_LINE> self.W_[b, c] = product.min() <NEW_LINE> self.M_[b, c] = product.max() <NEW_LINE> <DEDENT> <DEDENT> return self.W_, self.M_ | The Lattice Associative Memories is a kind of associative memory working
over lattice operations. If X=Y then W and M are Lattice AutoAssociative
Memories (LAAM), otherwise they are Lattice HeteroAssociative Memories
(LHAM).
Parameters
----------
X: numpy.ndarray
input pattern matrix [n_samples x n_variables]
Y: numpy.ndarray
output pattern matrix [n_samples x m_variables]
Returns
-------
W: numpy.ndarray
dilative LAM [m_variables x n_variables]
M: numpy.ndarray
erosive LAM [m_variables x n_variables]
Notes
-----
Bibliographical references:
[1] M. Grana, D. Chyzhyk, M. Garcia-Sebastian, y C. Hernandez, "Lattice independent component analysis for functional magnetic resonance imaging",
Information Sciences, vol. 181, n. 10, pags. 1910-1928, May. 2011. | 6259907f44b2445a339b76a7 |
class TextLabel(QWidget): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> QWidget.__init__(self, *args, **kwargs) <NEW_LINE> self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) <NEW_LINE> self.__text = "" <NEW_LINE> self.__textElideMode = Qt.ElideMiddle <NEW_LINE> self.__sizeHint = None <NEW_LINE> self.__alignment = Qt.AlignLeft | Qt.AlignVCenter <NEW_LINE> <DEDENT> def setText(self, text): <NEW_LINE> <INDENT> check_type(text, basestring) <NEW_LINE> if self.__text != text: <NEW_LINE> <INDENT> self.__text = unicode(text) <NEW_LINE> self.__update() <NEW_LINE> <DEDENT> <DEDENT> def text(self): <NEW_LINE> <INDENT> return self.__text <NEW_LINE> <DEDENT> def setTextElideMode(self, mode): <NEW_LINE> <INDENT> if self.__textElideMode != mode: <NEW_LINE> <INDENT> self.__textElideMode = mode <NEW_LINE> self.__update() <NEW_LINE> <DEDENT> <DEDENT> def elideMode(self): <NEW_LINE> <INDENT> return self.__elideMode <NEW_LINE> <DEDENT> def setAlignment(self, align): <NEW_LINE> <INDENT> if self.__alignment != align: <NEW_LINE> <INDENT> self.__alignment = align <NEW_LINE> self.__update() <NEW_LINE> <DEDENT> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> if self.__sizeHint is None: <NEW_LINE> <INDENT> option = QStyleOption() <NEW_LINE> option.initFrom(self) <NEW_LINE> metrics = option.fontMetrics <NEW_LINE> self.__sizeHint = QSize(200, metrics.height()) <NEW_LINE> <DEDENT> return self.__sizeHint <NEW_LINE> <DEDENT> def paintEvent(self, event): <NEW_LINE> <INDENT> painter = QStylePainter(self) <NEW_LINE> option = QStyleOption() <NEW_LINE> option.initFrom(self) <NEW_LINE> rect = option.rect <NEW_LINE> metrics = option.fontMetrics <NEW_LINE> text = metrics.elidedText(self.__text, self.__textElideMode, rect.width()) <NEW_LINE> painter.drawItemText(rect, self.__alignment, option.palette, self.isEnabled(), text, self.foregroundRole()) <NEW_LINE> painter.end() <NEW_LINE> <DEDENT> def changeEvent(self, event): <NEW_LINE> <INDENT> if event.type() == QEvent.FontChange: <NEW_LINE> <INDENT> self.__update() <NEW_LINE> <DEDENT> return QWidget.changeEvent(self, event) <NEW_LINE> <DEDENT> def __update(self): <NEW_LINE> <INDENT> self.__sizeHint = None <NEW_LINE> self.updateGeometry() <NEW_LINE> self.update() | A plain text label widget with support for elided text.
| 6259907fa8370b77170f1e64 |
class CallbackBlock(CopyBlock): <NEW_LINE> <INDENT> def __init__(self, iring, seq_callback, data_callback, data_ref=None, *args, **kwargs): <NEW_LINE> <INDENT> super(CallbackBlock, self).__init__(iring, *args, **kwargs) <NEW_LINE> self.seq_callback = seq_callback <NEW_LINE> self.data_callback = data_callback <NEW_LINE> self.data_ref = data_ref <NEW_LINE> <DEDENT> def on_sequence(self, iseq): <NEW_LINE> <INDENT> self.seq_callback(iseq) <NEW_LINE> return super(CallbackBlock, self).on_sequence(iseq) <NEW_LINE> <DEDENT> def on_data(self, ispan, ospan): <NEW_LINE> <INDENT> self.data_callback(ispan, ospan) <NEW_LINE> if self.data_ref is not None: <NEW_LINE> <INDENT> self.data_ref['odata'] = ospan.data.copy() <NEW_LINE> <DEDENT> return super(CallbackBlock, self).on_data(ispan, ospan) | Testing-only block which calls user-defined
functions on sequence and on data | 6259907fbf627c535bcb2f67 |
class IGenwebJsonifyLayer(IDefaultPloneLayer): <NEW_LINE> <INDENT> pass | Marker interface that defines a Zope 3 browser layer. | 6259907f60cbc95b06365ab7 |
class ParentEnvConfig(namedtuple("ParentEnvConfig", "parent sep shell env var")): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.shell | Configuration for testing parent environments. | 6259907fd268445f2663a8a9 |
class SegmentProximicContextual(ProximicSegmentTree): <NEW_LINE> <INDENT> PRICE_CPM = TARGETING_ADDITIONAL_DATA_COSTS['contextual_categories'] <NEW_LINE> SEGMENT_IDS = segments.proximic_contextual <NEW_LINE> DIMENSION = dimensions.proximic_contextual <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('name',) | .. note::
please see :attr:`bidrequest.segments.proximic_contextual`
for values we match and update them accordingly | 6259907f23849d37ff852b4f |
class TestGraphSplit(unittest.TestCase): <NEW_LINE> <INDENT> def test_has_subgraph(self): <NEW_LINE> <INDENT> global snt, pat <NEW_LINE> g0 = graph2.cnll10_to_networkx(snt) <NEW_LINE> g1 = graph2.cnll10_to_networkx(pat) <NEW_LINE> print(g0.nodes()) <NEW_LINE> print(g1.nodes()) <NEW_LINE> assert graph2.has_sub_graph(g0,g1) <NEW_LINE> <DEDENT> def test_best_mapping(self): <NEW_LINE> <INDENT> g0 = graph2.cnll10_to_networkx(snt) <NEW_LINE> g1 = graph2.cnll10_to_networkx(pat) <NEW_LINE> bestMapping = graph2.best_mapping(g0,g1) <NEW_LINE> ref = {0: 0, 2: 20, 4: 40, -1: -1, 6: 60} <NEW_LINE> print(bestMapping) <NEW_LINE> assert bestMapping == ref <NEW_LINE> <DEDENT> def test_split_graph(self): <NEW_LINE> <INDENT> g0 = graph2.cnll10_to_networkx(snt) <NEW_LINE> g1 = graph2.cnll10_to_networkx(pat) <NEW_LINE> rlt = graph2.split_by_subgraph(g0, g1) <NEW_LINE> assert len(rlt) == 2 <NEW_LINE> <DEDENT> def test_graph_expand(self): <NEW_LINE> <INDENT> g0 = graph2.cnll10_to_networkx(snt) <NEW_LINE> patterns = [pat] <NEW_LINE> dg = graph2.DecisionGraph2(g=g0) <NEW_LINE> rlt = dg.expand_by_decomposition(patterns) <NEW_LINE> pprint(dg.nodes) <NEW_LINE> assert rlt == 1 | Basic test cases. | 6259907fa8370b77170f1e66 |
class TestGenerationInRequestsMove(TestGenerationInRequestsPutContent): <NEW_LINE> <INDENT> request_class = Move <NEW_LINE> def build_request(self): <NEW_LINE> <INDENT> return self.request_class(FakedProtocol(), None, None, None, None) | Tests for new_generation in Move. | 6259907f7047854f46340e4c |
class XMPPError(FortniteException): <NEW_LINE> <INDENT> pass | This exception is raised when something regarding the XMPP service
fails. | 6259907ff548e778e596d028 |
class UserRankingsForm(messages.Message): <NEW_LINE> <INDENT> rankings = messages.MessageField(UserRankingInfoForm, 1, repeated=True) | Form for outbound User ranking list | 6259907f5166f23b2e244e6f |
class SteppedTomography(XrayTubeMixin, BaseSteppedTomography): <NEW_LINE> <INDENT> def __init__(self, walker, flat_motor, tomography_motor, radio_position, flat_position, camera, xray_tube, num_flats=200, num_darks=200, num_projections=3000, angular_range=360 * q.deg, start_angle=0 * q.deg, separate_scans=True): <NEW_LINE> <INDENT> XrayTubeMixin.__init__(self, xray_tube) <NEW_LINE> BaseSteppedTomography.__init__(self, walker=walker, flat_motor=flat_motor, tomography_motor=tomography_motor, radio_position=radio_position, flat_position=flat_position, camera=camera, num_flats=num_flats, num_darks=num_darks, num_projections=num_projections, angular_range=angular_range, start_angle=start_angle, separate_scans=separate_scans) | Stepped tomography experiment. | 6259907fdc8b845886d55051 |
class Divider(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def calc(operand_1, operand_2): <NEW_LINE> <INDENT> return operand_1/operand_2 | Division | 6259907f32920d7e50bc7ad8 |
class VideoMockup(BaseHardwareObjects.Device): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> BaseHardwareObjects.Device.__init__(self, name) <NEW_LINE> self.force_update = None <NEW_LINE> self.image_dimensions = None <NEW_LINE> self.image_polling = None <NEW_LINE> self.image_type = None <NEW_LINE> self.qimage = None <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> self.qimage = QImage() <NEW_LINE> current_path = os.path.dirname(os.path.abspath(__file__)).split(os.sep) <NEW_LINE> current_path = os.path.join(*current_path[1:-1]) <NEW_LINE> image_path = os.path.join("/", current_path, "ExampleFiles/fakeimg.jpg") <NEW_LINE> self.qimage.load(image_path) <NEW_LINE> self.force_update = False <NEW_LINE> self.image_dimensions = [600, 400] <NEW_LINE> self.image_type = JpegType() <NEW_LINE> self.set_is_ready(True) <NEW_LINE> <DEDENT> def imageType(self): <NEW_LINE> <INDENT> return self.image_type <NEW_LINE> <DEDENT> def contrastExists(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def setContrast(self, contrast): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getContrast(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getContrastMinMax(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def brightnessExists(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def setBrightness(self, brightness): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getBrightness(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getBrightnessMinMax(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def gainExists(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def setGain(self, gain): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getGain(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getGainMinMax(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def gammaExists(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def setGamma(self, gamma): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getGamma(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def getGammaMinMax(self): <NEW_LINE> <INDENT> return (0, 1) <NEW_LINE> <DEDENT> def set_live(self, mode): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def get_width(self): <NEW_LINE> <INDENT> return self.image_dimensions[0] <NEW_LINE> <DEDENT> def get_height(self): <NEW_LINE> <INDENT> return self.image_dimensions[1] <NEW_LINE> <DEDENT> def _do_imagePolling(self, sleep_time): <NEW_LINE> <INDENT> self.image_dimensions = (self.qimage.width(), self.qimage.height()) <NEW_LINE> while True: <NEW_LINE> <INDENT> self.emit( "imageReceived", self.qimage, self.qimage.width(), self.qimage.height(), self.force_update, ) <NEW_LINE> time.sleep(sleep_time) <NEW_LINE> <DEDENT> <DEDENT> def connect_notify(self, signal): <NEW_LINE> <INDENT> if signal == "imageReceived": <NEW_LINE> <INDENT> self.image_polling = gevent.spawn(self._do_imagePolling, 1) | Descript. : | 6259907f2c8b7c6e89bd527c |
class InccreaseSortableTitleMaxLength(UpgradeStep): <NEW_LINE> <INDENT> deferrable = True <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> getQueue().hook() <NEW_LINE> processor = getUtility(IIndexQueueProcessor, name='ftw.solr') <NEW_LINE> catalog = api.portal.get_tool('portal_catalog') <NEW_LINE> for obj in self.objects({'object_provides': IDexterityContent.__identifier__}, "Reindex sortable title."): <NEW_LINE> <INDENT> catalog.reindexObject(obj, idxs=['sortable_title'], update_metadata=False) <NEW_LINE> processor.index(obj, ['sortable_title']) | Increase maximal length of sortable title.
| 6259907fad47b63b2c5a92e7 |
class UnreadableSectorResponse(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'max_limit': 'int', 'database': 'list[UnreadableSectorEntryResult]' } <NEW_LINE> self.attribute_map = { 'max_limit': 'maxLimit', 'database': 'database' } <NEW_LINE> self._max_limit = None <NEW_LINE> self._database = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_limit(self): <NEW_LINE> <INDENT> return self._max_limit <NEW_LINE> <DEDENT> @max_limit.setter <NEW_LINE> def max_limit(self, max_limit): <NEW_LINE> <INDENT> self._max_limit = max_limit <NEW_LINE> <DEDENT> @property <NEW_LINE> def database(self): <NEW_LINE> <INDENT> return self._database <NEW_LINE> <DEDENT> @database.setter <NEW_LINE> def database(self, database): <NEW_LINE> <INDENT> self._database = database <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if self is None or other is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907f7cff6e4e811b74d8 |
class ApplicationRequestSchema(object): <NEW_LINE> <INDENT> swagger_types = { 'name': 'str' } <NEW_LINE> attribute_map = { 'name': 'name' } <NEW_LINE> def __init__(self, name=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(ApplicationRequestSchema, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ApplicationRequestSchema): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259907fa05bb46b3848be74 |
class Linkage(MultiBodySystem): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._root = RootLink(self) <NEW_LINE> self._constants = dict() <NEW_LINE> self._constant_descs = dict() <NEW_LINE> self._forces = dict() <NEW_LINE> self._gravity_vector = None <NEW_LINE> self._gravity_vector_updated = Event( 'Update gravity forces when gravity vector is changed.') <NEW_LINE> self._gravity_vector_updated.subscriber_new(self._manage_gravity_forces) <NEW_LINE> <DEDENT> def _get_name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def _set_name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> name = property(_get_name, _set_name) <NEW_LINE> def _get_root(self): <NEW_LINE> <INDENT> return self._root <NEW_LINE> <DEDENT> root = property(_get_root) <NEW_LINE> def constant_new(self, name, description): <NEW_LINE> <INDENT> self._constants[name] = symbols(name) <NEW_LINE> self._constant_descs[name] = description <NEW_LINE> return self._constants[name] <NEW_LINE> <DEDENT> def force_new(self, name, point_of_application, vec): <NEW_LINE> <INDENT> self._forces[name] = (point_of_application, vec) <NEW_LINE> <DEDENT> def force_del(self, name): <NEW_LINE> <INDENT> self._forces.pop(name) <NEW_LINE> <DEDENT> def _manage_gravity_forces(self): <NEW_LINE> <INDENT> for body in self.body_list(): <NEW_LINE> <INDENT> self.force_new('%s_gravity', body.masscenter, body.mass * self.gravity_vector) <NEW_LINE> <DEDENT> <DEDENT> def _get_gravity_vector(self): <NEW_LINE> <INDENT> return self._gravity_vector <NEW_LINE> <DEDENT> def _set_gravity_vector(self, vec): <NEW_LINE> <INDENT> _check_vector(vec) <NEW_LINE> self._gravity_vector = vec <NEW_LINE> self._gravity_vector_updated.fire() <NEW_LINE> <DEDENT> gravity_vector = property(_get_gravity_vector, _set_gravity_vector) <NEW_LINE> def independent_coordinates(self): <NEW_LINE> <INDENT> return self.root.independent_coordinates_in_subtree() <NEW_LINE> <DEDENT> def independent_speeds(self): <NEW_LINE> <INDENT> return self.root.independent_speeds_in_subtree() <NEW_LINE> <DEDENT> def kinematic_differential_equations(self): <NEW_LINE> <INDENT> return self.root.kinematic_differential_equations_in_subtree() <NEW_LINE> <DEDENT> def body_list(self): <NEW_LINE> <INDENT> return self.root.body_list_in_subtree() <NEW_LINE> <DEDENT> def force_list(self): <NEW_LINE> <INDENT> return self._forces.values() <NEW_LINE> <DEDENT> def mass_matrix(self): <NEW_LINE> <INDENT> self._kanes_method = KanesMethod(self.root.frame, q_ind=self.independent_coordinates(), u_ind=self.independent_speeds(), kd_eqs=self.kinematic_differential_equations() ) <NEW_LINE> self._kanes_method.kanes_equations(self.force_list(), self.body_list()); <NEW_LINE> return self._kanes_method.mass_matrix <NEW_LINE> <DEDENT> def state_derivatives(self): <NEW_LINE> <INDENT> kin_diff_eqns = self._kanes_method.kindiffdict() <NEW_LINE> state_derivatives = self.mass_matrix.inv() * self._kanes_method.forcing <NEW_LINE> state_derivatives = state_derivatives.subs(kin_diff_eqns) <NEW_LINE> state_derivatives.simplify() <NEW_LINE> return state_derivatives <NEW_LINE> <DEDENT> def _check_link_name(self): <NEW_LINE> <INDENT> pass | TODO
| 6259907f5fc7496912d48fb7 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.