code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class APICommentListView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> def get_document(self): <NEW_LINE> <INDENT> if self.request.method == 'GET': <NEW_LINE> <INDENT> permission_required = permission_document_comment_view <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> permission_required = permission_document_comment_create <NEW_LINE> <DEDENT> document = get_object_or_404( klass=Document, pk=self.kwargs['document_pk'] ) <NEW_LINE> AccessControlList.objects.check_access( obj=document, permissions=(permission_required,), user=self.request.user ) <NEW_LINE> return document <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> return self.get_document().comments.all() <NEW_LINE> <DEDENT> def get_serializer(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.request: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return super(APICommentListView, self).get_serializer(*args, **kwargs) <NEW_LINE> <DEDENT> def get_serializer_class(self): <NEW_LINE> <INDENT> if self.request.method == 'GET': <NEW_LINE> <INDENT> return CommentSerializer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return WritableCommentSerializer <NEW_LINE> <DEDENT> <DEDENT> def get_serializer_context(self): <NEW_LINE> <INDENT> context = super(APICommentListView, self).get_serializer_context() <NEW_LINE> if self.kwargs: <NEW_LINE> <INDENT> context.update( { 'document': self.get_document(), } ) <NEW_LINE> <DEDENT> return context | get: Returns a list of all the document comments.
post: Create a new document comment. | 62598fd5377c676e912f6ff0 |
class TimedProcTimeoutError(SaltException): <NEW_LINE> <INDENT> pass | Thrown when a timed subprocess does not terminate within the timeout,
or if the specified timeout is not an int or a float | 62598fd5ad47b63b2c5a7d3e |
class Point(): <NEW_LINE> <INDENT> def __init__(self, x=0, y=0): <NEW_LINE> <INDENT> self.x, self.y = x, y <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.x, self.y)) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if self.x != other.x: <NEW_LINE> <INDENT> return self.x < other.x <NEW_LINE> <DEDENT> return self.y < other.y <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.x == other.x and self.y == other.y <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return self < other or self == other <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return Point(self.x - other.x, self.y - other.y) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '(' + str(self.x) + ',' + str(self.y) + ')' | Data and operations of 2D points | 62598fd526238365f5fad052 |
class AccountAndProjectData(fixtures.Fixture): <NEW_LINE> <INDENT> def __init__(self, dbconn, context, user_id, project_id, domain_id, level, owed=False, balance=0, frozen_balance=0, consumption=0, inviter=None, sales_id=None): <NEW_LINE> <INDENT> self.dbconn = dbconn <NEW_LINE> self.context = context <NEW_LINE> self.user_id = user_id <NEW_LINE> self.project_id = project_id <NEW_LINE> self.domain_id = domain_id <NEW_LINE> self.level = level <NEW_LINE> self.owed = owed <NEW_LINE> self.inviter = inviter <NEW_LINE> self.sales_id = sales_id <NEW_LINE> self.balance = balance <NEW_LINE> self.frozen_balance = frozen_balance <NEW_LINE> self.consumption = consumption <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> super(self.__class__, self).setUp() <NEW_LINE> self.account = db_models.Account( user_id=self.user_id, project_id=self.project_id, domain_id=self.domain_id, balance=self.balance, frozen_balance=self.frozen_balance, consumption=self.consumption, level=self.level, inviter=self.inviter, sales_id=self.sales_id ) <NEW_LINE> self.dbconn.create_account(self.context, self.account) <NEW_LINE> self.project = db_models.Project( user_id=self.user_id, project_id=self.project_id, domain_id=self.domain_id, consumption=0 ) <NEW_LINE> self.dbconn.create_project(self.context, self.project) <NEW_LINE> self.user_project = copy.deepcopy(self.project) <NEW_LINE> self.addCleanup(delete_all_rows, sql_models.UserProject) <NEW_LINE> self.addCleanup(delete_all_rows, sql_models.Project) <NEW_LINE> self.addCleanup(delete_all_rows, sql_models.Account) | A fixture for generating account and project data | 62598fd597e22403b383b3f7 |
class DashboardModel(models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def time_since_update(self): <NEW_LINE> <INDENT> update_delta = timezone_now() - self.updated <NEW_LINE> seconds_since_update = update_delta.seconds <NEW_LINE> if seconds_since_update / MONTH >= 1: <NEW_LINE> <INDENT> quantity = seconds_since_update / MONTH <NEW_LINE> units = 'months' if quantity > 1 else 'month' <NEW_LINE> <DEDENT> elif seconds_since_update / WEEK >= 1: <NEW_LINE> <INDENT> quantity = seconds_since_update / WEEK <NEW_LINE> units = 'weeks' if quantity > 1 else 'week' <NEW_LINE> <DEDENT> elif seconds_since_update / DAY >= 1: <NEW_LINE> <INDENT> quantity = seconds_since_update / DAY <NEW_LINE> units = 'days' if quantity > 1 else 'day' <NEW_LINE> <DEDENT> elif seconds_since_update / HOUR >= 1: <NEW_LINE> <INDENT> quantity = seconds_since_update / HOUR <NEW_LINE> units = 'hours' if quantity > 1 else 'hour' <NEW_LINE> <DEDENT> elif seconds_since_update / MINUTE >= 1: <NEW_LINE> <INDENT> quantity = seconds_since_update / MINUTE <NEW_LINE> units = 'minutes' if quantity > 1 else 'minute' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "updated just now" <NEW_LINE> <DEDENT> base_string = 'updated {quantity:.2f} {units} ago' <NEW_LINE> return base_string.format(quantity=quantity, units=units) | Abstract base model for things which will be displayed on the dashboard, adds in created and updated fields,
and provides a convenience method which provides a nicely formatted string of the time since update. | 62598fd5adb09d7d5dc0aa68 |
class CudaFnUfuncs(FnBaseUfuncs): <NEW_LINE> <INDENT> sin = _make_unary_fun('sin') <NEW_LINE> cos = _make_unary_fun('cos') <NEW_LINE> arcsin = _make_unary_fun('arcsin') <NEW_LINE> arccos = _make_unary_fun('arccos') <NEW_LINE> log = _make_unary_fun('log') <NEW_LINE> exp = _make_unary_fun('exp') <NEW_LINE> absolute = _make_unary_fun('absolute') <NEW_LINE> sign = _make_unary_fun('sign') <NEW_LINE> sqrt = _make_unary_fun('sqrt') <NEW_LINE> sum = _make_nullary_fun('sum') <NEW_LINE> prod = _make_nullary_fun('prod') <NEW_LINE> min = _make_nullary_fun('min') <NEW_LINE> max = _make_nullary_fun('max') | Ufuncs for `CudaFnVector` objects.
Internal object, should not be created except in `CudaFnVector`. | 62598fd5099cdd3c63675656 |
class Constant_CT_Signal(CT_Signal): <NEW_LINE> <INDENT> def __init__(self, k): <NEW_LINE> <INDENT> assert is_number(k), 'k must be a number' <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def sample(self, t): <NEW_LINE> <INDENT> return self.k | Constant CT signal. | 62598fd5c4546d3d9def74fa |
class GeneQueryTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._op = SetupHelper.createOrthoXMLParserFromSimpleEx() <NEW_LINE> self._tax = fa.TaxonomyFactory.newTaxonomy(self._op) <NEW_LINE> self._op.augmentTaxonomyInfo(self._tax) <NEW_LINE> self._input_query = fa.OrthoXMLQuery.getInputGenes <NEW_LINE> self._grouped_query = fa.OrthoXMLQuery.getGroupedGenes <NEW_LINE> <DEDENT> def test_all_input_genes(self): <NEW_LINE> <INDENT> expected_ids = {'1', '2', '3', '5', '11', '12', '13', '14', '21', '22', '23', '31', '32', '33', '34', '41', '43', '51', '53'} <NEW_LINE> result_nodes = self._input_query(self._op.root) <NEW_LINE> result_ids = {n.get('id') for n in result_nodes} <NEW_LINE> self.assertEqual(result_ids, expected_ids) <NEW_LINE> <DEDENT> def test_filtered_input_genes(self): <NEW_LINE> <INDENT> filters = ['HUMAN', 'PANTR', 'CANFA', 'MOUSE', 'RATNO', 'XENTR'] <NEW_LINE> expected_ids = dict(HUMAN={'1', '2', '3', '5'}, PANTR={'11', '12', '13', '14'}, CANFA={'21', '22', '23'}, MOUSE={'31', '32', '33', '34'}, RATNO={'41', '43'}, XENTR={'51', '53'}) <NEW_LINE> for filter_ in filters: <NEW_LINE> <INDENT> result_nodes = self._input_query(self._op.root, filter_) <NEW_LINE> result_ids = {n.get('id') for n in result_nodes} <NEW_LINE> self.assertEqual(result_ids, expected_ids[filter_], 'failed with {}'.format(filter_)) <NEW_LINE> <DEDENT> <DEDENT> def test_all_grouped_genes(self): <NEW_LINE> <INDENT> expected_ids = {'1', '2', '3', '11', '12', '13', '14', '21', '22', '23', '31', '32', '33', '34', '41', '51', '53'} <NEW_LINE> result_nodes = self._grouped_query(self._op.root) <NEW_LINE> result_ids = {n.get('id') for n in result_nodes} <NEW_LINE> self.assertEqual(result_ids, expected_ids) <NEW_LINE> <DEDENT> def test_filtered_grouped_genes(self): <NEW_LINE> <INDENT> filters = ['HUMAN', 'PANTR', 'CANFA', 'MOUSE', 'RATNO', 'XENTR'] <NEW_LINE> expected_ids = dict(HUMAN={'1', '2', '3'}, PANTR={'11', '12', '13', '14'}, CANFA={'21', '22', '23'}, MOUSE={'31', '32', '33', '34'}, RATNO={'41'}, XENTR={'51', '53'}) <NEW_LINE> for filter_ in filters: <NEW_LINE> <INDENT> result_nodes = self._grouped_query(self._op.root, filter_) <NEW_LINE> result_ids = {n.get('id') for n in result_nodes} <NEW_LINE> self.assertEqual(result_ids, expected_ids[filter_], 'failed with {}'.format(filter_)) | tests the OrthoXMLQuery methods getInputGenes and getGroupedGenes,
with and without species filters | 62598fd58a349b6b43686730 |
class IndexState(object): <NEW_LINE> <INDENT> SUCCESS = 'SUCCESS' <NEW_LINE> RUNNING = 'RUNNING' <NEW_LINE> FAILURE = 'FAILURE' <NEW_LINE> PARTIAL_SUCCESS = 'PARTIAL_SUCCESS' <NEW_LINE> TIMEOUT = 'TIMEOUT' <NEW_LINE> CREATED = 'CREATED' | Possible states for the inventory/scanner index. | 62598fd5be7bc26dc92520cf |
class returnPyArgument( ReturnValues ): <NEW_LINE> <INDENT> argNames = ('name',) <NEW_LINE> indexLookups = [ ('index','name', 'pyArgIndex' ), ] <NEW_LINE> __slots__ = ( 'index', 'name' ) <NEW_LINE> def __call__( self, result, baseOperation, pyArgs, cArgs ): <NEW_LINE> <INDENT> return pyArgs[self.index] | ReturnValues returning the named pyArgs value | 62598fd5283ffb24f3cf3d71 |
class StubEtcd(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.request_queue = Queue() <NEW_LINE> self.response_queue = Queue() <NEW_LINE> self.headers = { "x-etcd-cluster-id": "abcdefg" } <NEW_LINE> self.lock = threading.Lock() <NEW_LINE> self.open_reqs = set() <NEW_LINE> <DEDENT> def request(self, key, **kwargs): <NEW_LINE> <INDENT> _log.info("New request on thread %s: %s, %s", threading.current_thread(), key, kwargs) <NEW_LINE> request = StubRequest(self, key, kwargs) <NEW_LINE> with self.lock: <NEW_LINE> <INDENT> self.open_reqs.add(request) <NEW_LINE> rq = self.request_queue <NEW_LINE> if rq is None: <NEW_LINE> <INDENT> _log.warn("Request after shutdown: %s, %s", key, kwargs) <NEW_LINE> raise SystemExit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rq.put(request) <NEW_LINE> <DEDENT> <DEDENT> response = request.get_response() <NEW_LINE> if isinstance(response, BaseException): <NEW_LINE> <INDENT> raise response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> <DEDENT> def get_next_request(self): <NEW_LINE> <INDENT> _log.info("Waiting for next request") <NEW_LINE> req = self.request_queue.get(timeout=1) <NEW_LINE> _log.info("Got request %s", req) <NEW_LINE> return req <NEW_LINE> <DEDENT> def assert_request(self, expected_key, **expected_args): <NEW_LINE> <INDENT> req = self.request_queue.get(timeout=1) <NEW_LINE> req.assert_request(expected_key, **expected_args) <NEW_LINE> return req <NEW_LINE> <DEDENT> def on_req_closed(self, req): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.open_reqs.remove(req) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> _log.info("Stopping stub etcd") <NEW_LINE> with self.lock: <NEW_LINE> <INDENT> _log.info("stop() got rq_lock") <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> req = self.request_queue.get_nowait() <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.open_reqs.add(req) <NEW_LINE> <DEDENT> <DEDENT> self.request_queue = None <NEW_LINE> <DEDENT> for req in list(self.open_reqs): <NEW_LINE> <INDENT> _log.info("Aborting request %s", req) <NEW_LINE> req.stop() <NEW_LINE> <DEDENT> _log.info("Stub etcd stopped; future requests should self-abort") | A fake connection to etcd. We hook the driver's _issue_etcd_request
method and block the relevant thread until the test calls one of the
respond_... methods. | 62598fd5adb09d7d5dc0aa6a |
class TestMovies(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 test_find_year_for_title(self): <NEW_LINE> <INDENT> harness = ( ("Starwars (1977)", "1977",), ("2001 A space odyssey 1968", "1968",), ("2010", None,), ("1985.", None,), (".1985", "1985",), ("75", None,), ) <NEW_LINE> for given, expected in harness: <NEW_LINE> <INDENT> self.assertEqual(movies.find_year(given), expected) <NEW_LINE> <DEDENT> <DEDENT> def test_count_freq_of_decade(self): <NEW_LINE> <INDENT> inputs = ( "Jaws (1975)", "Starwars 1977", "2001 A Space Odyssey ( 1968 )", "Back to the future 1985.", "Raiders of the lost ark 1981 .", "jurassic park 1993", "The Matrix 1999", "A fist full of Dollars", "10,000 BC (2008)", "1941 (1979)", "24 Hour Party People (2002)", "300 (2007)", "2010", ) <NEW_LINE> harness = { "2000s" : 3, "1970s" : 3, "1980s" : 2, "1990s" : 2, "1960s" : 1 } <NEW_LINE> results = movies.rank_decades(inputs) <NEW_LINE> for decade, expected in harness.iteritems(): <NEW_LINE> <INDENT> self.assertEquals(results[decade], expected) | Test cases for the sorting of movie popularity by decade.
Given the following list in a string seperated by
characters.
Jaws (1975)
Starwars 1977
2001 A Space Odyssey ( 1968 )
Back to the future 1985.
Raiders of the lost ark 1981 .
jurassic park 1993
The Matrix 1999
A fist full of Dollars
10,000 BC (2008)
1941 (1979)
24 Hour Party People (2002)
300 (2007)
2010
Produce the following output.
2000s : 3
1970s : 3
1980s : 2
1990s : 2
1960s : 1
| 62598fd560cbc95b0636482e |
class RequestLogging(wsgi.Middleware): <NEW_LINE> <INDENT> @webob.dec.wsgify(RequestClass=wsgi.Request) <NEW_LINE> def __call__(self, req): <NEW_LINE> <INDENT> start = timeutils.utcnow() <NEW_LINE> rv = req.get_response(self.application) <NEW_LINE> self.log_request_completion(rv, req, start) <NEW_LINE> return rv <NEW_LINE> <DEDENT> def log_request_completion(self, response, request, start): <NEW_LINE> <INDENT> apireq = request.environ.get('ec2.request', None) <NEW_LINE> if apireq: <NEW_LINE> <INDENT> controller = apireq.controller <NEW_LINE> action = apireq.action <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> controller = None <NEW_LINE> action = None <NEW_LINE> <DEDENT> ctxt = request.environ.get('patron.context', None) <NEW_LINE> delta = timeutils.utcnow() - start <NEW_LINE> seconds = delta.seconds <NEW_LINE> microseconds = delta.microseconds <NEW_LINE> LOG.info( "%s.%ss %s %s %s %s:%s %s [%s] %s %s", seconds, microseconds, request.remote_addr, request.method, "%s%s" % (request.script_name, request.path_info), controller, action, response.status_int, request.user_agent, request.content_type, response.content_type, context=ctxt) | Access-Log akin logging for all EC2 API requests. | 62598fd5ad47b63b2c5a7d43 |
class PubSubModerationActionBanRequest(PubSubMessage): <NEW_LINE> <INDENT> __slots__ = "action", "args", "created_by", "message_id", "target" <NEW_LINE> def __init__(self, client: Client, topic: str, data: dict): <NEW_LINE> <INDENT> super().__init__(client, topic, data) <NEW_LINE> self.action: str = data["message"]["data"]["moderation_action"] <NEW_LINE> self.args: List[str] = data["message"]["data"]["moderator_message"] <NEW_LINE> self.created_by = PartialUser( client._http, data["message"]["data"]["created_by_id"], data["message"]["data"]["created_by_login"] ) <NEW_LINE> self.target = ( PartialUser( client._http, data["message"]["data"]["target_user_id"], data["message"]["data"]["target_user_login"] ) if data["message"]["data"]["target_user_id"] else None ) | A Ban/Unban event
Attributes
-----------
action: :class:`str`
The action taken.
args: List[:class:`str`]
The arguments given to the command.
created_by: :class:`twitchio.PartialUser`
The user that created the action.
target: :class:`twitchio.PartialUser`
The target of this action. | 62598fd550812a4eaa620e5c |
class Dipendente(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Dipendente' <NEW_LINE> verbose_name_plural = 'Dipendenti' <NEW_LINE> <DEDENT> nome = models.CharField(max_length=32) <NEW_LINE> cognome = models.CharField(max_length=32) <NEW_LINE> sesso = models.CharField(max_length=7, choices=SESSO) <NEW_LINE> dataNascita = models.DateField() <NEW_LINE> codiceFiscale = models.CharField(max_length=16) <NEW_LINE> email = models.CharField(max_length=32) <NEW_LINE> telefono = PhoneNumberField() <NEW_LINE> domicilio = models.CharField(max_length=32) <NEW_LINE> mansione = models.ForeignKey(Mansione) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.codiceFiscale + ' - ' + self.nome+' '+ self.cognome | La classe Dipendente identifica un dipendente all'interno di un'azienda.
Gli attributi di classe specificano le caratteristiche possedute da un dipendente. | 62598fd5656771135c489b64 |
class CourseSocialNetworkTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(CourseSocialNetworkTests, self).setUp() <NEW_LINE> self.network = factories.CourseRunSocialNetworkFactory() <NEW_LINE> self.course_run = factories.CourseRunFactory() <NEW_LINE> <DEDENT> def test_str(self): <NEW_LINE> <INDENT> self.assertEqual( str(self.network), '{type}: {value}'.format(type=self.network.type, value=self.network.value) ) <NEW_LINE> <DEDENT> def test_unique_constraint(self): <NEW_LINE> <INDENT> factories.CourseRunSocialNetworkFactory(course_run=self.course_run, type='facebook') <NEW_LINE> with self.assertRaises(IntegrityError): <NEW_LINE> <INDENT> factories.CourseRunSocialNetworkFactory(course_run=self.course_run, type='facebook') | Tests of the CourseSocialNetwork model. | 62598fd5c4546d3d9def74fc |
class Solution: <NEW_LINE> <INDENT> def sortIntegers2(self, A): <NEW_LINE> <INDENT> if A is None or len(A) == 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> self.quick_sort(A, 0, len(A) - 1) <NEW_LINE> return A <NEW_LINE> <DEDENT> def quick_sort(self, A, start, end): <NEW_LINE> <INDENT> if start >= end: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> left = start <NEW_LINE> right = end <NEW_LINE> pivot = A[start + (end - start) // 2] <NEW_LINE> while left <= right: <NEW_LINE> <INDENT> while left <= right and A[left] < pivot: <NEW_LINE> <INDENT> left += 1 <NEW_LINE> <DEDENT> while left <= right and A[right] > pivot: <NEW_LINE> <INDENT> right -= 1 <NEW_LINE> <DEDENT> if left <= right: <NEW_LINE> <INDENT> A[left], A[right] = A[right], A[left] <NEW_LINE> left += 1 <NEW_LINE> right -= 1 <NEW_LINE> <DEDENT> <DEDENT> self.quick_sort(A, start, right) <NEW_LINE> self.quick_sort(A, left, end) | @param A: an integer array
@return: nothing | 62598fd58a349b6b43686734 |
class Tags(object): <NEW_LINE> <INDENT> def __init__(self, patterns=TAGS_ANDROID, reverse=TAG_REVERSE_ANDROID): <NEW_LINE> <INDENT> self.tags = set() <NEW_LINE> self.patterns = patterns <NEW_LINE> self.reverse = TAG_REVERSE_ANDROID <NEW_LINE> for i in self.patterns: <NEW_LINE> <INDENT> self.patterns[i][1] = re.compile(self.patterns[i][1]) <NEW_LINE> <DEDENT> <DEDENT> def emit(self, method): <NEW_LINE> <INDENT> for i in self.patterns: <NEW_LINE> <INDENT> if self.patterns[i][0] == 0: <NEW_LINE> <INDENT> if self.patterns[i][1].search(method.get_class()) is not None: <NEW_LINE> <INDENT> self.tags.add(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def emit_by_classname(self, classname): <NEW_LINE> <INDENT> for i in self.patterns: <NEW_LINE> <INDENT> if self.patterns[i][0] == 0: <NEW_LINE> <INDENT> if self.patterns[i][1].search(classname) is not None: <NEW_LINE> <INDENT> self.tags.add(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_list(self): <NEW_LINE> <INDENT> return [self.reverse[i] for i in self.tags] <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.tags <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str([self.reverse[i] for i in self.tags]) <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> return self.tags == set() | Handle specific tags
:param patterns:
:params reverse: | 62598fd53d592f4c4edbb3a9 |
class SearchFacetsView(BrowserView, FacetMixin): <NEW_LINE> <INDENT> def __call__(self, *args, **kw): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.kw = kw <NEW_LINE> return super(SearchFacetsView, self).__call__(*args, **kw) <NEW_LINE> <DEDENT> def facets(self): <NEW_LINE> <INDENT> results = self.kw.get('results', None) <NEW_LINE> fcs = getattr(results, 'facet_counts', None) <NEW_LINE> if results is not None and fcs is not None: <NEW_LINE> <INDENT> filter = lambda name, count: name and count > 0 <NEW_LINE> return convertFacets(fcs.get('facet_fields', {}), self.context, self.request, filter) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def selected(self): <NEW_LINE> <INDENT> info = [] <NEW_LINE> facets = param(self, 'facet.field') <NEW_LINE> fq = param(self, 'fq') <NEW_LINE> for idx, query in enumerate(fq): <NEW_LINE> <INDENT> field, value = query.split(':', 1) <NEW_LINE> params = self.request.form.copy() <NEW_LINE> params['fq'] = fq[:idx] + fq[idx+1:] <NEW_LINE> if field not in facets: <NEW_LINE> <INDENT> params['facet.field'] = facets + [field] <NEW_LINE> <DEDENT> if value.startswith('"') and value.endswith('"'): <NEW_LINE> <INDENT> vfactory = queryUtility(IFacetTitleVocabularyFactory, name=field) <NEW_LINE> if vfactory is None: <NEW_LINE> <INDENT> vfactory = getUtility(IFacetTitleVocabularyFactory) <NEW_LINE> <DEDENT> vocabulary = vfactory(self.context) <NEW_LINE> value = value[1:-1] <NEW_LINE> if value in vocabulary: <NEW_LINE> <INDENT> value = vocabulary.getTerm(value).title <NEW_LINE> <DEDENT> if isinstance(value, Message): <NEW_LINE> <INDENT> value = translate(value, context=self.request) <NEW_LINE> <DEDENT> info.append(dict(title=field, value=value, query=urlencode(params, doseq=True))) <NEW_LINE> <DEDENT> <DEDENT> return info | view for displaying facetting info as provided by solr searches | 62598fd5be7bc26dc92520d1 |
class TimestampParam(Parameter): <NEW_LINE> <INDENT> def __init__(self, alias=None, required=False, default=None, validate=None): <NEW_LINE> <INDENT> Parameter.__init__(self, alias=alias, required=required, default=default, validate=validate) <NEW_LINE> <DEDENT> def convert(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> converted = float(value) <NEW_LINE> if math.isnan( converted ): <NEW_LINE> <INDENT> raise ConversionError(self, value) <NEW_LINE> <DEDENT> return datetime.fromtimestamp( converted ) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ConversionError(self, value) | Parameter for timestamp values | 62598fd5ec188e330fdf8d8a |
class CarePlanSymptomTemplateViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = CarePlanSymptomTemplateSerializer <NEW_LINE> permission_classes = ( permissions.IsAuthenticated, IsEmployeeOrPatientReadOnly, ) <NEW_LINE> filter_backends = (DjangoFilterBackend, ) <NEW_LINE> filterset_fields = ( 'plan', 'symptom_task_template', ) <NEW_LINE> queryset = CarePlanSymptomTemplate.objects.all() <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> qs = super(CarePlanSymptomTemplateViewSet, self).get_queryset() <NEW_LINE> user = self.request.user <NEW_LINE> if user.is_employee: <NEW_LINE> <INDENT> employee_profile = user.employee_profile <NEW_LINE> if employee_profile.organizations_managed.exists(): <NEW_LINE> <INDENT> organizations = employee_profile.organizations_managed.all() <NEW_LINE> qs = qs.filter( plan__patient__facility__organization__in=organizations) <NEW_LINE> <DEDENT> elif employee_profile.facilities_managed.exists(): <NEW_LINE> <INDENT> facilities = employee_profile.facilities_managed.all() <NEW_LINE> assigned_roles = employee_profile.assigned_roles.all() <NEW_LINE> qs = qs.filter( Q(plan__patient__facility__in=facilities) | Q(plan__care_team_members__in=assigned_roles) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assigned_roles = employee_profile.assigned_roles.all() <NEW_LINE> qs = qs.filter(plan__care_team_members__in=assigned_roles) <NEW_LINE> <DEDENT> <DEDENT> elif user.is_patient: <NEW_LINE> <INDENT> qs = qs.filter(plan__patient=user.patient_profile) <NEW_LINE> <DEDENT> return qs.distinct() | Viewset for :model:`tasks.CarePlanSymptomTemplate`
========
create:
Creates :model:`tasks.CarePlanSymptomTemplate` object.
Only admins and employees are allowed to perform this action.
update:
Updates :model:`tasks.CarePlanSymptomTemplate` object.
Only admins and employees who belong to the same care team are allowed
to perform this action.
partial_update:
Updates one or more fields of an existing plan symptom template object.
Only admins and employees who belong to the same care team are allowed
to perform this action.
retrieve:
Retrieves a :model:`tasks.CarePlanSymptomTemplate` instance.
Admins will have access to all plan symptom template objects. Employees
will only have access to those plan symptom templates belonging to its
own care team. Patients will have access to all plan symptom templates
assigned to them.
list:
Returns list of all :model:`tasks.CarePlanSymptomTemplate` objects.
Admins will get all existing plan symptom template objects. Employees
will get the plan symptom templates belonging to a certain care team.
Patients will get all plan symptom templates belonging to them.
delete:
Deletes a :model:`tasks.CarePlanSymptomTemplate` instance.
Only admins and employees who belong to the same care team are allowed
to perform this action. | 62598fd5956e5f7376df58f7 |
class TestBase(unittest.TestCase): <NEW_LINE> <INDENT> def are_lists_equal(self, list1, list2, equality_method=lambda x, y: x == y): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> if len(list1) != len(list2): <NEW_LINE> <INDENT> raise AssertionError( "length of {} is not equal to length of {}\n {} != {}".format(list1, list2, len(list1), len(list2))) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> for i in range(len(list1)): <NEW_LINE> <INDENT> self.are_equal(list1[i], list2[i], equality_method) <NEW_LINE> <DEDENT> <DEDENT> except AssertionError as err: <NEW_LINE> <INDENT> raise AssertionError("Assertion error on element {}: {}".format(i, err)) <NEW_LINE> <DEDENT> <DEDENT> def are_equal(self, obj1, obj2, equality_method=lambda x, y: x == y): <NEW_LINE> <INDENT> if not equality_method(obj1, obj2): <NEW_LINE> <INDENT> message = pytest_assertrepr_compare("==", obj1, obj2) <NEW_LINE> if message is not None: <NEW_LINE> <INDENT> raise AssertionError('\n'.join(message)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AssertionError("{} != {} ".format(obj1, obj2)) | Testing base class | 62598fd50fa83653e46f53dc |
class Bind(Statement): <NEW_LINE> <INDENT> match = re.compile(r'bind\s*\(.*\)',re.I).match <NEW_LINE> def process_item(self): <NEW_LINE> <INDENT> line = self.item.line <NEW_LINE> self.specs, line = parse_bind(line, self.item) <NEW_LINE> if line.startswith('::'): <NEW_LINE> <INDENT> line = line[2:].lstrip() <NEW_LINE> <DEDENT> items = [] <NEW_LINE> for item in split_comma(line, self.item): <NEW_LINE> <INDENT> if item.startswith('/'): <NEW_LINE> <INDENT> assert item.endswith('/'),repr(item) <NEW_LINE> item = '/ ' + item[1:-1].strip() + ' /' <NEW_LINE> <DEDENT> items.append(item) <NEW_LINE> <DEDENT> self.items = items <NEW_LINE> return <NEW_LINE> <DEDENT> def tofortran(self, isfix=None): <NEW_LINE> <INDENT> return self.get_indent_tab(isfix=isfix) + 'BIND (%s) %s' % (', '.join(self.specs), ', '.join(self.items)) | <language-binding-spec> [ :: ] <bind-entity-list>
<language-binding-spec> = BIND ( C [ , NAME = <scalar-char-initialization-expr> ] )
<bind-entity> = <entity-name> | / <common-block-name> / | 62598fd5377c676e912f6ff4 |
class MoveByCar(Movable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._speed = 0.0001 <NEW_LINE> self._min_distance_radius = 10 | Движение на машине | 62598fd5c4546d3d9def74fd |
class FormatCBFFullPilatusDLS6MSN100(FormatCBFFullPilatus): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def understand(image_file): <NEW_LINE> <INDENT> header = FormatCBFFullPilatus.get_cbf_header(image_file) <NEW_LINE> for record in header.split("\n"): <NEW_LINE> <INDENT> if ( "# Detector" in record and "PILATUS" in record and "S/N 60-0100 Diamond" in header ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def has_dynamic_shadowing(**kwargs): <NEW_LINE> <INDENT> dynamic_shadowing = kwargs.get("dynamic_shadowing", False) <NEW_LINE> if dynamic_shadowing in (libtbx.Auto, "Auto"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return dynamic_shadowing <NEW_LINE> <DEDENT> def __init__(self, image_file, **kwargs): <NEW_LINE> <INDENT> self._dynamic_shadowing = self.has_dynamic_shadowing(**kwargs) <NEW_LINE> super().__init__(image_file, **kwargs) <NEW_LINE> <DEDENT> def get_goniometer_shadow_masker(self, goniometer=None): <NEW_LINE> <INDENT> if goniometer is None: <NEW_LINE> <INDENT> goniometer = self.get_goniometer() <NEW_LINE> <DEDENT> assert goniometer is not None <NEW_LINE> if goniometer.get_names()[1] == "GON_CHI": <NEW_LINE> <INDENT> return GoniometerMaskerFactory.smargon(goniometer) <NEW_LINE> <DEDENT> elif goniometer.get_names()[1] == "GON_KAPPA": <NEW_LINE> <INDENT> return GoniometerMaskerFactory.mini_kappa(goniometer) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( "Don't understand this goniometer: %s" % list(goniometer.get_names()) ) | An image reading class for full CBF format images from Pilatus
detectors. | 62598fd5ab23a570cc2d4fe8 |
class Grp70No160(base_tests.SimpleDataPlane): <NEW_LINE> <INDENT> @wireshark_capture <NEW_LINE> def runTest(self): <NEW_LINE> <INDENT> logging = get_logger() <NEW_LINE> logging.info("Running Grp70No160 Strip vlan header test") <NEW_LINE> of_ports = config["port_map"].keys() <NEW_LINE> of_ports.sort() <NEW_LINE> self.assertTrue(len(of_ports) > 1,"Not enogh ports for test") <NEW_LINE> rv = delete_all_flows(self.controller) <NEW_LINE> self.assertEqual(rv, 0, "Failed to delete all flows") <NEW_LINE> self.assertEqual(do_barrier(self.controller),0,"Barrier failed") <NEW_LINE> logging.info("Creating a vlan tagged packet") <NEW_LINE> pkt = simple_tcp_packet(pktlen=104, dl_vlan_enable=True, dl_vlan=3) <NEW_LINE> exp_pkt = simple_tcp_packet() <NEW_LINE> match=parse.packet_to_flow_match(pkt) <NEW_LINE> self.assertTrue(match is not None, "Could not generate a match from the packet") <NEW_LINE> match.wildcards = ofp.OFPFW_ALL ^ofp.OFPFW_DL_VLAN <NEW_LINE> msg = message.flow_mod() <NEW_LINE> msg.outport=ofp.OFPP_NONE <NEW_LINE> msg.command=ofp.OFPFC_ADD <NEW_LINE> msg.buffer_id=0xffffffff <NEW_LINE> msg.match=match <NEW_LINE> act=action.action_strip_vlan() <NEW_LINE> self.assertTrue(msg.actions.add(act), "could not add strip vlan action") <NEW_LINE> act=action.action_output() <NEW_LINE> act.port=of_ports[1] <NEW_LINE> self.assertTrue(msg.actions.add(act),"could not add output action") <NEW_LINE> logging.info("Installing a flow entry") <NEW_LINE> rv=self.controller.message_send(msg) <NEW_LINE> self.assertTrue(rv!=-1,"Error Could not send a flow_mod") <NEW_LINE> self.assertEqual(do_barrier(self.controller),0,"Barrier failed") <NEW_LINE> logging.info("sending a matching packet") <NEW_LINE> self.dataplane.send(of_ports[0], str(pkt)) <NEW_LINE> receive_pkt_check(self.dataplane, exp_pkt, [of_ports[1]], set(of_ports).difference([of_ports[1]]),self) | Strip vlan header | 62598fd550812a4eaa620e5e |
class Property: <NEW_LINE> <INDENT> def __init__(self, name: str, signature: str, access: PropertyAccess = PropertyAccess.READWRITE): <NEW_LINE> <INDENT> assert_member_name_valid(name) <NEW_LINE> if hasattr(signature, 'tree'): <NEW_LINE> <INDENT> signature = signature.tree.signature <NEW_LINE> <DEDENT> tree = SignatureTree._get(signature) <NEW_LINE> if len(tree.types) != 1: <NEW_LINE> <INDENT> raise InvalidIntrospectionError( f'properties must have a single complete type. (has {len(tree.types)} types)') <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> self.signature = signature <NEW_LINE> self.access = access <NEW_LINE> self.type = tree.types[0] <NEW_LINE> <DEDENT> def from_xml(element): <NEW_LINE> <INDENT> name = element.attrib.get('name') <NEW_LINE> signature = element.attrib.get('type') <NEW_LINE> access = PropertyAccess(element.attrib.get('access', 'readwrite')) <NEW_LINE> if not name: <NEW_LINE> <INDENT> raise InvalidIntrospectionError('properties must have a "name" attribute') <NEW_LINE> <DEDENT> if not signature: <NEW_LINE> <INDENT> raise InvalidIntrospectionError('properties must have a "type" attribute') <NEW_LINE> <DEDENT> return Property(name, signature, access) <NEW_LINE> <DEDENT> def to_xml(self) -> ET.Element: <NEW_LINE> <INDENT> element = ET.Element('property') <NEW_LINE> element.set('name', self.name) <NEW_LINE> element.set('type', _sig(self)) <NEW_LINE> element.set('access', self.access.value) <NEW_LINE> return element | A class that represents a DBus property exposed on an
:class:`Interface`.
:ivar name: The name of this property.
:vartype name: str
:ivar signature: The signature string for this property. Must be a single complete type.
:vartype signature: str
:ivar access: Whether this property is readable and writable.
:vartype access: :class:`PropertyAccess <asyncdbus.PropertyAccess>`
:ivar type: The parsed type of this property.
:vartype type: :class:`SignatureType <asyncdbus.SignatureType>`
:raises:
- :class:`InvalidIntrospectionError <asyncdbus.InvalidIntrospectionError>` - If the property is not a single complete type.
- :class `InvalidSignatureError <asyncdbus.InvalidSignatureError>` - If the given signature is not valid.
- :class: `InvalidMemberNameError <asyncdbus.InvalidMemberNameError>` - If the member name is not valid. | 62598fd53617ad0b5ee0663e |
class LibvirtNonblockingTestCase(test.NoDBTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(LibvirtNonblockingTestCase, self).setUp() <NEW_LINE> self.flags(connection_uri="test:///default", group='libvirt') <NEW_LINE> <DEDENT> def test_connection_to_primitive(self): <NEW_LINE> <INDENT> import nova.virt.libvirt.driver as libvirt_driver <NEW_LINE> drvr = libvirt_driver.LibvirtDriver('') <NEW_LINE> drvr.set_host_enabled = mock.Mock() <NEW_LINE> jsonutils.to_primitive(drvr._conn, convert_instances=True) <NEW_LINE> <DEDENT> @mock.patch.object(objects.Service, 'get_by_compute_host') <NEW_LINE> def test_tpool_execute_calls_libvirt(self, mock_svc): <NEW_LINE> <INDENT> conn = fakelibvirt.virConnect() <NEW_LINE> conn.is_expected = True <NEW_LINE> self.mox.StubOutWithMock(eventlet.tpool, 'execute') <NEW_LINE> eventlet.tpool.execute( fakelibvirt.openAuth, 'test:///default', mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(conn) <NEW_LINE> eventlet.tpool.execute( conn.domainEventRegisterAny, None, fakelibvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, mox.IgnoreArg(), mox.IgnoreArg()) <NEW_LINE> if hasattr(fakelibvirt.virConnect, 'registerCloseCallback'): <NEW_LINE> <INDENT> eventlet.tpool.execute( conn.registerCloseCallback, mox.IgnoreArg(), mox.IgnoreArg()) <NEW_LINE> <DEDENT> self.mox.ReplayAll() <NEW_LINE> driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) <NEW_LINE> c = driver._get_connection() <NEW_LINE> self.assertTrue(c.is_expected) | Test libvirtd calls are nonblocking. | 62598fd58a349b6b43686738 |
class MainMenu(Menu): <NEW_LINE> <INDENT> def __init__(self, master=None, **kwargs): <NEW_LINE> <INDENT> Menu.__init__(self, master, **kwargs) <NEW_LINE> file_menu = Menu(self, tearoff=0) <NEW_LINE> file_menu.add_command(label='Save Data', command=lambda: self.save_data) <NEW_LINE> file_menu.add_command(label='Exit', command=self.quit) <NEW_LINE> self.add_cascade(label='File', underline=0, menu=file_menu) <NEW_LINE> data_menu = Menu(self, tearoff=0) <NEW_LINE> data_menu.add_command(label='Courses', command=lambda:self.master.show_frame("CourseFrame")) <NEW_LINE> data_menu.add_command(label='Enrollment', command=lambda:self.master.show_frame("EnrollmentFrame")) <NEW_LINE> data_menu.add_command(label='Student', command=lambda:self.master.show_frame("StudentFrame")) <NEW_LINE> self.add_cascade(label='Data', underline=0, menu=data_menu) <NEW_LINE> help_menu = Menu(self, tearoff=0) <NEW_LINE> help_menu.add_command(label='About', command=lambda:self.master.show_frame("AboutFrame")) <NEW_LINE> self.add_cascade(label='Help', underline=0, menu=help_menu) | Main menu for the Contoso App | 62598fd5099cdd3c6367565a |
class FieldFile(_FileProxyMixin): <NEW_LINE> <INDENT> def __init__(self, instance, field, file_id): <NEW_LINE> <INDENT> self.instance = instance <NEW_LINE> self.field = field <NEW_LINE> self.file_id = file_id <NEW_LINE> self.storage = field.storage <NEW_LINE> self._file = None <NEW_LINE> self._committed = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def file(self): <NEW_LINE> <INDENT> if self._file is None: <NEW_LINE> <INDENT> self.open() <NEW_LINE> <DEDENT> return self._file <NEW_LINE> <DEDENT> @file.setter <NEW_LINE> def file(self, file): <NEW_LINE> <INDENT> self._file = file <NEW_LINE> <DEDENT> def save(self, name, content): <NEW_LINE> <INDENT> self.file_id = self.storage.save(name, content, self.metadata) <NEW_LINE> setattr(self.instance, self.field.attname, self.file_id) <NEW_LINE> self._committed = True <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> self.storage.delete(self.file_id) <NEW_LINE> delattr(self.instance, self.field.attname) <NEW_LINE> self._committed = False <NEW_LINE> <DEDENT> def open(self, mode='rb'): <NEW_LINE> <INDENT> self.close() <NEW_LINE> self._file = self.storage.open(self.file_id, mode) <NEW_LINE> self._committed = True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self._file is not None: <NEW_LINE> <INDENT> self._file.close() <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, File): <NEW_LINE> <INDENT> return self.file_id == other.file_id <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | Type returned when accessing a :class:`~pymodm.fields.FileField`.
This type is just a thin wrapper around a :class:`~pymodm.files.File` and
can be treated as a file-like object in most places where a `file` is
expected. | 62598fd5d8ef3951e32c80d7 |
class UnexpectedTokenError(RuntimeError): <NEW_LINE> <INDENT> def __init__(self, line: int, line_index: int, token: str, message: str = ""): <NEW_LINE> <INDENT> self.__line = line <NEW_LINE> self.__line_index = line_index <NEW_LINE> self.__token = token <NEW_LINE> self.__message = f"Unexpected token {token} on line {line} at {line_index}.\n{message}" <NEW_LINE> super().__init__(self.__message) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Line: {self.__line}\nLine Index: {self.__line_index}\nToken: {self.__token}\n{super().__repr__()}" | Error thrown when a token is not part of the MLP. | 62598fd5ad47b63b2c5a7d49 |
class InboundNatRuleListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[InboundNatRule]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(InboundNatRuleListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = None | Response for ListInboundNatRule API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of inbound nat rules in a load balancer.
:type value: list[~azure.mgmt.network.v2020_04_01.models.InboundNatRule]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str | 62598fd550812a4eaa620e5f |
class getAdUsersByCid_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I32, 'creator_id', None, None, ), (2, TType.I32, 'account_status', None, None, ), ) <NEW_LINE> def __init__(self, creator_id=None, account_status=None,): <NEW_LINE> <INDENT> self.creator_id = creator_id <NEW_LINE> self.account_status = account_status <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.creator_id = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.account_status = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getAdUsersByCid_args') <NEW_LINE> if self.creator_id is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('creator_id', TType.I32, 1) <NEW_LINE> oprot.writeI32(self.creator_id) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.account_status is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('account_status', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.account_status) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- creator_id
- account_status | 62598fd57cff6e4e811b5f23 |
class BugStatusUnknownError(Exception): <NEW_LINE> <INDENT> pass | We have encountered a bug whose status is unknown to us.
See :mod:`pulp_smash.selectors` for more information on how bug statuses
are used. | 62598fd560cbc95b06364837 |
class RetrieveWorksheetsResultSet(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. ((XML) The response from Google) | 62598fd5ec188e330fdf8d90 |
class MAVLink_ping_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_PING <NEW_LINE> name = 'PING' <NEW_LINE> fieldnames = ['time_usec', 'seq', 'target_system', 'target_component'] <NEW_LINE> ordered_fieldnames = [ 'time_usec', 'seq', 'target_system', 'target_component' ] <NEW_LINE> format = '<QIBB' <NEW_LINE> native_format = bytearray('<QIBB', 'ascii') <NEW_LINE> orders = [0, 1, 2, 3] <NEW_LINE> lengths = [1, 1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0, 0] <NEW_LINE> crc_extra = 237 <NEW_LINE> def __init__(self, time_usec, seq, target_system, target_component): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_ping_message.id, MAVLink_ping_message.name) <NEW_LINE> self._fieldnames = MAVLink_ping_message.fieldnames <NEW_LINE> self.time_usec = time_usec <NEW_LINE> self.seq = seq <NEW_LINE> self.target_system = target_system <NEW_LINE> self.target_component = target_component <NEW_LINE> <DEDENT> def pack(self, mav, force_mavlink1=False): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 237, struct.pack('<QIBB', self.time_usec, self.seq, self.target_system, self.target_component), force_mavlink1=force_mavlink1) | A ping message either requesting or responding to a ping. This
allows to measure the system latencies, including serial port,
radio modem and UDP connections. | 62598fd5be7bc26dc92520d4 |
class CacheHandler(urllib2.BaseHandler): <NEW_LINE> <INDENT> def __init__(self,cacheLocation): <NEW_LINE> <INDENT> self.cacheLocation = lazylibrarian.DATADIR + os.sep + cacheLocation <NEW_LINE> if not os.path.exists(self.cacheLocation): <NEW_LINE> <INDENT> os.mkdir(self.cacheLocation) <NEW_LINE> <DEDENT> <DEDENT> def default_open(self,request): <NEW_LINE> <INDENT> if ((request.get_method() == "GET") and (CachedResponse.ExistsInCache(self.cacheLocation, request.get_full_url()))): <NEW_LINE> <INDENT> return CachedResponse(self.cacheLocation, request.get_full_url(), setCacheHeader=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def http_response(self, request, response): <NEW_LINE> <INDENT> if request.get_method() == "GET": <NEW_LINE> <INDENT> if 'x-local-cache' in response.info(): <NEW_LINE> <INDENT> return CachedResponse(self.cacheLocation, request.get_full_url(), setCacheHeader=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> CachedResponse.StoreInCache(self.cacheLocation, request.get_full_url(), response) <NEW_LINE> return CachedResponse(self.cacheLocation, request.get_full_url(), setCacheHeader=False) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return response | Stores responses in a persistant on-disk cache.
If a subsequent GET request is made for the same URL, the stored
response is returned, saving time, resources and bandwith | 62598fd5bf627c535bcb19aa |
class MismatchingBlockEnd(Exception): <NEW_LINE> <INDENT> pass | When an BlockEnd with a name not matching the current block is found | 62598fd5ad47b63b2c5a7d4c |
class CreateChartModel(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'Name', 'type': 'str'}, 'is_public': {'key': 'IsPublic', 'type': 'bool'}, } <NEW_LINE> def __init__(self, *, name: str=None, is_public: bool=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(CreateChartModel, self).__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.is_public = is_public | CreateChartModel.
:param name:
:type name: str
:param is_public:
:type is_public: bool | 62598fd550812a4eaa620e61 |
class XfconfProptype(Enum): <NEW_LINE> <INDENT> INT = "int" <NEW_LINE> UINT = "uint" <NEW_LINE> BOOL = "bool" <NEW_LINE> FLOAT = "float" <NEW_LINE> DOUBLE = "double" <NEW_LINE> STRING = "string" | Types of properties that can be stored in the xfconf database. | 62598fd5283ffb24f3cf3d7d |
class package(BaseNode): <NEW_LINE> <INDENT> def action(self): <NEW_LINE> <INDENT> with zipfile.ZipFile('layers_image.zip', 'w', zipfile.ZIP_DEFLATED) as tzip: <NEW_LINE> <INDENT> tzip.write("./scripter.py") <NEW_LINE> tzip.close() <NEW_LINE> <DEDENT> if not os.path.exists("./dist"): <NEW_LINE> <INDENT> os.mkdir("./dist") <NEW_LINE> <DEDENT> shutil.move("layers_image.zip", "dist/layers_image.zip") | package prject to release file (zip) | 62598fd5dc8b845886d53aba |
class GetSmartAccountListResponse(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <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, GetSmartAccountListResponse): <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. | 62598fd526238365f5fad062 |
class UnlockProtocol(protocol.Protocol): <NEW_LINE> <INDENT> name = 'unlock' <NEW_LINE> def on_interact(self): <NEW_LINE> <INDENT> if not self.args.unlock: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> formatting.print_title('Unlocking tests for {}'.format( self.assignment['name'])) <NEW_LINE> print('At each "{}",'.format(UnlockConsole.PROMPT) + ' type in what you would expect the output to be.') <NEW_LINE> print('Type {} to quit'.format(UnlockConsole.EXIT_INPUTS[0])) <NEW_LINE> for test in self._filter_tests(): <NEW_LINE> <INDENT> if test.num_cases == 0: <NEW_LINE> <INDENT> print('No tests to unlock for {}.'.format(test.name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> formatting.underline('Unlocking tests for {}'.format(test.name)) <NEW_LINE> print() <NEW_LINE> cases_unlocked, end_session = unlock( test, self.logger, self.assignment['name'], self.analytics) <NEW_LINE> if end_session: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> print() <NEW_LINE> <DEDENT> <DEDENT> return self.analytics <NEW_LINE> <DEDENT> def _filter_tests(self): <NEW_LINE> <INDENT> if self.args.question: <NEW_LINE> <INDENT> return [test for test in self.assignment.tests if self.args.question in test['names']] <NEW_LINE> <DEDENT> return self.assignment.tests | Unlocking protocol that wraps that mechanism. | 62598fd5656771135c489b70 |
class Object(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=10) <NEW_LINE> description = models.CharField(max_length=100) <NEW_LINE> num = models.IntegerField() <NEW_LINE> img = models.FileField(default='/static/img/default.png',upload_to = 'static/img/') <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) | 货物类 | 62598fd6ec188e330fdf8d96 |
class NewRemoteCommandWithArgs(_command.Command): <NEW_LINE> <INDENT> group_name = "test" <NEW_LINE> command_name = "remote_command_1" <NEW_LINE> def execute(self, arg_1, arg_2): <NEW_LINE> <INDENT> pass | New remote command that requires argument(s).
Detailed information on how to use the command. | 62598fd655399d3f05626a1a |
@dataclass <NEW_LINE> class ParameterDefinition(BaseDefinition): <NEW_LINE> <INDENT> parameterType: str = '' <NEW_LINE> defaultValue: str = '' | Defines a single parameter for a method | 62598fd6091ae3566870511b |
class InferenceDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, example_ids, data_dir, model_type='region_attention', spatial_feature_size=5, drop_num_regions=False, drop_bb_coords=False): <NEW_LINE> <INDENT> self.example_ids = example_ids <NEW_LINE> self.data_dir = data_dir <NEW_LINE> self.model_type = model_type <NEW_LINE> self.spatial_feature_size = spatial_feature_size <NEW_LINE> self.drop_num_regions = drop_num_regions <NEW_LINE> self.drop_bb_coords = drop_bb_coords <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.example_ids) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self.load(self.example_ids[index]) <NEW_LINE> <DEDENT> def get_example_id(self, index): <NEW_LINE> <INDENT> return self.example_ids[index] <NEW_LINE> <DEDENT> def load(self, example_id): <NEW_LINE> <INDENT> data = np.load(os_path.join(self.data_dir, example_id + '.npz')) <NEW_LINE> region_features = data['region_features'] <NEW_LINE> num_regions = len(region_features) <NEW_LINE> if num_regions > 0: <NEW_LINE> <INDENT> if self.model_type == 'no_attention': <NEW_LINE> <INDENT> full_image_padded = np.pad(np.expand_dims(data['full_image_features'], axis=0), pad_width=((0, 0), (0, self.spatial_feature_size)), mode='constant', constant_values=0) <NEW_LINE> region_features = np.repeat(full_image_padded, num_regions, axis=0) <NEW_LINE> <DEDENT> elif self.model_type == 'average_attention': <NEW_LINE> <INDENT> avg_regions = region_features.mean(axis=0, keepdims=True)[:, :-5] <NEW_LINE> avg_regions_padded = np.pad(avg_regions, pad_width=((0, 0), (0, self.spatial_feature_size)), mode='constant', constant_values=0) <NEW_LINE> region_features = np.repeat(avg_regions_padded, num_regions, axis=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.drop_num_regions: <NEW_LINE> <INDENT> if self.drop_bb_coords: <NEW_LINE> <INDENT> region_features = region_features[:, :-5] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> region_features = region_features[:, :-1] <NEW_LINE> <DEDENT> <DEDENT> elif self.drop_bb_coords: <NEW_LINE> <INDENT> total_size = len(region_features[0]) <NEW_LINE> region_features = region_features[:, np.r_[0:total_size-5, total_size-1:total_size]] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return {'example_id': example_id, 'full_image_features': data['full_image_features'], 'region_features': region_features} | Loads all the relevant data from disk and prepares it for collating.
Only the list of all example ids is permanently stored in memory.
Arguments:
example_ids (list): full list of examples in the form of image ids with the annotation number at the end
data_dir (string): directory where the data files are located
model_type (string): region_attention (full model) or average_attention (ablation model)
spatial_feature_size (int): number of features at the end after the the bottom-up visual features
drop_num_regions (bool): set to false to disregard the feature saying how many sub-regions make up this region
drop_bb_coords (string): set to false to disregard the min and max x,y of this region | 62598fd6c4546d3d9def7503 |
class TestResursConnectorSettings(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 testResursConnectorSettings(self): <NEW_LINE> <INDENT> pass | ResursConnectorSettings unit test stubs | 62598fd6099cdd3c6367565f |
class PasswordKdfAlgoUnknown(Object): <NEW_LINE> <INDENT> ID = 0xd45ab096 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "PasswordKdfAlgoUnknown": <NEW_LINE> <INDENT> return PasswordKdfAlgoUnknown() <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> return b.getvalue() | Attributes:
ID: ``0xd45ab096``
No parameters required. | 62598fd6a219f33f346c6d08 |
class QuantRiskResult(BaseObject): <NEW_LINE> <INDENT> volatility = None <NEW_LINE> Max_Drawdown = None <NEW_LINE> Max_Drawdown_recover_period = None <NEW_LINE> SharpRatio = None <NEW_LINE> SortinoRatio = None <NEW_LINE> DownsideRisk_LMPN = None <NEW_LINE> varHistory = None <NEW_LINE> Max_consecutive_up_days = None <NEW_LINE> Max_consecutive_down_days = None <NEW_LINE> Max_consecutive_up_peak = None <NEW_LINE> Max_consecutive_down_peak = None <NEW_LINE> profit_period_ratio = None <NEW_LINE> loss_period_ratio = None <NEW_LINE> profit_period_days = None <NEW_LINE> loss_period_days = None | 风险类量化指标结果类 | 62598fd660cbc95b0636483f |
class Warrior(Soldier): <NEW_LINE> <INDENT> def load_weapon(self): <NEW_LINE> <INDENT> print('The brave warrior unsheathe his sword') <NEW_LINE> <DEDENT> def combat_move(self): <NEW_LINE> <INDENT> print('Then, he falls it into his enemy') | The warrior class | 62598fd6be7bc26dc92520d8 |
class SharedCriterionServiceGrpcTransport(object): <NEW_LINE> <INDENT> _OAUTH_SCOPES = () <NEW_LINE> def __init__(self, channel=None, credentials=None, address='googleads.googleapis.com:443'): <NEW_LINE> <INDENT> if channel is not None and credentials is not None: <NEW_LINE> <INDENT> raise ValueError( 'The `channel` and `credentials` arguments are mutually ' 'exclusive.', ) <NEW_LINE> <DEDENT> if channel is None: <NEW_LINE> <INDENT> channel = self.create_channel( address=address, credentials=credentials, ) <NEW_LINE> <DEDENT> self._channel = channel <NEW_LINE> self._stubs = { 'shared_criterion_service_stub': shared_criterion_service_pb2_grpc.SharedCriterionServiceStub(channel), } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_channel( cls, address='googleads.googleapis.com:443', credentials=None, **kwargs): <NEW_LINE> <INDENT> return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def channel(self): <NEW_LINE> <INDENT> return self._channel <NEW_LINE> <DEDENT> @property <NEW_LINE> def get_shared_criterion(self): <NEW_LINE> <INDENT> return self._stubs['shared_criterion_service_stub'].GetSharedCriterion <NEW_LINE> <DEDENT> @property <NEW_LINE> def mutate_shared_criteria(self): <NEW_LINE> <INDENT> return self._stubs[ 'shared_criterion_service_stub'].MutateSharedCriteria | gRPC transport class providing stubs for
google.ads.googleads.v1.services SharedCriterionService API.
The transport provides access to the raw gRPC stubs,
which can be used to take advantage of advanced
features of gRPC. | 62598fd6656771135c489b74 |
class ValueIterationAgent(ValueEstimationAgent): <NEW_LINE> <INDENT> def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> import copy <NEW_LINE> for iteration in range(iterations): <NEW_LINE> <INDENT> newvalues = util.Counter() <NEW_LINE> for state in mdp.getStates(): <NEW_LINE> <INDENT> if mdp.isTerminal(state): <NEW_LINE> <INDENT> newvalues[state] = 0 <NEW_LINE> continue <NEW_LINE> <DEDENT> possibleActions = mdp.getPossibleActions(state) <NEW_LINE> maxAction = None <NEW_LINE> maxActionValue = float('-inf') <NEW_LINE> if (possibleActions==None): <NEW_LINE> <INDENT> newvalues[state] = 0 <NEW_LINE> <DEDENT> for action in possibleActions: <NEW_LINE> <INDENT> actionsum = self.getQValue(state, action) <NEW_LINE> if maxActionValue < actionsum: <NEW_LINE> <INDENT> maxAction = action <NEW_LINE> maxActionValue = actionsum <NEW_LINE> <DEDENT> <DEDENT> newvalues[state] = maxActionValue <NEW_LINE> <DEDENT> self.values = newvalues <NEW_LINE> <DEDENT> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.values[state] <NEW_LINE> <DEDENT> def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> actionSum = 0 <NEW_LINE> for transition in self.mdp.getTransitionStatesAndProbs(state, action): <NEW_LINE> <INDENT> TransitionProb = transition[1] <NEW_LINE> pstate = transition[0] <NEW_LINE> gamma = self.discount <NEW_LINE> reward = self.mdp.getReward(state, action, pstate) <NEW_LINE> actionSum = actionSum+ TransitionProb * (reward + (gamma * self.values[pstate])) <NEW_LINE> <DEDENT> return actionSum <NEW_LINE> <DEDENT> def computeActionFromValues(self, state): <NEW_LINE> <INDENT> mdp = self.mdp <NEW_LINE> possibleActions = mdp.getPossibleActions(state) <NEW_LINE> maxActionValue = float('-inf') <NEW_LINE> maxAction = None <NEW_LINE> if ((possibleActions==None) or (mdp.isTerminal(state))): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for action in possibleActions: <NEW_LINE> <INDENT> actionSum = self.getQValue(state, action) <NEW_LINE> if maxActionValue < actionSum: <NEW_LINE> <INDENT> maxAction = action <NEW_LINE> maxActionValue = actionSum <NEW_LINE> <DEDENT> <DEDENT> return maxAction <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.computeQValueFromValues(state, action) | * Please read learningAgents.py before reading this.*
A ValueIterationAgent takes a Markov decision process
(see mdp.py) on initialization and runs value iteration
for a given number of iterations using the supplied
discount factor. | 62598fd63617ad0b5ee0664a |
class MsgTrackingIqDepB(SBP): <NEW_LINE> <INDENT> _parser = construct.Struct( 'channel' / construct.Int8ul, 'sid' / GnssSignal._parser, 'corrs' / construct.Array(3, construct.Byte),) <NEW_LINE> __slots__ = [ 'channel', 'sid', 'corrs', ] <NEW_LINE> def __init__(self, sbp=None, **kwargs): <NEW_LINE> <INDENT> if sbp: <NEW_LINE> <INDENT> super( MsgTrackingIqDepB, self).__init__(sbp.msg_type, sbp.sender, sbp.length, sbp.payload, sbp.crc) <NEW_LINE> self.from_binary(sbp.payload) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super( MsgTrackingIqDepB, self).__init__() <NEW_LINE> self.msg_type = SBP_MSG_TRACKING_IQ_DEP_B <NEW_LINE> self.sender = kwargs.pop('sender', SENDER_ID) <NEW_LINE> self.channel = kwargs.pop('channel') <NEW_LINE> self.sid = kwargs.pop('sid') <NEW_LINE> self.corrs = kwargs.pop('corrs') <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return fmt_repr(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(s): <NEW_LINE> <INDENT> d = json.loads(s) <NEW_LINE> return MsgTrackingIqDepB.from_json_dict(d) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json_dict(d): <NEW_LINE> <INDENT> sbp = SBP.from_json_dict(d) <NEW_LINE> return MsgTrackingIqDepB(sbp, **d) <NEW_LINE> <DEDENT> def from_binary(self, d): <NEW_LINE> <INDENT> p = MsgTrackingIqDepB._parser.parse(d) <NEW_LINE> for n in self.__class__.__slots__: <NEW_LINE> <INDENT> setattr(self, n, getattr(p, n)) <NEW_LINE> <DEDENT> <DEDENT> def to_binary(self): <NEW_LINE> <INDENT> c = containerize(exclude_fields(self)) <NEW_LINE> self.payload = MsgTrackingIqDepB._parser.build(c) <NEW_LINE> return self.pack() <NEW_LINE> <DEDENT> def into_buffer(self, buf, offset): <NEW_LINE> <INDENT> self.payload = containerize(exclude_fields(self)) <NEW_LINE> self.parser = MsgTrackingIqDepB._parser <NEW_LINE> self.stream_payload.reset(buf, offset) <NEW_LINE> return self.pack_into(buf, offset, self._build_payload) <NEW_LINE> <DEDENT> def to_json_dict(self): <NEW_LINE> <INDENT> self.to_binary() <NEW_LINE> d = super( MsgTrackingIqDepB, self).to_json_dict() <NEW_LINE> j = walk_json_dict(exclude_fields(self)) <NEW_LINE> d.update(j) <NEW_LINE> return d | SBP class for message MSG_TRACKING_IQ_DEP_B (0x002C).
You can have MSG_TRACKING_IQ_DEP_B inherit its fields directly
from an inherited SBP object, or construct it inline using a dict
of its fields.
When enabled, a tracking channel can output the correlations at each update
interval.
Parameters
----------
sbp : SBP
SBP parent object to inherit from.
channel : int
Tracking channel of origin
sid : GnssSignal
GNSS signal identifier
corrs : array
Early, Prompt and Late correlations
sender : int
Optional sender ID, defaults to SENDER_ID (see sbp/msg.py). | 62598fd6adb09d7d5dc0aa7c |
class ClientManager(object): <NEW_LINE> <INDENT> rm = ClientCache(rm_client.make_client) <NEW_LINE> def __init__(self, api_version=None, url=None, app_name=None ): <NEW_LINE> <INDENT> self._api_version = api_version <NEW_LINE> self._url = url <NEW_LINE> self._app_name = app_name <NEW_LINE> return <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> if not self._url: <NEW_LINE> <INDENT> httpclient = HTTPClient() | Manages access to API clients, including authentication.
| 62598fd6ab23a570cc2d4fef |
class Hyperparameter(object): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> self._parent = parent <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if '_parent' not in self.__dict__: <NEW_LINE> <INDENT> raise AttributeError('_parent is not set up yet') <NEW_LINE> <DEDENT> return getattr(self._parent, name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> d = self.get_dict() <NEW_LINE> keys = sorted(d.keys()) <NEW_LINE> values_repr = ', '.join('%s=%s' % (k, d[k]) for k in keys) <NEW_LINE> return 'Hyperparameter(%s)' % values_repr <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent(self): <NEW_LINE> <INDENT> return self._parent <NEW_LINE> <DEDENT> def get_dict(self): <NEW_LINE> <INDENT> d = {} if self._parent is None else self._parent.get_dict() <NEW_LINE> for k, v in six.iteritems(self.__dict__): <NEW_LINE> <INDENT> if k != '_parent': <NEW_LINE> <INDENT> d[k] = v <NEW_LINE> <DEDENT> <DEDENT> return d | Set of hyperparameter entries of an optimizer.
This is a utility class to provide a set of hyperparameter entries for
update rules and an optimizer. Each entry can be set as an attribute of a
hyperparameter object.
A hyperparameter object can hold a reference to its parent hyperparameter
object. When an attribute does not exist in the child hyperparameter, it
automatically refers to the parent. We typically set the hyperparameter of
the gradient method as the parent of the hyperparameter of each update
rule. It enables us to centralize the management of hyperparameters (e.g.
we can change the learning rate of all update rules just by modifying the
hyperparameter of the central optimizer object), while users can freely
customize the hyperparameter of each update rule if needed.
Args:
parent (Hyperparameter): Parent hyperparameter. | 62598fd660cbc95b06364841 |
class Token(object): <NEW_LINE> <INDENT> def __init__(self, auth_ref): <NEW_LINE> <INDENT> user = {} <NEW_LINE> user['id'] = auth_ref.user_id <NEW_LINE> user['name'] = auth_ref.username <NEW_LINE> self.user = user <NEW_LINE> self.user_domain_id = auth_ref.user_domain_id <NEW_LINE> self.id = auth_ref.auth_token <NEW_LINE> if len(self.id) > 32: <NEW_LINE> <INDENT> self.id = hashlib.md5(self.id).hexdigest() <NEW_LINE> <DEDENT> self.expires = auth_ref.expires <NEW_LINE> project = {} <NEW_LINE> project['id'] = auth_ref.project_id <NEW_LINE> project['name'] = auth_ref.project_name <NEW_LINE> self.project = project <NEW_LINE> self.tenant = self.project <NEW_LINE> domain = {} <NEW_LINE> domain['id'] = auth_ref.domain_id <NEW_LINE> domain['name'] = auth_ref.domain_name <NEW_LINE> self.domain = domain <NEW_LINE> if auth_ref.version == 'v2.0': <NEW_LINE> <INDENT> self.roles = auth_ref['user'].get('roles', []) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.roles = auth_ref.get('roles', []) <NEW_LINE> <DEDENT> if utils.get_keystone_version() < 3: <NEW_LINE> <INDENT> self.serviceCatalog = auth_ref.get('serviceCatalog', []) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.serviceCatalog = auth_ref.get('catalog', []) | Token object that encapsulates the auth_ref (AccessInfo)from keystone
client.
Added for maintaining backward compatibility with horizon that expects
Token object in the user object. | 62598fd60fa83653e46f53ec |
class Card(object): <NEW_LINE> <INDENT> SUITS = 'cdhs' <NEW_LINE> SUIT_NAMES = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] <NEW_LINE> RANKS = range(1, 14) <NEW_LINE> RANK_NAMES = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King'] <NEW_LINE> def __init__(self, rank, suit): <NEW_LINE> <INDENT> self.rank_num = rank <NEW_LINE> self.suit_char = suit <NEW_LINE> <DEDENT> def suit(self): <NEW_LINE> <INDENT> return self.suit_char <NEW_LINE> <DEDENT> def rank(self): <NEW_LINE> <INDENT> return self.rank_num <NEW_LINE> <DEDENT> def suitName(self): <NEW_LINE> <INDENT> index = self.SUITS.index(self.suit_char) <NEW_LINE> return self.SUIT_NAMES[index] <NEW_LINE> <DEDENT> def rankName(self): <NEW_LINE> <INDENT> index = self.RANKS.index(self.rank_num) <NEW_LINE> return self.RANK_NAMES[index] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{0} of {1}'.format(self.rankName(), self.suitName()) | A simple playing card, characterized by two components:
rank: an interger value in the range 1 - 13, inclusing (Ace-King)
suit: a character in 'cdhs' for clubs, diamonds, hearts and spades. | 62598fd6091ae3566870511f |
class CB(nn.Module): <NEW_LINE> <INDENT> def __init__(self, nIn, nOut, kSize, stride=1): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> padding = int((kSize - 1) / 2) <NEW_LINE> self.conv = nn.Conv2d(nIn, nOut, (kSize, kSize), stride=stride, padding=(padding, padding), bias=False) <NEW_LINE> self.bn = nn.BatchNorm2d(nOut, eps=1e-03, momentum= BN_moment) <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> output = self.conv(input) <NEW_LINE> output = self.bn(output) <NEW_LINE> return output | This class groups the convolution and batch normalization | 62598fd63617ad0b5ee0664c |
class InputFeatures: <NEW_LINE> <INDENT> def __init__( self, input_ids, attention_mask=None, token_type_ids=None, labels=None, sent_rep_token_ids=None, sent_lengths=None, source=None, target=None, ): <NEW_LINE> <INDENT> self.input_ids = input_ids <NEW_LINE> self.attention_mask = attention_mask <NEW_LINE> self.token_type_ids = token_type_ids <NEW_LINE> self.labels = labels <NEW_LINE> self.sent_rep_token_ids = sent_rep_token_ids <NEW_LINE> self.sent_lengths = sent_lengths <NEW_LINE> self.source = source <NEW_LINE> self.target = target <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.to_json_string()) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> _dict = self.__dict__ <NEW_LINE> output = {} <NEW_LINE> for key, value in _dict.items(): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> output[key] = value <NEW_LINE> <DEDENT> <DEDENT> return output <NEW_LINE> <DEDENT> def to_json_string(self): <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" | A single set of features of data.
Args:
input_ids: Indices of input sequence tokens in the vocabulary.
attention_mask: Mask to avoid performing attention on padding token indices.
Mask values selected in `[0, 1]`:
Usually `1` for tokens that are NOT MASKED, `0` for MASKED (padded) tokens.
token_type_ids: Usually, segment token indices to indicate first and second portions
of the inputs. However, for summarization they are used to indicate different
sentences. Depending on the size of the token type id vocabulary, these values
may alternate between ``0`` and ``1`` or they may increase sequentially for each
sentence in the input.
labels: Labels corresponding to the input.
sent_rep_token_ids: The locations of the sentence representation tokens.
sent_lengths: A list of the lengths of each sentence in the `source` and `input_ids`.
source: The actual source document as a list of sentences.
target: The ground truth abstractive summary. | 62598fd6adb09d7d5dc0aa7e |
class IVocabularyFactory(schema.interfaces.IVocabularyFactory): <NEW_LINE> <INDENT> pass | vocabulary factory | 62598fd6c4546d3d9def7505 |
class JobStatus(async_.PollResultBase): <NEW_LINE> <INDENT> complete = None <NEW_LINE> @classmethod <NEW_LINE> def failed(cls, val): <NEW_LINE> <INDENT> return cls('failed', val) <NEW_LINE> <DEDENT> def is_complete(self): <NEW_LINE> <INDENT> return self._tag == 'complete' <NEW_LINE> <DEDENT> def is_failed(self): <NEW_LINE> <INDENT> return self._tag == 'failed' <NEW_LINE> <DEDENT> def get_failed(self): <NEW_LINE> <INDENT> if not self.is_failed(): <NEW_LINE> <INDENT> raise AttributeError("tag 'failed' not set") <NEW_LINE> <DEDENT> return self._value <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(JobStatus, self)._process_custom_annotations(annotation_type, field_path, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'JobStatus(%r, %r)' % (self._tag, self._value) | This class acts as a tagged union. Only one of the ``is_*`` methods will
return true. To get the associated value of a tag (if one exists), use the
corresponding ``get_*`` method.
:ivar sharing.JobStatus.complete: The asynchronous job has finished.
:ivar JobError JobStatus.failed: The asynchronous job returned an error. | 62598fd655399d3f05626a20 |
class CacheIO: <NEW_LINE> <INDENT> DBCache = dbio('cache_database') <NEW_LINE> table_name = 'api_json_return_values' <NEW_LINE> result_ttl = 300 <NEW_LINE> def __init__(self, result_ttl=300): <NEW_LINE> <INDENT> self.result_ttl = result_ttl <NEW_LINE> self.DBCache.create_table(self.table_name, 'result_id integer PRIMARY KEY, ' 'datetime text NOT NULL, ' 'api_name text NOT NULL, ' 'query_term text NOT NULL, ' 'api_result_text text NOT NULL') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> tables = [str(each) for each in self.DBCache.spew_tables()] <NEW_LINE> verbose_table_data = "" <NEW_LINE> for each in tables: <NEW_LINE> <INDENT> fields = ", ".join(item for item in self.DBCache.spew_header(each)) <NEW_LINE> contents = "\n".join("\t\t" + str(item) for item in self.DBCache.execute_query(each)) <NEW_LINE> verbose_table_data += str("table: " + each + "\n\tfields: " + fields + "\n\tcontents:\n" + contents) <NEW_LINE> <DEDENT> return verbose_table_data <NEW_LINE> <DEDENT> def update_result_ttl(self, seconds): <NEW_LINE> <INDENT> self.result_ttl = seconds <NEW_LINE> <DEDENT> def search(self, term): <NEW_LINE> <INDENT> db = self.DBCache <NEW_LINE> results = db.execute_query(table='api_json_return_values', regex=term, parm='query_term') <NEW_LINE> filtered_set = [] <NEW_LINE> if len(results) > 0: <NEW_LINE> <INDENT> for each in results: <NEW_LINE> <INDENT> if self.get_time_elapsed(each[1]) <= self.result_ttl: <NEW_LINE> <INDENT> filtered_set.append(each[4]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> db.delete_record(table_name=self.table_name, regex=each[0], parm='result_id') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return filtered_set <NEW_LINE> <DEDENT> def add_record(self, term,api,result): <NEW_LINE> <INDENT> current_datetime = self.get_date_time() <NEW_LINE> api = api <NEW_LINE> query_term = term <NEW_LINE> result = result <NEW_LINE> field_data = "'{}', '{}', '{}', '{}'".format(current_datetime, api, query_term, result) <NEW_LINE> self.DBCache.add_record('api_json_return_values', 'datetime, api_name, query_term, api_result_text', field_data) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_date_time(): <NEW_LINE> <INDENT> return datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") <NEW_LINE> <DEDENT> def get_time_elapsed(self, test): <NEW_LINE> <INDENT> test_time = datetime.datetime.strptime(test, "%Y-%m-%d %H:%M:%S") <NEW_LINE> now = datetime.datetime.strptime(self.get_date_time(), "%Y-%m-%d %H:%M:%S") <NEW_LINE> return (now - test_time).seconds | this class should record the search term, get the date and time, and record the json to the sql handler
logic regarding how long to keep an object cached should operate here based on parameters passed into the class
this class should return an existing archive, or return "" if no previous entry exists based on sql search | 62598fd650812a4eaa620e66 |
class OrientationActuatorClass(morse.core.actuator.MorseActuatorClass): <NEW_LINE> <INDENT> def __init__(self, obj, parent=None): <NEW_LINE> <INDENT> print ('######## ORIENTATION CONTROL INITIALIZATION ########') <NEW_LINE> super(self.__class__,self).__init__(obj, parent) <NEW_LINE> self.local_data['rx'] = 0.0 <NEW_LINE> self.local_data['ry'] = 0.0 <NEW_LINE> self.local_data['rz'] = 0.0 <NEW_LINE> print ('######## CONTROL INITIALIZED ########') <NEW_LINE> <DEDENT> def default_action(self): <NEW_LINE> <INDENT> parent = self.robot_parent.blender_obj <NEW_LINE> parent.orientation = [self.local_data['rx'], self.local_data['ry'], self.local_data['rz']] | Motion controller changing the robot orientation
This class will read angles as input from an external middleware,
and then change the robot orientation accordingly. | 62598fd6fbf16365ca7945c6 |
class ModuleLocalCommand(TemplerLocalTemplate): <NEW_LINE> <INDENT> use_cheetah = True <NEW_LINE> parent_templates = ['basic_namespace', ] <NEW_LINE> _template_dir = 'templates/module' <NEW_LINE> summary = "Add a module to your package" <NEW_LINE> vars = [ var('module_name', 'Module Name', default="mymodule"), ] | A bogus local command for use in testing | 62598fd6c4546d3d9def7507 |
class import_dsf (bpy.types.Operator): <NEW_LINE> <INDENT> bl_label = 'import dsf-geom' <NEW_LINE> bl_idname = 'mesh.dsf' <NEW_LINE> filepath = StringProperty (name = 'file path', description = 'file path for importing dsf-file.', maxlen = 1000, default = '') <NEW_LINE> filter_glob = StringProperty (default = '*.dsf') <NEW_LINE> prop_materials = BoolProperty (name = 'materials', description = 'assign material names to faces', default = True) <NEW_LINE> prop_use_material = BoolProperty (name = 'use material', description = 'use existing materials if available', default = True) <NEW_LINE> prop_groups = BoolProperty (name = 'groups', description = 'assign vertex groups based on face groups', default = True) <NEW_LINE> def execute (self, context): <NEW_LINE> <INDENT> import_props = { 'materials': self.properties.prop_materials, 'use_material': self.properties.prop_use_material, 'groups': self.properties.prop_groups, 'uvs': True, } <NEW_LINE> log.info ("execute (path = {0}, kwargs = {1})".format (self.properties.filepath, str (import_props))) <NEW_LINE> obj = import_dsf_file (self.properties.filepath, import_props) <NEW_LINE> context.scene.objects.active = obj <NEW_LINE> return { 'FINISHED' } <NEW_LINE> <DEDENT> def invoke (self, context, event): <NEW_LINE> <INDENT> context.window_manager.fileselect_add (self) <NEW_LINE> return {'RUNNING_MODAL'} | Load a daz studio 4 dsf file. | 62598fd6ad47b63b2c5a7d5a |
class CheckKeys(object): <NEW_LINE> <INDENT> not_empty = True <NEW_LINE> string_validator_instance = None <NEW_LINE> key_names = None <NEW_LINE> refer_key_name = None <NEW_LINE> level = None <NEW_LINE> messages = dict( names='%(keyNames (type list of strings or string) is is required.', stores='%(stores (type dict) is is required.', missing='%(param)s is required for CheckKeys.', type='%(param)s should be of type %(type)s.', duplicate='%(value)s is a duplicate entry for key %(key)s.', noMatch='Could not find match for path %(path)s.', stateMissing='Parameter state is required.', emptyValue='Value may not be empty.', ) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.key_names = kwargs.get('key_names', self.key_names) <NEW_LINE> self.level = kwargs.get('level', self.level) <NEW_LINE> assert self.key_names, self.messages['names'] <NEW_LINE> if isinstance(self.key_names, list): <NEW_LINE> <INDENT> assert self.key_names <NEW_LINE> for name in self.key_names: <NEW_LINE> <INDENT> assert isinstance(name, string_types) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(self.key_names, string_types) <NEW_LINE> self.key_names = [self.key_names] <NEW_LINE> <DEDENT> assert isinstance(self.level, int) <NEW_LINE> <DEDENT> def validate(self, key_value, **kwargs): <NEW_LINE> <INDENT> path, stores = get_value_path_stores(**kwargs) <NEW_LINE> if not key_value: <NEW_LINE> <INDENT> if not self.not_empty: <NEW_LINE> <INDENT> return key_value <NEW_LINE> <DEDENT> raise ValidationException(self.messages['emptyValue'], key_value) <NEW_LINE> <DEDENT> if self.string_validator_instance: <NEW_LINE> <INDENT> string_value = self.string_validator_instance.validate(key_value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> string_value = key_value <NEW_LINE> <DEDENT> if stores is None: <NEW_LINE> <INDENT> return string_value <NEW_LINE> <DEDENT> target_path = '.'.join(path.split('.')[:-self.level]) <NEW_LINE> if self.refer_key_name: <NEW_LINE> <INDENT> stores.refStore.add_key_ref(self.refer_key_name, key_value, path) <NEW_LINE> <DEDENT> self.add_value(stores, target_path, string_value, path) <NEW_LINE> return string_value <NEW_LINE> <DEDENT> def add_value(self, stores, target_path, value, path): <NEW_LINE> <INDENT> if self.key_names: <NEW_LINE> <INDENT> stores.keyStore.add_value(self.key_names, target_path, value, path) | Determines the targetPath by removing <level>s from path.
Looks up store[keyName:keyTargetInstancePath] for all
keyNames and checks the dict if keyValue (element.value) is already
present (duplicate error). If not it adds the element.value as key
and element.path as value. | 62598fd6ad47b63b2c5a7d5b |
class AnalysisCostBreakdown(Resource): <NEW_LINE> <INDENT> storage = FloatField(read_only=True) <NEW_LINE> computation = FloatField(read_only=True) <NEW_LINE> data_transfer_in = FloatField(read_only=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return ( f'<AnalysisCostBreakdown: storage={self.storage}, ' f'computation={self.computation}, ' f'data_transfer_in={self.data_transfer_in}' ) | AnalysisCostBreakdown resource contains price breakdown by storage and
computation. | 62598fd6fbf16365ca7945c8 |
class Quintiles(Aggregation): <NEW_LINE> <INDENT> def get_cache_key(self): <NEW_LINE> <INDENT> return 'Quintiles' <NEW_LINE> <DEDENT> def run(self, column): <NEW_LINE> <INDENT> percentiles = column.aggregate(Percentiles()) <NEW_LINE> return Quantiles([percentiles[i] for i in range(0, 101, 20)]) | The quintiles of a column based on the 20th, 40th, 60th and 80th
percentiles.
"Zeroth" (min value) and "Fifth" (max value) quintiles are included for
reference and intuitive indexing.
See :class:`Percentiles` for implementation details.
This aggregation can not be applied to a :class:`.TableSet`. | 62598fd6956e5f7376df5902 |
class ProfileFeedItemSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model=models.ProfileFeedItem <NEW_LINE> fields=('id','user_profile','status_text','created_on') <NEW_LINE> extra_kwargs={'user_profile':{'read_only':True}} | serializer for profile feed | 62598fd626238365f5fad06e |
class Command: <NEW_LINE> <INDENT> def __init__(self, state, bool_func, effect, name='untitled'): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.bool_func = bool_func <NEW_LINE> self.effect = effect <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def check_command(self, test): <NEW_LINE> <INDENT> if self.bool_func(self.state, test) is True: <NEW_LINE> <INDENT> self.effect(self.state, test) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Binds an evaluation callback to an effect callback.
:param state: The state using this Command
:type state: class State
:param bool_func: A callback which returns True if the effect should be triggered
:type bool_func: Function
:param effect: A callback called when command should be executed
:type effect: Function
:param name: Optional parameter containing human-readable command name
:type name: str | 62598fd6283ffb24f3cf3d8b |
class FailoverConditionSettings(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "AudioSilenceSettings": (AudioSilenceFailoverSettings, False), "InputLossSettings": (InputLossFailoverSettings, False), "VideoBlackSettings": (VideoBlackFailoverSettings, False), } | `FailoverConditionSettings <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-failoverconditionsettings.html>`__ | 62598fd6656771135c489b7c |
class OldFunctions: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def compute_turns_to_distance(EL:object, areas:list, desired_distance:float, minus_entrance:bool=True) -> dict: <NEW_LINE> <INDENT> area_query = [f"area == '{area}'" for area in areas] <NEW_LINE> area_query = " or ".join(area_query) <NEW_LINE> df = EL.get_current_property_table(properties=["depth_mm"])[-1] <NEW_LINE> mm_required = (desired_distance - (df.reset_index('area') .query(area_query) .set_index('area', append = True) .astype('float') + EL.const_depth_mm)) <NEW_LINE> if minus_entrance: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> fullturns_required = (EL.get_turns_per_mm() * mm_required.copy()).rename(columns={'depth_mm':'fullturn'}) <NEW_LINE> twelths_required = (fullturns_required.copy() * 12).rename(columns={'fullturn':'twelths'}) <NEW_LINE> quarters_required = (fullturns_required.copy() * 4).rename(columns={'fullturn':'quarters'}) <NEW_LINE> move_dict ={ 'mm' : mm_required, 'fullturn' : fullturns_required, 'twelths' : twelths_required, 'quarters' : quarters_required, } <NEW_LINE> return move_dict <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def compute_tetrode_distance_difference(tet1, tet2, DF=None, prop='depth_mm'): <NEW_LINE> <INDENT> from .notes import get_notes <NEW_LINE> note1 = get_notes(tet1, DF).reset_index('depth_mm')[prop] <NEW_LINE> note2 = get_notes(tet2, DF).reset_index('depth_mm')[prop] <NEW_LINE> note1 = note1[note1 != ''].astype('float').iloc[-1] <NEW_LINE> note2 = note2[note2 != ''].astype('float').iloc[-1] <NEW_LINE> return (note2 - note1) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def compute_entrances_per_tetrode(EL): <NEW_LINE> <INDENT> pass | Groups together older methods | 62598fd6dc8b845886d53ac8 |
class Queue(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vals = [] <NEW_LINE> <DEDENT> def insert(self, e): <NEW_LINE> <INDENT> self.vals.append(e) <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.vals.pop(0) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError('Queue is empty') | A Queue is a list of elements the follows the FIFO method of removing
elements | 62598fd6099cdd3c63675664 |
class Grp50No120b(base_tests.SimpleDataPlane): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> logging.info("Running IcmpType test") <NEW_LINE> of_ports = config["port_map"].keys() <NEW_LINE> of_ports.sort() <NEW_LINE> self.assertTrue(len(of_ports) > 1, "Not enough ports for test") <NEW_LINE> rc = delete_all_flows(self.controller) <NEW_LINE> self.assertEqual(rc, 0, "Failed to delete all flows") <NEW_LINE> egress_port=of_ports[1] <NEW_LINE> no_ports=set(of_ports).difference([egress_port]) <NEW_LINE> yes_ports = of_ports[1] <NEW_LINE> sleep(2) <NEW_LINE> (pkt,match) = match_icmp_type(self,of_ports) <NEW_LINE> self.dataplane.send(of_ports[0], str(pkt)) <NEW_LINE> receive_pkt_check(self.dataplane,pkt,[yes_ports],no_ports,self) <NEW_LINE> pkt2 = simple_icmp_packet(icmp_type=11); <NEW_LINE> self.dataplane.send(of_ports[0], str(pkt2)) <NEW_LINE> (response, raw) = self.controller.poll(ofp.OFPT_PACKET_IN,timeout=4) <NEW_LINE> self.assertTrue(response is not None, "PacketIn not received for non matching packet") | Verify match on Single header field --Match on Tcp Source Port/IcmpType | 62598fd6ec188e330fdf8da2 |
class LazySparseInputReader(_LazyInputReaderBase): <NEW_LINE> <INDENT> def __init__(self, indices, values, shape, node, input_alias=None, dynamic_axis=''): <NEW_LINE> <INDENT> super(LazySparseInputReader, self).__init__(node, input_alias, dynamic_axis) <NEW_LINE> if not indices or not values or not shape: <NEW_LINE> <INDENT> raise ValueError( 'you initalized LazySparseInputReader without valid initialization') <NEW_LINE> <DEDENT> if not len(indices) == len(values): <NEW_LINE> <INDENT> raise ValueError('indices has different length than values') <NEW_LINE> <DEDENT> self.indices = indices <NEW_LINE> self.values = values <NEW_LINE> self.shape = self.node.shape = tuple(reversed(shape)) <NEW_LINE> self.param_dict = {} <NEW_LINE> self.param_dict['dim'] = np.multiply.reduce(self.shape) <NEW_LINE> self.param_dict['format'] = 'sparse' <NEW_LINE> <DEDENT> def batch_size(self): <NEW_LINE> <INDENT> return len(self.indices) <NEW_LINE> <DEDENT> def data_of_sample(self, idx): <NEW_LINE> <INDENT> indices = self.indices[idx] <NEW_LINE> values = self.values[idx] <NEW_LINE> data = dict(zip(indices,values)) <NEW_LINE> if not self.dynamic_axis: <NEW_LINE> <INDENT> data = [data] <NEW_LINE> <DEDENT> return data | Lazy reader that takes an NumPy array and serializes it to disk only when
the complete graph is specified. This is necessary in case of multiple
inputs, because they have to reside in the same file.
Note:
All readers of this type need to have the exact same number of samples,
as they will be aligned by the first index.
Note:
This class will be deprecated once the reader bundlers have arrived in
CNTK.
Args:
indices (list): list of indices
values (list): list of values corresponding to indices
shape (tuple): shape of the input
node (`_InputComputationNodeBase`): node to which this lazy reader is connected
input_alias (str): a short name for the input, it is how inputs are referenced in the data files. If not provided, it will be automatically assigned.
dynamic_axis (str or output of :func:`cntk.ops.dynamic_axis`): the dynamic axis packaged as sequences. If not, it will wrapped again in a sequence of length 1. | 62598fd626238365f5fad070 |
class SSGRLClassifier(Model): <NEW_LINE> <INDENT> def __init__(self, backbone, coocurence_matrix, class_embeddings, d1=1024, d2=1024, time_steps=3, logit_fts=2048, use_si=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.num_classes = coocurence_matrix.shape[0] <NEW_LINE> if backbone == "resnext101": <NEW_LINE> <INDENT> self.backbone = resnext101_32x8d_wsl() <NEW_LINE> self.nb_ft = 2048 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.backbone = get_encoder(SETTINGS[backbone]) <NEW_LINE> self.nb_ft = SETTINGS[backbone]["out_shapes"][0] <NEW_LINE> <DEDENT> self.pooler = nn.AvgPool2d(2, stride=2) <NEW_LINE> self.semantic_decoupling = SemanticDecoupling(self.nb_ft, class_embeddings, d1=d1, d2=d2) <NEW_LINE> if use_si: <NEW_LINE> <INDENT> self.semantic_interaction = SemanticInteraction(self.nb_ft, coocurence_matrix, time_steps=time_steps) <NEW_LINE> self.semantic_fts = self.nb_ft * 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.semantic_interaction = None <NEW_LINE> self.semantic_fts = self.nb_ft <NEW_LINE> <DEDENT> self.fo = nn.Sequential( nn.Linear(self.semantic_fts, logit_fts), nn.Tanh(), ) <NEW_LINE> self.logits = nn.ModuleList([]) <NEW_LINE> for i in range(self.num_classes): <NEW_LINE> <INDENT> self.logits.append(nn.Linear(logit_fts, 1)) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.backbone(x) <NEW_LINE> x = self.pooler(x) <NEW_LINE> h0 = self.semantic_decoupling(x) <NEW_LINE> if self.semantic_interaction is not None: <NEW_LINE> <INDENT> hT = self.semantic_interaction(h0) <NEW_LINE> o = self.fo(torch.cat([h0, hT], 2)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o = self.fo(h0) <NEW_LINE> <DEDENT> outputs = [] <NEW_LINE> for i in range(self.num_classes): <NEW_LINE> <INDENT> outputs.append(self.logits[i](o[:, i, :])) <NEW_LINE> <DEDENT> return torch.cat(outputs, 1) <NEW_LINE> <DEDENT> def get_attention(self, x): <NEW_LINE> <INDENT> x = self.backbone(x) <NEW_LINE> x = self.pooler(x) <NEW_LINE> h0, att = self.semantic_decoupling(x, return_att=True) <NEW_LINE> if self.semantic_interaction is not None: <NEW_LINE> <INDENT> hT = self.semantic_interaction(h0) <NEW_LINE> o = F.tanh(self.fo(torch.cat([h0, hT], 2))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o = F.tanh(self.fo(h0)) <NEW_LINE> <DEDENT> outputs = [] <NEW_LINE> for i in range(self.num_classes): <NEW_LINE> <INDENT> outputs.append(self.logits[i](o[:, i, :])) <NEW_LINE> <DEDENT> return torch.cat(outputs, 1), att | Implementation of the Semantic-Specific Graph Representation Learning framework from :
Tianshui Chen, Muxin Xu, Xiaolu Hui, Hefeng Wu, and Liang Lin. Learning semantic-specific graphrepresentation for multi-label image recognition
(http://openaccess.thecvf.com/content_ICCV_2019/papers/Chen_Learning_Semantic-Specific_Graph_Representation_for_Multi-Label_Image_Recognition_ICCV_2019_paper.pdf) | 62598fd6ad47b63b2c5a7d5e |
class LVQT(_LVQT): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(LVQT, self).__init__(**kwargs) <NEW_LINE> self.l2_pool = torch.nn.LPPool1d(norm_type=2, kernel_size=2, stride=2) <NEW_LINE> <DEDENT> def forward(self, audio): <NEW_LINE> <INDENT> real_feats = super(type(self).__bases__[0], self).forward(audio) <NEW_LINE> padded_audio = torch.nn.functional.pad(audio, self.pd1) <NEW_LINE> imag_weights = self.get_imag_weights().unsqueeze(1) <NEW_LINE> imag_feats = torch.nn.functional.conv1d(padded_audio, weight=imag_weights, stride=self.sd1, padding=0) <NEW_LINE> real_feats = real_feats.unsqueeze(-1) <NEW_LINE> imag_feats = imag_feats.unsqueeze(-1) <NEW_LINE> feats = torch.cat((real_feats, imag_feats), dim=-1) <NEW_LINE> feats = feats.transpose(1, 2) <NEW_LINE> feats = feats.reshape(tuple(list(feats.shape[:-2]) + [-1])) <NEW_LINE> feats = self.l2_pool(feats) <NEW_LINE> feats = feats.transpose(1, 2) <NEW_LINE> feats = self.post_proc(feats) <NEW_LINE> return feats <NEW_LINE> <DEDENT> def get_imag_weights(self): <NEW_LINE> <INDENT> real_weights = self.get_real_weights() <NEW_LINE> if self.update: <NEW_LINE> <INDENT> imag_weights = torch_hilbert(real_weights) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> imag_weights = torch_hilbert(real_weights) <NEW_LINE> <DEDENT> <DEDENT> return imag_weights | Implements an extension of the real-only LVQT variant. In this version, the imaginary
weights of the transform are inferred from the real weights by using the Hilbert transform. | 62598fd650812a4eaa620e6a |
class Account(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.statement = None <NEW_LINE> self.routing_number = '' <NEW_LINE> self.branch_id = '' <NEW_LINE> self.account_type = '' <NEW_LINE> self.institution = None <NEW_LINE> self.type = AccountType.unknown <NEW_LINE> self.desc = None <NEW_LINE> self.account_id = None <NEW_LINE> self.suptxdl = None <NEW_LINE> self.xfersrc = None <NEW_LINE> self.xferdest = None <NEW_LINE> self.svcstatus = None <NEW_LINE> self.warnings = [] | An OFX account object. | 62598fd6adb09d7d5dc0aa88 |
class TournamentListView(SingleTableMixin, TemplateView): <NEW_LINE> <INDENT> table_class = TournamentTable <NEW_LINE> table_pagination = False <NEW_LINE> template_name = 'UGD/tournament_list.html' <NEW_LINE> def get_table_data(self): <NEW_LINE> <INDENT> return Tournament.objects.all().order_by('-date_begin') | Турніри | 62598fd6c4546d3d9def750a |
class TestNthOfTypeQuirks(TestNthOfType): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.purge() <NEW_LINE> self.quirks = True | Test `nth` of type selectors with quirks. | 62598fd6099cdd3c63675666 |
class MongodbConnParams(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> version = self.get_argument("ver", "3.4.0") <NEW_LINE> self.write(db_pymongo.mongodb_conn_by_mongoclient_params(version)) | :ver: 作为参数传入,区分版本号
:return: | 62598fd6ad47b63b2c5a7d61 |
class Command(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def execute(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def unexecute(self) -> None: <NEW_LINE> <INDENT> pass | Базовый класс для всех команд | 62598fd626238365f5fad074 |
class Lock: <NEW_LINE> <INDENT> def __init__(self, row): <NEW_LINE> <INDENT> self.locker = Doc.User(row.id, row.name, row.fullname) <NEW_LINE> self.locked = row.dt_out <NEW_LINE> if isinstance(self.locked, datetime.datetime): <NEW_LINE> <INDENT> self.locked = self.locked.replace(microsecond=0) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> args = self.locker.name, self.locker.fullname, self.locked <NEW_LINE> return "Document checked out to {} ({}) {}".format(*args) | Who has the document checked out, beginning when | 62598fd6dc8b845886d53ace |
class TraitWXFont(TraitHandler): <NEW_LINE> <INDENT> def validate(self, object, name, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return create_traitsfont(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise TraitError(object, name, 'a font descriptor string', repr(value)) <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> return ("a string describing a font (e.g. '12 pt bold italic " "swiss family Arial' or 'default 12')") | Ensures that values assigned to a trait attribute are valid font
descriptor strings; the value actually assigned is the corresponding
TraitsFont. | 62598fd6a219f33f346c6d18 |
class InvalidDateOffset(HL7apyException): <NEW_LINE> <INDENT> def __init__(self, offset): <NEW_LINE> <INDENT> self.offset = offset <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Invalid date offset: {0}'.format(self.offset) | Raised when the offset for a :class:`TM` or :class:`hl7apy.base_datatypes.DTM` is not valid
>>> from hl7apy.v2_5 import DTM
>>> DTM(value='20131010', format="%Y%m%d", offset='+1300')
Traceback (most recent call last):
...
InvalidDateOffset: Invalid date offset: +1300 | 62598fd6656771135c489b84 |
class EvalPoint(object): <NEW_LINE> <INDENT> def __init__(self, field, n, use_omega_powers=False): <NEW_LINE> <INDENT> self.use_omega_powers = use_omega_powers <NEW_LINE> self.field = field <NEW_LINE> self.n = n <NEW_LINE> order = n <NEW_LINE> if use_omega_powers: <NEW_LINE> <INDENT> self.order = ( order if (order & (order - 1) == 0) else 2 ** order.bit_length() ) <NEW_LINE> self.omega2 = get_omega(field, 2 * self.order, seed=0) <NEW_LINE> self.omega = self.omega2 ** 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.order = order <NEW_LINE> self.omega2 = None <NEW_LINE> self.omega = None <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, i): <NEW_LINE> <INDENT> if self.use_omega_powers: <NEW_LINE> <INDENT> return self.field(self.omega2.value ** (2 * i)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.field(i + 1) <NEW_LINE> <DEDENT> <DEDENT> def zero(self): <NEW_LINE> <INDENT> return self.field(0) | Helper to generate evaluation points for polynomials between n parties
If FFT is being used:
omega is a root of unity s.t. order(omega) = (smallest power of 2 >= n)
i'th point (zero-indexed) = omega^(i)
Without FFT:
i'th point (zero-indexed) = i + 1 | 62598fd6283ffb24f3cf3d93 |
class ImportSource(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'source_image': {'required': True}, } <NEW_LINE> _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'registry_uri': {'key': 'registryUri', 'type': 'str'}, 'credentials': {'key': 'credentials', 'type': 'ImportSourceCredentials'}, 'source_image': {'key': 'sourceImage', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, source_image: str, resource_id: Optional[str] = None, registry_uri: Optional[str] = None, credentials: Optional["ImportSourceCredentials"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ImportSource, self).__init__(**kwargs) <NEW_LINE> self.resource_id = resource_id <NEW_LINE> self.registry_uri = registry_uri <NEW_LINE> self.credentials = credentials <NEW_LINE> self.source_image = source_image | ImportSource.
All required parameters must be populated in order to send to Azure.
:ivar resource_id: The resource identifier of the source Azure Container Registry.
:vartype resource_id: str
:ivar registry_uri: The address of the source registry (e.g. 'mcr.microsoft.com').
:vartype registry_uri: str
:ivar credentials: Credentials used when importing from a registry uri.
:vartype credentials: ~azure.mgmt.containerregistry.v2019_05_01.models.ImportSourceCredentials
:ivar source_image: Required. Repository name of the source image.
Specify an image by repository ('hello-world'). This will use the 'latest' tag.
Specify an image by tag ('hello-world:latest').
Specify an image by sha256-based manifest digest ('hello-world@sha256:abc123').
:vartype source_image: str | 62598fd6099cdd3c63675668 |
class PointsHelper(object, metaclass=Singleton): <NEW_LINE> <INDENT> points = [] <NEW_LINE> def set(self, points: List[Point]) -> NoReturn: <NEW_LINE> <INDENT> self.points = points <NEW_LINE> <DEDENT> def get_point_by_id(self, asset_id: int): <NEW_LINE> <INDENT> result = None <NEW_LINE> if self.points: <NEW_LINE> <INDENT> for point in self.points: <NEW_LINE> <INDENT> if point.id == asset_id: <NEW_LINE> <INDENT> result = point <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result | Служит для хранения последних полученных курсов | 62598fd6d8ef3951e32c80e5 |
class DiscoverGeographicalCoverage(object): <NEW_LINE> <INDENT> implements(IDiscoverGeographicalCoverage) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._key = '' <NEW_LINE> self._alchemy = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def key(self): <NEW_LINE> <INDENT> return self._key <NEW_LINE> <DEDENT> @property <NEW_LINE> def alchemy(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def __call__(self, key, text="", path=""): <NEW_LINE> <INDENT> self._key = key <NEW_LINE> if not self.alchemy: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for entity in []: <NEW_LINE> <INDENT> etype = entity.get('type', '') <NEW_LINE> if etype not in ENTITY_TYPES: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield entity | Discover geotags
| 62598fd650812a4eaa620e6d |
class ScalarField: <NEW_LINE> <INDENT> def __init__(self, values, dx, dy): <NEW_LINE> <INDENT> self.values = values <NEW_LINE> self.dx = dx <NEW_LINE> self.dy = dy <NEW_LINE> self.ddx = None <NEW_LINE> self.ddy = None <NEW_LINE> self.laplacian = None <NEW_LINE> <DEDENT> def get_ddx(self): <NEW_LINE> <INDENT> if self.ddx is not None: <NEW_LINE> <INDENT> return self.ddx <NEW_LINE> <DEDENT> self.ddx = first_derivative(f=self.values, axis=-1, distance=self.dx) <NEW_LINE> return self.ddx <NEW_LINE> <DEDENT> def get_ddy(self): <NEW_LINE> <INDENT> if self.ddy is not None: <NEW_LINE> <INDENT> return self.ddy <NEW_LINE> <DEDENT> self.ddy = first_derivative(f=self.values, axis=-2, distance=self.dy) <NEW_LINE> return self.ddy <NEW_LINE> <DEDENT> def get_laplacian(self): <NEW_LINE> <INDENT> if self.laplacian is not None: <NEW_LINE> <INDENT> return self.laplacian <NEW_LINE> <DEDENT> self.d2dx2 = second_derivative(f=self.values, axis=-1, distance=self.dx) <NEW_LINE> self.d2dy2 = second_derivative(f=self.values, axis=-2, distance=self.dy) <NEW_LINE> self.laplacian = self.d2dx2 + self.d2dy2 <NEW_LINE> return self.laplacian | Given a N dimensional numpy array, here's a class that will
ideally give us everything we could ever want. For derivatives.
DIMENSIONS: could be (time, plvl, lat, lon), (plvl, lat, lon), OR
(lat, lon). Who knows. | 62598fd63617ad0b5ee0665c |
class Flyable(): <NEW_LINE> <INDENT> pass | docstring for Flyable | 62598fd6c4546d3d9def750d |
class TestProductsApps(TestCase): <NEW_LINE> <INDENT> def test_apps(self): <NEW_LINE> <INDENT> self.assertEqual(ProductsConfig.name, 'products') <NEW_LINE> self.assertEqual(apps.get_app_config('products').name, 'products') | Testing the apps.py file | 62598fd68a349b6b43686755 |
@admin.register(models.CandidateContest) <NEW_LINE> class CandidateContestAdmin(base.ModelAdmin): <NEW_LINE> <INDENT> readonly_fields = ( 'id', 'created_at', 'updated_at', ) <NEW_LINE> raw_id_fields = ('division', 'runoff_for_contest', ) <NEW_LINE> fields = ( 'name', 'election', 'party', 'previous_term_unexpired', 'number_elected', ) + raw_id_fields + readonly_fields <NEW_LINE> list_display = ( 'name', 'election', 'division_name', 'id', 'updated_at', ) <NEW_LINE> search_fields = ('name', 'election__name', ) <NEW_LINE> list_filter = ('updated_at', ) <NEW_LINE> if django_version[0] >= 1 and django_version[1] >= 11: <NEW_LINE> <INDENT> date_hierarchy = 'election__date' <NEW_LINE> <DEDENT> inlines = [ CandidateContestPostInline, CandidateContestIdentifierInline, CandidateContestSourceInline, ] <NEW_LINE> def division_name(self, obj): <NEW_LINE> <INDENT> return obj.division.name | Custom administrative panel for the CandidateContest model. | 62598fd6091ae35668705131 |
class FunctionAPI(ModelView): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> if 'q' not in request.args or not request.args.get('q'): <NEW_LINE> <INDENT> return dict(message='Empty query parameter'), 400 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = json.loads(str(request.args.get('q'))) or {} <NEW_LINE> <DEDENT> except (TypeError, ValueError, OverflowError) as exception: <NEW_LINE> <INDENT> current_app.logger.exception(str(exception)) <NEW_LINE> return dict(message='Unable to decode data'), 400 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = evaluate_functions(self.session, self.model, data.get('functions', [])) <NEW_LINE> if not result: <NEW_LINE> <INDENT> return {}, 204 <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> except AttributeError as exception: <NEW_LINE> <INDENT> current_app.logger.exception(str(exception)) <NEW_LINE> message = 'No such field "{0}"'.format(exception.field) <NEW_LINE> return dict(message=message), 400 <NEW_LINE> <DEDENT> except OperationalError as exception: <NEW_LINE> <INDENT> current_app.logger.exception(str(exception)) <NEW_LINE> message = 'No such function "{0}"'.format(exception.function) <NEW_LINE> return dict(message=message), 400 | Provides method-based dispatching for :http:method:`get` requests which
wish to apply SQL functions to all instances of a model.
.. versionadded:: 0.4 | 62598fd6956e5f7376df5908 |
class Grid(NanonisFile): <NEW_LINE> <INDENT> def __init__(self, fname): <NEW_LINE> <INDENT> _is_valid_file(fname, ext='3ds') <NEW_LINE> super(Grid,self).__init__(fname) <NEW_LINE> self.header = _parse_3ds_header(self.header_raw) <NEW_LINE> self.signals = self._load_data() <NEW_LINE> self.signals['sweep_signal'] = self._derive_sweep_signal() <NEW_LINE> self.signals['topo'] = self._extract_topo() <NEW_LINE> <DEDENT> def _load_data(self): <NEW_LINE> <INDENT> nx, ny = self.header['dim_px'] <NEW_LINE> num_sweep = self.header['num_sweep_signal'] <NEW_LINE> num_param = self.header['num_parameters'] <NEW_LINE> num_chan = self.header['num_channels'] <NEW_LINE> data_dict = dict() <NEW_LINE> f = open(self.fname, 'rb') <NEW_LINE> f.seek(self.byte_offset) <NEW_LINE> data_format = '>f4' <NEW_LINE> griddata = np.fromfile(f, dtype=data_format) <NEW_LINE> f.close() <NEW_LINE> exp_size_per_pix = num_param + num_sweep*num_chan <NEW_LINE> griddata_shaped = griddata.reshape((nx, ny, exp_size_per_pix)) <NEW_LINE> params = griddata_shaped[:, :, :num_param] <NEW_LINE> data_dict['params'] = params <NEW_LINE> for i, chann in enumerate(self.header['channels']): <NEW_LINE> <INDENT> start_ind = num_param + i * num_sweep <NEW_LINE> stop_ind = num_param + (i+1) * num_sweep <NEW_LINE> data_dict[chann] = griddata_shaped[:, :, start_ind:stop_ind] <NEW_LINE> <DEDENT> return data_dict <NEW_LINE> <DEDENT> def _derive_sweep_signal(self): <NEW_LINE> <INDENT> sweep_start, sweep_end = self.signals['params'][0, 0, :2] <NEW_LINE> num_sweep_signal = self.header['num_sweep_signal'] <NEW_LINE> return np.linspace(sweep_start, sweep_end, num_sweep_signal, dtype=np.float32) <NEW_LINE> <DEDENT> def _extract_topo(self): <NEW_LINE> <INDENT> return self.signals['params'][:, :, 4] | Nanonis grid file class.
Contains data loading method specific to Nanonis grid file. Nanonis
3ds files contain a header terminated by '
:HEADER_END:
'
line, after which big endian encoded binary data starts. A grid is
always recorded in an 'up' direction, and data is recorded
sequentially starting from the first pixel. The number of bytes
corresponding to a single pixel will depend on the experiment
parameters. In general the size of one pixel will be a sum of
- # fixed parameters
- # experimental parameters
- # sweep signal points (typically bias).
Hence if there are 2 fixed parameters, 8 experimental parameters,
and a 512 point bias sweep, a pixel will account 4 x (522) = 2088
bytes of data. The class intuits this from header info and extracts
the data for you and cuts it up into each channel, though normally
this should be just the current.
Currently cannot accept grids that are incomplete.
Parameters
----------
fname : str
Filename for grid file.
Attributes
----------
header : dict
Parsed 3ds header. Relevant fields are converted to float,
otherwise most are string values.
signals : dict
Dict keys correspond to channel name, with values being the
corresponding data array.
Raises
------
UnhandledFileError
If fname does not have a '.3ds' extension.
| 62598fd6377c676e912f7005 |
class TestDistCTR(TestFleetBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> TestFleetBase.__init__(self, pservers=2, trainers=2) <NEW_LINE> self.single_cpu_data = [ 2.6925561, 2.692213, 2.4876955, 1.225985, 2.522475 ] <NEW_LINE> self._model_file = 'dist_fleet_ctr.py' <NEW_LINE> <DEDENT> def check_data(self, loss, delta=None, expect=None): <NEW_LINE> <INDENT> if expect: <NEW_LINE> <INDENT> expect_data = expect <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> expect_data = self.single_cpu_data <NEW_LINE> <DEDENT> if delta: <NEW_LINE> <INDENT> for i in range(len(expect_data)): <NEW_LINE> <INDENT> tools.assert_almost_equal(loss[i], expect_data[i], delta=delta) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(len(expect_data)): <NEW_LINE> <INDENT> tools.assert_equal(loss[i], expect_data[i]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> """sync""" <NEW_LINE> def test_ctr_2ps_2tr_async_2thread_Tslice_Fdc_Fsm_Tsr_Tgeo_Twp_Fha_pn25( self): <NEW_LINE> <INDENT> TestFleetBase.__init__(self, pservers=2, trainers=2) <NEW_LINE> self.run_params = { 'sync_mode': 'sync', 'cpu_num': 2, 'num_threads': 2, 'slice_var_up': True, 'enable_dc_asgd': False, 'split_method': False, 'runtime_split_send_recv': True, 'geo_sgd': True, 'wait_port': True, 'use_hierarchical_allreduce': False, 'push_nums': 25 } <NEW_LINE> self.test_ctr_2ps_2tr_async_2thread_Tslice_Fdc_Fsm_Tsr_Tgeo_Twp_Fha_pn25.__func__.__doc__ = json.dumps( self.run_params) <NEW_LINE> train_data_list1 = self.get_result( self._model_file, update_method='pserver') <NEW_LINE> train_data_list2 = self.get_result( self._model_file, update_method='pserver') <NEW_LINE> assert len(train_data_list1) == 2 <NEW_LINE> assert len(train_data_list2) == 2 <NEW_LINE> self.check_data( train_data_list1[0], delta=1e-1, expect=train_data_list2[0]) <NEW_LINE> self.check_data( train_data_list1[1], delta=1e-1, expect=self.single_cpu_data) | Test dist save_persitable cases. | 62598fd6ad47b63b2c5a7d68 |
class PatternLookAhead(CompositePattern): <NEW_LINE> <INDENT> precedence = 5 <NEW_LINE> def __init__(self, pattern): <NEW_LINE> <INDENT> CompositePattern.__init__(self) <NEW_LINE> P.isValidValue(pattern) <NEW_LINE> self.patterns.append(P.asPattern(pattern)) <NEW_LINE> <DEDENT> @ConfigBackCaptureString4match <NEW_LINE> def match(self, string, index=0, context=None): <NEW_LINE> <INDENT> match = self.patterns[0].match(string, index, context) <NEW_LINE> if isinstance(match, Match): return match._setEnd(index) <NEW_LINE> return None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "~%s" % repr(self.patterns[0]) | Check whether the pattern matches the string that follows without consuming the
string | 62598fd697e22403b383b421 |
class ChoiceMatcher(CountMatcher, CompoundMatcher): <NEW_LINE> <INDENT> def __init__(self, comment=None, count=None): <NEW_LINE> <INDENT> super(ChoiceMatcher, self).__init__(comment, count) <NEW_LINE> <DEDENT> def validate(self, parents, rules_lookup, classes_lookup): <NEW_LINE> <INDENT> CompoundMatcher.validate(self, parents, rules_lookup, classes_lookup) <NEW_LINE> <DEDENT> def get_pattern(self, rules_lookup, classes_lookup, unicode_database, is_look_behind=False): <NEW_LINE> <INDENT> count = CountMatcher.get_pattern(self, is_look_behind=is_look_behind) <NEW_LINE> choice = '(?:' + '(?:' + ')|(?:'.join([m.get_pattern(rules_lookup, classes_lookup, unicode_database, is_look_behind) for m in self._children]) + ')' + ')' <NEW_LINE> if len(count) > 0: <NEW_LINE> <INDENT> return '%s%s' % (choice, count) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return choice <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> count = CountMatcher.get_pattern(self) <NEW_LINE> return '({}){}'.format('|'.join('{}'.format(m) for m in self._children), count) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> count = super(ChoiceMatcher, self).get_pattern() <NEW_LINE> return '<ChoiceMatcher %s>' % count | Represent a list of alternative matchers.
Defined in
5.3.5. The choice Element | 62598fd6656771135c489b8a |
class PatchParams: <NEW_LINE> <INDENT> def __init__(self, patch_alias=None, select_all_from=False, orig_alias=None): <NEW_LINE> <INDENT> self.patch_alias = patch_alias <NEW_LINE> self.select_all_from = select_all_from <NEW_LINE> self.orig_alias = orig_alias or patch_alias | Parameters for controlling patch behavior | 62598fd6adb09d7d5dc0aa92 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.