code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class PlayGameState(GameState): <NEW_LINE> <INDENT> def __init__(self, window): <NEW_LINE> <INDENT> super(PlayGameState, self).__init__(window) <NEW_LINE> self.board.load_state('default') <NEW_LINE> self.load_interface('play.interface') <NEW_LINE> self.views.end_turn.on_press = self.board.pass_turn <NEW_LINE> self.views.main_menu.on_press = ( lambda: self.window.set_state(MainMenuState)) <NEW_LINE> <DEDENT> def on_mouse_press(self, x, y, button, modifiers): <NEW_LINE> <INDENT> if button in [pyglet.window.mouse.LEFT]: <NEW_LINE> <INDENT> self.board.click() <NEW_LINE> <DEDENT> <DEDENT> def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): <NEW_LINE> <INDENT> z = Vector3(0, 0, 1) <NEW_LINE> if pyglet.window.mouse.RIGHT & buttons: <NEW_LINE> <INDENT> cam = self.window.camera <NEW_LINE> cam.position = cam.position.rotate_around(z, -dx / 64.) <NEW_LINE> axis = cam.up.cross(cam.position) <NEW_LINE> cam.position = cam.position.rotate_around(axis, dy / 64.) <NEW_LINE> <DEDENT> <DEDENT> def draw_2d(self): <NEW_LINE> <INDENT> self.views.end_turn.visible = not self.board.pieces.filter( player=self.board.active_player, moved=False) <NEW_LINE> super(PlayGameState, self).draw_2d() | Handle the playing of the game. | 62598fc45166f23b2e2436b0 |
class UserRole(BaseCredentialSource): <NEW_LINE> <INDENT> def get(self, username, instance_role_name): <NEW_LINE> <INDENT> identity = clients.sts.get_caller_identity() <NEW_LINE> role_arn = ( 'arn:aws:iam::{account}:role/' + self.config.role_name_pattern ).format(account=identity['Account'], username=username) <NEW_LINE> logger.debug(f'{username}: {role_arn}') <NEW_LINE> try: <NEW_LINE> <INDENT> response = clients.cached_assume_role( RoleArn=role_arn, RoleSessionName=username) <NEW_LINE> return utils.assume_role_response(response) <NEW_LINE> <DEDENT> except clients.sts.exceptions.ClientError as ex: <NEW_LINE> <INDENT> if 'AccessDenied' not in str(ex): <NEW_LINE> <INDENT> raise ex <NEW_LINE> <DEDENT> logger.debug(str(ex)) <NEW_LINE> return None | AssumeRole to an existing user-oriented role.
| 62598fc47b180e01f3e491b7 |
class GitHubEnterprise(GitHub): <NEW_LINE> <INDENT> def __init__(self, url, username='', password='', token='', verify=True): <NEW_LINE> <INDENT> super(GitHubEnterprise, self).__init__(username, password, token) <NEW_LINE> self.session.base_url = url.rstrip('/') + '/api/v3' <NEW_LINE> self.session.verify = verify <NEW_LINE> self.url = url <NEW_LINE> <DEDENT> def _repr(self): <NEW_LINE> <INDENT> return '<GitHub Enterprise [{0.url}]>'.format(self) <NEW_LINE> <DEDENT> @requires_auth <NEW_LINE> def admin_stats(self, option): <NEW_LINE> <INDENT> stats = {} <NEW_LINE> if option.lower() in ('all', 'repos', 'hooks', 'pages', 'orgs', 'users', 'pulls', 'issues', 'milestones', 'gists', 'comments'): <NEW_LINE> <INDENT> url = self._build_url('enterprise', 'stats', option.lower()) <NEW_LINE> stats = self._json(self._get(url), 200) <NEW_LINE> <DEDENT> return stats | For GitHub Enterprise users, this object will act as the public API to
your instance. You must provide the URL to your instance upon
initialization and can provide the rest of the login details just like in
the :class:`GitHub <GitHub>` object.
There is no need to provide the end of the url (e.g., /api/v3/), that will
be taken care of by us.
If you have a self signed SSL for your local github enterprise you can
override the validation by passing `verify=False`. | 62598fc4be7bc26dc9251fc3 |
class Item(object): <NEW_LINE> <INDENT> def __init__(self, text, name=None): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self._name = name <NEW_LINE> if not self._name: <NEW_LINE> <INDENT> for line in unfold(self.text): <NEW_LINE> <INDENT> if line.startswith("X-RADICALE-NAME:"): <NEW_LINE> <INDENT> self._name = line.replace("X-RADICALE-NAME:", "").strip() <NEW_LINE> break <NEW_LINE> <DEDENT> elif line.startswith("TZID:"): <NEW_LINE> <INDENT> self._name = line.replace("TZID:", "").strip() <NEW_LINE> break <NEW_LINE> <DEDENT> elif line.startswith("UID:"): <NEW_LINE> <INDENT> self._name = line.replace("UID:", "").strip() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self._name: <NEW_LINE> <INDENT> self._name = self._name.strip("{}") <NEW_LINE> if "\nX-RADICALE-NAME:" in text: <NEW_LINE> <INDENT> for line in unfold(self.text): <NEW_LINE> <INDENT> if line.startswith("X-RADICALE-NAME:"): <NEW_LINE> <INDENT> self.text = self.text.replace( line, "X-RADICALE-NAME:%s" % self._name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.text = self.text.replace( "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._name = uuid4().hex.encode("ascii").decode("ascii") <NEW_LINE> self.text = self.text.replace( "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name) <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.text) <NEW_LINE> <DEDENT> def __eq__(self, item): <NEW_LINE> <INDENT> return isinstance(item, Item) and self.text == item.text <NEW_LINE> <DEDENT> @property <NEW_LINE> def etag(self): <NEW_LINE> <INDENT> md5 = hashlib.md5() <NEW_LINE> md5.update(self.text.encode("utf-8")) <NEW_LINE> return '"%s"' % md5.hexdigest() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name | Internal iCal item. | 62598fc4d486a94d0ba2c2a1 |
class RandomHorizontalFlip(object): <NEW_LINE> <INDENT> def __call__(self, inputs,target_depth,target_label): <NEW_LINE> <INDENT> if random.random() < 0.5: <NEW_LINE> <INDENT> inputs = np.flip(inputs,axis=0).copy() <NEW_LINE> target_depth = np.flip(target_depth,axis=0).copy() <NEW_LINE> <DEDENT> return inputs,target_depth,target_label | Randomly horizontally flips the given PIL.Image with a probability of 0.5
| 62598fc45fdd1c0f98e5e263 |
class OBJECTPATH(CIMElement): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> Element.__init__(self, 'OBJECTPATH') <NEW_LINE> self.appendChild(data) | The OBJECTPATH element is used to define a full path to a single
CIM Object (Class or Instance).
<!ELEMENT OBJECTPATH (INSTANCEPATH | CLASSPATH)> | 62598fc44f88993c371f0673 |
class PurpleAI(BlueAI): <NEW_LINE> <INDENT> body_image_name = "tank_corps_purple.png" <NEW_LINE> canon_image_name = "canon_purple.png" <NEW_LINE> def __init__(self, pos, target_pos, points_list=None): <NEW_LINE> <INDENT> BlueAI.__init__(self, pos, target_pos, points_list) <NEW_LINE> self.max_shots = 3 <NEW_LINE> self.n_shots = 0 <NEW_LINE> v = utils.get_volume('fx') <NEW_LINE> self.destroyedSound = load.sound("destroyed_sound.wav") <NEW_LINE> self.destroyedSound.set_volume(v) <NEW_LINE> self.fire_sound.set_volume(v) <NEW_LINE> self.updater_class = YellowAI <NEW_LINE> <DEDENT> def update(self, path, target_pos, walls_group, pits_group, bullets_group, in_menu=False): <NEW_LINE> <INDENT> if not in_menu: <NEW_LINE> <INDENT> self.basic_move(path, target_pos) <NEW_LINE> collided = pygame.sprite.spritecollide(self.body, bullets_group, False) <NEW_LINE> if collided: <NEW_LINE> <INDENT> for bullet in collided: <NEW_LINE> <INDENT> bullet.kill() <NEW_LINE> <DEDENT> self.destroyedSound.play() <NEW_LINE> self.n_shots += 1 <NEW_LINE> if self.n_shots == self.max_shots: <NEW_LINE> <INDENT> self.alive = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.body.image = load.image( "tank_corps_purple_dmg{}.png" .format(self.n_shots)) <NEW_LINE> self.body.base_image = self.body.image <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.updater_class.update(self, path, target_pos, walls_group, pits_group, bullets_group, in_menu) | An AI that moves along a pre-defined path.
Shoots the player on sight.
A certain number of shots (3) are needed to kill it. | 62598fc4f9cc0f698b1c543a |
class StewartEtAl2016RegJPNVH(StewartEtAl2016VH): <NEW_LINE> <INDENT> VGMPE = boore_2014.StewartEtAl2016(region='JPN') <NEW_LINE> HGMPE = boore_2014.BooreEtAl2014LowQ() | This class implements the Stewart et al. (2016) V/H model considering the
correction to the path scaling term for Low Q regions (e.g. Japan) | 62598fc47047854f4633f6a4 |
class DescribeVideoGenerationTaskCallbackRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SdkAppId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SdkAppId = params.get("SdkAppId") | DescribeVideoGenerationTaskCallback请求参数结构体
| 62598fc47d847024c075c68f |
class UpdateQuoteView(UpdateView): <NEW_LINE> <INDENT> form_class = UpdateQuoteForm <NEW_LINE> template_name = "quotes/update_quote_form.html" <NEW_LINE> queryset = Quote.objects.all() | Create a new Quote object and store it in the database | 62598fc423849d37ff851385 |
class PluginCollection(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def add(cls, key, obj): <NEW_LINE> <INDENT> if 'key_to_obj' not in cls.__dict__: <NEW_LINE> <INDENT> cls.key_to_obj = {} <NEW_LINE> <DEDENT> if key in cls.key_to_obj: <NEW_LINE> <INDENT> raise Exception('Key {} is used both by {} and {}'.format( key, cls.key_to_obj[key], obj )) <NEW_LINE> <DEDENT> cls.key_to_obj[key] = obj | A singleton dict for finding plugins -- usage:
1) Inherit to make a collection:
class FunkyPlugins(PluginCollection):
pass
3) Add plugins to the collection (usually, at module initialization):
FunkyPlugins.add('groovy', lambda x, y: '{} rocks {}'.format(x, y))
4) Access plugins via their keys, i.e.
FunkyPlugins.key_to_obj['groovy'] | 62598fc4d8ef3951e32c7fc5 |
class WikiPage(RedditBase): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _revision_generator(subreddit, url, generator_kwargs): <NEW_LINE> <INDENT> for revision in ListingGenerator(subreddit._reddit, url, **generator_kwargs): <NEW_LINE> <INDENT> revision['author'] = Redditor(subreddit._reddit, _data=revision['author']['data']) <NEW_LINE> revision['page'] = WikiPage(subreddit._reddit, subreddit, revision['page'], revision['id']) <NEW_LINE> yield revision <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def mod(self): <NEW_LINE> <INDENT> if self._mod is None: <NEW_LINE> <INDENT> self._mod = WikiPageModeration(self) <NEW_LINE> <DEDENT> return self._mod <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and str(self).lower() == str(other).lower() <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return super(WikiPage, self).__hash__() <NEW_LINE> <DEDENT> def __init__(self, reddit, subreddit, name, revision=None, _data=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self._revision = revision <NEW_LINE> self.subreddit = subreddit <NEW_LINE> super(WikiPage, self).__init__(reddit, _data) <NEW_LINE> self._mod = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}(subreddit={!r}, name={!r})'.format( self.__class__.__name__, self.subreddit, self.name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}/{}'.format(self.subreddit, self.name) <NEW_LINE> <DEDENT> def _fetch(self): <NEW_LINE> <INDENT> params = {'v': self._revision} if self._revision else None <NEW_LINE> data = self._reddit.get(self._info_path(), params=params)['data'] <NEW_LINE> data['revision_by'] = Redditor(self._reddit, _data=data['revision_by']['data']) <NEW_LINE> self.__dict__.update(data) <NEW_LINE> self._fetched = True <NEW_LINE> <DEDENT> def _info_path(self): <NEW_LINE> <INDENT> return API_PATH['wiki_page'].format(subreddit=self.subreddit, page=self.name) <NEW_LINE> <DEDENT> def edit(self, content, reason=None, **other_settings): <NEW_LINE> <INDENT> other_settings.update({'content': content, 'page': self.name, 'reason': reason}) <NEW_LINE> self._reddit.post(API_PATH['wiki_edit'].format( subreddit=self.subreddit), data=other_settings) <NEW_LINE> <DEDENT> def revisions(self, **generator_kwargs): <NEW_LINE> <INDENT> url = API_PATH['wiki_page_revisions'].format(subreddit=self.subreddit, page=self.name) <NEW_LINE> return self._revision_generator(self.subreddit, url, generator_kwargs) | An individual WikiPage object. | 62598fc4283ffb24f3cf3b57 |
class Join(models.Model): <NEW_LINE> <INDENT> email = models.EmailField() <NEW_LINE> ip_address = models.CharField(max_length=120, default='ABC') <NEW_LINE> timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) <NEW_LINE> updated = models.DateTimeField(auto_now_add=False, auto_now=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.email | Model to save all the emails for people joining the web page | 62598fc563b5f9789fe85446 |
class Graph(object): <NEW_LINE> <INDENT> def __init__(self, connections, directed=False): <NEW_LINE> <INDENT> self._graph = defaultdict(set) <NEW_LINE> self._directed = directed <NEW_LINE> self.add_connections(connections) <NEW_LINE> <DEDENT> def add_connections(self, connections): <NEW_LINE> <INDENT> for node1, node2 in connections: <NEW_LINE> <INDENT> self.add(node1, node2) <NEW_LINE> <DEDENT> <DEDENT> def add(self, node1, node2): <NEW_LINE> <INDENT> self._graph[node1].add(node2) <NEW_LINE> if not self._directed: <NEW_LINE> <INDENT> self._graph[node2].add(node1) <NEW_LINE> <DEDENT> <DEDENT> def remove(self, node): <NEW_LINE> <INDENT> for _, connections in self._graph.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> connections.remove(node) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> del self._graph[node] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def is_connected(self, node1, node2): <NEW_LINE> <INDENT> return node1 in self._graph and node2 in self._graph[node1] <NEW_LINE> <DEDENT> def find_path(self, node1, node2, path=None): <NEW_LINE> <INDENT> path = path + [node1] <NEW_LINE> if node1 == node2: <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> if node1 not in self._graph: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for node in self._graph[node1]: <NEW_LINE> <INDENT> if node not in path: <NEW_LINE> <INDENT> new_path = self.find_path(node, node2, path) <NEW_LINE> if new_path: <NEW_LINE> <INDENT> return new_path <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def adjacency_matrix(self): <NEW_LINE> <INDENT> num = len(self._graph) <NEW_LINE> matrix = [["inf" for i in range(num)] for j in range(num)] <NEW_LINE> for i, j in [(k, k) for k in range(5)]: <NEW_LINE> <INDENT> matrix[i][j] = 0 <NEW_LINE> <DEDENT> for k, v in self._graph.items(): <NEW_LINE> <INDENT> k <NEW_LINE> <DEDENT> return matrix <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}({})'.format(self.__class__.__name__, dict(self._graph)) | Graph class, undirected by default. | 62598fc54a966d76dd5ef1a8 |
class ReferenceValuesValidator: <NEW_LINE> <INDENT> implements(IValidator) <NEW_LINE> name = "referencevalues_validator" <NEW_LINE> def __call__(self, value, *args, **kwargs): <NEW_LINE> <INDENT> instance = kwargs['instance'] <NEW_LINE> request = kwargs.get('REQUEST', {}) <NEW_LINE> if instance.REQUEST.get('validated', '') == self.name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> instance.REQUEST['validated'] = self.name <NEW_LINE> <DEDENT> ts = getToolByName(instance, 'translation_service').translate <NEW_LINE> ress = request.get('result', {})[0] <NEW_LINE> mins = request.get('min', {})[0] <NEW_LINE> maxs = request.get('max', {})[0] <NEW_LINE> errs = request.get('error', {})[0] <NEW_LINE> uids = ress.keys() <NEW_LINE> for uid in uids: <NEW_LINE> <INDENT> res = ress[uid] if ress[uid] else '0' <NEW_LINE> min = mins[uid] if mins[uid] else '0' <NEW_LINE> max = maxs[uid] if maxs[uid] else '0' <NEW_LINE> err = errs[uid] if errs[uid] else '0' <NEW_LINE> try: <NEW_LINE> <INDENT> res = float(res) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return ts(_("Validation failed: Expected values must be numeric")) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> min = float(min) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return ts(_("Validation failed: Min values must be numeric")) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> max = float(max) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return ts(_("Validation failed: Max values must be numeric")) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> err = float(err) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return ts(_("Validation failed: Percentage error values must be numeric")) <NEW_LINE> <DEDENT> if min > max: <NEW_LINE> <INDENT> return ts(_("Validation failed: Max values must be greater than Min values")) <NEW_LINE> <DEDENT> if res < min or res > max: <NEW_LINE> <INDENT> return ts(_("Validation failed: Expected values must be between Min and Max values")) <NEW_LINE> <DEDENT> if err < 0 or err > 100: <NEW_LINE> <INDENT> return ts(_("Validation failed: Percentage error values must be between 0 and 100")) <NEW_LINE> <DEDENT> <DEDENT> return True | Min value must be below max value
Percentage value must be between 0 and 100
Values must be numbers
Expected values must be between min and max values | 62598fc57b180e01f3e491b9 |
class EditContView(ContextualActionView): <NEW_LINE> <INDENT> __events__ = ('on_undo', 'on_redo', 'on_cut', 'on_copy', 'on_paste', 'on_delete', 'on_selectall', 'on_next_screen', 'on_prev_screen') <NEW_LINE> action_btn_next_screen = ObjectProperty(None, allownone=True) <NEW_LINE> action_btn_prev_screen = ObjectProperty(None, allownone=True) <NEW_LINE> def show_action_btn_screen(self, show): <NEW_LINE> <INDENT> if self.action_btn_next_screen: <NEW_LINE> <INDENT> self.remove_widget(self.action_btn_next_screen) <NEW_LINE> <DEDENT> if self.action_btn_prev_screen: <NEW_LINE> <INDENT> self.remove_widget(self.action_btn_prev_screen) <NEW_LINE> <DEDENT> self.action_btn_next_screen = None <NEW_LINE> self.action_btn_prev_screen = None <NEW_LINE> if show: <NEW_LINE> <INDENT> self.action_btn_next_screen = ActionButton(text="Next Screen") <NEW_LINE> self.action_btn_next_screen.bind(on_press=partial(self.dispatch, 'on_next_screen')) <NEW_LINE> self.action_btn_prev_screen = ActionButton(text="Previous Screen") <NEW_LINE> self.action_btn_prev_screen.bind(on_press=partial(self.dispatch, 'on_prev_screen')) <NEW_LINE> self.add_widget(self.action_btn_next_screen) <NEW_LINE> self.add_widget(self.action_btn_prev_screen) <NEW_LINE> <DEDENT> <DEDENT> def on_undo(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_redo(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_cut(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_copy(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_paste(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_delete(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_selectall(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_next_screen(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_prev_screen(self, *args): <NEW_LINE> <INDENT> pass | EditContView is a ContextualActionView, used to display Edit items:
Copy, Cut, Paste, Undo, Redo, Select All, Add Custom Widget. It has
events:
on_undo, emitted when Undo ActionButton is clicked.
on_redo, emitted when Redo ActionButton is clicked.
on_cut, emitted when Cut ActionButton is clicked.
on_copy, emitted when Copy ActionButton is clicked.
on_paste, emitted when Paste ActionButton is clicked.
on_delete, emitted when Delete ActionButton is clicked.
on_selectall, emitted when Select All ActionButton is clicked.
on_add_custom, emitted when Add Custom ActionButton is clicked. | 62598fc5a05bb46b3848ab3f |
class NewsSerializer(FlexFieldsModelSerializer): <NEW_LINE> <INDENT> expandable_fields = { "categories": (CategorySerializer, {"source": "categories", "many": True}), "language": (LanguageSerializer, {"source": "language"}), } <NEW_LINE> url = URLField(read_only=True, allow_null=True) <NEW_LINE> media = NewsMediaSerializer(many=True, read_only=True) <NEW_LINE> breadcrumb = ReadOnlyField() <NEW_LINE> categories = PrimaryKeyRelatedField(many=True, read_only=True) <NEW_LINE> groups = GroupSerializer(many=True, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = models.News <NEW_LINE> exclude = ("source", "tags") | ## Expansions
To activate relation expansion add the desired fields as a comma separated
list to the `expand` query parameter like this:
?expand=<field>,<field>,<field>,...
The following relational fields can be expanded:
* `categories`
* `language` | 62598fc5283ffb24f3cf3b58 |
class DiffbotControlPanel(ControlPanelForm): <NEW_LINE> <INDENT> form_fields = form.FormFields(IDiffbotSettings) <NEW_LINE> label = _(u"Diffbot API") <NEW_LINE> description = _(u"Diffbot API settings") <NEW_LINE> form_name = _(u"Diffbot settings") | Diffbot API
| 62598fc57047854f4633f6a6 |
class ANRException(UnexpectedUIStateException): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(ANRException, self).__init__(message) | Application Not Responded | 62598fc576e4537e8c3ef879 |
class ConverterABC(SubConverter): <NEW_LINE> <INDENT> registerFormats = ('abc',) <NEW_LINE> registerInputExtensions = ('abc',) <NEW_LINE> def parseData(self, strData, number=None): <NEW_LINE> <INDENT> from music21 import abcFormat <NEW_LINE> af = abcFormat.ABCFile() <NEW_LINE> abcHandler = af.readstr(strData, number=number) <NEW_LINE> if abcHandler.definesReferenceNumbers(): <NEW_LINE> <INDENT> self.stream = abcFormat.translate.abcToStreamOpus(abcHandler, number=number) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> abcFormat.translate.abcToStreamScore(abcHandler, self.stream) <NEW_LINE> <DEDENT> <DEDENT> def parseFile(self, fp, number=None): <NEW_LINE> <INDENT> from music21 import abcFormat <NEW_LINE> af = abcFormat.ABCFile() <NEW_LINE> af.open(fp) <NEW_LINE> abcHandler = af.read(number=number) <NEW_LINE> af.close() <NEW_LINE> if abcHandler.definesReferenceNumbers(): <NEW_LINE> <INDENT> self.stream = abcFormat.translate.abcToStreamOpus(abcHandler, number=number) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> abcFormat.translate.abcToStreamScore(abcHandler, self.stream) | Simple class wrapper for parsing ABC.
Input only | 62598fc5377c676e912f6edf |
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect( 0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect) | 一个对飞船发射的子弹进行管理的类 | 62598fc5f9cc0f698b1c543c |
class Capturing(list): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> self._stdout = sys.stdout <NEW_LINE> sys.stdout = self._stringio = StringIO() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> self.extend(self._stringio.getvalue().splitlines()) <NEW_LINE> sys.stdout = self._stdout | Context that captures the standard output of a function | 62598fc5283ffb24f3cf3b5a |
class ShowPlatformSudiPkiSchema(MetaParser): <NEW_LINE> <INDENT> schema = { Optional('Cisco Manufacturing CA III certificate') : str, Optional('Cisco Manufacturing CA') : str, Optional('Cisco Manufacturing CA III') : str, Optional('Cisco Manufacturing CA SHA2') : str, } | Schema for show platform sudi pki. | 62598fc55fc7496912d483e5 |
class updateComment(generics.GenericAPIView): <NEW_LINE> <INDENT> permissions_classes = [ permissions.IsAuthenticated ] <NEW_LINE> def post(self, request, commentId, *args, **kwargs): <NEW_LINE> <INDENT> print(request.data) <NEW_LINE> newContent = request.data.get('newContent') <NEW_LINE> queryset = Comment.objects.get(id=commentId) <NEW_LINE> queryset.content = newContent <NEW_LINE> queryset.save() <NEW_LINE> print(queryset) <NEW_LINE> updatedComment = CommentSerializer(queryset).data <NEW_LINE> return Response({'updatedComment': updatedComment}) | 상품 댓글 수정
---
## `/product/updateComment/<int:commentId>` | 62598fc560cbc95b06364613 |
class HelpCmd(Cmd): <NEW_LINE> <INDENT> implements(ICmdArgumentsSyntax) <NEW_LINE> command('help') <NEW_LINE> @defer.inlineCallbacks <NEW_LINE> def arguments(self): <NEW_LINE> <INDENT> parser = VirtualConsoleArgumentParser() <NEW_LINE> choices = [i.name for i in (yield self._commands())] <NEW_LINE> parser.add_argument('command', nargs='?', choices=choices, help="command to get help for") <NEW_LINE> defer.returnValue(parser) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def execute(self, args): <NEW_LINE> <INDENT> if args.command: <NEW_LINE> <INDENT> yield self._cmd_help(args.command) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd_names = ', '.join(sorted(i._format_names() for i in (yield self._commands()))) <NEW_LINE> self.write("valid commands: %s\n" % cmd_names) <NEW_LINE> <DEDENT> <DEDENT> @db.transact <NEW_LINE> def _cmd_help(self, name): <NEW_LINE> <INDENT> deferred = self.protocol.get_command_class(name)(self.protocol).parse_args(['-h']) <NEW_LINE> @deferred <NEW_LINE> def on_error(*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> @db.transact <NEW_LINE> def _commands(self): <NEW_LINE> <INDENT> dummy = NoCommand(self.protocol) <NEW_LINE> cmds = [] <NEW_LINE> for d in self.protocol.environment['PATH'].split(':'): <NEW_LINE> <INDENT> for i in dummy.traverse(d) or []: <NEW_LINE> <INDENT> if ICommand.providedBy(i): <NEW_LINE> <INDENT> cmds.append(i.cmd) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return cmds | Outputs the names of all commands. | 62598fc57cff6e4e811b5cfb |
class PyPythonHtmlgen(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/srittau/python-htmlgen" <NEW_LINE> url = "https://github.com/srittau/python-htmlgen/archive/v1.2.2.tar.gz" <NEW_LINE> version('1.2.2', sha256='9dc60e10511f0fd13014659514c6c333498c21779173deb585cd4964ea667770') <NEW_LINE> conflicts('python@3.0:3.3.99') <NEW_LINE> depends_on('py-setuptools', type='build') <NEW_LINE> depends_on('py-typing', type='test') <NEW_LINE> depends_on('py-python-asserts', type='test') | Library to generate HTML from classes.
| 62598fc57047854f4633f6a8 |
class TestKendallTau(object): <NEW_LINE> <INDENT> def test_kendalltau(self): <NEW_LINE> <INDENT> X, _ = load_energy(return_dataset=True).to_numpy() <NEW_LINE> expected = np.array( [ [1.0, -1.0, -0.2724275, -0.7361443, 0.7385489, 0.0, 0.0, 0.0], [-1.0, 1.0, 0.2724275, 0.7361443, -0.7385489, 0.0, 0.0, 0.0], [-0.2724275, 0.2724275, 1.0, -0.15192004, 0.19528337, 0.0, 0.0, 0.0], [-0.73614431, 0.73614431, -0.15192004, 1.0, -0.87518995, 0.0, 0.0, 0.0], [0.73854895, -0.73854895, 0.19528337, -0.87518995, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.15430335], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15430335, 1.0], ] ) <NEW_LINE> actual = kendalltau(X) <NEW_LINE> npt.assert_almost_equal(expected, actual) <NEW_LINE> <DEDENT> def test_kendalltau_shape(self): <NEW_LINE> <INDENT> X, _ = load_energy(return_dataset=True).to_numpy() <NEW_LINE> corr = kendalltau(X) <NEW_LINE> assert corr.shape[0] == corr.shape[1] <NEW_LINE> for (i, j), val in np.ndenumerate(corr): <NEW_LINE> <INDENT> assert corr[j][i] == pytest.approx(val) <NEW_LINE> <DEDENT> <DEDENT> def test_kendalltau_1D(self): <NEW_LINE> <INDENT> with pytest.raises(IndexError, match="tuple index out of range"): <NEW_LINE> <INDENT> X = 0.1 * np.arange(10) <NEW_LINE> kendalltau(X) | Test the Kendall-Tau correlation metric | 62598fc5d486a94d0ba2c2a7 |
class OneDimNondeterministicCellLoop(NondeterministicCellLoopMixin,OneDimCellLoop): <NEW_LINE> <INDENT> pass | This Nondeterministic Cell Loop loops over one dimension, skipping cells
with a probability of probab. | 62598fc523849d37ff851389 |
class TBoolColumn: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.LIST, 'values', (TType.BOOL,None), None, ), (2, TType.STRING, 'nulls', None, None, ), ) <NEW_LINE> def __init__(self, values=None, nulls=None,): <NEW_LINE> <INDENT> self.values = values <NEW_LINE> self.nulls = nulls <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.values = [] <NEW_LINE> (_etype51, _size48) = iprot.readListBegin() <NEW_LINE> for _i52 in xrange(_size48): <NEW_LINE> <INDENT> _elem53 = iprot.readBool(); <NEW_LINE> self.values.append(_elem53) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.nulls = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('TBoolColumn') <NEW_LINE> if self.values is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('values', TType.LIST, 1) <NEW_LINE> oprot.writeListBegin(TType.BOOL, len(self.values)) <NEW_LINE> for iter54 in self.values: <NEW_LINE> <INDENT> oprot.writeBool(iter54) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.nulls is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('nulls', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.nulls) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.values is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field values is unset!') <NEW_LINE> <DEDENT> if self.nulls is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field nulls is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- values
- nulls | 62598fc5091ae35668704efe |
class BTreeST(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.root = Page(True, 0) <NEW_LINE> self.numpages = 1 <NEW_LINE> self.N = 0 <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self.numpages, self.N <NEW_LINE> <DEDENT> def contains(self, key): <NEW_LINE> <INDENT> def helper_contains(p, key): <NEW_LINE> <INDENT> if p.isExternal(): <NEW_LINE> <INDENT> return p.contains(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return helper_contains(p.next(key), key) <NEW_LINE> <DEDENT> <DEDENT> return helper_contains(self.root, key) <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> def helper_get(page, key): <NEW_LINE> <INDENT> if page.isExternal(): <NEW_LINE> <INDENT> for e in page.keylist[:page.m]: <NEW_LINE> <INDENT> if key == e.key: <NEW_LINE> <INDENT> return e.values <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nextpage = page.getNext(key) <NEW_LINE> return helper_get(nextpage, key) <NEW_LINE> <DEDENT> <DEDENT> return helper_get(self.root, key) <NEW_LINE> <DEDENT> def add(self, r): <NEW_LINE> <INDENT> soup = BeautifulSoup(r.text, "lxml") <NEW_LINE> list_of_words = [] <NEW_LINE> for string in soup.stripped_strings: <NEW_LINE> <INDENT> if string and not js.search(string): <NEW_LINE> <INDENT> words = (word for word in string.split() if p.match(word) if word not in list_of_words) <NEW_LINE> for word in words: <NEW_LINE> <INDENT> list_of_words.append(word) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> list_of_words.sort() <NEW_LINE> def helper_add(page, word): <NEW_LINE> <INDENT> if page.isExternal(): <NEW_LINE> <INDENT> if not page.contains(word): <NEW_LINE> <INDENT> page.add(word, r.url, None) <NEW_LINE> self.N += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> page.addValue(word, r.url) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> nextpage = page.getNext(word) <NEW_LINE> if not nextpage: <NEW_LINE> <INDENT> return("file not found") <NEW_LINE> <DEDENT> helper_add(nextpage, word) <NEW_LINE> if nextpage.isFull(): <NEW_LINE> <INDENT> new_page = nextpage.split(self.numpages) <NEW_LINE> self.numpages += 1 <NEW_LINE> page.add(new_page.keylist[0].key, value=None, nextpage=new_page) <NEW_LINE> new_page.close() <NEW_LINE> <DEDENT> nextpage.close() <NEW_LINE> return <NEW_LINE> <DEDENT> for word in list_of_words: <NEW_LINE> <INDENT> helper_add(self.root, word) <NEW_LINE> if self.root.isFull(): <NEW_LINE> <INDENT> self.root = self.splitRoot() <NEW_LINE> self.numpages += 2 <NEW_LINE> print(self.root.m) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def splitRoot(self): <NEW_LINE> <INDENT> return self.root.splitRoot(self.numpages) | balanced M order B-tree
underlying data structure for a reverse web index
each node (page) is stored as a file on disk
word => file that contains word | 62598fc5a8370b77170f06b1 |
class Mapping(Sized, Iterable, Container): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def __getitem__(self, key): <NEW_LINE> <INDENT> raise KeyError <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def iterkeys(self): <NEW_LINE> <INDENT> return iter(self) <NEW_LINE> <DEDENT> def itervalues(self): <NEW_LINE> <INDENT> for key in self: <NEW_LINE> <INDENT> yield self[key] <NEW_LINE> <DEDENT> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> for key in self: <NEW_LINE> <INDENT> yield (key, self[key]) <NEW_LINE> <DEDENT> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return list(self) <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return [(key, self[key]) for key in self] <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return [self[key] for key in self] <NEW_LINE> <DEDENT> __hash__ = None <NEW_LINE> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Mapping): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return dict(self.items()) == dict(other.items()) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | A Mapping is a generic container for associating key/value
pairs.
This class provides concrete generic implementations of all
methods except for __getitem__, __iter__, and __len__. | 62598fc50fa83653e46f51bd |
class UDPMCastServer(UDPServer): <NEW_LINE> <INDENT> def _create_socket(self): <NEW_LINE> <INDENT> self._addrinfo = addrinfo = socket.getaddrinfo(self._bind[0], None)[0] <NEW_LINE> sock = socket.socket(addrinfo[0], socket.SOCK_DGRAM) <NEW_LINE> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> sock.bind(('', self._bind[1])) <NEW_LINE> group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) <NEW_LINE> if addrinfo[0] == socket.AF_INET: <NEW_LINE> <INDENT> mreq = group_bin + struct.pack('=I', socket.INADDR_ANY) <NEW_LINE> sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mreq = group_bin + struct.pack('@I', 0) <NEW_LINE> sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) <NEW_LINE> <DEDENT> return sock <NEW_LINE> <DEDENT> def setTTL(self, ttl): <NEW_LINE> <INDENT> ttl_bin = struct.pack('@i', ttl) <NEW_LINE> if self._addrinfo[0] == socket.AF_INET: <NEW_LINE> <INDENT> self._sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin) | classdocs | 62598fc59f288636728189e7 |
class create(BrowserView): <NEW_LINE> <INDENT> def go(self): <NEW_LINE> <INDENT> imAlbumid="MyTestAlbum" <NEW_LINE> imPhotoid=("MyTestPhoto1","MyTestPhoto2","MyTestPhoto3","MyTestPhoto4") <NEW_LINE> debug="Creating imAlbum "+imAlbumid+"/n" <NEW_LINE> try: <NEW_LINE> <INDENT> self.context.invokeFactory(id=imAlbumid, type_name='imAlbum') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> debug=debug+" OOPS !! "+"/n" <NEW_LINE> <DEDENT> container = getattr(self.context, "MyTestAlbum", None) <NEW_LINE> for photo in imPhotoid: <NEW_LINE> <INDENT> debug=debug+"Creating imPhoto "+photo+"/n" <NEW_LINE> try: <NEW_LINE> <INDENT> container.invokeFactory(id=photo, type_name='imPhoto') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> debug=debug+" OOPS !! "+"/n" <NEW_LINE> <DEDENT> imPhotoSmallId=photo+"_small" <NEW_LINE> debug=debug+"Creating imPhotoSmall "+imPhotoSmallId+"/n" <NEW_LINE> try: <NEW_LINE> <INDENT> container.invokeFactory(id=imPhotoSmallId, type_name='imPhotoSmall') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> debug=debug+" OOPS !! "+"/n" <NEW_LINE> <DEDENT> <DEDENT> return debug | a view | 62598fc571ff763f4b5e7a54 |
class AccountSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Account <NEW_LINE> fields = '__all__' | Serializer for Account model | 62598fc55166f23b2e2436b8 |
class S20Switch(SwitchDevice): <NEW_LINE> <INDENT> def __init__(self, name, s20): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._s20 = s20 <NEW_LINE> self._state = False <NEW_LINE> self._exc = S20Exception <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._state = self._s20.on <NEW_LINE> <DEDENT> except self._exc: <NEW_LINE> <INDENT> _LOGGER.exception("Error while fetching S20 state") <NEW_LINE> <DEDENT> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._s20.on = True <NEW_LINE> <DEDENT> except self._exc: <NEW_LINE> <INDENT> _LOGGER.exception("Error while turning on S20") <NEW_LINE> <DEDENT> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._s20.on = False <NEW_LINE> <DEDENT> except self._exc: <NEW_LINE> <INDENT> _LOGGER.exception("Error while turning off S20") | Representation of an S20 switch. | 62598fc53617ad0b5ee0641e |
@ISISSansSystemTest(SANSInstrument.SANS2D) <NEW_LINE> class SANS2DMinimalSingleReductionTest_V2(systemtesting.MantidSystemTest): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SANS2DMinimalSingleReductionTest_V2, self).__init__() <NEW_LINE> config['default.instrument'] = 'SANS2D' <NEW_LINE> self.tolerance_is_rel_err = True <NEW_LINE> self.tolerance = 1.0e-2 <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> UseCompatibilityMode() <NEW_LINE> SANS2D() <NEW_LINE> MaskFile('MaskSANS2DReductionGUI.txt') <NEW_LINE> AssignSample('22048') <NEW_LINE> AssignCan('22023') <NEW_LINE> TransmissionSample('22041', '22024') <NEW_LINE> TransmissionCan('22024', '22024') <NEW_LINE> reduced = WavRangeReduction() <NEW_LINE> RenameWorkspace(reduced, OutputWorkspace='trans_test_rear') <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> self.disableChecking.append('Instrument') <NEW_LINE> return "trans_test_rear", "SANSReductionGUI.nxs" | Minimal script to perform full reduction in single mode | 62598fc560cbc95b06364615 |
class TestUtils(unittest.TestCase): <NEW_LINE> <INDENT> def test_overlap_p_1(self): <NEW_LINE> <INDENT> a = (0, 1, 0, 1) <NEW_LINE> b = (0.2, 2, 0.2, 2) <NEW_LINE> res = mht.utils.overlap_pa(a, b) <NEW_LINE> self.assertAlmostEqual(res, 0.64) <NEW_LINE> <DEDENT> def test_overlap_p_2(self): <NEW_LINE> <INDENT> a = (0, 1, 0, 1) <NEW_LINE> b = (-0.2, 2, -0.2, 2) <NEW_LINE> res = mht.utils.overlap_pa(a, b) <NEW_LINE> self.assertAlmostEqual(res, 1) <NEW_LINE> <DEDENT> def test_overlap_p_3(self): <NEW_LINE> <INDENT> a = (0, 1, 0, 1) <NEW_LINE> b = (0.2, 0.8, 0.2, 0.8) <NEW_LINE> res = mht.utils.overlap_pa(a, b) <NEW_LINE> self.assertAlmostEqual(res, 0.36) | Testshell for utilities. | 62598fc555399d3f056267ef |
class ClientPutInServer(_ListenerManager): <NEW_LINE> <INDENT> manager = client_put_in_server_listener_manager | Register/unregister a ClientPutInServer listener. | 62598fc5bf627c535bcb177f |
class ListIterator(JavaIterator): <NEW_LINE> <INDENT> def __init__(self, l): <NEW_LINE> <INDENT> self.nr_pairs = len(l) <NEW_LINE> self._iter = iter(l) <NEW_LINE> <DEDENT> def hasNext(self): <NEW_LINE> <INDENT> return self.nr_pairs > 0 <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> self.nr_pairs -= 1 <NEW_LINE> return next(self._iter) | Adds the hasNext() method to the standard list iterator
>>> it = ListIterator([(1, 0), (2, 1), (3, 0)])
>>> it.next()
(1, 0)
>>> it.next()
(2, 1)
>>> it.next()
(3, 0)
>>> it.hasNext()
False | 62598fc5956e5f7376df57ea |
class Magic(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.MIME_TYPE = 0x000010 <NEW_LINE> self.PRESERVE_ATIME = 0x000080 <NEW_LINE> self.NO_CHECK_ENCODING = 0x200000 <NEW_LINE> self.DEFAULT = self.MIME_TYPE | self.PRESERVE_ATIME | self.NO_CHECK_ENCODING <NEW_LINE> libmagic = ctypes.util.find_library('magic') <NEW_LINE> self.libmagic = ctypes.CDLL(libmagic, use_errno=True) <NEW_LINE> self._magic_open = self.libmagic.magic_open <NEW_LINE> self._magic_open.restype = ctypes.c_void_p <NEW_LINE> self._magic_open.argtypes = [ctypes.c_int] <NEW_LINE> self._magic_close = self.libmagic.magic_close <NEW_LINE> self._magic_close.restype = None <NEW_LINE> self._magic_close.argtypes = [ctypes.c_void_p] <NEW_LINE> self._magic_load = self.libmagic.magic_load <NEW_LINE> self._magic_load.restype = ctypes.c_int <NEW_LINE> self._magic_load.argtypes = [ctypes.c_void_p, ctypes.c_char_p] <NEW_LINE> self._magic_file = self.libmagic.magic_file <NEW_LINE> self._magic_file.restype = ctypes.c_char_p <NEW_LINE> self._magic_file.argtypes = [ctypes.c_void_p, ctypes.c_char_p] <NEW_LINE> self.cookie = self._magic_open(self.DEFAULT) <NEW_LINE> self._magic_load(self.cookie, None) <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> if self.cookie and self._magic_close: <NEW_LINE> <INDENT> self._magic_close(self.cookie) <NEW_LINE> <DEDENT> <DEDENT> def error(self): <NEW_LINE> <INDENT> return os.strerror(ctypes.get_errno()) <NEW_LINE> <DEDENT> def get(self, path): <NEW_LINE> <INDENT> if not isinstance(path, str): <NEW_LINE> <INDENT> path = path.encode('utf-8') <NEW_LINE> <DEDENT> if misc.python3: <NEW_LINE> <INDENT> path = bytes(path, 'utf-8') <NEW_LINE> <DEDENT> result = self._magic_file(self.cookie, path) <NEW_LINE> if not result or result == -1: <NEW_LINE> <INDENT> raise Exception(self.error()) <NEW_LINE> <DEDENT> return result | Magic wrapper | 62598fc5cc40096d6161a344 |
class Subtasks(object): <NEW_LINE> <INDENT> def __init__(self, api): <NEW_LINE> <INDENT> self.__api = api <NEW_LINE> <DEDENT> def new(self, task, title): <NEW_LINE> <INDENT> from tasks import Task <NEW_LINE> if isinstance(task, int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif isinstance(task, Task): <NEW_LINE> <INDENT> task = task.id <NEW_LINE> <DEDENT> elif isinstance(task, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> task = int(task) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> subtask = self.__api.call('subtasks/create', id_task=task, title=title)['subtask'] <NEW_LINE> return Subtask(self.__api, subtask) | Subtasks give an interface for manage subtasks in Producteev. | 62598fc5851cf427c66b858d |
class GroupModifyLoop(GroupTest): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> port1, = openflow_ports(1) <NEW_LINE> msg = ofp.message.group_add( group_type=ofp.OFPGT_ALL, group_id=0, buckets=[ create_bucket(actions=[ofp.action.output(port1)])]) <NEW_LINE> self.controller.message_send(msg) <NEW_LINE> do_barrier(self.controller) <NEW_LINE> msg = ofp.message.group_add( group_type=ofp.OFPGT_ALL, group_id=1, buckets=[ create_bucket(actions=[ofp.action.group(0)])]) <NEW_LINE> self.controller.message_send(msg) <NEW_LINE> do_barrier(self.controller) <NEW_LINE> msg = ofp.message.group_add( group_type=ofp.OFPGT_ALL, group_id=2, buckets=[ create_bucket(actions=[ofp.action.group(1)])]) <NEW_LINE> self.controller.message_send(msg) <NEW_LINE> do_barrier(self.controller) <NEW_LINE> msg = ofp.message.group_modify( group_type=ofp.OFPGT_ALL, group_id=0, buckets=[ create_bucket(actions=[ofp.action.group(2)])]) <NEW_LINE> response, _ = self.controller.transact(msg) <NEW_LINE> self.assertIsInstance(response, ofp.message.group_mod_failed_error_msg) <NEW_LINE> self.assertEquals(response.code, ofp.OFPGMFC_LOOP) | A modification causing loop should result in OFPET_GROUP_MOD_FAILED/OFPGMFC_LOOP | 62598fc55fcc89381b2662b9 |
class LookUpTableBrain(Brain): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._table = {} <NEW_LINE> <DEDENT> def configure(self,**kargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def learn(self,dataset): <NEW_LINE> <INDENT> if dataset == {}: raise LookUpTableBrainException("Dataset for learning is empty.") <NEW_LINE> self._table = dataset <NEW_LINE> <DEDENT> def think(self,data): <NEW_LINE> <INDENT> try: return self._table[data] <NEW_LINE> except KeyError: raise LookUpTableBrainException("Don't know.") | Brain class based on Lookup table
Attributes:
_table - Look up table | 62598fc550812a4eaa620d51 |
class Ospf(VersionedPanObject): <NEW_LINE> <INDENT> NAME = None <NEW_LINE> CHILDTYPES = ( "network.OspfArea", "network.OspfAuthProfile", "network.OspfExportRules", ) <NEW_LINE> def _setup(self): <NEW_LINE> <INDENT> self._xpaths.add_profile(value='/protocol/ospf') <NEW_LINE> params = [] <NEW_LINE> params.append(VersionedParamPath( 'enable', default=True, path='enable', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'router_id')) <NEW_LINE> params.append(VersionedParamPath( 'reject_default_route', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'allow_redist_default_route', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'rfc1583', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'spf_calculation_delay', path='timers/spf-calculation-delay', vartype='int')) <NEW_LINE> params.append(VersionedParamPath( 'lsa_interval', path='timers/lsa-interval', vartype='int')) <NEW_LINE> params.append(VersionedParamPath( 'graceful_restart_enable', path='graceful-restart/enable', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'gr_grace_period', path='graceful-restart/grace-period', vartype='int')) <NEW_LINE> params.append(VersionedParamPath( 'gr_helper_enable', path='graceful-restart/helper-enable', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'gr_strict_lsa_checking', path='graceful-restart/strict-LSA-checking', vartype='yesno')) <NEW_LINE> params.append(VersionedParamPath( 'gr_max_neighbor_restart_time', path='graceful-restart/max-neighbor-restart-time', vartype='int')) <NEW_LINE> self._params = tuple(params) | OSPF Process
Args:
enable (bool): Enable OSPF (Default: True)
router_id (str): Router ID in IP format (eg. 1.1.1.1)
reject_default_route (bool): Reject default route
allow_redist_default_route (bool): Allow redistribution in default route
rfc1583 (bool): rfc1583
spf_calculation_delay (int): SPF calculation delay
lsa_interval (int): LSA interval
graceful_restart_enable (bool): Enable OSPF graceful restart
gr_grace_period (int): Graceful restart period
gr_helper_enable (bool): Graceful restart helper enable
gr_strict_lsa_checking (bool): Graceful restart strict lsa checking
gr_max_neighbor_restart_time (int): Graceful restart neighbor restart time | 62598fc55fdd1c0f98e5e26b |
class ScrapyPriorityQueue(PriorityQueue): <NEW_LINE> <INDENT> def __init__(self, crawler, qfactory, startprios=(), serialize=False): <NEW_LINE> <INDENT> super(ScrapyPriorityQueue, self).__init__(qfactory, startprios) <NEW_LINE> self.serialize = serialize <NEW_LINE> self.spider = crawler.spider <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_crawler(cls, crawler, qfactory, startprios=(), serialize=False): <NEW_LINE> <INDENT> return cls(crawler, qfactory, startprios, serialize) <NEW_LINE> <DEDENT> def push(self, request, priority=0): <NEW_LINE> <INDENT> if self.serialize: <NEW_LINE> <INDENT> request = request_to_dict(request, self.spider) <NEW_LINE> <DEDENT> super(ScrapyPriorityQueue, self).push(request, priority) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> request = super(ScrapyPriorityQueue, self).pop() <NEW_LINE> if request and self.serialize: <NEW_LINE> <INDENT> request = request_from_dict(request, self.spider) <NEW_LINE> <DEDENT> return request | PriorityQueue which works with scrapy.Request instances and
can optionally convert them to/from dicts before/after putting to a queue. | 62598fc5a219f33f346c6ae0 |
class IBUCalculation(): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def tinseth_ibu(AA, m, u, c): <NEW_LINE> <INDENT> return c * u * m * AA | Container class for IBU calculations
| 62598fc5656771135c489948 |
class SubnetManagerInitializationError(Exception): <NEW_LINE> <INDENT> pass | Custom initialization exception
| 62598fc52c8b7c6e89bd3a9c |
class Supytube(callbacks.Plugin): <NEW_LINE> <INDENT> threaded = True <NEW_LINE> def doPrivmsg(self, irc, msg): <NEW_LINE> <INDENT> if(self.registryValue('enable', msg.args[0])): <NEW_LINE> <INDENT> if(msg.args[1].find("youtube") != -1 or msg.args[1].find("youtu.be") != -1): <NEW_LINE> <INDENT> youtube_pattern = re.compile('(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\?=\-]*)(&(amp;)?[\w\?=]*)?') <NEW_LINE> m = youtube_pattern.search(msg.args[1]); <NEW_LINE> if(m): <NEW_LINE> <INDENT> r = requests.get('http://gdata.youtube.com/feeds/api/videos/%s?v=2&alt=json' % m.group(1)) <NEW_LINE> data = json.loads(r.content) <NEW_LINE> likes = float(data['entry']["yt$rating"]['numLikes']) <NEW_LINE> dislikes = float(data['entry']["yt$rating"]['numDislikes']) <NEW_LINE> rating = (likes/(likes+dislikes))*100 <NEW_LINE> message = 'Title: %s, Views: %s, Rating: %s%%' % (ircutils.bold(data['entry']['title']['$t']), ircutils.bold(str(locale.format("%d", int(data['entry']['yt$statistics']['viewCount']), grouping=True))), ircutils.bold(round(float(rating)))) <NEW_LINE> message = message.encode("utf-8", "replace") <NEW_LINE> irc.queueMsg(ircmsgs.privmsg(msg.args[0], message)) <NEW_LINE> <DEDENT> <DEDENT> if(msg.args[1].find("vimeo") != -1): <NEW_LINE> <INDENT> vimeo_pattern = re.compile('vimeo.com/(\\d+)') <NEW_LINE> m = vimeo_pattern.search(msg.args[1]); <NEW_LINE> if(m): <NEW_LINE> <INDENT> r = requests.get("http://vimeo.com/api/v2/video/%s.json" % m.group(1)) <NEW_LINE> data = json.loads(r.content) <NEW_LINE> message = 'Title: %s, Views: %s, Likes: %s' % (ircutils.bold(data[0]['title']), ircutils.bold(data[0]['stats_number_of_plays']), ircutils.bold(data[0]['stats_number_of_likes'])) <NEW_LINE> message = message.encode("utf-8", "replace") <NEW_LINE> irc.queueMsg(ircmsgs.privmsg(msg.args[0], message)) | Add the help for "@plugin help Supytube" here
This should describe *how* to use this plugin. | 62598fc54a966d76dd5ef1ae |
class HomepageTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = Client() <NEW_LINE> self.url = reverse('homepage') <NEW_LINE> <DEDENT> def test_home_template_used(self): <NEW_LINE> <INDENT> response = self.client.get(self.url) <NEW_LINE> self.assertIn('public/home.html', response.template_name) <NEW_LINE> <DEDENT> def test_anonymous_can_access(self): <NEW_LINE> <INDENT> response = self.client.get(self.url) <NEW_LINE> self.assertEqual(200, response.status_code) <NEW_LINE> <DEDENT> def test_email_address_in_context(self): <NEW_LINE> <INDENT> response = self.client.get(self.url) <NEW_LINE> self.assertIn('emma_email', response.context) <NEW_LINE> self.assertEqual( settings.EMMA_EMAIL_ADDRESS, response.context['emma_email'] ) | Tests for the homepage view. | 62598fc5283ffb24f3cf3b5e |
class HTTPRuntimeException(ServiceHTTPException): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> ServiceHTTPException.__init__(self) <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "HTTP runtime exception - %s" % self.message | The HTTP runtime exception class. | 62598fc55fc7496912d483e7 |
class IotModelData(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Revision = None <NEW_LINE> self.ReleaseTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Revision = params.get("Revision") <NEW_LINE> self.ReleaseTime = params.get("ReleaseTime") <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)) | 物模型历史版本
| 62598fc555399d3f056267f1 |
class PyPackageReaderVlab(AbstractPackageReader): <NEW_LINE> <INDENT> def register_packages(self, pkgmanager): <NEW_LINE> <INDENT> fn = _path(self.filename).abspath() <NEW_LINE> pkg_path = fn.dirname() <NEW_LINE> spec_file = fn.basename() <NEW_LINE> assert 'specification' in spec_file <NEW_LINE> vlab_package = vlab_object(pkg_path, pkgmanager) <NEW_LINE> pkg = vlab_package.get_package() <NEW_LINE> pkgmanager.add_package(pkg) | Build a package from a vlab specification file. | 62598fc57047854f4633f6ac |
class UserTasksConfig(AppConfig): <NEW_LINE> <INDENT> name = 'user_tasks' <NEW_LINE> verbose_name = 'User Tasks' <NEW_LINE> def ready(self): <NEW_LINE> <INDENT> import user_tasks.signals | Configuration for the user_tasks Django application. | 62598fc5e1aae11d1e7ce992 |
class AdvancedImportSelect(ObjListWindow): <NEW_LINE> <INDENT> def __init__(self, bibs={}, parent=None): <NEW_LINE> <INDENT> self.bibs = bibs <NEW_LINE> super(AdvancedImportSelect, self).__init__(parent, gridLayout=True) <NEW_LINE> self.checkBoxes = [] <NEW_LINE> self.result = False <NEW_LINE> self.askCats = None <NEW_LINE> self.tableModel = None <NEW_LINE> self.askCats = None <NEW_LINE> self.acceptButton = None <NEW_LINE> self.cancelButton = None <NEW_LINE> self.initUI() <NEW_LINE> <DEDENT> def onCancel(self): <NEW_LINE> <INDENT> self.result = False <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def onOk(self): <NEW_LINE> <INDENT> self.selected = self.tableModel.selectedElements <NEW_LINE> self.result = True <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def keyPressEvent(self, e): <NEW_LINE> <INDENT> if e.key() == Qt.Key_Escape: <NEW_LINE> <INDENT> self.result = False <NEW_LINE> self.close() <NEW_LINE> <DEDENT> <DEDENT> def initUI(self): <NEW_LINE> <INDENT> self.setWindowTitle(dwstr.advImpResults) <NEW_LINE> self.currLayout.setSpacing(1) <NEW_LINE> self.currLayout.addWidget(PBLabel(dwstr.importSelRes)) <NEW_LINE> headers = ["ID", "title", "author", "eprint", "doi"] <NEW_LINE> for k in self.bibs.keys(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.bibs[k]["bibpars"]["eprint"] = self.bibs[k]["bibpars"]["arxiv"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.bibs[k]["bibpars"]["author"] = self.bibs[k]["bibpars"]["authors"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for f in headers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.bibs[k]["bibpars"][f] = self.bibs[k]["bibpars"][f].replace( "\n", " " ) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.tableModel = PBImportedTableModel(self, self.bibs, headers) <NEW_LINE> self.addFilterInput(dwstr.filterEntries, gridPos=(1, 0)) <NEW_LINE> self.setProxyStuff(0, Qt.AscendingOrder) <NEW_LINE> self.finalizeTable(gridPos=(2, 0, 1, 2)) <NEW_LINE> i = 3 <NEW_LINE> self.askCats = QCheckBox(dwstr.askCats, self) <NEW_LINE> self.askCats.toggle() <NEW_LINE> self.currLayout.addWidget(self.askCats, i, 0) <NEW_LINE> self.acceptButton = QPushButton(dwstr.ok, self) <NEW_LINE> self.acceptButton.clicked.connect(self.onOk) <NEW_LINE> self.currLayout.addWidget(self.acceptButton, i + 1, 0) <NEW_LINE> self.cancelButton = QPushButton(dwstr.cancel, self) <NEW_LINE> self.cancelButton.clicked.connect(self.onCancel) <NEW_LINE> self.cancelButton.setAutoDefault(True) <NEW_LINE> self.currLayout.addWidget(self.cancelButton, i + 2, 0) <NEW_LINE> <DEDENT> def triggeredContextMenuEvent(self, row, col, event): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handleItemEntered(self, index): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def cellClick(self, index): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def cellDoubleClick(self, index): <NEW_LINE> <INDENT> pass | create a window for the advanced import | 62598fc54c3428357761a596 |
class PopenModuleRunner(ModuleRunner): <NEW_LINE> <INDENT> def run(self, cmd, inpLines=[], execStart=None): <NEW_LINE> <INDENT> inpLines.reverse() <NEW_LINE> inp, outp, errp = os.popen3(cmd) <NEW_LINE> pid = 0 <NEW_LINE> if execStart: <NEW_LINE> <INDENT> wx.CallAfter(execStart, pid) <NEW_LINE> <DEDENT> out = [] <NEW_LINE> while 1: <NEW_LINE> <INDENT> if inpLines: <NEW_LINE> <INDENT> inp.write(inpLines.pop()) <NEW_LINE> <DEDENT> l = outp.readline() <NEW_LINE> if not l: break <NEW_LINE> out.append(l) <NEW_LINE> <DEDENT> errLines = errp.readlines() <NEW_LINE> serr = ErrorStack.buildErrorList(errLines) <NEW_LINE> self.pid = pid <NEW_LINE> if serr or out: <NEW_LINE> <INDENT> return self.checkError(serr, _('Ran'), out, errRaw=errLines) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Uses Python's popen2, output and errors are redirected and displayed
in a frame. | 62598fc5091ae35668704f02 |
class ItemViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Item.objects.all().order_by('-create_date') <NEW_LINE> serializer_class = ItemSerializer <NEW_LINE> @action(detail=True, methods=['post']) <NEW_LINE> def create_transaction(self, request, pk=None): <NEW_LINE> <INDENT> item = self.get_object() <NEW_LINE> transaction = item.create_transaction() <NEW_LINE> serializer = ItemSerializer( item, context={ 'request': request } ) <NEW_LINE> response_data = serializer.data <NEW_LINE> response_data['status'] = 'Transaction {} created'.format(transaction.id) <NEW_LINE> return Response(response_data) <NEW_LINE> <DEDENT> @action(detail=True, methods=['put']) <NEW_LINE> def move(self, request, pk=None): <NEW_LINE> <INDENT> item = self.get_object() <NEW_LINE> try: <NEW_LINE> <INDENT> item.move() <NEW_LINE> <DEDENT> except InvalidStateTransitionError as ex: <NEW_LINE> <INDENT> return Response( data={ 'error': str(ex) }, status=status.HTTP_400_BAD_REQUEST, exception=True ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer = ItemSerializer( item, context={ 'request': request } ) <NEW_LINE> response_data = serializer.data <NEW_LINE> response_data['status'] = 'Item moved to {}/{}'.format(item.status, item.location) <NEW_LINE> return Response(response_data) <NEW_LINE> <DEDENT> <DEDENT> @action(detail=True, methods=['put']) <NEW_LINE> def error(self, request, pk=None): <NEW_LINE> <INDENT> item = self.get_object() <NEW_LINE> try: <NEW_LINE> <INDENT> item.error() <NEW_LINE> <DEDENT> except InvalidStateTransitionError as ex: <NEW_LINE> <INDENT> return Response( data={ 'error': str(ex) }, status=status.HTTP_400_BAD_REQUEST, exception=True ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer = ItemSerializer( item, context={ 'request': request } ) <NEW_LINE> response_data = serializer.data <NEW_LINE> response_data['status'] = 'Item errored' <NEW_LINE> return Response(response_data) <NEW_LINE> <DEDENT> <DEDENT> @action(detail=True, methods=['put']) <NEW_LINE> def fix(self, request, pk=None): <NEW_LINE> <INDENT> item = self.get_object() <NEW_LINE> try: <NEW_LINE> <INDENT> item.fix() <NEW_LINE> <DEDENT> except InvalidStateTransitionError as ex: <NEW_LINE> <INDENT> return Response( data={ 'error': str(ex) }, status=status.HTTP_400_BAD_REQUEST, exception=True ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer = ItemSerializer( item, context={ 'request': request } ) <NEW_LINE> response_data = serializer.data <NEW_LINE> response_data['status'] = 'Item fixed' <NEW_LINE> return Response(response_data) | API endpoint allowing Item operations | 62598fc550812a4eaa620d52 |
class IntegrationTestCase(BaseTestCase): <NEW_LINE> <INDENT> layer = VNCCOLLAB_COMMON_INTEGRATION_TESTING | Base class for integration tests. | 62598fc50fa83653e46f51c1 |
class ArrayStack: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._data = [] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._data) <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return len(self) == 0 <NEW_LINE> <DEDENT> def push(self, _e): <NEW_LINE> <INDENT> self._data.append(_e) <NEW_LINE> <DEDENT> def top(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Exception("Stack is Empty.") <NEW_LINE> <DEDENT> return self._data[-1] <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Exception("Stack is Empty.") <NEW_LINE> <DEDENT> return self._data.pop() | LIFO Stack implementation using in-built Python-List for storage | 62598fc55fdd1c0f98e5e26e |
class TbilisiManager (models.Manager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> cityhall = Unit.objects.get(pk=2) <NEW_LINE> return cityhall.active_term.representatives.all() | Manager to return Tbilisi City Hall representatives in active term. | 62598fc57c178a314d78d77a |
@provider(IFormFieldProvider) <NEW_LINE> class IHPHWidgetContentAlias(Interface): <NEW_LINE> <INDENT> alias = schema.TextLine( title=u"Content Source", description=_(u"Please enter the unique identifier of the target " u"content item available via attaching @@uuid to the " u"target object's url"), required=True, ) | Content Widget to display external content via references | 62598fc57b180e01f3e491bd |
class Rastrigin(OptimizationTestProblem): <NEW_LINE> <INDENT> name = 'Rastrigin' <NEW_LINE> opt_f = 0 <NEW_LINE> opt_x = [0, 0] <NEW_LINE> x_min = [-5.12, -5.12] <NEW_LINE> x_max = [5.12, 5.12] <NEW_LINE> n_cons = 0 <NEW_LINE> n_eq_cons = 0 <NEW_LINE> def __call__(self, x): <NEW_LINE> <INDENT> f = 20 + x[0]**2 + x[1]**2 - 10*np.cos(2*np.pi*x[0]) - 10*np.cos(2*np.pi*x[1]) <NEW_LINE> g = [] * self.n_cons <NEW_LINE> return [f], g | 2-dimensional Rastrigin function.
https://www.sfu.ca/~ssurjano/rastr.html
f* = 0, x* = (0, 0) | 62598fc5377c676e912f6ee2 |
class SourceStatus(): <NEW_LINE> <INDENT> def __init__(self, *, status: str = None, next_crawl: datetime = None) -> None: <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.next_crawl = next_crawl <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, _dict: Dict) -> 'SourceStatus': <NEW_LINE> <INDENT> args = {} <NEW_LINE> valid_keys = ['status', 'next_crawl'] <NEW_LINE> bad_keys = set(_dict.keys()) - set(valid_keys) <NEW_LINE> if bad_keys: <NEW_LINE> <INDENT> raise ValueError( 'Unrecognized keys detected in dictionary for class SourceStatus: ' + ', '.join(bad_keys)) <NEW_LINE> <DEDENT> if 'status' in _dict: <NEW_LINE> <INDENT> args['status'] = _dict.get('status') <NEW_LINE> <DEDENT> if 'next_crawl' in _dict: <NEW_LINE> <INDENT> args['next_crawl'] = string_to_datetime(_dict.get('next_crawl')) <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> return cls.from_dict(_dict) <NEW_LINE> <DEDENT> def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'status') and self.status is not None: <NEW_LINE> <INDENT> _dict['status'] = self.status <NEW_LINE> <DEDENT> if hasattr(self, 'next_crawl') and self.next_crawl is not None: <NEW_LINE> <INDENT> _dict['next_crawl'] = datetime_to_string(self.next_crawl) <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return self.to_dict() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other: 'SourceStatus') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other: 'SourceStatus') -> bool: <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> class StatusEnum(Enum): <NEW_LINE> <INDENT> RUNNING = "running" <NEW_LINE> COMPLETE = "complete" <NEW_LINE> NOT_CONFIGURED = "not_configured" <NEW_LINE> QUEUED = "queued" <NEW_LINE> UNKNOWN = "unknown" | Object containing source crawl status information.
:attr str status: (optional) The current status of the source crawl for this
collection. This field returns `not_configured` if the default configuration for
this source does not have a **source** object defined.
- `running` indicates that a crawl to fetch more documents is in progress.
- `complete` indicates that the crawl has completed with no errors.
- `queued` indicates that the crawl has been paused by the system and will
automatically restart when possible.
- `unknown` indicates that an unidentified error has occured in the service.
:attr datetime next_crawl: (optional) Date in `RFC 3339` format indicating the
time of the next crawl attempt. | 62598fc560cbc95b06364619 |
class VariantsMenu(walterWidgets.BaseVariantsMenu): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(VariantsMenu, self).__init__(parent) <NEW_LINE> <DEDENT> def _getVariantList(self, recursively=True): <NEW_LINE> <INDENT> return pm.walterStandin( getVariants=(self.nodePath, self.primPath, recursively)) <NEW_LINE> <DEDENT> def _createMenu(self, primPath, index, variantSet): <NEW_LINE> <INDENT> return VariantSetMenu(primPath, variantSet, self) | Menu for editing walter variants. | 62598fc57047854f4633f6ae |
class User(object): <NEW_LINE> <INDENT> def __init__(self, name, email, role): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.email = email <NEW_LINE> self.role = role | A minimal user class | 62598fc5956e5f7376df57ec |
class Game(object): <NEW_LINE> <INDENT> def __init__(self, column_id, game_id, teams, score, status, is_tb_game, start_time = 'add later'): <NEW_LINE> <INDENT> self.column_id = column_id <NEW_LINE> self.game_id = game_id <NEW_LINE> self.teams = teams <NEW_LINE> self.score = score <NEW_LINE> self.status = status <NEW_LINE> self.start_time = start_time <NEW_LINE> self.is_tb_game = is_tb_game <NEW_LINE> self.been_updated = False <NEW_LINE> <DEDENT> def get_winner(self): <NEW_LINE> <INDENT> if self.score[0] > self.score[1]: <NEW_LINE> <INDENT> return self.teams[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.teams[1] | classdocs | 62598fc576e4537e8c3ef881 |
class SignalLink(object): <NEW_LINE> <INDENT> def __init__(self, widgetFrom, outputSignal, widgetTo, inputSignal, enabled=True, dynamic=False): <NEW_LINE> <INDENT> self.widgetFrom = widgetFrom <NEW_LINE> self.widgetTo = widgetTo <NEW_LINE> self.outputSignal = outputSignal <NEW_LINE> self.inputSignal = inputSignal <NEW_LINE> self.dynamic = dynamic <NEW_LINE> self.enabled = enabled <NEW_LINE> self.signalNameFrom = self.outputSignal.name <NEW_LINE> self.signalNameTo = self.inputSignal.name <NEW_LINE> <DEDENT> def canEnableDynamic(self, obj): <NEW_LINE> <INDENT> return isinstance(obj, name_lookup(self.inputSignal.type)) | Back compatibility with old orngSignalManager, do not use. | 62598fc5adb09d7d5dc0a858 |
class CreateOWHLSkateSessionForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = OWHLSkateSession <NEW_LINE> exclude = ['paid'] <NEW_LINE> widgets = { 'skater': forms.HiddenInput(), 'skate_date': forms.HiddenInput(), 'goalie': forms.HiddenInput(), } <NEW_LINE> labels = {'goalie': 'Goalie?', } | Form used to sign up for OWHL Hockey skate sessions. | 62598fc50fa83653e46f51c3 |
class ConfigurationOptions(object): <NEW_LINE> <INDENT> pass | generic shell object for storing attributes | 62598fc55166f23b2e2436be |
class InforBaseStorage(AbstractComponent): <NEW_LINE> <INDENT> _name = 'infor.base.storage' <NEW_LINE> _inherit = ['infor.base'] <NEW_LINE> _usage = 'storage' <NEW_LINE> def write(self, verb, message_id, content): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_processed(self, message_id): <NEW_LINE> <INDENT> raise NotImplementedError | Manipulate files in the Infor storage
Base component, the various methods of writing the files
must be implemented in sub-components (sql or file). | 62598fc5656771135c48994c |
class NPEndPatternExtractor(SkillExtractor): <NEW_LINE> <INDENT> def __init__(self, endings, stop_phrases, only_bulleted_lines=True, confidence=95, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.endings = endings <NEW_LINE> self.stop_phrases = stop_phrases <NEW_LINE> self.only_bulleted_lines = only_bulleted_lines <NEW_LINE> self.detokenizer = MosesDetokenizer() <NEW_LINE> self.confidence = confidence <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return f'Noun phrases ending with one of: {self.endings}\n' <NEW_LINE> <DEDENT> def candidate_skills(self, source_object: Dict) -> CandidateSkillYielder: <NEW_LINE> <INDENT> document = self.transform_func(source_object) <NEW_LINE> for cleaned_phrase, context, phrase_start in self.noun_phrases_matching_endings(document): <NEW_LINE> <INDENT> orig_context = self.detokenizer.detokenize([t[0] for t in context], return_str=True) <NEW_LINE> logging.info( 'Yielding candidate skill %s in context %s', cleaned_phrase, orig_context ) <NEW_LINE> yield CandidateSkill( skill_name=cleaned_phrase, matched_skill_identifier=None, confidence=self.confidence, context=orig_context, start_index=phrase_start, document_id=source_object['id'], document_type=source_object['@type'], source_object=source_object, skill_extractor_name=self.name ) <NEW_LINE> <DEDENT> <DEDENT> def noun_phrases_matching_endings(self, document): <NEW_LINE> <INDENT> lines = document.split('\n') <NEW_LINE> phrase_start = 0 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if not self.only_bulleted_lines or is_bulleted(line): <NEW_LINE> <INDENT> for noun_phrase, context in noun_phrases_in_line_with_context(line): <NEW_LINE> <INDENT> term_list = noun_phrase.split() <NEW_LINE> if term_list[-1].lower() in self.endings: <NEW_LINE> <INDENT> cleaned_phrase = clean_beginning(noun_phrase).lower() <NEW_LINE> if cleaned_phrase not in self.stop_phrases: <NEW_LINE> <INDENT> yield cleaned_phrase, context, phrase_start <NEW_LINE> <DEDENT> <DEDENT> phrase_start += len(noun_phrase) | Identify noun phrases with certain ending words (e.g 'skills', 'abilities') as skills
Args:
endings (list): Single words that should identify the ending of a noun phrase
as being a skill
stop_phrases (list): Noun phrases that should not be considered skills
only_bulleted_lines (bool, default True): Whether or not to only consider lines
that look like they are items in a list | 62598fc57c178a314d78d77c |
class SpeedValue: <NEW_LINE> <INDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.to_native_units() < other.to_native_units() <NEW_LINE> <DEDENT> def __rmul__(self,other): <NEW_LINE> <INDENT> return self.__mul__(other) <NEW_LINE> <DEDENT> def to_native_units(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> pass | The base class for the SpeedValue classes.
Not meant to be used directly.
Use SpeedNativeUnits, SpeedPercent, SpeedRPS, SpeedRPM, SpeedDPS, SpeedDPM | 62598fc5a05bb46b3848ab49 |
class _PyAccessF(PyAccess): <NEW_LINE> <INDENT> def _post_init(self, *args, **kwargs): <NEW_LINE> <INDENT> self.pixels = ffi.cast("float **", self.image32) <NEW_LINE> <DEDENT> def get_pixel(self, x, y): <NEW_LINE> <INDENT> return self.pixels[y][x] <NEW_LINE> <DEDENT> def set_pixel(self, x, y, color): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.pixels[y][x] = color <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.pixels[y][x] = color[0] | 32 bit float access | 62598fc5f548e778e596b87a |
class CohorteMaker(object): <NEW_LINE> <INDENT> def __init__(self, index_url): <NEW_LINE> <INDENT> self.index_url = index_url <NEW_LINE> self._index = {} <NEW_LINE> self._templates = {} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_file_content(url): <NEW_LINE> <INDENT> return urllib2.urlopen(url).read() <NEW_LINE> <DEDENT> def load_index(self, force=False): <NEW_LINE> <INDENT> if force or not self._index: <NEW_LINE> <INDENT> data = to_str(self._get_file_content(self.index_url)) <NEW_LINE> index = json.loads(data) <NEW_LINE> for key in ('home', 'base'): <NEW_LINE> <INDENT> self._index[key] = index['snapshots']['cohorte-minimal-{0}-distribution' .format(key)]['url'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def load_template(self, name, force=False): <NEW_LINE> <INDENT> if force or name not in self._templates: <NEW_LINE> <INDENT> content = self._get_file_content(self._index[name]) <NEW_LINE> filep = tempfile.TemporaryFile() <NEW_LINE> filep.write(content) <NEW_LINE> filep.flush() <NEW_LINE> self._templates[name] = filep <NEW_LINE> <DEDENT> <DEDENT> def extract_template(self, name, directory): <NEW_LINE> <INDENT> with zipfile.ZipFile(self._templates[name]) as tpl_zip: <NEW_LINE> <INDENT> infos = tpl_zip.infolist() <NEW_LINE> content_folder = os.path.commonprefix( [info.filename for info in infos if info.filename[-1] != '/']) <NEW_LINE> content_folder_len = len(content_folder) <NEW_LINE> for info in infos: <NEW_LINE> <INDENT> output_name = info.filename[content_folder_len:] <NEW_LINE> output_name.replace('/', os.path.sep) <NEW_LINE> target_path = os.path.join(directory, output_name) <NEW_LINE> target_path = os.path.normpath(target_path) <NEW_LINE> upperdirs = os.path.dirname(target_path) <NEW_LINE> if upperdirs and not os.path.exists(upperdirs): <NEW_LINE> <INDENT> os.makedirs(upperdirs) <NEW_LINE> <DEDENT> if info.filename[-1] == '/': <NEW_LINE> <INDENT> if not os.path.isdir(target_path): <NEW_LINE> <INDENT> os.mkdir(target_path) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with tpl_zip.open(info) as source, open(target_path, "wb") as target: <NEW_LINE> <INDENT> shutil.copyfileobj(source, target) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def make_home_directory(self, home_dir): <NEW_LINE> <INDENT> if os.path.exists(home_dir): <NEW_LINE> <INDENT> raise IOError("Home directory {0} already exist. Abandon." .format(home_dir)) <NEW_LINE> <DEDENT> self.load_index(False) <NEW_LINE> self.load_template("home", False) <NEW_LINE> self.extract_template("home", home_dir) <NEW_LINE> print("Home template extracted, you know have to set the COHORTE_HOME " "environment variable:") <NEW_LINE> print("set COHORTE_HOME=\"{0}\"".format(home_dir)) <NEW_LINE> <DEDENT> def make_base_directory(self, base_dir): <NEW_LINE> <INDENT> if os.path.exists(base_dir): <NEW_LINE> <INDENT> raise IOError("Base directory {0} already exist. Abandon." .format(base_dir)) <NEW_LINE> <DEDENT> self.load_index(False) <NEW_LINE> self.load_template("base", False) <NEW_LINE> self.extract_template("base", base_dir) <NEW_LINE> print("Base template extracted, you know have to set the COHORTE_BASE " "environment variable:") <NEW_LINE> print("set COHORTE_BASE=\"{0}\"".format(base_dir)) | Utility class to construct home and bases folders | 62598fc526068e7796d4cc39 |
class InvalidConfigException(Exception): <NEW_LINE> <INDENT> pass | Thrown when the configuration for a question is invalid | 62598fc52c8b7c6e89bd3aa0 |
class NumberRange(object): <NEW_LINE> <INDENT> def __init__(self, min=None, max=None, message=None): <NEW_LINE> <INDENT> self.min = min <NEW_LINE> self.max = max <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> return { 'name' : self.__class__.__name__, 'message' : self.message, 'min' : self.min , 'max' : self.max , } <NEW_LINE> <DEDENT> def validator(self, form, element): <NEW_LINE> <INDENT> data = element.get_value() <NEW_LINE> if data is None or (self.min is not None and data < self.min) or (self.max is not None and data > self.max): <NEW_LINE> <INDENT> if self.message is None: <NEW_LINE> <INDENT> if self.max is None: <NEW_LINE> <INDENT> self.message = form._('Number must be greater than %s.') % self.min <NEW_LINE> <DEDENT> elif self.min is None: <NEW_LINE> <INDENT> self.message = form._('Number must be less than %s.') % self.max <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.message = form._('Number must be between %s and %s.') % (self.min , self.max) <NEW_LINE> <DEDENT> <DEDENT> element._on['error'](element , self.message) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True | Validates that a number is of a minimum and/or maximum value, inclusive.
This will work with any comparable number type, such as floats and
decimals, not just integers.
:param min:
The minimum required value of the number. If not provided, minimum
value will not be checked.
:param max:
The maximum value of the number. If not provided, maximum value
will not be checked.
:param message:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults
are provided depending on the existence of min and max. | 62598fc5be7bc26dc9251fca |
class Hash(object): <NEW_LINE> <INDENT> def __init__(self, selector, id): <NEW_LINE> <INDENT> self.selector = selector <NEW_LINE> self.id = id <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s[%r#%s]' % ( self.__class__.__name__, self.selector, self.id) <NEW_LINE> <DEDENT> def specificity(self): <NEW_LINE> <INDENT> a, b, c = self.selector.specificity() <NEW_LINE> a += 1 <NEW_LINE> return a, b, c | Represents selector#id | 62598fc5ec188e330fdf8b72 |
class JsonErrorHandler(base_handler.JsonHandler): <NEW_LINE> <INDENT> def __init__(self, error): <NEW_LINE> <INDENT> self.error = error <NEW_LINE> self.json_response = {} <NEW_LINE> <DEDENT> def handle(self): <NEW_LINE> <INDENT> raise self.error | JsonHandler that raises an error when invoked. | 62598fc5e1aae11d1e7ce994 |
class DummyShell: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.handler = None <NEW_LINE> self.exc_tuple = None <NEW_LINE> <DEDENT> def set_custom_exc(self, exc_tuple, handler): <NEW_LINE> <INDENT> self.handler = handler <NEW_LINE> self.exc_tuple = exc_tuple <NEW_LINE> <DEDENT> def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, exception_only=False): <NEW_LINE> <INDENT> if self.handler is not None and self.exc_tuple is not None: <NEW_LINE> <INDENT> etype, evalue, tb = exc_tuple <NEW_LINE> func, self.handler = self.handler, None <NEW_LINE> func(self, etype, evalue, tb, tb_offset) <NEW_LINE> self.handler = func <NEW_LINE> <DEDENT> <DEDENT> def set(self, module): <NEW_LINE> <INDENT> assert 'get_ipython' not in dir(module) <NEW_LINE> module.get_ipython = lambda: self <NEW_LINE> <DEDENT> def remove(self, module): <NEW_LINE> <INDENT> del module.get_ipython | Dummy class to emulate the iPython interactive shell.
https://ipython.org/ipython-doc/dev/api/generated/IPython.core.interactiveshell.html | 62598fc5091ae35668704f06 |
@attr.s(auto_attribs=True) <NEW_LINE> class Configuration: <NEW_LINE> <INDENT> appdaemon_path: str = "appdaemon/apps/" <NEW_LINE> appdaemon: bool = False <NEW_LINE> netdaemon_path: str = "netdaemon/apps/" <NEW_LINE> netdaemon: bool = False <NEW_LINE> config: dict = {} <NEW_LINE> config_entry: dict = {} <NEW_LINE> config_type: str = None <NEW_LINE> debug: bool = False <NEW_LINE> dev: bool = False <NEW_LINE> frontend_mode: str = "Grid" <NEW_LINE> frontend_compact: bool = False <NEW_LINE> frontend_repo: str = "" <NEW_LINE> frontend_repo_url: str = "" <NEW_LINE> options: dict = {} <NEW_LINE> onboarding_done: bool = False <NEW_LINE> plugin_path: str = "www/community/" <NEW_LINE> python_script_path: str = "python_scripts/" <NEW_LINE> python_script: bool = False <NEW_LINE> sidepanel_icon: str = "hacs:hacs" <NEW_LINE> sidepanel_title: str = "HACS" <NEW_LINE> theme_path: str = "themes/" <NEW_LINE> theme: bool = False <NEW_LINE> token: str = None <NEW_LINE> country: str = "ALL" <NEW_LINE> experimental: bool = False <NEW_LINE> release_limit: int = 5 <NEW_LINE> def to_json(self) -> dict: <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def print(self) -> None: <NEW_LINE> <INDENT> config = self.to_json() <NEW_LINE> for key in config: <NEW_LINE> <INDENT> if key in ["config", "config_entry", "options", "token"]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> _LOGGER.debug("%s: %s", key, config[key]) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def from_dict(configuration: dict, options: dict = None) -> None: <NEW_LINE> <INDENT> if isinstance(options, bool) or isinstance(configuration.get("options"), bool): <NEW_LINE> <INDENT> raise HacsException("Configuration is not valid.") <NEW_LINE> <DEDENT> if options is None: <NEW_LINE> <INDENT> options = {} <NEW_LINE> <DEDENT> if not configuration: <NEW_LINE> <INDENT> raise HacsException("Configuration is not valid.") <NEW_LINE> <DEDENT> config = Configuration() <NEW_LINE> config.config = configuration <NEW_LINE> config.options = options <NEW_LINE> for conf_type in [configuration, options]: <NEW_LINE> <INDENT> for key in conf_type: <NEW_LINE> <INDENT> setattr(config, key, conf_type[key]) <NEW_LINE> <DEDENT> <DEDENT> return config | Configuration class. | 62598fc576e4537e8c3ef883 |
class ASFGUIDAttribute(ASFBaseAttribute): <NEW_LINE> <INDENT> TYPE = 0x0006 <NEW_LINE> def parse(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def _render(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def data_size(self): <NEW_LINE> <INDENT> return len(self.value) <NEW_LINE> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "".join("{:02X}".format(i) for i in self.value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return bytes(self) == other <NEW_LINE> <DEDENT> __hash__ = ASFBaseAttribute.__hash__ | GUID attribute. | 62598fc55fcc89381b2662bc |
class TriangleROI(ROI): <NEW_LINE> <INDENT> def __init__(self, pos, size, **args): <NEW_LINE> <INDENT> ROI.__init__(self, pos, [size, size], aspectLocked=True, **args) <NEW_LINE> angles = np.linspace(0, np.pi * 4 / 3, 3) <NEW_LINE> verticies = (np.array((np.sin(angles), np.cos(angles))).T + 1.0) / 2.0 <NEW_LINE> self.poly = QtGui.QPolygonF() <NEW_LINE> for pt in verticies: <NEW_LINE> <INDENT> self.poly.append(QtCore.QPointF(*pt)) <NEW_LINE> <DEDENT> self.addRotateHandle(verticies[0], [0.5, 0.5]) <NEW_LINE> self.addScaleHandle(verticies[1], [0.5, 0.5]) <NEW_LINE> <DEDENT> def paint(self, p, *args): <NEW_LINE> <INDENT> r = self.boundingRect() <NEW_LINE> p.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing) <NEW_LINE> p.scale(r.width(), r.height()) <NEW_LINE> p.setPen(self.currentPen) <NEW_LINE> p.drawPolygon(self.poly) <NEW_LINE> <DEDENT> def shape(self): <NEW_LINE> <INDENT> self.path = QtGui.QPainterPath() <NEW_LINE> r = self.boundingRect() <NEW_LINE> t = QtGui.QTransform() <NEW_LINE> t.scale(r.width(), r.height()) <NEW_LINE> self.path.addPolygon(self.poly) <NEW_LINE> return t.map(self.path) <NEW_LINE> <DEDENT> def getArrayRegion(self, *args, **kwds): <NEW_LINE> <INDENT> return self._getArrayRegionForArbitraryShape(*args, **kwds) | Equilateral triangle ROI subclass with one scale handle and one rotation handle.
Arguments
pos (length-2 sequence) The position of the ROI's origin.
size (float) The length of an edge of the triangle.
\**args All extra keyword arguments are passed to ROI()
============== ============================================================= | 62598fc5a8370b77170f06b9 |
class Poll(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=200, verbose_name="Название") <NEW_LINE> text = models.TextField(max_length=200, verbose_name="Описание") <NEW_LINE> date_start = models.DateTimeField(verbose_name="Дата старта") <NEW_LINE> date_end = models.DateTimeField(verbose_name="Дата окончания") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Опрос' <NEW_LINE> verbose_name_plural = 'Опросы' | Атрибуты опроса: название, дата старта, дата окончания, описание. | 62598fc599fddb7c1ca62f5c |
class ContainerRegistryManagementClientConfiguration(AzureConfiguration): <NEW_LINE> <INDENT> def __init__( self, credentials, subscription_id, base_url=None): <NEW_LINE> <INDENT> if credentials is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credentials' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'https://management.azure.com' <NEW_LINE> <DEDENT> super(ContainerRegistryManagementClientConfiguration, self).__init__(base_url) <NEW_LINE> self.add_user_agent('azure-mgmt-containerregistry/{}'.format(VERSION)) <NEW_LINE> self.add_user_agent('Azure-SDK-For-Python') <NEW_LINE> self.credentials = credentials <NEW_LINE> self.subscription_id = subscription_id | Configuration for ContainerRegistryManagementClient
Note that all parameters used to create this instance are saved as instance
attributes.
:param credentials: Credentials needed for the client to connect to Azure.
:type credentials: :mod:`A msrestazure Credentials
object<msrestazure.azure_active_directory>`
:param subscription_id: The Microsoft Azure subscription ID.
:type subscription_id: str
:param str base_url: Service URL | 62598fc53317a56b869be6c0 |
class GetBucketLocationResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_LocationConstraint(self): <NEW_LINE> <INDENT> return self._output.get('LocationConstraint', None) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) | A ResultSet with methods tailored to the values returned by the GetBucketLocation Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62598fc5283ffb24f3cf3b64 |
class Square: <NEW_LINE> <INDENT> def __init__(self, size=0): <NEW_LINE> <INDENT> self.__size = size <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.__size <NEW_LINE> <DEDENT> @size.setter <NEW_LINE> def size(self, size): <NEW_LINE> <INDENT> if type(size) != int: <NEW_LINE> <INDENT> raise TypeError('size must be an integer') <NEW_LINE> <DEDENT> if size >= 0: <NEW_LINE> <INDENT> self.__size = size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('size must be >= 0') <NEW_LINE> <DEDENT> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.__size ** 2 | class Square with private instance attribute size | 62598fc54a966d76dd5ef1b4 |
class ContourPoint(Point): <NEW_LINE> <INDENT> def SetPoint(self, P): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self, P=None, C=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Chamfer = property(lambda self: object(), lambda self, v: None, lambda self: None) | ContourPoint()
ContourPoint(P: Point, C: Chamfer) | 62598fc52c8b7c6e89bd3aa2 |
@req_cmd(Bugzilla4_4Rpc, cmd='fields') <NEW_LINE> class _FieldsRequest(FieldsRequest, RPCRequest): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> super().__init__(command='Bug.fields', **kw) | Construct a fields request.
API docs: https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/Bug.html#fields | 62598fc526068e7796d4cc3b |
class ArchFontPackage(object): <NEW_LINE> <INDENT> def __init__(self, pkg_dir, err_filename='makepkg.stderr.log'): <NEW_LINE> <INDENT> self.pkg_name = os.path.basename(pkg_dir) <NEW_LINE> self.pkg_dir = pkg_dir <NEW_LINE> self.status = {} <NEW_LINE> self.err_file = open(err_filename, 'a') <NEW_LINE> self.failed = [] <NEW_LINE> if os.path.exists(IGNORE_FILE): <NEW_LINE> <INDENT> self.ignore_list = open(IGNORE_FILE).readlines() <NEW_LINE> self.ignore_list = list(map(lambda x: x.strip(), self.ignore_list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ignore_list = [] <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.err_file.close() <NEW_LINE> <DEDENT> def copy(self, dest_dir): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shutil.copytree(self.pkg_dir, dest_dir) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.pkg_dir = dest_dir <NEW_LINE> <DEDENT> def ignore_pkg(self): <NEW_LINE> <INDENT> with open(IGNORE_FILE, 'a') as ignore_file: <NEW_LINE> <INDENT> ignore_file.write(self.pkg_name + '\n') <NEW_LINE> <DEDENT> <DEDENT> def make_pkg(self): <NEW_LINE> <INDENT> os.chdir(self.pkg_dir) <NEW_LINE> return subprocess.call(MAKEPKG_CMD, stderr=self.err_file) <NEW_LINE> <DEDENT> def extract_pkg(self): <NEW_LINE> <INDENT> xz_pkgs = glob.glob(os.path.join(self.pkg_dir, '*.tar.xz')) <NEW_LINE> if xz_pkgs: <NEW_LINE> <INDENT> os.chdir(self.pkg_dir) <NEW_LINE> return subprocess.call(['tar', '-Jxf', xz_pkgs[0]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get_ttfs(self): <NEW_LINE> <INDENT> ttf_paths = [] <NEW_LINE> for root, dirnames, filenames in os.walk(self.pkg_dir): <NEW_LINE> <INDENT> for filename in fnmatch.filter(filenames, '*.ttf'): <NEW_LINE> <INDENT> ttf_paths.append(os.path.join(root, filename)) <NEW_LINE> <DEDENT> <DEDENT> return ttf_paths <NEW_LINE> <DEDENT> def to_pngs(self, ttf_paths): <NEW_LINE> <INDENT> png_paths = [] <NEW_LINE> for ttf_path in ttf_paths: <NEW_LINE> <INDENT> output_png = ttf_path + '.png' <NEW_LINE> command = TTF2PNG_CMD[:] <NEW_LINE> command.extend(['-o', output_png, ttf_path]) <NEW_LINE> ret_code = subprocess.call(command) <NEW_LINE> if ret_code == 0: <NEW_LINE> <INDENT> png_paths.append(output_png) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.failed.append(ttf_path) <NEW_LINE> <DEDENT> <DEDENT> return png_paths <NEW_LINE> <DEDENT> def trim_pngs(self, png_paths): <NEW_LINE> <INDENT> for png_path in png_paths: <NEW_LINE> <INDENT> subprocess.call(['convert', '-trim', png_path, png_path]) | Main class for an Archlinux font package.
It receives a package directory `pkg_dir` containing a PKGBUILD and
possible other files, as specified by ABS and AUR. | 62598fc5091ae35668704f08 |
class AugmentedNegativeBinomialCounts(GibbsSampling): <NEW_LINE> <INDENT> def __init__(self, X, counts, nbmodel): <NEW_LINE> <INDENT> assert counts.ndim == 1 <NEW_LINE> self.counts = counts <NEW_LINE> self.T = counts.shape[0] <NEW_LINE> self.X = X <NEW_LINE> self.model = nbmodel <NEW_LINE> self.omegas = np.ones(self.T) <NEW_LINE> self.psi = np.zeros(self.T) <NEW_LINE> <DEDENT> def log_likelihood(self, x): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def rvs(self,size=[]): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def resample(self, data=None, stats=None): <NEW_LINE> <INDENT> xi = self.model.xi <NEW_LINE> mu = self.model.mu_psi(self.X) <NEW_LINE> sigma = self.model.sigma <NEW_LINE> trunc = self.model.trunc <NEW_LINE> sigma = np.asscalar(sigma) <NEW_LINE> self.omega = polya_gamma(self.counts.reshape(self.T)+xi, self.psi.reshape(self.T), trunc).reshape((self.T,)) <NEW_LINE> sig_post = 1.0 / (1.0/sigma + self.omega) <NEW_LINE> mu_post = sig_post * ((self.counts-xi)/2.0 + mu / sigma) <NEW_LINE> self.psi = mu_post + np.sqrt(sig_post) * np.random.normal(size=(self.T,)) | Class to keep track of a set of counts and the corresponding Polya-gamma
auxiliary variables associated with them. | 62598fc55fcc89381b2662bd |
class ConnectionError(Error): <NEW_LINE> <INDENT> def __init__(self, msg, details): <NEW_LINE> <INDENT> super(ConnectionError, self).__init__(msg) <NEW_LINE> self._details = details <NEW_LINE> <DEDENT> @property <NEW_LINE> def details(self): <NEW_LINE> <INDENT> return self._details <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}(message={!r})". format(self.__class__.__name__, self.args[0]) <NEW_LINE> <DEDENT> def str_def(self): <NEW_LINE> <INDENT> return "classname={!r}; message={!r};". format(self.__class__.__name__, self.args[0]) | This exception indicates a problem with the connection to the HMC, below
the HTTP level. HTTP errors are indicated via :exc:`~zhmcclient.HTTPError`.
A retry by the user code is not likely to be successful, unless connect or
read retries had been disabled when creating the session (see
:class:`~zhmcclient.Session`).
Even though this class has exceptions derived from it, exceptions of this
class may also be raised (if no other derived class matches the
circumstances).
Derived from :exc:`~zhmcclient.Error`. | 62598fc5656771135c489950 |
class UNet(dygraph.Layer): <NEW_LINE> <INDENT> def __init__(self, num_inp=3, num_out=59, act="relu"): <NEW_LINE> <INDENT> super(UNet, self).__init__() <NEW_LINE> self.encoder = Encoder(num_inp) <NEW_LINE> self.middle_layer = Sequential( Conv2D(512, 1024, filter_size=3, stride=1, padding=0, act=None), BatchNorm(1024, act=act), Conv2D(1024, 1024, filter_size=3, stride=1, padding=0, act=None), BatchNorm(1024, act=act), ) <NEW_LINE> self.decoder = Decoder() <NEW_LINE> self.header = Sequential( Conv2D(64, num_out, filter_size=1, stride=1, padding=0, act=None), BatchNorm(num_out, act=None) ) <NEW_LINE> <DEDENT> def forward(self, inp): <NEW_LINE> <INDENT> (x, pool_layers) = self.encoder(inp) <NEW_LINE> x = self.middle_layer(x) <NEW_LINE> x = self.decoder(x, pool_layers) <NEW_LINE> return self.header(x) | 4 downsample.
4 upsample. | 62598fc5ff9c53063f51a92d |
class RelatedUserBase(models.Model, AbstractIsAdmin): <NEW_LINE> <INDENT> period = models.ForeignKey(Period, verbose_name='Period', help_text="The period.") <NEW_LINE> user = models.ForeignKey(User, help_text="The related user.") <NEW_LINE> tags = models.TextField(blank=True, null=True, help_text="Comma-separated list of tags. Each tag is a word with the following letters allowed: a-z, 0-9, ``_`` and ``-``. Each word is separated by a comma, and no whitespace.") <NEW_LINE> tags_patt = re.compile('^(?:[a-z0-9_-]+,)*[a-z0-9_-]+$') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> unique_together = ('period', 'user') <NEW_LINE> app_label = 'core' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def q_is_admin(cls, user_obj): <NEW_LINE> <INDENT> return Q(period__admins=user_obj) | Q(period__parentnode__admins=user_obj) | Q(period__parentnode__parentnode__pk__in=Node._get_nodepks_where_isadmin(user_obj)) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if self.tags and not self.tags_patt.match(self.tags): <NEW_LINE> <INDENT> raise ValidationError('tags must be a comma-separated list of tags, each tag only containing a-z, 0-9, ``_`` and ``-``.') <NEW_LINE> <DEDENT> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '{0}:user={1}:tags={2}'.format(self.period, self.user.username, self.tags) | Common fields for examiners and students related to a period.
.. attribute:: period
The period that the user is related to.
.. attribute:: user
A django.contrib.auth.models.User_ object. Must be unique within this
period.
.. attribute:: tags
Comma-separated list of tags. Each tag is a word with the following
letters allowed: a-z and 0-9. Each word is separated by a comma, and no
whitespace. | 62598fc54527f215b58ea1b0 |
class ResultNotReady(Error): <NEW_LINE> <INDENT> pass | Raised when you access a data from a Future before it is assigned. | 62598fc5adb09d7d5dc0a85c |
class PIMD(QuaggaDaemon): <NEW_LINE> <INDENT> NAME = 'pimd' <NEW_LINE> DEPENDS = (Zebra,) <NEW_LINE> KILL_PATTERNS = (NAME,) <NEW_LINE> def __init__(self, node, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(node=node, *args, **kwargs) <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> cfg = super().build() <NEW_LINE> cfg.update(self.options) <NEW_LINE> cfg.interfaces = [ ConfigDict(name=itf.name, ssm=itf.get('multicast_ssm', self.options.multicast_ssm), igmp=itf.get('multicast_igmp', self.options.multicast_igmp)) for itf in realIntfList(self._node) if itf.get("enable_multicast", False)] <NEW_LINE> return cfg <NEW_LINE> <DEDENT> def set_defaults(self, defaults): <NEW_LINE> <INDENT> defaults.multicast_ssm = True <NEW_LINE> defaults.multicast_igmp = True <NEW_LINE> super().set_defaults(defaults) | This class configures a PIM daemon to responds to IGMP queries in order
to setup multicast routing in the network. | 62598fc592d797404e388cd2 |
class ProcessController(BasicController): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, disk, backup_id, config): <NEW_LINE> <INDENT> super(ProcessController, self).__init__(backup_id) <NEW_LINE> self.disk = disk <NEW_LINE> self.config = config <NEW_LINE> self.backup_dir = ConfigHelper.config['node']['backup_path'] + str(backup_id) + '/' <NEW_LINE> self._thread = None <NEW_LINE> self._imager = None <NEW_LINE> self._disk_layout = None <NEW_LINE> self._status.update({ 'status': '', 'path': '', 'layout': '', 'partitions': [], 'start_time': '', 'end_time': '', 'operation': '', }) <NEW_LINE> <DEDENT> def get_status(self): <NEW_LINE> <INDENT> self._update_status() <NEW_LINE> return self._status <NEW_LINE> <DEDENT> def kill(self): <NEW_LINE> <INDENT> if self._imager: <NEW_LINE> <INDENT> self._imager.kill() <NEW_LINE> <DEDENT> self._set_error("Job cancelled by the user.") <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def run(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _update_status(self): <NEW_LINE> <INDENT> if self._imager: <NEW_LINE> <INDENT> self._status['partitions'] = self._imager.get_status() | This class defines the common structure for Backup and Restoration controllers
which need to be executed on threads separate from the standard server response thread pool. | 62598fc571ff763f4b5e7a5f |
class TimersResponse(object): <NEW_LINE> <INDENT> deserialized_types = { 'total_count': 'int', 'timers': 'list[ask_sdk_model.services.timer_management.timer_response.TimerResponse]', 'next_token': 'str' } <NEW_LINE> attribute_map = { 'total_count': 'totalCount', 'timers': 'timers', 'next_token': 'nextToken' } <NEW_LINE> supports_multiple_types = False <NEW_LINE> def __init__(self, total_count=None, timers=None, next_token=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.total_count = total_count <NEW_LINE> self.timers = timers <NEW_LINE> self.next_token = next_token <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_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 if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.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[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TimersResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | Timers object with paginated list of multiple timers
:param total_count: Total count of timers returned.
:type total_count: (optional) int
:param timers: List of multiple Timer objects
:type timers: (optional) list[ask_sdk_model.services.timer_management.timer_response.TimerResponse]
:param next_token: Link to retrieve next set of timers if total count is greater than max results.
:type next_token: (optional) str | 62598fc50fa83653e46f51c7 |
class RelatedItemsModifier(object): <NEW_LINE> <INDENT> implements(ISurfResourceModifier) <NEW_LINE> adapts(IBaseContent) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> <DEDENT> def run(self, resource, *args, **kwds): <NEW_LINE> <INDENT> if not getattr(self.context, 'getRelatedItems', None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> resource.dcterms_references = [rdflib.URIRef(o.absolute_url()) for o in self.context.getRelatedItems()] | Adds dcterms:references
| 62598fc599fddb7c1ca62f5d |
class _IdentityWrap: <NEW_LINE> <INDENT> __slots__ = ["unit_system", "ref"] <NEW_LINE> def __init__(self, obj: AbstractValueWithQuantityObject, unit_system: UnitSystemManager): <NEW_LINE> <INDENT> self.unit_system = unit_system <NEW_LINE> self.ref = weakref.ref(obj, self._OnRefKilled) <NEW_LINE> <DEDENT> def _OnRefKilled(self, ref: object) -> None: <NEW_LINE> <INDENT> self.unit_system._object_refs.remove(self) | Helper class to remove an object from the unit system references.
It's used so that we create a wrapper that'll give the __hash__ and __eq__ based on
the object id. | 62598fc57c178a314d78d780 |
class ADFSPTest(GenericSPTest): <NEW_LINE> <INDENT> mass_precision = 0.3 <NEW_LINE> foverlap00 = 1.00003 <NEW_LINE> foverlap11 = 1.02672 <NEW_LINE> foverlap22 = 1.03585 <NEW_LINE> b3lyp_energy = -140 <NEW_LINE> def testfoverlaps(self): <NEW_LINE> <INDENT> self.assertEquals(self.data.fooverlaps.shape, (self.data.nbasis, self.data.nbasis)) <NEW_LINE> row = self.data.fooverlaps[0,:] <NEW_LINE> col = self.data.fooverlaps[:,0] <NEW_LINE> self.assertEquals(sum(col - row), 0.0) <NEW_LINE> self.assertAlmostEquals(self.data.fooverlaps[0, 0], self.foverlap00, delta=0.0001) <NEW_LINE> self.assertAlmostEquals(self.data.fooverlaps[1, 1], self.foverlap11, delta=0.0001) <NEW_LINE> self.assertAlmostEquals(self.data.fooverlaps[2, 2], self.foverlap22, delta=0.0001) | Customized restricted single point unittest | 62598fc5dc8b845886d5389c |
@util.export <NEW_LINE> class TempDir(base.Base): <NEW_LINE> <INDENT> def _clear(self): <NEW_LINE> <INDENT> self.logger.debug("removing directory '%s'", self._dir) <NEW_LINE> if os.path.exists(self._dir): <NEW_LINE> <INDENT> shutil.rmtree(self._dir) <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, dir): <NEW_LINE> <INDENT> super(TempDir, self).__init__() <NEW_LINE> self._dir = dir <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> self._clear() <NEW_LINE> os.makedirs(self._dir) <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._clear() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.logger.warning( _("Cannot remove directory '{directory}': {error}").format( directory=self._dir, error=e, ), ) <NEW_LINE> self.logger.debug('exception', exc_info=True) <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.create() <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.destroy() | Temporary directory scope management
Usage:
with TempDir(directory):
pass | 62598fc5a05bb46b3848ab4c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.