code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class MappingCollection(dict): <NEW_LINE> <INDENT> def __init__(self, item_name): <NEW_LINE> <INDENT> dict.__init__(self) <NEW_LINE> self.item_name = item_name <NEW_LINE> <DEDENT> def filter_by_name(self, names): <NEW_LINE> <INDENT> for name in set(self) - set(names): <NEW_LINE> <INDENT> self.remove(name) <NEW_LINE> <DEDENT> <DEDENT> def remove(self, name): <NEW_LINE> <INDENT> if name not in self: <NEW_LINE> <INDENT> raise ValueError(f"{self.item_name} {name} unknown") <NEW_LINE> <DEDENT> log.info("Removing %s %s", self.item_name, name) <NEW_LINE> self.pop(name).disable() <NEW_LINE> <DEDENT> def contains_item(self, item, handle_update_func): <NEW_LINE> <INDENT> if item == self.get(item.get_name()): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return handle_update_func(item) if item.get_name() in self else False <NEW_LINE> <DEDENT> def add(self, item, update_func): <NEW_LINE> <INDENT> if self.contains_item(item, update_func): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> log.info("Adding new %s" % item) <NEW_LINE> self[item.get_name()] = item <NEW_LINE> return True <NEW_LINE> <DEDENT> def replace(self, item): <NEW_LINE> <INDENT> return self.add(item, self.remove_item) <NEW_LINE> <DEDENT> def remove_item(self, item): <NEW_LINE> <INDENT> return self.remove(item.get_name()) | Dictionary like object for managing collections of items. Item is
expected to support the following interface, and should be hashable.
class Item(object):
def get_name(self): ...
def restore_state(self, state_data): ...
def disable(self): ...
def __eq__(self, other): ... | 62599098283ffb24f3cf5669 |
class TestArchitecture(unittest.TestCase): <NEW_LINE> <INDENT> def test_modify_arch(self): <NEW_LINE> <INDENT> for _ in xrange(10): <NEW_LINE> <INDENT> setArchitecture(random.choice((ARCH.X86_64, ARCH.X86))) | Testing the architectures. | 62599098091ae35668706a02 |
class RunePage(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.current = kwargs['current'] <NEW_LINE> self.id = kwargs['id'] <NEW_LINE> self.name = kwargs['name'] <NEW_LINE> if 'slots' in kwargs: <NEW_LINE> <INDENT> slots = [] <NEW_LINE> for slot in kwargs['slots']: <NEW_LINE> <INDENT> slots.append(RuneSlot(**slot)) <NEW_LINE> <DEDENT> self.slots = slots <NEW_LINE> <DEDENT> <DEDENT> def __object_string(self): <NEW_LINE> <INDENT> objdict = self.__dict__ <NEW_LINE> object_string = '' <NEW_LINE> for key in objdict: <NEW_LINE> <INDENT> object_string = object_string + '{0}: {1}\n'.format(key, objdict[key]) <NEW_LINE> <DEDENT> return object_string <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__object_string() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__object_string() <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.__object_string() | current boolean Indicates if the page is the current page.
id long Rune page ID.
name string Rune page name.
slots List[RuneSlotDto] List of rune slots associated with the rune page. | 625990985fdd1c0f98e5fd45 |
class Betaplane(): <NEW_LINE> <INDENT> def __init__(self,lat): <NEW_LINE> <INDENT> const = Constants() <NEW_LINE> self.f0 = 2.*const.omega*sin(lat*pi/180.) <NEW_LINE> self.beta = 2*const.omega*cos(lat*pi/180.)/const.radius_mean | A class that represents parameters of the beta plane
centered at lat | 62599098283ffb24f3cf566b |
class DescribeTaskLastStatusRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TaskId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TaskId = params.get("TaskId") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | DescribeTaskLastStatus请求参数结构体
| 62599098099cdd3c636762e2 |
@taskrooms_ns.expect(auth_parser) <NEW_LINE> @taskrooms_ns.route('') <NEW_LINE> class Rooms(Resource): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> @taskrooms_ns.expect(room_request) <NEW_LINE> def post(self): <NEW_LINE> <INDENT> email = get_jwt_identity() <NEW_LINE> payload = marshal(api.payload, room_request) <NEW_LINE> payload['users'] = [email] <NEW_LINE> payload['tasks'] = [] <NEW_LINE> taskroom_service.create_room(payload) <NEW_LINE> return {'Message': "Room created successfully"} <NEW_LINE> <DEDENT> @taskrooms_ns.expect(state_parser) <NEW_LINE> @jwt_required <NEW_LINE> def get(self): <NEW_LINE> <INDENT> email = get_jwt_identity() <NEW_LINE> args = state_parser.parse_args() <NEW_LINE> if self.validate_state(args['State']): <NEW_LINE> <INDENT> response = taskroom_service.get_rooms(email, state=args['State']) <NEW_LINE> return {'Message': "Rooms rendered successfully", 'records': marshal(response, room_response)} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {"Message": "State is not in (active|archived|deleted)"} <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def validate_state(state): <NEW_LINE> <INDENT> if state == 'active' or state == 'archived' or state == 'deleted': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Create and Get Rooms | 62599098283ffb24f3cf566d |
class ItemAccessPermissions(BaseAccessPermissions): <NEW_LINE> <INDENT> base_permission = "agenda.can_see" <NEW_LINE> async def get_restricted_data( self, full_data: List[Dict[str, Any]], user_id: int ) -> List[Dict[str, Any]]: <NEW_LINE> <INDENT> def filtered_data(full_data, blocked_keys): <NEW_LINE> <INDENT> whitelist = full_data.keys() - blocked_keys <NEW_LINE> return {key: full_data[key] for key in whitelist} <NEW_LINE> <DEDENT> if full_data and await async_has_perm(user_id, "agenda.can_see"): <NEW_LINE> <INDENT> if await async_has_perm( user_id, "agenda.can_manage" ) and await async_has_perm(user_id, "agenda.can_see_internal_items"): <NEW_LINE> <INDENT> data = full_data <NEW_LINE> <DEDENT> elif await async_has_perm(user_id, "agenda.can_see_internal_items"): <NEW_LINE> <INDENT> data = [ full for full in full_data if not full["is_hidden"] ] <NEW_LINE> blocked_keys = ("comment",) <NEW_LINE> data = [ filtered_data(full, blocked_keys) for full in data ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> blocked_keys_internal_hidden_case = set(full_data[0].keys()) - set( ( "id", "title_information", "speakers", "speaker_list_closed", "content_object", ) ) <NEW_LINE> if await async_has_perm(user_id, "agenda.can_manage"): <NEW_LINE> <INDENT> blocked_keys_non_internal_hidden_case: Iterable[str] = [] <NEW_LINE> can_see_hidden = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> blocked_keys_non_internal_hidden_case = ("comment",) <NEW_LINE> can_see_hidden = False <NEW_LINE> <DEDENT> data = [] <NEW_LINE> for full in full_data: <NEW_LINE> <INDENT> if full["is_hidden"]: <NEW_LINE> <INDENT> if can_see_hidden: <NEW_LINE> <INDENT> data.append( filtered_data(full, blocked_keys_internal_hidden_case) ) <NEW_LINE> <DEDENT> <DEDENT> elif full["is_internal"]: <NEW_LINE> <INDENT> data.append( filtered_data(full, blocked_keys_internal_hidden_case) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data.append( filtered_data(full, blocked_keys_non_internal_hidden_case) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> data = [] <NEW_LINE> <DEDENT> return data | Access permissions container for Item and ItemViewSet. | 62599098656771135c48af1a |
class EndpointConsumer(bootsteps.ConsumerStep): <NEW_LINE> <INDENT> def get_consumers(self, channel): <NEW_LINE> <INDENT> return [Consumer(channel, queues=[Queue(Config.CELERY_DEFAULT_QUEUE)], on_message=self.on_message, tag_prefix='tentacle',)] <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> if Config.CELERY_TASK_SERIALIZER.endswith('json'): <NEW_LINE> <INDENT> serializer = json_loads <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer = msgpack_loads <NEW_LINE> <DEDENT> payload = serializer(message.body) <NEW_LINE> if 'action' not in payload: <NEW_LINE> <INDENT> logger.info('Received msg with no action. Rejecting it.') <NEW_LINE> message.reject() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = payload.get('action') <NEW_LINE> task_payload = payload.get('task') <NEW_LINE> logger.info('Received msg: <%s> action and <%s> id.', action, payload.get('id')) <NEW_LINE> logger.debug('Active tasks: %s', ','.join(item for item in app.tasks)) <NEW_LINE> app.tasks['tentacle.endpointtasks.' + action].apply_async( args=(task_payload,), task_id=payload.get('id'), reply_to=payload.get('id')) <NEW_LINE> message.ack() | Consumer that is used to provide endpoints to the Event Repository.
http://celery.readthedocs.org/en/latest/userguide/extending.html | 62599098099cdd3c636762e3 |
class NumberSet: <NEW_LINE> <INDENT> def __init__(self, x=-1, z=-1, a=-1): <NEW_LINE> <INDENT> pass | common base class for all number manipulations | 62599098adb09d7d5dc0c32e |
class USTimeZones(zc.sourcefactory.basic.BasicSourceFactory): <NEW_LINE> <INDENT> tzs = [tz for tz in pytz.common_timezones if 'US/' in tz and 'Pacific-New' not in tz] <NEW_LINE> def getValues(self): <NEW_LINE> <INDENT> return self.tzs <NEW_LINE> <DEDENT> def getTitle(self, value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def getToken(self, value): <NEW_LINE> <INDENT> return value | List of timezones taken from pytz | 625990985fdd1c0f98e5fd49 |
class TestGetPseudonym(TestCase): <NEW_LINE> <INDENT> def test_pseudonym(self): <NEW_LINE> <INDENT> user_data = {'first_name': 'Eda', 'last_name': 'Tester', 'birth_date': datetime.date(2000, 5, 1)} <NEW_LINE> with responses.RequestsMock() as rsps: <NEW_LINE> <INDENT> rsps.add(responses.POST, 'https://tnia.eidentita.cz/IPSTS/issue.svc/certificate', body=file_content('IPSTS_response.xml')) <NEW_LINE> rsps.add(responses.POST, 'https://tnia.eidentita.cz/FPSTS/Issue.svc', body=file_content('FPSTS_response.xml')) <NEW_LINE> rsps.add(responses.POST, 'https://tnia.eidentita.cz/WS/submission/Public.svc/token', body=file_content('Sub_response.xml')) <NEW_LINE> self.assertEqual(get_pseudonym(SETTINGS, user_data), '1d71ff1a-d732-4485-a8dc-ad4c42a8a739') <NEW_LINE> <DEDENT> <DEDENT> def test_no_data(self): <NEW_LINE> <INDENT> user_data = {'first_name': 'Eda', 'last_name': 'Tester', 'birth_date': datetime.date(2000, 5, 1)} <NEW_LINE> with responses.RequestsMock() as rsps: <NEW_LINE> <INDENT> rsps.add(responses.POST, 'https://tnia.eidentita.cz/IPSTS/issue.svc/certificate', body=file_content('IPSTS_response.xml')) <NEW_LINE> rsps.add(responses.POST, 'https://tnia.eidentita.cz/FPSTS/Issue.svc', body=file_content('FPSTS_response.xml')) <NEW_LINE> rsps.add(responses.POST, 'https://tnia.eidentita.cz/WS/submission/Public.svc/token', body=file_content('Sub_empty_response.xml')) <NEW_LINE> with self.assertRaises(NiaException) as err: <NEW_LINE> <INDENT> get_pseudonym(SETTINGS, user_data) <NEW_LINE> <DEDENT> self.assertEqual(str(err.exception), 'ISZR returned zero AIFOs') | Unittests for get_pseudonym function. | 6259909850812a4eaa621ab1 |
class PosixLDIFMail(PosixLDIF): <NEW_LINE> <INDENT> def init_user(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__super.init_user(*args, **kwargs) <NEW_LINE> timer = make_timer(self.logger, 'Starting PosixLDIFMail.init_user...') <NEW_LINE> self.mail_attrs = cereconf.LDAP_USER.get('mail_attrs', ['mail']) <NEW_LINE> from string import Template <NEW_LINE> self.mail_template = Template(cereconf.LDAP_USER.get( 'mail_default_template')) <NEW_LINE> mail_spreads = LDIFutils.map_spreads( cereconf.LDAP_USER.get('mail_spreads'), list) <NEW_LINE> self.accounts_with_email = set() <NEW_LINE> for account_id, spread in self.posuser.list_entity_spreads( entity_types=self.const.entity_account): <NEW_LINE> <INDENT> if spread in mail_spreads: <NEW_LINE> <INDENT> self.accounts_with_email.add(account_id) <NEW_LINE> <DEDENT> <DEDENT> timer('...done PosixLDIFMail.init_user') <NEW_LINE> <DEDENT> def update_user_entry(self, account_id, entry, owner_id): <NEW_LINE> <INDENT> mail = None <NEW_LINE> if account_id in self.accounts_with_email: <NEW_LINE> <INDENT> mail = self.mail_template.substitute(uid=entry['uid'][0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> contacts = self.posuser.list_contact_info( entity_id=account_id, source_system=self.const.system_manual, contact_type=self.const.contact_email) <NEW_LINE> if contacts: <NEW_LINE> <INDENT> mail = contacts[0]['contact_value'] <NEW_LINE> <DEDENT> <DEDENT> if mail: <NEW_LINE> <INDENT> for attr in self.mail_attrs: <NEW_LINE> <INDENT> entry[attr] = (mail, ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.warn('Account %s is missing mail', entry['uid'][0]) <NEW_LINE> <DEDENT> return self.__super.update_user_entry(account_id, entry, owner_id) | PosixLDIF mixin for mail attributes. | 62599098be7bc26dc9252d40 |
class Template(_messages.Message): <NEW_LINE> <INDENT> @encoding.MapUnrecognizedFields('additionalProperties') <NEW_LINE> class ActionsValue(_messages.Message): <NEW_LINE> <INDENT> class AdditionalProperty(_messages.Message): <NEW_LINE> <INDENT> key = _messages.StringField(1) <NEW_LINE> value = _messages.MessageField('Action', 2) <NEW_LINE> <DEDENT> additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) <NEW_LINE> <DEDENT> @encoding.MapUnrecognizedFields('additionalProperties') <NEW_LINE> class ModulesValue(_messages.Message): <NEW_LINE> <INDENT> class AdditionalProperty(_messages.Message): <NEW_LINE> <INDENT> key = _messages.StringField(1) <NEW_LINE> value = _messages.MessageField('Module', 2) <NEW_LINE> <DEDENT> additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) <NEW_LINE> <DEDENT> actions = _messages.MessageField('ActionsValue', 1) <NEW_LINE> description = _messages.StringField(2) <NEW_LINE> modules = _messages.MessageField('ModulesValue', 3) <NEW_LINE> name = _messages.StringField(4) | A Template represents a complete configuration for a Deployment.
Messages:
ActionsValue: Action definitions for use in Module intents in this
Template.
ModulesValue: A list of modules for this Template.
Fields:
actions: Action definitions for use in Module intents in this Template.
description: A user-supplied description of this Template.
modules: A list of modules for this Template.
name: Name of this Template. The name must conform to the expression:
[a-zA-Z0-9-_]{1,64} | 62599098c4546d3d9def8186 |
class _Sentinel: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._sentinels = {} <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return self._sentinels.setdefault(name, _SentinelObject(name)) | Access attributes to return a named object, usable as a sentinel. | 625990985fdd1c0f98e5fd4b |
import naarad.utils <NEW_LINE> logger = logging.getLogger('naarad.metrics.ProcVmstatMetric') <NEW_LINE> class ProcVmstatMetric(Metric): <NEW_LINE> <INDENT> def __init__ (self, metric_type, infile_list, hostname, output_directory, resource_path, label, ts_start, ts_end, rule_strings, important_sub_metrics, **other_options): <NEW_LINE> <INDENT> Metric.__init__(self, metric_type, infile_list, hostname, output_directory, resource_path, label, ts_start, ts_end, rule_strings, important_sub_metrics) <NEW_LINE> self.sub_metrics = None <NEW_LINE> for (key, val) in other_options.iteritems(): <NEW_LINE> <INDENT> setattr(self, key, val.split()) <NEW_LINE> <DEDENT> self.sub_metric_description = { 'nr_free_pages': 'Number of free pages', 'nr_inactive_anon': 'Number of inactive anonymous pages', 'nr_active_anon': 'Number of active anonymous pages', 'nr_inactive_file': 'Number of inactive file pages', 'nr_active_file': 'Number of active file pages', } <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> file_status = True <NEW_LINE> for input_file in self.infile_list: <NEW_LINE> <INDENT> file_status = file_status and naarad.utils.is_valid_file(input_file) <NEW_LINE> <DEDENT> if not file_status: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> status = True <NEW_LINE> data = {} <NEW_LINE> for input_file in self.infile_list: <NEW_LINE> <INDENT> logger.info('Processing : %s', input_file) <NEW_LINE> with open(input_file) as fh: <NEW_LINE> <INDENT> for line in fh: <NEW_LINE> <INDENT> words = line.split() <NEW_LINE> if len(words) < 3: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ts = words[0] + " " + words[1] <NEW_LINE> if self.ts_out_of_range(ts): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> col = words[2] <NEW_LINE> if self.sub_metrics and col not in self.sub_metrics: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.sub_metric_unit[col] = 'pages' <NEW_LINE> if col in self.column_csv_map: <NEW_LINE> <INDENT> out_csv = self.column_csv_map[col] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_csv = self.get_csv(col) <NEW_LINE> data[out_csv] = [] <NEW_LINE> <DEDENT> data[out_csv].append(ts + "," + words[3]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for csv in data.keys(): <NEW_LINE> <INDENT> self.csv_files.append(csv) <NEW_LINE> with open(csv, 'w') as fh: <NEW_LINE> <INDENT> fh.write('\n'.join(data[csv])) <NEW_LINE> <DEDENT> <DEDENT> return status | logs of /proc/vmstat
The raw log file is assumed to have a timestamp prefix of all lines. E.g. in the format of "2013-01-02 03:55:22.13456 compact_fail 36"
The log lines can be generated by 'cat /proc/vmstat | sed "s/^/$(date +%Y-%m-%d\ %H:%M:%S.%05N) /" ' | 62599098656771135c48af1c |
class FavoriteManager(models.Manager): <NEW_LINE> <INDENT> def favorites_for_user(self, user): <NEW_LINE> <INDENT> return self.get_query_set().filter(user=user) <NEW_LINE> <DEDENT> def favorites_for_model(self, model, user=None): <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_model(model) <NEW_LINE> qs = self.get_query_set().filter(content_type=content_type) <NEW_LINE> if user: <NEW_LINE> <INDENT> qs = qs.filter(user=user) <NEW_LINE> <DEDENT> return qs <NEW_LINE> <DEDENT> def favorites_for_object(self, obj, user=None): <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_model(type(obj)) <NEW_LINE> qs = self.get_query_set().filter(content_type=content_type, object_id=obj.pk) <NEW_LINE> if user: <NEW_LINE> <INDENT> qs = qs.filter(user=user) <NEW_LINE> <DEDENT> return qs <NEW_LINE> <DEDENT> def favorite_for_user(self, obj, user): <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_model(type(obj)) <NEW_LINE> return self.get_query_set().get(content_type=content_type, object_id=obj.pk) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_favorite(cls, content_object, user): <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_model(type(content_object)) <NEW_LINE> favorite = Favorite( user=user, content_type=content_type, object_id=content_object.pk, content_object=content_object ) <NEW_LINE> favorite.save() <NEW_LINE> return favorite | A Manager for Favorites | 625990988a349b6b43688039 |
class TestSecure3D21AuthenticationUpdateRequestAllOf(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 testSecure3D21AuthenticationUpdateRequestAllOf(self): <NEW_LINE> <INDENT> pass | Secure3D21AuthenticationUpdateRequestAllOf unit test stubs | 62599098be7bc26dc9252d41 |
class Color(object): <NEW_LINE> <INDENT> RED = Fore.RED <NEW_LINE> WHITE = Fore.WHITE <NEW_LINE> CYAN = Fore.CYAN <NEW_LINE> GREEN = Fore.GREEN <NEW_LINE> MAGENTA = Fore.MAGENTA <NEW_LINE> BLUE = Fore.BLUE <NEW_LINE> YELLOW = Fore.YELLOW <NEW_LINE> BLACK = Fore.BLACK <NEW_LINE> BRIGHT_RED = Style.BRIGHT + Fore.RED <NEW_LINE> BRIGHT_BLUE = Style.BRIGHT + Fore.BLUE <NEW_LINE> BRIGHT_YELLOW = Style.BRIGHT + Fore.YELLOW <NEW_LINE> BRIGHT_GREEN = Style.BRIGHT + Fore.GREEN <NEW_LINE> BRIGHT_CYAN = Style.BRIGHT + Fore.CYAN <NEW_LINE> BRIGHT_WHITE = Style.BRIGHT + Fore.WHITE <NEW_LINE> BRIGHT_MAGENTA = Style.BRIGHT + Fore.MAGENTA | Wrapper around colorama colors that are undefined in importing
| 62599098099cdd3c636762e6 |
@register_event('output') <NEW_LINE> @register <NEW_LINE> class OutputEvent(BaseSchema): <NEW_LINE> <INDENT> __props__ = { "seq": { "type": "integer", "description": "Sequence number (also known as message ID). For protocol messages of type 'request' this ID can be used to cancel the request." }, "type": { "type": "string", "enum": [ "event" ] }, "event": { "type": "string", "enum": [ "output" ] }, "body": { "type": "object", "properties": { "category": { "type": "string", "description": "The output category. If not specified, 'console' is assumed.", "_enum": [ "console", "stdout", "stderr", "telemetry" ] }, "output": { "type": "string", "description": "The output to report." }, "variablesReference": { "type": "integer", "description": "If an attribute 'variablesReference' exists and its value is > 0, the output contains objects which can be retrieved by passing 'variablesReference' to the 'variables' request. The value should be less than or equal to 2147483647 (2^31 - 1)." }, "source": { "$ref": "#/definitions/Source", "description": "An optional source location where the output was produced." }, "line": { "type": "integer", "description": "An optional source location line where the output was produced." }, "column": { "type": "integer", "description": "An optional source location column where the output was produced." }, "data": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Optional data to report. For the 'telemetry' category the data will be sent to telemetry, for the other categories the data is shown in JSON format." } }, "required": [ "output" ] } } <NEW_LINE> __refs__ = set(['body']) <NEW_LINE> __slots__ = list(__props__.keys()) + ['kwargs'] <NEW_LINE> def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): <NEW_LINE> <INDENT> self.type = 'event' <NEW_LINE> self.event = 'output' <NEW_LINE> if body is None: <NEW_LINE> <INDENT> self.body = OutputEventBody() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.body = OutputEventBody(update_ids_from_dap=update_ids_from_dap, **body) if body.__class__ != OutputEventBody else body <NEW_LINE> <DEDENT> self.seq = seq <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def to_dict(self, update_ids_to_dap=False): <NEW_LINE> <INDENT> type = self.type <NEW_LINE> event = self.event <NEW_LINE> body = self.body <NEW_LINE> seq = self.seq <NEW_LINE> dct = { 'type': type, 'event': event, 'body': body.to_dict(update_ids_to_dap=update_ids_to_dap), 'seq': seq, } <NEW_LINE> dct.update(self.kwargs) <NEW_LINE> return dct | The event indicates that the target has produced some output.
Note: automatically generated code. Do not edit manually. | 62599098d8ef3951e32c8d49 |
class DisconfAPIFactory(object): <NEW_LINE> <INDENT> def __init__(self, dapi, api): <NEW_LINE> <INDENT> self.__dapi = dapi <NEW_LINE> self.__api = api <NEW_LINE> <DEDENT> def __checkAuth__(self): <NEW_LINE> <INDENT> self.__dapi.__checkAuth__() <NEW_LINE> <DEDENT> def __getattr__(self, method): <NEW_LINE> <INDENT> def func(**params): <NEW_LINE> <INDENT> if method.upper() not in self.__dapi._method[self.__api]: <NEW_LINE> <INDENT> raise DisconfAPIException( 'No such API Method: %s %s' % (method.upper(), self.__api)) <NEW_LINE> <DEDENT> return self.proxy_api(method=method, **params) <NEW_LINE> <DEDENT> return func <NEW_LINE> <DEDENT> def url_request(self, method, **params): <NEW_LINE> <INDENT> return self.__dapi.url_request( api=self.__api, method=method, **params) <NEW_LINE> <DEDENT> @check_auth <NEW_LINE> @disconf_api <NEW_LINE> def proxy_api(self, method, **params): <NEW_LINE> <INDENT> pass | Disconf API Factory | 625990983617ad0b5ee07f2e |
class registrovacunaView(View): <NEW_LINE> <INDENT> template_name = 'admin/registro-vacunas.html' <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> return render(request, self.template_name, {}) | Vista de la pagina Home | 625990988a349b6b4368803d |
class RunTaskFailure(TaskError): <NEW_LINE> <INDENT> pass | Error from rpc_run_task in Odoo. | 62599098d8ef3951e32c8d4a |
class PriceRange(proto.Message): <NEW_LINE> <INDENT> min_ = proto.Field( proto.FLOAT, number=1, ) <NEW_LINE> max_ = proto.Field( proto.FLOAT, number=2, ) | Product price range when there are a range of prices for
different variations of the same product.
Attributes:
min_ (float):
Required. The minimum product price.
max_ (float):
Required. The maximum product price. | 62599099099cdd3c636762e8 |
class QuadTree: <NEW_LINE> <INDENT> def __init__(self, data, mins, maxs, depth=10): <NEW_LINE> <INDENT> self.data = np.asarray(data) <NEW_LINE> assert self.data.shape[1] == 2 <NEW_LINE> if mins is None: <NEW_LINE> <INDENT> mins = data.min(0) <NEW_LINE> <DEDENT> if maxs is None: <NEW_LINE> <INDENT> maxs = data.max(0) <NEW_LINE> <DEDENT> self.mins = np.asarray(mins) <NEW_LINE> self.maxs = np.asarray(maxs) <NEW_LINE> self.sizes = self.maxs - self.mins <NEW_LINE> self.children = [] <NEW_LINE> mids = 0.5 * (self.mins + self.maxs) <NEW_LINE> xmin, ymin = self.mins <NEW_LINE> xmax, ymax = self.maxs <NEW_LINE> xmid, ymid = mids <NEW_LINE> if depth > 0: <NEW_LINE> <INDENT> data_q1 = data[(data[:, 0] < mids[0]) & (data[:, 1] < mids[1])] <NEW_LINE> data_q2 = data[(data[:, 0] < mids[0]) & (data[:, 1] >= mids[1])] <NEW_LINE> data_q3 = data[(data[:, 0] >= mids[0]) & (data[:, 1] < mids[1])] <NEW_LINE> data_q4 = data[(data[:, 0] >= mids[0]) & (data[:, 1] >= mids[1])] <NEW_LINE> if data_q1.shape[0] > 0: <NEW_LINE> <INDENT> self.children.append(QuadTree(data_q1, [xmin, ymin], [xmid, ymid], depth - 1)) <NEW_LINE> <DEDENT> if data_q2.shape[0] > 0: <NEW_LINE> <INDENT> self.children.append(QuadTree(data_q2, [xmin, ymid], [xmid, ymax], depth - 1)) <NEW_LINE> <DEDENT> if data_q3.shape[0] > 0: <NEW_LINE> <INDENT> self.children.append(QuadTree(data_q3, [xmid, ymin], [xmax, ymid], depth - 1)) <NEW_LINE> <DEDENT> if data_q4.shape[0] > 0: <NEW_LINE> <INDENT> self.children.append(QuadTree(data_q4, [xmid, ymid], [xmax, ymax], depth - 1)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def draw_rectangle(self, ax, depth): <NEW_LINE> <INDENT> if depth is None or depth == 0: <NEW_LINE> <INDENT> rect = plt.Rectangle(self.mins, *self.sizes, zorder=2, ec='#000000', fc='none') <NEW_LINE> ax.add_patch(rect) <NEW_LINE> <DEDENT> if depth is None or depth > 0: <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> child.draw_rectangle(ax, depth - 1) | Simple Quad-tree class | 62599099091ae35668706a10 |
class UpdateInterventionStatus(Resource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.db = IncidentModel() <NEW_LINE> <DEDENT> @require_token <NEW_LINE> def patch(current_user, self, incident_id): <NEW_LINE> <INDENT> if current_user['isadmin'] is False: <NEW_LINE> <INDENT> return only_admin_can_edit() <NEW_LINE> <DEDENT> edit_status = self.db.edit_incident_status( incident_id, incident_type='intervention') <NEW_LINE> if edit_status == None: <NEW_LINE> <INDENT> return non_existance_incident() <NEW_LINE> <DEDENT> if edit_status == "status updated": <NEW_LINE> <INDENT> return jsonify({ "status": 200, "data": { "id": incident_id, "message": "Updated intervention's status" } }) | docstring for patching status of an intervention | 625990995fdd1c0f98e5fd55 |
class TestV1ReplicaSpec(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 testV1ReplicaSpec(self): <NEW_LINE> <INDENT> pass | V1ReplicaSpec unit test stubs | 6259909950812a4eaa621ab7 |
class CyberListenerSnort(CyberListener): <NEW_LINE> <INDENT> def runit(self): <NEW_LINE> <INDENT> i=1 <NEW_LINE> while (1): <NEW_LINE> <INDENT> line = linecache.getline(self.def_log_file,i) <NEW_LINE> if (len(line)>1): <NEW_LINE> <INDENT> line = line.split(',') <NEW_LINE> self.sendEvenToMaster( CyberEvent("Snort", line[0], line[4], line[5], line[7], line[6])) <NEW_LINE> i=i+1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time.sleep(2) <NEW_LINE> linecache.checkcache(self.def_log_file) | classdocs | 625990993617ad0b5ee07f34 |
class TimeUnit(StrEnum): <NEW_LINE> <INDENT> NS = 'ns' <NEW_LINE> US = 'us' <NEW_LINE> MS = 'ms' <NEW_LINE> S = 's' <NEW_LINE> M = 'm' <NEW_LINE> H = 'h' <NEW_LINE> D = 'd' <NEW_LINE> @property <NEW_LINE> def multiplier(self) -> float: <NEW_LINE> <INDENT> mult = (1.0, 1.0E3, 1.0E6, 1.0E9, 6.0E10, 3.6E12, 8.64E13) <NEW_LINE> return mult[self.all().index(self)] <NEW_LINE> <DEDENT> def __call__(self, value: Value) -> TimeMeasurement: <NEW_LINE> <INDENT> return TimeMeasurement(value, self) | Time unit. | 62599099adb09d7d5dc0c33c |
class DataParser: <NEW_LINE> <INDENT> def __init__(self, acc_unit=100, gy_unit=100): <NEW_LINE> <INDENT> self.data_split = range(6) <NEW_LINE> self.acc_unit = acc_unit <NEW_LINE> self.gy_unit = gy_unit <NEW_LINE> <DEDENT> def parse_data(self, buffer, sensor): <NEW_LINE> <INDENT> for i in range(6): <NEW_LINE> <INDENT> self.data_split[i] = buffer[2*i:2*(i+1)] <NEW_LINE> <DEDENT> sensor.setValues(x=struct.unpack_from("!h",self.data_split[0])[0]/self.acc_unit, y=struct.unpack_from("!h",self.data_split[1])[0]/self.acc_unit, z=struct.unpack_from("!h",self.data_split[2])[0]/self.acc_unit, gX=struct.unpack_from("!h",self.data_split[3])[0]/self.gy_unit, gY=struct.unpack_from("!h",self.data_split[4])[0]/self.gy_unit, gZ=struct.unpack_from("!h",self.data_split[5])[0]/self.gy_unit ) | parses bytes from sensor and saves the values in a SensorStream; acc_unit and gy_unit
are the quantization steps for accelerometer and gyroscope respectively | 625990995fdd1c0f98e5fd59 |
class HelloViewSets(viewsets.ViewSet): <NEW_LINE> <INDENT> serializer_class = serializer.HelloSerializer <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> aViewset=[ 'Uses the Actions: List, Create, Retrive, Update, Partial_Update', 'Automatic mapping of urls by the Router', 'Provides more functionality with less code' ] <NEW_LINE> return Response({'message':'Hello', 'aViewset':aViewset}) <NEW_LINE> <DEDENT> def create(self, request): <NEW_LINE> <INDENT> serialized = serializer.HelloSerializer(data = request.data) <NEW_LINE> if serialized.is_valid(): <NEW_LINE> <INDENT> name = serialized.data.get('name') <NEW_LINE> message = 'Hello {0}, from ViewSet'.format(name) <NEW_LINE> return Response({'message':message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response(serialized.errors, status = status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def retrieve(self, request, pk = None): <NEW_LINE> <INDENT> return Response({'http_method':'GET'}) <NEW_LINE> <DEDENT> def update(self, request, pk = None): <NEW_LINE> <INDENT> return Response({'http_method':'PUT'}) <NEW_LINE> <DEDENT> def partial_update(self, request, pk = None): <NEW_LINE> <INDENT> return Response({'http_method':'PATCH'}) <NEW_LINE> <DEDENT> def destroy(self, request, pk = None): <NEW_LINE> <INDENT> return Response({'http_method':'DELETE'}) | To Explain viewsets | 62599099283ffb24f3cf567f |
class Faculty(PriorityQueue): <NEW_LINE> <INDENT> def find(self, image): <NEW_LINE> <INDENT> return "Found image in database: " + image | Locates images in database. | 62599099dc8b845886d5539f |
class SearchAutoCompleteAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> change_list_template = 'search_admin_autocomplete/change_list.html' <NEW_LINE> search_fields = [] <NEW_LINE> search_prefix = '__contains' <NEW_LINE> max_results = 10 <NEW_LINE> def get_urls(self) -> List[URLPattern]: <NEW_LINE> <INDENT> urls = super(SearchAutoCompleteAdmin, self).get_urls() <NEW_LINE> api_urls = [url(r'^search/(?P<search_term>\w{0,50})$', self.search_api)] <NEW_LINE> return api_urls + urls <NEW_LINE> <DEDENT> def search_api(self, request: HttpRequest, search_term: str) -> HttpResponse: <NEW_LINE> <INDENT> if len(self.search_fields) == 0: <NEW_LINE> <INDENT> return HttpResponseBadRequest(reason='Mo search_fields defined in {}'.format(self.__class__.__name__)) <NEW_LINE> <DEDENT> query = [Q(**{'{}{}'.format(field, self.search_prefix): search_term}) for field in self.search_fields] <NEW_LINE> query = reduce(or_, query) <NEW_LINE> return JsonResponse(data=[{'keyword': self.get_instance_name(item), 'url': self.get_instance_url(item)} for item in self.model.objects.filter(query)[0:self.max_results]], safe=False) <NEW_LINE> <DEDENT> def get_instance_name(self, instance: Model) -> str: <NEW_LINE> <INDENT> values = [] <NEW_LINE> for field in self.search_fields: <NEW_LINE> <INDENT> value = getattr(instance, field) <NEW_LINE> if not value: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> values.append(str(value)) <NEW_LINE> <DEDENT> if not values: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return ", ".join(values) <NEW_LINE> <DEDENT> def get_instance_url(self, instance: Model) -> str: <NEW_LINE> <INDENT> url_name = "admin:{}_{}_change".format(self.model._meta.app_label, str(self.model.__name__).lower()) <NEW_LINE> return reverse(url_name, args=(instance.pk,)) | Basic admin class that allows to enable search autocomplete for certain model.
Usage:
.. code-block:: python
class MyModelAdmin(SearchAutoCompleteAdmin)
search_fields = ['search_field', ]
admin.site.register(MyModel, MyModelAdmin) | 62599099adb09d7d5dc0c342 |
class DataClass2(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.data = np.zeros((60,3,32,32)) <NEW_LINE> self.indexes = np.arange(self.data.shape[0]) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.data.shape[0] <NEW_LINE> <DEDENT> def __getitem__(self, indexes): <NEW_LINE> <INDENT> return self.data[self.indexes[indexes]] | docstring for A | 62599099d8ef3951e32c8d50 |
class ServiceException(PythonRuntimeException): <NEW_LINE> <INDENT> pass | Exception thrown in case of an error in Zserio Service | 625990995fdd1c0f98e5fd5d |
class Reviews(Base): <NEW_LINE> <INDENT> _review_locator = (By.CSS_SELECTOR, '#review-list li') <NEW_LINE> _success_notification_locator = (By.CSS_SELECTOR, 'section.notification-box.full > div.success') <NEW_LINE> def __init__(self, testsetup, app_name = False): <NEW_LINE> <INDENT> Base.__init__(self, testsetup) <NEW_LINE> self.wait_for_ajax_on_page_finish() <NEW_LINE> if app_name: <NEW_LINE> <INDENT> self._page_title = "Reviews for %s | Mozilla Marketplace" % app_name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def reviews(self): <NEW_LINE> <INDENT> return [self.ReviewSnippet(self.testsetup, web_element) for web_element in self.selenium.find_elements(*self._review_locator)] <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_success_message_visible(self): <NEW_LINE> <INDENT> return self.is_element_visible(*self._success_notification_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def success_message(self): <NEW_LINE> <INDENT> return self.selenium.find_element(*self._success_notification_locator).text <NEW_LINE> <DEDENT> class ReviewSnippet(Base): <NEW_LINE> <INDENT> _review_text_locator = (By.CSS_SELECTOR, '.body') <NEW_LINE> _review_rating_locator = (By.CSS_SELECTOR, 'span.stars') <NEW_LINE> _review_author_locator = (By.CSS_SELECTOR, 'span.byline > a') <NEW_LINE> _delete_review_locator = (By.CSS_SELECTOR, '.delete') <NEW_LINE> _edit_review_locator = (By.CSS_SELECTOR, '.edit') <NEW_LINE> def __init__(self, testsetup, element): <NEW_LINE> <INDENT> Base.__init__(self, testsetup) <NEW_LINE> self._root_element = element <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self._root_element.find_element(*self._review_text_locator).text <NEW_LINE> <DEDENT> @property <NEW_LINE> def rating(self): <NEW_LINE> <INDENT> return int(self._root_element.find_element(*self._review_rating_locator).text.split()[1]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def author(self): <NEW_LINE> <INDENT> return self._root_element.find_element(*self._review_author_locator).text <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> self._root_element.find_element(*self._delete_review_locator).click() <NEW_LINE> self.wait_for_ajax_on_page_finish() <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_review_visible(self): <NEW_LINE> <INDENT> return self.is_element_visible(*self._review_text_locator) | Page with all reviews of an app.
https://marketplace-dev.allizom.org/en-US/app/app-name/reviews/ | 625990993617ad0b5ee07f3c |
class ClassifyEvaluator(object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, labels_to_names): <NEW_LINE> <INDENT> self._labels_to_names = labels_to_names <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_single_detected_image_info(self, detections_dict): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def evaluate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def clear(self): <NEW_LINE> <INDENT> pass | Interface for object classify evalution classes.
Example usage of the Evaluator:
------------------------------
evaluator = ClassifyEvaluator(categories)
# Classifys and groundtruth for image 1.
evaluator.add_single_detected_image_info(...)
# Classifys and groundtruth for image 2.
evaluator.add_single_detected_image_info(...)
metrics_dict = evaluator.evaluate() | 62599099dc8b845886d553a1 |
class BJ_Game(object): <NEW_LINE> <INDENT> def __init__(self, names): <NEW_LINE> <INDENT> self.players = [] <NEW_LINE> for name in names: <NEW_LINE> <INDENT> player = BJ_Player(name) <NEW_LINE> self.players.append(player) <NEW_LINE> <DEDENT> self.dealer = BJ_Dealer("Rozdający") <NEW_LINE> self.deck = BJ_Deck() <NEW_LINE> self.deck.populate() <NEW_LINE> self.deck.shuffle() <NEW_LINE> <DEDENT> @property <NEW_LINE> def still_playing(self): <NEW_LINE> <INDENT> sp = [] <NEW_LINE> for player in self.players: <NEW_LINE> <INDENT> if not player.is_busted(): <NEW_LINE> <INDENT> sp.append(player) <NEW_LINE> <DEDENT> <DEDENT> return sp <NEW_LINE> <DEDENT> def __additional_cards(self, player): <NEW_LINE> <INDENT> while not player.is_busted() and player.is_hitting(): <NEW_LINE> <INDENT> self.deck.deal([player]) <NEW_LINE> print(player) <NEW_LINE> if player.is_busted(): <NEW_LINE> <INDENT> player.bust() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def money(self, player): <NEW_LINE> <INDENT> value = 0 <NEW_LINE> while not player.is_busted() and player.bet(): <NEW_LINE> <INDENT> value = int(input("Jak duzo chcesz obstawic? ")) <NEW_LINE> maks = int(player.my_money()) + 1 <NEW_LINE> while value not in range(0, maks): <NEW_LINE> <INDENT> value = int(input("Jak duzo chcesz obstawic? ")) <NEW_LINE> <DEDENT> player.lose_money(value) <NEW_LINE> maks = int(player.my_money()) <NEW_LINE> return int(value) <NEW_LINE> <DEDENT> return int(value) <NEW_LINE> <DEDENT> def play(self): <NEW_LINE> <INDENT> for player in self.players: <NEW_LINE> <INDENT> if player.my_money() <= 0: <NEW_LINE> <INDENT> self.players.remove(player) <NEW_LINE> <DEDENT> <DEDENT> self.deck.deal(self.players + [self.dealer], per_hand = 2) <NEW_LINE> self.dealer.flip_first_card() <NEW_LINE> for player in self.players: <NEW_LINE> <INDENT> print(player) <NEW_LINE> <DEDENT> print(self.dealer) <NEW_LINE> cash = 0 <NEW_LINE> for player in self.players: <NEW_LINE> <INDENT> self.__additional_cards(player) <NEW_LINE> cash += self.money(player) <NEW_LINE> cash += int(cash * 1.5) <NEW_LINE> <DEDENT> self.dealer.flip_first_card() <NEW_LINE> if not self.still_playing: <NEW_LINE> <INDENT> print(self.dealer) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(self.dealer) <NEW_LINE> self.__additional_cards(self.dealer) <NEW_LINE> if self.dealer.is_busted(): <NEW_LINE> <INDENT> for player in self.still_playing: <NEW_LINE> <INDENT> player.win(cash) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for player in self.still_playing: <NEW_LINE> <INDENT> if player.total > self.dealer.total: <NEW_LINE> <INDENT> player.win(cash) <NEW_LINE> <DEDENT> elif player.total < self.dealer.total: <NEW_LINE> <INDENT> player.lose() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> player.push() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for player in self.players: <NEW_LINE> <INDENT> player.clear() <NEW_LINE> <DEDENT> self.dealer.clear() <NEW_LINE> self.deck.clear() <NEW_LINE> self.deck.populate() <NEW_LINE> self.deck.shuffle() | Gra w blackjacka. | 625990995fdd1c0f98e5fd5f |
class Output(object): <NEW_LINE> <INDENT> COLOR = rh.terminal.Color() <NEW_LINE> COMMIT = COLOR.color(COLOR.CYAN, 'COMMIT') <NEW_LINE> RUNNING = COLOR.color(COLOR.YELLOW, 'RUNNING') <NEW_LINE> PASSED = COLOR.color(COLOR.GREEN, 'PASSED') <NEW_LINE> FAILED = COLOR.color(COLOR.RED, 'FAILED') <NEW_LINE> def __init__(self, project_name, num_hooks): <NEW_LINE> <INDENT> self.project_name = project_name <NEW_LINE> self.num_hooks = num_hooks <NEW_LINE> self.hook_index = 0 <NEW_LINE> self.success = True <NEW_LINE> <DEDENT> def commit_start(self, commit, commit_summary): <NEW_LINE> <INDENT> status_line = '[%s %s] %s' % (self.COMMIT, commit[0:12], commit_summary) <NEW_LINE> rh.terminal.print_status_line(status_line, print_newline=True) <NEW_LINE> self.hook_index = 1 <NEW_LINE> <DEDENT> def hook_start(self, hook_name): <NEW_LINE> <INDENT> status_line = '[%s %d/%d] %s' % (self.RUNNING, self.hook_index, self.num_hooks, hook_name) <NEW_LINE> self.hook_index += 1 <NEW_LINE> rh.terminal.print_status_line(status_line) <NEW_LINE> <DEDENT> def hook_error(self, hook_name, error): <NEW_LINE> <INDENT> status_line = '[%s] %s' % (self.FAILED, hook_name) <NEW_LINE> rh.terminal.print_status_line(status_line, print_newline=True) <NEW_LINE> print(error, file=sys.stderr) <NEW_LINE> self.success = False <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> status_line = '[%s] repohooks for %s %s' % ( self.PASSED if self.success else self.FAILED, self.project_name, 'passed' if self.success else 'failed') <NEW_LINE> rh.terminal.print_status_line(status_line, print_newline=True) | Class for reporting hook status. | 6259909950812a4eaa621abc |
class Command(BaseCommand): <NEW_LINE> <INDENT> help = "for all source models, collect rss feed and create items" <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> collect_all_rss_items() | collect rss | 62599099c4546d3d9def8191 |
class TestReadsIntervalIteratorClassMethods(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.read = generateReadAlignment(5) <NEW_LINE> self.intervalIterator = backend.ReadsIntervalIterator <NEW_LINE> <DEDENT> def testGetReadStart(self): <NEW_LINE> <INDENT> result = self.intervalIterator._getStart(self.read) <NEW_LINE> self.assertEqual(self.read.alignment.position.position, result) <NEW_LINE> <DEDENT> def testGetReadEnd(self): <NEW_LINE> <INDENT> result = self.intervalIterator._getEnd(self.read) <NEW_LINE> self.assertEqual( self.intervalIterator._getStart(self.read) + len(self.read.aligned_sequence), result) | Test the variants interval iterator class methods | 62599099dc8b845886d553a5 |
class TestUserTemplatesWithImpressionsFromEmptyDatabase(UserTemplatesFixture): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__({'impressions_enabled': True}) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> super().setup() <NEW_LINE> ut.generate_templates(self.session_context) <NEW_LINE> <DEDENT> def test_templates(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_strengths_incremental_new_product_5star(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_strengths_incremental_new_product_3star(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_strengths_incremental_old_product_5_to_3star(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_strengths_incremental_new_product_5_to_3_to_5star(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_user_user_strengths_incremental_random(self): <NEW_LINE> <INDENT> pass | Class for testing barbante.maintenance.user_templates when impressions are enabled,
starting from a database with no impressions at all. | 62599099099cdd3c636762f1 |
class Visitor(object): <NEW_LINE> <INDENT> node_method_map = {} <NEW_LINE> visit_childs = True <NEW_LINE> visit_next = True <NEW_LINE> visit_index = 0 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.node_method_map = {} <NEW_LINE> self.visit_childs = True <NEW_LINE> self.visit_next = True <NEW_LINE> self.visit_index = 0 <NEW_LINE> self.update_node_method_map() <NEW_LINE> <DEDENT> def update_node_method_map(self): <NEW_LINE> <INDENT> self_class = self.__class__ <NEW_LINE> self_class_elements = dir(self_class) <NEW_LINE> for self_class_element in self_class_elements: <NEW_LINE> <INDENT> self_class_real_element = getattr(self_class, self_class_element) <NEW_LINE> if not hasattr(self_class_real_element, "ast_node_class"): continue <NEW_LINE> ast_node_class = getattr(self_class_real_element, "ast_node_class") <NEW_LINE> self.node_method_map[ast_node_class] = self_class_real_element <NEW_LINE> <DEDENT> <DEDENT> @colony.dispatch_visit() <NEW_LINE> def visit(self, node): <NEW_LINE> <INDENT> print("unrecognized element node of type " + node.__class__.__name__) <NEW_LINE> <DEDENT> def before_visit(self, node): <NEW_LINE> <INDENT> self.visit_childs = True <NEW_LINE> self.visit_next = True <NEW_LINE> <DEDENT> def after_visit(self, node): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @colony.visit(ast.AstNode) <NEW_LINE> def visit_ast_node(self, node): <NEW_LINE> <INDENT> print("AstNode: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.GenericElement) <NEW_LINE> def visit_generic_element(self, node): <NEW_LINE> <INDENT> print("GenericElement: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.PrintingDocument) <NEW_LINE> def visit_printing_document(self, node): <NEW_LINE> <INDENT> print("PrintingDocument: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.Block) <NEW_LINE> def visit_block(self, node): <NEW_LINE> <INDENT> print("Block: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.Paragraph) <NEW_LINE> def visit_paragraph(self, node): <NEW_LINE> <INDENT> print("Paragraph: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.Line) <NEW_LINE> def visit_line(self, node): <NEW_LINE> <INDENT> print("Line: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.Text) <NEW_LINE> def visit_text(self, node): <NEW_LINE> <INDENT> print("Text: " + str(node)) <NEW_LINE> <DEDENT> @colony.visit(ast.Image) <NEW_LINE> def visit_image(self, node): <NEW_LINE> <INDENT> print("Image: " + str(node)) | The visitor class. | 62599099283ffb24f3cf568d |
class LocationManipulator(object): <NEW_LINE> <INDENT> def __init__(self, v, ratio, brakeDuration, sleep): <NEW_LINE> <INDENT> self.v = v <NEW_LINE> self.ratio = ratio <NEW_LINE> self.sleep = sleep <NEW_LINE> self.brakeDuration = brakeDuration <NEW_LINE> self.centrePoint = 1515 <NEW_LINE> <DEDENT> def move(self, x, y): <NEW_LINE> <INDENT> unitx, unity, sleeptime = Mathinator.createUnitVector(x, y, sleep) <NEW_LINE> dx = unitx * ratio <NEW_LINE> dy = unity * ratio <NEW_LINE> self.moveToLocation(dx, dy, sleeptime) <NEW_LINE> self.cancelMovement(unitx, unity) <NEW_LINE> self.clearOverrride() <NEW_LINE> <DEDENT> def moveToLocation(self, x, y, duration): <NEW_LINE> <INDENT> dx = self.centrePoint - x <NEW_LINE> dy = self.centrePoint - y <NEW_LINE> self.sendCommand(dx, dy, duration) <NEW_LINE> <DEDENT> def cancelMovement(self, x, y): <NEW_LINE> <INDENT> dx = self.centrePoint + x <NEW_LINE> dy = self.centrePoint + y <NEW_LINE> self.sendCommand(dx, dy, self.brakeDuration) <NEW_LINE> <DEDENT> def sendCommand(self, dx, dy, duration): <NEW_LINE> <INDENT> v.channel_override = { "1": dx, "2": dy } <NEW_LINE> v.flush() <NEW_LINE> sleep(duration) <NEW_LINE> <DEDENT> def clearOverrride(self): <NEW_LINE> <INDENT> v.channel_override = { "1": 0, "2": 0 } <NEW_LINE> v.flush() <NEW_LINE> sleep(brakeDuration) | moves the quad and shit | 6259909950812a4eaa621ac0 |
class TestLexer(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass | test: Lexer.get_next_token | 62599099656771135c48af2a |
class TestMyDatFileIO(TestWEFileIO): <NEW_LINE> <INDENT> def test_duplication(self): <NEW_LINE> <INDENT> self._test_duplication(MyDatFileIO, './test/dat/test_file.dat') | Test class for MyFileType class | 625990995fdd1c0f98e5fd69 |
class CheckAgainType(object): <NEW_LINE> <INDENT> CAN_CHI = 1 <NEW_LINE> CAN_PENG = 2 <NEW_LINE> CAN_DIAN_PAO = 3 <NEW_LINE> CAN_DIAN_GANG = 4 <NEW_LINE> @classmethod <NEW_LINE> def to_dict(cls): <NEW_LINE> <INDENT> return { "can_chi": cls.CAN_CHI, "can_peng": cls.CAN_PENG, "can_dian_pao": cls.CAN_DIAN_PAO, "can_dian_gang": cls.CAN_DIAN_GANG } | 某次出牌后,检查其他玩家可进行的操作配置项 | 62599099656771135c48af2b |
class SciUnit(SciUnitNS, DataObject, metaclass=SciUnitClass): <NEW_LINE> <INDENT> class_context = SU_CONTEXT <NEW_LINE> rdf_type_object_deferred = True | Base class for SciUnit `DataObject`s | 62599099283ffb24f3cf5691 |
class Cosine(AngularPotential): <NEW_LINE> <INDENT> pmiproxydefs = dict( cls = 'espressopp.interaction.CosineLocal', pmiproperty = ['K', 'theta0'] ) | The Cosine potential. | 6259909950812a4eaa621ac2 |
class Preference(BaseModel): <NEW_LINE> <INDENT> title = models.CharField(max_length=1024,verbose_name="优惠标题") <NEW_LINE> link = models.CharField(max_length=128,verbose_name="优惠链接",null=True,blank=True) <NEW_LINE> descp = models.TextField(verbose_name="优惠描述",null=True,blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "优惠信息" <NEW_LINE> verbose_name_plural = "优惠信息" <NEW_LINE> ordering = ["-create_time",] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_json(self): <NEW_LINE> <INDENT> serials = serializers.serialize("json", [self]) <NEW_LINE> struct = json.loads(serials) <NEW_LINE> data = struct[0]['fields'] <NEW_LINE> if 'pk' in struct[0]: <NEW_LINE> <INDENT> data['id'] = struct[0]['pk'] <NEW_LINE> <DEDENT> return data | 优惠信息 | 62599099d8ef3951e32c8d58 |
class AirlyAirQuality(AirQualityEntity): <NEW_LINE> <INDENT> def __init__(self, airly, name, unique_id): <NEW_LINE> <INDENT> self.airly = airly <NEW_LINE> self.data = airly.data <NEW_LINE> self._name = name <NEW_LINE> self._unique_id = unique_id <NEW_LINE> self._pm_2_5 = None <NEW_LINE> self._pm_10 = None <NEW_LINE> self._aqi = None <NEW_LINE> self._icon = "mdi:blur" <NEW_LINE> self._attrs = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self._icon <NEW_LINE> <DEDENT> @property <NEW_LINE> @round_state <NEW_LINE> def air_quality_index(self): <NEW_LINE> <INDENT> return self._aqi <NEW_LINE> <DEDENT> @property <NEW_LINE> @round_state <NEW_LINE> def particulate_matter_2_5(self): <NEW_LINE> <INDENT> return self._pm_2_5 <NEW_LINE> <DEDENT> @property <NEW_LINE> @round_state <NEW_LINE> def particulate_matter_10(self): <NEW_LINE> <INDENT> return self._pm_10 <NEW_LINE> <DEDENT> @property <NEW_LINE> def attribution(self): <NEW_LINE> <INDENT> return ATTRIBUTION <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self.data[ATTR_API_CAQI_DESCRIPTION] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self._unique_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return bool(self.data) <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> self._attrs[LABEL_ADVICE] = self.data[ATTR_API_ADVICE] <NEW_LINE> self._attrs[LABEL_AQI_LEVEL] = self.data[ATTR_API_CAQI_LEVEL] <NEW_LINE> self._attrs[LABEL_PM_2_5_LIMIT] = self.data[ATTR_API_PM25_LIMIT] <NEW_LINE> self._attrs[LABEL_PM_2_5_PERCENT] = round(self.data[ATTR_API_PM25_PERCENT]) <NEW_LINE> self._attrs[LABEL_PM_10_LIMIT] = self.data[ATTR_API_PM10_LIMIT] <NEW_LINE> self._attrs[LABEL_PM_10_PERCENT] = round(self.data[ATTR_API_PM10_PERCENT]) <NEW_LINE> return self._attrs <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> await self.airly.async_update() <NEW_LINE> if self.airly.data: <NEW_LINE> <INDENT> self.data = self.airly.data <NEW_LINE> self._pm_10 = self.data[ATTR_API_PM10] <NEW_LINE> self._pm_2_5 = self.data[ATTR_API_PM25] <NEW_LINE> self._aqi = self.data[ATTR_API_CAQI] | Define an Airly air quality. | 62599099c4546d3d9def8197 |
class VarCharField(SQLField): <NEW_LINE> <INDENT> def __init__(self, max_length, silent_truncate=False, **kwargs): <NEW_LINE> <INDENT> super().__init__(py_type=None, **kwargs) <NEW_LINE> self._max_length = max_length <NEW_LINE> self._silent_truncate = silent_truncate <NEW_LINE> <DEDENT> def convert(self, value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> if len(value) > self._max_length: <NEW_LINE> <INDENT> if self._silent_truncate: <NEW_LINE> <INDENT> return value[0:self._max_length] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('''Field '{0}' can not accept strings longer than {1}.''' .format(self.name, self._max_length)) <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> raise TypeError <NEW_LINE> <DEDENT> def sql_type(self): <NEW_LINE> <INDENT> return 'CHARACTER VARYING({0})'.format(self._max_length) | Represents a VARCHAR field in a database, which maps to str in Python.
The field has a maximum length max_length and it is selectable on
initialisation whether values longer than this will be silently truncated,
or will trigger an exception. | 62599099adb09d7d5dc0c354 |
class ConfigError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg: str, path: Optional[Iterable[str]] = None): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> self.path = path | Represents a problem parsing the configuration
Args:
msg: A textual description of the error.
path: Where appropriate, an indication of where in the configuration
the problem lies. | 6259909950812a4eaa621ac4 |
class EventServerThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, address): <NEW_LINE> <INDENT> super(EventServerThread, self).__init__() <NEW_LINE> self.stop_flag = threading.Event() <NEW_LINE> self.address = address <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> listener = EventServer(self.address, EventNotifyHandler) <NEW_LINE> log.debug("Event listener running on %s", listener.server_address) <NEW_LINE> while not self.stop_flag.is_set(): <NEW_LINE> <INDENT> listener.handle_request() | The thread in which the event listener server will run | 625990995fdd1c0f98e5fd71 |
class AspectBaseTest: <NEW_LINE> <INDENT> def test_class(self): <NEW_LINE> <INDENT> assert not isinstance(aspectbase, aspectclass) <NEW_LINE> <DEDENT> def test_init_needs_aspectclass(self): <NEW_LINE> <INDENT> with pytest.raises(AttributeError): <NEW_LINE> <INDENT> aspectbase('py') | aspectbase is just a mixin base class for new aspectclasses
and is therefore only usable works with a derived aspectclass
and therefore doesn't use the aspectclass meta for itself | 62599099099cdd3c636762f8 |
class GcLogger: <NEW_LINE> <INDENT> def __enter__(self) -> 'GcLogger': <NEW_LINE> <INDENT> self.gc_start_time = None <NEW_LINE> self.gc_time = 0.0 <NEW_LINE> self.gc_calls = 0 <NEW_LINE> self.gc_collected = 0 <NEW_LINE> self.gc_uncollectable = 0 <NEW_LINE> gc.callbacks.append(self.gc_callback) <NEW_LINE> self.start_time = time.time() <NEW_LINE> return self <NEW_LINE> <DEDENT> def gc_callback(self, phase: str, info: Mapping[str, int]) -> None: <NEW_LINE> <INDENT> if phase == 'start': <NEW_LINE> <INDENT> assert self.gc_start_time is None, "Start phase out of sequence" <NEW_LINE> self.gc_start_time = time.time() <NEW_LINE> <DEDENT> elif phase == 'stop': <NEW_LINE> <INDENT> assert self.gc_start_time is not None, "Stop phase out of sequence" <NEW_LINE> self.gc_calls += 1 <NEW_LINE> self.gc_time += time.time() - self.gc_start_time <NEW_LINE> self.gc_start_time = None <NEW_LINE> self.gc_collected += info['collected'] <NEW_LINE> self.gc_uncollectable += info['uncollectable'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False, "Unrecognized gc phase (%r)" % (phase,) <NEW_LINE> <DEDENT> <DEDENT> def __exit__(self, *args: object) -> None: <NEW_LINE> <INDENT> while self.gc_callback in gc.callbacks: <NEW_LINE> <INDENT> gc.callbacks.remove(self.gc_callback) <NEW_LINE> <DEDENT> <DEDENT> def get_stats(self) -> Mapping[str, float]: <NEW_LINE> <INDENT> end_time = time.time() <NEW_LINE> result = {} <NEW_LINE> result['gc_time'] = self.gc_time <NEW_LINE> result['gc_calls'] = self.gc_calls <NEW_LINE> result['gc_collected'] = self.gc_collected <NEW_LINE> result['gc_uncollectable'] = self.gc_uncollectable <NEW_LINE> result['build_time'] = end_time - self.start_time <NEW_LINE> return result | Context manager to log GC stats and overall time. | 6259909a5fdd1c0f98e5fd73 |
@db_test_lib.DualDBTest <NEW_LINE> class GetMBRFlowTest(flow_test_lib.FlowTestsBaseclass): <NEW_LINE> <INDENT> mbr = (b"123456789" * 1000)[:4096] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(GetMBRFlowTest, self).setUp() <NEW_LINE> self.client_id = self.SetupClient(0) <NEW_LINE> <DEDENT> def testGetMBR(self): <NEW_LINE> <INDENT> flow_id = flow_test_lib.TestFlowHelper( transfer.GetMBR.__name__, ClientMock(self.mbr), token=self.token, client_id=self.client_id) <NEW_LINE> results = flow_test_lib.GetFlowResults(self.client_id, flow_id) <NEW_LINE> self.assertLen(results, 1) <NEW_LINE> self.assertEqual(results[0], self.mbr) <NEW_LINE> if data_store.AFF4Enabled(): <NEW_LINE> <INDENT> fd = aff4.FACTORY.Open(self.client_id.Add("mbr"), token=self.token) <NEW_LINE> self.assertEqual(fd.Read(4096), self.mbr) <NEW_LINE> <DEDENT> <DEDENT> def _RunAndCheck(self, chunk_size, download_length): <NEW_LINE> <INDENT> with utils.Stubber(constants, "CLIENT_MAX_BUFFER_SIZE", chunk_size): <NEW_LINE> <INDENT> flow_id = flow_test_lib.TestFlowHelper( transfer.GetMBR.__name__, ClientMock(self.mbr), token=self.token, client_id=self.client_id, length=download_length) <NEW_LINE> <DEDENT> results = flow_test_lib.GetFlowResults(self.client_id, flow_id) <NEW_LINE> self.assertLen(results, 1) <NEW_LINE> self.assertEqual(results[0], self.mbr[:download_length]) <NEW_LINE> <DEDENT> def testGetMBRChunked(self): <NEW_LINE> <INDENT> chunk_size = 100 <NEW_LINE> download_length = 15 * chunk_size <NEW_LINE> self._RunAndCheck(chunk_size, download_length) <NEW_LINE> download_length = 15 * chunk_size + chunk_size // 2 <NEW_LINE> self._RunAndCheck(chunk_size, download_length) | Test the transfer mechanism. | 6259909a3617ad0b5ee07f52 |
class File(FileStr): <NEW_LINE> <INDENT> def __init__(self, fpath, comment_char="//"): <NEW_LINE> <INDENT> super(File, self).__init__(comment_char) <NEW_LINE> self._fpath = Path(fpath).resolve() <NEW_LINE> <DEDENT> @property <NEW_LINE> def fpath(self): <NEW_LINE> <INDENT> return self._fpath <NEW_LINE> <DEDENT> def pre_to_str(self): <NEW_LINE> <INDENT> today = date.today() <NEW_LINE> rstr = f"{self._comment_char}{'='*(80-len(self._comment_char))}\n" <NEW_LINE> rstr += f"{self._comment_char} User: {getpass.getuser()}\n" <NEW_LINE> rstr += f"{self._comment_char} Date: {today.strftime('%m/%d/%y')}\n" <NEW_LINE> rstr += f"{self._comment_char} Path: {self._fpath}\n" <NEW_LINE> rstr += f"{self._comment_char}{'='*(80-len(self._comment_char))}\n" <NEW_LINE> return rstr <NEW_LINE> <DEDENT> def generate(self, overwrite=False): <NEW_LINE> <INDENT> if self._fpath.exists() and not overwrite: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with open(self._fpath, "w") as fp: <NEW_LINE> <INDENT> fp.write(self.to_str()) <NEW_LINE> <DEDENT> return True | Top level file str | 6259909a091ae35668706a32 |
class RecipeForm(Form): <NEW_LINE> <INDENT> title = StringField(u'Title', validators=[validators.Length(min=1, max=200)]) <NEW_LINE> category = SelectField(u'Category', coerce=str) <NEW_LINE> ingredients = StringField(u'Ingredients', validators=[validators.Length(min=1, max=200)]) <NEW_LINE> steps = TextAreaField(u'Steps', validators=[validators.Length(min=30)]) <NEW_LINE> status = BooleanField(u'Private') | Recipe form for adding and editing recipes | 6259909ac4546d3d9def819c |
class Box(BodyPart): <NEW_LINE> <INDENT> MASS = 1.0 <NEW_LINE> X = 1.0 <NEW_LINE> Y = 1.0 <NEW_LINE> Z = 1.0 <NEW_LINE> def __init__(self, id, conf, **kwargs): <NEW_LINE> <INDENT> self.x, self.y, self.z = self.X, self.Y, self.Z <NEW_LINE> self.mass = self.MASS <NEW_LINE> super(Box, self).__init__(id, conf, **kwargs) <NEW_LINE> <DEDENT> def _initialize(self, **kwargs): <NEW_LINE> <INDENT> self.component = self.create_component(BoxGeom(self.x, self.y, self.z, self.mass), "box") <NEW_LINE> <DEDENT> def get_slot(self, slot): <NEW_LINE> <INDENT> self.check_slot(slot) <NEW_LINE> return self.component <NEW_LINE> <DEDENT> def get_slot_position(self, slot): <NEW_LINE> <INDENT> self.check_slot(slot) <NEW_LINE> xmax, ymax, zmax = self.x / 2.0, self.y / 2.0, self.z / 2.0 <NEW_LINE> if slot == 0: <NEW_LINE> <INDENT> return Vector3(0, -ymax, 0) <NEW_LINE> <DEDENT> elif slot == 1: <NEW_LINE> <INDENT> return Vector3(0, ymax, 0) <NEW_LINE> <DEDENT> elif slot == 2: <NEW_LINE> <INDENT> return Vector3(0, 0, zmax) <NEW_LINE> <DEDENT> elif slot == 3: <NEW_LINE> <INDENT> return Vector3(0, 0, -zmax) <NEW_LINE> <DEDENT> elif slot == 4: <NEW_LINE> <INDENT> return Vector3(xmax, 0, 0) <NEW_LINE> <DEDENT> return Vector3(-xmax, 0, 0) <NEW_LINE> <DEDENT> def get_slot_normal(self, slot): <NEW_LINE> <INDENT> return self.get_slot_position(slot).normalized() <NEW_LINE> <DEDENT> def get_slot_tangent(self, slot): <NEW_LINE> <INDENT> self.check_slot(slot) <NEW_LINE> if slot == 0: <NEW_LINE> <INDENT> return Vector3(0, 0, 1) <NEW_LINE> <DEDENT> elif slot == 1: <NEW_LINE> <INDENT> return Vector3(0, 0, 1) <NEW_LINE> <DEDENT> elif slot == 2: <NEW_LINE> <INDENT> return Vector3(1, 0, 0) <NEW_LINE> <DEDENT> elif slot == 3: <NEW_LINE> <INDENT> return Vector3(1, 0, 0) <NEW_LINE> <DEDENT> elif slot == 4: <NEW_LINE> <INDENT> return Vector3(0, 1, 0) <NEW_LINE> <DEDENT> return Vector3(0, 1, 0) | A base class that allows to you quickly define a body part
that is just a simple box. | 6259909a656771135c48af32 |
class BIOBERT_DISEASE_BC5CDR(ColumnCorpus): <NEW_LINE> <INDENT> def __init__(self, base_path: Union[str, Path] = None, in_memory: bool = True): <NEW_LINE> <INDENT> columns = {0: "text", 1: "ner"} <NEW_LINE> dataset_name = self.__class__.__name__.lower() <NEW_LINE> if base_path is None: <NEW_LINE> <INDENT> base_path = flair.cache_root / "datasets" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base_path = Path(base_path) <NEW_LINE> <DEDENT> data_folder = base_path / dataset_name <NEW_LINE> train_file = data_folder / "train.conll" <NEW_LINE> dev_file = data_folder / "dev.conll" <NEW_LINE> test_file = data_folder / "test.conll" <NEW_LINE> if not (train_file.exists() and dev_file.exists() and test_file.exists()): <NEW_LINE> <INDENT> common_path = base_path / "biobert_common" <NEW_LINE> if not (common_path / "BC5CDR-disease").exists(): <NEW_LINE> <INDENT> BioBertHelper.download_corpora(common_path) <NEW_LINE> <DEDENT> BioBertHelper.convert_and_write(common_path / "BC5CDR-disease", data_folder, tag_type=DISEASE_TAG) <NEW_LINE> <DEDENT> super(BIOBERT_DISEASE_BC5CDR, self).__init__(data_folder, columns, tag_to_bioes="ner", in_memory=in_memory) | BC5CDR corpus with disease annotations as used in the evaluation
of BioBERT.
For further details regarding BioBERT and it's evaluation, see Lee et al.:
https://academic.oup.com/bioinformatics/article/36/4/1234/5566506
https://github.com/dmis-lab/biobert | 6259909adc8b845886d553bb |
class Function(object): <NEW_LINE> <INDENT> def __init__(self, function, msg=None, message=None): <NEW_LINE> <INDENT> self.function = function <NEW_LINE> if msg is not None and message is not None: <NEW_LINE> <INDENT> raise ValueError('Only one of msg and message can be passed') <NEW_LINE> <DEDENT> if msg is None and message is None: <NEW_LINE> <INDENT> msg = _('Invalid value') <NEW_LINE> <DEDENT> elif message is not None: <NEW_LINE> <INDENT> warnings.warn( 'The "message" argument has been deprecated, use "msg" ' 'instead.', DeprecationWarning ) <NEW_LINE> msg = message <NEW_LINE> <DEDENT> self.msg = msg <NEW_LINE> <DEDENT> def __call__(self, node, value): <NEW_LINE> <INDENT> result = self.function(value) <NEW_LINE> if not result: <NEW_LINE> <INDENT> raise Invalid( node, translationstring.TranslationString( self.msg, mapping={'val':value})) <NEW_LINE> <DEDENT> if isinstance(result, string_types): <NEW_LINE> <INDENT> raise Invalid( node, translationstring.TranslationString( result, mapping={'val':value})) | Validator which accepts a function and an optional message;
the function is called with the ``value`` during validation.
If the function returns anything falsy (``None``, ``False``, the
empty string, ``0``, an object with a ``__nonzero__`` that returns
``False``, etc) when called during validation, an
:exc:`colander.Invalid` exception is raised (validation fails);
its msg will be the value of the ``msg`` argument passed to this
class' constructor.
If the function returns a stringlike object (a ``str`` or
``unicode`` object) that is *not* the empty string , a
:exc:`colander.Invalid` exception is raised using the stringlike
value returned from the function as the exeption message
(validation fails).
If the function returns anything *except* a stringlike object
object which is truthy (e.g. ``True``, the integer ``1``, an
object with a ``__nonzero__`` that returns ``True``, etc), an
:exc:`colander.Invalid` exception is *not* raised (validation
succeeds).
The default value for the ``msg`` when not provided via the
constructor is ``Invalid value``. | 6259909a3617ad0b5ee07f58 |
class TextLine(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'text_lines' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> line = db.Column(db.String(250)) <NEW_LINE> line_no = db.Column(db.Integer) <NEW_LINE> text_to_compare_id = db.Column(db.Integer, db.ForeignKey('texts.id')) <NEW_LINE> text_to_compare = db.relationship(ComparisonTexts, foreign_keys=[text_to_compare_id]) <NEW_LINE> def as_dict(self): <NEW_LINE> <INDENT> return {c.name: getattr(self, c.name) for c in self.__table__.columns} | Lines that are compared. These belong to a text to compare.
| 6259909adc8b845886d553bd |
class ArmHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def __init__(self, application, *args, **kwargs): <NEW_LINE> <INDENT> self.client = application.client <NEW_LINE> super(ArmHandler, self).__init__(application, *args, **kwargs) <NEW_LINE> <DEDENT> def post(self, *args, **kwargs): <NEW_LINE> <INDENT> self.client.publish(REDIS_ARM_CHANNEL, json.dumps([ self.get_argument('part'), self.get_argument('action'), ])) | Arm handler | 6259909a091ae35668706a38 |
class FastWeightsStateTuple(_FastWeightsStateTuple): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> (c, a) = self <NEW_LINE> if c.dtype != a.dtype: <NEW_LINE> <INDENT> raise TypeError("Inconsistent internal state: {} vs {}".format( (str(c.dtype), str(a.dtype)))) <NEW_LINE> <DEDENT> return c.dtype | Tuple used by FastWeights Cells for `state_size`, `zero_state`, and output state.
Stores two elements: `(c, A)`, in that order. Where `c` is the hidden state
and `A` is the fast weights state. | 6259909a656771135c48af34 |
class MediaBaseResource(MediaResource): <NEW_LINE> <INDENT> title = CharField(_('title'), required=True) <NEW_LINE> description = CharField(_('description_old')) <NEW_LINE> descriptions = TextField(_('description')) <NEW_LINE> code = CharField(_('code'), unique=True, required=True) <NEW_LINE> public_access = CharField(_('public access'), choices=PUBLIC_ACCESS_CHOICES, max_length=16, default="metadata") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.code <NEW_LINE> <DEDENT> @property <NEW_LINE> def public_id(self): <NEW_LINE> <INDENT> return self.code <NEW_LINE> <DEDENT> def save(self, force_insert=False, force_update=False, user=None, code=None): <NEW_LINE> <INDENT> super(MediaBaseResource, self).save(force_insert, force_update) <NEW_LINE> <DEDENT> def get_fields(self): <NEW_LINE> <INDENT> return self._meta.fields <NEW_LINE> <DEDENT> class Meta(MetaCore): <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['code'] | Describe a media base resource | 6259909aadb09d7d5dc0c364 |
class Tooth_30_pt(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.tooth_30_pt" <NEW_LINE> bl_label = "Tooth 30" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> found = 'Tooth 30' in bpy.data.objects <NEW_LINE> if found == False: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if found == True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> CriaPontoDef('Tooth 30', 'Anatomical Points - Teeth') <NEW_LINE> TestaPontoCollDef() <NEW_LINE> return {'FINISHED'} | Tooltip | 6259909adc8b845886d553c1 |
class LdapBooleanAttribute(LdapAttribute): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def parse(value): <NEW_LINE> <INDENT> return value.lower() == b'true' | A boolean LDAP attribute | 6259909a283ffb24f3cf56a5 |
class StandardPermutations_n_abstract(Permutations): <NEW_LINE> <INDENT> def __init__(self, n, category=None): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> if category is None: <NEW_LINE> <INDENT> category = FiniteEnumeratedSets() <NEW_LINE> <DEDENT> Permutations.__init__(self, category=category) <NEW_LINE> <DEDENT> def _element_constructor_(self, x, check_input=True): <NEW_LINE> <INDENT> if len(x) < self.n: <NEW_LINE> <INDENT> x = list(x) + list(range(len(x) + 1, self.n + 1)) <NEW_LINE> <DEDENT> return self.element_class(self, x, check_input=check_input) <NEW_LINE> <DEDENT> def __contains__(self, x): <NEW_LINE> <INDENT> return Permutations.__contains__(self, x) and len(x) == self.n | Abstract base class for subsets of permutations of the
set `\{1, 2, \ldots, n\}`.
.. WARNING::
Anything inheriting from this class should override the
``__contains__`` method. | 6259909a656771135c48af36 |
class EntityMeta(type): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def __prepare__(cls, name, bases): <NEW_LINE> <INDENT> return collections.OrderedDict() <NEW_LINE> <DEDENT> def __init__(cls, name, bases, attr_dict): <NEW_LINE> <INDENT> super().__init__(name, bases, attr_dict) <NEW_LINE> cls._field_names = [] <NEW_LINE> for key, attr in attr_dict.items(): <NEW_LINE> <INDENT> if isinstance(attr, Validated): <NEW_LINE> <INDENT> attr.storage_name = f'_{type(attr).__name__}#{key}' <NEW_LINE> cls._field_names.append(key) | Metaclass for business entities with validated fields | 6259909a283ffb24f3cf56a9 |
class GameScreen(Screen): <NEW_LINE> <INDENT> switch_screen = ObjectProperty() <NEW_LINE> disabled = BooleanProperty(False) <NEW_LINE> @property <NEW_LINE> def app(self): <NEW_LINE> <INDENT> return App.get_running_app() <NEW_LINE> <DEDENT> @property <NEW_LINE> def engine(self): <NEW_LINE> <INDENT> return App.get_running_app().engine <NEW_LINE> <DEDENT> def disable_input(self, cb=None): <NEW_LINE> <INDENT> self.disabled = True <NEW_LINE> if cb: <NEW_LINE> <INDENT> cb() <NEW_LINE> <DEDENT> <DEDENT> def enable_input(self, cb=None): <NEW_LINE> <INDENT> if cb: <NEW_LINE> <INDENT> cb() <NEW_LINE> <DEDENT> self.disabled = False <NEW_LINE> <DEDENT> def wait_travel(self, character, thing, dest, cb=None): <NEW_LINE> <INDENT> self.disable_input() <NEW_LINE> self.app.wait_travel(character, thing, dest, cb=partial(self.enable_input, cb)) <NEW_LINE> <DEDENT> def wait_turns(self, turns, cb=None): <NEW_LINE> <INDENT> self.disable_input() <NEW_LINE> self.app.wait_turns(turns, cb=partial(self.enable_input, cb)) <NEW_LINE> <DEDENT> def wait_command(self, start_func, turns=1, end_func=None): <NEW_LINE> <INDENT> self.disable_input() <NEW_LINE> start_func() <NEW_LINE> self.app.wait_turns(turns, cb=partial(self.enable_input, end_func)) <NEW_LINE> <DEDENT> def wait_travel_command(self, character, thing, dest, start_func, turns=1, end_func=lambda: None): <NEW_LINE> <INDENT> self.disable_input() <NEW_LINE> self.app.wait_travel_command(character, thing, dest, start_func, turns, partial(self.enable_input, end_func)) | A version of :class:`kivy.uix.screenmanager.Screen` that is easier to set up and use with ELiDE
Should be a child of the :class:`ELiDE.game.Screens` widget, which will never itself be displayed.
``GameScreen`` instances in it will be added to the screen manager, so that you can switch
to them with the ``switch_screen`` method.
Every ``GameScreen`` needs a ``name``, just like regular ``Screen``. | 6259909a099cdd3c63676301 |
class GetTicketInputSet(InputSet): <NEW_LINE> <INDENT> def set_Email(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Email', value) <NEW_LINE> <DEDENT> def set_ID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ID', value) <NEW_LINE> <DEDENT> def set_Password(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Password', value) <NEW_LINE> <DEDENT> def set_Server(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Server', value) | An InputSet with methods appropriate for specifying the inputs to the GetTicket
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 6259909a656771135c48af39 |
class ServiceProxy (object): <NEW_LINE> <INDENT> def __init__(self, url): <NEW_LINE> <INDENT> if not (url.startswith('http://') or url.startswith('https://')): <NEW_LINE> <INDENT> url = 'http://' + url <NEW_LINE> <DEDENT> self.url = url <NEW_LINE> <DEDENT> def _compose(self, endpoint): <NEW_LINE> <INDENT> return '/'.join([self.url, endpoint]) <NEW_LINE> <DEDENT> def get(self, endpoint, **params): <NEW_LINE> <INDENT> params = params and params or None <NEW_LINE> return requests.get(self._compose(endpoint), params) <NEW_LINE> <DEDENT> def post(self, endpoint, **params): <NEW_LINE> <INDENT> params = params and params or None <NEW_LINE> return requests.post(self._compose(endpoint), data=params) <NEW_LINE> <DEDENT> def put(self, endpoint, **params): <NEW_LINE> <INDENT> params = params and params or None <NEW_LINE> return requests.put(self._compose(endpoint), data=params) <NEW_LINE> <DEDENT> def delete(self, endpoint, **params): <NEW_LINE> <INDENT> params = params and params or None <NEW_LINE> return requests.delete(self._compose(endpoint), params=params) | Helper class for interacting with an external service. | 6259909aadb09d7d5dc0c36c |
class RendererOfNumericalExperiment(RendererBase): <NEW_LINE> <INDENT> @property <NEW_LINE> def view_type(self): <NEW_LINE> <INDENT> return 'numericalExperiment' <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return u'TODO - render {0}'.format(self.view_type) | Manages rendering of a view over a cim numerical experiment. | 6259909aadb09d7d5dc0c36e |
class KeventDescriptorSet: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._descriptors = set() <NEW_LINE> self._descriptor_for_path = dict() <NEW_LINE> self._descriptor_for_fd = dict() <NEW_LINE> self._kevents = list() <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> <DEDENT> @property <NEW_LINE> def kevents(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> return self._kevents <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def paths(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> return list(self._descriptor_for_path.keys()) <NEW_LINE> <DEDENT> <DEDENT> def get_for_fd(self, fd): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> return self._descriptor_for_fd[fd] <NEW_LINE> <DEDENT> <DEDENT> def get(self, path): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> path = absolute_path(path) <NEW_LINE> return self._get(path) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, path): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> path = absolute_path(path) <NEW_LINE> return self._has_path(path) <NEW_LINE> <DEDENT> <DEDENT> def add(self, path, is_directory): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> path = absolute_path(path) <NEW_LINE> if not self._has_path(path): <NEW_LINE> <INDENT> self._add_descriptor(KeventDescriptor(path, is_directory)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def remove(self, path): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> path = absolute_path(path) <NEW_LINE> if self._has_path(path): <NEW_LINE> <INDENT> self._remove_descriptor(self._get(path)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> for descriptor in self._descriptors: <NEW_LINE> <INDENT> descriptor.close() <NEW_LINE> <DEDENT> self._descriptors.clear() <NEW_LINE> self._descriptor_for_fd.clear() <NEW_LINE> self._descriptor_for_path.clear() <NEW_LINE> self._kevents = [] <NEW_LINE> <DEDENT> <DEDENT> def _get(self, path): <NEW_LINE> <INDENT> return self._descriptor_for_path[path] <NEW_LINE> <DEDENT> def _has_path(self, path): <NEW_LINE> <INDENT> return path in self._descriptor_for_path <NEW_LINE> <DEDENT> def _add_descriptor(self, descriptor): <NEW_LINE> <INDENT> self._descriptors.add(descriptor) <NEW_LINE> self._kevents.append(descriptor.kevent) <NEW_LINE> self._descriptor_for_path[descriptor.path] = descriptor <NEW_LINE> self._descriptor_for_fd[descriptor.fd] = descriptor <NEW_LINE> <DEDENT> def _remove_descriptor(self, descriptor): <NEW_LINE> <INDENT> self._descriptors.remove(descriptor) <NEW_LINE> del self._descriptor_for_fd[descriptor.fd] <NEW_LINE> del self._descriptor_for_path[descriptor.path] <NEW_LINE> self._kevents.remove(descriptor.kevent) <NEW_LINE> descriptor.close() | Thread-safe kevent descriptor collection. | 6259909a099cdd3c63676304 |
class Task(BaseModel): <NEW_LINE> <INDENT> OPEN = 'O' <NEW_LINE> IN_PROGRESS = 'I' <NEW_LINE> COMPLETE = 'C' <NEW_LINE> STATUS_CHOICES = ( (OPEN, 'Open'), (IN_PROGRESS, 'In Progress'), (COMPLETE, 'Complete') ) <NEW_LINE> status = models.CharField( max_length=2, choices = STATUS_CHOICES, default=OPEN ) <NEW_LINE> title = models.CharField(max_length=128) <NEW_LINE> description = models.TextField(max_length=2000) <NEW_LINE> offer = models.IntegerField() <NEW_LINE> location = models.CharField(max_length=128) <NEW_LINE> is_remote = models.BooleanField(default=False) <NEW_LINE> owner = models.ForeignKey('jobs.Profile',related_name="poster") <NEW_LINE> helper = models.ForeignKey('jobs.Profile',related_name="helper",blank=True,null=True) <NEW_LINE> question1 = models.CharField(max_length=300,blank=True) <NEW_LINE> question2 = models.CharField(max_length=300,blank=True) <NEW_LINE> question3 = models.CharField(max_length=300,blank=True) <NEW_LINE> skills = models.ManyToManyField('jobs.Skill') <NEW_LINE> display_rank = models.IntegerField(blank=True,null=True) <NEW_LINE> date_due = models.DateField(blank=True,null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title | Model for a Task | 6259909a5fdd1c0f98e5fd89 |
class EmrClusterException(Exception): <NEW_LINE> <INDENT> pass | Exception for unsuccessful step submission to EMR cluster. | 6259909a099cdd3c63676305 |
class HtmlTidy(Linter): <NEW_LINE> <INDENT> syntax = ('html', 'html 5') <NEW_LINE> cmd = 'tidy -errors -quiet -utf8' <NEW_LINE> regex = r'^line (?P<line>\d+) column (?P<col>\d+) - (?:(?P<error>Error)|(?P<warning>Warning)): (?P<message>.+)' <NEW_LINE> line_col_base = (1, 1) <NEW_LINE> error_stream = util.STREAM_STDERR | Provides an interface to tidy. | 6259909adc8b845886d553d0 |
class Exponential(gamma.Gamma): <NEW_LINE> <INDENT> def __init__(self, lam, validate_args=False, allow_nan_stats=True, name="Exponential"): <NEW_LINE> <INDENT> parameters = locals() <NEW_LINE> parameters.pop("self") <NEW_LINE> with ops.name_scope(name, values=[lam]) as ns: <NEW_LINE> <INDENT> self._lam = ops.convert_to_tensor(lam, name="lam") <NEW_LINE> <DEDENT> super(Exponential, self).__init__( alpha=array_ops.ones((), dtype=self._lam.dtype), beta=self._lam, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=ns) <NEW_LINE> self._is_reparameterized = True <NEW_LINE> self._parameters = parameters <NEW_LINE> self._graph_parents += [self._lam] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _param_shapes(sample_shape): <NEW_LINE> <INDENT> return {"lam": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)} <NEW_LINE> <DEDENT> @property <NEW_LINE> def lam(self): <NEW_LINE> <INDENT> return self._lam <NEW_LINE> <DEDENT> def _sample_n(self, n, seed=None): <NEW_LINE> <INDENT> shape = array_ops.concat_v2(([n], array_ops.shape(self._lam)), 0) <NEW_LINE> sampled = random_ops.random_uniform( shape, minval=np.nextafter(self.dtype.as_numpy_dtype(0.), self.dtype.as_numpy_dtype(1.)), maxval=array_ops.ones((), dtype=self.dtype), seed=seed, dtype=self.dtype) <NEW_LINE> return -math_ops.log(sampled) / self._lam | The Exponential distribution with rate parameter lam.
The PDF of this distribution is:
```prob(x) = (lam * e^(-lam * x)), x > 0```
Note that the Exponential distribution is a special case of the Gamma
distribution, with Exponential(lam) = Gamma(1, lam). | 6259909a099cdd3c63676307 |
class EventResultOrError: <NEW_LINE> <INDENT> def __init__(self, loop): <NEW_LINE> <INDENT> self._loop = loop <NEW_LINE> self._exc = None <NEW_LINE> self._event = asyncio.Event(loop=loop) <NEW_LINE> self._waiters = collections.deque() <NEW_LINE> <DEDENT> def set(self, exc=None): <NEW_LINE> <INDENT> self._exc = exc <NEW_LINE> self._event.set() <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def wait(self): <NEW_LINE> <INDENT> fut = ensure_future(self._event.wait(), loop=self._loop) <NEW_LINE> self._waiters.append(fut) <NEW_LINE> try: <NEW_LINE> <INDENT> val = yield from fut <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._waiters.remove(fut) <NEW_LINE> <DEDENT> if self._exc is not None: <NEW_LINE> <INDENT> raise self._exc <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> def cancel(self): <NEW_LINE> <INDENT> for fut in self._waiters: <NEW_LINE> <INDENT> if not fut.done(): <NEW_LINE> <INDENT> fut.cancel() | This class wrappers the Event asyncio lock allowing either awake the
locked Tasks without any error or raising an exception.
thanks to @vorpalsmith for the simple design. | 6259909a3617ad0b5ee07f6f |
class CTRL(IPACommon): <NEW_LINE> <INDENT> def ctrl_SET(self, data, op_id, v): <NEW_LINE> <INDENT> self.dbg('CTRL SET [%s] %s' % (op_id, v)) <NEW_LINE> <DEDENT> def ctrl_SET_REPLY(self, data, op_id, v): <NEW_LINE> <INDENT> self.dbg('CTRL SET REPLY [%s] %s' % (op_id, v)) <NEW_LINE> <DEDENT> def ctrl_GET(self, data, op_id, v): <NEW_LINE> <INDENT> self.dbg('CTRL GET [%s] %s' % (op_id, v)) <NEW_LINE> <DEDENT> def ctrl_GET_REPLY(self, data, op_id, v): <NEW_LINE> <INDENT> self.dbg('CTRL GET REPLY [%s] %s' % (op_id, v)) <NEW_LINE> <DEDENT> def ctrl_TRAP(self, data, op_id, v): <NEW_LINE> <INDENT> self.dbg('CTRL TRAP [%s] %s' % (op_id, v)) <NEW_LINE> <DEDENT> def ctrl_ERROR(self, data, op_id, v): <NEW_LINE> <INDENT> self.dbg('CTRL ERROR [%s] %s' % (op_id, v)) <NEW_LINE> <DEDENT> def osmo_CTRL(self, data): <NEW_LINE> <INDENT> self.dbg('OSMO CTRL received %s::%s' % Ctrl().parse(data.decode('utf-8'))) <NEW_LINE> (cmd, op_id, v) = data.decode('utf-8').split(' ', 2) <NEW_LINE> method = getattr(self, 'ctrl_' + cmd, lambda: "CTRL unknown command") <NEW_LINE> method(data, op_id, v) | Implementation of Osmocom control protocol for IPA multiplex | 6259909a091ae35668706a4e |
class LiveGraph(): <NEW_LINE> <INDENT> def __init__(self, fields, title='MAVProxy: LiveGraph', timespan=20.0, tickresolution=0.2, colors=[ 'red', 'green', 'blue', 'orange', 'olive', 'yellow', 'grey', 'black']): <NEW_LINE> <INDENT> import multiprocessing <NEW_LINE> self.fields = fields <NEW_LINE> self.colors = colors <NEW_LINE> self.title = title <NEW_LINE> self.timespan = timespan <NEW_LINE> self.tickresolution = tickresolution <NEW_LINE> self.values = [None]*len(self.fields) <NEW_LINE> self.parent_pipe,self.child_pipe = multiprocessing.Pipe() <NEW_LINE> self.close_graph = multiprocessing.Event() <NEW_LINE> self.close_graph.clear() <NEW_LINE> self.child = multiprocessing.Process(target=self.child_task) <NEW_LINE> self.child.start() <NEW_LINE> <DEDENT> def child_task(self): <NEW_LINE> <INDENT> mp_util.child_close_fds() <NEW_LINE> import wx, matplotlib <NEW_LINE> matplotlib.use('WXAgg') <NEW_LINE> app = wx.PySimpleApp() <NEW_LINE> app.frame = GraphFrame(state=self) <NEW_LINE> app.frame.Show() <NEW_LINE> app.MainLoop() <NEW_LINE> <DEDENT> def add_values(self, values): <NEW_LINE> <INDENT> if self.child.is_alive(): <NEW_LINE> <INDENT> self.parent_pipe.send(values) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.close_graph.set() <NEW_LINE> if self.is_alive(): <NEW_LINE> <INDENT> self.child.join(2) <NEW_LINE> <DEDENT> <DEDENT> def is_alive(self): <NEW_LINE> <INDENT> return self.child.is_alive() | a live graph object using wx and matplotlib
All of the GUI work is done in a child process to provide some insulation
from the parent mavproxy instance and prevent instability in the GCS
New data is sent to the LiveGraph instance via a pipe | 6259909adc8b845886d553d4 |
class Unauthorized(HomeAssistantError): <NEW_LINE> <INDENT> def __init__( self, context: Optional["Context"] = None, user_id: Optional[str] = None, entity_id: Optional[str] = None, config_entry_id: Optional[str] = None, perm_category: Optional[str] = None, permission: Optional[Tuple[str]] = None, ) -> None: <NEW_LINE> <INDENT> super().__init__(self.__class__.__name__) <NEW_LINE> self.context = context <NEW_LINE> self.user_id = user_id <NEW_LINE> self.entity_id = entity_id <NEW_LINE> self.config_entry_id = config_entry_id <NEW_LINE> self.perm_category = perm_category <NEW_LINE> self.permission = permission | When an action is unauthorized. | 6259909b656771135c48af42 |
class TestFunctionTestWebPageContent(InvenioTestCase): <NEW_LINE> <INDENT> def test_twpc_username_arg(self): <NEW_LINE> <INDENT> self.assertEqual([], test_web_page_content(CFG_SITE_URL, username="admin", expected_text="</html>")) <NEW_LINE> errmsgs = test_web_page_content(CFG_SITE_URL, username="admin", password="foo", expected_text="</html>") <NEW_LINE> if errmsgs[0].find("ERROR: Cannot login as admin.") > -1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fail("Should not be able to login as admin with foo password.") <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def test_twpc_expected_text_arg(self): <NEW_LINE> <INDENT> self.assertEqual([], test_web_page_content(CFG_SITE_URL + "/search?p=ellis", expected_text="</html>")) <NEW_LINE> errmsgs = test_web_page_content(CFG_SITE_URL + "/search?p=ellis&of=xm") <NEW_LINE> if errmsgs[0].find(" does not contain </html>") > -1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fail("Should not find </html> in an XML page.") <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def test_twpc_expected_link_arg(self): <NEW_LINE> <INDENT> self.assertEqual([], test_web_page_content(CFG_SITE_URL, expected_link_target=CFG_BASE_URL + "/collection/ALEPH?ln=" + CFG_SITE_LANG)) <NEW_LINE> self.assertEqual([], test_web_page_content(CFG_SITE_URL, expected_link_label="ISOLDE")) <NEW_LINE> self.assertEqual([], test_web_page_content(CFG_SITE_URL, expected_link_target=CFG_BASE_URL + "/collection/ISOLDE?ln=" + CFG_SITE_LANG, expected_link_label="ISOLDE")) <NEW_LINE> errmsgs = test_web_page_content(CFG_SITE_URL, expected_link_target=CFG_BASE_URL + "/collection/ALEPH?ln=" + CFG_SITE_LANG, expected_link_label="ISOLDE") <NEW_LINE> if errmsgs[0].find(" does not contain link to ") > -1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fail("Should not find link to ALEPH entitled ISOLDE.") <NEW_LINE> <DEDENT> return | Check browser test_web_page_content() function. | 6259909bd8ef3951e32c8d6f |
class BaseService(object, Root): <NEW_LINE> <INDENT> services = {} <NEW_LINE> name = None <NEW_LINE> description = None <NEW_LINE> cmdline = None <NEW_LINE> def __init__(self, *a, **kw): <NEW_LINE> <INDENT> super(BaseService, self).__init__() <NEW_LINE> self.factory = None <NEW_LINE> self.listener = None <NEW_LINE> for name, service_class in self.services.items(): <NEW_LINE> <INDENT> service = service_class(*a, **kw) <NEW_LINE> setattr(self, name, service) <NEW_LINE> setattr(self, 'remote_get_%s' % name, partial(self._get_service, name)) <NEW_LINE> <DEDENT> <DEDENT> def _get_service(self, name): <NEW_LINE> <INDENT> return getattr(self, name) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def start(self): <NEW_LINE> <INDENT> self.factory = PBServerFactory(self) <NEW_LINE> self.listener = yield server_listen(self.factory, self.name, self.cmdline, self.description) <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> self.listener.stopListening() | Base PB service.
Inherit from this class and define name, description and cmdline.
If 'start' is called, 'shutdown' should be called when done. | 6259909b091ae35668706a5a |
class TestGetInstance(testtools.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestGetInstance, self).setUp() <NEW_LINE> self.pvc_id = 123456789 <NEW_LINE> self.pvcdrv_init_copy = PowerVCDriver.__init__ <NEW_LINE> <DEDENT> def test_get_instance_found(self): <NEW_LINE> <INDENT> pvc_svc = mock.MagicMock() <NEW_LINE> pvc_svc.get_instance = mock.MagicMock(return_value="an instance") <NEW_LINE> def pvc_drv_init_instance_found(self): <NEW_LINE> <INDENT> self._service = pvc_svc <NEW_LINE> <DEDENT> PowerVCDriver.__init__ = pvc_drv_init_instance_found <NEW_LINE> pvc_drv = PowerVCDriver() <NEW_LINE> self.assertIsNotNone(pvc_drv.get_instance(self.pvc_id)) <NEW_LINE> <DEDENT> def test_get_instance_not_found(self): <NEW_LINE> <INDENT> pvc_svc = mock.MagicMock() <NEW_LINE> pvc_svc.get_instance = mock.MagicMock(side_effect=exceptions.NotFound(0)) <NEW_LINE> def pvc_drv_init_instance_not_found(self): <NEW_LINE> <INDENT> self._service = pvc_svc <NEW_LINE> <DEDENT> PowerVCDriver.__init__ = pvc_drv_init_instance_not_found <NEW_LINE> pvc_drv = PowerVCDriver() <NEW_LINE> self.assertIsNone(pvc_drv.get_instance(self.pvc_id)) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(TestGetInstance, self).tearDown() <NEW_LINE> PowerVCDriver.__init__ = self.pvcdrv_init_copy | This is the test fixture for PowerVCDriver.get_instance. | 6259909b50812a4eaa621adb |
class TrackError(Exception): <NEW_LINE> <INDENT> pass | General error class raised by Track | 6259909bd8ef3951e32c8d71 |
class Forbidden(CloudServersException): <NEW_LINE> <INDENT> http_status = 403 <NEW_LINE> message = "Forbidden" | HTTP 403 - Forbidden: your credentials don't give you access to this resource. | 6259909badb09d7d5dc0c386 |
class WKTAdapter: <NEW_LINE> <INDENT> def __init__(self, geom): <NEW_LINE> <INDENT> self.wkt = geom.wkt <NEW_LINE> self.srid = geom.srid <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return ( isinstance(other, WKTAdapter) and self.wkt == other.wkt and self.srid == other.srid ) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.wkt, self.srid)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.wkt <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _fix_polygon(cls, poly): <NEW_LINE> <INDENT> return poly | An adaptor for Geometries sent to the MySQL and Oracle database backends. | 6259909bd8ef3951e32c8d72 |
class TestSamConverterRoundTrip(TestSamConverter): <NEW_LINE> <INDENT> def _testRoundTrip(self, binaryOutput): <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile() as fileHandle: <NEW_LINE> <INDENT> filePath = fileHandle.name <NEW_LINE> samConverter = converters.SamConverter( None, self.getReads(), filePath, binaryOutput) <NEW_LINE> samConverter.convert() <NEW_LINE> samfile = pysam.AlignmentFile(filePath, "r") <NEW_LINE> reads = list(samfile.fetch()) <NEW_LINE> self.assertEqual(reads[0].query_name, "SRR622461.77861202") <NEW_LINE> samfile.close() <NEW_LINE> <DEDENT> <DEDENT> def testPlainText(self): <NEW_LINE> <INDENT> self._testRoundTrip(False) <NEW_LINE> <DEDENT> def testBinary(self): <NEW_LINE> <INDENT> self._testRoundTrip(True) | Write a sam file and see if pysam can read it | 6259909b656771135c48af47 |
def __init__(self): <NEW_LINE> <INDENT> self.x = 0 <NEW_LINE> self.y = 0 <NEW_LINE> self.last_x = 0 <NEW_LINE> self.last_y = 0 <NEW_LINE> self.xDiff = 0 <NEW_LINE> self.yDiff = 0 <NEW_LINE> self.xDiff1 = 0 <NEW_LINE> self.yDiff1 = 0 <NEW_LINE> self.diffMag1 = 0 <NEW_LINE> self.diffMag2 = 0 <NEW_LINE> self.B2P_angle = 0 <NEW_LINE> self.sprite = pygame.image.load("Game Files/Sprites/Bullet.png").convert_alpha() <NEW_LINE> self.sprite = pygame.transform.scale(self.sprite, (15, 15)) <NEW_LINE> self.mask = pygame.mask.from_surface(self.sprite) <NEW_LINE> self.offset = 0 <NEW_LINE> self.result = False <NEW_LINE> self.width, self.height = self.sprite.get_rect().size <NEW_LINE> self.velocity = [0, 0] <NEW_LINE> self.speed = 1 <NEW_LINE> self.creator = None <NEW_LINE> self.hit = False | Bullet() | 6259909b3617ad0b5ee07f81 |
class DiscontinuousInterpolator(object): <NEW_LINE> <INDENT> def __init__(self,x,y,period,offset=0): <NEW_LINE> <INDENT> y=y-offset <NEW_LINE> di=np.where(y[1:]-y[:-1]<0) <NEW_LINE> for i in di[0]: <NEW_LINE> <INDENT> y[i:]=y[i:]+offset <NEW_LINE> <DEDENT> self.int=interp1d(x,y) <NEW_LINE> self.period=24 <NEW_LINE> self.offset=offset <NEW_LINE> <DEDENT> def __call__(self,x): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _ = (d for d in dates) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> x=[x] <NEW_LINE> <DEDENT> y=self.int(x) <NEW_LINE> y=y%self.period+self.offset <NEW_LINE> if len(x)==1: <NEW_LINE> <INDENT> return x[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x | Interpolates a function which increases monotonically but resets to zero upon reaching a defined value | 6259909b091ae35668706a60 |
class LeaveComment(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Facebook/Publishing/LeaveComment') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return LeaveCommentInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return LeaveCommentResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return LeaveCommentChoreographyExecution(session, exec_id, path) | Create a new instance of the LeaveComment Choreography. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 6259909b099cdd3c63676311 |
class InferenceEngine: <NEW_LINE> <INDENT> def __init__(self, bnet, do_print=False, is_quantum=False): <NEW_LINE> <INDENT> self.bnet = bnet <NEW_LINE> self.do_print = do_print <NEW_LINE> self.is_quantum = is_quantum <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def print_annotated_story(annotated_story): <NEW_LINE> <INDENT> story_line = "" <NEW_LINE> for node in annotated_story.keys(): <NEW_LINE> <INDENT> story_line += node.name + "=" <NEW_LINE> story_line += str(annotated_story[node]) + ", " <NEW_LINE> <DEDENT> print(story_line[:-2]) | This is the parent class of all inference engines.
Attributes
----------
bnet : BayesNet
do_print : bool
is_quantum : bool | 6259909bdc8b845886d553e7 |
class JSONClient(client.RESTClient): <NEW_LINE> <INDENT> _req_class = JSONRequest <NEW_LINE> _content_type = 'application/json' <NEW_LINE> def __init__(self, baseurl, headers=None, debug=False, client=None): <NEW_LINE> <INDENT> super(JSONClient, self).__init__(baseurl, headers, debug, client) <NEW_LINE> self._headers.setdefault('accept', self._content_type) <NEW_LINE> <DEDENT> def _attach_obj(self, req, obj): <NEW_LINE> <INDENT> json.dump(obj, req) <NEW_LINE> req['content-type'] = self._content_type | Process JSON data in requests and responses.
Augments RESTClient to include the _attach_obj() helper method,
for attaching JSON objects to requests. Also uses JSONRequest in
preference to HTTPRequest, so that JSON data in responses is
processed. | 6259909bd8ef3951e32c8d75 |
class DictChunk(Chunk): <NEW_LINE> <INDENT> default = {} <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(DictChunk, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.internal_value[key] <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return self.internal_value[name] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.internal_value[key] = value <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> self.internal_value.remove(key) <NEW_LINE> <DEDENT> def raw2internal(self, raw_value): <NEW_LINE> <INDENT> raise Exception("Base implementation of ListChunk does not support raw2internal") <NEW_LINE> <DEDENT> def internal2raw(self, internal_value): <NEW_LINE> <INDENT> raw_data = b"" <NEW_LINE> for chunk in internal_value: <NEW_LINE> <INDENT> raw_data += chunk.raw_value <NEW_LINE> <DEDENT> return raw_data <NEW_LINE> <DEDENT> def internal2rawlength(self, internal_value): <NEW_LINE> <INDENT> total_size = 0 <NEW_LINE> for elmnt in internal_value: <NEW_LINE> <INDENT> total_size += elmnt.raw_length <NEW_LINE> <DEDENT> return total_size <NEW_LINE> <DEDENT> def human2internal(self, human_value): <NEW_LINE> <INDENT> raise Exception("Base implementation of ListChunk does not support human2internal") <NEW_LINE> <DEDENT> def internal2human(self, internal_value): <NEW_LINE> <INDENT> rstr = "%s " % self.name + " { " <NEW_LINE> for elmnt in internal_value.keys(): <NEW_LINE> <INDENT> rstr += elmnt + self.internal_value[elmnt].human_value + "," <NEW_LINE> <DEDENT> rstr += " ]" <NEW_LINE> return rstr <NEW_LINE> <DEDENT> def display_string(self, indent=""): <NEW_LINE> <INDENT> rstr = indent + "%s " % self.name + " [ " <NEW_LINE> for elmnt in self.internal_value: <NEW_LINE> <INDENT> rstr += "\n" + elmnt.display_string(indent + " ") + "," <NEW_LINE> <DEDENT> rstr += " ]" <NEW_LINE> return rstr | A chunk whereby the internal value is stored as a python list | 6259909bc4546d3d9def81b5 |
class APIRouterV21(base_wsgi.Router): <NEW_LINE> <INDENT> def __init__(self, custom_routes=None): <NEW_LINE> <INDENT> super(APIRouterV21, self).__init__(nova.api.openstack.ProjectMapper()) <NEW_LINE> if custom_routes is None: <NEW_LINE> <INDENT> custom_routes = tuple() <NEW_LINE> <DEDENT> for path, methods in ROUTE_LIST + custom_routes: <NEW_LINE> <INDENT> if isinstance(methods, str): <NEW_LINE> <INDENT> self.map.redirect(path, methods) <NEW_LINE> continue <NEW_LINE> <DEDENT> for method, controller_info in methods.items(): <NEW_LINE> <INDENT> controller = controller_info[0]() <NEW_LINE> action = controller_info[1] <NEW_LINE> self.map.create_route(path, method, controller, action) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def factory(cls, global_config, **local_config): <NEW_LINE> <INDENT> return cls() | Routes requests on the OpenStack API to the appropriate controller
and method. The URL mapping based on the plain list `ROUTE_LIST` is built
at here. | 6259909bdc8b845886d553eb |
class ecs(object): <NEW_LINE> <INDENT> def __init__(self, RA, Dec): <NEW_LINE> <INDENT> self.RA = RA <NEW_LINE> self.Dec = Dec <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s(%g S) %s(%g s)' % (self.RA, self.RA.SSuncertainty ,self.Dec,self.Dec.SSuncertainty) <NEW_LINE> <DEDENT> def ecs2gcs(self): <NEW_LINE> <INDENT> ra = self.RA.in_unit_degree <NEW_LINE> dec = self.Dec.in_unit_degree <NEW_LINE> GCOra = 266.405100 <NEW_LINE> GCOdec = -28.936175 <NEW_LINE> GCNPra = 192.859508 <NEW_LINE> GCNPdec = 27.128336 | Equatorial coordinate system | 6259909badb09d7d5dc0c390 |
class GroupViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Group.objects.all() <NEW_LINE> serializer_class = GroupSerializer | retrieve:
Return o group instance
list:
Return all group,odered by most recent joined
create:
Create a new group
delete:
Remove a existing group
partial_update:
Update one or more fields on a existing group
update:
Update a group | 6259909bdc8b845886d553ed |
class CatalogGenreView(ListView): <NEW_LINE> <INDENT> model = Genre <NEW_LINE> newdeals = Book.objects.all().order_by('-pk')[:6] <NEW_LINE> extra_context = {'newdeals':newdeals} <NEW_LINE> template_name = "catalog/catalog_list.html" | displays cards with Genres objects | 6259909b099cdd3c63676315 |
class Interval(Reference): <NEW_LINE> <INDENT> def __init__(self, vertices=((0,), (1,))): <NEW_LINE> <INDENT> self.tdim = 1 <NEW_LINE> self.name = "interval" <NEW_LINE> self.origin = vertices[0] <NEW_LINE> self.axes = (vsub(vertices[1], vertices[0]),) <NEW_LINE> self.reference_vertices = ((0,), (1,)) <NEW_LINE> self.vertices = tuple(vertices) <NEW_LINE> self.edges = ((0, 1),) <NEW_LINE> self.faces = tuple() <NEW_LINE> self.volumes = tuple() <NEW_LINE> self.sub_entity_types = ["point", "interval", None, None] <NEW_LINE> super().__init__(simplex=True, tp=True) <NEW_LINE> <DEDENT> def default_reference(self): <NEW_LINE> <INDENT> return Interval(self.reference_vertices) <NEW_LINE> <DEDENT> def integral(self, f, vars=t): <NEW_LINE> <INDENT> return (f * self.jacobian()).integrate((vars[0], 0, 1)) <NEW_LINE> <DEDENT> def get_map_to(self, vertices): <NEW_LINE> <INDENT> assert self.vertices == self.reference_vertices <NEW_LINE> return tuple(v0 + (v1 - v0) * x[0] for v0, v1 in zip(*vertices)) <NEW_LINE> <DEDENT> def get_inverse_map_to(self, vertices): <NEW_LINE> <INDENT> assert self.vertices == self.reference_vertices <NEW_LINE> p = vsub(x, vertices[0]) <NEW_LINE> v = vsub(vertices[1], vertices[0]) <NEW_LINE> return (vdot(p, v) / vdot(v, v), ) <NEW_LINE> <DEDENT> def _compute_map_to_self(self): <NEW_LINE> <INDENT> return tuple(v0 + (v1 - v0) * x[0] for v0, v1 in zip(*self.vertices)) <NEW_LINE> <DEDENT> def _compute_inverse_map_to_self(self): <NEW_LINE> <INDENT> p = vsub(x, self.vertices[0]) <NEW_LINE> v = vsub(self.vertices[1], self.vertices[0]) <NEW_LINE> return (vdot(p, v) / vdot(v, v), ) <NEW_LINE> <DEDENT> def volume(self): <NEW_LINE> <INDENT> return self.jacobian() <NEW_LINE> <DEDENT> def contains(self, point): <NEW_LINE> <INDENT> if self.vertices != self.reference_vertices: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> return 0 <= point[0] <= 1 | An interval. | 6259909bdc8b845886d553f1 |
Subsets and Splits