code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class ReverseGenericRelatedObjectsDescriptor(object): <NEW_LINE> <INDENT> def __init__(self, field, for_concrete_model=True): <NEW_LINE> <INDENT> self.field = field <NEW_LINE> self.for_concrete_model = for_concrete_model <NEW_LINE> <DEDENT> def __get__(self, instance, instance_type=None): <NEW_LINE> <INDENT> if instance is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> rel_model = self.field.rel.to <NEW_LINE> superclass = rel_model._default_manager.__class__ <NEW_LINE> RelatedManager = create_generic_related_manager(superclass) <NEW_LINE> qn = connection.ops.quote_name <NEW_LINE> content_type = ContentType.objects.db_manager(instance._state.db).get_for_model( instance, for_concrete_model=self.for_concrete_model) <NEW_LINE> join_cols = self.field.get_joining_columns(reverse_join=True)[0] <NEW_LINE> manager = RelatedManager( model = rel_model, instance = instance, source_col_name = qn(join_cols[0]), target_col_name = qn(join_cols[1]), content_type = content_type, content_type_field_name = self.field.content_type_field_name, object_id_field_name = self.field.object_id_field_name, prefetch_cache_name = self.field.attname, ) <NEW_LINE> return manager <NEW_LINE> <DEDENT> def __set__(self, instance, value): <NEW_LINE> <INDENT> manager = self.__get__(instance) <NEW_LINE> manager.clear() <NEW_LINE> for obj in value: <NEW_LINE> <INDENT> manager.add(obj) | This class provides the functionality that makes the related-object
managers available as attributes on a model class, for fields that have
multiple "remote" values and have a GenericRelation defined in their model
(rather than having another model pointed *at* them). In the example
"article.publications", the publications attribute is a
ReverseGenericRelatedObjectsDescriptor instance. | 62598fa5462c4b4f79dbb8ea |
class Notifier: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._logger = logging.getLogger('{base}.{suffix}' .format(base=LOGGER_BASENAME, suffix=self.__class__.__name__) ) <NEW_LINE> self.broadcast = Group('broadcast') <NEW_LINE> <DEDENT> @property <NEW_LINE> def channels(self): <NEW_LINE> <INDENT> return [channel.name for channel in self.broadcast._channels] <NEW_LINE> <DEDENT> def register(self, *args): <NEW_LINE> <INDENT> for channel in args: <NEW_LINE> <INDENT> if not isinstance(channel, Channel): <NEW_LINE> <INDENT> raise ValueError(('The object is not a Channel :' '[{}]').format(channel)) <NEW_LINE> <DEDENT> if channel.name in self.channels: <NEW_LINE> <INDENT> raise ValueError('Channel already registered') <NEW_LINE> <DEDENT> self.broadcast._channels.append(channel) <NEW_LINE> <DEDENT> <DEDENT> def unregister(self, *args): <NEW_LINE> <INDENT> for channel in args: <NEW_LINE> <INDENT> if channel.name not in self.channels: <NEW_LINE> <INDENT> raise ValueError('Channel not registered') <NEW_LINE> <DEDENT> self.broadcast._channels = [ch for ch in self.broadcast._channels if not ch.name == channel.name] <NEW_LINE> <DEDENT> <DEDENT> def add_group(self, group): <NEW_LINE> <INDENT> if not isinstance(group, Group): <NEW_LINE> <INDENT> raise ValueError(('The object is not a Group :' '[{}]').format(group)) <NEW_LINE> <DEDENT> setattr(self, group.name, group) <NEW_LINE> <DEDENT> def remove_group(self, group): <NEW_LINE> <INDENT> if not isinstance(group, Group): <NEW_LINE> <INDENT> raise ValueError(('The object is not a Group :' '[{}]').format(group)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> delattr(self, group.name) <NEW_LINE> return True <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self._logger.error('No such group :{}'.format(group.name)) <NEW_LINE> return False | Model of a notifier. | 62598fa5dd821e528d6d8e13 |
class SharedLibrary(_Library): <NEW_LINE> <INDENT> def __init__(self, name, baseEnv = None): <NEW_LINE> <INDENT> lib_name = path.join(path.dirname(str(name)), baseEnv.subst('${SHLIBPREFIX}') + path.basename(str(name)) + baseEnv.subst('${SHLIBSUFFIX}')) <NEW_LINE> _Library.__init__(self, lib_name, baseEnv, SCons.Defaults.SharedLibrary) | This object knows how to build (and install) a shared library from a given
set of sources. | 62598fa5090684286d59364a |
class DeleteResourceRecordsRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(DeleteResourceRecordsRequest, self).__init__( '/regions/{regionId}/zone/{zoneId}/resourceRecords/{resourceRecordId}', 'DELETE', header, version) <NEW_LINE> self.parameters = parameters | 删除解析记录。批量删除时多个resourceRecordId用","分隔。批量删除每次最多不超过100个记录 | 62598fa51f037a2d8b9e3fc9 |
class PrivateUserApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = create_user( email = 'test@test.com', password ='testpass', name = 'name', ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=self.user) <NEW_LINE> <DEDENT> def test_retrieve_profile_success(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, { 'name': self.user.name, 'email': self.user.email, }) <NEW_LINE> <DEDENT> def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> res = self.client.post(ME_URL, {}) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_update_user_profile(self): <NEW_LINE> <INDENT> payload = {'name': 'new_name', 'password': 'newpassword123'} <NEW_LINE> res = self.client.patch(ME_URL, payload) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE> self.assertEqual(self.user.name, payload['name']) <NEW_LINE> self.assertTrue(self.user.check_password(payload['password'])) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) | Test Api requests that require authentication | 62598fa5167d2b6e312b6e4e |
class Reader(object): <NEW_LINE> <INDENT> def __init__(self, name, reader, data_type): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.reader = reader <NEW_LINE> self.data_type = data_type | Class for cyber reader wrapper. | 62598fa5a219f33f346c66f6 |
class MockGraph(object): <NEW_LINE> <INDENT> def __init__(self, transaction_errors=False, **kwargs): <NEW_LINE> <INDENT> self.nodes = set() <NEW_LINE> self.number_commits = 0 <NEW_LINE> self.number_rollbacks = 0 <NEW_LINE> self.transaction_errors = transaction_errors <NEW_LINE> <DEDENT> def begin(self): <NEW_LINE> <INDENT> return MockTransaction(self) | A stubbed out version of py2neo's Graph object, used for testing.
Args:
transaction_errors: a bool for whether transactions should throw
an error. | 62598fa599fddb7c1ca62d57 |
class CreateRecordingPlanRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Name = None <NEW_LINE> self.TimeTemplateId = None <NEW_LINE> self.Channels = None <NEW_LINE> self.RecordStorageTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Name = params.get("Name") <NEW_LINE> self.TimeTemplateId = params.get("TimeTemplateId") <NEW_LINE> if params.get("Channels") is not None: <NEW_LINE> <INDENT> self.Channels = [] <NEW_LINE> for item in params.get("Channels"): <NEW_LINE> <INDENT> obj = ChannelItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Channels.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RecordStorageTime = params.get("RecordStorageTime") <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)) | CreateRecordingPlan请求参数结构体
| 62598fa5e5267d203ee6b7ea |
class PagedCloudIntegration(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'items': 'list[CloudIntegration]', 'offset': 'int', 'limit': 'int', 'cursor': 'str', 'total_items': 'int', 'more_items': 'bool', 'sort': 'Sorting' } <NEW_LINE> self.attribute_map = { 'items': 'items', 'offset': 'offset', 'limit': 'limit', 'cursor': 'cursor', 'total_items': 'totalItems', 'more_items': 'moreItems', 'sort': 'sort' } <NEW_LINE> self._items = None <NEW_LINE> self._offset = None <NEW_LINE> self._limit = None <NEW_LINE> self._cursor = None <NEW_LINE> self._total_items = None <NEW_LINE> self._more_items = None <NEW_LINE> self._sort = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> @property <NEW_LINE> def offset(self): <NEW_LINE> <INDENT> return self._offset <NEW_LINE> <DEDENT> @offset.setter <NEW_LINE> def offset(self, offset): <NEW_LINE> <INDENT> self._offset = offset <NEW_LINE> <DEDENT> @property <NEW_LINE> def limit(self): <NEW_LINE> <INDENT> return self._limit <NEW_LINE> <DEDENT> @limit.setter <NEW_LINE> def limit(self, limit): <NEW_LINE> <INDENT> self._limit = limit <NEW_LINE> <DEDENT> @property <NEW_LINE> def cursor(self): <NEW_LINE> <INDENT> return self._cursor <NEW_LINE> <DEDENT> @cursor.setter <NEW_LINE> def cursor(self, cursor): <NEW_LINE> <INDENT> self._cursor = cursor <NEW_LINE> <DEDENT> @property <NEW_LINE> def total_items(self): <NEW_LINE> <INDENT> return self._total_items <NEW_LINE> <DEDENT> @total_items.setter <NEW_LINE> def total_items(self, total_items): <NEW_LINE> <INDENT> self._total_items = total_items <NEW_LINE> <DEDENT> @property <NEW_LINE> def more_items(self): <NEW_LINE> <INDENT> return self._more_items <NEW_LINE> <DEDENT> @more_items.setter <NEW_LINE> def more_items(self, more_items): <NEW_LINE> <INDENT> self._more_items = more_items <NEW_LINE> <DEDENT> @property <NEW_LINE> def sort(self): <NEW_LINE> <INDENT> return self._sort <NEW_LINE> <DEDENT> @sort.setter <NEW_LINE> def sort(self, sort): <NEW_LINE> <INDENT> self._sort = sort <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa5a8370b77170f02b9 |
class IRefreshActionsManager(models.Manager): <NEW_LINE> <INDENT> def selectable_intentions(self, user, max=1): <NEW_LINE> <INDENT> intentions = self.filter(user=user, job=None, previous=None) <NEW_LINE> return intentions.all()[:max] | Model manager for instances of IRefreshActions | 62598fa52c8b7c6e89bd36a4 |
class NickHandler(AttributeHandler): <NEW_LINE> <INDENT> _attrtype = "nick" <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._regex_cache = {} <NEW_LINE> <DEDENT> def has(self, key, category="inputline"): <NEW_LINE> <INDENT> return super().has(key, category=category) <NEW_LINE> <DEDENT> def get(self, key=None, category="inputline", return_tuple=False, **kwargs): <NEW_LINE> <INDENT> if return_tuple or "return_obj" in kwargs: <NEW_LINE> <INDENT> return super().get(key=key, category=category, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retval = super().get(key=key, category=category, **kwargs) <NEW_LINE> if retval: <NEW_LINE> <INDENT> return ( retval[3] if isinstance(retval, tuple) else [tup[3] for tup in make_iter(retval)] ) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def add(self, key, replacement, category="inputline", **kwargs): <NEW_LINE> <INDENT> if category == "channel": <NEW_LINE> <INDENT> nick_regex, nick_template = initialize_nick_templates(key + " $1", replacement + " $1") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nick_regex, nick_template = initialize_nick_templates(key, replacement) <NEW_LINE> <DEDENT> super().add(key, (nick_regex, nick_template, key, replacement), category=category, **kwargs) <NEW_LINE> <DEDENT> def remove(self, key, category="inputline", **kwargs): <NEW_LINE> <INDENT> super().remove(key, category=category, **kwargs) <NEW_LINE> <DEDENT> def nickreplace(self, raw_string, categories=("inputline", "channel"), include_account=True): <NEW_LINE> <INDENT> nicks = {} <NEW_LINE> for category in make_iter(categories): <NEW_LINE> <INDENT> nicks.update( { nick.key: nick for nick in make_iter(self.get(category=category, return_obj=True)) if nick and nick.key } ) <NEW_LINE> <DEDENT> if include_account and self.obj.has_account: <NEW_LINE> <INDENT> for category in make_iter(categories): <NEW_LINE> <INDENT> nicks.update( { nick.key: nick for nick in make_iter( self.obj.account.nicks.get(category=category, return_obj=True) ) if nick and nick.key } ) <NEW_LINE> <DEDENT> <DEDENT> for key, nick in nicks.items(): <NEW_LINE> <INDENT> nick_regex, template, _, _ = nick.value <NEW_LINE> regex = self._regex_cache.get(nick_regex) <NEW_LINE> if not regex: <NEW_LINE> <INDENT> regex = re.compile(nick_regex, re.I + re.DOTALL + re.U) <NEW_LINE> self._regex_cache[nick_regex] = regex <NEW_LINE> <DEDENT> is_match, raw_string = parse_nick_template(raw_string.strip(), regex, template) <NEW_LINE> if is_match: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return raw_string | Handles the addition and removal of Nicks. Nicks are special
versions of Attributes with an `_attrtype` hardcoded to `nick`.
They also always use the `strvalue` fields for their data. | 62598fa51f5feb6acb162b00 |
class BannedEmailTestCase(TestCase): <NEW_LINE> <INDENT> def test_str(self): <NEW_LINE> <INDENT> banned_email = BannedEmail.objects.create(email='test@example.com') <NEW_LINE> self.assertEqual(str(banned_email), 'test@example.com') | Tests suite for the ``BannedEmail`` class. | 62598fa5627d3e7fe0e06d8b |
class Variable(Symbol) : <NEW_LINE> <INDENT> def __init__(self) : <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.name = '' <NEW_LINE> <DEDENT> def register(self, id_file, code) : <NEW_LINE> <INDENT> super().register(id_file, code) <NEW_LINE> try : <NEW_LINE> <INDENT> self.analyze() <NEW_LINE> <DEDENT> except : <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.update() <NEW_LINE> <DEDENT> def load(self, data) : <NEW_LINE> <INDENT> super().load(data) <NEW_LINE> self.name = data[7] <NEW_LINE> <DEDENT> def analyze(self) : <NEW_LINE> <INDENT> code = self.code[0].ccode <NEW_LINE> self.name = RDIC['variable'].match(code).group(1) <NEW_LINE> <DEDENT> def update(self) : <NEW_LINE> <INDENT> values = ['variable', '', self.id_file, self.iline] <NEW_LINE> values[1] = [['name', self.name]] <NEW_LINE> return self.DBC.updateSymbol(values) <NEW_LINE> <DEDENT> def symbRepr(self) : <NEW_LINE> <INDENT> return str(self.name) + ' [' + str(self.iline) + ']' | Python Variable can be defined by :
. a name | 62598fa53317a56b869be4b9 |
class BadSearch(VonAnchorError): <NEW_LINE> <INDENT> def __init__(self, message: str): <NEW_LINE> <INDENT> super().__init__(ErrorCode.BadSearch, message) | Search operation failed. | 62598fa5a79ad16197769f41 |
class TestCalendarDate(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return CalendarDate( all_day = True, calendar_category_id = 56, category = '0', description = '0', end_date = '0', event_id = 56, location = '0', start_date = '0', state = [ '0' ], summary = '0', url = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return CalendarDate( ) <NEW_LINE> <DEDENT> <DEDENT> def testCalendarDate(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | CalendarDate unit test stubs | 62598fa544b2445a339b68de |
class QuiveringPalm(Feature): <NEW_LINE> <INDENT> name = "Quivering Palm" <NEW_LINE> source = "Monk (Way of the Open Hand)" | At 17th level, you gain the ability to set up lethal vibrations in
someone’s body. When you hit a creature with an unarmed strike, you can
spend 3 ki points to start these imperceptible vibrations, which last for a
number of days equal to your monk level. The vibrations are harmless unless
you use your action to end them. To do so, you and the target must be on
the same plane of existence. When you use this action, the creature must
make a Constitution saving throw. If it fails, it is reduced to 0 hit
points. If it succeeds, it takes 10d10 necrotic damage. You can have only
one creature under the effect of this feature at a time. You can choose to
end the vibrations harmlessly without using an action. | 62598fa576e4537e8c3ef48b |
@parser(Specs.tuned_adm) <NEW_LINE> class Tuned(Parser): <NEW_LINE> <INDENT> def parse_content(self, content): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> self.data['available'] = [] <NEW_LINE> for line in content: <NEW_LINE> <INDENT> if line.startswith('-'): <NEW_LINE> <INDENT> self.data['available'].append(line.split('- ')[1]) <NEW_LINE> <DEDENT> elif line.startswith('Current'): <NEW_LINE> <INDENT> self.data['active'] = line.split(': ')[1] <NEW_LINE> <DEDENT> elif line.startswith('Preset'): <NEW_LINE> <INDENT> self.data['preset'] = line.split(': ')[1] | Parse data from the ``/usr/sbin/tuned-adm list`` command. | 62598fa56fb2d068a7693da5 |
class Runner(object): <NEW_LINE> <INDENT> def __init__(self, job=None): <NEW_LINE> <INDENT> self.extract_packages_archive() <NEW_LINE> self.job = job or pickle.load(open("job-instance.pickle")) <NEW_LINE> self.job._setup_remote() <NEW_LINE> <DEDENT> def run(self, kind, stdin=sys.stdin, stdout=sys.stdout): <NEW_LINE> <INDENT> if kind == "map": <NEW_LINE> <INDENT> self.job.run_mapper(stdin, stdout) <NEW_LINE> <DEDENT> elif kind == "combiner": <NEW_LINE> <INDENT> self.job.run_combiner(stdin, stdout) <NEW_LINE> <DEDENT> elif kind == "reduce": <NEW_LINE> <INDENT> self.job.run_reducer(stdin, stdout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('weird command: %s' % kind) <NEW_LINE> <DEDENT> <DEDENT> def extract_packages_archive(self): <NEW_LINE> <INDENT> if not os.path.exists("packages.tar"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tar = tarfile.open("packages.tar") <NEW_LINE> for tarinfo in tar: <NEW_LINE> <INDENT> tar.extract(tarinfo) <NEW_LINE> <DEDENT> tar.close() <NEW_LINE> if '' not in sys.path: <NEW_LINE> <INDENT> sys.path.insert(0, '') | Run the mapper or reducer on hadoop nodes. | 62598fa55f7d997b871f9350 |
class YAMLMetaField(YAMLJSONField): <NEW_LINE> <INDENT> def to_python(self, value): <NEW_LINE> <INDENT> obj = super().to_python(value) <NEW_LINE> for k, v in obj.items(): <NEW_LINE> <INDENT> if not isinstance(k, str): <NEW_LINE> <INDENT> raise forms.ValidationError('Error "{}" is not a sting key.'.format(k)) <NEW_LINE> <DEDENT> if '.' not in k: <NEW_LINE> <INDENT> raise forms.ValidationError('Error "{}" key is missing namespace denoted with a "."'.format(k)) <NEW_LINE> <DEDENT> if not isinstance(v, (str, int)): <NEW_LINE> <INDENT> raise forms.ValidationError('Error "{}" is not a string or integer value.'.format(v)) <NEW_LINE> <DEDENT> <DEDENT> return obj | YAML Metafields form field | 62598fa5e76e3b2f99fd8915 |
class TestCase(models.Model): <NEW_LINE> <INDENT> module = models.ForeignKey(Module, on_delete=models.CASCADE) <NEW_LINE> name = models.CharField("名称", max_length=100, blank=False, default="") <NEW_LINE> url = models.TextField("URL", default="") <NEW_LINE> req_method = models.CharField("方法", max_length=10, default="") <NEW_LINE> req_type = models.CharField("参数类型", max_length=10, default="") <NEW_LINE> req_header = models.TextField("header", default="") <NEW_LINE> req_parameter = models.TextField("参数", default="") <NEW_LINE> resp_assert = models.TextField("验证", default="") <NEW_LINE> create_time = models.DateTimeField("创建时间", auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '测试用例' <NEW_LINE> verbose_name_plural = '测试用例' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | 用例表 | 62598fa5baa26c4b54d4f190 |
class function_type(base): <NEW_LINE> <INDENT> def __init__(self, return_type, argument_types): <NEW_LINE> <INDENT> self.return_type = return_type <NEW_LINE> self.arg_type_list = argument_types <NEW_LINE> <DEDENT> def __ne__(self, rival): <NEW_LINE> <INDENT> return not self.__eq__(rival) <NEW_LINE> <DEDENT> def __eq__(self, rival): <NEW_LINE> <INDENT> return isinstance(rival, function_type) and rival.return_type == self.return_type and rival.arg_type_list == self.arg_type_list <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if len(self.arg_type_list) == 0: <NEW_LINE> <INDENT> arg_type_list_repr = 'unit' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arg_type_list_repr = ' x '.join([str(type) for type in self.arg_type_list]) <NEW_LINE> <DEDENT> return '%s -> %s' % (arg_type_list_repr, self.return_type) | A function type. | 62598fa526068e7796d4c838 |
class Larva(Agent): <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> Agent.__init__(self, x, y, "Larva") <NEW_LINE> <DEDENT> def getValidMoves(self): <NEW_LINE> <INDENT> x, y = self.getPosition() <NEW_LINE> up_right = Coordinates(x - 1, y + 1) <NEW_LINE> up_left = Coordinates(x - 1, y - 1) <NEW_LINE> down_right = Coordinates(x + 1, y + 1) <NEW_LINE> down_left = Coordinates(x + 1, y - 1) <NEW_LINE> moves = [up_right, up_left, down_right, down_left] <NEW_LINE> validMoves = [] <NEW_LINE> for move in moves: <NEW_LINE> <INDENT> if 0 <= move.x < 8 and 0 <= move.y < 8: <NEW_LINE> <INDENT> validMoves.append(move) <NEW_LINE> <DEDENT> <DEDENT> return validMoves | Class for the larva agent | 62598fa5fff4ab517ebcd6c4 |
class RoomSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Room <NEW_LINE> fields = ("id", "name", "university_building",) <NEW_LINE> read_only_fields = ("id",) | Serializer to represent the Room model | 62598fa50a50d4780f7052bc |
class OssException(Exception): <NEW_LINE> <INDENT> message = _("An unknown exception occurred") <NEW_LINE> def __init__(self, message=None, *args, **kwargs): <NEW_LINE> <INDENT> if not message: <NEW_LINE> <INDENT> message = self.message <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> message = message % kwargs <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if _FATAL_EXCEPTION_FORMAT_ERRORS: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.msg = message <NEW_LINE> super(OssException, self).__init__(message) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return six.text_type(self.msg) | Base ops-adapter Exception
To correctly use this class, inherit from it and define
a 'message' property. That message will get printf'd
with the keyword arguments provided to the constructor. | 62598fa54e4d562566372304 |
class LogicalOr(Operator): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def do_export_proto(self): <NEW_LINE> <INDENT> params = OpProto.LogicalOrOperator() <NEW_LINE> return params | Apply the LogicalOr operator entrywise. | 62598fa5851cf427c66b81a8 |
@attr.s(slots=True) <NEW_LINE> class Group: <NEW_LINE> <INDENT> name = attr.ib(type=str) <NEW_LINE> policy = attr.ib(type=perm_mdl.PolicyType) <NEW_LINE> id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex) | A group. | 62598fa51f037a2d8b9e3fcb |
class MedicamentoForm(AdmisionBaseForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Medicamento <NEW_LINE> exclude = ('proxima_dosis', 'suministrado') <NEW_LINE> <DEDENT> inicio = forms.DateTimeField(widget=DateTimeWidget(), required=False) <NEW_LINE> cargo = ModelChoiceField(name='cargo', model='', queryset=ItemTemplate.objects.filter( activo=True).order_by('descripcion').all()) <NEW_LINE> admision = forms.ModelChoiceField(label="", queryset=Admision.objects.all(), widget=forms.HiddenInput(), required=False) <NEW_LINE> usuario = forms.ModelChoiceField(label="", queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MedicamentoForm, self).__init__(*args, **kwargs) <NEW_LINE> self.helper.layout = Fieldset(u'Recetar Medicamento', *self.field_names) | Permite Agregar o modificar los datos de un :class:`Medicamento` | 62598fa5d486a94d0ba2bead |
class RecordValueList(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=64) <NEW_LINE> slug = models.SlugField(max_length=64, unique=True) <NEW_LINE> location = models.ForeignKey(Location) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @models.permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return ('recordvaluelist-detail', (), { 'location_slug': self.location.slug, 'slug': self.slug }) | List RecordValues for a specific location.
This is referred to by RecordValue | 62598fa57d43ff2487427372 |
class JobLogConfigInfo(NetAppObject): <NEW_LINE> <INDENT> _job_log_level = None <NEW_LINE> @property <NEW_LINE> def job_log_level(self): <NEW_LINE> <INDENT> return self._job_log_level <NEW_LINE> <DEDENT> @job_log_level.setter <NEW_LINE> def job_log_level(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('job_log_level', val) <NEW_LINE> <DEDENT> self._job_log_level = val <NEW_LINE> <DEDENT> _job_log_module = None <NEW_LINE> @property <NEW_LINE> def job_log_module(self): <NEW_LINE> <INDENT> return self._job_log_module <NEW_LINE> <DEDENT> @job_log_module.setter <NEW_LINE> def job_log_module(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('job_log_module', val) <NEW_LINE> <DEDENT> self._job_log_module = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "job-log-config-info" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'job-log-level', 'job-log-module', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'job_log_level': { 'class': basestring, 'is_list': False, 'required': 'optional' }, 'job_log_module': { 'class': basestring, 'is_list': False, 'required': 'optional' }, } | Contains job-manager-logging configuration for a single module in
the system.
When returned as part of the output, all elements of this typedef
are reported, unless limited by a set of desired attributes
specified by the caller.
<p>
When used as input to specify desired attributes to return,
omitting a given element indicates that it shall not be returned
in the output. In contrast, by providing an element (even with
no value) the caller ensures that a value for that element will
be returned, given that the value can be retrieved.
<p>
When used as input to specify queries, any element can be omitted
in which case the resulting set of objects is not constrained by
any specific value of that attribute. | 62598fa5be383301e02536d8 |
@expose_substitution('eval') <NEW_LINE> class PythonExpression(Substitution): <NEW_LINE> <INDENT> def __init__(self, expression: SomeSubstitutionsType) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> ensure_argument_type( expression, (str, Substitution, collections.abc.Iterable), 'expression', 'PythonExpression') <NEW_LINE> from ..utilities import normalize_to_list_of_substitutions <NEW_LINE> self.__expression = normalize_to_list_of_substitutions(expression) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse(cls, data: Iterable[SomeSubstitutionsType]): <NEW_LINE> <INDENT> if len(data) != 1: <NEW_LINE> <INDENT> raise TypeError('eval substitution expects 1 argument') <NEW_LINE> <DEDENT> return cls, {'expression': data[0]} <NEW_LINE> <DEDENT> @property <NEW_LINE> def expression(self) -> List[Substitution]: <NEW_LINE> <INDENT> return self.__expression <NEW_LINE> <DEDENT> def describe(self) -> Text: <NEW_LINE> <INDENT> return 'PythonExpr({})'.format(' + '.join([sub.describe() for sub in self.expression])) <NEW_LINE> <DEDENT> def perform(self, context: LaunchContext) -> Text: <NEW_LINE> <INDENT> from ..utilities import perform_substitutions <NEW_LINE> return str(eval(perform_substitutions(context, self.expression), {}, math.__dict__)) | Substitution that can access contextual local variables.
The expression may contain Substitutions, but must return something that can
be converted to a string with `str()`.
It also may contain math symbols and functions. | 62598fa5e5267d203ee6b7ec |
@register_block(lookup_name='FULLY_CONNECTED_PYRAMID', init_args={}, enum_id=15) <NEW_LINE> class FullyConnectedPyramidBlock(Block): <NEW_LINE> <INDENT> def __init__(self, max_output_size=100, max_number_of_parameters=None, **kwargs): <NEW_LINE> <INDENT> self._max_number_of_parameters = max_number_of_parameters <NEW_LINE> self._max_output_size = max_output_size <NEW_LINE> super(FullyConnectedPyramidBlock, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def block_build(self, input_tensors, is_training, lengths=None, hparams=None): <NEW_LINE> <INDENT> input_tensor = input_tensors[-1] <NEW_LINE> net = tf.keras.layers.Flatten(name='flatten')(input_tensor) <NEW_LINE> max_output_size = self._max_output_size <NEW_LINE> if self._max_number_of_parameters: <NEW_LINE> <INDENT> max_output_size = min( self._max_output_size, self._max_number_of_parameters // net.get_shape()[1]) <NEW_LINE> <DEDENT> net = tf.keras.layers.Dense( min(max_output_size, max(net.get_shape()[1] // 2, 2)), name='dense')( net) <NEW_LINE> net = tf.nn.relu(net) <NEW_LINE> return input_tensors + [net] <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_input_order_important(self): <NEW_LINE> <INDENT> return False | A fully connected layer with leaky relu.
Output number of hidden nodes is equal to the input number of hidden nodes
divided by 2, with some restrictions:
- output number of hidden nodes is at least 2.
- output number of hidden nodes is at most max_output_size.
- The number of elements in the kernel matrix is at most:
max_number_of_parameters. | 62598fa54527f215b58e9dc3 |
class Server(models.Model): <NEW_LINE> <INDENT> key = models.OneToOneField(Key, on_delete=models.DO_NOTHING) <NEW_LINE> ip = models.GenericIPAddressField() <NEW_LINE> host_name = models.CharField(max_length=50) <NEW_LINE> current_map = models.ForeignKey('maps.Map', on_delete=models.DO_NOTHING) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = (('key'),) | Server model | 62598fa50c0af96317c56263 |
class MostPrevalentBagColorStrategy(pcs.PlayableColorStrategy): <NEW_LINE> <INDENT> def evaluate(self, options, board, game = None): <NEW_LINE> <INDENT> playlist = super().evaluate(options, board, game) <NEW_LINE> prevailingcolors = game.bag.colorcounts() <NEW_LINE> mincount = 20 <NEW_LINE> for color in prevailingcolors.keys(): <NEW_LINE> <INDENT> mincount = min(mincount, prevailingcolors[color]) <NEW_LINE> <DEDENT> evals = [] <NEW_LINE> for potentialplay in playlist: <NEW_LINE> <INDENT> color = potentialplay[1] <NEW_LINE> if color in prevailingcolors: <NEW_LINE> <INDENT> rankval = prevailingcolors[color] - mincount + 1 <NEW_LINE> modplay = potentialplay[0:3] + "_" + str(rankval) <NEW_LINE> evals.append(modplay) <NEW_LINE> <DEDENT> <DEDENT> evals.sort(key=strat.getcount2, reverse=True) <NEW_LINE> return(evals) <NEW_LINE> <DEDENT> def recommend(self, options, board, game = None): <NEW_LINE> <INDENT> evals = self.evaluate(options, board, game) <NEW_LINE> if len(evals) > 0: <NEW_LINE> <INDENT> return(evals[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (None) | MostPrevalentBagColorStrategy - choose the color that is most prevalent on
the whole board. Temper it with the PlayableColorStrategy. | 62598fa5435de62698e9bcd5 |
class GenericReference(fields.Field): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.document_class_choices = [] <NEW_LINE> choices = kwargs.pop("choices", None) <NEW_LINE> if choices: <NEW_LINE> <INDENT> for choice in choices: <NEW_LINE> <INDENT> if hasattr(choice, "_class_name"): <NEW_LINE> <INDENT> self.document_class_choices.append(choice._class_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.document_class_choices.append(choice) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> super(GenericReference, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def _deserialize(self, value, attr, data, **kwargs): <NEW_LINE> <INDENT> if not isinstance(value, dict) or not value.get("id") or not value.get("_cls"): <NEW_LINE> <INDENT> raise ValidationError("Need a dict with 'id' and '_cls' fields") <NEW_LINE> <DEDENT> doc_id = value["id"] <NEW_LINE> doc_cls_name = value["_cls"] <NEW_LINE> if ( self.document_class_choices and doc_cls_name not in self.document_class_choices ): <NEW_LINE> <INDENT> raise ValidationError( "Invalid _cls field `%s`, must be one of %s" % (doc_cls_name, self.document_class_choices) ) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> doc_cls = get_document(doc_cls_name) <NEW_LINE> <DEDENT> except NotRegistered: <NEW_LINE> <INDENT> raise ValidationError("Invalid _cls field `%s`" % doc_cls_name) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> doc = doc_cls.objects.get(pk=doc_id) <NEW_LINE> <DEDENT> except (doc_cls.DoesNotExist, MongoValidationError, ValueError, TypeError): <NEW_LINE> <INDENT> raise ValidationError("unknown document %s `%s`" % (doc_cls_name, value)) <NEW_LINE> <DEDENT> return doc <NEW_LINE> <DEDENT> def _serialize(self, value, attr, obj, **kwargs): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return missing <NEW_LINE> <DEDENT> return str(value.pk) if isinstance(value.pk, bson.ObjectId) else value.pk | Marshmallow custom field to map with :class Mongoengine.GenericReferenceField:
:param choices: List of Mongoengine document class (or class name) allowed
.. note:: Without `choices` param, this field allow to reference to
any document in the application which can be a security issue. | 62598fa563d6d428bbee2692 |
class VarNode(object): <NEW_LINE> <INDENT> def __init__(self, iden, channel_profile): <NEW_LINE> <INDENT> self.iden = iden <NEW_LINE> self.channel_profile = channel_profile <NEW_LINE> self.Res_size = len(self.channel_profile) <NEW_LINE> self.original_Thru = None <NEW_LINE> self.Thru = None <NEW_LINE> self.ReqNodes = None <NEW_LINE> self.NonReqNodes = None <NEW_LINE> self.ReqSize = None <NEW_LINE> self.connVNodes = None <NEW_LINE> self.NonconnVNodes = None <NEW_LINE> <DEDENT> def GenResReq(self, NumRes, DepthTree, Allow_DepthTree, MaxDepthTree, TTI): <NEW_LINE> <INDENT> self.req_size = 2**random.randint(DepthTree, MaxDepthTree) <NEW_LINE> self.req_weight=[] <NEW_LINE> col=[row[TTI] for row in self.channel_profile] <NEW_LINE> for i in range(0,self.Res_size,max(self.req_size,2**Allow_DepthTree)): <NEW_LINE> <INDENT> self.req_weight.append(sum(col[i:i+self.req_size])) <NEW_LINE> <DEDENT> self.max_ResReq_index, self.max_ResReq = max(enumerate(self.req_weight), key = operator.itemgetter(1)) <NEW_LINE> self.Thru = self.max_ResReq <NEW_LINE> self.original_Thru = self.max_ResReq <NEW_LINE> self.ResReq = bin(self.max_ResReq_index)[2:].zfill(int(math.log2(len(self.req_weight)))) <NEW_LINE> <DEDENT> def UpdateThru(self): <NEW_LINE> <INDENT> temp_NonconnVNodes = sorted(self.NonconnVNodes, key = lambda VarNode: len(VarNode.connVNodes), reverse=True) <NEW_LINE> norm_Glob_Thru = [] <NEW_LINE> for j in temp_NonconnVNodes: <NEW_LINE> <INDENT> temp_sub_Thru = [j.Thru] <NEW_LINE> for k in j.connVNodes: <NEW_LINE> <INDENT> if k in temp_NonconnVNodes: <NEW_LINE> <INDENT> temp_sub_Thru.append(k.Thru) <NEW_LINE> temp_NonconnVNodes.remove(k) <NEW_LINE> <DEDENT> <DEDENT> norm_Thru = max(temp_sub_Thru) <NEW_LINE> norm_Glob_Thru.append(norm_Thru) <NEW_LINE> <DEDENT> self.Glob_Thru = sum(norm_Glob_Thru) | The main node for scheduling entities, each object represents a flow | 62598fa5aad79263cf42e6b5 |
class TestOauth2Credentials(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 testOauth2Credentials(self): <NEW_LINE> <INDENT> pass | Oauth2Credentials unit test stubs | 62598fa58da39b475be030c2 |
class GruArtPanel(ga.AnagPanel): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> ga.AnagPanel.__init__(self, *args, **kwargs) <NEW_LINE> self.SetDbSetup( Azienda.BaseTab.tabelle[ Azienda.BaseTab.TABSETUP_TABLE_GRUART ] ) <NEW_LINE> self.SetDbOrderColumns(( ("Inventario", ('catart.codice', 'gruart.codice')), ("Codice", ('gruart.codice',)), ("Descrizione", ('gruart.descriz',)), )) <NEW_LINE> self._sqlrelcol = ", catart.id, catart.codice, catart.descriz" <NEW_LINE> self._sqlrelfrm = " INNER JOIN %s AS catart ON %s.id_catart=catart.id" % ( bt.TABNAME_CATART, bt.TABNAME_GRUART ) <NEW_LINE> self.db_tabprefix = "%s." % bt.TABNAME_GRUART <NEW_LINE> self._valfilters['catart'] = ['catart.codice', None, None] <NEW_LINE> self._hasfilters = True <NEW_LINE> self.db_report = "Gruppi merce" <NEW_LINE> <DEDENT> def InitAnagCard(self, parent): <NEW_LINE> <INDENT> p = wx.Panel( parent, -1) <NEW_LINE> wdr.GruArtCardFunc( p, True ) <NEW_LINE> return p <NEW_LINE> <DEDENT> def GetSearchResultsGrid(self, parent): <NEW_LINE> <INDENT> grid = GruArtSearchResultsGrid(parent, ga.ID_SEARCHGRID, self.db_tabname, self.GetSqlColumns()) <NEW_LINE> return grid <NEW_LINE> <DEDENT> def GetDbPrint(self): <NEW_LINE> <INDENT> db = adb.DbTable(self.db_tabname, writable=False) <NEW_LINE> db.AddOrder("catart.codice") <NEW_LINE> return db <NEW_LINE> <DEDENT> def GetSpecializedSearchPanel(self, parent): <NEW_LINE> <INDENT> p = wx.Panel(parent, -1) <NEW_LINE> wdr.GruArtSpecSearchFunc(p) <NEW_LINE> return p | Gestione tabella Gruppi merce. | 62598fa5435de62698e9bcd6 |
class DepDiamondPatchMid1(Package): <NEW_LINE> <INDENT> homepage = "http://www.example.com" <NEW_LINE> url = "http://www.example.com/patch-a-dependency-1.0.tar.gz" <NEW_LINE> version('1.0', '0123456789abcdef0123456789abcdef') <NEW_LINE> depends_on('patch', patches='mid1.patch') | Package that requires a patch on a dependency
W
/ \
X Y
\ /
Z
This is package X
| 62598fa532920d7e50bc5f37 |
class PushHelper(object): <NEW_LINE> <INDENT> def push_notification(self, title, content, appid, query, silent=None): <NEW_LINE> <INDENT> silent = silent or False <NEW_LINE> match_uids = self.find_match_uids(appid, query) <NEW_LINE> notification_id = self.save_notification(dict( title=title, content=content, appid=appid, silent=silent, query=query, ), dst_users_count=len(match_uids), ) <NEW_LINE> if not match_uids: <NEW_LINE> <INDENT> return notification_id, match_uids <NEW_LINE> <DEDENT> uids_list = [[] for it in range(0, len(kit.triggers))] <NEW_LINE> for uid in match_uids: <NEW_LINE> <INDENT> i = uid % len(uids_list) <NEW_LINE> uids_list[i].append(uid) <NEW_LINE> <DEDENT> for i, uids in enumerate(uids_list): <NEW_LINE> <INDENT> if not uids: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> kit.triggers[i].write_to_users([ [uids, dict( cmd=proto.EVT_NOTIFICATION, body=pack_data(dict( id=notification_id, title=title, content=content, silent=silent, )) )], ]) <NEW_LINE> <DEDENT> return notification_id, match_uids <NEW_LINE> <DEDENT> def find_match_uids(self, appid, query): <NEW_LINE> <INDENT> query_params = dict( appid=appid ) <NEW_LINE> alias = query.get('alias') <NEW_LINE> tags_or = query.get('tags_or') <NEW_LINE> if alias is not None: <NEW_LINE> <INDENT> query_params['alias'] = alias <NEW_LINE> <DEDENT> if tags_or: <NEW_LINE> <INDENT> query_params['$or'] = [] <NEW_LINE> for tags in tags_or: <NEW_LINE> <INDENT> query_params['$or'].append({ "tags": { "$all": tags } }) <NEW_LINE> <DEDENT> <DEDENT> user_table = kit.mongo_client.get_default_database()[current_app.config['MONGO_TB_USER']] <NEW_LINE> users = user_table.find(query_params, { "uid": 1 }) <NEW_LINE> return [user['uid'] for user in users] <NEW_LINE> <DEDENT> def save_notification(self, src_notification, dst_users_count): <NEW_LINE> <INDENT> notification_table = kit.mongo_client.get_default_database()[current_app.config['MONGO_TB_NOTIFICATION']] <NEW_LINE> notification_id = alloc_autoid('notification') <NEW_LINE> notification = dict( id=notification_id, create_time=datetime.datetime.now(), stat=dict( dst=dst_users_count, recv=0, click=0, ) ) <NEW_LINE> notification.update(src_notification) <NEW_LINE> notification_table.save(notification) <NEW_LINE> return notification_id | 发送消息的helper | 62598fa54428ac0f6e658402 |
class APIImplementationError(PlugError): <NEW_LINE> <INDENT> pass | Raise when an API is defined incorrectly. | 62598fa5009cb60464d01405 |
class LogoutHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.clear_cookie('uid') | Logout? duh | 62598fa54f88993c371f047a |
class PyQtHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> logging.Handler.__init__(self) <NEW_LINE> self.info_handler = None <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> self.format(record) <NEW_LINE> message = record.msg <NEW_LINE> if record.levelno > logging.WARNING: <NEW_LINE> <INDENT> extra = translate_error(message) <NEW_LINE> if record.exc_info: <NEW_LINE> <INDENT> if not extra: <NEW_LINE> <INDENT> extra = translate_error(repr(record.exc_info[1])) <NEW_LINE> <DEDENT> detail = logging._defaultFormatter.formatException(record.exc_info) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> detail = None <NEW_LINE> <DEDENT> if hasattr(record, "worker_name"): <NEW_LINE> <INDENT> title = "Error on {}".format(record.worker_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> title = "DEXBot Error" <NEW_LINE> <DEDENT> idle_add(show_dialog, title, message, extra, detail) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.info_handler and hasattr(record, "worker_name"): <NEW_LINE> <INDENT> idle_add(self.info_handler, record.worker_name, record.levelno, message) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def set_info_handler(self, info_handler): <NEW_LINE> <INDENT> self.info_handler = info_handler | Logging handler for Py Qt events.
Based on Vinay Sajip's DBHandler class (http://www.red-dove.com/python_logging.html) | 62598fa58e7ae83300ee8f82 |
class DSMREntity(Entity): <NEW_LINE> <INDENT> def __init__(self, name, obis, config): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._obis = obis <NEW_LINE> self._config = config <NEW_LINE> self.telegram = {} <NEW_LINE> <DEDENT> def get_dsmr_object_attr(self, attribute): <NEW_LINE> <INDENT> if self._obis not in self.telegram: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> dsmr_object = self.telegram[self._obis] <NEW_LINE> return getattr(dsmr_object, attribute, None) <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> if "Sags" in self._name or "Swells" in self.name: <NEW_LINE> <INDENT> return ICON_SWELL_SAG <NEW_LINE> <DEDENT> if "Failure" in self._name: <NEW_LINE> <INDENT> return ICON_POWER_FAILURE <NEW_LINE> <DEDENT> if "Power" in self._name: <NEW_LINE> <INDENT> return ICON_POWER <NEW_LINE> <DEDENT> if "Gas" in self._name: <NEW_LINE> <INDENT> return ICON_GAS <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> value = self.get_dsmr_object_attr("value") <NEW_LINE> if self._obis == obis_ref.ELECTRICITY_ACTIVE_TARIFF: <NEW_LINE> <INDENT> return self.translate_tariff(value, self._config[CONF_DSMR_VERSION]) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> value = round(float(value), self._config[CONF_PRECISION]) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if value is not None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return self.get_dsmr_object_attr("unit") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def translate_tariff(value, dsmr_version): <NEW_LINE> <INDENT> if dsmr_version in ("5B",): <NEW_LINE> <INDENT> if value == "0001": <NEW_LINE> <INDENT> value = "0002" <NEW_LINE> <DEDENT> elif value == "0002": <NEW_LINE> <INDENT> value = "0001" <NEW_LINE> <DEDENT> <DEDENT> if value == "0002": <NEW_LINE> <INDENT> return "normal" <NEW_LINE> <DEDENT> if value == "0001": <NEW_LINE> <INDENT> return "low" <NEW_LINE> <DEDENT> return None | Entity reading values from DSMR telegram. | 62598fa5e5267d203ee6b7ed |
class SimpleStitchAssignmentsLocal(SimpleStitchAssignmentsBase, LocalTask): <NEW_LINE> <INDENT> pass | SimpleStitchAssignments on local machine | 62598fa5a79ad16197769f43 |
class RandomGenerator(object): <NEW_LINE> <INDENT> def __init__(self, total=100, labeled=True, fraud_n=2): <NEW_LINE> <INDENT> self.total = total <NEW_LINE> self.labeled = labeled <NEW_LINE> self.fraud_n = fraud_n <NEW_LINE> <DEDENT> def generate_data(self): <NEW_LINE> <INDENT> data = [] <NEW_LINE> num_predictors = len(basic_features_list)-1 <NEW_LINE> for tr_index in xrange(0, self.total): <NEW_LINE> <INDENT> t = Transaction() <NEW_LINE> for feat_index in xrange(0, num_predictors): <NEW_LINE> <INDENT> f = Feature() <NEW_LINE> f.description = basic_features_list[feat_index]['description'] <NEW_LINE> f.kind = basic_features_list[feat_index]['kind'] <NEW_LINE> f.name = basic_features_list[feat_index]['name'] <NEW_LINE> f.position = basic_features_list[feat_index]['position'] <NEW_LINE> f.is_target = basic_features_list[feat_index]['is_target'] <NEW_LINE> if f.kind == 1: <NEW_LINE> <INDENT> f.value = np.random.randint(2, size=1) <NEW_LINE> <DEDENT> elif f.kind == 2: <NEW_LINE> <INDENT> f.value = np.random.rand()*1000 <NEW_LINE> <DEDENT> elif f.kind == 3: <NEW_LINE> <INDENT> min = 1 <NEW_LINE> max = 5 <NEW_LINE> f.value = (np.random.rand() * (max - min) ) + min <NEW_LINE> <DEDENT> t.add_feature(f) <NEW_LINE> <DEDENT> data.append(t) <NEW_LINE> <DEDENT> return data | Random generator class.
This class can be used to generate
random transaction data either annotated
or not. | 62598fa5cb5e8a47e493c0e8 |
class FileMonitorProxy(object): <NEW_LINE> <INDENT> monitor = None <NEW_LINE> def __init__(self, logger, ignore_files=None): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.change_event = threading.Event() <NEW_LINE> self.changed_paths = set() <NEW_LINE> self.ignore_files = [ re.compile(fnmatch.translate(x)) for x in set(ignore_files or []) ] <NEW_LINE> <DEDENT> def add_path(self, path): <NEW_LINE> <INDENT> for p in glob(path, recursive=True) or [path]: <NEW_LINE> <INDENT> if not any(x.match(p) for x in self.ignore_files): <NEW_LINE> <INDENT> self.monitor.add_path(p) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.monitor.start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.monitor.stop() <NEW_LINE> self.monitor.join() <NEW_LINE> <DEDENT> def file_changed(self, path): <NEW_LINE> <INDENT> if path not in self.changed_paths: <NEW_LINE> <INDENT> self.changed_paths.add(path) <NEW_LINE> self.logger.info('%s changed; reloading ...' % (path,)) <NEW_LINE> <DEDENT> self.set_changed() <NEW_LINE> <DEDENT> def is_changed(self): <NEW_LINE> <INDENT> return self.change_event.is_set() <NEW_LINE> <DEDENT> def wait_for_change(self, timeout=None): <NEW_LINE> <INDENT> return self.change_event.wait(timeout) <NEW_LINE> <DEDENT> def clear_changes(self): <NEW_LINE> <INDENT> self.change_event.clear() <NEW_LINE> self.changed_paths.clear() <NEW_LINE> <DEDENT> def set_changed(self): <NEW_LINE> <INDENT> self.change_event.set() | Wrap an :class:`hupper.interfaces.IFileMonitor` into an object that
exposes a thread-safe interface back to the reloader to detect
when it should reload. | 62598fa5baa26c4b54d4f192 |
class TestASAPCurrInfoCurrentMain(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> ca_patcher = mock.patch( "siriuspy.currinfo.main._ClientArch", autospec=True) <NEW_LINE> self.addCleanup(ca_patcher.stop) <NEW_LINE> self.mock_ca = ca_patcher.start() <NEW_LINE> self.mock_ca.return_value.getData.return_value = None <NEW_LINE> pv_patcher = mock.patch( "siriuspy.currinfo.main._PV", autospec=True) <NEW_LINE> self.addCleanup(pv_patcher.stop) <NEW_LINE> self.mock_pv = pv_patcher.start() <NEW_LINE> self.mock_pv.return_value.connected = False <NEW_LINE> self.app = SICurrInfoApp() <NEW_LINE> <DEDENT> def test_public_interface(self): <NEW_LINE> <INDENT> valid = util.check_public_interface_namespace( _CurrInfoApp, PUB_INTERFACE_BASE, print_flag=True) <NEW_LINE> self.assertTrue(valid) <NEW_LINE> valid = util.check_public_interface_namespace( SICurrInfoApp, PUB_INTERFACE_SI, print_flag=True) <NEW_LINE> self.assertTrue(valid) <NEW_LINE> <DEDENT> def test_write_DCCTFltCheck(self): <NEW_LINE> <INDENT> self.app.write( 'SI-Glob:AP-CurrInfo:DCCTFltCheck-Sel', Const.DCCTFltCheck.On) <NEW_LINE> self.assertEqual(self.app._dcctfltcheck_mode, Const.DCCTFltCheck.On) <NEW_LINE> <DEDENT> def test_write_DCCT_FltCheckOn(self): <NEW_LINE> <INDENT> self.app._dcctfltcheck_mode = Const.DCCTFltCheck.On <NEW_LINE> init_status = self.app._dcct_mode <NEW_LINE> self.app.write('SI-Glob:AP-CurrInfo:DCCT-Sel', Const.DCCT.DCCT13C4) <NEW_LINE> self.app.write('SI-Glob:AP-CurrInfo:DCCT-Sel', Const.DCCT.DCCT14C4) <NEW_LINE> end_status = self.app._dcct_mode <NEW_LINE> self.assertEqual(init_status, end_status) <NEW_LINE> <DEDENT> def test_write_DCCT_FltCheckOff(self): <NEW_LINE> <INDENT> self.app.write( 'SI-Glob:AP-CurrInfo:DCCTFltCheck-Sel', Const.DCCTFltCheck.Off) <NEW_LINE> self.app.write('SI-Glob:AP-CurrInfo:DCCT-Sel', Const.DCCT.DCCT13C4) <NEW_LINE> self.assertEqual(self.app._dcct_mode, Const.DCCT.DCCT13C4) | Test AS-AP-CurrInfo Soft IOC. | 62598fa5d58c6744b42dc245 |
class CFSRData: <NEW_LINE> <INDENT> def __init__(self,basefolder): <NEW_LINE> <INDENT> self.basefolder=basefolder <NEW_LINE> files={} <NEW_LINE> files['st'] = os.path.join(basefolder,'ST/*.nc') <NEW_LINE> files['rh'] = os.path.join(basefolder,'RH/*.nc') <NEW_LINE> files['sp'] = os.path.join(basefolder,'SP/*.nc') <NEW_LINE> files['pr'] = os.path.join(basefolder,'PR/*.nc') <NEW_LINE> files['rad'] = os.path.join(basefolder,'RAD/*.nc') <NEW_LINE> files['uv'] = os.path.join(basefolder,'UV/*.nc') <NEW_LINE> files['cc'] = os.path.join(basefolder,'CC/*.nc') <NEW_LINE> self.files=files <NEW_LINE> <DEDENT> def data(self,date0=False,date1=False,quiet=True): <NEW_LINE> <INDENT> res=cfsr_file_data(self.files,quiet=quiet) <NEW_LINE> time=res['time'] <NEW_LINE> if date0: <NEW_LINE> <INDENT> date0=dateu.parse_date(date0) <NEW_LINE> i,=np.where(time>=date0) <NEW_LINE> i=i[0] <NEW_LINE> <DEDENT> else: i=0 <NEW_LINE> if date1: <NEW_LINE> <INDENT> date1=dateu.parse_date(date1) <NEW_LINE> j,=np.where(time<=date1) <NEW_LINE> j=j[-1] <NEW_LINE> <DEDENT> else: j=len(time) <NEW_LINE> if date0 or date1: <NEW_LINE> <INDENT> for k in res.keys(): <NEW_LINE> <INDENT> if k =='time': <NEW_LINE> <INDENT> res[k]=res[k][i:j+1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res[k].data=res[k].data[i:j+1,...] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return res | CFSR data extraction | 62598fa526068e7796d4c83a |
class Abbreviator: <NEW_LINE> <INDENT> def __init__(self, target_length: int): <NEW_LINE> <INDENT> if target_length < 1: <NEW_LINE> <INDENT> raise ValueError("target_length must be greater than 0.") <NEW_LINE> <DEDENT> self.target_len = target_length <NEW_LINE> <DEDENT> def abbreviate(self, input_sent) -> str: <NEW_LINE> <INDENT> current_length = len(input_sent) <NEW_LINE> if current_length <= self.target_len: <NEW_LINE> <INDENT> return input_sent <NEW_LINE> <DEDENT> words = {word: i for i, word in enumerate(input_sent.split())} <NEW_LINE> result = [word for word in words] <NEW_LINE> while current_length > self.target_len: <NEW_LINE> <INDENT> sorted_words = [word for word in sorted(words.keys(), key=len, reverse=True)] <NEW_LINE> longest_word = sorted_words[0] <NEW_LINE> if len(longest_word) == 1: <NEW_LINE> <INDENT> return self._re_assemble(words, result) <NEW_LINE> <DEDENT> words[longest_word[:-1]] = words.pop(longest_word) <NEW_LINE> current_length -= 1 <NEW_LINE> if current_length <= self.target_len: <NEW_LINE> <INDENT> return self._re_assemble(words, result) <NEW_LINE> <DEDENT> for k, v in words.items(): <NEW_LINE> <INDENT> result[v] = k <NEW_LINE> <DEDENT> <DEDENT> return ' '.join(result) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _re_assemble(words, result): <NEW_LINE> <INDENT> for k, v in words.items(): <NEW_LINE> <INDENT> result[v] = k <NEW_LINE> <DEDENT> return ' '.join(result) | Abbreviates strings to target_length | 62598fa5aad79263cf42e6b6 |
class ResetStampView(grok.View): <NEW_LINE> <INDENT> grok.name('reset_syncstamp') <NEW_LINE> grok.context(IPloneSiteRoot) <NEW_LINE> grok.require('cmf.ManagePortal') <NEW_LINE> def render(self): <NEW_LINE> <INDENT> set_remote_import_stamp(self.context) <NEW_LINE> IStatusMessage(self.context.REQUEST).addStatusMessage( u"Successfully reset the Syncstamp on every client", "info") <NEW_LINE> url = self.context.REQUEST.environ.get('HTTP_REFERER') <NEW_LINE> if not url: <NEW_LINE> <INDENT> url = self.context.absolute_url() <NEW_LINE> <DEDENT> return self.context.REQUEST.RESPONSE.redirect(url) | A view wich reset the actual syncstamp with a actual stamp
on every client registered in the ogds | 62598fa5009cb60464d01406 |
class ModuleConfig: <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.name = data['name'] <NEW_LINE> self.description = data['description'] <NEW_LINE> self.variables = data['config'] <NEW_LINE> self._data = data | Config class for each module: plugins and adapters | 62598fa5f548e778e596b485 |
class AddForm(base.AddForm): <NEW_LINE> <INDENT> form_fields = form.Fields(IPopupForm) <NEW_LINE> form_fields['target_form'].custom_widget = UberSelectionWidget <NEW_LINE> def create(self, data): <NEW_LINE> <INDENT> return Assignment(**data) | Portlet add form.
This is registered in configure.zcml. The form_fields variable tells
zope.formlib which fields to display. The create() method actually
constructs the assignment that is being added. | 62598fa5cc0a2c111447aef0 |
class MetricAlertResourceCollection(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[MetricAlertResource]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(MetricAlertResourceCollection, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) | Represents a collection of alert rule resources.
:param value: the values for the alert rule resources.
:type value: list[~$(python-base-namespace).v2018_03_01.models.MetricAlertResource] | 62598fa50a50d4780f7052be |
class AgentReroProvider(BaseProvider): <NEW_LINE> <INDENT> pid_type = 'agrero' <NEW_LINE> pid_identifier = AgentReroIdentifier.__tablename__ <NEW_LINE> pid_provider = None <NEW_LINE> default_status = PIDStatus.REGISTERED | Rero identifier provider. | 62598fa5cc0a2c111447aef1 |
class Tile: <NEW_LINE> <INDENT> def __init__(self, color=0, character=" "): <NEW_LINE> <INDENT> self.character = character <NEW_LINE> self.color = color | Super-class that represents the basic information for an object of the grid | 62598fa58a43f66fc4bf205e |
class GensimTopicSumModel(object): <NEW_LINE> <INDENT> def __init__(self, tfidf_model_name, word_ids_loc, tfidf_model_loc, tokenizer=lambda x: x.split(), lazy_Load=True): <NEW_LINE> <INDENT> self.tfidf_model = load_gensim_tfidf_model(tfidf_model_name, word_ids_loc, tfidf_model_loc, tokenizer, lazy_Load) <NEW_LINE> self.model=None <NEW_LINE> <DEDENT> def _purge_model(self, purge_tfidf=True): <NEW_LINE> <INDENT> self.model = None <NEW_LINE> if purge_tfidf: <NEW_LINE> <INDENT> self.tfidf_model._purge_model() <NEW_LINE> <DEDENT> <DEDENT> def _convert_to_numpy_array(self, tuples): <NEW_LINE> <INDENT> vec = np.zeros(self._get_model().num_topics) <NEW_LINE> for i, val in tuples: <NEW_LINE> <INDENT> vec[i] = val <NEW_LINE> <DEDENT> return vec <NEW_LINE> <DEDENT> @lru_cache(maxsize=_cache_size) <NEW_LINE> def get_topics(self, document): <NEW_LINE> <INDENT> tfidf_vector = self.tfidf_model.get_tfidf_vector(document) <NEW_LINE> topic_scores = self._get_model()[tfidf_vector] <NEW_LINE> return topic_scores <NEW_LINE> <DEDENT> def get_vector(self,document): <NEW_LINE> <INDENT> tuples = self.get_topics(document) <NEW_LINE> vector = self._convert_to_numpy_array(tuples) <NEW_LINE> return vector <NEW_LINE> <DEDENT> def get_similarity(self, doc1, doc2): <NEW_LINE> <INDENT> return cossim(self.get_topics(doc1), self.get_topics(doc2)) | A convenience class for unify Gensim topic summarization models due
to their similar syntax.
This model contains no code for actually initializing topic
summarization models themselves. That's the responsibility of children
classes. As such, should never create an instance of this class
directly, only through inheritance. | 62598fa53539df3088ecc196 |
class JCYLContextLoadTestCase(WithContext, ContextLoadTests, unittest.TestCase): <NEW_LINE> <INDENT> def create_app(self): <NEW_LINE> <INDENT> app = Flask(__name__, template_folder=u'templates') <NEW_LINE> app.config.from_object(CONFIG) <NEW_LINE> app.register_blueprint(blueprint) <NEW_LINE> Locales(app) <NEW_LINE> Locales.context_loader = json_caching_yaml_loader <NEW_LINE> return app | Test Strategies
- each template returns a string containing its path. This way I can easily confirm which template rendered by simply checking the returned string. | 62598fa585dfad0860cbf9e5 |
class V1BuildConfigStatus(object): <NEW_LINE> <INDENT> operations = [ ] <NEW_LINE> swagger_types = { 'last_version': 'int' } <NEW_LINE> attribute_map = { 'last_version': 'lastVersion' } <NEW_LINE> def __init__(self, last_version=None): <NEW_LINE> <INDENT> self._last_version = last_version <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_version(self): <NEW_LINE> <INDENT> return self._last_version <NEW_LINE> <DEDENT> @last_version.setter <NEW_LINE> def last_version(self, last_version): <NEW_LINE> <INDENT> self._last_version = last_version <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(V1BuildConfigStatus.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa5a8ecb033258710f1 |
class X12(object): <NEW_LINE> <INDENT> def __init__(self, givenfile): <NEW_LINE> <INDENT> self.filename = givenfile <NEW_LINE> self.readable = False <NEW_LINE> self.raw = '' <NEW_LINE> self.edix12 = False <NEW_LINE> self.fieldsep = '' <NEW_LINE> self.segsep = '' <NEW_LINE> self.segments = [] <NEW_LINE> self.isafile = isfile(self.filename) <NEW_LINE> if self.isafile: <NEW_LINE> <INDENT> if access(self.filename, R_OK): <NEW_LINE> <INDENT> self.readable = True <NEW_LINE> with open(self.filename, 'r') as onefile: <NEW_LINE> <INDENT> self.raw = onefile.read() <NEW_LINE> <DEDENT> if self.raw[:3] == "ISA": <NEW_LINE> <INDENT> self.edix12 = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.edix12 = False <NEW_LINE> self.fieldsep = '' <NEW_LINE> self.segsep = '' <NEW_LINE> self.segments = [] <NEW_LINE> <DEDENT> if self.edix12: <NEW_LINE> <INDENT> self.fieldsep = self.raw[3] <NEW_LINE> pos = self.raw.find("GS", 105) <NEW_LINE> lastfieldsep = self.raw.rfind(self.fieldsep, 0, pos) <NEW_LINE> self.segsep = self.raw[lastfieldsep+2] <NEW_LINE> self.segments = self.raw.split(self.segsep) <NEW_LINE> self.segments = '\t'.join(self.segments).replace('\r', '').split('\t') <NEW_LINE> self.segments = '\t'.join(self.segments).replace('\n', '').split('\t') <NEW_LINE> if '' in self.segments: <NEW_LINE> <INDENT> self.segments.remove('') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if not self.isafile: <NEW_LINE> <INDENT> return "Not a file: %s" % self.filename <NEW_LINE> <DEDENT> if not self.readable: <NEW_LINE> <INDENT> return "File not readable: %s" % self.filename <NEW_LINE> <DEDENT> if not self.edix12: <NEW_LINE> <INDENT> return "Not an X12 file: %s" % self.filename <NEW_LINE> <DEDENT> tabs = 0 <NEW_LINE> prettyx12 = '' <NEW_LINE> for seg in self.segments: <NEW_LINE> <INDENT> if seg[:2] == "GS" or seg[:2] == "ST": <NEW_LINE> <INDENT> tabs += 1 <NEW_LINE> <DEDENT> if seg[:2] == "SE": <NEW_LINE> <INDENT> tabs -= 1 <NEW_LINE> <DEDENT> prettyx12 = prettyx12 + " " * (tabs*4) + seg + self.segsep <NEW_LINE> if self.segsep != '\n': <NEW_LINE> <INDENT> prettyx12 = prettyx12 + '\n' <NEW_LINE> <DEDENT> if seg[:2] == "ST": <NEW_LINE> <INDENT> tabs += 1 <NEW_LINE> <DEDENT> if seg[:2] == "GE" or seg[:2] == "SE": <NEW_LINE> <INDENT> tabs -= 1 <NEW_LINE> <DEDENT> <DEDENT> return prettyx12 | Class for an X12 file requires the path/filename.
Replaces print of object with a more human readable X12
broken into one segment per line.
attibutes:
filename - the file read
readable - if the file is readable
raw - the full unformatted X12
edix12 - Boolean: True if it appears to be X12 structure
fieldsep - the field separator - commonly '*'
segsep - the segment separator - commonly '~'
segments - list of segments with separator removed | 62598fa591f36d47f2230e14 |
class SignupForm(FlaskForm): <NEW_LINE> <INDENT> email = StringField('Email', validators=[ DataRequired('Please enter your email'), Email('Please enter your email')]) <NEW_LINE> password = PasswordField('Password', validators=[ DataRequired('Please enter your password'), Length(min=4, message='Password must be 4 or more characters')]) <NEW_LINE> name = StringField('Name', validators=[ DataRequired('Please enter your first name')]) <NEW_LINE> deposit = DecimalField('Deposit Amount', validators=[ DataRequired('Please add a deposit amount'), NumberRange(min=0, message='Please enter a valid number')]) <NEW_LINE> submit = SubmitField('Sign up') | Defines the sign up form fields | 62598fa54a966d76dd5eedc5 |
class CalendarQueue(PriorityQueue): <NEW_LINE> <INDENT> def _put(self, item): <NEW_LINE> <INDENT> if item not in self.queue: <NEW_LINE> <INDENT> return super()._put(item) <NEW_LINE> <DEDENT> return None | Priority Queue for holding calendar events in chronological order | 62598fa599cbb53fe6830db7 |
class PaasStrategy(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.CrowdID = None <NEW_LINE> self.Items = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.CrowdID = params.get("CrowdID") <NEW_LINE> if params.get("Items") is not None: <NEW_LINE> <INDENT> self.Items = [] <NEW_LINE> for item in params.get("Items"): <NEW_LINE> <INDENT> obj = PaasStrategyItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Items.append(obj) | 短信发送人群包策略
| 62598fa5e1aae11d1e7ce794 |
class GlobalCoin(Bitcoin): <NEW_LINE> <INDENT> name = 'globalcoin' <NEW_LINE> symbols = ('GLC', ) <NEW_LINE> seeds = ("ip 54.252.196.5", "ip 52.24.129.149", ) <NEW_LINE> port = 55789 <NEW_LINE> message_start = b'\xe4\xe8\xe9\xe5' <NEW_LINE> base58_prefixes = { 'PUBKEY_ADDR': 11, 'SCRIPT_ADDR': 8, 'SECRET_KEY': 139 } | Class with all the necessary CryptoBullion network information based on
https://github.com/cryptogenicbonds/cryptobullion-cbx/blob/master/src/net.cpp
(date of access: 02/12/2018) | 62598fa599fddb7c1ca62d59 |
class GetPartitions(IcontrolCommand): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> ic = self.api <NEW_LINE> return ic.Management.Partition.get_partition_list() | get the full partition list | 62598fa501c39578d7f12c62 |
class CronTriggers(resource.Resource): <NEW_LINE> <INDENT> cron_triggers = [CronTrigger] <NEW_LINE> @classmethod <NEW_LINE> def sample(cls): <NEW_LINE> <INDENT> return cls(cron_triggers=[CronTrigger.sample()]) | A collection of cron triggers. | 62598fa51f5feb6acb162b04 |
class GeneralizedRCNN(nn.Module): <NEW_LINE> <INDENT> def __init__(self, cfg): <NEW_LINE> <INDENT> super(GeneralizedRCNN, self).__init__() <NEW_LINE> self.backbone = build_backbone(cfg) <NEW_LINE> self.rpn = build_rpn(cfg) <NEW_LINE> self.roi_heads = build_roi_heads(cfg) <NEW_LINE> self.return_feats = cfg.MODEL.ROI_BOX_HEAD.RETURN_FC_FEATS <NEW_LINE> <DEDENT> def forward(self, images, targets=None, input_boxes=None): <NEW_LINE> <INDENT> if self.training and targets is None: <NEW_LINE> <INDENT> raise ValueError("In training mode, targets should be passed") <NEW_LINE> <DEDENT> images = to_image_list(images) <NEW_LINE> features = self.backbone(images.tensors) <NEW_LINE> proposals, proposal_losses = self.rpn(images, features, targets) <NEW_LINE> if input_boxes is not None: <NEW_LINE> <INDENT> assert not self.training <NEW_LINE> load_boxes_for_feature_extraction(proposals, input_boxes) <NEW_LINE> <DEDENT> if self.roi_heads: <NEW_LINE> <INDENT> x, result, detector_losses = self.roi_heads(features, proposals, targets) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = features <NEW_LINE> result = proposals <NEW_LINE> detector_losses = {} <NEW_LINE> <DEDENT> if self.training: <NEW_LINE> <INDENT> losses = {} <NEW_LINE> losses.update(detector_losses) <NEW_LINE> losses.update(proposal_losses) <NEW_LINE> return losses <NEW_LINE> <DEDENT> if self.return_feats and not self.training: <NEW_LINE> <INDENT> return (x, result) <NEW_LINE> <DEDENT> return result | Main class for Generalized R-CNN. Currently supports boxes and masks.
It consists of three main parts:
- backbone
= rpn
- heads: takes the features + the proposals from the RPN and computes
detections / masks from it. | 62598fa53317a56b869be4bb |
class NMEASentenceTests(NMEAReceiverSetup, TestCase): <NEW_LINE> <INDENT> def test_repr(self): <NEW_LINE> <INDENT> sentencesWithExpectedRepr = [ (GPGSA, "<NMEASentence (GPGSA) {" "dataMode: A, " "fixType: 3, " "horizontalDilutionOfPrecision: 1.0, " "positionDilutionOfPrecision: 1.7, " "usedSatellitePRN_0: 19, " "usedSatellitePRN_1: 28, " "usedSatellitePRN_2: 14, " "usedSatellitePRN_3: 18, " "usedSatellitePRN_4: 27, " "usedSatellitePRN_5: 22, " "usedSatellitePRN_6: 31, " "usedSatellitePRN_7: 39, " "verticalDilutionOfPrecision: 1.3" "}>"), ] <NEW_LINE> for sentence, expectedRepr in sentencesWithExpectedRepr: <NEW_LINE> <INDENT> self.protocol.lineReceived(sentence) <NEW_LINE> received = self.receiver.receivedSentence <NEW_LINE> self.assertEqual(repr(received), expectedRepr) | Tests for L{nmea.NMEASentence} objects. | 62598fa567a9b606de545eae |
class NetWorkTester(threading.Thread): <NEW_LINE> <INDENT> queue = None <NEW_LINE> broadcast = None <NEW_LINE> is_gfw_open = False <NEW_LINE> test_ips = PING_TEST_IPS <NEW_LINE> def __init__(self, queue, broadcast): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.queue = queue <NEW_LINE> self.broadcast = broadcast <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> time.sleep(random.randint(30, 120)) <NEW_LINE> text = 'Network Status: ' <NEW_LINE> for name, ip in self.test_ips.items(): <NEW_LINE> <INDENT> last_time = ping.do_one(ip, 3) <NEW_LINE> last_time = int(last_time * 1000) if last_time else '-' <NEW_LINE> text += '{0}: {1}ms, '.format(name, last_time) <NEW_LINE> <DEDENT> self.broadcast.put(text[:-2]) | 网络测试 | 62598fa54428ac0f6e658404 |
class InterfaceCollection(BaseIterable): <NEW_LINE> <INDENT> def __init__(self, engine, rel='interfaces'): <NEW_LINE> <INDENT> self._engine = engine <NEW_LINE> self._rel = rel <NEW_LINE> self.href = engine.get_relation(rel, UnsupportedInterfaceType) <NEW_LINE> super(InterfaceCollection, self).__init__(InterfaceEditor(engine)) <NEW_LINE> <DEDENT> def get(self, interface_id): <NEW_LINE> <INDENT> return self.items.get(interface_id) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for interface in super(InterfaceCollection, self).__iter__(): <NEW_LINE> <INDENT> if self._rel != 'interfaces': <NEW_LINE> <INDENT> if interface.typeof == self._rel: <NEW_LINE> <INDENT> yield interface <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield interface <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __contains__(self, interface_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.get(interface_id) <NEW_LINE> <DEDENT> except InterfaceNotFound: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def update_or_create(self, interface): <NEW_LINE> <INDENT> created, modified = (False, False) <NEW_LINE> try: <NEW_LINE> <INDENT> intf = self._engine.interface.get( interface.interface_id) <NEW_LINE> interface, updated = intf.update_interface(interface) <NEW_LINE> if updated: <NEW_LINE> <INDENT> modified = True <NEW_LINE> <DEDENT> <DEDENT> except InterfaceNotFound: <NEW_LINE> <INDENT> self._engine.add_interface(interface) <NEW_LINE> interface = self._engine.interface.get(interface.interface_id) <NEW_LINE> created = True <NEW_LINE> <DEDENT> return interface, modified, created | An interface collection provides top level search capabilities
to iterate or get interfaces of the specified type. This also
delegates all 'add' methods of an interface to the interface type
specified. Collections are returned from an engine reference and
not called directly.
For example, you can use this to obtain all interfaces of a given
type from an engine::
>>> for interface in engine.interface.all():
... print(interface.name, interface.addresses)
('Tunnel Interface 2001', [('169.254.9.22', '169.254.9.20/30', '2001')])
('Tunnel Interface 2000', [('169.254.11.6', '169.254.11.4/30', '2000')])
('Interface 2', [('192.168.1.252', '192.168.1.0/24', '2')])
('Interface 1', [('10.0.0.254', '10.0.0.0/24', '1')])
('Interface 0', [('172.18.1.254', '172.18.1.0/24', '0')])
Or only physical interface types::
for interface in engine.physical_interfaces:
print(interface)
Get a specific interface directly::
engine.interface.get(10)
Or use delegation to create interfaces::
engine.physical_interface.add(2)
engine.physical_interface.add_layer3_interface(....)
...
.. note:: This can raise UnsupportedInterfaceType for unsupported engine
types based on the interface context. | 62598fa54f88993c371f047b |
class Game(ndb.Model): <NEW_LINE> <INDENT> target = ndb.StringProperty(required=True) <NEW_LINE> letters_guessed = ndb.StringProperty(required=True, default='') <NEW_LINE> correct_letters = ndb.StringProperty(required=True, default='') <NEW_LINE> guessed_word = ndb.StringProperty(required=True) <NEW_LINE> attempts_allowed = ndb.IntegerProperty(required=True, default=13) <NEW_LINE> attempts_remaining = ndb.IntegerProperty(required=True, default=13) <NEW_LINE> game_over = ndb.BooleanProperty(required=True, default=False) <NEW_LINE> history = ndb.StringProperty(repeated=True) <NEW_LINE> user = ndb.KeyProperty(required=True, kind='User') <NEW_LINE> @classmethod <NEW_LINE> def new_game(cls, user): <NEW_LINE> <INDENT> words = ["cat", "dog", "bat", "dosa", "dinosaur", "biscuits"] <NEW_LINE> target_word = random.choice(words) <NEW_LINE> blank_string = "_" * len(target_word) <NEW_LINE> game = Game(user=user, target=target_word, guessed_word=blank_string) <NEW_LINE> game.put() <NEW_LINE> return game <NEW_LINE> <DEDENT> def to_form(self, message): <NEW_LINE> <INDENT> form = GameForm() <NEW_LINE> form.urlsafe_key = self.key.urlsafe() <NEW_LINE> form.user_name = self.user.get().name <NEW_LINE> form.guessed_word = self.guessed_word <NEW_LINE> form.letters_guessed = self.letters_guessed <NEW_LINE> form.attempts_allowed = self.attempts_allowed <NEW_LINE> form.attempts_remaining = self.attempts_remaining <NEW_LINE> form.game_over = self.game_over <NEW_LINE> form.history = self.history <NEW_LINE> form.message = message <NEW_LINE> return form <NEW_LINE> <DEDENT> def end_game(self, won=False): <NEW_LINE> <INDENT> self.game_over = True <NEW_LINE> self.put() <NEW_LINE> if won == True: <NEW_LINE> <INDENT> self.user.get().add_win() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.user.get().add_loss() <NEW_LINE> <DEDENT> score = Score(user=self.user, date=date.today(), won=won, guesses=self.attempts_allowed - self.attempts_remaining) <NEW_LINE> score.put() | Game object | 62598fa556ac1b37e63020cf |
class DecoThree(): <NEW_LINE> <INDENT> def __init__(self, wrapped_function): <NEW_LINE> <INDENT> self.__name__ = wrapped_function.__name__ <NEW_LINE> self._wrapped = wrapped_function <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> print("GREETINGS from deco_three!") <NEW_LINE> result = self._wrapped(*args, **kwargs) <NEW_LINE> return result + 3 | class without params decorating a function
__call__() is the replacement function
__init__() is passed the wrapped function
@DecoThree
def bar():
pass
same as
bar = DecoThree(bar) | 62598fa57cff6e4e811b590c |
class AccessMixin: <NEW_LINE> <INDENT> login_url = None <NEW_LINE> permission_denied_message = '' <NEW_LINE> raise_exception = False <NEW_LINE> redirect_field_name = REDIRECT_FIELD_NAME <NEW_LINE> def get_login_url(self): <NEW_LINE> <INDENT> login_url = self.login_url or settings.LOGIN_URL <NEW_LINE> if not login_url: <NEW_LINE> <INDENT> raise ImproperlyConfigured( '{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override ' '{0}.get_login_url().'.format(self.__class__.__name__) ) <NEW_LINE> <DEDENT> return str(login_url) <NEW_LINE> <DEDENT> def get_permission_denied_message(self): <NEW_LINE> <INDENT> return self.permission_denied_message <NEW_LINE> <DEDENT> def get_redirect_field_name(self): <NEW_LINE> <INDENT> return self.redirect_field_name <NEW_LINE> <DEDENT> def handle_no_permission(self): <NEW_LINE> <INDENT> if self.raise_exception: <NEW_LINE> <INDENT> raise PermissionDenied(self.get_permission_denied_message()) <NEW_LINE> <DEDENT> return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) | Abstract CBV mixin that gives access mixins the same customizable
functionality. | 62598fa5e76e3b2f99fd8919 |
class LockedDefaultDict(defaultdict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.lock = threading.Lock() <NEW_LINE> super(LockedDefaultDict, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> return super(LockedDefaultDict, self).__getitem__(key) <NEW_LINE> <DEDENT> <DEDENT> def pop(self, key, *args): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> key_lock = super(LockedDefaultDict, self).__getitem__(key) <NEW_LINE> if key_lock.acquire(False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(LockedDefaultDict, self).pop(key, *args) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> key_lock.release() | defaultdict with lock to handle threading
Dictionary only deletes if nothing is accessing dict and nothing is holding
lock to be deleted. If both cases are not true, it will skip delete. | 62598fa556ac1b37e63020d0 |
class MoneyAgent(Agent): <NEW_LINE> <INDENT> def __init__(self,unique_id,model): <NEW_LINE> <INDENT> super().__init__(unique_id,model) <NEW_LINE> self.wealth = 1 <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> print(self.unique_id, self.wealth) <NEW_LINE> print(self.unique_id) <NEW_LINE> if self.wealth == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> other_agent = random.choice(self.model.schedule.agents) <NEW_LINE> other_agent.wealth += 1 <NEW_LINE> self.wealth -=1 | an agent with a fixed initial wealth | 62598fa57047854f4633f2bc |
class Kind(Enum): <NEW_LINE> <INDENT> UNKNOWN = 0 <NEW_LINE> IMAGE = 1 <NEW_LINE> OUTLINE = 2 <NEW_LINE> SHAPE = 3 <NEW_LINE> RGB = 4 <NEW_LINE> COMPOSITE = 1 <NEW_LINE> CONTOUR = 6 | Kind of entities we're working with. | 62598fa5236d856c2adc93ad |
class City(models.Model): <NEW_LINE> <INDENT> city = models.CharField('城市名称', max_length=40, db_index=True) <NEW_LINE> district = models.CharField('市区信息', max_length=40) <NEW_LINE> user_id = models.IntegerField('创建者') <NEW_LINE> status = models.IntegerField('数据状态', default=1) <NEW_LINE> created = models.DateTimeField(default=now) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> objects = BaseManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'ys_city' <NEW_LINE> ordering = ['city', 'district'] <NEW_LINE> unique_together = ('city', 'district', 'status') <NEW_LINE> app_label = 'Business_App.bz_dishes.models.City' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.city <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_object(cls, **kwargs): <NEW_LINE> <INDENT> _kwargs = get_perfect_filter_params(cls, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> return cls.objects.get(**_kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def filter_objects(cls, fuzzy=True, **kwargs): <NEW_LINE> <INDENT> _kwargs = get_perfect_filter_params(cls, **kwargs) <NEW_LINE> if fuzzy: <NEW_LINE> <INDENT> if 'city' in _kwargs: <NEW_LINE> <INDENT> _kwargs['city__contains'] = _kwargs.pop('city') <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> return cls.objects.filter(**_kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def filter_details(cls, fuzzy=True, **kwargs): <NEW_LINE> <INDENT> instances = cls.filter_objects(fuzzy, **kwargs) <NEW_LINE> if isinstance(instances, Exception): <NEW_LINE> <INDENT> return instances <NEW_LINE> <DEDENT> return [model_to_dict(ins) for ins in instances] | 城市信息 | 62598fa566673b3332c302ad |
class DbUser(Base): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = Column(INTEGER(10, unsigned=True), primary_key=True) <NEW_LINE> email = Column(String(191), nullable=False) <NEW_LINE> primary_owner_id = Column(ForeignKey('owners.id', name='fk_users_primary_owner_id', ondelete='SET NULL'), nullable=True, index=True) | Users - Laravel maintained table!
Only columns needed for migration | 62598fa567a9b606de545eaf |
class CloudStackIPForwardingRule(object): <NEW_LINE> <INDENT> def __init__(self, node, id, address, protocol, start_port, end_port=None): <NEW_LINE> <INDENT> self.node = node <NEW_LINE> self.id = id <NEW_LINE> self.address = address <NEW_LINE> self.protocol = protocol <NEW_LINE> self.start_port = start_port <NEW_LINE> self.end_port = end_port <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> self.node.ex_delete_ip_forwarding_rule(rule=self) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__class__ is other.__class__ and self.id == other.id | A NAT/firewall forwarding rule. | 62598fa521bff66bcd722b49 |
class ElFarolEnv(mgym.MEnv): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.N = None <NEW_LINE> self.nA = 2 <NEW_LINE> self.action_space = None <NEW_LINE> self.observation_space = spaces.Box(low=0.0, high=1.0, shape=(1,)) <NEW_LINE> self.state = None <NEW_LINE> self.attendence_threshold = None <NEW_LINE> self.WORD_FOR_ACTION = {0: 'STAY HOME', 1: 'GO TO BAR'} <NEW_LINE> self.iteration = 0 <NEW_LINE> <DEDENT> def reset(self, N=10, total_iterations=100, threshold=0.6): <NEW_LINE> <INDENT> self.N = N <NEW_LINE> self.action_space = spaces.Tuple( [spaces.Discrete(self.nA) for _ in range(self.N)]) <NEW_LINE> self.state = np.array([0.]) <NEW_LINE> self.iteration = 0 <NEW_LINE> self.total_iterations = total_iterations <NEW_LINE> self.attendence_threshold = threshold <NEW_LINE> return self.state <NEW_LINE> <DEDENT> def step(self, actions): <NEW_LINE> <INDENT> self.iteration += 1 <NEW_LINE> if self.iteration >= self.total_iterations: <NEW_LINE> <INDENT> done = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> done = False <NEW_LINE> <DEDENT> self.state = np.array([sum(list(actions)) / self.N]) <NEW_LINE> crowded = (self.state[0] > 0.6) <NEW_LINE> rewards = [] <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> if action == 1: <NEW_LINE> <INDENT> if crowded: <NEW_LINE> <INDENT> reward = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reward = +1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> reward = 0 <NEW_LINE> <DEDENT> rewards.append(reward) <NEW_LINE> <DEDENT> info = {} <NEW_LINE> return self.state, rewards, done, info <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> print('\n Bar: {} Home: {}'.format(self.state[0], 1. - self.state[0])) | El Farol N-person Game
Example
-------
>>> import gym
>>> import mgym
>>> import random
>>>
>>> env = gym.make('ElFarol-v0')
>>> obs = env.reset(N=10, total_iterations=100, threshold=0.6)
>>> done = False
>>> while True:
... a = env.action_space.sample()
... obs,r,done,info = env.step(a)
... env.render()
... if done:
... break | 62598fa53cc13d1c6d46564f |
class TestProcessMentions(BasicUserTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestProcessMentions, self).setUp() <NEW_LINE> self.link_markdown = "[{}]({})" <NEW_LINE> self.func = process_mentions <NEW_LINE> <DEDENT> def test_valid_process(self): <NEW_LINE> <INDENT> template = "{} this is a good idea. {} what do you think?" <NEW_LINE> sample = template.format("@user1", "@admin") <NEW_LINE> user1 = self.__get_user_markdown(self.user1) <NEW_LINE> admin = self.__get_user_markdown(self.admin) <NEW_LINE> expected_output = template.format(user1, admin) <NEW_LINE> output = self.func(sample) <NEW_LINE> self.assertEquals(output, expected_output) <NEW_LINE> <DEDENT> def test_process_non_existing_user(self): <NEW_LINE> <INDENT> sample = "@ryan is this working? @bill" <NEW_LINE> output = self.func(sample) <NEW_LINE> self.assertEquals(output, sample) <NEW_LINE> <DEDENT> def test_process_mix_of_users(self): <NEW_LINE> <INDENT> template = "{} are you a test? {} is a fake user" <NEW_LINE> sample = template.format("@user1", "@ryan") <NEW_LINE> user1 = self.__get_user_markdown(self.user1) <NEW_LINE> expected_output = template.format(user1, "@ryan") <NEW_LINE> output = self.func(sample) <NEW_LINE> self.assertEquals(output, expected_output) <NEW_LINE> <DEDENT> def test_process_with_no_mentions(self): <NEW_LINE> <INDENT> sample = "Hello World. I am working today" <NEW_LINE> output = self.func(sample) <NEW_LINE> self.assertEquals(output, sample) <NEW_LINE> <DEDENT> def test_process_empty_inputs(self): <NEW_LINE> <INDENT> sample = '' <NEW_LINE> output = self.func(sample) <NEW_LINE> self.assertEquals(output, sample) <NEW_LINE> <DEDENT> def test_process_none_input(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.func(None) <NEW_LINE> <DEDENT> <DEDENT> def test_process_invalid_input_type(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.func(1233) <NEW_LINE> <DEDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.func(['@ryan', 'Hello', 'World']) <NEW_LINE> <DEDENT> class dummy(object): <NEW_LINE> <INDENT> mentions = "@ryan hello world" <NEW_LINE> <DEDENT> obj = dummy() <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> self.func(obj) <NEW_LINE> <DEDENT> <DEDENT> def __get_user_markdown(self, user): <NEW_LINE> <INDENT> url = reverse('user_profile', kwargs={'pk': user.pk}) <NEW_LINE> mention = "@{}".format(user.username) <NEW_LINE> return self.link_markdown.format(mention, url) | Test case for process mentions function in timeline utils. | 62598fa510dbd63aa1c70a95 |
class EmptyResultException(Exception): <NEW_LINE> <INDENT> pass | This exception is executed if getSingle, getSingleRow or getSingleColumn are
performed on a result which does not contain any row. | 62598fa58c0ade5d55dc3602 |
class ConstantPropertyWater(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._d = 998.207150468 <NEW_LINE> self._cp = 4184.05092452 <NEW_LINE> self._v = 0.00100179606961 <NEW_LINE> <DEDENT> def get_Density(self, **kwargs): <NEW_LINE> <INDENT> return self._d <NEW_LINE> <DEDENT> def get_SpecificIsobaricHeatCapacity(self, **kwargs): <NEW_LINE> <INDENT> return self._cp <NEW_LINE> <DEDENT> def get_SpecificVolume(self, **kwargs): <NEW_LINE> <INDENT> return self._v <NEW_LINE> <DEDENT> def modelicaModelPath(self): <NEW_LINE> <INDENT> return 'Modelica.Media.Water.ConstantPropertyLiquidWater(T_min=223.15)' | Object for the evaluation of thermal properties of heat transfer fluid
Water. | 62598fa532920d7e50bc5f3a |
class GreenthreadSafeIterator(object): <NEW_LINE> <INDENT> def __init__(self, unsafe_iterable): <NEW_LINE> <INDENT> self.unsafe_iter = iter(unsafe_iterable) <NEW_LINE> self.semaphore = eventlet.semaphore.Semaphore(value=1) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> with self.semaphore: <NEW_LINE> <INDENT> return next(self.unsafe_iter) | Wrap an iterator to ensure that only one greenthread is inside its next()
method at a time.
This is useful if an iterator's next() method may perform network IO, as
that may trigger a greenthread context switch (aka trampoline), which can
give another greenthread a chance to call next(). At that point, you get
an error like "ValueError: generator already executing". By wrapping calls
to next() with a mutex, we avoid that error. | 62598fa5462c4b4f79dbb8f0 |
class Stats(object): <NEW_LINE> <INDENT> def __init__(self, subject, listeners = None, playcount = None, tagcount = None, count = None, match = None, rank = None, weight = None, attendance = None, reviews = None,): <NEW_LINE> <INDENT> self.__subject = subject <NEW_LINE> self.__listeners = listeners <NEW_LINE> self.__playcount = playcount <NEW_LINE> self.__tagcount = tagcount <NEW_LINE> self.__count = count <NEW_LINE> self.__match = match <NEW_LINE> self.__rank = rank <NEW_LINE> self.__weight = weight <NEW_LINE> self.__attendance = attendance <NEW_LINE> self.__reviews = reviews <NEW_LINE> <DEDENT> @property <NEW_LINE> def subject(self): <NEW_LINE> <INDENT> return self.__subject <NEW_LINE> <DEDENT> @property <NEW_LINE> def rank(self): <NEW_LINE> <INDENT> return self.__rank <NEW_LINE> <DEDENT> @property <NEW_LINE> def listeners(self): <NEW_LINE> <INDENT> return self.__listeners <NEW_LINE> <DEDENT> @property <NEW_LINE> def playcount(self): <NEW_LINE> <INDENT> return self.__playcount <NEW_LINE> <DEDENT> @property <NEW_LINE> def tagcount(self): <NEW_LINE> <INDENT> return self.__tagcount <NEW_LINE> <DEDENT> @property <NEW_LINE> def count(self): <NEW_LINE> <INDENT> return self.__count <NEW_LINE> <DEDENT> @property <NEW_LINE> def match(self): <NEW_LINE> <INDENT> return self.__match <NEW_LINE> <DEDENT> @property <NEW_LINE> def weight(self): <NEW_LINE> <INDENT> return self.__weight <NEW_LINE> <DEDENT> @property <NEW_LINE> def attendance(self): <NEW_LINE> <INDENT> return self.__attendance <NEW_LINE> <DEDENT> @property <NEW_LINE> def reviews(self): <NEW_LINE> <INDENT> return self.__reviews <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<lastfm.Stats: for '%s'>" % self.__subject.name | A class representing the stats of an artist. | 62598fa5dd821e528d6d8e19 |
class PageLimit(ModelSimple): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { ('value',): { 'inclusive_maximum': 100, 'inclusive_minimum': 10, }, } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> return { 'value': (int,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = {} <NEW_LINE> _composed_schemas = None <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> if 'value' in kwargs: <NEW_LINE> <INDENT> value = kwargs.pop('value') <NEW_LINE> <DEDENT> elif args: <NEW_LINE> <INDENT> args = list(args) <NEW_LINE> value = args.pop(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = 10 <NEW_LINE> <DEDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> self.value = value <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid named arguments=%s passed to %s. Remove those invalid named arguments." % ( kwargs, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values. | 62598fa54e4d562566372308 |
class TpuProjectsLocationsListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> name = _messages.StringField(2, required=True) <NEW_LINE> pageSize = _messages.IntegerField(3, variant=_messages.Variant.INT32) <NEW_LINE> pageToken = _messages.StringField(4) | A TpuProjectsLocationsListRequest object.
Fields:
filter: The standard list filter.
name: The resource that owns the locations collection, if applicable.
pageSize: The standard list page size.
pageToken: The standard list page token. | 62598fa599cbb53fe6830db9 |
class LogisticRegressionWithSGD(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @since('0.9.0') <NEW_LINE> def train(cls, data, iterations=100, step=1.0, miniBatchFraction=1.0, initialWeights=None, regParam=0.01, regType="l2", intercept=False, validateData=True, convergenceTol=0.001): <NEW_LINE> <INDENT> warnings.warn( "Deprecated in 2.0.0. Use ml.classification.LogisticRegression or " "LogisticRegressionWithLBFGS.", DeprecationWarning) <NEW_LINE> def train(rdd, i): <NEW_LINE> <INDENT> return callMLlibFunc("trainLogisticRegressionModelWithSGD", rdd, int(iterations), float(step), float(miniBatchFraction), i, float(regParam), regType, bool(intercept), bool(validateData), float(convergenceTol)) <NEW_LINE> <DEDENT> return _regression_train_wrapper(train, LogisticRegressionModel, data, initialWeights) | .. versionadded:: 0.9.0
.. note:: Deprecated in 2.0.0. Use ml.classification.LogisticRegression or
LogisticRegressionWithLBFGS. | 62598fa54a966d76dd5eedc7 |
class QueryEvent(BinLogEvent): <NEW_LINE> <INDENT> def __init__(self, from_packet, event_size, table_map, ctl_connection, **kwargs): <NEW_LINE> <INDENT> super(QueryEvent, self).__init__(from_packet, event_size, table_map, ctl_connection, **kwargs) <NEW_LINE> self.slave_proxy_id = self.packet.read_uint32() <NEW_LINE> self.execution_time = self.packet.read_uint32() <NEW_LINE> self.schema_length = byte2int(self.packet.read(1)) <NEW_LINE> self.error_code = self.packet.read_uint16() <NEW_LINE> self.status_vars_length = self.packet.read_uint16() <NEW_LINE> self.status_vars = self.packet.read(self.status_vars_length) <NEW_LINE> self.schema = self.packet.read(self.schema_length) <NEW_LINE> self.packet.advance(1) <NEW_LINE> self.query = self.packet.read(event_size - 13 - self.status_vars_length - self.schema_length - 1).decode("utf-8") <NEW_LINE> <DEDENT> def _dump(self): <NEW_LINE> <INDENT> super(QueryEvent, self)._dump() | This evenement is trigger when a query is run of the database.
Only replicated queries are logged. | 62598fa5be383301e02536dc |
class ConferencesFile(File): <NEW_LINE> <INDENT> filename_extensions = [] <NEW_LINE> folder_path = ['conferences', 'files'] <NEW_LINE> status = models.CharField(max_length=2, choices=FILE_STATUSES, default='PR') <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.folder: <NEW_LINE> <INDENT> folder = None <NEW_LINE> for name in self.folder_path: <NEW_LINE> <INDENT> folder, _ = Folder.objects.get_or_create( name=name, parent=folder) <NEW_LINE> <DEDENT> self.folder = folder <NEW_LINE> <DEDENT> super(ConferencesFile, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def author(self): <NEW_LINE> <INDENT> return self.owner <NEW_LINE> <DEDENT> @author.setter <NEW_LINE> def author(self, value): <NEW_LINE> <INDENT> self.owner = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_info(self): <NEW_LINE> <INDENT> return self.description <NEW_LINE> <DEDENT> @extra_info.setter <NEW_LINE> def extra_info(self, value): <NEW_LINE> <INDENT> self.description = value <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def matches_file_type(cls, iname, ifile, request): <NEW_LINE> <INDENT> ext = os.path.splitext(iname)[1].lower() <NEW_LINE> return ext in cls.filename_extensions if cls.filename_extensions else True <NEW_LINE> <DEDENT> @property <NEW_LINE> def status_verbose(self): <NEW_LINE> <INDENT> return get_display(self.status, FILE_STATUSES) | Multi-table inheritance base model
https://docs.djangoproject.com/en/1.6/topics/db/models/#multi-table-inheritance | 62598fa555399d3f05626408 |
class VoiceCommandError(commands.CheckFailure): <NEW_LINE> <INDENT> pass | This is raised when an error occurs in a voice command. | 62598fa5adb09d7d5dc0a46f |
class _Prop_modified(aetools.NProperty): <NEW_LINE> <INDENT> which = 'imod' <NEW_LINE> want = 'bool' | modified - Has the document been modified since the last save? | 62598fa597e22403b383adf0 |
class Vertex: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.coord = (x, y) <NEW_LINE> self.neighbors = [] <NEW_LINE> self.number = 0 <NEW_LINE> self.number_options = [] <NEW_LINE> self.illegal_numbers = [] <NEW_LINE> <DEDENT> def add_neighbor(self, neighbor): <NEW_LINE> <INDENT> if neighbor not in self.neighbors: <NEW_LINE> <INDENT> self.neighbors.append(neighbor) <NEW_LINE> <DEDENT> <DEDENT> def remove_neighbor(self, neighbor): <NEW_LINE> <INDENT> if neighbor in self.neighbors: <NEW_LINE> <INDENT> self.neighbors.remove(neighbor) <NEW_LINE> <DEDENT> <DEDENT> def add_illegal_number(self, number): <NEW_LINE> <INDENT> if number in self.number_options: <NEW_LINE> <INDENT> self.number_options.remove(number) <NEW_LINE> <DEDENT> if number not in self.illegal_numbers: <NEW_LINE> <INDENT> self.illegal_numbers.append(number) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def rank(self): <NEW_LINE> <INDENT> return len(self.neighbors) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Vertex: ' + str(self.number) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Vertex: R=' + str(self.rank()) + ', C=' + str(self.number) + ', XY=' + str(self.coord) + '>' | A vertex in a graph, with atributes to be used for sudoku solving. | 62598fa56e29344779b00541 |
class Firedevil(spriteobj.SpriteObj): <NEW_LINE> <INDENT> def __init__(self, screen, level, gfx, x, y): <NEW_LINE> <INDENT> spriteobj.SpriteObj.__init__(self, screen, level, gfx, x, y) <NEW_LINE> self.movingLeftAnim = [(0, 80), (1, 80), (2, 80), (3, 80)] <NEW_LINE> self.movingRightAnim = [(5, 80), (6, 80), (7, 80), (8, 80)] <NEW_LINE> self.turningLeftAnim = [(4, 40), (4, 40)] <NEW_LINE> self.turningRightAnim = [(4, 40), (4, 40)] <NEW_LINE> self.sleepingAnim = [(4, 40), (4, 40)] <NEW_LINE> self.move = self.move4 <NEW_LINE> self.moveLeft() <NEW_LINE> self.sleep = self.sleep1 <NEW_LINE> self.sleepMax = 6000 <NEW_LINE> self.name = "Firedevil" <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> if self.verticalMovement == 0: <NEW_LINE> <INDENT> bt = self.bottomTile() <NEW_LINE> if bt == 0: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> self.fall() <NEW_LINE> <DEDENT> elif bt == 1: <NEW_LINE> <INDENT> self.level.frontData[self.bottomSpotOut][self.midX] = 0 <NEW_LINE> self.screen.blit(self.level.backGfx[self.level.backData[self.bottomSpotOut][self.midX]], (self.midX*32, self.bottomSpotOut*32)) <NEW_LINE> <DEDENT> tt = self.topTile() <NEW_LINE> if tt == 1: <NEW_LINE> <INDENT> self.level.frontData[self.topSpotOut][self.midX] = 0 <NEW_LINE> self.screen.blit(self.level.backGfx[self.level.backData[self.topSpotOut][self.midX]], (self.midX*32, self.topSpotOut*32)) <NEW_LINE> <DEDENT> <DEDENT> if self.horizontalMovement == self.movingRight: <NEW_LINE> <INDENT> if self.rightTile() == 1: <NEW_LINE> <INDENT> self.level.frontData[self.midY][self.rightSpotOut] = 0 <NEW_LINE> self.screen.blit(self.level.backGfx[self.level.backData[self.midY][self.rightSpotOut]], (self.rightSpotOut*32, self.midY*32)) <NEW_LINE> self.turnLeft() <NEW_LINE> <DEDENT> elif self.wallRight(): <NEW_LINE> <INDENT> self.turnLeft() <NEW_LINE> <DEDENT> <DEDENT> elif self.horizontalMovement == self.movingLeft: <NEW_LINE> <INDENT> if self.leftTile() == 1: <NEW_LINE> <INDENT> self.level.frontData[self.midY][self.leftSpotOut] = 0 <NEW_LINE> self.screen.blit(self.level.backGfx[self.level.backData[self.midY][self.leftSpotOut]], (self.leftSpotOut*32, self.midY*32)) <NEW_LINE> self.turnRight() <NEW_LINE> <DEDENT> elif self.wallLeft(): <NEW_LINE> <INDENT> self.turnRight() <NEW_LINE> <DEDENT> <DEDENT> elif self.verticalMovement == self.falling: <NEW_LINE> <INDENT> self.checkFalling() | Class for the fire devil: falls, removes ice-blocks | 62598fa532920d7e50bc5f3b |
class Forums(object): <NEW_LINE> <INDENT> def __init__(self, sess): <NEW_LINE> <INDENT> assert isinstance(sess, SakaiSession.SakaiSession) <NEW_LINE> self.session = sess <NEW_LINE> <DEDENT> def getForumsForSite(self, siteid): <NEW_LINE> <INDENT> return self.session.executeRequest('GET', '/forums/site/{0}.json'.format(siteid)) <NEW_LINE> <DEDENT> def getAllTopicsForForum(self, siteid, forumid): <NEW_LINE> <INDENT> return self.session.executeRequest('GET', '/forums/site/{0}/forum/{1}.json'.format(siteid, forumid)) <NEW_LINE> <DEDENT> def getAllConversationsForTopic( self, siteid, forumid, topicid, ): <NEW_LINE> <INDENT> return self.session.executeRequest('GET', '/forums/site/{0}/forum/{1}/topic/{2}.json'.format(siteid, forumid, topicid)) <NEW_LINE> <DEDENT> def getAllMessagesForConversation( self, siteid, forumid, topicid, messageid, ): <NEW_LINE> <INDENT> return self.session.executeRequest('GET', '/forums/site/{0}/forum/{1}/topic/{2}/message/{3}.json'.format(siteid, forumid, topicid, messageid)) | Contains logic for the Sakai Forums tool.
More information about the RESTful interface can be found at:
https://trunk-mysql.nightly.sakaiproject.org/direct/forums/describe | 62598fa54f88993c371f047c |
class Message(): <NEW_LINE> <INDENT> def __init__(self, entity_name, text, date=datetime.today(), language='english'): <NEW_LINE> <INDENT> self.entity_name = entity_name <NEW_LINE> self.text = text <NEW_LINE> self.date = date <NEW_LINE> self.language = language <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.__dict__) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self[key] = value <NEW_LINE> <DEDENT> def to_emotion_vector(self, cc=CacheController(max_depth=MAX_DEPTH, min_weight=MIN_WEIGHT, req_limit=REQ_LIMIT)): <NEW_LINE> <INDENT> tokens = " ".join([" ".join([w for w in s]) for s in text_processing(self.text, stemming=False)]) .split() <NEW_LINE> for i, t in enumerate(tokens): <NEW_LINE> <INDENT> empty_vector = { 'name': t, 'emotions': {} } <NEW_LINE> if cc is not None: <NEW_LINE> <INDENT> pot_t_vector = cc.fetch_word(t) <NEW_LINE> if pot_t_vector is not None: <NEW_LINE> <INDENT> tokens[i] = pot_t_vector <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tokens[i] = build_graph(Set([Node(t, lang_name_to_code(self.language), 'c')]), Set([]), empty_vector, 0) <NEW_LINE> cc.add_word(tokens[i]['name'], tokens[i]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> tokens[i] = build_graph(Set([Node(t, lang_name_to_code(self.language), 'c')]), Set([]), empty_vector, 0) <NEW_LINE> <DEDENT> <DEDENT> self.text = tokens <NEW_LINE> return self | Represents a message a user of Emotext sends to the cofra framework. | 62598fa6cb5e8a47e493c0ea |
class SeaBreezeRawUSBBusAccessFeature(SeaBreezeFeature): <NEW_LINE> <INDENT> identifier = "raw_usb_bus_access" <NEW_LINE> _required_protocol_cls = PySeaBreezeProtocol <NEW_LINE> @classmethod <NEW_LINE> def supports_protocol(cls, protocol: PySeaBreezeProtocol) -> bool: <NEW_LINE> <INDENT> return isinstance(protocol.transport, USBTransport) <NEW_LINE> <DEDENT> def raw_usb_write( self, data: bytes, endpoint: Literal["primary_out", "secondary_out"] ) -> None: <NEW_LINE> <INDENT> if endpoint not in {"primary_out", "secondary_out"}: <NEW_LINE> <INDENT> raise ValueError("endpoint has to be one of 'primary_out', 'secondary_out'") <NEW_LINE> <DEDENT> if endpoint == "secondary_out": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.protocol.transport.write(data) <NEW_LINE> <DEDENT> def raw_usb_read( self, endpoint: Literal["primary_in", "secondary_in", "secondary_in2"], buffer_length: int | None = None, ) -> bytes: <NEW_LINE> <INDENT> if endpoint == "primary_in": <NEW_LINE> <INDENT> return self.protocol.transport.read(size=buffer_length, mode="low_speed") <NEW_LINE> <DEDENT> elif endpoint == "secondary_in": <NEW_LINE> <INDENT> return self.protocol.transport.read(size=buffer_length, mode="high_speed") <NEW_LINE> <DEDENT> elif endpoint == "secondary_in2": <NEW_LINE> <INDENT> return self.protocol.transport.read( size=buffer_length, mode="high_speed_alt" ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( "endpoint has to be one of 'primary_in', 'secondary_in', 'secondary_in2'" ) | Reading and writing raw usb
Example usage
.. code-block:: python
>>> import struct # needed for packing binary data into bytestrings
>>> from seabreeze.spectrometers import Spectrometer
>>> spec = Spectrometer.from_first_available()
# features need to be accessed on the spectrometer instance via spec.f or spec.features
# the data you provide needs to packed into a bytestring via struct.pack
>>> spec.f.raw_usb_bus_access.raw_usb_write(data=struct.pack('<B', 0xFE), endpoint='primary_out')
# when reading via the raw_usb feature you can easily block the spectrometer.
# so make sure to only read when you expect new data (after you sent a command)
# and only read as many bytes as the command returns
>>> output = spec.f.raw_usb_bus_access.raw_usb_read(endpoint='primary_in', buffer_length=16)
>>> print(output)
b'\x00\x08p\x17\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x80U'
# extract by providing the data format from the developer datasheet and `output` to struct.unpack | 62598fa644b2445a339b68e1 |
class ClassicAgent(Agent): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def decide(self, observation: np.ndarray) -> int: <NEW_LINE> <INDENT> return 0 | Fixed-policy traditional agent.
Represents an agent based on a traditional fixed policy. It can be used as a comparison against deep
reinforcement learning agents being developed. May implement any of the policy pairs in the action
space.
| 62598fa65166f23b2e2432bc |
class Adaptor (saga.adaptors.base.Base): <NEW_LINE> <INDENT> def __init__ (self) : <NEW_LINE> <INDENT> saga.adaptors.base.Base.__init__ (self, _ADAPTOR_INFO, _ADAPTOR_OPTIONS) <NEW_LINE> self._default_contexts = [] <NEW_LINE> self._have_defaults = False <NEW_LINE> <DEDENT> def sanity_check (self) : <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _get_default_contexts (self) : <NEW_LINE> <INDENT> if not self._have_defaults : <NEW_LINE> <INDENT> import glob <NEW_LINE> candidate_certs = glob.glob ("%s/.ssh/*" % os.environ['HOME']) <NEW_LINE> for key in candidate_certs : <NEW_LINE> <INDENT> if os.path.isdir (key) : <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if key.endswith ('.pub') : <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if key.endswith ('.pem') : <NEW_LINE> <INDENT> pub = "%s" % key <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> pub = "%s.pub" % key <NEW_LINE> <DEDENT> if not os.path.exists (key ) or not os.path.isfile (key ) : <NEW_LINE> <INDENT> self._logger.info ("ignore ssh key at %s (no private key: %s)" % (key, key)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not os.path.exists (pub) or not os.path.isfile (pub) : <NEW_LINE> <INDENT> self._logger.info ("ignore ssh key at %s (no public key: %s)" % (key, pub)) <NEW_LINE> continue <NEW_LINE> <DEDENT> try : <NEW_LINE> <INDENT> fh_key = open (key ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._logger.info ("ignore ssh key at %s (key not readable: %s)" % (key, e)) <NEW_LINE> continue <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> fh_key .close () <NEW_LINE> <DEDENT> try : <NEW_LINE> <INDENT> fh_pub = open (pub ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._logger.info ("ignore ssh key at %s (public key %s not readable: %s)" % (key, pub, e)) <NEW_LINE> continue <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> fh_pub .close () <NEW_LINE> <DEDENT> import subprocess <NEW_LINE> if not subprocess.call (["sh", "-c", "grep ENCRYPTED %s > /dev/null" % key]) : <NEW_LINE> <INDENT> self._logger.warn ("ignore ssh key at %s (requires passphrase)" % key) <NEW_LINE> continue <NEW_LINE> <DEDENT> c = saga.Context ('ssh') <NEW_LINE> c.user_key = key <NEW_LINE> c.user_cert = pub <NEW_LINE> self._default_contexts.append (c) <NEW_LINE> self._logger.info ("default ssh key at %s" % key) <NEW_LINE> <DEDENT> self._have_defaults = True <NEW_LINE> <DEDENT> return self._default_contexts | This is the actual adaptor class, which gets loaded by SAGA (i.e. by the
SAGA engine), and which registers the CPI implementation classes which
provide the adaptor's functionality. | 62598fa626068e7796d4c83e |
class CachedS3BotoStorage(S3BotoStorage): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CachedS3BotoStorage, self).__init__(*args, **kwargs) <NEW_LINE> self.local_storage = get_storage_class("compressor.storage.CompressorFileStorage")() <NEW_LINE> <DEDENT> def save(self, name, content): <NEW_LINE> <INDENT> non_gzipped_file_content = content.file <NEW_LINE> name = super(CachedS3BotoStorage, self).save(name, content) <NEW_LINE> content.file = non_gzipped_file_content <NEW_LINE> self.local_storage._save(name, content) <NEW_LINE> return name <NEW_LINE> <DEDENT> def url(self, name): <NEW_LINE> <INDENT> orig = super(CachedS3BotoStorage, self).url(name) <NEW_LINE> scheme, netloc, path, params, query, fragment = urlparse.urlparse(orig) <NEW_LINE> params = urlparse.parse_qs(query) <NEW_LINE> if 'x-amz-security-token' in params: <NEW_LINE> <INDENT> del params['x-amz-security-token'] <NEW_LINE> <DEDENT> query = urllib.urlencode(params) <NEW_LINE> url = urlparse.urlunparse( (scheme, netloc, path, params, query, fragment) ) <NEW_LINE> if name.endswith('/') and not url.endswith('/'): <NEW_LINE> <INDENT> url += '/' <NEW_LINE> <DEDENT> return url | S3 storage backend that saves the files locally, too. | 62598fa60a50d4780f7052c1 |
class BrowserEnv(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> osenv = os.environ.copy() <NEW_LINE> self.selenium_platform = osenv.get('SELENIUM_PLATFORM') <NEW_LINE> self.selenium_version = osenv.get('SELENIUM_VERSION') <NEW_LINE> self.selenium_browser = osenv.get('SELENIUM_BROWSER', 'firefox') <NEW_LINE> self.selenium_host = osenv.get('SELENIUM_HOST') <NEW_LINE> self.selenium_port = osenv.get('SELENIUM_PORT') <NEW_LINE> self.selenium_driver = osenv.get('SELENIUM_DRIVER') <NEW_LINE> self.sauce_user_name = osenv.get('SAUCE_USER_NAME') <NEW_LINE> self.sauce_api_key = osenv.get('SAUCE_API_KEY') <NEW_LINE> self.run_on_saucelabs = bool( self.selenium_host == 'ondemand.saucelabs.com' or self.selenium_driver ) <NEW_LINE> self.run_on_jenkins = bool(osenv.get('JOB_NAME')) <NEW_LINE> self.build_number = osenv.get('BUILD_NUMBER', 'local harvest') <NEW_LINE> self.job_name = osenv.get('JOB_NAME', 'acceptance tests') <NEW_LINE> self.session_id = None <NEW_LINE> if self.selenium_driver: <NEW_LINE> <INDENT> parse = ParseSauceUrl(self.selenium_driver) <NEW_LINE> self.sauce_user_name = parse.get_value('username') <NEW_LINE> self.sauce_api_key = parse.get_value('access-key') <NEW_LINE> self.selenium_browser = parse.get_value('browser') <NEW_LINE> self.selenium_version = parse.get_value('browser-version') <NEW_LINE> sauce_driver_os = parse.get_value('os') <NEW_LINE> if 'Windows 2003' in sauce_driver_os: <NEW_LINE> <INDENT> self.selenium_platform = 'XP' <NEW_LINE> <DEDENT> elif 'Windows 2008' in sauce_driver_os: <NEW_LINE> <INDENT> self.selenium_platform = 'VISTA' <NEW_LINE> <DEDENT> elif 'Linux' in sauce_driver_os: <NEW_LINE> <INDENT> self.selenium_platform = 'LINUX' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.selenium_platform = sauce_driver_os | Class to hold the browser environment settings.
These are determined by OS environment values that are
set locally, by Jenkins, and by the SauceLabs Jenkins plugin. | 62598fa6f548e778e596b48a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.