code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class CroppedImage(AxesWidget, Actionable): <NEW_LINE> <INDENT> ACTIONS = [ ('on_changed', 'changed', 'disconect'), ] <NEW_LINE> def __init__(self, ax, pixels): <NEW_LINE> <INDENT> AxesWidget.__init__(self, ax) <NEW_LINE> Actionable.__init__(self) <NEW_LINE> self.pixels = pixels <NEW_LINE> self.image = self.ax.imshow(self.pixels, aspect='auto', interpolation='none', vmin=0, vmax=1) <NEW_LINE> self.l = None <NEW_LINE> self.observers = {} <NEW_LINE> self.cid = 0 <NEW_LINE> <DEDENT> def make_xyextent_textboxes(self, ax_xlo, ax_xhi, ax_ylo, ax_yhi): <NEW_LINE> <INDENT> ext = self.image.get_extent() <NEW_LINE> self.image.set_extent(ext) <NEW_LINE> self.textboxes = [] <NEW_LINE> for i, ax in enumerate([ax_xlo, ax_xhi, ax_ylo, ax_yhi]): <NEW_LINE> <INDENT> tb = TextBoxFloat(ax, str(ext[i])) <NEW_LINE> tb.on_changed(partial(self.set_side_extent, i)) <NEW_LINE> self.textboxes.append(tb) <NEW_LINE> <DEDENT> <DEDENT> def set_side_extent(self, side, val): <NEW_LINE> <INDENT> ext = list(self.image.get_extent()) <NEW_LINE> ext[side] = val <NEW_LINE> self.image.set_extent(ext) <NEW_LINE> self.ax.set_xlim(ext[:2]) <NEW_LINE> self.ax.set_ylim(ext[2:]) <NEW_LINE> <DEDENT> def crop(self, extent): <NEW_LINE> <INDENT> x0, x1, y0, y1 = np.array(extent, dtype=int) <NEW_LINE> if x1 < x0: <NEW_LINE> <INDENT> x0, x1 = x1, x0 <NEW_LINE> <DEDENT> if y1 < y0: <NEW_LINE> <INDENT> y0, y1 = y1, y0 <NEW_LINE> <DEDENT> pix = self.pixels[y0:y1, x0:x1] <NEW_LINE> self.image.set_data(pix) <NEW_LINE> if self.drawon: <NEW_LINE> <INDENT> self.canvas.draw() <NEW_LINE> <DEDENT> self.changed() | Widget that recolors a multichannel image using a given a scale sequence
and associated colors.
Parameters
----------
ax : axes
Axes to draw the widget
pixels : 3d array
Source pixels to recolor
Attributes
----------
ax : axes
Axes to draw the widget
pixels : 3d array
Source pixels to recolor
image : matplotlib image
The image displayed on the axes | 62598fa2009cb60464d0138b |
class CacheInvalidationRule(_messages.Message): <NEW_LINE> <INDENT> host = _messages.StringField(1) <NEW_LINE> path = _messages.StringField(2) | A CacheInvalidationRule object.
Fields:
host: If set, this invalidation rule will only apply to requests with a
Host header matching host.
path: A string attribute. | 62598fa2d6c5a102081e1fad |
class EvaluatorMeta(type): <NEW_LINE> <INDENT> def __init__(cls, name, bases, namespace): <NEW_LINE> <INDENT> super().__init__(name, bases, namespace) <NEW_LINE> if 'evaluate' in namespace and not isinstance(namespace['evaluate'], staticmethod): <NEW_LINE> <INDENT> raise EvaluatorError(cls.__name__ + ".evaluate() should be a @staticmethod.") <NEW_LINE> <DEDENT> if 'requires' not in namespace: <NEW_LINE> <INDENT> raise EvaluatorError(cls.__name__ + " should have a 'requires' class attribute.") <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise EvaluatorError(self.__name__ + " objects cannot be created. Use the class object itself.") | A metaclass for creating Evaluator classes.
The metaclass ensures that Evaluator instances cannot be created and
it checks that the 'evaluate' method of a (derived) Evaluator class
is static.
If these conditions are not met, an EvaluatorError exception is raised. | 62598fa2435de62698e9bc5a |
class ContractCredentialsTest(BaseContractTerminatedMilestonesWebTest): <NEW_LINE> <INDENT> initial_auth = ('Basic', ('broker', '')) <NEW_LINE> initial_data = test_contract_data <NEW_LINE> test_get_credentials = snitch(get_credentials) <NEW_LINE> test_generate_credentials = snitch(generate_credentials) | esco contract credentials tests | 62598fa201c39578d7f12be5 |
class RefStateProvinceRUDView(RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> lookup_field = 'id' <NEW_LINE> serializer_class = RefStateProvinceSerializer <NEW_LINE> permission_classes = (PermissionSettings.IS_ADMIN_OR_READ_ONLY, CustomDjangoModelPermissions) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return RefStateProvince.objects.all() | This module creates the RETRIEVE, UPDATE, DESTROY method for Country Model | 62598fa2adb09d7d5dc0a3f0 |
class _StatusConditionImpl(NamedTuple): <NEW_LINE> <INDENT> and_clauses: Tuple[BoolFun, ...] <NEW_LINE> def __call__(self, target: Stateful) -> bool: <NEW_LINE> <INDENT> return all(clause(target) for clause in self.and_clauses) <NEW_LINE> <DEDENT> def __and__(self, other: Any) -> 'StatusCondition': <NEW_LINE> <INDENT> if not isinstance(other, _StatusConditionImpl): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return _StatusConditionImpl(self.and_clauses + other.and_clauses) <NEW_LINE> <DEDENT> def __or__(self, other: Any) -> 'StatusCondition': <NEW_LINE> <INDENT> if not isinstance(other, _StatusConditionImpl): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return _StatusConditionImpl((lambda t: self(t) or other(t),)) <NEW_LINE> <DEDENT> def __invert__(self) -> 'StatusCondition': <NEW_LINE> <INDENT> def not_self(target: Stateful) -> bool: <NEW_LINE> <INDENT> return any(not clause(target) for clause in self.and_clauses) <NEW_LINE> <DEDENT> return _StatusConditionImpl((not_self,)) | Internal implementation of StatusCondition.
See the factory function status_condition for a summary. | 62598fa245492302aabfc337 |
class classical_thermo: <NEW_LINE> <INDENT> _ptr=0 <NEW_LINE> _link=0 <NEW_LINE> _owner=True <NEW_LINE> def __init__(self,link,pointer=0): <NEW_LINE> <INDENT> if pointer==0: <NEW_LINE> <INDENT> f=link.o2scl.o2scl_create_classical_thermo <NEW_LINE> f.restype=ctypes.c_void_p <NEW_LINE> f.argtypes=[] <NEW_LINE> self._ptr=f() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ptr=pointer <NEW_LINE> self._owner=False <NEW_LINE> <DEDENT> self._link=link <NEW_LINE> return <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self._owner==True: <NEW_LINE> <INDENT> f=self._link.o2scl.o2scl_free_classical_thermo <NEW_LINE> f.argtypes=[ctypes.c_void_p] <NEW_LINE> f(self._ptr) <NEW_LINE> self._owner=False <NEW_LINE> self._ptr=0 <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> new_obj=type(self)(self._link,self._ptr) <NEW_LINE> return new_obj <NEW_LINE> <DEDENT> def calc_density(self,p,T): <NEW_LINE> <INDENT> func=self._link.o2scl.o2scl_classical_thermo_calc_density <NEW_LINE> func.argtypes=[ctypes.c_void_p,ctypes.c_void_p,ctypes.c_double] <NEW_LINE> func(self._ptr,p._ptr,T) <NEW_LINE> return <NEW_LINE> <DEDENT> def calc_mu(self,p,T): <NEW_LINE> <INDENT> func=self._link.o2scl.o2scl_classical_thermo_calc_mu <NEW_LINE> func.argtypes=[ctypes.c_void_p,ctypes.c_void_p,ctypes.c_double] <NEW_LINE> func(self._ptr,p._ptr,T) <NEW_LINE> return | Python interface for class :ref:`classical_thermo <o2sclp:classical_thermo_tl>`. | 62598fa26aa9bd52df0d4d31 |
class Creator(_AtomFromString): <NEW_LINE> <INDENT> _tag = 'creator' <NEW_LINE> _namespace = DC_NAMESPACE | The <dc:creator> element identifies an author-or more generally, an entity
responsible for creating the volume in question. Examples of a creator
include a person, an organization, or a service. In the case of
anthologies, proceedings, or other edited works, this field may be used to
indicate editors or other entities responsible for collecting the volume's
contents.
This element appears as a child of <entry>. If there are multiple authors or
contributors to the book, there may be multiple <dc:creator> elements in the
volume entry (one for each creator or contributor). | 62598fa2d53ae8145f9182f2 |
class WtfError(Exception): <NEW_LINE> <INDENT> pass | (For debugging) Should never occur | 62598fa2a17c0f6771d5c0a1 |
class CriticNetwork(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_dim, action_dim, hidden_size, output_size=1): <NEW_LINE> <INDENT> super(CriticNetwork, self).__init__() <NEW_LINE> self.fc1 = nn.Linear(state_dim, hidden_size) <NEW_LINE> self.fc2 = nn.Linear(hidden_size + action_dim, hidden_size) <NEW_LINE> self.fc3 = nn.Linear(hidden_size, output_size) <NEW_LINE> <DEDENT> def __call__(self, state, action): <NEW_LINE> <INDENT> out = nn.functional.relu(self.fc1(state)) <NEW_LINE> out = th.cat([out, action], 1) <NEW_LINE> out = nn.functional.relu(self.fc2(out)) <NEW_LINE> out = self.fc3(out) <NEW_LINE> return out | A network for critic | 62598fa20a50d4780f705241 |
class OverlayText(TextState): <NEW_LINE> <INDENT> def __init__(self, engine, target, parent, text, center=False): <NEW_LINE> <INDENT> super().__init__(engine, target, text, center) <NEW_LINE> self.parent = parent <NEW_LINE> <DEDENT> def render(self, console): <NEW_LINE> <INDENT> self.parent.render(console) <NEW_LINE> y = self.engine.screen_height // 2 - self.height // 2 <NEW_LINE> x = self.engine.screen_width // 2 - self.width // 2 <NEW_LINE> console.draw_frame(x, y, self.width, self.height, bg=C["BLACK"], fg=C["WHITE"]) <NEW_LINE> for line in self.lines: <NEW_LINE> <INDENT> if line != "BLANK": <NEW_LINE> <INDENT> console.print(x + 2, y + 2, line, C["WHITE"]) <NEW_LINE> <DEDENT> y += 1 | Displays text over another state's rendering. | 62598fa2e5267d203ee6b773 |
class Xrdb(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "http://cgit.freedesktop.org/xorg/app/xrdb" <NEW_LINE> url = "https://www.x.org/archive/individual/app/xrdb-1.1.0.tar.gz" <NEW_LINE> version('1.1.0', 'd48983e561ef8b4b2e245feb584c11ce') <NEW_LINE> depends_on('libxmu') <NEW_LINE> depends_on('libx11') <NEW_LINE> depends_on('xproto@7.0.17:', type='build') <NEW_LINE> depends_on('pkgconfig', type='build') <NEW_LINE> depends_on('util-macros', type='build') | xrdb - X server resource database utility. | 62598fa256b00c62f0fb2717 |
class Crossintray(_ObjectiveFunction): <NEW_LINE> <INDENT> def __init__(self, ndim): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._objective_function = crossintray <NEW_LINE> self.ndim = ndim <NEW_LINE> if self.ndim != 2: <NEW_LINE> <INDENT> raise ValueError("The crossintray function is defined for solution spaces having 2 dimensions.") <NEW_LINE> <DEDENT> self.bounds = np.ones((2, self.ndim)) <NEW_LINE> self.bounds[0,:] = -10. <NEW_LINE> self.bounds[1,:] = 10. <NEW_LINE> self.continuous = True <NEW_LINE> self.arg_min = np.ones(self.ndim) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unimodal(self): <NEW_LINE> <INDENT> return False | TODO | 62598fa2cc0a2c111447ae74 |
class Circle(object): <NEW_LINE> <INDENT> def __init__(self, radius): <NEW_LINE> <INDENT> self.radius = radius <NEW_LINE> <DEDENT> @property <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return math.pi*self.radius**2 <NEW_LINE> <DEDENT> @property <NEW_LINE> def perimeter(self): <NEW_LINE> <INDENT> return math.pi*self.radius*2 | classdocs | 62598fa255399d3f05626389 |
class HamrMessenger(object): <NEW_LINE> <INDENT> def __init__(self, server_ip='192.168.1.1', server_port=2390): <NEW_LINE> <INDENT> self.address=(server_ip, server_port) <NEW_LINE> self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> self.message_types = { 'holo_drive': (103, 'fff'), 'dif_drive': (104, 'fff') } <NEW_LINE> <DEDENT> def send_holonomic_command(self, x=0, y=0, r=0): <NEW_LINE> <INDENT> vector = [float(x), float(y), float(r)] <NEW_LINE> msg = self._message_generator('holo_drive', vector) <NEW_LINE> self._send_message(msg) <NEW_LINE> <DEDENT> def send_dif_drive_command(self, right=0, left=0, r=0): <NEW_LINE> <INDENT> vector = [float(right) * -1.0, float(left), float(r)] <NEW_LINE> self._send_message(self._message_generator('dif_drive', vector)) <NEW_LINE> <DEDENT> def kill_motors(self): <NEW_LINE> <INDENT> self.send_dif_drive_command(0.0, 0.0, 0.0) <NEW_LINE> <DEDENT> def _message_generator(self, message_type, data=[]): <NEW_LINE> <INDENT> msg_type = self.message_types[message_type][0] <NEW_LINE> msg_format = self.message_types[message_type][1] <NEW_LINE> msg = chr(msg_type) <NEW_LINE> if (len(data) != len(msg_format)): <NEW_LINE> <INDENT> raise ValueError('You provided insufficient data for this kind of message') <NEW_LINE> <DEDENT> msg += struct.pack('<' + msg_format, *data) <NEW_LINE> return msg <NEW_LINE> <DEDENT> def _send_message(self, message): <NEW_LINE> <INDENT> for _ in range(0, 2): <NEW_LINE> <INDENT> self.sock.sendto(message, self.address) | An interface that allows for motor commands to be sent to the HAMR.
If the source code on the HAMR was not changed, custom params for initialization should not be
necessary.
Attributes:
server_ip: A string that represents the IP of the access point of the HAMR.
server_port: An integer that represents the port the HAMR is listening on.
address: A tuple with server_ip and server_port
sock: A socket object responsible for sending out messages
message_types: A dictionary with the name of message associated with a tuple that contains the
ID of the message and format of the message. | 62598fa22ae34c7f260aaf47 |
class Environment(BASE, ModificationsTrackedObject): <NEW_LINE> <INDENT> __tablename__ = 'environment' <NEW_LINE> id = sa.Column(sa.String(255), primary_key=True, default=uuidutils.generate_uuid) <NEW_LINE> name = sa.Column(sa.String(255), nullable=False) <NEW_LINE> tenant_id = sa.Column(sa.String(36), nullable=False) <NEW_LINE> version = sa.Column(sa.BigInteger, nullable=False, default=0) <NEW_LINE> description = sa.Column(JsonBlob(), nullable=False, default={}) <NEW_LINE> networking = sa.Column(JsonBlob(), nullable=True, default={}) <NEW_LINE> sessions = sa_orm.relationship("Session", backref='environment', cascade='save-update, merge, delete') <NEW_LINE> deployments = sa_orm.relationship("Deployment", backref='environment', cascade='save-update, merge, delete') <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> dictionary = super(Environment, self).to_dict() <NEW_LINE> del dictionary['description'] <NEW_LINE> return dictionary | Represents a Environment in the metadata-store | 62598fa285dfad0860cbf9a8 |
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.params['W1'] = np.random.normal(0,weight_scale,(input_dim,hidden_dim)) <NEW_LINE> self.params['b1'] = np.zeros(hidden_dim) <NEW_LINE> self.params['W2'] = np.random.normal(0,weight_scale,(hidden_dim,num_classes)) <NEW_LINE> self.params['b2'] = np.zeros(num_classes) <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> X = np.reshape(X,(X.shape[0],-1)) <NEW_LINE> hidden_layer,cache_hidden_layer = affine_relu_forward(X,W1,b1) <NEW_LINE> scores,cache_scores = affine_forward(hidden_layer,W2,b2) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> reg = self.reg <NEW_LINE> loss,dscores = softmax_loss(scores,y) <NEW_LINE> loss += 0.5 * reg * (np.sum(W1*W1) + np.sum(W2*W2)) <NEW_LINE> da1, dW2, db2 = affine_backward(dscores,cache_scores) <NEW_LINE> dW2 += reg * W2 <NEW_LINE> dx, dW1, db1 = affine_relu_backward(da1,cache_hidden_layer) <NEW_LINE> dW1 += reg * W1 <NEW_LINE> grads.update({'W1':dW1, 'b1':db1, 'W2':dW2, 'b2':db2, }) <NEW_LINE> return loss, grads | A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classification over C classes.
The architecure should be affine - relu - affine - softmax.
Note that this class does not implement gradient descent; instead, it
will interact with a separate Solver object that is responsible for running
optimization.
The learnable parameters of the model are stored in the dictionary
self.params that maps parameter names to numpy arrays. | 62598fa201c39578d7f12be6 |
class EmptySeqError(Error): <NEW_LINE> <INDENT> pass | Raised when sequence is empty or whitespace only | 62598fa22c8b7c6e89bd362e |
class EditArticleHandler(FrontPageHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.preprocess(Article, handleSinglePage = True) <NEW_LINE> if self.user and self.admin: <NEW_LINE> <INDENT> article = ndb.Key(urlsafe=self.request.get('aid')).get() <NEW_LINE> template_values = { 'article':article, 'articles':self.articles, 'page':self.page, 'num_of_pages': self.num_of_pages, 'user':self.user, 'admin':self.admin, 'tag':self.tag, 'tags':self.tags, 'tagstr':self.tagstr, 'year':self.year, 'month':self.month, 'group_by_month':self.group_by_month, 'month_count':self.month_count, 'user_url':self.user_url, 'user_url_linktext':self.user_url_linktext } <NEW_LINE> template = JINJA_ENVIRONMENT.get_template('EditArticle.html') <NEW_LINE> self.response.write(template.render(template_values)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect('/') <NEW_LINE> <DEDENT> <DEDENT> def post(self): <NEW_LINE> <INDENT> title = self.request.get('title') <NEW_LINE> content = self.request.get('content') <NEW_LINE> article_urlsafe = cgi.escape(self.request.get('aid')) <NEW_LINE> tags = cgi.escape(self.request.get('tags')) <NEW_LINE> decision = self.request.get('decision') <NEW_LINE> if decision == 'P': <NEW_LINE> <INDENT> draft = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> draft = True <NEW_LINE> <DEDENT> if tags: <NEW_LINE> <INDENT> tags = [t.strip() for t in tags.split(',')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tags = [] <NEW_LINE> <DEDENT> article = ndb.Key(urlsafe=article_urlsafe).get() <NEW_LINE> is_published = article.draft and draft <NEW_LINE> article.title = title <NEW_LINE> article.content = content <NEW_LINE> article.tags = tags <NEW_LINE> article.draft = is_published <NEW_LINE> article.put() <NEW_LINE> self.redirect('/admin/Article?aid=' + article_urlsafe) | Handles from show to modify to submit an article in textarea. | 62598fa2379a373c97d98e7f |
class ApexAgent(DQNAgent): <NEW_LINE> <INDENT> _agent_name = "APEX" <NEW_LINE> _default_config = APEX_DEFAULT_CONFIG <NEW_LINE> @override(DQNAgent) <NEW_LINE> def update_target_if_needed(self): <NEW_LINE> <INDENT> if self.optimizer.num_steps_trained - self.last_target_update_ts > self.config["target_network_update_freq"]: <NEW_LINE> <INDENT> self.local_evaluator.foreach_trainable_policy( lambda p, _: p.update_target()) <NEW_LINE> self.last_target_update_ts = self.optimizer.num_steps_trained <NEW_LINE> self.num_target_updates += 1 | DQN variant that uses the Ape-X distributed policy optimizer.
By default, this is configured for a large single node (32 cores). For
running in a large cluster, increase the `num_workers` config var. | 62598fa23cc13d1c6d4655d4 |
class ProgramsApiConfigMixin(object): <NEW_LINE> <INDENT> DEFAULTS = { 'enabled': True, 'api_version_number': 1, 'internal_service_url': 'http://internal.programs.org/', 'public_service_url': 'http://public.programs.org/', 'authoring_app_js_path': '/path/to/js', 'authoring_app_css_path': '/path/to/css', 'cache_ttl': 0, 'enable_student_dashboard': True, 'enable_studio_tab': True, 'enable_certification': True, 'xseries_ad_enabled': True, } <NEW_LINE> def create_programs_config(self, **kwargs): <NEW_LINE> <INDENT> fields = dict(self.DEFAULTS, **kwargs) <NEW_LINE> ProgramsApiConfig(**fields).save() <NEW_LINE> return ProgramsApiConfig.current() | Utilities for working with Programs configuration during testing. | 62598fa2d58c6744b42dc207 |
class DjangoSQLPanel(DebugPanel): <NEW_LINE> <INDENT> name = 'Django SQL' <NEW_LINE> has_content = True <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(DjangoSQLPanel, self).__init__(*args, **kwargs) <NEW_LINE> self.jinja_env.loader = jinja2.ChoiceLoader( [ self.jinja_env.loader, jinja2.PrefixLoader( {'debug_tb_django': jinja2.PackageLoader(__name__, 'templates')} ), ] ) <NEW_LINE> filters = ( 'format_stack_trace', 'embolden_file', 'format_dict', 'highlight', 'pluralize', ) <NEW_LINE> for jfilter in filters: <NEW_LINE> <INDENT> self.jinja_env.filters[jfilter] = getattr(jinja_filters, jfilter) <NEW_LINE> <DEDENT> self._offset = {k: len(connections[k].queries) for k in connections} <NEW_LINE> self._sql_time = 0 <NEW_LINE> self._num_queries = 0 <NEW_LINE> self._queries = [] <NEW_LINE> self._databases = {} <NEW_LINE> self._transaction_status = {} <NEW_LINE> self._transaction_ids = {} <NEW_LINE> self.enable_instrumentation() <NEW_LINE> <DEDENT> def enable_instrumentation(self): <NEW_LINE> <INDENT> for connection in connections.all(): <NEW_LINE> <INDENT> wrap_cursor(connection, self) <NEW_LINE> <DEDENT> <DEDENT> def disable_instrumentation(self): <NEW_LINE> <INDENT> for connection in connections.all(): <NEW_LINE> <INDENT> unwrap_cursor(connection) <NEW_LINE> <DEDENT> <DEDENT> def record(self, alias, **kwargs): <NEW_LINE> <INDENT> self._queries.append((alias, kwargs)) <NEW_LINE> if alias not in self._databases: <NEW_LINE> <INDENT> self._databases[alias] = { "time_spent": kwargs["duration"], "num_queries": 1, } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._databases[alias]["time_spent"] += kwargs["duration"] <NEW_LINE> self._databases[alias]["num_queries"] += 1 <NEW_LINE> <DEDENT> self._sql_time += kwargs["duration"] <NEW_LINE> self._num_queries += 1 <NEW_LINE> <DEDENT> def title(self): <NEW_LINE> <INDENT> return 'Django SQL' <NEW_LINE> <DEDENT> def nav_title(self): <NEW_LINE> <INDENT> return 'Django SQL' <NEW_LINE> <DEDENT> def nav_subtitle(self): <NEW_LINE> <INDENT> ctx = {} <NEW_LINE> ctx['count'] = self._num_queries <NEW_LINE> ctx['time'] = '%.2f' % self._sql_time <NEW_LINE> return self.render('debug_tb_django/subtitle.html', ctx) <NEW_LINE> <DEDENT> def url(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def content(self): <NEW_LINE> <INDENT> context = self.context.copy() <NEW_LINE> context['queries'] = [q[1] for q in self._queries] <NEW_LINE> return self.render('debug_tb_django/panel.html', context) | Panel that shows information about Django SQL operations.
| 62598fa27b25080760ed7312 |
class UserProfile(AbstractUser): <NEW_LINE> <INDENT> email = models.EmailField(verbose_name="pochtovyy yashchik") <NEW_LINE> point = models.PositiveIntegerField(default=0, verbose_name="integratsiya") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "Profil' pol'zovatelya" <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.username <NEW_LINE> <DEDENT> def increase_point(self): <NEW_LINE> <INDENT> self.point += 1 <NEW_LINE> self.save(update_fields=['point']) | 用户资料 | 62598fa2adb09d7d5dc0a3f2 |
class UserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('email', 'password', 'name') <NEW_LINE> extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> return get_user_model().objects.create_user(**validated_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop('password', None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user | Serializer for the users object
| 62598fa2097d151d1a2c0e93 |
class TransitionDurationLessThanEqualTransitionDurationMixed(Atom): <NEW_LINE> <INDENT> def __init__(self, lhs_transition, rhs_transition): <NEW_LINE> <INDENT> self._lhs = lhs_transition <NEW_LINE> self._rhs = rhs_transition <NEW_LINE> self.verdict = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "d(%s) <= d(%s)" % (self._lhs, self._rhs) <NEW_LINE> <DEDENT> def __eq__(self, other_atom): <NEW_LINE> <INDENT> if type(other_atom) is TransitionDurationLessThanEqualTransitionDurationMixed: <NEW_LINE> <INDENT> return (self._lhs == other_atom._lhs and self._rhs == other_atom._rhs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def check(self, cummulative_state): <NEW_LINE> <INDENT> if cummulative_state.get(0) is None or cummulative_state.get(1) is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cummulative_state[0][0] <= cummulative_state[1][0] | This class models the atom (duration(t1) < duration(t2))
for v the duration of another transition. | 62598fa292d797404e388a9a |
class Bars(Selection1DExpr, Chart): <NEW_LINE> <INDENT> group = param.String(default='Bars', constant=True) <NEW_LINE> kdims = param.List(default=[Dimension('x')], bounds=(1,3)) <NEW_LINE> _max_kdim_count = 3 | Bars is a Chart element representing categorical observations
using the height of rectangular bars. The key dimensions represent
the categorical groupings of the data, but may also be used to
stack the bars, while the first value dimension represents the
height of each bar. | 62598fa20a50d4780f705243 |
@API.resource('/api/v1/users') <NEW_LINE> class UsersAPI(Resource): <NEW_LINE> <INDENT> @admin_required <NEW_LINE> def get(self): <NEW_LINE> <INDENT> args = rqParse(rqArg('cursor', type=vdr.toCursor)) <NEW_LINE> usersQuery = User.query() .order(-User.created_r) .fetch_page_async(page_size=10, start_cursor=args.cursor) <NEW_LINE> totalQuery = User.query().count_async(keys_only=True) <NEW_LINE> users, next_cursor, more = usersQuery.get_result() <NEW_LINE> users = [u.toDict() for u in users] <NEW_LINE> return list_response(users, next_cursor, more, totalQuery.get_result()) | Get list of users with ndb Cursor for pagination. Obtaining users is executed
in parallel with obtaining total count via *_async functions | 62598fa20c0af96317c561ea |
class DatasetsPatch(base.Command): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.add_argument('--description', help='Description of the dataset.') <NEW_LINE> parser.add_argument('dataset_name', help='The name of the dataset.') <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> apitools_client = self.context[commands.APITOOLS_CLIENT_KEY] <NEW_LINE> bigquery_messages = self.context[commands.BIGQUERY_MESSAGES_MODULE_KEY] <NEW_LINE> resource_parser = self.context[commands.BIGQUERY_REGISTRY_KEY] <NEW_LINE> resource = resource_parser.Parse( args.dataset_name, collection='bigquery.datasets') <NEW_LINE> reference = message_conversions.DatasetResourceToReference( bigquery_messages, resource) <NEW_LINE> request = bigquery_messages.BigqueryDatasetsPatchRequest( dataset=bigquery_messages.Dataset( datasetReference=bigquery_messages.DatasetReference( projectId=reference.projectId, datasetId=reference.datasetId), description=args.description), projectId=reference.projectId, datasetId=reference.datasetId) <NEW_LINE> apitools_client.datasets.Patch(request) <NEW_LINE> log.UpdatedResource(resource) | Updates the description of a dataset.
| 62598fa267a9b606de545e33 |
class Message(object): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> DESCRIPTOR = None <NEW_LINE> def __deepcopy__(self, memo=None): <NEW_LINE> <INDENT> clone = type(self)() <NEW_LINE> clone.MergeFrom(self) <NEW_LINE> return clone <NEW_LINE> <DEDENT> def __eq__(self, other_msg): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __ne__(self, other_msg): <NEW_LINE> <INDENT> return not self == other_msg <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> raise TypeError('unhashable object') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def MergeFrom(self, other_msg): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def CopyFrom(self, other_msg): <NEW_LINE> <INDENT> if self is other_msg: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.Clear() <NEW_LINE> self.MergeFrom(other_msg) <NEW_LINE> <DEDENT> def Clear(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def SetInParent(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def IsInitialized(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def MergeFromString(self, serialized): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ParseFromString(self, serialized): <NEW_LINE> <INDENT> self.Clear() <NEW_LINE> return self.MergeFromString(serialized) <NEW_LINE> <DEDENT> def SerializeToString(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def SerializePartialToString(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ListFields(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def HasField(self, field_name): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ClearField(self, field_name): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def WhichOneof(self, oneof_group): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def HasExtension(self, extension_handle): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ClearExtension(self, extension_handle): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def UnknownFields(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def DiscardUnknownFields(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ByteSize(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _SetListener(self, message_listener): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return dict(serialized=self.SerializePartialToString()) <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self.__init__() <NEW_LINE> self.ParseFromString(state['serialized']) | Abstract base class for protocol messages.
Protocol message classes are almost always generated by the protocol
compiler. These generated types subclass Message and implement the methods
shown below.
TODO(robinson): Link to an HTML document here.
TODO(robinson): Document that instances of this class will also
have an Extensions attribute with __getitem__ and __setitem__.
Again, not sure how to best convey this.
TODO(robinson): Document that the class must also have a static
RegisterExtension(extension_field) method.
Not sure how to best express at this point. | 62598fa2eab8aa0e5d30bbf0 |
class LimitAggregatorQuotaField(AggregatorQuotaField): <NEW_LINE> <INDENT> aggregation_field = 'limit' | Aggregates sum children quotas limits. | 62598fa255399d3f0562638b |
class ShowSpanningTreeMstDetailSchema(MetaParser): <NEW_LINE> <INDENT> schema = { 'mst_instances': { Any(): { 'mst_id': int, Optional('vlan'): str, 'bridge_address': str, 'bridge_priority': int, 'sysid': int, Optional('root'): str, Optional('root_address'): str, Optional('root_priority'): int, Optional('operational'): { 'hello_time': int, 'forward_delay': int, 'max_age': int, 'tx_hold_count': int }, Optional('configured'): { 'hello_time': int, 'forward_delay': int, 'max_age': int, 'max_hops': int }, 'interfaces': { Any(): { 'status': str, Optional('broken_reason'): str, 'name': str, 'port_id': str, 'cost': int, 'port_priority': int, 'designated_root_priority': int, 'designated_root_address': str, 'designated_root_cost': int, Optional('designated_regional_root_cost'): int, Optional('designated_regional_root_priority'): int, Optional('designated_regional_root_address'): str, 'designated_bridge_priority': int, 'designated_bridge_address': str, 'designated_bridge_port_id': str, 'forward_transitions': int, 'message_expires': int, 'forward_delay': int, 'counters': { 'bpdu_sent': int, 'bpdu_received': int, } } } }, } } | Schema for show spanning-tree mst detail | 62598fa2dd821e528d6d8d9e |
class ClanWarLeagueClan(BaseClan): <NEW_LINE> <INDENT> __slots__ = BaseClan.__slots__ + ("_cs_members", "_iter_members") <NEW_LINE> def __init__(self, *, data, client): <NEW_LINE> <INDENT> super().__init__(data=data, client=client) <NEW_LINE> self._iter_members = ( ClanWarLeagueClanMember(data=mdata, client=self._client) for mdata in data.get("members", []) ) <NEW_LINE> <DEDENT> @cached_property("_cs_members") <NEW_LINE> def members(self) -> typing.List[ClanWarLeagueClanMember]: <NEW_LINE> <INDENT> return list(self._iter_members) | Represents a Clan War League Clan.
Attributes
----------
tag: :class:`str`
The clan's tag
name: :class:`str`
The clan's name
badge: :class:`Badge`
The clan's badge
level: :class:`int`
The clan's level. | 62598fa24f6381625f1993f1 |
class DistrictButon(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.enabled = True <NEW_LINE> self.checked = False <NEW_LINE> <DEDENT> def onClick(self): <NEW_LINE> <INDENT> infc = (GetSelectedLayers())[0] <NEW_LINE> if ensure_dist_id(infc): <NEW_LINE> <INDENT> add_id = Add_Integer_Field_Tool() <NEW_LINE> add_id.run(infc, 'Dist_ID', numDistricts(infc)) <NEW_LINE> <DEDENT> updateSymbolization() | Implementation for DSaddin_district.button (Button) | 62598fa2090684286d59360f |
class CleanupNonlocalControl(NonlocalControl): <NEW_LINE> <INDENT> def __init__(self, outer: NonlocalControl) -> None: <NEW_LINE> <INDENT> self.outer = outer <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def gen_cleanup(self, builder: 'IRBuilder', line: int) -> None: ... <NEW_LINE> def gen_break(self, builder: 'IRBuilder', line: int) -> None: <NEW_LINE> <INDENT> self.gen_cleanup(builder, line) <NEW_LINE> self.outer.gen_break(builder, line) <NEW_LINE> <DEDENT> def gen_continue(self, builder: 'IRBuilder', line: int) -> None: <NEW_LINE> <INDENT> self.gen_cleanup(builder, line) <NEW_LINE> self.outer.gen_continue(builder, line) <NEW_LINE> <DEDENT> def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None: <NEW_LINE> <INDENT> self.gen_cleanup(builder, line) <NEW_LINE> self.outer.gen_return(builder, value, line) | Abstract nonlocal control that runs some cleanup code. | 62598fa23d592f4c4edbad36 |
class OneShotClientTransaction(ClientTransaction): <NEW_LINE> <INDENT> FSMDefinitions = { InitialState: { Transaction.Inputs.request: { tsk.NewState: Transaction.States.terminated, tsk.Action: 'transmit', }, }, Transaction.States.terminated: {}, } | Transaction that constitutes a single unreliable request send. | 62598fa201c39578d7f12be8 |
class WriteLogEntriesResponse(_messages.Message): <NEW_LINE> <INDENT> pass | Result returned from WriteLogEntries.
empty | 62598fa297e22403b383ad74 |
class ZincblendeStructureGenerator(BulkGeneratorBase, ZincblendeStructure): <NEW_LINE> <INDENT> def save(self, fname='zincblende', **kwargs): <NEW_LINE> <INDENT> super().save(fname=fname, scaling_matrix=self.scaling_matrix, **kwargs) | :class:`ZincblendeStructure` generator class. | 62598fa21f5feb6acb162a8c |
class QueuedMogileFSStorage(QueuedFileSystemStorage): <NEW_LINE> <INDENT> def __init__(self, remote='storages.backends.mogile.MogileFSStorage', *args, **kwargs): <NEW_LINE> <INDENT> super(QueuedMogileFSStorage, self).__init__(remote=remote, *args, **kwargs) | A custom :class:`~queued_storage.backends.QueuedFileSystemStorage`
subclass which uses the ``MogileFSStorage`` storage of the
`django-storages <https://django-storages.readthedocs.io/>`_ app as
the remote storage. | 62598fa27d847024c075c22f |
class UnexpectedRSPValue(Exception): <NEW_LINE> <INDENT> pass | 가위 바위 보 가운데 하나가 아닌 값인 경우에 발생하는 에러 | 62598fa2cb5e8a47e493c0ab |
class api: <NEW_LINE> <INDENT> def __init__(self, info): <NEW_LINE> <INDENT> requires = ('description', 'score', 'choices') <NEW_LINE> options = ('difficulty', 'analysis', 'remark') <NEW_LINE> for require in requires: <NEW_LINE> <INDENT> setattr(self, '_'+require, info.get(require)) <NEW_LINE> <DEDENT> for option in options: <NEW_LINE> <INDENT> setattr(self, '_'+option, info.get(option, None)) <NEW_LINE> <DEDENT> self._preprocess() <NEW_LINE> <DEDENT> def render(self, begin='\n', end='\n'): <NEW_LINE> <INDENT> _remark = self._remark or '%' <NEW_LINE> _question = f'\\question[{self._score}] {self._description}\\par' <NEW_LINE> _choices = f'\\begin{{不定项选择}}\n{self._choices}\n\\end{{不定项选择}}' <NEW_LINE> if self._analysis is not None: <NEW_LINE> <INDENT> _analysis = f'\\begin{{解析}}\n{self._analysis}\n\\end{{解析}}' <NEW_LINE> <DEDENT> else: _analysis='' <NEW_LINE> return begin + '\n'.join((_remark, _question, _choices, _analysis)) + end <NEW_LINE> <DEDENT> def _preprocess(self): <NEW_LINE> <INDENT> self._score = int(self._score) <NEW_LINE> _choices = list(self._choices.items()) <NEW_LINE> random.shuffle(_choices) <NEW_LINE> self._choices = '\n'.join((f'\\CorrectChoice {c}' if int(f) else f'\\choice {c}') for c, f in _choices) <NEW_LINE> if self._difficulty is not None: <NEW_LINE> <INDENT> self._difficulty = float(self._difficulty) <NEW_LINE> <DEDENT> if self._remark is not None: <NEW_LINE> <INDENT> _remarks = (f'% {line}' for line in self._remark.splitlines()) <NEW_LINE> self._remark = '\n'.join(_remarks) | 不定项选择 API
Argument
--------
description: DataRequired
score: DataRequired
choices: DataRequired: Dict[str, int]
difficulty: Optional, NumberRange(0, 1): float
analysis: Optional
remark: Optional
Example
-------
{
"type": "不定项选择",
"description": "本题为不定项选择.",
"score": "5",
"difficulty": "0.1",
"analysis": "这里为解析部分.",
"choices": {
"错误答案-1": "0",
"错误答案-2": "0",
"正确答案-3": "1",
"正确答案-4": "1"
},
"remark": "本题考察了模板的使用."
} | 62598fa2379a373c97d98e81 |
class Object(object): <NEW_LINE> <INDENT> def __init__(self, name, size, hash, extra, meta_data, container, driver): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.size = size <NEW_LINE> self.hash = hash <NEW_LINE> self.container = container <NEW_LINE> self.extra = extra or {} <NEW_LINE> self.meta_data = meta_data or {} <NEW_LINE> self.driver = driver <NEW_LINE> <DEDENT> def download(self, destination_path, overwrite_existing=False, delete_on_failure=True): <NEW_LINE> <INDENT> return self.driver.download_object(self, destination_path, overwrite_existing, delete_on_failure) <NEW_LINE> <DEDENT> def as_stream(self, chunk_size=None): <NEW_LINE> <INDENT> return self.driver.download_object_as_stream(self, chunk_size) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self.driver.delete_object(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('<Object: name=%s, size=%s, hash=%s, provider=%s ...>' % (self.name, self.size, self.hash, self.driver.name)) | Represents an object (BLOB). | 62598fa28c0ade5d55dc35c4 |
class U(R): <NEW_LINE> <INDENT> def b(self): <NEW_LINE> <INDENT> pass | clashes with class A. | 62598fa27cff6e4e811b5890 |
class DeleteDeployGroupsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DeployGroupIds = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DeployGroupIds = params.get("DeployGroupIds") <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)) | DeleteDeployGroups请求参数结构体
| 62598fa2adb09d7d5dc0a3f4 |
class UrlBase(object): <NEW_LINE> <INDENT> def __init__(self, source=None): <NEW_LINE> <INDENT> self.urls = list(map(Url, source.urls)) if source else [] <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return [url.serialize() for url in self.urls] <NEW_LINE> <DEDENT> def to_struct(self): <NEW_LINE> <INDENT> return [url.to_struct() for url in self.urls] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_struct(cls, struct): <NEW_LINE> <INDENT> return [Url.from_struct(url) for url in struct] <NEW_LINE> <DEDENT> def unserialize(self, data): <NEW_LINE> <INDENT> self.urls = [Url().unserialize(item) for item in data] <NEW_LINE> <DEDENT> def get_url_list(self): <NEW_LINE> <INDENT> return self.urls <NEW_LINE> <DEDENT> def set_url_list(self, url_list): <NEW_LINE> <INDENT> self.urls = url_list <NEW_LINE> <DEDENT> def _merge_url_list(self, acquisition): <NEW_LINE> <INDENT> url_list = self.urls[:] <NEW_LINE> for addendum in acquisition.get_url_list(): <NEW_LINE> <INDENT> for url in url_list: <NEW_LINE> <INDENT> equi = url.is_equivalent(addendum) <NEW_LINE> if equi == IDENTICAL: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif equi == EQUAL: <NEW_LINE> <INDENT> url.merge(addendum) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.urls.append(addendum) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_url(self, url): <NEW_LINE> <INDENT> self.urls.append(url) <NEW_LINE> <DEDENT> def remove_url(self, url): <NEW_LINE> <INDENT> if url in self.urls: <NEW_LINE> <INDENT> self.urls.remove(url) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Base class for url-aware objects. | 62598fa201c39578d7f12be9 |
class ConfigurationSpec(_messages.Message): <NEW_LINE> <INDENT> generation = _messages.IntegerField(1, variant=_messages.Variant.INT32) <NEW_LINE> revisionTemplate = _messages.MessageField('RevisionTemplate', 2) | ConfigurationSpec holds the desired state of the Configuration (from the
client).
Fields:
generation: Deprecated and not currently populated by Cloud Run. See
metadata.generation instead, which is the sequence number containing the
latest generation of the desired state. Read-only.
revisionTemplate: RevisionTemplate holds the latest specification for the
Revision to be stamped out. The template references the container image,
and may also include labels and annotations that should be attached to
the Revision. To correlate a Revision, and/or to force a Revision to be
created when the spec doesn't otherwise change, a nonce label may be
provided in the template metadata. For more details, see:
https://github.com/knative/serving/blob/master/docs/client-
conventions.md#associate-modifications-with-revisions Cloud Run does
not currently support referencing a build that is responsible for
materializing the container image from source. | 62598fa257b8e32f52508051 |
class PluginClasses(Collection): <NEW_LINE> <INDENT> def __init__(self, world, collection, owning=False): <NEW_LINE> <INDENT> assert type(collection) == POINTER(PluginClasses) <NEW_LINE> assert collection <NEW_LINE> self.owning = owning <NEW_LINE> super(PluginClasses, self).__init__( world, collection, c.plugin_classes_begin, PluginClass, c.plugin_classes_get, c.plugin_classes_next, c.plugin_classes_is_end, ) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.owning: <NEW_LINE> <INDENT> c.plugin_classes_free(self.collection) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return bool(self.get_by_uri(_as_uri(key))) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return c.plugin_classes_size(self.collection) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if type(key) == int: <NEW_LINE> <INDENT> return super(PluginClasses, self).__getitem__(key) <NEW_LINE> <DEDENT> klass = self.get_by_uri(key) <NEW_LINE> if klass is None: <NEW_LINE> <INDENT> raise KeyError("Plugin class not found: " + str(key)) <NEW_LINE> <DEDENT> return klass <NEW_LINE> <DEDENT> def get_by_uri(self, uri): <NEW_LINE> <INDENT> if type(uri) == str: <NEW_LINE> <INDENT> uri = self.world.new_uri(uri) <NEW_LINE> <DEDENT> plugin_class = c.plugin_classes_get_by_uri(self.collection, uri.node) <NEW_LINE> return PluginClass(self.world, plugin_class) if plugin_class else None | Collection of plugin classes. | 62598fa26fb2d068a7693d6a |
class ExpectHelloRequest(ExpectHandshake): <NEW_LINE> <INDENT> def __init__(self, description=None): <NEW_LINE> <INDENT> super(ExpectHelloRequest, self).__init__( ContentType.handshake, HandshakeType.hello_request) <NEW_LINE> self.description = description <NEW_LINE> <DEDENT> def process(self, state, msg): <NEW_LINE> <INDENT> assert msg.contentType == ContentType.handshake <NEW_LINE> parser = Parser(msg.write()) <NEW_LINE> hs_type = parser.get(1) <NEW_LINE> assert hs_type == HandshakeType.hello_request <NEW_LINE> HelloRequest().parse(parser) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._repr(['description']) | Processing of TLS handshake protocol hello request message. | 62598fa2e76e3b2f99fd88a2 |
class tf_reader(object): <NEW_LINE> <INDENT> def __init__(self, tf_record_path, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> print(config) <NEW_LINE> dataset = tf.data.TFRecordDataset([tf_record_path], buffer_size=config.BUFFER_SIZE) <NEW_LINE> dataset = dataset.repeat(cfg.TRAIN.EPOCH) <NEW_LINE> if self.config.SHUFFLE: <NEW_LINE> <INDENT> dataset = dataset.shuffle(self.config.BATCH_SIZE * 3) <NEW_LINE> <DEDENT> dataset = dataset.map(self.parse_function, num_parallel_calls=12) <NEW_LINE> dataset = dataset.prefetch(self.config.BUFFER_SIZE) <NEW_LINE> self.dataset = dataset.batch(self.config.BATCH_SIZE) <NEW_LINE> self.batch_iterator = self.dataset.make_initializable_iterator() <NEW_LINE> <DEDENT> def parse_function(self, example_proto): <NEW_LINE> <INDENT> features = { 'qa_id': tf.FixedLenFeature(shape=[1], dtype=tf.int64), 'qtype': tf.FixedLenFeature(shape=[1], dtype=tf.int64), 'video_feature': tf.FixedLenFeature(shape=[20,7,4100], dtype=tf.float32), 'question': tf.FixedLenFeature(shape=[30,1001], dtype=tf.int64), 'answer': tf.FixedLenFeature(shape=[1001], dtype=tf.int64), 'candidate': tf.FixedLenFeature(shape=[4,1001], dtype=tf.int64), } <NEW_LINE> parsed_features = tf.parse_single_example(example_proto, features) <NEW_LINE> return parsed_features | dataset reader | 62598fa2a17c0f6771d5c0a4 |
class Login(APIView): <NEW_LINE> <INDENT> permission_classes = (AllowAny, ) <NEW_LINE> def post(self, request, format=None): <NEW_LINE> <INDENT> adapter = self.adapter_class(request) <NEW_LINE> provider = adapter.get_provider() <NEW_LINE> app = provider.get_app(request) <NEW_LINE> view = OAuth2LoginView() <NEW_LINE> view.request = request <NEW_LINE> view.adapter = adapter <NEW_LINE> client = view.get_client(request, app) <NEW_LINE> action = AuthAction.AUTHENTICATE <NEW_LINE> auth_params = provider.get_auth_params(request, action) <NEW_LINE> client.state = SocialLogin.stash_state(request) <NEW_LINE> url = client.get_redirect_url(adapter.authorize_url, auth_params) <NEW_LINE> return Response({'url': url}) | View for returning Ibis-specific url to submit Oauth2 request
The user submits a blank post request to this view and receives,
view a serialized JSON object, a url that embedds an oauth
'client_id' to identify the app with, a 'redirect_uri' to
redirect the user after login, and a 'state' to secure against
tampering through the entire process. | 62598fa266656f66f7d5a25c |
class DeleteComment(bloghandler.Handler): <NEW_LINE> <INDENT> @decorator.user_logged_in <NEW_LINE> @decorator.post_exists <NEW_LINE> @decorator.comment_exists <NEW_LINE> @decorator.user_owns_comment <NEW_LINE> def get(self, blog_id): <NEW_LINE> <INDENT> blog_post = BlogPost.get_by_id(int(blog_id)) <NEW_LINE> cid = self.request.get('cid') <NEW_LINE> cmt = self.get_valid_comment(cid) <NEW_LINE> blog_post.delete_comment(int(cid)) <NEW_LINE> blog_post.put() <NEW_LINE> cmt.delete() <NEW_LINE> self.redirect('/blog/%d' % int(blog_id)) | DeleteComment handler processes a User request to remove a
comment that they made from the blog and delete it from the
comment database. | 62598fa2dd821e528d6d8d9f |
class Signal(QObject): <NEW_LINE> <INDENT> changed = pyqtSignal() | Signal creates a pyqtSignal to be emitted in other classes. | 62598fa23539df3088ecc11f |
@pytest.mark.usefixtures("localtyperegistry") <NEW_LINE> class BaseSpokeTest(object): <NEW_LINE> <INDENT> type = None <NEW_LINE> def create_instance(self): <NEW_LINE> <INDENT> return self.type.model() <NEW_LINE> <DEDENT> @classproperty <NEW_LINE> def typename(cls): <NEW_LINE> <INDENT> return cls.type.model.get_name() <NEW_LINE> <DEDENT> def test_equal_none(self, client): <NEW_LINE> <INDENT> s = self.create_instance().spoke().save() <NEW_LINE> assert not s == None <NEW_LINE> <DEDENT> def test_nonequal_none(self, client): <NEW_LINE> <INDENT> s = self.create_instance().spoke().save() <NEW_LINE> assert s != None <NEW_LINE> <DEDENT> def test_equal_self(self, client): <NEW_LINE> <INDENT> s = self.create_instance().spoke().save() <NEW_LINE> assert s == s <NEW_LINE> <DEDENT> def test_equal_multi_spokes(self, client): <NEW_LINE> <INDENT> i = self.create_instance().save() <NEW_LINE> s1 = i.spoke() <NEW_LINE> s2 = i.spoke() <NEW_LINE> assert s1 == s2 <NEW_LINE> <DEDENT> def test_notequal_multi_spokes(self, client): <NEW_LINE> <INDENT> s1 = self.create_instance().spoke().save() <NEW_LINE> s2 = self.create_instance().spoke().save() <NEW_LINE> assert s1 != s2 <NEW_LINE> <DEDENT> def test_name(self, client): <NEW_LINE> <INDENT> model = self.create_instance() <NEW_LINE> model.save() <NEW_LINE> spoke = self.type(model) <NEW_LINE> assert spoke.name() == self.typename <NEW_LINE> <DEDENT> def test_fields(self, client): <NEW_LINE> <INDENT> model = self.create_instance() <NEW_LINE> model.save() <NEW_LINE> spoke = self.type(model) <NEW_LINE> fields = dict(spoke.fields()) <NEW_LINE> assert 'title' in fields <NEW_LINE> return fields <NEW_LINE> <DEDENT> def test_spoke_save(self, client): <NEW_LINE> <INDENT> M = self.type.model <NEW_LINE> model = self.create_instance() <NEW_LINE> spoke = self.type(model) <NEW_LINE> spoke.save() <NEW_LINE> assert M.objects.all()[0] == model | Basic spoke testing | 62598fa291af0d3eaad39c77 |
class PrivateEndpointConnection(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'private_endpoint': {'key': 'properties.privateEndpoint', 'type': 'PrivateEndpoint'}, 'private_link_service_connection_state': {'key': 'properties.privateLinkServiceConnectionState', 'type': 'ConnectionState'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, private_endpoint: Optional["PrivateEndpoint"] = None, private_link_service_connection_state: Optional["ConnectionState"] = None, provisioning_state: Optional[Union[str, "EndPointProvisioningState"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(PrivateEndpointConnection, self).__init__(**kwargs) <NEW_LINE> self.private_endpoint = private_endpoint <NEW_LINE> self.private_link_service_connection_state = private_link_service_connection_state <NEW_LINE> self.provisioning_state = provisioning_state | Properties of the PrivateEndpointConnection.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource ID for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or
"Microsoft.Storage/storageAccounts".
:vartype type: str
:param private_endpoint: The Private Endpoint resource for this Connection.
:type private_endpoint: ~azure.mgmt.eventhub.v2018_01_01_preview.models.PrivateEndpoint
:param private_link_service_connection_state: Details about the state of the connection.
:type private_link_service_connection_state:
~azure.mgmt.eventhub.v2018_01_01_preview.models.ConnectionState
:param provisioning_state: Provisioning state of the Private Endpoint Connection. Possible
values include: "Creating", "Updating", "Deleting", "Succeeded", "Canceled", "Failed".
:type provisioning_state: str or
~azure.mgmt.eventhub.v2018_01_01_preview.models.EndPointProvisioningState | 62598fa276e4537e8c3ef417 |
class CmdSnmpMemDataSourceInfo(RRDDataSourceInfo): <NEW_LINE> <INDENT> implements(ICmdSnmpMemDataSourceInfo) <NEW_LINE> adapts(CmdSnmpMemDataSource) <NEW_LINE> hostname = ProxyProperty('hostname') <NEW_LINE> ipAddress = ProxyProperty('ipAddress') <NEW_LINE> snmpVer = ProxyProperty('snmpVer') <NEW_LINE> snmpCommunity = ProxyProperty('snmpCommunity') <NEW_LINE> cycletime = ProxyProperty('cycletime') <NEW_LINE> testable = False | Adapter between ICmdSnmpMemDataSourceInfo and CmdSnmpMemDataSource. | 62598fa21f037a2d8b9e3f54 |
class Iface: <NEW_LINE> <INDENT> def checkKeyword(self, params): <NEW_LINE> <INDENT> pass | 关键词服务
@since 1.0.0
@author bjf
@date 2015年9月1日 下午5:34:32 | 62598fa2e1aae11d1e7ce759 |
class TradeMonitor(BasicMonitor): <NEW_LINE> <INDENT> def __init__(self, mainEngine, eventEngine, parent=None): <NEW_LINE> <INDENT> super(TradeMonitor, self).__init__(mainEngine, eventEngine, parent) <NEW_LINE> d = OrderedDict() <NEW_LINE> d['tradeID'] = {'chinese': u'成交编号', 'cellType': BasicCell} <NEW_LINE> d['orderID'] = {'chinese': u'委托编号', 'cellType': BasicCell} <NEW_LINE> d['symbol'] = {'chinese': u'合约代码', 'cellType': BasicCell} <NEW_LINE> d['name'] = {'chinese': u'名称', 'cellType': NameCell} <NEW_LINE> d['direction'] = {'chinese': u'方向', 'cellType': DirectionCell} <NEW_LINE> d['offset'] = {'chinese': u'开平', 'cellType': BasicCell} <NEW_LINE> d['price'] = {'chinese': u'价格', 'cellType': BasicCell} <NEW_LINE> d['volume'] = {'chinese': u'数量', 'cellType': NumCell} <NEW_LINE> d['tradeTime'] = {'chinese': u'成交时间', 'cellType': BasicCell} <NEW_LINE> self.setHeaderDict(d) <NEW_LINE> self.setDataKey('vtTradeID') <NEW_LINE> self.setEventType(EVENT_TRADE, EVENT_CLEAR) <NEW_LINE> self.setFont(BASIC_FONT) <NEW_LINE> self.setSorting(True) <NEW_LINE> self.initTable() <NEW_LINE> self.registerEvent() | 成交监控 | 62598fa2925a0f43d25e7ea8 |
class BadRequestImageBuilderActionError(ImageBuilderActionError, BadRequest): <NEW_LINE> <INDENT> def __init__(self, message: str, validation_failures: list = None): <NEW_LINE> <INDENT> super().__init__(message, validation_failures) | Represent an error during the execution of an action due to a problem with the request. | 62598fa24527f215b58e9d4d |
class Credits(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.finished = False <NEW_LINE> <DEDENT> def progress(self, window): <NEW_LINE> <INDENT> self.finished = True | Plays the credits sequence at the end of the game. | 62598fa2460517430c431f90 |
class MigrationStatusPrinter(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.printed_yet = False <NEW_LINE> <DEDENT> def info(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> if not self.printed_yet: <NEW_LINE> <INDENT> print('\n ', end='') <NEW_LINE> self.printed_yet = True <NEW_LINE> <DEDENT> msg = msg.format(*args, **kwargs) <NEW_LINE> print(' {0}'.format(msg), end='\n ') | Print migration status in an attractive way during a Django migration run.
In particular, you get output that looks like this
Running migrations:
Applying users.0005_set_initial_contrib_email_flag...
set first_l10n_email_sent on 2793 profiles.
set first_answer_email_sent on 46863 profiles.
OK
Each step that wants to use this class should make its own instance.
Reusing instances will not result in the right print behavior. | 62598fa26e29344779b004c7 |
class TestCertificateFields(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testCertificateFields(self): <NEW_LINE> <INDENT> model = artikcloud.models.certificate_fields.CertificateFields() | CertificateFields unit test stubs | 62598fa2e5267d203ee6b778 |
class TestLibVirtControllerSessionDirectTLS( TestLibVirtControllerSession, TestLibVirtControllerDirectTLS, unittest.TestCase ): <NEW_LINE> <INDENT> pass | Test LibVirtController with spice_remote_viewer viewer at session mode. | 62598fa2498bea3a75a5798c |
class KeyboardHook(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.user32 = windll.user32 <NEW_LINE> self.kbHook = None <NEW_LINE> <DEDENT> def installHook(self, pointer): <NEW_LINE> <INDENT> self.kbHook = self.user32.SetWindowsHookExA( win32con.WH_KEYBOARD_LL, pointer, win32api.GetModuleHandle(None), 0 ) <NEW_LINE> if not self.kbHook: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.uninstallHook() <NEW_LINE> self.kbHook = None <NEW_LINE> <DEDENT> def keepAlive(self): <NEW_LINE> <INDENT> if self.kbHook is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> while self.kbHook is not None: <NEW_LINE> <INDENT> win32gui.PumpWaitingMessages() <NEW_LINE> time.sleep(0.001) <NEW_LINE> <DEDENT> <DEDENT> def uninstallHook(self): <NEW_LINE> <INDENT> if self.kbHook is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.user32.UnhookWindowsHookEx(self.kbHook) <NEW_LINE> self.kbHook = None | Written by: TwhK / Kheldar
What do? Installs a global keyboard hook
To install the hook, call the (gasp!) installHook() function.
installHook() takes a pointer to the function that will be called
after a keyboard event. installHook() returns True if everything
was successful, and False if it failed
Note: I've also provided a function to return a valid function pointer
To make sure the hook is actually doing what you want, call the
keepAlive() function
Note: keepAlive() doesn't return until kbHook is None, so it should
be called from a separate thread
To uninstall the hook, call uninstallHook()
Note: relies on modules provided by pywin32.
http://sourceforge.net/projects/pywin32/ | 62598fa297e22403b383ad76 |
class DummyABBController: <NEW_LINE> <INDENT> def __init__(self, ip='192.168.125.1', port=5000): <NEW_LINE> <INDENT> logger.debug("DummyABBController.__init__(ip={}, port={})".format( ip, port)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() | Dummy ABB controller class.
| 62598fa22ae34c7f260aaf4c |
class TokenGenerator(PasswordResetTokenGenerator): <NEW_LINE> <INDENT> def _make_hash_value(self, user, timestamp): <NEW_LINE> <INDENT> return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) | Generate token to create link during reseting user's password | 62598fa267a9b606de545e36 |
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim) <NEW_LINE> self.params['b1'] = np.zeros(hidden_dim) <NEW_LINE> self.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes) <NEW_LINE> self.params['b2'] = np.zeros(num_classes) <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> out1, cache1 = affine_forward(X, W1, b1) <NEW_LINE> out_relu, cache_relu = relu_forward(out1) <NEW_LINE> out2, cache2 = affine_forward(out_relu, W2, b2) <NEW_LINE> scores = out2 <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss, dscores = softmax_loss(scores, y) <NEW_LINE> loss += 0.5 * self.reg * np.sum(W1 * W1) <NEW_LINE> loss += 0.5 * self.reg * np.sum(W2 * W2) <NEW_LINE> dout2, grads['W2'], grads['b2'] = affine_backward(dscores, cache2) <NEW_LINE> dout_relu = relu_backward(dout2, cache_relu) <NEW_LINE> dout1, grads['W1'], grads['b1'] = affine_backward(dout_relu, cache1) <NEW_LINE> grads['W2'] += self.reg * W2 <NEW_LINE> grads['W1'] += self.reg * W1 <NEW_LINE> return loss, grads | A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classification over C classes.
The architecture should be affine - relu - affine - softmax.
Note that this class does not implement gradient descent; instead, it
will interact with a separate Solver object that is responsible for running
optimization.
The learnable parameters of the model are stored in the dictionary
self.params that maps parameter names to numpy arrays. | 62598fa2379a373c97d98e82 |
@Body.register <NEW_LINE> class Keyword(model.Keyword): <NEW_LINE> <INDENT> __slots__ = ['lineno'] <NEW_LINE> def __init__(self, name='', doc='', args=(), assign=(), tags=(), timeout=None, type=BodyItem.KEYWORD, parent=None, lineno=None): <NEW_LINE> <INDENT> model.Keyword.__init__(self, name, doc, args, assign, tags, timeout, type, parent) <NEW_LINE> self.lineno = lineno <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self.parent.source if self.parent is not None else None <NEW_LINE> <DEDENT> def run(self, context, run=True, templated=None): <NEW_LINE> <INDENT> return KeywordRunner(context, run).run(self) | Represents a single executable keyword.
These keywords never have child keywords or messages. The actual keyword
that is executed depends on the context where this model is executed.
See the base class for documentation of attributes not documented here. | 62598fa256ac1b37e6302057 |
class LieAlgebraRegularVectorFields(InfinitelyGeneratedLieAlgebra, IndexedGenerators): <NEW_LINE> <INDENT> def __init__(self, R): <NEW_LINE> <INDENT> cat = LieAlgebras(R).WithBasis() <NEW_LINE> InfinitelyGeneratedLieAlgebra.__init__(self, R, index_set=ZZ, category=cat) <NEW_LINE> IndexedGenerators.__init__(self, ZZ, prefix='d', bracket='[') <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "The Lie algebra of regular vector fields over {}".format(self.base_ring()) <NEW_LINE> <DEDENT> _repr_term = IndexedGenerators._repr_generator <NEW_LINE> _latex_term = IndexedGenerators._latex_generator <NEW_LINE> @cached_method <NEW_LINE> def lie_algebra_generators(self): <NEW_LINE> <INDENT> return Family(self._indices, self.monomial, name='generator map') <NEW_LINE> <DEDENT> def bracket_on_basis(self, i, j): <NEW_LINE> <INDENT> return self.term(i + j, i - j) <NEW_LINE> <DEDENT> def _an_element_(self): <NEW_LINE> <INDENT> return self.monomial(0) - 3*self.monomial(1) + self.monomial(-1) <NEW_LINE> <DEDENT> def some_elements(self): <NEW_LINE> <INDENT> return [self.monomial(0), self.monomial(2), self.monomial(-2), self.an_element()] <NEW_LINE> <DEDENT> class Element(LieAlgebraElement): <NEW_LINE> <INDENT> pass | The Lie algebra of regular vector fields on `\CC^{\times}`.
This is the Lie algebra with basis `\{d_i\}_{i \in \ZZ}` and subject
to the relations
.. MATH::
[d_i, d_j] = (i - j) d_{i+j}.
This is also known as the Witt (Lie) algebra.
.. NOTE::
This differs from some conventions (e.g., [Ka1990]_), where
we have `d'_i \mapsto -d_i`.
REFERENCES:
- :wikipedia:`Witt_algebra`
.. SEEALSO::
:class:`WittLieAlgebra_charp` | 62598fa2b7558d589546349a |
class FolderPlayList(topic.TopicPlayList): <NEW_LINE> <INDENT> def brains(self): <NEW_LINE> <INDENT> return self.context.getFolderContents() | Playlist view for folder | 62598fa2a8ecb0332587107a |
class Abstract (WebDAVElement): <NEW_LINE> <INDENT> name = "abstract" | Identifies a privilege as abstract. (RFC 3744, section 5.3) | 62598fa299cbb53fe6830d3f |
class DeletePortPair(command.Command): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(DeletePortPair, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'port_pair', metavar="PORT_PAIR", help=_("ID or name of the Port Pair to delete.") ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> client = self.app.client_manager.neutronclient <NEW_LINE> id = common.find_sfc_resource(client, resource, parsed_args.port_pair) <NEW_LINE> common.delete_sfc_resource(client, resource, id) | Delete a given Port Pair. | 62598fa2442bda511e95c2c7 |
class SystemAttackHandler(Handler): <NEW_LINE> <INDENT> def handle_request(self, request): <NEW_LINE> <INDENT> print("Request handled in system attack handler.....!\n") <NEW_LINE> self._successor.handle_request(request) <NEW_LINE> print("Passed the request to next handler....!") | Handle request and forward it to the successor. | 62598fa2435de62698e9bc60 |
class AliasedSubParsersAction(argparse._SubParsersAction): <NEW_LINE> <INDENT> class _AliasedPseudoAction(argparse.Action): <NEW_LINE> <INDENT> def __init__(self, name, aliases, help): <NEW_LINE> <INDENT> dest = name <NEW_LINE> if aliases: <NEW_LINE> <INDENT> dest += ' (%s)' % ','.join(aliases) <NEW_LINE> <DEDENT> super(AliasedSubParsersAction._AliasedPseudoAction, self).__init__(option_strings=[], dest=dest, help=help) <NEW_LINE> <DEDENT> <DEDENT> def add_parser(self, name, **kwargs): <NEW_LINE> <INDENT> if 'aliases' in kwargs: <NEW_LINE> <INDENT> aliases = kwargs['aliases'] <NEW_LINE> del kwargs['aliases'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> aliases = [] <NEW_LINE> <DEDENT> parser = super(AliasedSubParsersAction, self).add_parser(name, **kwargs) <NEW_LINE> for alias in aliases: <NEW_LINE> <INDENT> self._name_parser_map[alias] = parser <NEW_LINE> <DEDENT> if 'help' in kwargs: <NEW_LINE> <INDENT> help = kwargs.pop('help') <NEW_LINE> self._choices_actions.pop() <NEW_LINE> pseudo_action = self._AliasedPseudoAction(name, aliases, help) <NEW_LINE> self._choices_actions.append(pseudo_action) <NEW_LINE> <DEDENT> return parser | Manually add aliases (which aren't supported in Python 2...
From https://gist.github.com/sampsyo/471779 | 62598fa28da39b475be0304c |
class LowercaseUnit(ProcessorUnit): <NEW_LINE> <INDENT> def transform(self, tokens: list) -> list: <NEW_LINE> <INDENT> return [token.lower() for token in tokens] | Process unit for text lower case. | 62598fa2d7e4931a7ef3bf06 |
class TestAuthRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testAuthRequest(self): <NEW_LINE> <INDENT> pass | AuthRequest unit test stubs | 62598fa2cc0a2c111447ae7a |
class BaoTing(BaseType): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BaoTing, self).__init__() <NEW_LINE> <DEDENT> def is_this_type(self, hand_card, card_analyse): <NEW_LINE> <INDENT> used_card_type = [CardType.WAN] <NEW_LINE> return hand_card.is_ting | 8) 报听:在听牌阶段选择报听,并最终胡牌。 。 | 62598fa224f1403a926857e9 |
class Formatter(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._filters = {} <NEW_LINE> for name, func in DEFAULT_FORMATTERS.items(): <NEW_LINE> <INDENT> self.register(name, func) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, value, func, *args): <NEW_LINE> <INDENT> if not callable(func): <NEW_LINE> <INDENT> func = self._filters[func] <NEW_LINE> <DEDENT> return func(value, *args) <NEW_LINE> <DEDENT> def register(self, name=None, func=None): <NEW_LINE> <INDENT> if not func and not name: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if callable(name) and not func: <NEW_LINE> <INDENT> func = name <NEW_LINE> name = func.__name__ <NEW_LINE> <DEDENT> elif func and not name: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> self._filters[name] = func <NEW_LINE> <DEDENT> def unregister(self, name=None, func=None): <NEW_LINE> <INDENT> if not func and not name: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not name: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> if name not in self._filters: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> del self._filters[name] | A formatter is a function (or any callable, really)
that takes a value and returns a nicer-looking value,
most likely a sting.
Formatter stores and calls those functions, keeping
the namespace uncluttered.
Formatting functions should take a value as the first
argument--usually the value of the Datum on which the
function is called--followed by any number of positional
arguments.
In the context of TableFu, those arguments may refer to
other columns in the same row.
>>> formatter = Formatter()
>>> formatter(1200, 'intcomma')
'1,200'
>>> formatter(1200, 'dollars')
'$1,200' | 62598fa2925a0f43d25e7eaa |
class WebcamCollector(memdam.recorder.collector.collector.Collector): <NEW_LINE> <INDENT> def _collect(self, limit): <NEW_LINE> <INDENT> handle, screenshot_file = tempfile.mkstemp('') <NEW_LINE> exe = './bin/wacaw' <NEW_LINE> if not os.path.exists(exe): <NEW_LINE> <INDENT> exe = './wacaw' <NEW_LINE> <DEDENT> command = '%s %s && mv %s.jpeg %s.jpg' % (exe, screenshot_file, screenshot_file, screenshot_file) <NEW_LINE> subprocess.check_call(command, shell=True) <NEW_LINE> screenshot_file += '.jpg' <NEW_LINE> screenshot = self._save_file(screenshot_file, consume_file=True) <NEW_LINE> os.close(handle) <NEW_LINE> return [memdam.common.event.new(u'com.memdam.webcam', data__file=screenshot)] | Collects snapshots from webcam by using external universal (osx) binary wacaw | 62598fa2090684286d593611 |
@add_start_docstrings( BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING, ) <NEW_LINE> class TFBertForSequenceClassification(TFBertPreTrainedModel): <NEW_LINE> <INDENT> def __init__(self, config, *inputs, **kwargs): <NEW_LINE> <INDENT> super(TFBertForSequenceClassification, self).__init__(config, *inputs, **kwargs) <NEW_LINE> self.num_labels = config.num_labels <NEW_LINE> self.bert = TFBertMainLayer(config, name="bert") <NEW_LINE> self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob) <NEW_LINE> self.classifier = tf.keras.layers.Dense( config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier" ) <NEW_LINE> <DEDENT> def call(self, inputs, **kwargs): <NEW_LINE> <INDENT> outputs = self.bert(inputs, **kwargs) <NEW_LINE> pooled_output = outputs[1] <NEW_LINE> pooled_output = self.dropout(pooled_output, training=kwargs.get("training", False)) <NEW_LINE> logits = self.classifier(pooled_output) <NEW_LINE> outputs = (logits,) + outputs[2:] <NEW_LINE> return outputs | Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
**logits**: ``Numpy array`` or ``tf.Tensor`` of shape ``(batch_size, config.num_labels)``
Classification (or regression if config.num_labels==1) scores (before SoftMax).
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
list of ``Numpy array`` or ``tf.Tensor`` (one for the output of each layer + the output of the embeddings)
of shape ``(batch_size, sequence_length, hidden_size)``:
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
list of ``Numpy array`` or ``tf.Tensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Examples::
import tensorflow as tf
from transformers import BertTokenizer, TFBertForSequenceClassification
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = TFBertForSequenceClassification.from_pretrained('bert-base-uncased')
input_ids = tf.constant(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True))[None, :] # Batch size 1
outputs = model(input_ids)
logits = outputs[0] | 62598fa230dc7b766599f6ba |
class JSONSpecValidatorFactory: <NEW_LINE> <INDENT> schema_validator_class = Draft4Validator <NEW_LINE> spec_validator_factory = Draft4ExtendedValidatorFactory <NEW_LINE> def __init__(self, schema, schema_url='', resolver_handlers=None): <NEW_LINE> <INDENT> self.schema = schema <NEW_LINE> self.schema_url = schema_url <NEW_LINE> self.resolver_handlers = resolver_handlers or () <NEW_LINE> self.schema_validator_class.check_schema(self.schema) <NEW_LINE> <DEDENT> @property <NEW_LINE> def schema_resolver(self): <NEW_LINE> <INDENT> return self._get_resolver(self.schema_url, self.schema) <NEW_LINE> <DEDENT> def create(self, spec_resolver): <NEW_LINE> <INDENT> validator_cls = self.spec_validator_factory.from_resolver( spec_resolver) <NEW_LINE> return validator_cls( self.schema, resolver=self.schema_resolver) <NEW_LINE> <DEDENT> def _get_resolver(self, base_uri, referrer): <NEW_LINE> <INDENT> return RefResolver( base_uri, referrer, handlers=self.resolver_handlers) | Json documents validator factory against a json schema.
:param schema: schema for validation.
:param schema_url: schema base uri. | 62598fa2e5267d203ee6b77a |
class Drillstring(pydantic.BaseModel): <NEW_LINE> <INDENT> id: str = pydantic.Field(..., alias="_id") <NEW_LINE> data: DrillstringData <NEW_LINE> @property <NEW_LINE> def mwd_with_gamma_sensor(self) -> Optional[DrillstringDataComponent]: <NEW_LINE> <INDENT> for component in self.data.components: <NEW_LINE> <INDENT> if component.is_mwd_with_gamma_sensor: <NEW_LINE> <INDENT> return component <NEW_LINE> <DEDENT> <DEDENT> return None | Needed subset of drillstring response fields | 62598fa27047854f4633f244 |
class MessengerLabelViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> queryset = models.MessengerLabel.objects.all() <NEW_LINE> serializer_class = serializers.MessengerLabelSerializer | API endpoint that allows to create a new Messenger Label. | 62598fa2d486a94d0ba2be44 |
class TestPO2IniCommand(test_convert.TestConvertCommand, TestPO2Ini): <NEW_LINE> <INDENT> convertmodule = po2ini <NEW_LINE> defaultoptions = {"progress": "none"} <NEW_LINE> def test_help(self): <NEW_LINE> <INDENT> options = test_convert.TestConvertCommand.test_help(self) <NEW_LINE> options = self.help_check(options, "-t TEMPLATE, --template=TEMPLATE") <NEW_LINE> options = self.help_check(options, "--threshold=PERCENT") <NEW_LINE> options = self.help_check(options, "--fuzzy") <NEW_LINE> options = self.help_check(options, "--nofuzzy", last=True) | Tests running actual po2ini commands on files | 62598fa24428ac0f6e658398 |
class UserEvent(WebhookEvent, WithUser): <NEW_LINE> <INDENT> pass | A user event. | 62598fa263d6d428bbee261f |
class Article(ndb.Model): <NEW_LINE> <INDENT> title = ndb.StringProperty() <NEW_LINE> slug = ndb.StringProperty() <NEW_LINE> keywords = ndb.StringProperty(repeated=True) <NEW_LINE> text = ndb.TextProperty() <NEW_LINE> when = ndb.DateTimeProperty(auto_now_add=True) <NEW_LINE> def as_dict(self): <NEW_LINE> <INDENT> return {'title': self.title, 'slug' : self.slug, 'keywords': self.keywords, 'text': self.text, 'when': self.when.isoformat(), 'key': self.key.urlsafe(), 'comments':Comment.from_article(self.key.urlsafe())} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def key_from_slug(cls,slug): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cls.query(cls.slug==slug).fetch(1)[0].key.urlsafe() <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return "" | classdocs | 62598fa25166f23b2e243244 |
class MethodIdItem(Measurable): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> Measurable.__init__(self, parent) <NEW_LINE> self.classIdx = Bytes(self, 2) <NEW_LINE> self.protoIdx = Bytes(self, 2) <NEW_LINE> self.nameIdx = Bytes(self, 4) <NEW_LINE> self._data = [self.classIdx, self.protoIdx, self.nameIdx] | classdocs | 62598fa2dd821e528d6d8da2 |
class ValueType(object): <NEW_LINE> <INDENT> VALUE_TYPE_UNSPECIFIED = 0 <NEW_LINE> BOOL = 1 <NEW_LINE> INT64 = 2 <NEW_LINE> DOUBLE = 3 <NEW_LINE> STRING = 4 <NEW_LINE> DISTRIBUTION = 5 <NEW_LINE> MONEY = 6 | The value type of a metric.
Attributes:
VALUE_TYPE_UNSPECIFIED (int): Do not use this default value.
BOOL (int): The value is a boolean.
This value type can be used only if the metric kind is ``GAUGE``.
INT64 (int): The value is a signed 64-bit integer.
DOUBLE (int): The value is a double precision floating point number.
STRING (int): The value is a text string.
This value type can be used only if the metric kind is ``GAUGE``.
DISTRIBUTION (int): The value is a ````Distribution````.
MONEY (int): The value is money. | 62598fa299fddb7c1ca62d1e |
class NodeMetadata: <NEW_LINE> <INDENT> def __init__(self, updated_at: int = 1000): <NEW_LINE> <INDENT> self.updated = updated_at <NEW_LINE> <DEDENT> def get_content_from_node(self): <NEW_LINE> <INDENT> return {'getNode': {'updated_at': self.updated}, 'random': {'random': 2}} | Classe utilizzata per simulare le chiamate richiedenti info sui metadati dei file | 62598fa23539df3088ecc121 |
class Example: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.klass = '' <NEW_LINE> self.words = [] | Represents a document with a label. klass is 'pos' or 'neg' by convention.
words is a list of strings. | 62598fa2009cb60464d01392 |
class ListViewTestSuite: <NEW_LINE> <INDENT> root_url = None <NEW_LINE> def test_list_view(self): <NEW_LINE> <INDENT> response = self.client.get(f"/{self.root_url}/") <NEW_LINE> self.assertEqual(200, response.status_code) | Tests for ListView. | 62598fa26fb2d068a7693d6b |
@unique <NEW_LINE> class ScriptType(Enum): <NEW_LINE> <INDENT> shell = 0 <NEW_LINE> python = 1 | Defines script types such as shell or python script | 62598fa291f36d47f2230dd8 |
class YouTube: <NEW_LINE> <INDENT> y_id: Optional[str] <NEW_LINE> format: Optional[str] <NEW_LINE> video: dict <NEW_LINE> def __init__(self, y_id, video_format=None): <NEW_LINE> <INDENT> self.y_id = y_id <NEW_LINE> self.format = video_format <NEW_LINE> self.video = models.DB().jget(self.y_id, 'info', {}) <NEW_LINE> <DEDENT> async def check_file(self) -> Optional[str]: <NEW_LINE> <INDENT> filename_ext = None <NEW_LINE> filename = models.YouTube.filename.format(y_id=self.y_id, format=self.format) <NEW_LINE> for ext in ['mkv', 'mp4']: <NEW_LINE> <INDENT> if os.path.isfile(os.path.join(settings.DOWNLOAD_PATH, f'{filename}.{ext}')): <NEW_LINE> <INDENT> filename_ext = f'{filename}.{ext}' <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return filename_ext <NEW_LINE> <DEDENT> async def check_status(self) -> Tuple[Optional[str], Optional[str]]: <NEW_LINE> <INDENT> url: Optional[str] <NEW_LINE> filename = await self.check_file() <NEW_LINE> if filename: <NEW_LINE> <INDENT> url = f'{settings.DOWNLOAD_URL}{filename}' <NEW_LINE> status = '100' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if models.DB().sget(self.y_id, self.format, 'error'): <NEW_LINE> <INDENT> raise YouTubeDownloadError('Ошибка при скачивании видео') <NEW_LINE> <DEDENT> url = None <NEW_LINE> status = models.DB().sget(self.y_id, self.format, 'status') <NEW_LINE> <DEDENT> return status, url <NEW_LINE> <DEDENT> async def get_info(self) -> dict: <NEW_LINE> <INDENT> if not self.video: <NEW_LINE> <INDENT> self.video = await models.YouTube().extract_info(self.y_id) <NEW_LINE> <DEDENT> return self.video <NEW_LINE> <DEDENT> def filter_formats(self) -> dict: <NEW_LINE> <INDENT> if not self.video: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def criteria(format_): <NEW_LINE> <INDENT> return ( (format_.get('asr') and format_['fps']) or ((format_.get('height') or 0) > 720) ) and ( format_.get('container') != 'webm_dash' ) <NEW_LINE> <DEDENT> formats = {f['format_id']: [f['format_note']] for f in self.video['formats'] if criteria(f)} <NEW_LINE> return formats | Дополнительные методы для работы с YouTube | 62598fa22ae34c7f260aaf4e |
class SpoolMotor(Motor): <NEW_LINE> <INDENT> def __init__(self, motor_hat, name="spool_motor", index=3): <NEW_LINE> <INDENT> super().__init__(motor_hat, name=name, style="spool", index=index) | Creates a SpoolMotor object for use with the MotorHAT | 62598fa221bff66bcd722ad2 |
class SandboxFolder(Folder): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> sandbox = get_repository_folder('sandbox') <NEW_LINE> if not os.path.exists(sandbox): <NEW_LINE> <INDENT> os.makedirs(sandbox) <NEW_LINE> <DEDENT> abspath = tempfile.mkdtemp(dir=sandbox) <NEW_LINE> super(SandboxFolder, self).__init__(abspath=abspath) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.erase() | A class to manage the creation and management of a sandbox folder.
Note: this class must be used within a context manager, i.e.:
with SandboxFolder as f:
## do something with f
In this way, the sandbox folder is removed from disk
(if it wasn't removed already) when exiting the 'with' block.
.. todo:: Implement check of whether the folder has been removed. | 62598fa244b2445a339b68a4 |
class CapacityFilter(filters.BaseHostFilter): <NEW_LINE> <INDENT> def host_passes(self, host_state, filter_properties): <NEW_LINE> <INDENT> if host_state.host == filter_properties.get('vol_exists_on'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> volume_size = filter_properties.get('size') <NEW_LINE> if host_state.free_capacity_gb is None: <NEW_LINE> <INDENT> LOG.error(_("Free capacity not set: " "volume node info collection broken.")) <NEW_LINE> return False <NEW_LINE> <DEDENT> free_space = host_state.free_capacity_gb <NEW_LINE> if free_space == 'infinite' or free_space == 'unknown': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> reserved = float(host_state.reserved_percentage) / 100 <NEW_LINE> free = math.floor(free_space * (1 - reserved)) <NEW_LINE> msg_args = {"host": host_state.host, "requested": volume_size, "available": free} <NEW_LINE> if free < volume_size: <NEW_LINE> <INDENT> LOG.warning(_("Insufficient free space for volume creation " "on host %(host)s (requested / avail): " "%(requested)s/%(available)s") % msg_args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.debug("Sufficient free space for volume creation " "on host %(host)s (requested / avail): " "%(requested)s/%(available)s" % msg_args) <NEW_LINE> <DEDENT> return free >= volume_size | CapacityFilter filters based on volume host's capacity utilization. | 62598fa299cbb53fe6830d41 |
class KeyHandler(object): <NEW_LINE> <INDENT> def __init__(self, filename=None, resaveOnDeletion=True): <NEW_LINE> <INDENT> if not resaveOnDeletion: <NEW_LINE> <INDENT> warnings.warn("The resaveOnDeletion argument to KeyHandler will" " default to True in future versions.") <NEW_LINE> <DEDENT> self._keys = {} <NEW_LINE> self.resaveOnDeletion = False <NEW_LINE> self.filename = filename <NEW_LINE> if filename is not None: <NEW_LINE> <INDENT> self.resaveOnDeletion = resaveOnDeletion <NEW_LINE> f = open(filename, "rt") <NEW_LINE> while True: <NEW_LINE> <INDENT> key = f.readline().strip() <NEW_LINE> if not key: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> secret = f.readline().strip() <NEW_LINE> nonce = int(f.readline().strip()) <NEW_LINE> self.addKey(key, secret, nonce) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.resaveOnDeletion: <NEW_LINE> <INDENT> self.save(self.filename) <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> @property <NEW_LINE> def keys(self): <NEW_LINE> <INDENT> return self._keys.keys() <NEW_LINE> <DEDENT> def getKeys(self): <NEW_LINE> <INDENT> return self._keys.keys() <NEW_LINE> <DEDENT> def save(self, filename): <NEW_LINE> <INDENT> f = open(filename, "wt") <NEW_LINE> for k, data in self._keys.items(): <NEW_LINE> <INDENT> f.write("%s\n%s\n%d\n" % (k, data.secret, data.nonce)) <NEW_LINE> <DEDENT> <DEDENT> def addKey(self, key, secret, next_nonce): <NEW_LINE> <INDENT> self._keys[key] = KeyData(secret, next_nonce) <NEW_LINE> <DEDENT> def getNextNonce(self, key): <NEW_LINE> <INDENT> data = self._keys.get(key) <NEW_LINE> if data is None: <NEW_LINE> <INDENT> raise KeyError("Key not found: %r" % key) <NEW_LINE> <DEDENT> nonce = data.nonce <NEW_LINE> data.nonce += 1 <NEW_LINE> return nonce <NEW_LINE> <DEDENT> def getSecret(self, key): <NEW_LINE> <INDENT> data = self._keys.get(key) <NEW_LINE> if data is None: <NEW_LINE> <INDENT> raise KeyError("Key not found: %r" % key) <NEW_LINE> <DEDENT> return data.secret <NEW_LINE> <DEDENT> def setNextNonce(self, key, next_nonce): <NEW_LINE> <INDENT> data = self._keys.get(key) <NEW_LINE> if data is None: <NEW_LINE> <INDENT> raise KeyError("Key not found: %r" % key) <NEW_LINE> <DEDENT> data.nonce = next_nonce | KeyHandler handles the tedious task of managing nonces associated
with a BTC-e API key/secret pair.
The getNextNonce method is threadsafe, all others are not. | 62598fa23c8af77a43b67e77 |
class SvgTest(unittest.TestCase): <NEW_LINE> <INDENT> maxDiff = None <NEW_LINE> def result_file_name(self, slug, ext): <NEW_LINE> <INDENT> test_name = self._testMethodName <NEW_LINE> assert test_name.startswith("test_") <NEW_LINE> file_name = "{}_{}{}".format(test_name[5:], slug, ext) <NEW_LINE> return os.path.join(HERE, "results", file_name) <NEW_LINE> <DEDENT> def assert_good_svg(self, svg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.result_file_name("ok", ".out")) as f: <NEW_LINE> <INDENT> svg_good = canonicalize_svg(f.read()) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> svg_good = "<svg></svg>" <NEW_LINE> <DEDENT> svg = canonicalize_svg(svg) <NEW_LINE> if svg != svg_good: <NEW_LINE> <INDENT> with open(self.result_file_name("xx", ".out"), "w") as out: <NEW_LINE> <INDENT> out.write(svg) <NEW_LINE> <DEDENT> for kind, content in zip(["ok", "xx"], [svg_good, svg]): <NEW_LINE> <INDENT> with open(self.result_file_name(kind, ".html"), "w") as out: <NEW_LINE> <INDENT> out.write("<!DOCTYPE html>\n<html><head><style>\n") <NEW_LINE> out.write(PyFig.CSS) <NEW_LINE> out.write("</style></head><body><div>") <NEW_LINE> out.write(content) <NEW_LINE> out.write("</div></body></html>\n") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for file_parts in [("xx", ".out"), ("xx", ".html"), ("ok", ".html")]: <NEW_LINE> <INDENT> fname = self.result_file_name(*file_parts) <NEW_LINE> if os.path.exists(fname): <NEW_LINE> <INDENT> os.remove(fname) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.assertMultiLineEqual(svg, svg_good) | Base class for tests of SVG output. | 62598fa27cff6e4e811b5894 |
class NovacView(BrowserView): <NEW_LINE> <INDENT> implements(INovacView) <NEW_LINE> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> self.logger = logging.getLogger('cirb.novac.browser.novacview') <NEW_LINE> novac_url = os.environ.get("novac_url", None) <NEW_LINE> if novac_url: <NEW_LINE> <INDENT> self.novac_url = novac_url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> registry = getUtility(IRegistry) <NEW_LINE> self.novac_url = registry['cirb.novac.novac_url'] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def portal_catalog(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_catalog') <NEW_LINE> <DEDENT> @property <NEW_LINE> def portal(self): <NEW_LINE> <INDENT> return getToolByName(self.context, 'portal_url').getPortalObject() <NEW_LINE> <DEDENT> def view_name(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def second_level(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def utils_url(self): <NEW_LINE> <INDENT> error = False <NEW_LINE> msg_error = "" <NEW_LINE> if not self.novac_url: <NEW_LINE> <INDENT> error=True <NEW_LINE> msg_error=_(u'No url for cirb.novac.novac_url') <NEW_LINE> <DEDENT> return {'novac_url':self.novac_url, 'error':error, 'msg_error':msg_error} <NEW_LINE> <DEDENT> def novac(self): <NEW_LINE> <INDENT> error=False <NEW_LINE> msg_error='' <NEW_LINE> return {'private_url':LISTPRIVATE} | Cas browser view | 62598fa2adb09d7d5dc0a3f8 |
class number_of_potential_SSS_job_movers(Variable): <NEW_LINE> <INDENT> _return_type="int32" <NEW_LINE> def __init__(self, type): <NEW_LINE> <INDENT> self.is_type = "is_building_type_%s" % type <NEW_LINE> Variable.__init__(self) <NEW_LINE> <DEDENT> def dependencies(self): <NEW_LINE> <INDENT> return [attribute_label('job', "zone_id"), attribute_label('job', "potential_movers"), attribute_label('job', self.is_type)] <NEW_LINE> <DEDENT> def compute(self, dataset_pool): <NEW_LINE> <INDENT> job = dataset_pool.get_dataset('job') <NEW_LINE> is_mover = logical_and(job.get_attribute(self.is_type), job.get_attribute("potential_movers")) <NEW_LINE> return self.get_dataset().sum_over_ids(job.get_attribute(self.get_dataset().get_id_name()[0]), is_mover) <NEW_LINE> <DEDENT> def post_check(self, values, dataset_pool): <NEW_LINE> <INDENT> size = dataset_pool.get_dataset('job').size() <NEW_LINE> self.do_check("x >= 0 and x <= " + str(size), values) | Number of jobs of given type that should potentially move. Expects attribute 'potential_movers'
of job set that has 1's for jobs that should move, otherwise 0's. | 62598fa2435de62698e9bc62 |
class UserDB(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> username = db.Column(db.String(15), primary_key=True, nullable=False) <NEW_LINE> contact_id = db.Column(db.Integer, db.ForeignKey('contacts.id'), nullable=False) <NEW_LINE> password_hash = db.Column(db.String(128), nullable=False) <NEW_LINE> def hash_password(self, password): <NEW_LINE> <INDENT> self.password_hash = pwd_context.encrypt(password) <NEW_LINE> <DEDENT> def verify_password(self, password): <NEW_LINE> <INDENT> return pwd_context.verify(password, self.password_hash) <NEW_LINE> <DEDENT> def generate_auth_token(self, expiration=600): <NEW_LINE> <INDENT> s = Serializer(app.config['SECRET_KEY'], expires_in=expiration) <NEW_LINE> return s.dumps({'username': self.username}) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def verify_auth_token(token): <NEW_LINE> <INDENT> s = Serializer(app.config['SECRET_KEY']) <NEW_LINE> try: <NEW_LINE> <INDENT> data = s.loads(token) <NEW_LINE> <DEDENT> except SignatureExpired: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> except BadSignature: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> user = UserDB.query.get(data['username']) | User object stores all necessary information for a site user.
| 62598fa28da39b475be0304e |
class AddParameters(Brick): <NEW_LINE> <INDENT> @lazy <NEW_LINE> def __init__(self, transition, num_params, params_name, weights_init, biases_init, **kwargs): <NEW_LINE> <INDENT> super(AddParameters, self).__init__(**kwargs) <NEW_LINE> update_instance(self, locals()) <NEW_LINE> self.input_names = [name for name in transition.apply.sequences if name != 'mask'] <NEW_LINE> self.state_name = transition.apply.states[0] <NEW_LINE> assert len(transition.apply.states) == 1 <NEW_LINE> self.fork = Fork(self.input_names) <NEW_LINE> self.init = MLP([Identity()], name="init") <NEW_LINE> self.children = [self.transition, self.fork, self.init] <NEW_LINE> <DEDENT> def _push_allocation_config(self): <NEW_LINE> <INDENT> self.fork.input_dim = self.num_params <NEW_LINE> self.fork.fork_dims = {name: self.transition.get_dim(name) for name in self.input_names} <NEW_LINE> self.init.dims[0] = self.num_params <NEW_LINE> self.init.dims[-1] = self.transition.get_dim(self.state_name) <NEW_LINE> <DEDENT> def _push_initialization_config(self): <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> if self.weights_init: <NEW_LINE> <INDENT> child.weights_init = self.weights_init <NEW_LINE> <DEDENT> if self.biases_init: <NEW_LINE> <INDENT> child.biases_init = self.biases_init <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @application <NEW_LINE> def apply(self, **kwargs): <NEW_LINE> <INDENT> inputs = {name: kwargs.pop(name) for name in self.input_names} <NEW_LINE> params = kwargs.pop("params") <NEW_LINE> forks = self.fork.apply(params, return_dict=True) <NEW_LINE> for name in self.input_names: <NEW_LINE> <INDENT> inputs[name] = inputs[name] + forks[name] <NEW_LINE> <DEDENT> kwargs.update(inputs) <NEW_LINE> if kwargs.get('iterate', True): <NEW_LINE> <INDENT> kwargs[self.state_name] = self.initial_state(None, params=params) <NEW_LINE> <DEDENT> return self.transition.apply(**kwargs) <NEW_LINE> <DEDENT> @apply.delegate <NEW_LINE> def apply_delegate(self): <NEW_LINE> <INDENT> return self.transition.apply <NEW_LINE> <DEDENT> @apply.property('contexts') <NEW_LINE> def apply_contexts(self): <NEW_LINE> <INDENT> return [self.params_name] + self.transition.apply.contexts <NEW_LINE> <DEDENT> @application <NEW_LINE> def initial_state(self, batch_size, *args, **kwargs): <NEW_LINE> <INDENT> return self.init.apply(kwargs['params']) <NEW_LINE> <DEDENT> def get_dim(self, name): <NEW_LINE> <INDENT> if name == 'params': <NEW_LINE> <INDENT> return self.num_params <NEW_LINE> <DEDENT> return self.transition.get_dim(name) | Adds dependency on parameters to a transition function.
In fact an improved version of this brick should be moved
to the main body of the library, because it is clearly reusable
(e.g. it can be a part of Encoder-Decoder translation model. | 62598fa2d7e4931a7ef3bf08 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.