def test_immutable_population_list(self): p1 = record(id='a') p2 = record(id='b') plist = ImmutablePopulationList([p1, p2]) with pytest.raises(TypeError): plist[0] = p1 with pytest.raises(TypeError): del plist[0] with pytest.raises(TypeError): plist.insert(0, p1)
def model_class(self): import sys class Base: pass class Model(Base): _meta = sk.record(app_label='app', model_name='model') sys.modules['django.db.models'] = sk.record(Model=Base) sys.modules['django.template.loader'] = sk.record(get_template=Mock()) try: yield Model finally: del sys.modules['django.db.models']
def region_data(region: RegionT): """ Collect data from region. """ data = dict(epidemic_data(region)) if region.country_code == "BR" and region.type == "state": paho = sk.record(paho_br_state_data(region)) data.update( # Update daily information since the PAHO database more carefully handle # "reports from the last 24h" than Brazil.io new_cases=paho.cases_24h, new_prevalence_today=1e5 * paho.cases_24h / region.population, new_deaths=paho.deaths_24h, new_mortality_today=1e5 * paho.deaths_24h / region.population, # Occupancy data hospital_occupancy=paho.hospital_occupancy, icu_occupancy=paho.icu_occupancy, # Policy isolation_score=paho.isolation_score, has_lockdown=bool(paho.n_cities_lockdown), lockdown_ratio=100 * paho.n_cities_lockdown / paho.n_cities, # Tests tests=paho.tests, tests_100k=1e5 * paho.tests / region.population, tests_positive=paho.tests_positive, tests_positive_ratio=100 * paho.tests_positive / paho.tests, ) return MappingProxyType(data)
def login(self, user): """ Force Django user to login at Rocket.Chat. User must already been registered and provided a RC username. """ # Super-user share the global config account. Login will force login and # update the global config if user.is_superuser: from .models import RCAccount response = self.password_login(self.admin_username, self.admin_password) self.config.admin_token = response["data"]["authToken"] self.config.save() return record( config=self.config, username=self.admin_username, password=self.admin_password, auth_token=self.config.admin_token, user_rc_id=self.admin_id, user=user, ) # Handle regular accounts account = self.accounts.get(user=user) if not account.is_active: return account response = self.password_login(account.username, account.password) account.auth_token = response["data"]["authToken"] account.save() return account
def login(self, user): """ Force Django user to login at Rocket.Chat. User must already been registered with an RC username. """ # Super-user share the global config account. Login will force login and # update the global config if user.is_superuser: self.admin_login() return record( config=self.config, username=self.admin_username, password=self.admin_password, auth_token=self.config.admin_token, user_rc_id=self.admin_id, user=user, ) # Handle regular accounts account = self.accounts.get(user=user) if not account.is_active: raise PermissionError("cannot login with inactive accounts") response = self.password_login(account.username, account.password) account.auth_token = response["data"]["authToken"] account.save() return account
def ply_lexer(rules): """ A lexer factory that uses PLY own lexer module to build tokens. It has the same interface as the simple_lexer() function. """ from ply import lex # PLY documentation asks us to define a series of constants or functions # named as t_TOK_NAME in a module. This is not necessary and any # introspectable Python object that exposes those constants via getattr # is good enough. We use a record() object here and let PLY instrospect it # by pretending it is a module :) namespace = record(tokens=[x for x, _ in rules], t_ignore=' \t', t_error=ply_lexer_error, **{'t_' + x: y for (x, y) in rules}) ply_lexer = lex.lex(module=namespace) def lexer(expr): ply_lexer.input(expr) while True: tok = ply_lexer.token() if tok is None: break yield Token(tok.type, tok.value, tok.lineno, tok.lexpos, lexer) lexer.which = 'ply' return lexer
def get_data(self, request): data = super().get_data(request) stereotype = self.stereotype.make(owner=data.author) votes = [ self.stereotype_vote.make(author=stereotype, comment=comment) for comment in data.comments ] return record(data, stereotype=stereotype, stereotype_votes=votes)
def parser(tokens: list): if isinstance(tokens, str): raise ValueError('parser receives a list of tokens, not a string!') tk_list = list(reversed(tokens)) def next_token(): if tk_list: return tk_list.pop() return yacc_parser.parse(lexer=record(token=next_token))
def ply_parser(rules, tokens, start=None): """ Return a parser from a list of (rule, reducer) tuples: Args: rules: A list of (handler, *rules). Each rule must be a single line string with a grammar rule that PLY understands. The handler function is called with the inputs on the rhs of the rule as arguments. This function must return a node in the parse tree. tokens: A list of valid token types. start: The start/root expression type. It will reduce the AST to the given start expression value. """ from ply import yacc # We use a similar strategy as in the ply_lexer function, but this time # the process is more involving. Let us start with a very basic namespace # that does not define any p_<rule>_<id> functions yet. namespace = dict( tokens=tokens, p_error=ply_parser_error, ) # Now we create rules from the input list counter = Counter() for rule, handler in rules: name = rule.partition(':')[0].strip() if start is None: start = name rule_id = counter[name] = counter[name] + 1 rule_name = 'p_%s_%s' % (name, rule_id) namespace[rule_name] = make_rule_handler(rule, handler) # We build a module-like object from namespace dictionary module = record(**namespace) yacc_parser = yacc.yacc(module=module, start=start) def parser(tokens: list): if isinstance(tokens, str): raise ValueError('parser receives a list of tokens, not a string!') tk_list = list(reversed(tokens)) def next_token(): if tk_list: return tk_list.pop() return yacc_parser.parse(lexer=record(token=next_token)) return parser
def get_data(self, request): data = super().get_data(request) conversation = self.conversation.make(author=data.author) comments = [ self.comment.make( author=data.author, conversation=conversation, content="comment-author" ), self.comment.make(author=data.user, conversation=conversation), ] votes = [ self.vote.make(comment=comment, author=data.user) for comment in comments ] return record(data, conversation=conversation, comments=comments, votes=votes)
def environment(autoescape=True, **options): options.pop("debug", None) options.setdefault("trim_blocks", True) options.setdefault("lstrip_blocks", True) options["undefined"] = StrictUndefined env = Environment(autoescape=True, **options) env.globals.update( static=staticfiles_storage.url, url=reverse, settings=record( **{k: getattr(settings, k) for k in dir(settings)}, has_boards=apps.is_installed("ej_boards"), has_clusters=apps.is_installed("ej_clusters"), has_dataviz=apps.is_installed("ej_dataviz"), has_gamification=apps.is_installed("ej_gamification"), has_profiles=apps.is_installed("ej_profiles"), has_users=apps.is_installed("ej_users"), has_rocketchat=apps.is_installed("ej_rocketchat"), service_worker=getattr(settings, "SERVICE_WORKER", False), all=settings, ), # Localization get_language=get_language, date_format=date_format, # Security salt_attr=salt_attr, salt_tag=salt_tag, salt=salt, # Platform functions generic_context=generic_context, get_messages=messages, # Available tags and components fragment=context_fragment, render=html, tag=roles, blob=Blob, **FUNCTIONS, ) env.filters.update( markdown=lambda x: Markup(markdown(x)), pc=format_percent, salt=salt, **hyperpython.jinja2.filters, ) env.install_gettext_translations(translation, newstyle=True) return env
def handler(request): # Read request headers and creates the request.up object value = request.META.get request.up = sk.record( location=value('X-Up-Location'), target=value('X-Up-Target'), fail_target=value('X-Up-Fail-Target'), validate=value('X-Up-Validate'), ) # Handle response and extract title from the context response = get_response(request) if hasattr(response, 'context'): title = request.context.get('title') if title: response.META.setdefault('X-Up-Title', title) return response
def update_actions(self, commands, physics): """ Update internal state from given commands. It must pass the PhysicsEngine object with a can_jump method that tests if jumps are allowed or not. """ if physics == None : physics_engine = record(can_jump=lambda: True, update=lambda *args: None) change_x = self.change_x change_y = self.change_y can_jump = abs(change_y) <= 2 * abs(change_x) and physics.can_jump() if abs(change_y) > 1: self.last_time_jumped = self.time max_speed = 4.5 delta = 1.25 if can_jump else 0.5 jump = 10 go_left = commands & self.command_left go_right = commands & self.command_right change_x *= 0.95 # Change speeds if commands & self.command_jump and can_jump: if not (self.time < self.last_time_jumped + self.jump_cooldown): self.last_time_jumped = self.time self.change_y = jump if go_left and go_right: pass elif go_right and change_x >= 0: change_x += delta elif go_left and change_x <= 0: change_x -= delta else: change_x = 0 # Set maximum speed if change_x > 0: change_x = min(change_x, max_speed) elif change_x < 0: change_x = max(change_x, -max_speed) self.change_x = change_x
def get_data(self, request): data = super().get_data(request) profile = self.profile.make(user=data.user) return record(data, profile=profile)
def get_data(self, request): data = super().get_data(request) board = self.board.make(owner=data.author) return record(data, board=board)
def test_nested_attribute_access(self): x = record(foo=record(bar=42)) assert fn(_.foo.bar == 42)(x) is True assert fn(_.foo.bar == 40)(x) is False assert fn(_.foo.bar.bit_length())(x) == 6
def pt(self): return record(x=1, y=2)
def get_data(self, request): user, author, admin = self.get_users(request) return record(user=user, author=author, admin=admin)
class HasPlayerMixin(GameWindow): """ Mixin that adds a player element into the class. """ #: Scaling for assets scaling = 1.0 #: Player theme player_theme = 'grey' #: Initial player position (measured in tiles) player_initial_tile = 4, 1 #: Dummy physics engine physics_engine = record(can_jump=lambda: True, update=lambda *args: None) #: Default player class player_class = lazy(lambda _: Player) @lazy def player(self): x, y = self.player_initial_tile x, y = int(64 * x + 32), int(64 * y + 32) player = self.player_class(self.player_theme, scaling=self.scaling, center_x=x, center_y=y) self.__dict__['player'] = player self.on_player_init(player) return player # # Base implementations for class hooks # def on_player_init(self, player): """ Hook called when player is first created with the player as single argument. """ # # Hooks and methods overrides # def get_viewport_focus(self): player = self.player return player.left, player.bottom, player.right, player.top def update_player(self, dt): """ Update player element after a time increment of dt. """ self.player.update_clock(dt) self.player.update_actions(self.commands, self.physics_engine) self.player.update() self.player.update_animation() def update_elements(self, dt): super().update_elements(dt) self.update_player(dt) def draw_player(self): """ Draw player on screen. """ return self.player.draw_sprites() def draw_elements(self): super().draw_elements() self.draw_player()
def p1(self): return record(id='a')
def add_django_ns(doctest_namespace): doctest_namespace.update(request=record())
def p2(self): return record(id='b')
class Model(Base): _meta = sk.record(app_label='app', model_name='model')
def to_record(self, **kwargs) -> sk.record: """ Return a sidekick record object with all disease parameters. """ return sk.record(self.to_dict(**kwargs))
import sys import mock from sidekick import Record, record class Model: __module__ = "django.db.models" class User(Model, Record): first_name: str username: str def get_absolute_url(self): return "/users/" + self.username def __str__(self): return self.first_name or self.username sys.modules["django"] = record() sys.modules["django.contrib"] = record() sys.modules["django.contrib.auth"] = record(get_user_model=lambda: User) sys.modules["django.template"] = record() sys.modules["django.template.loader"] = record(get_template=mock.Mock()) sys.modules["django.middleware"] = record() sys.modules["django.middleware.csrf"] = record( get_token=lambda _: "csrf-token-value")
def test_record_base_funcs(self): r = record(x=1, y=2) assert r.x == 1 assert r.y == 2 assert repr(r) == 'record(x=1, y=2)'
def social_js_template(): if apps.is_installed("allauth.socialaccount"): return get_template("socialaccount/snippets/login_extra.html") else: return record(render=lambda *args, **kwargs: "")
def get_data(self, request): data = super().get_data(request) return record(data, token=self.token.make(user=data.user))