code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class PoMessage: <NEW_LINE> <INDENT> def __init__(self, id, msg, default, fuzzy=False, comments=[], niceDefault=False): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.msg = msg <NEW_LINE> self.default = default <NEW_LINE> if niceDefault: self.produceNiceDefault() <NEW_LINE> self.fuzzy = fuzzy <NEW_LINE> self.comments = comments <NEW_LINE> <DEDENT> def update(self, newMsg, isPot, language): <NEW_LINE> <INDENT> if isPot: <NEW_LINE> <INDENT> self.msg = "" <NEW_LINE> if not self.default: <NEW_LINE> <INDENT> self.default = newMsg.default <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> oldDefault = self.default <NEW_LINE> if self.default != newMsg.default: <NEW_LINE> <INDENT> oldDefault = self.default <NEW_LINE> self.default = newMsg.default <NEW_LINE> if self.msg.strip(): <NEW_LINE> <INDENT> self.fuzzy = True <NEW_LINE> if not oldDefault.strip(): <NEW_LINE> <INDENT> self.fuzzy = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.fuzzy = False <NEW_LINE> <DEDENT> <DEDENT> if (language == 'en'): <NEW_LINE> <INDENT> if not self.msg: <NEW_LINE> <INDENT> self.msg = self.default <NEW_LINE> <DEDENT> if self.fuzzy and (self.msg == oldDefault): <NEW_LINE> <INDENT> self.fuzzy = False <NEW_LINE> self.msg = self.default <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def produceNiceDefault(self): <NEW_LINE> <INDENT> self.default = produceNiceMessage(self.default) <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> res = '' <NEW_LINE> for comment in self.comments: <NEW_LINE> <INDENT> res += comment + '\n' <NEW_LINE> <DEDENT> if self.default != None: <NEW_LINE> <INDENT> res = '#. Default: "%s"\n' % self.default <NEW_LINE> <DEDENT> if self.fuzzy: <NEW_LINE> <INDENT> res += '#, fuzzy\n' <NEW_LINE> <DEDENT> res += 'msgid "%s"\n' % self.id <NEW_LINE> res += 'msgstr "%s"\n' % self.msg <NEW_LINE> return res <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<i18n msg id="%s", msg="%s", default="%s">' % (self.id, self.msg, self.default) <NEW_LINE> <DEDENT> def getMessage(self): <NEW_LINE> <INDENT> return self.msg.replace('<br/>', '\n').replace('\\"', '"') | Represents a i18n message (po format). | 6259903830c21e258be999a9 |
class ModularParameterization: <NEW_LINE> <INDENT> def __init__(self, E): <NEW_LINE> <INDENT> self._E = E <NEW_LINE> <DEDENT> def curve(self): <NEW_LINE> <INDENT> return self._E <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Modular parameterization from the upper half plane to %s" % self._E <NEW_LINE> <DEDENT> def __cmp__(self,other): <NEW_LINE> <INDENT> c = cmp(type(self), type(other)) <NEW_LINE> if c: <NEW_LINE> <INDENT> return c <NEW_LINE> <DEDENT> return cmp(self._E, other._E) <NEW_LINE> <DEDENT> def __call__(self, z, prec=None): <NEW_LINE> <INDENT> if isinstance(z, heegner.HeegnerPointOnX0N): <NEW_LINE> <INDENT> return z.map_to_curve(self.curve()) <NEW_LINE> <DEDENT> tm = misc.verbose("Evaluating modular parameterization to precision %s bits"%prec) <NEW_LINE> w = self.map_to_complex_numbers(z, prec=prec) <NEW_LINE> z = self._E.elliptic_exponential(w) <NEW_LINE> misc.verbose("Finished evaluating modular parameterization", tm) <NEW_LINE> return z <NEW_LINE> <DEDENT> def map_to_complex_numbers(self, z, prec=None): <NEW_LINE> <INDENT> if prec is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> prec = z.parent().prec() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> prec = 53 <NEW_LINE> <DEDENT> <DEDENT> CC = ComplexField(prec) <NEW_LINE> if z in QQ: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> z = CC(z) <NEW_LINE> if z.imag() <= 0: <NEW_LINE> <INDENT> raise ValueError("Point must be in the upper half plane") <NEW_LINE> <DEDENT> q = (2*CC.gen()*CC.pi()*z).exp() <NEW_LINE> nterms = (-(prec+10)/q.abs().log2()).ceil() <NEW_LINE> enumerated_an = list(enumerate(self._E.anlist(nterms)))[1:] <NEW_LINE> lattice_point = 0 <NEW_LINE> for n, an in reversed(enumerated_an): <NEW_LINE> <INDENT> lattice_point += an/n <NEW_LINE> lattice_point *= q <NEW_LINE> <DEDENT> return lattice_point <NEW_LINE> <DEDENT> def power_series(self, prec=20): <NEW_LINE> <INDENT> R = LaurentSeriesRing(RationalField(),'q') <NEW_LINE> if not self._E.is_minimal(): <NEW_LINE> <INDENT> raise NotImplementedError("only implemented for minimal curves") <NEW_LINE> <DEDENT> XY = self._E.pari_mincurve().elltaniyama(prec-1) <NEW_LINE> return R(XY[0]),R(XY[1]) | This class represents the modular parametrization of an elliptic curve
.. math::
\phi_E: X_0(N) \rightarrow E.
Evaluation is done by passing through the lattice representation of `E`.
EXAMPLES::
sage: phi = EllipticCurve('11a1').modular_parametrization()
sage: phi
Modular parameterization from the upper half plane to Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field | 6259903876d4e153a661db40 |
class AnswerForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.Answer <NEW_LINE> fields = [ 'order', 'text', 'correct' ] | The form for a question | 6259903821bff66bcd723e04 |
class AccountCSV(ExportCSV): <NEW_LINE> <INDENT> filename = 'rich_account_list.csv' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return Account.objects.filter(balance__gt=600000) <NEW_LINE> <DEDENT> def get_field_names(self): <NEW_LINE> <INDENT> return ['account_no', 'owner'] | View for creating and rendering CSV of Account instances returned by
custom queryset. | 625990386e29344779b017ed |
class Results(QWidget): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Results, self).__init__(*args, **kwargs) <NEW_LINE> self.setProperty("id", "results") <NEW_LINE> self.vbox = QVBoxLayout(self) <NEW_LINE> self.vbox.setAlignment(Qt.AlignCenter) <NEW_LINE> self.vbox.setSpacing(4) <NEW_LINE> self.message = QLabel() <NEW_LINE> self.message.setProperty("id", "result") <NEW_LINE> self.vbox.setAlignment(self.message, Qt.AlignCenter) <NEW_LINE> self.vbox.addWidget(self.message) <NEW_LINE> self.old_high_score = QLabel() <NEW_LINE> self.old_high_score.setProperty("type", "results-label") <NEW_LINE> self.vbox.addWidget(self.old_high_score) <NEW_LINE> self.vbox.setAlignment(self.old_high_score, Qt.AlignCenter) <NEW_LINE> self.score_entered = QLabel() <NEW_LINE> self.score_entered.setProperty("type", "results-label") <NEW_LINE> self.vbox.addWidget(self.score_entered) <NEW_LINE> self.vbox.setAlignment(self.score_entered, Qt.AlignCenter) <NEW_LINE> self.ok = QPushButton("OK") <NEW_LINE> self.vbox.addWidget(self.ok) <NEW_LINE> <DEDENT> def generate_results(self, passed, old, new): <NEW_LINE> <INDENT> if passed: <NEW_LINE> <INDENT> self.message.setText("New high score!") <NEW_LINE> self.old_high_score.setText(f"Old High Score:{old:>8}") <NEW_LINE> self.score_entered.setText(f"New High Score:{new:>8}") <NEW_LINE> self.message.setStyleSheet("color: green") <NEW_LINE> self.old_high_score.setStyleSheet("color: red") <NEW_LINE> self.score_entered.setStyleSheet("color: green") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.message.setText("You did not beat your score...") <NEW_LINE> self.old_high_score.setText(f"Old High Score:{old:>8}") <NEW_LINE> self.score_entered.setText(f"Your attempt:{new:>10}") <NEW_LINE> self.message.setStyleSheet("color: red") <NEW_LINE> self.old_high_score.setStyleSheet("color: white") <NEW_LINE> self.score_entered.setStyleSheet("color: red") | Shows the results for the session that just finished
Tells whether the score entered is greater than the previous score | 6259903807d97122c4217e39 |
class FSMonitorPolling(FSMonitor): <NEW_LINE> <INDENT> interval = 10 <NEW_LINE> def __init__(self, callback, persistent=True, trigger_events_for_initial_scan=False, ignored_dirs=[], dbfile="fsmonitor.db", parent_logger=None): <NEW_LINE> <INDENT> FSMonitor.__init__(self, callback, True, trigger_events_for_initial_scan, ignored_dirs, dbfile, parent_logger) <NEW_LINE> self.logger.info("FSMonitor class used: FSMonitorPolling.") <NEW_LINE> <DEDENT> def __add_dir(self, path, event_mask): <NEW_LINE> <INDENT> self.monitored_paths[path] = MonitoredPath(path, event_mask, None) <NEW_LINE> self.monitored_paths[path].monitoring = True <NEW_LINE> if self.persistent: <NEW_LINE> <INDENT> FSMonitor.generate_missed_events(self, path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pathscanner.initial_scan(path) <NEW_LINE> <DEDENT> return self.monitored_paths[path] <NEW_LINE> <DEDENT> def __remove_dir(self, path): <NEW_LINE> <INDENT> if path in self.monitored_paths.keys(): <NEW_LINE> <INDENT> del self.monitored_paths[path] <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> FSMonitor.setup(self) <NEW_LINE> self.lock.release() <NEW_LINE> while not self.die: <NEW_LINE> <INDENT> self.__process_queues() <NEW_LINE> time.sleep(self.__class__.interval) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> self.die = True <NEW_LINE> self.lock.release() <NEW_LINE> for path in self.monitored_paths.keys(): <NEW_LINE> <INDENT> self.__remove_dir(path) <NEW_LINE> <DEDENT> <DEDENT> def __process_queues(self): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> if self.die: <NEW_LINE> <INDENT> self.notifier.stop() <NEW_LINE> <DEDENT> self.lock.release() <NEW_LINE> self.lock.acquire() <NEW_LINE> if not self.add_queue.empty(): <NEW_LINE> <INDENT> (path, event_mask) = self.add_queue.get() <NEW_LINE> self.lock.release() <NEW_LINE> self.__add_dir(path, event_mask) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lock.release() <NEW_LINE> <DEDENT> self.lock.acquire() <NEW_LINE> if not self.remove_queue.empty(): <NEW_LINE> <INDENT> path = self.add_queue.get() <NEW_LINE> self.lock.release() <NEW_LINE> self.__remove_dir(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lock.release() <NEW_LINE> <DEDENT> discovered_through = "polling" <NEW_LINE> for monitored_path in self.monitored_paths.keys(): <NEW_LINE> <INDENT> for event_path, result in self.pathscanner.scan_tree(monitored_path): <NEW_LINE> <INDENT> FSMonitor.trigger_events_for_pathscanner_result(self, monitored_path, event_path, result, discovered_through) | polling support for FSMonitor | 6259903871ff763f4b5e8936 |
class PutAppend(BinaryOperator): <NEW_LINE> <INDENT> operator = '>>>' <NEW_LINE> precedence = 30 <NEW_LINE> attributes = ('Protected') <NEW_LINE> def apply(self, exprs, filename, evaluation): <NEW_LINE> <INDENT> instream = Expression('OpenAppend', filename).evaluate(evaluation) <NEW_LINE> if len(instream.leaves) == 2: <NEW_LINE> <INDENT> name, n = instream.leaves <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> result = self.apply_input(exprs, name, n, evaluation) <NEW_LINE> Expression('Close', instream).evaluate(evaluation) <NEW_LINE> return result <NEW_LINE> <DEDENT> def apply_input(self, exprs, name, n, evaluation): <NEW_LINE> <INDENT> stream = _lookup_stream(n.get_int_value()) <NEW_LINE> if stream is None or stream.closed: <NEW_LINE> <INDENT> evaluation.message('Put', 'openx', Expression( 'OutputSteam', name, n)) <NEW_LINE> return <NEW_LINE> <DEDENT> text = [six.text_type(e.do_format(evaluation, 'System`OutputForm').__str__()) for e in exprs.get_sequence()] <NEW_LINE> text = '\n'.join(text) + '\n' <NEW_LINE> text.encode('ascii') <NEW_LINE> stream.write(text) <NEW_LINE> return Symbol('Null') <NEW_LINE> <DEDENT> def apply_default(self, exprs, filename, evaluation): <NEW_LINE> <INDENT> expr = Expression('PutAppend', exprs, filename) <NEW_LINE> evaluation.message('General', 'stream', filename) <NEW_LINE> return expr | <dl>
<dt>'$expr$ >>> $filename$'
<dd>append $expr$ to a file.
<dt>'PutAppend[$expr1$, $expr2$, ..., $"filename"$]'
<dd>write a sequence of expressions to a file.
</dl>
>> Put[50!, "factorials"]
>> FilePrint["factorials"]
| 30414093201713378043612608166064768844377641568960512000000000000
>> PutAppend[10!, 20!, 30!, "factorials"]
>> FilePrint["factorials"]
| 30414093201713378043612608166064768844377641568960512000000000000
| 3628800
| 2432902008176640000
| 265252859812191058636308480000000
>> 60! >>> "factorials"
>> FilePrint["factorials"]
| 30414093201713378043612608166064768844377641568960512000000000000
| 3628800
| 2432902008176640000
| 265252859812191058636308480000000
| 8320987112741390144276341183223364380754172606361245952449277696409600000000000000
>> "string" >>> factorials
>> FilePrint["factorials"]
| 30414093201713378043612608166064768844377641568960512000000000000
| 3628800
| 2432902008176640000
| 265252859812191058636308480000000
| 8320987112741390144276341183223364380754172606361245952449277696409600000000000000
| "string"
#> DeleteFile["factorials"];
## writing to dir
#> x >>> /var/
: Cannot open /var/.
= x >>> /var/
## writing to read only file
#> x >>> /proc/uptime
: Cannot open /proc/uptime.
= x >>> /proc/uptime | 625990385e10d32532ce41d1 |
class LogFoodResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) | A ResultSet with methods tailored to the values returned by the LogFood Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 6259903810dbd63aa1c71d71 |
class Solution: <NEW_LINE> <INDENT> def findAnagrams(self, s, p): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> len_p = len(p) <NEW_LINE> if len(s) < len_p: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> di_p = build_di(p, 0, len_p) <NEW_LINE> di_s = build_di(s, 0, len_p) <NEW_LINE> if di_s == di_p: <NEW_LINE> <INDENT> ret.append(0) <NEW_LINE> <DEDENT> for i in range(1, len(s) - len_p + 1): <NEW_LINE> <INDENT> update_di(di_s, s[i - 1], 'remove') <NEW_LINE> update_di(di_s, s[i + len_p - 1], 'add') <NEW_LINE> if s[i] in di_p: <NEW_LINE> <INDENT> if di_p == di_s: <NEW_LINE> <INDENT> ret.append(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return ret | @param s: a string
@param p: a string
@return: a list of index | 62599038a4f1c619b294f755 |
class Permission(object): <NEW_LINE> <INDENT> READ = "read" <NEW_LINE> CREATE = "create" <NEW_LINE> UPDATE = "update" <NEW_LINE> DELETE = "delete" <NEW_LINE> @classmethod <NEW_LINE> def all_permissions(cls): <NEW_LINE> <INDENT> return [val for perm, val in inspect.getmembers(cls, lambda memb: not inspect.isroutine(memb)) if not perm.startswith('_')] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def valid_permission(cls, perm_name): <NEW_LINE> <INDENT> return perm_name in cls.all_permissions() | Scope permissions types | 6259903830dc7b76659a09cf |
class HttpdAirOs(AirOs): <NEW_LINE> <INDENT> converters = [ Httpd, ] | Mock backend with converter for web server | 625990388c3a8732951f76f3 |
@view_defaults(context=Engagement, permission='view') <NEW_LINE> class EngagementViews(BaseView): <NEW_LINE> <INDENT> @view_config(name='view', permission='view', renderer='episkopos:templates/engagement.pt') <NEW_LINE> def default_view(self): <NEW_LINE> <INDENT> return { 'foo': _(u'bar'), } | Views for :class:`episkopos.resources.Engagement` | 62599038c432627299fa4195 |
@implementer(IPended) <NEW_LINE> class Pended(Model): <NEW_LINE> <INDENT> __tablename__ = 'pended' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> token = Column(Unicode) <NEW_LINE> expiration_date = Column(DateTime) <NEW_LINE> key_values = relationship('PendedKeyValue') <NEW_LINE> def __init__(self, token, expiration_date): <NEW_LINE> <INDENT> super(Pended, self).__init__() <NEW_LINE> self.token = token <NEW_LINE> self.expiration_date = expiration_date | A pended event, tied to a token. | 6259903873bcbd0ca4bcb426 |
class Config(ElementBase): <NEW_LINE> <INDENT> name = "config" <NEW_LINE> namespace = "weld:config" <NEW_LINE> interfaces = set(('jid', 'password', 'server', 'port', 'clients')) <NEW_LINE> sub_interfaces = interfaces <NEW_LINE> subitem = (ConfigClient,) <NEW_LINE> def get_clients(self): <NEW_LINE> <INDENT> clients = [] <NEW_LINE> clientsXML = self.xml.findall('{%s}client' % self.namespace) <NEW_LINE> for clientXML in clientsXML: <NEW_LINE> <INDENT> client = ConfigClient(xml=clientXML, parent=None) <NEW_LINE> clients.append(client) <NEW_LINE> <DEDENT> return clients | Connection information for the gateway, and config data
for all monitored email addresses.
Example stanza:
<config>
<jid>email.localhost</jid>
<server>localhost</server>
<port>8888</port>
<client>....</client>
<client>....</client>
</config>
Stanza Interface:
jid -- Component JID for the gateway.
password -- Component secret.
server -- Server hosting the gateway component.
port -- Port to connect to the server.
clients -- List of client configuration stanzas. | 62599038b5575c28eb713598 |
class TestReceiver(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def echo(context, value): <NEW_LINE> <INDENT> LOG.debug(_("Received %s"), value) <NEW_LINE> return value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def context(context, value): <NEW_LINE> <INDENT> LOG.debug(_("Received %s"), context) <NEW_LINE> return context.to_dict() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def multicall_three_nones(context, value): <NEW_LINE> <INDENT> yield None <NEW_LINE> yield None <NEW_LINE> yield None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def echo_three_times_yield(context, value): <NEW_LINE> <INDENT> yield value <NEW_LINE> yield value + 1 <NEW_LINE> yield value + 2 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def fail(context, value): <NEW_LINE> <INDENT> raise Exception(value) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def block(context, value): <NEW_LINE> <INDENT> time.sleep(2) | Simple Proxy class so the consumer has methods to call.
Uses static methods because we aren't actually storing any state. | 6259903807d97122c4217e3a |
class AnyFoodSearchProblem(PositionSearchProblem): <NEW_LINE> <INDENT> def __init__(self, gameState): <NEW_LINE> <INDENT> print("PROBLEM INITIALIZED") <NEW_LINE> self.food = gameState.getFood() <NEW_LINE> self.walls = gameState.getWalls() <NEW_LINE> self.startState = gameState.getPacmanPosition() <NEW_LINE> self.costFn = lambda x: 1 <NEW_LINE> self._visited, self._visitedlist, self._expanded = {}, [], 0 <NEW_LINE> self.Goal = self.calculateNearestFoodLocation(self.startState) <NEW_LINE> <DEDENT> def calculateNearestFoodLocation(self, startPos): <NEW_LINE> <INDENT> distanceFromFoods = list( map(manhattanDistance, [[startPos, (x, y)] for x in range(len(list(self.food))) for y in range(len(list(self.food)[0]))])) <NEW_LINE> foodBools = [foodBool for foodBoolList in list( self.food) for foodBool in foodBoolList] <NEW_LINE> distanceFromAvailableFoods = [ a*b for (a, b) in zip(distanceFromFoods, foodBools)] <NEW_LINE> minFoodVal = min( [foodDist for foodDist in distanceFromAvailableFoods if foodDist != 0]) <NEW_LINE> minFoodIndex = distanceFromAvailableFoods.index(minFoodVal) <NEW_LINE> x, y = minFoodIndex // len( list(self.food)[0]), minFoodIndex % len(list(self.food)[0]) <NEW_LINE> return (x, y) <NEW_LINE> <DEDENT> def isGoalState(self, state): <NEW_LINE> <INDENT> isGoal = state == self.Goal <NEW_LINE> return isGoal | A search problem for finding a path to any food.
This search problem is just like the PositionSearchProblem, but has a
different goal test, which you need to fill in below. The state space and
successor function do not need to be changed.
The class definition above, AnyFoodSearchProblem(PositionSearchProblem),
inherits the methods of the PositionSearchProblem.
You can use this search problem to help you fill in the findPathToClosestDot
method. | 62599039cad5886f8bdc594b |
class Meta(object): <NEW_LINE> <INDENT> db_table = 'strike' | meta information for database | 625990396e29344779b017ef |
class DateFieldCategorizer(NumericFieldCategorizer): <NEW_LINE> <INDENT> def key_to_name(self, key): <NEW_LINE> <INDENT> if key == DEFAULT_LONG: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return long_to_datetime(key) | Categorizer for date fields. Same as NumericFieldCategorizer, but
converts the numeric keys back to dates for better labels. | 62599039baa26c4b54d50446 |
class exponential_weibull(SimpleDistribution): <NEW_LINE> <INDENT> def __init__(self, a=1, c=1): <NEW_LINE> <INDENT> super(exponential_weibull, self).__init__(dict(a=a, c=c)) <NEW_LINE> <DEDENT> def _pdf(self, x, a, c): <NEW_LINE> <INDENT> exc = numpy.exp(-x**c) <NEW_LINE> return a*c*(1-exc)**(a-1)*exc*x**(c-1) <NEW_LINE> <DEDENT> def _cdf(self, x, a, c): <NEW_LINE> <INDENT> exm1c = -numpy.expm1(-x**c) <NEW_LINE> return (exm1c)**a <NEW_LINE> <DEDENT> def _ppf(self, q, a, c): <NEW_LINE> <INDENT> return (-numpy.log1p(-q**(1./a)))**(1./c) <NEW_LINE> <DEDENT> def _lower(self, a, c): <NEW_LINE> <INDENT> return 0. <NEW_LINE> <DEDENT> def _upper(self, a, c): <NEW_LINE> <INDENT> return (-numpy.log1p(-(1-1e-15)**(1./a)))**(1./c) | Exponential Weibull distribution. | 6259903916aa5153ce40168b |
class PastasEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, Timestamp): <NEW_LINE> <INDENT> return o.isoformat() <NEW_LINE> <DEDENT> elif isinstance(o, Series): <NEW_LINE> <INDENT> return o.to_json(date_format="iso", orient="split") <NEW_LINE> <DEDENT> elif isinstance(o, DataFrame): <NEW_LINE> <INDENT> return json.dumps(o.to_dict(orient="index"), indent=0) <NEW_LINE> <DEDENT> elif isinstance(o, Timedelta): <NEW_LINE> <INDENT> return o.to_timedelta64().__str__() <NEW_LINE> <DEDENT> elif isna(o): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(PastasEncoder, self).default(o) | Enhanced encoder to deal with the pandas formats used throughout Pastas.
Notes
-----
Currently supported formats are: DataFrame, Series,
Timedelta, TimeStamps.
see: https://docs.python.org/3/library/json.html | 62599039e76e3b2f99fd9baa |
class SQLError(Exception): <NEW_LINE> <INDENT> def __init__(self, code, message=None, response=None): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.message = message or 'Unknown' <NEW_LINE> self.response = response <NEW_LINE> super(SQLError, self).__init__(code, message, response) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "SQL %d: %s" % (self.code, self.message) <NEW_LINE> <DEDENT> __repr__ = __str__ | Exception thrown for an unsuccessful sql.
Attributes:
* ``code`` - HTTP error integer error code, e.g. 404. Error code 599 is
used when no HTTP response was received, e.g. for a timeout.
* ``response`` - `HTTPResponse` object, if any.
Note that if ``follow_redirects`` is False, redirects become HTTPErrors,
and you can look at ``error.response.headers['Location']`` to see the
destination of the redirect. | 625990395e10d32532ce41d2 |
class Infobox(): <NEW_LINE> <INDENT> def __init__(self, screen, fFont, title=None, info={}, order=[]): <NEW_LINE> <INDENT> numLines = len(info) <NEW_LINE> if title is not None: <NEW_LINE> <INDENT> numLines += 1 <NEW_LINE> <DEDENT> self.height = ((fFont.height+LINEBUFFER)*numLines)-LINEBUFFER+(BORDER*2) <NEW_LINE> self.width = screen.get_width()/2 <NEW_LINE> self.box = box.Box((self.width, self.height)).convert(screen) <NEW_LINE> i = 0 <NEW_LINE> if title is not None: <NEW_LINE> <INDENT> location = BORDER*3, BORDER <NEW_LINE> fFont.writeText(title, self.box, location) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> for param in order: <NEW_LINE> <INDENT> location = BORDER, (i*(fFont.height+LINEBUFFER))+BORDER <NEW_LINE> fFont.writeText(param, self.box, location) <NEW_LINE> location = self.width/2, (i*(fFont.height+LINEBUFFER))+BORDER <NEW_LINE> fFont.writeText(info[param], self.box, location) <NEW_LINE> i += 1 | Class used to show information on the game select screen. | 6259903926068e7796d4dae6 |
class CloudSigmaUploadResource (ResourceBase): <NEW_LINE> <INDENT> resource_name = 'initupload' <NEW_LINE> def __init__(self , **generic_client_kwargs): <NEW_LINE> <INDENT> self.generic_client_kwargs = generic_client_kwargs or {} <NEW_LINE> super(CloudSigmaUploadResource, self).__init__(**self.generic_client_kwargs) | auxillary class to make pycloudsigma happy | 6259903973bcbd0ca4bcb428 |
class L3AgentSchedulerPluginBase(object): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def add_router_to_l3_agent(self, context, id, router_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_router_from_l3_agent(self, context, id, router_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def list_routers_on_l3_agent(self, context, id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def list_l3_agents_hosting_router(self, context, router_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_firewall_to_l3_agent(self, context, id, firewall_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove_firewall_from_l3_agent(self, context, id, firewall_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def list_firewalls_on_l3_agent(self, context, id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def list_l3_agents_hosting_firewall(self, context, router_id): <NEW_LINE> <INDENT> pass | REST API to operate the l3 agent scheduler.
All of method must be in an admin context. | 625990398a43f66fc4bf332c |
class JogadorXPStatus: <NEW_LINE> <INDENT> fonte = None <NEW_LINE> last_xp = -1 <NEW_LINE> fgcolor = None <NEW_LINE> bgcolor = None <NEW_LINE> imagem = None <NEW_LINE> def __init__( self, jogador, posicao=None, fonte=None, ptsize=30, fgcolor="0xffff00", bgcolor=None ): <NEW_LINE> <INDENT> self.jogador = jogador <NEW_LINE> self.fgcolor = pygame.color.Color( fgcolor ) <NEW_LINE> if bgcolor: <NEW_LINE> <INDENT> self.bgcolor = pygame.color.Color( bgcolor ) <NEW_LINE> <DEDENT> self.posicao = posicao or [ 0, 0 ] <NEW_LINE> self.fonte = pygame.font.Font( fonte, ptsize ) <NEW_LINE> <DEDENT> def update( self, dt ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def draw( self, screen ): <NEW_LINE> <INDENT> xp = self.jogador.get_XP() <NEW_LINE> if self.last_xp != xp: <NEW_LINE> <INDENT> self.last_xp = xp <NEW_LINE> texto = "XP: % 4d" % xp <NEW_LINE> if self.bgcolor: <NEW_LINE> <INDENT> self.imagem = self.fonte.render( texto, True, self.fgcolor, self.bgcolor ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.imagem = self.fonte.render( texto, True, self.fgcolor ) <NEW_LINE> <DEDENT> <DEDENT> screen.blit( self.imagem, self.posicao ) | Esta classe representa a experiência do usuário | 625990396fece00bbacccb4b |
class AdaptorFcFnicProfile(ManagedObject): <NEW_LINE> <INDENT> consts = AdaptorFcFnicProfileConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = MoMeta("AdaptorFcFnicProfile", "adaptorFcFnicProfile", "fc-fnic", VersionMeta.Version151a, "InputOutput", 0x3f, [], ["admin", "ls-config-policy", "ls-server-policy", "ls-storage"], [u'adaptorHostFcIfProfile'], [], ["Get", "Set"]) <NEW_LINE> prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []), "io_retry_timeout": MoPropertyMeta("io_retry_timeout", "ioRetryTimeout", "uint", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, [], ["1-59"]), "lun_queue_depth": MoPropertyMeta("lun_queue_depth", "lunQueueDepth", "uint", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, [], ["1-254"]), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } <NEW_LINE> prop_map = { "childAction": "child_action", "dn": "dn", "ioRetryTimeout": "io_retry_timeout", "lunQueueDepth": "lun_queue_depth", "rn": "rn", "status": "status", } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.child_action = None <NEW_LINE> self.io_retry_timeout = None <NEW_LINE> self.lun_queue_depth = None <NEW_LINE> self.status = None <NEW_LINE> ManagedObject.__init__(self, "AdaptorFcFnicProfile", parent_mo_or_dn, **kwargs) | This is AdaptorFcFnicProfile class. | 6259903982261d6c52730794 |
class BiLSTMChar(object): <NEW_LINE> <INDENT> def __init__(self, char_domain_size, char_embedding_dim, hidden_dim, embeddings=None): <NEW_LINE> <INDENT> self.char_domain_size = char_domain_size <NEW_LINE> self.embedding_size = char_embedding_dim <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.input_chars = tf.placeholder(tf.int64, [None, None], name="input_chars") <NEW_LINE> self.batch_size = tf.placeholder(tf.int32, None, name="batch_size") <NEW_LINE> self.max_seq_len = tf.placeholder(tf.int32, None, name="max_seq_len") <NEW_LINE> self.max_tok_len = tf.placeholder(tf.int32, None, name="max_tok_len") <NEW_LINE> self.input_dropout_keep_prob = tf.placeholder_with_default(1.0, [], name="input_dropout_keep_prob") <NEW_LINE> self.sequence_lengths = tf.placeholder(tf.int32, [None, None], name="sequence_lengths") <NEW_LINE> self.token_lengths = tf.placeholder(tf.int32, [None, None], name="tok_lengths") <NEW_LINE> self.output_size = 2*self.hidden_dim <NEW_LINE> print("LSTM char embedding model") <NEW_LINE> print("embedding dim: ", self.embedding_size) <NEW_LINE> print("out dim: ", self.output_size) <NEW_LINE> shape = (char_domain_size-1, self.embedding_size) <NEW_LINE> self.char_embeddings = tf_utils.initialize_embeddings(shape, name="char_embeddings", pretrained=embeddings) <NEW_LINE> self.outputs = self.forward(self.input_chars, self.input_dropout_keep_prob, reuse=False) <NEW_LINE> <DEDENT> def forward(self, input_x1, input_dropout_keep_prob, reuse=True): <NEW_LINE> <INDENT> with tf.variable_scope("char-forward", reuse=reuse): <NEW_LINE> <INDENT> char_embeddings_lookup = tf.nn.embedding_lookup(self.char_embeddings, input_x1) <NEW_LINE> char_embeddings_flat = tf.reshape(char_embeddings_lookup, tf.stack([self.batch_size*self.max_seq_len, self.max_tok_len, self.embedding_size])) <NEW_LINE> tok_lens_flat = tf.reshape(self.token_lengths, [self.batch_size*self.max_seq_len]) <NEW_LINE> input_feats_drop = tf.nn.dropout(char_embeddings_flat, input_dropout_keep_prob) <NEW_LINE> with tf.name_scope("char-bilstm"): <NEW_LINE> <INDENT> fwd_cell = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_dim, state_is_tuple=True) <NEW_LINE> bwd_cell = tf.nn.rnn_cell.BasicLSTMCell(self.hidden_dim, state_is_tuple=True) <NEW_LINE> lstm_outputs, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw=fwd_cell, cell_bw=bwd_cell, dtype=tf.float32, inputs=input_feats_drop, parallel_iterations=32, swap_memory=False, sequence_length=tok_lens_flat) <NEW_LINE> outputs_fw = lstm_outputs[0] <NEW_LINE> outputs_bw = lstm_outputs[1] <NEW_LINE> fw_output = tf_utils.last_relevant(outputs_fw, tok_lens_flat) <NEW_LINE> bw_output = outputs_bw[:, 0, :] <NEW_LINE> hidden_outputs = tf.concat(axis=1, values=[fw_output, bw_output]) <NEW_LINE> hidden_outputs_unflat = tf.reshape(hidden_outputs, tf.stack([self.batch_size, self.max_seq_len, self.output_size])) <NEW_LINE> <DEDENT> <DEDENT> return hidden_outputs_unflat | A bidirectional LSTM for embedding tokens. | 6259903976d4e153a661db42 |
class PollsConfig(AppConfig): <NEW_LINE> <INDENT> name = 'polls' | A class for poll configuration. | 6259903991af0d3eaad3afd2 |
class Color4D(Structure): <NEW_LINE> <INDENT> _fields_ = [ ("r", c_float),("g", c_float),("b", c_float),("a", c_float), ] | See 'aiColor4D.h' for details. | 62599039596a897236128e3e |
class HeatColorGradient(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.alpha = 1.0 <NEW_LINE> <DEDENT> def get_color_value(self, value): <NEW_LINE> <INDENT> colors = [[0,0,1,1], [0,1,0,1], [1,1,0,1], [1,0,0,1]] <NEW_LINE> num_colors = len(colors) <NEW_LINE> idx1 = 0 <NEW_LINE> idx2 = 0 <NEW_LINE> frac_between = 0.0 <NEW_LINE> if value <= 0: <NEW_LINE> <INDENT> idx1 = idx2 = 0 <NEW_LINE> <DEDENT> elif value >= 1: <NEW_LINE> <INDENT> idx1 = idx2 = num_colors - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = value * (num_colors - 1) <NEW_LINE> idx1 = int(math.floor(value)) <NEW_LINE> idx2 = idx1 + 1 <NEW_LINE> frac_between = value - float(idx1) <NEW_LINE> <DEDENT> red = (colors[idx2][0] - colors[idx1][0]) * frac_between + colors[idx1][0]; <NEW_LINE> green = (colors[idx2][1] - colors[idx1][1]) * frac_between + colors[idx1][1]; <NEW_LINE> blue = (colors[idx2][2] - colors[idx1][2]) * frac_between + colors[idx1][2]; <NEW_LINE> return [red, green, blue, self.alpha] | Calculate a heat gradient color based on the specified value
:param value the value for the gradient, between 0.0 - 1.0
:type value float | 62599039cad5886f8bdc594c |
class PostUniverseNamesInternalServerError(object): <NEW_LINE> <INDENT> def __init__(self, error=None): <NEW_LINE> <INDENT> self.swagger_types = { 'error': 'str' } <NEW_LINE> self.attribute_map = { 'error': 'error' } <NEW_LINE> self._error = error <NEW_LINE> <DEDENT> @property <NEW_LINE> def error(self): <NEW_LINE> <INDENT> return self._error <NEW_LINE> <DEDENT> @error.setter <NEW_LINE> def error(self, error): <NEW_LINE> <INDENT> self._error = error <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PostUniverseNamesInternalServerError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 625990396e29344779b017f1 |
class JaccardLoss(nn.Module): <NEW_LINE> <INDENT> def __init__( self, apply_sigmoid: bool = True, smooth: float = 0., eps: float = 1e-7, ): <NEW_LINE> <INDENT> super(JaccardLoss, self).__init__() <NEW_LINE> self.apply_sigmoid = apply_sigmoid <NEW_LINE> self.smooth = smooth <NEW_LINE> self.eps = eps <NEW_LINE> <DEDENT> def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor,): <NEW_LINE> <INDENT> batch_size = y_pred.shape[0] <NEW_LINE> if self.apply_sigmoid: <NEW_LINE> <INDENT> y_pred = torch.sigmoid(y_pred) <NEW_LINE> <DEDENT> y_pred = y_pred.view(batch_size, 1, -1) <NEW_LINE> y_true = y_true.view(batch_size, 1, -1) <NEW_LINE> intersection = torch.sum(y_pred * y_true, dim=2) <NEW_LINE> cardinality = torch.sum(y_pred + y_true, dim=2) <NEW_LINE> union = cardinality - intersection <NEW_LINE> score = (intersection + self.smooth) / (union + self.smooth).clamp(min=self.eps) <NEW_LINE> return (1 - score).mean() | Calculates Jaccard( alsow known as Intersection over Union (IoU))
loss by each y_pred map from batch and returns the average.
Note, that y_true is expected to be Binary
Paper: https://arxiv.org/pdf/2006.14822.pdf
Implementation inspired by
https://www.kaggle.com/bigironsphere/loss-function-library-keras-pytorch#Jaccard/Intersection-over-Union-(IoU)-Loss
and https://github.com/qubvel/segmentation_models.pytorch/blob/master/segmentation_models_pytorch/losses/jaccard.py
Args:
apply_sigmoid: set False if sigmoid is already applied to model y_pred
smooth: Smoothness constant for dice coefficient
eps: A small epsilon for numerical stability to avoid zero division error | 625990391f5feb6acb163d92 |
class LocalOrRemote(Command): <NEW_LINE> <INDENT> takes_options = ( Flag('server?', doc=_('Forward to server instead of running locally'), ), ) <NEW_LINE> def run(self, *args, **options): <NEW_LINE> <INDENT> if options.get('server', False) and not self.env.in_server: <NEW_LINE> <INDENT> return self.forward(*args, **options) <NEW_LINE> <DEDENT> return self.execute(*args, **options) | A command that is explicitly executed locally or remotely.
This is for commands that makes sense to execute either locally or
remotely to return a perhaps different result. The best example of
this is the `ipalib.plugins.f_misc.env` plugin which returns the
key/value pairs describing the configuration state: it can be | 6259903916aa5153ce40168d |
class Pool_Systems(BeakerCommand): <NEW_LINE> <INDENT> enabled = True <NEW_LINE> def options(self): <NEW_LINE> <INDENT> self.parser.usage = "%%prog %s <pool-name>" % self.normalized_name <NEW_LINE> self.parser.add_option( '--format', type='choice', choices=['list', 'json'], default='list', help='Results display format: json, list [default: %default]', ) <NEW_LINE> <DEDENT> def run(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) != 1: <NEW_LINE> <INDENT> self.parser.error('Exactly one pool name must be specified') <NEW_LINE> <DEDENT> pool_name = args[0] <NEW_LINE> self.set_hub(**kwargs) <NEW_LINE> requests_session = self.requests_session() <NEW_LINE> response = requests_session.get('pools/%s' % pool_name, headers={'Accept': 'application/json'}) <NEW_LINE> response.raise_for_status() <NEW_LINE> attributes = response.json() <NEW_LINE> systems = attributes['systems'] <NEW_LINE> if kwargs['format'] == 'json': <NEW_LINE> <INDENT> print(json.dumps(systems)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for system in systems: <NEW_LINE> <INDENT> print(system) | List systems in a pool | 6259903973bcbd0ca4bcb429 |
class OEB2HTMLNoCSSizer(OEB2HTML): <NEW_LINE> <INDENT> def dump_text(self, elem, stylizer, page): <NEW_LINE> <INDENT> if not isinstance(elem.tag, string_or_bytes) or namespace(elem.tag) not in (XHTML_NS, SVG_NS): <NEW_LINE> <INDENT> p = elem.getparent() <NEW_LINE> if p is not None and isinstance(p.tag, string_or_bytes) and namespace(p.tag) in (XHTML_NS, SVG_NS) and elem.tail: <NEW_LINE> <INDENT> return [elem.tail] <NEW_LINE> <DEDENT> return [''] <NEW_LINE> <DEDENT> text = [''] <NEW_LINE> style = stylizer.style(elem) <NEW_LINE> tags = [] <NEW_LINE> tag = barename(elem.tag) <NEW_LINE> attribs = elem.attrib <NEW_LINE> if tag == 'body': <NEW_LINE> <INDENT> tag = 'div' <NEW_LINE> <DEDENT> tags.append(tag) <NEW_LINE> if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') or style['visibility'] == 'hidden': <NEW_LINE> <INDENT> return [''] <NEW_LINE> <DEDENT> if 'class' in attribs: <NEW_LINE> <INDENT> del attribs['class'] <NEW_LINE> <DEDENT> if 'style' in attribs: <NEW_LINE> <INDENT> del attribs['style'] <NEW_LINE> <DEDENT> at = '' <NEW_LINE> for k, v in attribs.items(): <NEW_LINE> <INDENT> k = k.split('}')[-1] <NEW_LINE> at += ' %s="%s"' % (k, prepare_string_for_xml(v, attribute=True)) <NEW_LINE> <DEDENT> text.append('<%s%s' % (tag, at)) <NEW_LINE> if tag in SELF_CLOSING_TAGS: <NEW_LINE> <INDENT> text.append(' />') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text.append('>') <NEW_LINE> <DEDENT> if style['font-weight'] in ('bold', 'bolder'): <NEW_LINE> <INDENT> text.append('<b>') <NEW_LINE> tags.append('b') <NEW_LINE> <DEDENT> if style['font-style'] == 'italic': <NEW_LINE> <INDENT> text.append('<i>') <NEW_LINE> tags.append('i') <NEW_LINE> <DEDENT> if style['text-decoration'] == 'underline': <NEW_LINE> <INDENT> text.append('<u>') <NEW_LINE> tags.append('u') <NEW_LINE> <DEDENT> if style['text-decoration'] == 'line-through': <NEW_LINE> <INDENT> text.append('<s>') <NEW_LINE> tags.append('s') <NEW_LINE> <DEDENT> if hasattr(elem, 'text') and elem.text: <NEW_LINE> <INDENT> text.append(self.prepare_string_for_html(elem.text)) <NEW_LINE> <DEDENT> for item in elem: <NEW_LINE> <INDENT> text += self.dump_text(item, stylizer, page) <NEW_LINE> <DEDENT> tags.reverse() <NEW_LINE> for t in tags: <NEW_LINE> <INDENT> if t not in SELF_CLOSING_TAGS: <NEW_LINE> <INDENT> text.append('</%s>' % t) <NEW_LINE> <DEDENT> <DEDENT> if hasattr(elem, 'tail') and elem.tail: <NEW_LINE> <INDENT> text.append(self.prepare_string_for_html(elem.tail)) <NEW_LINE> <DEDENT> return text | This will remap a small number of CSS styles to equivalent HTML tags. | 6259903930c21e258be999ae |
class AbstractMelonOrder(): <NEW_LINE> <INDENT> def __init__(self, species, qty, country_code=None, passed_inspection=None): <NEW_LINE> <INDENT> self.species = species <NEW_LINE> self.qty = qty <NEW_LINE> self.shipped = False <NEW_LINE> if passed_inspection: <NEW_LINE> <INDENT> self.passed_inspection = passed_inspection <NEW_LINE> <DEDENT> if country_code: <NEW_LINE> <INDENT> self.country_code = country_code <NEW_LINE> <DEDENT> <DEDENT> def get_total(self): <NEW_LINE> <INDENT> base_price = 5 <NEW_LINE> fee = 0 <NEW_LINE> if self.order_type == "international" and self.qty < 10: <NEW_LINE> <INDENT> fee = 3 <NEW_LINE> <DEDENT> if self.species == "Christmas": <NEW_LINE> <INDENT> base_price = base_price * 1.5 <NEW_LINE> <DEDENT> total = (1 + self.tax) * (self.qty * base_price) + fee <NEW_LINE> return total <NEW_LINE> <DEDENT> def mark_shipped(self): <NEW_LINE> <INDENT> self.shipped = True | An abstract base class that other Melon Orders inherit from. | 62599039dc8b845886d54755 |
class XTP_FUND_TRANSFER_TYPE(IntEnum): <NEW_LINE> <INDENT> XTP_FUND_TRANSFER_OUT = 0 <NEW_LINE> XTP_FUND_TRANSFER_IN = auto() <NEW_LINE> XTP_FUND_TRANSFER_UNKNOWN = auto() | XTP_FUND_TRANSFER_TYPE是资金流转方向类型 | 62599039287bf620b6272d8b |
class SymbolicProblemTypeTest(ProblemTypeTestBase, ProblemTypeTestMixin): <NEW_LINE> <INDENT> problem_name = 'SYMBOLIC TEST PROBLEM' <NEW_LINE> problem_type = 'symbolicresponse' <NEW_LINE> partially_correct = False <NEW_LINE> factory = SymbolicResponseXMLFactory() <NEW_LINE> factory_kwargs = { 'expect': '2*x+3*y', 'question_text': 'Enter a value' } <NEW_LINE> status_indicators = { 'correct': ['div.capa_inputtype div.correct'], 'incorrect': ['div.capa_inputtype div.incorrect'], 'unanswered': ['div.capa_inputtype div.unanswered'], } <NEW_LINE> def answer_problem(self, correctness): <NEW_LINE> <INDENT> choice = "2*x+3*y" if correctness == 'correct' else "3*a+4*b" <NEW_LINE> self.problem_page.fill_answer(choice) | TestCase Class for Symbolic Problem Type | 6259903907d97122c4217e3e |
class TerminationNotice(Exception): <NEW_LINE> <INDENT> pass | This exception is raised inside a thread when it's time for it to die. | 6259903991af0d3eaad3afd4 |
class WizardLinkOrder( LoginRequiredMixin, StaffuserRequiredMixin, WizardLinkMixin, FormView): <NEW_LINE> <INDENT> form_class = EmptyForm <NEW_LINE> template_name = 'block/wizard_link_order.html' <NEW_LINE> def _move_up_down(self, up, down): <NEW_LINE> <INDENT> pk = int(up) if up else int(down) <NEW_LINE> idx = None <NEW_LINE> ordered = [] <NEW_LINE> many_to_many = self._get_many_to_many() <NEW_LINE> for count, item in enumerate(many_to_many): <NEW_LINE> <INDENT> if item.pk == pk: <NEW_LINE> <INDENT> idx = count <NEW_LINE> <DEDENT> ordered.append(item.pk) <NEW_LINE> count = count + 1 <NEW_LINE> <DEDENT> if idx is None: <NEW_LINE> <INDENT> raise BlockError("Cannot find item {} in {}".format(pk, ordered)) <NEW_LINE> <DEDENT> if down: <NEW_LINE> <INDENT> if idx == len(ordered) - 1: <NEW_LINE> <INDENT> raise BlockError("Cannot move the last item down") <NEW_LINE> <DEDENT> ordered[idx], ordered[idx+1] = ordered[idx+1], ordered[idx] <NEW_LINE> <DEDENT> elif up: <NEW_LINE> <INDENT> if idx == 0: <NEW_LINE> <INDENT> raise BlockError("Cannot move the first item up") <NEW_LINE> <DEDENT> ordered[idx], ordered[idx-1] = ordered[idx-1], ordered[idx] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise BlockError("No 'up' or 'down' (why?)") <NEW_LINE> <DEDENT> content_obj = self._content_obj() <NEW_LINE> field = self._get_field() <NEW_LINE> with transaction.atomic(): <NEW_LINE> <INDENT> for order, pk in enumerate(ordered, start=1): <NEW_LINE> <INDENT> obj = field.through.objects.get( pk=pk, content=content_obj, ) <NEW_LINE> obj.order = order <NEW_LINE> obj.save() <NEW_LINE> <DEDENT> content_obj.set_pending_edit() <NEW_LINE> content_obj.save() <NEW_LINE> <DEDENT> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> up = self.request.POST.get('up') <NEW_LINE> down = self.request.POST.get('down') <NEW_LINE> if up or down: <NEW_LINE> <INDENT> self._move_up_down(up, down) <NEW_LINE> <DEDENT> return HttpResponseRedirect( reverse('block.wizard.link.order', kwargs=self._kwargs()) ) | set the order of multiple links | 6259903994891a1f408b9fc8 |
class Comment(models.Model): <NEW_LINE> <INDENT> post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE) <NEW_LINE> author = models.CharField(max_length=200) <NEW_LINE> text = models.TextField() <NEW_LINE> create_date = models.DateTimeField(default=timezone.now()) <NEW_LINE> approved_comment = models.BooleanField(default=False) <NEW_LINE> def approve(self): <NEW_LINE> <INDENT> self.approved_comment = True <NEW_LINE> self.save() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_absolute_url(): <NEW_LINE> <INDENT> return reverse('post_list') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.text | Comments on certain blog posts.
Anyone can comment, but they will have to be approved to be shown. | 625990398da39b475be04391 |
class DAPLinkServer(object): <NEW_LINE> <INDENT> def __init__(self, address=None, socket=None, interface=None): <NEW_LINE> <INDENT> if interface: <NEW_LINE> <INDENT> self._interface = INTERFACE[interface] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._interface = default_interface <NEW_LINE> <DEDENT> if socket: <NEW_LINE> <INDENT> socket = SOCKET[socket] <NEW_LINE> <DEDENT> elif address: <NEW_LINE> <INDENT> socket = socket_by_address(address) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> socket = default_socket <NEW_LINE> <DEDENT> if address: <NEW_LINE> <INDENT> self._server = socket.Server(address) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._server = socket.Server() <NEW_LINE> <DEDENT> self.interface = self._interface.name <NEW_LINE> self.socket = socket.name <NEW_LINE> self._threads = set() <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> self._server.open() <NEW_LINE> thread = Thread(target=self._server_task) <NEW_LINE> thread.daemon = True <NEW_LINE> thread.shutdown = self._server.shutdown <NEW_LINE> thread.start() <NEW_LINE> self._threads.add(thread) <NEW_LINE> <DEDENT> @property <NEW_LINE> def client_count(self): <NEW_LINE> <INDENT> return max(len(self._threads)-1, 0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> return self._server.address <NEW_LINE> <DEDENT> def _server_task(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while self._server.isalive(): <NEW_LINE> <INDENT> client = self._server.accept() <NEW_LINE> if client: <NEW_LINE> <INDENT> thread = Thread(target=lambda: self._client_task(client)) <NEW_LINE> thread.daemon = True <NEW_LINE> thread.shutdown = client.shutdown <NEW_LINE> thread.start() <NEW_LINE> self._threads.add(thread) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._threads.discard(threading.current_thread()) <NEW_LINE> <DEDENT> <DEDENT> def _client_task(self, client): <NEW_LINE> <INDENT> connection = DAPLinkServerTransport(self._interface) <NEW_LINE> connection.init() <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = client.recv() <NEW_LINE> if not client.isalive(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> data = decode(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise CommandError('Malformed command') <NEW_LINE> <DEDENT> resp = connection.handle(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> exc = sys.exc_info() <NEW_LINE> type = exc[0].__name__ <NEW_LINE> message = str(exc[1]) <NEW_LINE> logging.error('%s: %s' % (type, message)) <NEW_LINE> try: <NEW_LINE> <INDENT> client.send(encode({'error': type, 'message': message})) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> client.send(encode(resp)) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> connection.uninit() <NEW_LINE> client.close() <NEW_LINE> self._threads.discard(threading.current_thread()) <NEW_LINE> <DEDENT> <DEDENT> def uninit(self): <NEW_LINE> <INDENT> threads = self._threads.copy() <NEW_LINE> for thread in threads: <NEW_LINE> <INDENT> thread.shutdown() <NEW_LINE> <DEDENT> for thread in threads: <NEW_LINE> <INDENT> thread.join() <NEW_LINE> <DEDENT> self._server.close() | This class provides the DAPLink interface as a streaming socket
based server. Communication is performed by sending commands
formed as JSON dictionaries. | 6259903907d97122c4217e3f |
class TemplateIncludeError(TemplateError): <NEW_LINE> <INDENT> pass | Raised by the `ControlledLoader` if recursive includes where
detected. | 6259903966673b3332c31597 |
class DictQueryset(AbstractQueryset): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> super(DictQueryset, self).__init__(db_conn=dict(), **kw) <NEW_LINE> <DEDENT> def create_one(self, shield): <NEW_LINE> <INDENT> if shield.id in self.db_conn: <NEW_LINE> <INDENT> status = self.MSG_UPDATED <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status = self.MSG_CREATED <NEW_LINE> <DEDENT> shield_key = str(getattr(shield, self.api_id)) <NEW_LINE> self.db_conn[shield_key] = shield.to_python() <NEW_LINE> return (status, shield) <NEW_LINE> <DEDENT> def create_many(self, shields): <NEW_LINE> <INDENT> statuses = [self.create_one(shield) for shield in shields] <NEW_LINE> return statuses <NEW_LINE> <DEDENT> def read_all(self): <NEW_LINE> <INDENT> return [(self.MSG_OK, datum) for datum in self.db_conn.values()] <NEW_LINE> <DEDENT> def read_one(self, iid): <NEW_LINE> <INDENT> iid = str(iid) <NEW_LINE> if iid in self.db_conn: <NEW_LINE> <INDENT> return (self.MSG_OK, self.db_conn[iid]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.MSG_FAILED, iid) <NEW_LINE> <DEDENT> <DEDENT> def read_many(self, ids): <NEW_LINE> <INDENT> return [self.read_one(iid) for iid in ids] <NEW_LINE> <DEDENT> def update_one(self, shield): <NEW_LINE> <INDENT> shield_key = str(getattr(shield, self.api_id)) <NEW_LINE> self.db_conn[shield_key] = shield.to_python() <NEW_LINE> return (self.MSG_UPDATED, shield) <NEW_LINE> <DEDENT> def update_many(self, shields): <NEW_LINE> <INDENT> statuses = [self.update_one(shield) for shield in shields] <NEW_LINE> return statuses <NEW_LINE> <DEDENT> def destroy_one(self, item_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> datum = self.db_conn[item_id] <NEW_LINE> del self.db_conn[item_id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ResponseException(404) <NEW_LINE> <DEDENT> return (self.MSG_UPDATED, datum) <NEW_LINE> <DEDENT> def destroy_many(self, ids): <NEW_LINE> <INDENT> statuses = [self.destroy_one(iid) for iid in ids] <NEW_LINE> return statuses | This class exists as an example of how one could implement a Queryset.
This model is an in-memory dictionary and uses the model's id as the key.
The data stored is the result of calling model's `to_python()` function. | 62599039ec188e330fdf9a3a |
class CheckSkuAvailabilityOperations(object): <NEW_LINE> <INDENT> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self.api_version = "2017-04-18" <NEW_LINE> self.config = config <NEW_LINE> <DEDENT> def list( self, location, skus, kind, type, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> parameters = models.CheckSkuAvailabilityParameter(skus=skus, kind=kind, type=type) <NEW_LINE> url = '/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/checkSkuAvailability' <NEW_LINE> path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'location': self._serialize.url("location", location, 'str') } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Content-Type'] = 'application/json; charset=utf-8' <NEW_LINE> if self.config.generate_client_request_id: <NEW_LINE> <INDENT> header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) <NEW_LINE> <DEDENT> if custom_headers: <NEW_LINE> <INDENT> header_parameters.update(custom_headers) <NEW_LINE> <DEDENT> if self.config.accept_language is not None: <NEW_LINE> <INDENT> header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') <NEW_LINE> <DEDENT> body_content = self._serialize.body(parameters, 'CheckSkuAvailabilityParameter') <NEW_LINE> request = self._client.post(url, query_parameters) <NEW_LINE> response = self._client.send( request, header_parameters, body_content, **operation_config) <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> exp = CloudError(response) <NEW_LINE> exp.request_id = response.headers.get('x-ms-request-id') <NEW_LINE> raise exp <NEW_LINE> <DEDENT> deserialized = None <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> deserialized = self._deserialize('CheckSkuAvailabilityResultList', response) <NEW_LINE> <DEDENT> if raw: <NEW_LINE> <INDENT> client_raw_response = ClientRawResponse(deserialized, response) <NEW_LINE> return client_raw_response <NEW_LINE> <DEDENT> return deserialized | CheckSkuAvailabilityOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model deserializer.
:ivar api_version: Version of the API to be used with the client request. Current version is 2017-04-18. Constant value: "2017-04-18". | 62599039a4f1c619b294f758 |
class DiagnosticStatusClass(object): <NEW_LINE> <INDENT> OK = "OK" <NEW_LINE> WAITING = "WAITING" <NEW_LINE> FAIL = "FAIL" <NEW_LINE> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(DiagnosticStatusClass, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, DiagnosticStatusClass): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599039d6c5a102081e32c9 |
class creatverfattr(BaseObj): <NEW_LINE> <INDENT> _attrlist = ("verifier", "attrs") <NEW_LINE> def __init__(self, unpack): <NEW_LINE> <INDENT> self.verifier = verifier4(unpack) <NEW_LINE> self.attrs = fattr4(unpack) | struct creatverfattr {
verifier4 verifier;
fattr4 attrs;
}; | 6259903926238365f5fadcf8 |
class GovFileInput(GovInput, FileInput): <NEW_LINE> <INDENT> template = "govuk_frontend_wtf/file-upload.html" <NEW_LINE> def __call__(self, field, **kwargs): <NEW_LINE> <INDENT> kwargs["value"] = False <NEW_LINE> if self.multiple: <NEW_LINE> <INDENT> kwargs["multiple"] = True <NEW_LINE> <DEDENT> return super().__call__(field, **kwargs) | Render a file chooser input.
:param multiple: allow choosing multiple files | 62599039b57a9660fecd2c1e |
class MooseFigure(MooseImageFile): <NEW_LINE> <INDENT> RE = r'^!figure\s+(.*?)(?:$|\s+)(.*)' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MooseFigure, self).__init__(*args, **kwargs) <NEW_LINE> self._settings['prefix'] = 'Figure' <NEW_LINE> self._settings['id'] = None <NEW_LINE> self._figure_number = 0 <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> self._figure_number = 0 <NEW_LINE> <DEDENT> def handleMatch(self, match): <NEW_LINE> <INDENT> self._figure_number += 1 <NEW_LINE> rel_filename = match.group(2) <NEW_LINE> settings = self.getSettings(match.group(3)) <NEW_LINE> if not settings['id']: <NEW_LINE> <INDENT> return self.createErrorElement("The 'id' setting must be supplied for the figure: {}".format(rel_filename)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> settings['id'] = settings['id'].replace(':', '') <NEW_LINE> <DEDENT> if settings['caption']: <NEW_LINE> <INDENT> settings['caption'] = '{} {}: {}'.format(settings['prefix'], self._figure_number, settings['caption']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> settings['caption'] = '{} {}'.format(settings['prefix'], self._figure_number) <NEW_LINE> <DEDENT> el = self.createImageElement(rel_filename, settings) <NEW_LINE> el.set('data-moose-figure-number', str(self._figure_number)) <NEW_LINE> return el | Defines syntax for adding images as numbered figures with labels that can be referenced (see MooseFigureReference) | 62599039be383301e02549ba |
@implementer(schemas.ICloudWatchLogging) <NEW_LINE> class CloudWatchLogging(Named, CloudWatchLogRetention): <NEW_LINE> <INDENT> log_sets = FieldProperty(schemas.ICloudWatchLogging["log_sets"]) | Contains global defaults for all CloudWatch logging and log sets | 62599039a8ecb033258723c2 |
class xep_0092(base_plugin): <NEW_LINE> <INDENT> def plugin_init(self): <NEW_LINE> <INDENT> self.xep = "0092" <NEW_LINE> self.description = "Software Version" <NEW_LINE> self.stanza = sleekxmpp.plugins.xep_0092.stanza <NEW_LINE> self.name = self.config.get('name', 'SleekXMPP') <NEW_LINE> self.version = self.config.get('version', '0.1-dev') <NEW_LINE> self.os = self.config.get('os', '') <NEW_LINE> self.getVersion = self.get_version <NEW_LINE> self.xmpp.register_handler( Callback('Software Version', StanzaPath('iq@type=get/software_version'), self._handle_version)) <NEW_LINE> register_stanza_plugin(Iq, Version) <NEW_LINE> <DEDENT> def post_init(self): <NEW_LINE> <INDENT> base_plugin.post_init(self) <NEW_LINE> self.xmpp.plugin['xep_0030'].add_feature('jabber:iq:version') <NEW_LINE> <DEDENT> def _handle_version(self, iq): <NEW_LINE> <INDENT> iq.reply() <NEW_LINE> iq['software_version']['name'] = self.name <NEW_LINE> iq['software_version']['version'] = self.version <NEW_LINE> iq['software_version']['os'] = self.os <NEW_LINE> iq.send() <NEW_LINE> <DEDENT> def get_version(self, jid, ifrom=None): <NEW_LINE> <INDENT> iq = self.xmpp.Iq() <NEW_LINE> iq['to'] = jid <NEW_LINE> if ifrom: <NEW_LINE> <INDENT> iq['from'] = ifrom <NEW_LINE> <DEDENT> iq['type'] = 'get' <NEW_LINE> iq['query'] = Version.namespace <NEW_LINE> result = iq.send() <NEW_LINE> if result and result['type'] != 'error': <NEW_LINE> <INDENT> return result['software_version'].values <NEW_LINE> <DEDENT> return False | XEP-0092: Software Version | 6259903963f4b57ef0086645 |
class TestContains(MemoryLeakMixin, TestCase): <NEW_LINE> <INDENT> def test_list_contains_empty(self): <NEW_LINE> <INDENT> @njit <NEW_LINE> def foo(i): <NEW_LINE> <INDENT> l = listobject.new_list(int32) <NEW_LINE> return i in l <NEW_LINE> <DEDENT> self.assertFalse(foo(0)) <NEW_LINE> self.assertFalse(foo(1)) <NEW_LINE> <DEDENT> def test_list_contains_singleton(self): <NEW_LINE> <INDENT> @njit <NEW_LINE> def foo(i): <NEW_LINE> <INDENT> l = listobject.new_list(int32) <NEW_LINE> l.append(0) <NEW_LINE> return i in l <NEW_LINE> <DEDENT> self.assertTrue(foo(0)) <NEW_LINE> self.assertFalse(foo(1)) <NEW_LINE> <DEDENT> def test_list_contains_multiple(self): <NEW_LINE> <INDENT> @njit <NEW_LINE> def foo(i): <NEW_LINE> <INDENT> l = listobject.new_list(int32) <NEW_LINE> for j in range(10, 20): <NEW_LINE> <INDENT> l.append(j) <NEW_LINE> <DEDENT> return i in l <NEW_LINE> <DEDENT> for i in range(10, 20): <NEW_LINE> <INDENT> self.assertTrue(foo(i)) <NEW_LINE> <DEDENT> for i in range(20, 30): <NEW_LINE> <INDENT> self.assertFalse(foo(i)) | Test list contains. | 625990398da39b475be04393 |
class GravimetryModelling(pg.ModellingBase): <NEW_LINE> <INDENT> def __init__(self, verbose=True): <NEW_LINE> <INDENT> super(GravimetryModelling, self).__init__(verbose) <NEW_LINE> self._J = pg.RMatrix() <NEW_LINE> self.sensorPositions = None <NEW_LINE> self.setJacobian(self._J) <NEW_LINE> <DEDENT> def createStartmodel(self): <NEW_LINE> <INDENT> return pg.RVector(self.regionManger().parameterCount(), 0.0) <NEW_LINE> <DEDENT> def setSensorPositions(self, pnts): <NEW_LINE> <INDENT> self.sensorPositions = pnts <NEW_LINE> <DEDENT> def response(self, dDensity): <NEW_LINE> <INDENT> return solveGravimetry(self.regionManager().paraDomain(), dDensity, pnts=self.sensorPositions, complete=False) <NEW_LINE> <DEDENT> def createJacobian(self, model): <NEW_LINE> <INDENT> gdz = solveGravimetry(self.regionManager().paraDomain(), dDensity=None, pnts=self.sensorPositions, complete=False) <NEW_LINE> self._J.resize(len(gdz), len(gdz[0])) <NEW_LINE> for i, gdzi in enumerate(gdz): <NEW_LINE> <INDENT> self._J.setVal(gdzi, i) <NEW_LINE> <DEDENT> raise BaseException('Scale with model??', model) | Gravimetry modelling operator. | 6259903971ff763f4b5e893e |
class Solution2: <NEW_LINE> <INDENT> def hasCycle(self, head: ListNode) -> bool: <NEW_LINE> <INDENT> visited = set() <NEW_LINE> while head: <NEW_LINE> <INDENT> if head in visited: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> visited.add(head) <NEW_LINE> head = head.next <NEW_LINE> <DEDENT> return False | 哈希表
时间复杂度:O(1),空间复杂度:O(n), | 6259903916aa5153ce401691 |
class GoogleCloudVisionV1p2beta1ImageAnnotationContext(_messages.Message): <NEW_LINE> <INDENT> pageNumber = _messages.IntegerField(1, variant=_messages.Variant.INT32) <NEW_LINE> uri = _messages.StringField(2) | If an image was produced from a file (e.g. a PDF), this message gives
information about the source of that image.
Fields:
pageNumber: If the file was a PDF or TIFF, this field gives the page
number within the file used to produce the image.
uri: The URI of the file used to produce the image. | 6259903923e79379d538d6a5 |
class SlackPMAppTokenError(SlackPMErrorBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SlackPMAppTokenError, self).__init__('Invalid Application Token') | Invalid Application Token. | 6259903930dc7b76659a09d7 |
class TestSimpleSignalOrderFillCycleForPortfolioHandler(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> initial_cash = Decimal("500000.00") <NEW_LINE> events_queue = EventsQueue() <NEW_LINE> price_handler = PriceHandlerMock() <NEW_LINE> position_sizer = PositionSizerMock() <NEW_LINE> risk_manager = RiskManagerMock() <NEW_LINE> self.portfolio_handler = PortfolioHandler( events_queue, initial_cash, price_handler, position_sizer, risk_manager ) <NEW_LINE> <DEDENT> def test_create_order_from_signal_basic_check(self): <NEW_LINE> <INDENT> signal_event = SignalEvent("MSFT", "BOT") <NEW_LINE> order = self.portfolio_handler._create_order_from_signal(signal_event) <NEW_LINE> self.assertEqual(order.ticker, "MSFT") <NEW_LINE> self.assertEqual(order.action, "BOT") <NEW_LINE> self.assertEqual(order.quantity, 0) <NEW_LINE> <DEDENT> def test_place_orders_onto_queue_basic_check(self): <NEW_LINE> <INDENT> order = OrderEvent("MSFT", "BOT", 100) <NEW_LINE> order_list = [order] <NEW_LINE> self.portfolio_handler._place_orders_onto_queue(order_list) <NEW_LINE> ret_order = self.portfolio_handler.events_queue.dequeue() <NEW_LINE> self.assertEqual(ret_order.ticker, "MSFT") <NEW_LINE> self.assertEqual(ret_order.action, "BOT") <NEW_LINE> self.assertEqual(ret_order.quantity, 100) <NEW_LINE> <DEDENT> def test_convert_fill_to_portfolio_update_basic_check(self): <NEW_LINE> <INDENT> fill_event_buy = FillEvent( datetime.datetime.utcnow(), "MSFT", "BOT", 100, "ARCA", Decimal("50.25"), Decimal("1.00") ) <NEW_LINE> self.portfolio_handler._convert_fill_to_portfolio_update(fill_event_buy) <NEW_LINE> port = self.portfolio_handler.portfolio <NEW_LINE> self.assertEqual(port.cur_cash, Decimal("494974.00")) <NEW_LINE> fill_event_sell = FillEvent( datetime.datetime.utcnow(), "MSFT", "SLD", 100, "ARCA", Decimal("50.25"), Decimal("1.00") ) <NEW_LINE> self.portfolio_handler._convert_fill_to_portfolio_update(fill_event_sell) <NEW_LINE> <DEDENT> def test_on_signal_basic_check(self): <NEW_LINE> <INDENT> signal_event = SignalEvent("MSFT", "BOT") <NEW_LINE> self.portfolio_handler.on_signal(signal_event) <NEW_LINE> ret_order = self.portfolio_handler.events_queue.dequeue() <NEW_LINE> self.assertEqual(ret_order.ticker, "MSFT") <NEW_LINE> self.assertEqual(ret_order.action, "BOT") <NEW_LINE> self.assertEqual(ret_order.quantity, 100) | Tests a simple Signal, Order and Fill cycle for the
PortfolioHandler. This is, in effect, a sanity check. | 62599039507cdc57c63a5f3e |
class Simple: <NEW_LINE> <INDENT> def decide_action(self, target, game): <NEW_LINE> <INDENT> actor = self.owner <NEW_LINE> distance = actor.distance_to_ent(target) <NEW_LINE> results = [] <NEW_LINE> if distance >= 2: <NEW_LINE> <INDENT> actor.move_astar(target, game) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results.extend(actor.f.attack_setup(target, game)) <NEW_LINE> <DEDENT> return results | Simple behavior moves the npc straight towards the player, attack if next to them and use a skill if available. | 62599039a4f1c619b294f759 |
class Proxy(Model): <NEW_LINE> <INDENT> proxy = CharField(primary_key=True) <NEW_LINE> check_time = DateTimeField(null=True) <NEW_LINE> response_time = FloatField(null=True) <NEW_LINE> status_code = IntegerField(null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> database = db | 数据库model | 6259903973bcbd0ca4bcb42d |
class SEResNet(Chain): <NEW_LINE> <INDENT> def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, in_channels=3, in_size=(224, 224), classes=1000): <NEW_LINE> <INDENT> super(SEResNet, self).__init__() <NEW_LINE> self.in_size = in_size <NEW_LINE> self.classes = classes <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> self.features = SimpleSequential() <NEW_LINE> with self.features.init_scope(): <NEW_LINE> <INDENT> setattr(self.features, "init_block", ResInitBlock( in_channels=in_channels, out_channels=init_block_channels)) <NEW_LINE> in_channels = init_block_channels <NEW_LINE> for i, channels_per_stage in enumerate(channels): <NEW_LINE> <INDENT> stage = SimpleSequential() <NEW_LINE> with stage.init_scope(): <NEW_LINE> <INDENT> for j, out_channels in enumerate(channels_per_stage): <NEW_LINE> <INDENT> stride = 2 if (j == 0) and (i != 0) else 1 <NEW_LINE> setattr(stage, "unit{}".format(j + 1), SEResUnit( in_channels=in_channels, out_channels=out_channels, stride=stride, bottleneck=bottleneck, conv1_stride=conv1_stride)) <NEW_LINE> in_channels = out_channels <NEW_LINE> <DEDENT> <DEDENT> setattr(self.features, "stage{}".format(i + 1), stage) <NEW_LINE> <DEDENT> setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=7, stride=1)) <NEW_LINE> <DEDENT> self.output = SimpleSequential() <NEW_LINE> with self.output.init_scope(): <NEW_LINE> <INDENT> setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) <NEW_LINE> setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> x = self.features(x) <NEW_LINE> x = self.output(x) <NEW_LINE> return x | SE-ResNet model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
bottleneck : bool
Whether to use a bottleneck or simple block in units.
conv1_stride : bool
Whether to use stride in the first or the second convolution layer in units.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes. | 62599039d6c5a102081e32cb |
class Error(XC): <NEW_LINE> <INDENT> pass | This is the base class for exceptions that may be recoverable.
Packages should create subclasses of this. | 625990396fece00bbacccb51 |
class EventPageGroup(models.Model): <NEW_LINE> <INDENT> eventpage = ParentalKey( "events.EventPage", on_delete=models.CASCADE, related_name="related_groups" ) <NEW_LINE> group = models.ForeignKey( "core.Group", on_delete=models.CASCADE, related_name="event_pages" ) <NEW_LINE> panels = [ PageChooserPanel("group"), ] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ("eventpage", "group") | model that saves the relation from EventPages to Groups, showing a PageChooserPanel | 625990391d351010ab8f4cc0 |
class Observable(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.observers = [] <NEW_LINE> <DEDENT> def register(self, observer): <NEW_LINE> <INDENT> self.observers.append(observer) <NEW_LINE> <DEDENT> def notify_observers(self, message): <NEW_LINE> <INDENT> for observer in self.observers: <NEW_LINE> <INDENT> observer.update(message) | Абстрактный наблюдаемый | 6259903921bff66bcd723e0e |
class CSOR(SFS): <NEW_LINE> <INDENT> DIVISION = FixedCharField(4, default='CSOR') <NEW_LINE> _training_pay = IntegerField() <NEW_LINE> _deployment_pay = IntegerField() <NEW_LINE> _section_call_sign = FixedCharField(3) <NEW_LINE> _kill_count = IntegerField(default=0) <NEW_LINE> def expire_training(self, training): <NEW_LINE> <INDENT> if training in self._trainings: <NEW_LINE> <INDENT> self._trainings.remove(training) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f"{self._rank} {self._lname} was never trained on {training}") <NEW_LINE> <DEDENT> <DEDENT> def train(self, training): <NEW_LINE> <INDENT> self._trainings.append(self.validate_training(training)) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return dict( Service_Number=self._SIN, Rank=self._rank, Last_Name=self._lname, First_Name=self._fname, Division=self.DIVISION, Training_Pay=self._training_pay, Deployment_Pay=self._deployment_pay, Trainings=self._trainings, Call_Sign=self._section_call_sign, Kill_Count=self._kill_count ) <NEW_LINE> <DEDENT> def update_soldier_info(self, call_sign, kills, rank, lname, fname, tpay, dpay): <NEW_LINE> <INDENT> self._section_call_sign = call_sign <NEW_LINE> self._kill_count = kills <NEW_LINE> self._rank = rank <NEW_LINE> self._lname = lname <NEW_LINE> self._fname = fname <NEW_LINE> self._training_pay = tpay <NEW_LINE> self._deployment_pay = dpay | CSOR Class | 6259903994891a1f408b9fca |
class MockTest(DropUploadTestMixin, unittest.TestCase): <NEW_LINE> <INDENT> def test_errors(self): <NEW_LINE> <INDENT> self.basedir = "drop_upload.MockTest.test_errors" <NEW_LINE> self.set_up_grid() <NEW_LINE> errors_dir = os.path.join(self.basedir, "errors_dir") <NEW_LINE> os.mkdir(errors_dir) <NEW_LINE> client = self.g.clients[0] <NEW_LINE> d = client.create_dirnode() <NEW_LINE> def _made_upload_dir(n): <NEW_LINE> <INDENT> self.failUnless(IDirectoryNode.providedBy(n)) <NEW_LINE> upload_dircap = n.get_uri() <NEW_LINE> readonly_dircap = n.get_readonly_uri() <NEW_LINE> self.shouldFail(AssertionError, 'invalid local.directory', 'could not be represented', DropUploader, client, upload_dircap, '\xFF', inotify=fake_inotify) <NEW_LINE> self.shouldFail(AssertionError, 'nonexistent local.directory', 'there is no directory', DropUploader, client, upload_dircap, os.path.join(self.basedir, "Laputa"), inotify=fake_inotify) <NEW_LINE> fp = filepath.FilePath(self.basedir).child('NOT_A_DIR') <NEW_LINE> fp.touch() <NEW_LINE> self.shouldFail(AssertionError, 'non-directory local.directory', 'is not a directory', DropUploader, client, upload_dircap, fp.path, inotify=fake_inotify) <NEW_LINE> self.shouldFail(AssertionError, 'bad upload.dircap', 'does not refer to a directory', DropUploader, client, 'bad', errors_dir, inotify=fake_inotify) <NEW_LINE> self.shouldFail(AssertionError, 'non-directory upload.dircap', 'does not refer to a directory', DropUploader, client, 'URI:LIT:foo', errors_dir, inotify=fake_inotify) <NEW_LINE> self.shouldFail(AssertionError, 'readonly upload.dircap', 'is not a writecap to a directory', DropUploader, client, readonly_dircap, errors_dir, inotify=fake_inotify) <NEW_LINE> <DEDENT> d.addCallback(_made_upload_dir) <NEW_LINE> return d <NEW_LINE> <DEDENT> def test_drop_upload(self): <NEW_LINE> <INDENT> self.inotify = fake_inotify <NEW_LINE> self.basedir = "drop_upload.MockTest.test_drop_upload" <NEW_LINE> return self._test() <NEW_LINE> <DEDENT> def notify_close_write(self, path): <NEW_LINE> <INDENT> self.uploader._notifier.event(path, self.inotify.IN_CLOSE_WRITE) | This can run on any platform, and even if twisted.internet.inotify can't be imported. | 625990398da39b475be04395 |
class describe_token_map_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, ire=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.ire = ire <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.MAP: <NEW_LINE> <INDENT> self.success = {} <NEW_LINE> (_ktype374, _vtype375, _size373) = iprot.readMapBegin() <NEW_LINE> for _i377 in range(_size373): <NEW_LINE> <INDENT> _key378 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> _val379 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> self.success[_key378] = _val379 <NEW_LINE> <DEDENT> iprot.readMapEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ire = InvalidRequestException() <NEW_LINE> self.ire.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('describe_token_map_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.MAP, 0) <NEW_LINE> oprot.writeMapBegin(TType.STRING, TType.STRING, len(self.success)) <NEW_LINE> for kiter380, viter381 in self.success.items(): <NEW_LINE> <INDENT> oprot.writeString(kiter380.encode('utf-8') if sys.version_info[0] == 2 else kiter380) <NEW_LINE> oprot.writeString(viter381.encode('utf-8') if sys.version_info[0] == 2 else viter381) <NEW_LINE> <DEDENT> oprot.writeMapEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ire is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ire', TType.STRUCT, 1) <NEW_LINE> self.ire.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- ire | 625990391f5feb6acb163d98 |
class SambaProtocolEntities(View): <NEW_LINE> <INDENT> samba_username = Input(id='log_userid') <NEW_LINE> samba_password = Input(id='log_password') <NEW_LINE> samba_confirm_password = Input(id='log_verify') | Samba Protocol fields on the shedule configuration page | 6259903907d97122c4217e43 |
class OcrdZipValidator(): <NEW_LINE> <INDENT> def __init__(self, resolver, path_to_zip): <NEW_LINE> <INDENT> self.resolver = resolver <NEW_LINE> self.path_to_zip = path_to_zip <NEW_LINE> self.report = ValidationReport() <NEW_LINE> self.profile_validator = Profile(OCRD_BAGIT_PROFILE_URL, profile=OCRD_BAGIT_PROFILE) <NEW_LINE> <DEDENT> def _validate_profile(self, bag): <NEW_LINE> <INDENT> if not self.profile_validator.validate(bag): <NEW_LINE> <INDENT> raise Exception(str(self.profile_validator.report)) <NEW_LINE> <DEDENT> <DEDENT> def _validate_bag(self, bag, **kwargs): <NEW_LINE> <INDENT> failed = None <NEW_LINE> try: <NEW_LINE> <INDENT> bag.validate(**kwargs) <NEW_LINE> <DEDENT> except BagValidationError as e: <NEW_LINE> <INDENT> failed = e <NEW_LINE> <DEDENT> if failed: <NEW_LINE> <INDENT> raise BagValidationError("%s" % failed) <NEW_LINE> <DEDENT> <DEDENT> def validate(self, skip_checksums=False, skip_bag=False, skip_unzip=False, skip_delete=False, processes=2): <NEW_LINE> <INDENT> if skip_unzip: <NEW_LINE> <INDENT> bagdir = self.path_to_zip <NEW_LINE> skip_delete = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.profile_validator.validate_serialization(self.path_to_zip) <NEW_LINE> bagdir = mkdtemp(prefix=TMP_BAGIT_PREFIX) <NEW_LINE> unzip_file_to_dir(self.path_to_zip, bagdir) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> bag = Bag(bagdir) <NEW_LINE> self._validate_profile(bag) <NEW_LINE> if not skip_bag: <NEW_LINE> <INDENT> self._validate_bag(bag, fast=skip_checksums, processes=processes) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if not skip_delete: <NEW_LINE> <INDENT> rmtree(bagdir) <NEW_LINE> <DEDENT> <DEDENT> return self.report | Validate conformance with BagIt and OCR-D bagit profile.
See:
- https://ocr-d.github.io/ocrd_zip
- https://ocr-d.github.io/bagit-profile.json
- https://ocr-d.github.io/bagit-profile.yml | 6259903971ff763f4b5e8940 |
class WaveformStreamID(QPCore.QPPublicObject): <NEW_LINE> <INDENT> addElements = QPElement.QPElementList(( QPElement.QPElement('networkCode', 'networkCode', 'attribute', unicode, 'basic'), QPElement.QPElement('stationCode', 'stationCode', 'attribute', unicode, 'basic'), QPElement.QPElement('channelCode', 'channelCode', 'attribute', unicode, 'basic'), QPElement.QPElement('locationCode', 'locationCode', 'attribute', unicode, 'basic'), QPElement.QPElement('resourceURI', 'resourceURI', 'cdata', unicode, 'basic'), )) <NEW_LINE> def __init__(self, networkCode=None, stationCode=None, channelCode=None, locationCode=None, resourceURI=None, **kwargs ): <NEW_LINE> <INDENT> super(WaveformStreamID, self).__init__(**kwargs) <NEW_LINE> self.elements.extend(self.addElements) <NEW_LINE> self.networkCode = networkCode <NEW_LINE> self.stationCode = stationCode <NEW_LINE> self.channelCode = channelCode <NEW_LINE> self.locationCode = locationCode <NEW_LINE> self.resourceURI = resourceURI <NEW_LINE> self._initMultipleElements() | QuakePy: WaveformStreamID | 62599039baa26c4b54d5044e |
class Transmitter: <NEW_LINE> <INDENT> streaming = 1 <NEW_LINE> gcode=[] <NEW_LINE> i = 0 <NEW_LINE> port="COM3" <NEW_LINE> board=57600 <NEW_LINE> ser="" <NEW_LINE> def __init__(self, port="COM3",board=57600): <NEW_LINE> <INDENT> self.board=board <NEW_LINE> self.port=port <NEW_LINE> self.filename="" <NEW_LINE> self.gcode=[]; <NEW_LINE> self.streaming = 1 <NEW_LINE> self.i=0 <NEW_LINE> <DEDENT> def readHandShake(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = self.ser.readline() <NEW_LINE> if line!="": <NEW_LINE> <INDENT> print(line) <NEW_LINE> if line.startswith("Y range is from"): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def SendStartPos(self): <NEW_LINE> <INDENT> print("start") <NEW_LINE> self.ser.write('G90\nG20\nG00 X0.000 Y0.000 Z0.000\n') <NEW_LINE> <DEDENT> def openSerial(self): <NEW_LINE> <INDENT> self.ser = serial.Serial(self.port, self.board, timeout=1) <NEW_LINE> print(self.ser.name) <NEW_LINE> <DEDENT> def readGcode(self,file): <NEW_LINE> <INDENT> f = open(file, 'r') <NEW_LINE> self.gcode = f.readlines() <NEW_LINE> f.close() <NEW_LINE> <DEDENT> def readOK(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = self.ser.readline() <NEW_LINE> if "ok" in line: <NEW_LINE> <INDENT> print(line.rstrip()) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def sendGCode(self): <NEW_LINE> <INDENT> if self.i>=len(self.gcode): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(self.gcode[self.i].rstrip()) <NEW_LINE> if len(self.gcode[self.i].strip())>0: <NEW_LINE> <INDENT> self.ser.write(self.gcode[self.i]) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def Transmit(self,file): <NEW_LINE> <INDENT> self.readGcode(file) <NEW_LINE> self.openSerial() <NEW_LINE> self.streaming=self.readHandShake() <NEW_LINE> self.streaming=1 <NEW_LINE> while self.streaming==1: <NEW_LINE> <INDENT> r=self.sendGCode() <NEW_LINE> if r==1: <NEW_LINE> <INDENT> self.readOK() <NEW_LINE> <DEDENT> if r==2: <NEW_LINE> <INDENT> r=1 <NEW_LINE> <DEDENT> self.streaming=r <NEW_LINE> self.i=self.i+1 <NEW_LINE> <DEDENT> print("trans") <NEW_LINE> self.SendStartPos() <NEW_LINE> self.readOK() <NEW_LINE> self.ser.close() | A class to ranmit the data to the dvd plotter | 6259903923e79379d538d6a7 |
class TestValidateBoolTests: <NEW_LINE> <INDENT> def test_bool(self): <NEW_LINE> <INDENT> assert not config._validate_bool(False) <NEW_LINE> assert config._validate_bool(True) <NEW_LINE> <DEDENT> def test_other(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError) as exc: <NEW_LINE> <INDENT> config._validate_bool({'not a': 'bool'}) <NEW_LINE> <DEDENT> assert str(exc.value) == "\"{'not a': 'bool'}\" is not a bool or a string." <NEW_LINE> <DEDENT> def test_string_falsey(self): <NEW_LINE> <INDENT> for s in ('f', 'false', 'n', 'no', 'off', '0'): <NEW_LINE> <INDENT> assert not config._validate_bool(s) <NEW_LINE> <DEDENT> <DEDENT> def test_string_other(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError) as exc: <NEW_LINE> <INDENT> config._validate_bool('oops typo') <NEW_LINE> <DEDENT> assert str(exc.value) == '"oops typo" cannot be interpreted as a boolean value.' <NEW_LINE> <DEDENT> def test_string_truthy(self): <NEW_LINE> <INDENT> for s in ('t', 'true', 'y', 'yes', 'on', '1'): <NEW_LINE> <INDENT> assert config._validate_bool(s) | This class contains tests for the _validate_bool() function. | 6259903910dbd63aa1c71d7b |
class Sensor(models.Model): <NEW_LINE> <INDENT> TEMPERATURE = "T" <NEW_LINE> HUMIDITY = "Hu" <NEW_LINE> PRESSURE = "P" <NEW_LINE> SENSOR_TYPE_CHOICE = [ (TEMPERATURE, "Temperature"), (HUMIDITY, "Humidity"), (PRESSURE, "Pressure"), ] <NEW_LINE> name = models.CharField(max_length=150) <NEW_LINE> timestamp = models.DateTimeField() <NEW_LINE> measure = models.FloatField(blank=True, null=True) <NEW_LINE> sensor_type = models.CharField( max_length=2, choices=SENSOR_TYPE_CHOICE, default=TEMPERATURE, ) <NEW_LINE> device = models.ForeignKey(Device, on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | The sensor and its measurement | 62599039a4f1c619b294f75a |
class CTCP(BaseExtension): <NEW_LINE> <INDENT> DEFAULT_VERSION = "Powered by PyIRC v{}".format(VERSIONSTR) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.version = kwargs.get("ctcp_version", self.DEFAULT_VERSION) <NEW_LINE> <DEDENT> def ctcp(self, target, command, param=None): <NEW_LINE> <INDENT> ctcp = CTCPMessage("PRIVMSG", command.upper(), target, param) <NEW_LINE> line = ctcp.line <NEW_LINE> self.send(line.command, line.params) <NEW_LINE> <DEDENT> def nctcp(self, target, command, param=None): <NEW_LINE> <INDENT> ctcp = CTCPMessage("NOTICE", command.upper(), target, param) <NEW_LINE> line = ctcp.line <NEW_LINE> self.send(line.command, line.params) <NEW_LINE> <DEDENT> @event("commands", "PRIVMSG") <NEW_LINE> def ctcp_in(self, _, line): <NEW_LINE> <INDENT> ctcp = CTCPMessage.parse(line) <NEW_LINE> if not ctcp: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> command = ctcp.command <NEW_LINE> self.call_event("commands_ctcp", command, ctcp, line) <NEW_LINE> <DEDENT> @event("commands", "NOTICE") <NEW_LINE> def nctcp_in(self, _, line): <NEW_LINE> <INDENT> ctcp = CTCPMessage.parse(line) <NEW_LINE> if not ctcp: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> command = ctcp.command <NEW_LINE> self.call_event("commands_ctcp", command, ctcp, line) <NEW_LINE> <DEDENT> @event("commands_ctcp", "PING") <NEW_LINE> def c_ping(self, _, ctcp, line): <NEW_LINE> <INDENT> self.nctcp(ctcp.target, "PING", ctcp.param) <NEW_LINE> <DEDENT> @event("commands_ctcp", "VERSION") <NEW_LINE> def c_version(self, _, ctcp, line): <NEW_LINE> <INDENT> self.nctcp(ctcp.target, "VERSION", self.version) | Add CTCP dispatch functionaltiy.
Hooks may be added by having a commands_ctcp or commands_nctcp
mapping in your base class. | 62599039c432627299fa419f |
class CreateUser(Command): <NEW_LINE> <INDENT> def create_auth0_user(self, name, email, pwd): <NEW_LINE> <INDENT> return requests.post( AUTH0_API_URL, headers={ 'Authorization': 'Bearer {token}'.format(AUTH0_CREATE_USER_JWT), 'Content-Type': 'application/json'}, json={ 'username': name, 'email': email, 'password': pwd}) <NEW_LINE> <DEDENT> def create_app_user(self, name, email): <NEW_LINE> <INDENT> return User.objects.create( full_name=name, email=email) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> email = prompt('email') <NEW_LINE> full_name = prompt('full name') <NEW_LINE> password = prompt_pass('password') <NEW_LINE> if not User.objects.filter(email=email): <NEW_LINE> <INDENT> self.create_auth0_user(full_name, email, password) <NEW_LINE> user = self.create_app_user(full_name, email) <NEW_LINE> user_role = user_datastore.find_or_create_role('USER') <NEW_LINE> user_datastore.add_role_to_user(user, user_role) <NEW_LINE> user.update( inbox_email="{username}@{domain}".format( username=email.split('@')[0], domain=current_app.config.get('EMAIL_DOMAIN'))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("User with email:", email, "already exists") | Creates a user for this app | 625990398a43f66fc4bf3334 |
class SigLenField(FieldLenField): <NEW_LINE> <INDENT> def getfield(self, pkt, s): <NEW_LINE> <INDENT> v = pkt.tls_session.tls_version <NEW_LINE> if v and v < 0x0300: <NEW_LINE> <INDENT> return s, None <NEW_LINE> <DEDENT> return super(SigLenField, self).getfield(pkt, s) <NEW_LINE> <DEDENT> def addfield(self, pkt, s, val): <NEW_LINE> <INDENT> v = pkt.tls_session.tls_version <NEW_LINE> if v and v < 0x0300: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> return super(SigLenField, self).addfield(pkt, s, val) | There is a trick for SSLv2, which uses implicit lengths... | 6259903976d4e153a661db46 |
class AddProjectToClient(generics.CreateAPIView): <NEW_LINE> <INDENT> authentication_classes = (authentication.TokenAuthentication,) <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> serializer_class = EmpS <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> client = self.kwargs['pk'] <NEW_LINE> project = Project.objects.get(pk=int(self.request.POST.get('project', None))) <NEW_LINE> client = Client.objects.get(pk=int(client)) <NEW_LINE> ProjectClient.objects.create(client=client, project=project) <NEW_LINE> return Response(status=200) <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> ProjectClient.objects.all() | Add Project to Client | 6259903907d97122c4217e44 |
class PerformanceCounter(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._count = 0 <NEW_LINE> self._jobs = 0 <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> <DEDENT> def add(self, n): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self._count += n <NEW_LINE> self._jobs += 1 <NEW_LINE> <DEDENT> <DEDENT> def split(self, precise=False): <NEW_LINE> <INDENT> return (self._count if precise else int(self._count)), self._jobs <NEW_LINE> <DEDENT> def reset(self, precise=False): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> c = self._count <NEW_LINE> j = self._jobs <NEW_LINE> self._count = 0 <NEW_LINE> self._jobs = 0 <NEW_LINE> return (c if precise else int(c)), j | This is a simple counter to record execution time and number of jobs. It's unique to each
poller instance, so does not need to be globally syncronised, just locally. | 62599039d164cc617582211b |
class TagCheckBox(QCheckBox): <NEW_LINE> <INDENT> def __init__(self, text, rightPanel): <NEW_LINE> <INDENT> QCheckBox.__init__(self, text) <NEW_LINE> self.rightPanel = rightPanel <NEW_LINE> self.stateChanged.connect(self.changeState) <NEW_LINE> <DEDENT> def changeState(self): <NEW_LINE> <INDENT> self.rightPanel.changeTags(self.text(), self.isChecked()) | Class for the Tag checkboxes that will go in the right panel.
This is only needed as a separate class to implement the changeState correctly. | 625990391d351010ab8f4cc2 |
class TypesUpdateTestCase(BaseTestGenerator): <NEW_LINE> <INDENT> scenarios = [ ('Update type under schema node', dict(url='/browser/type/obj/')) ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.db_name = parent_node_dict["database"][-1]["db_name"] <NEW_LINE> schema_info = parent_node_dict["schema"][-1] <NEW_LINE> self.server_id = schema_info["server_id"] <NEW_LINE> self.db_id = schema_info["db_id"] <NEW_LINE> db_con = database_utils.connect_database(self, utils.SERVER_GROUP, self.server_id, self.db_id) <NEW_LINE> if not db_con['data']["connected"]: <NEW_LINE> <INDENT> raise Exception("Could not connect to database to update a type.") <NEW_LINE> <DEDENT> self.schema_id = schema_info["schema_id"] <NEW_LINE> self.schema_name = schema_info["schema_name"] <NEW_LINE> schema_response = schema_utils.verify_schemas(self.server, self.db_name, self.schema_name) <NEW_LINE> if not schema_response: <NEW_LINE> <INDENT> raise Exception("Could not find the schema to update a type.") <NEW_LINE> <DEDENT> self.type_name = "test_type_put_%s" % (str(uuid.uuid4())[1:8]) <NEW_LINE> self.type_id = types_utils.create_type(self.server, self.db_name, self.schema_name, self.type_name ) <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> type_response = types_utils.verify_type(self.server, self.db_name, self.type_name) <NEW_LINE> if not type_response: <NEW_LINE> <INDENT> raise Exception("Could not find the type to update.") <NEW_LINE> <DEDENT> data = {"id": self.type_id, "description": "this is test comment."} <NEW_LINE> response = self.tester.put( "{0}{1}/{2}/{3}/{4}/{5}".format(self.url, utils.SERVER_GROUP, self.server_id, self.db_id, self.schema_id, self.type_id ), data=json.dumps(data), follow_redirects=True) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> database_utils.disconnect_database(self, self.server_id, self.db_id) | This class will update type under schema node. | 62599039507cdc57c63a5f42 |
class ChangeProposalAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ['content_short', 'actiontype', 'contenttype', 'user', 'document', 'refitem'] | Model:
document = models.ForeignKey(Document) # Document to reference
user = models.ForeignKey(User) # Who proposed it
timestamp = models.DateTimeField(auto_now_add=True) # When
actiontype = models.IntegerField() # Type of change to make [all]
refitem = models.IntegerField() # Number what in the sequence to act on [all]
destination = models.IntegerField() # Destination of moved item, or of new item [move]
content = models.TextField() # Content for new item, or for changed item (blank=same on change) [change, add]
contenttype = models.IntegerField() # Type for new content, or of changed item (0=same on change) [change, add] | 625990390a366e3fb87ddb8e |
@dataclass(frozen=True) <NEW_LINE> class Await(UnlabeledStmt): <NEW_LINE> <INDENT> value: Expr <NEW_LINE> def render(self, indent: int = 0) -> Iterable[Line]: <NEW_LINE> <INDENT> yield Line(f"await {str(self.value)};", indent) <NEW_LINE> <DEDENT> def validate(self) -> None: <NEW_LINE> <INDENT> self.value.validate() | Await ::= [await | when] <Expr>; | 62599039b57a9660fecd2c24 |
class CurrencyField(models.DecimalField): <NEW_LINE> <INDENT> __metaclass__ = models.SubfieldBase <NEW_LINE> def to_python(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return float(super(CurrencyField, self).to_python( value).quantize(Decimal("0.01"))) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return None | Custom field for a proper working with currencies. Using Decimal is not
enough because it returns the value as a normal Python float, which
is problematic when doing a lot of operations. | 6259903907d97122c4217e46 |
class DaosAgentYamlParameters(YamlParameters): <NEW_LINE> <INDENT> def __init__(self, filename, common_yaml): <NEW_LINE> <INDENT> super(DaosAgentYamlParameters, self).__init__( "/run/agent_config/*", filename, None, common_yaml) <NEW_LINE> log_dir = os.environ.get("DAOS_TEST_LOG_DIR", "/tmp") <NEW_LINE> self.runtime_dir = BasicParameter(None, "/var/run/daos_agent") <NEW_LINE> self.log_file = LogParameter(log_dir, None, "daos_agent.log") <NEW_LINE> <DEDENT> def update_log_file(self, name): <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> self.log_file.update(name, "agent_config.log_file") | Defines the daos_agent configuration yaml parameters. | 62599039b5575c28eb71359e |
class ActorFaultManager(object): <NEW_LINE> <INDENT> def __init__(self,parent,actorName,actorDef): <NEW_LINE> <INDENT> self.logger = logging.getLogger(__name__) <NEW_LINE> self.parent = parent <NEW_LINE> self.context = self.parent.context <NEW_LINE> self.actorName = actorName <NEW_LINE> self.proc = None <NEW_LINE> self.started = False <NEW_LINE> <DEDENT> def addClientDevice(self,_device): <NEW_LINE> <INDENT> appName = self.parent.appName <NEW_LINE> actorName = self.actorName <NEW_LINE> self.logger.info('actor.addClientDevice %s.%s' % (appName,actorName)) <NEW_LINE> <DEDENT> def startActor(self,proc): <NEW_LINE> <INDENT> self.proc = proc <NEW_LINE> self.started = True <NEW_LINE> <DEDENT> def stopActor(self,_proc): <NEW_LINE> <INDENT> if not self.started: return <NEW_LINE> self.started = False <NEW_LINE> <DEDENT> def cleanupActor(self): <NEW_LINE> <INDENT> pass | Fault manager for an actor | 62599039596a897236128e48 |
class ConfigurationFileRequest(object): <NEW_LINE> <INDENT> swagger_types = { 'path': 'str', 'last_read_hash': 'str' } <NEW_LINE> attribute_map = { 'path': 'path', 'last_read_hash': 'lastReadHash' } <NEW_LINE> def __init__(self, path=None, last_read_hash=None): <NEW_LINE> <INDENT> self._path = None <NEW_LINE> self._last_read_hash = None <NEW_LINE> self.discriminator = None <NEW_LINE> if path is not None: <NEW_LINE> <INDENT> self.path = path <NEW_LINE> <DEDENT> if last_read_hash is not None: <NEW_LINE> <INDENT> self.last_read_hash = last_read_hash <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return self._path <NEW_LINE> <DEDENT> @path.setter <NEW_LINE> def path(self, path): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_read_hash(self): <NEW_LINE> <INDENT> return self._last_read_hash <NEW_LINE> <DEDENT> @last_read_hash.setter <NEW_LINE> def last_read_hash(self, last_read_hash): <NEW_LINE> <INDENT> self._last_read_hash = last_read_hash <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(ConfigurationFileRequest, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ConfigurationFileRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259903991af0d3eaad3afdc |
class Chassis(base.APIBase): <NEW_LINE> <INDENT> uuid = wtypes.text <NEW_LINE> description = wtypes.text <NEW_LINE> extra = {wtypes.text: wtypes.text} <NEW_LINE> links = [link.Link] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.fields = objects.Chassis.fields.keys() <NEW_LINE> for k in self.fields: <NEW_LINE> <INDENT> setattr(self, k, kwargs.get(k)) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def convert_with_links(cls, rpc_chassis): <NEW_LINE> <INDENT> chassis = Chassis.from_rpc_object(rpc_chassis) <NEW_LINE> chassis.links = [link.Link.make_link('self', pecan.request.host_url, 'chassis', chassis.uuid), link.Link.make_link('bookmark', pecan.request.host_url, 'chassis', chassis.uuid, bookmark=True) ] <NEW_LINE> return chassis | API representation of a chassis.
This class enforces type checking and value constraints, and converts
between the internal object model and the API representation of
a chassis. | 625990398da39b475be04399 |
class CourseComments(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(UserProfile, verbose_name=u'用户') <NEW_LINE> course = models.ForeignKey(Course, verbose_name=u'课程') <NEW_LINE> comments = models.CharField(max_length=200, verbose_name=u'评论') <NEW_LINE> add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = u'课程评论' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.comments | 课程评论 | 6259903916aa5153ce401697 |
class SearchByAddressInputSet(InputSet): <NEW_LINE> <INDENT> def set_Address(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Address', value) <NEW_LINE> <DEDENT> def set_BusinessType(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'BusinessType', value) <NEW_LINE> <DEDENT> def set_ConsumerKey(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ConsumerKey', value) <NEW_LINE> <DEDENT> def set_ConsumerSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ConsumerSecret', value) <NEW_LINE> <DEDENT> def set_Range(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Range', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value) <NEW_LINE> <DEDENT> def set_TokenSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'TokenSecret', value) <NEW_LINE> <DEDENT> def set_Token(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Token', value) <NEW_LINE> <DEDENT> def set_Units(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Units', value) | An InputSet with methods appropriate for specifying the inputs to the SearchByAddress
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 6259903966673b3332c3159f |
class BoundingBox(object): <NEW_LINE> <INDENT> def __init__(self, coordinates: Tuple[int, int, int, int], score: float, color: int): <NEW_LINE> <INDENT> self.coordinates = coordinates <NEW_LINE> self.score = score <NEW_LINE> self.color = color <NEW_LINE> assert color != 0, 'Bounding box should not be related to the background' | A class which represents bounding box.
| 62599039ec188e330fdf9a42 |
class TypedFileField(forms.FileField): <NEW_LINE> <INDENT> default_error_messages = { 'extension': _('File extension is not supported.'), 'mimetype': _('File mimetype is not supported.') } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> ext_whitelist = kwargs.pop('ext_whitelist', []) <NEW_LINE> type_whitelist = kwargs.pop('type_whitelist', []) <NEW_LINE> self.ext_whitelist = [i.lower() for i in ext_whitelist] <NEW_LINE> self.type_whitelist = [i.lower() for i in type_whitelist] <NEW_LINE> self.use_magic = kwargs.pop('use_magic', True) <NEW_LINE> super(TypedFileField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> super(TypedFileField, self).validate(value) <NEW_LINE> if value in self.empty_values: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ext = pathlib.Path(value.name).name.split('.', 1)[-1] <NEW_LINE> if self.ext_whitelist and ext not in self.ext_whitelist: <NEW_LINE> <INDENT> raise forms.ValidationError(self.error_messages['extension']) <NEW_LINE> <DEDENT> if not self.type_whitelist: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if self.use_magic: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mimetype = get_content_type(value) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise forms.ValidationError(self.error_messages['invalid']) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mimetype = value.content_type <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise forms.ValidationError(self.error_messages['invalid']) <NEW_LINE> <DEDENT> <DEDENT> if mimetype not in self.type_whitelist: <NEW_LINE> <INDENT> raise forms.ValidationError(self.error_messages['mimetype']) <NEW_LINE> <DEDENT> return value | Typed FileField which allows to make sure the uploaded file has
the appropriate type.
File type can be verified either by extension and/or mimetype.
This field accepts all the parameters as FileField, however in addition
it accepts some additional parameters as documented below.
Examples
--------
::
TypedFileField(ext_whitelist=['jpg', 'jpeg'],
type_whitelist=['image/jpeg'])
.. warning::
If ``use_magic`` is used, please make sure that ``python-magic``
is installed. This library does not require it by default.
Parameters
----------
ext_whitelist : list, optional
List of allowed file extensions. Note that each extension
should emit the first period. For example for filename
``'example.jpg'``, the allowed extension should be ``'jpg'``.
type_whitelist : list, optional
List of allowed file mimetypes.
use_magic : bool, optional
If ``type_whitelist`` is specified, this boolean determines
whether to use ``python-magic`` (based of top of ``libmagic``)
to determine the mimetypes of files instead of relying
on Django's ``UploadedFile.content_type``.
Django does not take any real care to determine any accurately
the mimetype so it is recommended to leave this parameter
as ``True`` which is the default value. | 62599039507cdc57c63a5f44 |
class MinefieldResponseNackPdu( MinefieldFamilyPdu ): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MinefieldResponseNackPdu, self).__init__() <NEW_LINE> self.minefieldID = EntityID(); <NEW_LINE> self.requestingEntityID = EntityID(); <NEW_LINE> self.requestID = 0 <NEW_LINE> self.numberOfMissingPdus = 0 <NEW_LINE> self.missingPduSequenceNumbers = [] <NEW_LINE> self.pduType = 40 <NEW_LINE> <DEDENT> def serialize(self, outputStream): <NEW_LINE> <INDENT> super( MinefieldResponseNackPdu, self ).serialize(outputStream) <NEW_LINE> self.minefieldID.serialize(outputStream) <NEW_LINE> self.requestingEntityID.serialize(outputStream) <NEW_LINE> outputStream.write_unsigned_byte(self.requestID); <NEW_LINE> outputStream.write_unsigned_byte( len(self.missingPduSequenceNumbers)); <NEW_LINE> for anObj in self.missingPduSequenceNumbers: <NEW_LINE> <INDENT> anObj.serialize(outputStream) <NEW_LINE> <DEDENT> <DEDENT> def parse(self, inputStream): <NEW_LINE> <INDENT> super( MinefieldResponseNackPdu, self).parse(inputStream) <NEW_LINE> self.minefieldID.parse(inputStream) <NEW_LINE> self.requestingEntityID.parse(inputStream) <NEW_LINE> self.requestID = inputStream.read_unsigned_byte(); <NEW_LINE> self.numberOfMissingPdus = inputStream.read_unsigned_byte(); <NEW_LINE> for idx in range(0, self.numberOfMissingPdus): <NEW_LINE> <INDENT> element = null() <NEW_LINE> element.parse(inputStream) <NEW_LINE> self.missingPduSequenceNumbers.append(element) | proivde the means to request a retransmit of a minefield data pdu. Section 7.9.5 COMPLETE | 625990398a349b6b436873ee |
class _CppLintState(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.verbose_level = 1 <NEW_LINE> self.error_count = 0 <NEW_LINE> self.filters = _DEFAULT_FILTERS[:] <NEW_LINE> self._filters_backup = self.filters[:] <NEW_LINE> self.counting = 'total' <NEW_LINE> self.errors_by_category = {} <NEW_LINE> self.quiet = False <NEW_LINE> self.output_format = 'emacs' <NEW_LINE> <DEDENT> def SetOutputFormat(self, output_format): <NEW_LINE> <INDENT> self.output_format = output_format <NEW_LINE> <DEDENT> def SetQuiet(self, quiet): <NEW_LINE> <INDENT> last_quiet = self.quiet <NEW_LINE> self.quiet = quiet <NEW_LINE> return last_quiet <NEW_LINE> <DEDENT> def SetVerboseLevel(self, level): <NEW_LINE> <INDENT> last_verbose_level = self.verbose_level <NEW_LINE> self.verbose_level = level <NEW_LINE> return last_verbose_level <NEW_LINE> <DEDENT> def SetCountingStyle(self, counting_style): <NEW_LINE> <INDENT> self.counting = counting_style <NEW_LINE> <DEDENT> def SetFilters(self, filters): <NEW_LINE> <INDENT> self.filters = _DEFAULT_FILTERS[:] <NEW_LINE> self.AddFilters(filters) <NEW_LINE> <DEDENT> def AddFilters(self, filters): <NEW_LINE> <INDENT> for filt in filters.split(','): <NEW_LINE> <INDENT> clean_filt = filt.strip() <NEW_LINE> if clean_filt: <NEW_LINE> <INDENT> self.filters.append(clean_filt) <NEW_LINE> <DEDENT> <DEDENT> for filt in self.filters: <NEW_LINE> <INDENT> if not (filt.startswith('+') or filt.startswith('-')): <NEW_LINE> <INDENT> raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def BackupFilters(self): <NEW_LINE> <INDENT> self._filters_backup = self.filters[:] <NEW_LINE> <DEDENT> def RestoreFilters(self): <NEW_LINE> <INDENT> self.filters = self._filters_backup[:] <NEW_LINE> <DEDENT> def ResetErrorCounts(self): <NEW_LINE> <INDENT> self.error_count = 0 <NEW_LINE> self.errors_by_category = {} <NEW_LINE> <DEDENT> def IncrementErrorCount(self, category): <NEW_LINE> <INDENT> self.error_count += 1 <NEW_LINE> if self.counting in ('toplevel', 'detailed'): <NEW_LINE> <INDENT> if self.counting != 'detailed': <NEW_LINE> <INDENT> category = category.split('/')[0] <NEW_LINE> <DEDENT> if category not in self.errors_by_category: <NEW_LINE> <INDENT> self.errors_by_category[category] = 0 <NEW_LINE> <DEDENT> self.errors_by_category[category] += 1 <NEW_LINE> <DEDENT> <DEDENT> def PrintErrorCounts(self): <NEW_LINE> <INDENT> for category, count in iteritems(self.errors_by_category): <NEW_LINE> <INDENT> sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) <NEW_LINE> <DEDENT> sys.stdout.write('Total errors found: %d\n' % self.error_count) | Maintains module-wide state.. | 625990396fece00bbacccb57 |
class ComparisonTestFramework(Real_E_CoinTestFramework): <NEW_LINE> <INDENT> def set_test_params(self): <NEW_LINE> <INDENT> self.num_nodes = 2 <NEW_LINE> self.setup_clean_chain = True <NEW_LINE> <DEDENT> def add_options(self, parser): <NEW_LINE> <INDENT> parser.add_option("--testbinary", dest="testbinary", default=os.getenv("BITCOIND", "real_e_coind"), help="real_e_coind binary to test") <NEW_LINE> parser.add_option("--refbinary", dest="refbinary", default=os.getenv("BITCOIND", "real_e_coind"), help="real_e_coind binary to use for reference nodes (if any)") <NEW_LINE> <DEDENT> def setup_network(self): <NEW_LINE> <INDENT> extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes <NEW_LINE> if hasattr(self, "extra_args"): <NEW_LINE> <INDENT> extra_args = self.extra_args <NEW_LINE> <DEDENT> self.add_nodes(self.num_nodes, extra_args, binary=[self.options.testbinary] + [self.options.refbinary] * (self.num_nodes - 1)) <NEW_LINE> self.start_nodes() | Test framework for doing p2p comparison testing
Sets up some real_e_coind binaries:
- 1 binary: test binary
- 2 binaries: 1 test binary, 1 ref binary
- n>2 binaries: 1 test binary, n-1 ref binaries | 6259903982261d6c5273079a |
class TestPagureInit: <NEW_LINE> <INDENT> def test_init(self): <NEW_LINE> <INDENT> url = "http://testing.url" <NEW_LINE> timeout = (5, 20) <NEW_LINE> requests_session = mock.Mock() <NEW_LINE> validator = Pagure(url, requests_session, timeout) <NEW_LINE> assert validator.url == url <NEW_LINE> assert validator.requests_session == requests_session <NEW_LINE> assert validator.timeout == timeout | Test class for `hotness.validators.Pagure.__init__` method. | 625990394e696a045264e6f7 |
class LongBinValidator(LongValidator): <NEW_LINE> <INDENT> def _format(self, value): <NEW_LINE> <INDENT> return self.locale.from_long(value, base=2) <NEW_LINE> <DEDENT> def _convert(self, text): <NEW_LINE> <INDENT> return self.locale.to_long(text, base=2) | A LongValidator which converts and displays as a binary string
and uses the given locale object to perform conversion. | 62599039d4950a0f3b111715 |
class _MetaIxTclApi(type): <NEW_LINE> <INDENT> def __new__(cls, clsname, clsbases, clsdict): <NEW_LINE> <INDENT> members = clsdict.get('__tcl_members__', list()) <NEW_LINE> command = clsdict.get('__tcl_command__', None) <NEW_LINE> for (n,m) in enumerate(members): <NEW_LINE> <INDENT> if not isinstance(m, TclMember): <NEW_LINE> <INDENT> raise RuntimeError('Element #%d of __tcl_members__ is not a ' 'TclMember' % (n+1,)) <NEW_LINE> <DEDENT> def fget(self, cmd=command, m=m): <NEW_LINE> <INDENT> self._ix_get(m) <NEW_LINE> val = self._api.call('%s cget -%s' % (cmd,m.name))[0] <NEW_LINE> return m.type(val) <NEW_LINE> <DEDENT> def fset(self, value, cmd=command, m=m): <NEW_LINE> <INDENT> val = self._api.call('%s config -%s %s' % (cmd,m.name,value)) <NEW_LINE> self._ix_set(m) <NEW_LINE> <DEDENT> attrname = m.attrname <NEW_LINE> if m.attrname is None: <NEW_LINE> <INDENT> attrname = translate_ix_member_name(m.name) <NEW_LINE> <DEDENT> if m.doc is not None: <NEW_LINE> <INDENT> fget.__doc__ = m.doc <NEW_LINE> <DEDENT> fget.__name__ = '_get_%s' % attrname <NEW_LINE> clsdict[fget.__name__] = fget <NEW_LINE> if not m.flags & FLAG_RDONLY: <NEW_LINE> <INDENT> fset.__name__ = '_set_%s' % attrname <NEW_LINE> clsdict[fset.__name__] = fset <NEW_LINE> p = property(fget=fget, fset=fset) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = property(fget=fget) <NEW_LINE> <DEDENT> clsdict[attrname] = p <NEW_LINE> <DEDENT> t = type.__new__(cls, clsname, clsbases, clsdict) <NEW_LINE> return t | Dynamically creates properties, which wraps the IxTclHAL API.
The `__tcl_members__` attribute is a list of tuples of one of the following
forms: TBD
If no attribute name is given, it is derived from the tclMemberName by
replacing every uppercase letter with the lowercase variant prepended with
a '_', eg. 'portMode' will be translated to 'port_mode'.
The generated methods assume that the class provides a method called '_ix_get'
which fetches the properties and stores them into the IxTclHal object. Eg.
for the 'port' command this would be 'port get <ch> <card> <port>'. | 625990391d351010ab8f4cc6 |
class LogsTableModel(QAbstractTableModel): <NEW_LINE> <INDENT> def __init__(self, parent=None, memory_handler=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.records = [] <NEW_LINE> memory_handler.setTarget(self) <NEW_LINE> memory_handler.flush() <NEW_LINE> <DEDENT> def handle(self, record): <NEW_LINE> <INDENT> count = len(self.records) <NEW_LINE> self.beginInsertRows(QModelIndex(), count, count) <NEW_LINE> self.records.append(LogRecord( record.created, record.levelno, record.name, record.getMessage().splitlines()[0])) <NEW_LINE> self.endInsertRows() <NEW_LINE> <DEDENT> def columnCount(self, parent=None, *args, **kwargs): <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> def rowCount(self, parent=None, *args, **kwargs): <NEW_LINE> <INDENT> return len(self.records) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def format_timestamp(record, format): <NEW_LINE> <INDENT> return datetime.fromtimestamp(record.time).strftime(format) <NEW_LINE> <DEDENT> def data(self, index, role=None): <NEW_LINE> <INDENT> row = index.row() <NEW_LINE> col = index.column() <NEW_LINE> record = self.records[row] <NEW_LINE> if role == Qt.DisplayRole: <NEW_LINE> <INDENT> if col == Column.timestamp: <NEW_LINE> <INDENT> return self.format_timestamp(record, DISPLAY_DATETIME_FORMAT) <NEW_LINE> <DEDENT> elif col == Column.level: <NEW_LINE> <INDENT> return logging.getLevelName(record.level) <NEW_LINE> <DEDENT> elif col == Column.module: <NEW_LINE> <INDENT> return record.module <NEW_LINE> <DEDENT> elif col == Column.message: <NEW_LINE> <INDENT> return record.message <NEW_LINE> <DEDENT> <DEDENT> elif role == Qt.ToolTipRole: <NEW_LINE> <INDENT> if col == Column.timestamp: <NEW_LINE> <INDENT> return self.format_timestamp(record, TOOLTIP_DATETIME_FORMAT) <NEW_LINE> <DEDENT> <DEDENT> elif role == Qt.BackgroundRole: <NEW_LINE> <INDENT> if record.level >= logging.ERROR: <NEW_LINE> <INDENT> return ERROR_BRUSH <NEW_LINE> <DEDENT> elif record.level >= logging.WARNING: <NEW_LINE> <INDENT> return WARNING_BRUSH <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def headerData(self, section, orientation, role=None): <NEW_LINE> <INDENT> if role == Qt.DisplayRole and orientation == Qt.Horizontal: <NEW_LINE> <INDENT> return ["Time", "Level", "Module", "Message"][section] | Table model that retrieves log records from Python logging module and
uses them as model data. | 62599039287bf620b6272d96 |
class UserLoginSerializer(JSONWebTokenSerializer): <NEW_LINE> <INDENT> def create(self, validated_data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def validate(self, attrs): <NEW_LINE> <INDENT> credentials = { self.username_field: attrs.get(self.username_field), 'password': attrs.get('password') } <NEW_LINE> if all(credentials.values()): <NEW_LINE> <INDENT> user = authenticate(**credentials) <NEW_LINE> if user: <NEW_LINE> <INDENT> if not user.is_active: <NEW_LINE> <INDENT> raise serializers.ValidationError('账号已冻结,无法登陆') <NEW_LINE> <DEDENT> payload = jwt_payload_handler(user) <NEW_LINE> return { 'token': jwt_encode_handler(payload), 'user': user } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = _('Unable to log in with provided credentials.') <NEW_LINE> raise serializers.ValidationError(msg) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> msg = _('Must include "{username_field}" and "password".') <NEW_LINE> msg = msg.format(username_field=self.username_field) <NEW_LINE> raise serializers.ValidationError(msg) | 用户登陆获取JWT serializer | 625990399b70327d1c57ff2b |
class Ne(NpPairOperator): <NEW_LINE> <INDENT> def __init__(self, feature_left, feature_right): <NEW_LINE> <INDENT> super(Ne, self).__init__(feature_left, feature_right, "not_equal") | Not Equal Operator
Parameters
----------
feature_left : Expression
feature instance
feature_right : Expression
feature instance
Returns
----------
Feature:
bool series indicate `left != right` | 625990398da39b475be0439b |
class V1beta3_Capabilities(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'add': 'list[v1beta3_CapabilityType]', 'drop': 'list[v1beta3_CapabilityType]' } <NEW_LINE> self.attributeMap = { 'add': 'add', 'drop': 'drop' } <NEW_LINE> self.add = None <NEW_LINE> self.drop = None | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599039ac7a0e7691f73694 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.