code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class Generator(): <NEW_LINE> <INDENT> def __init__(self, owner='', history='', cur_yr='', xl_opts='', field_config='', mong_opts='', **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.owner = owner.lower() <NEW_LINE> self.history = history if history else 1 <NEW_LINE> self.cur_yr = cur_yr if cur_yr else 2018 <NEW_LINE> self.filepath = os.path.expanduser(xl_opts['filepath']) <NEW_LINE> self.sheetname = xl_opts['sheetname'] <NEW_LINE> self.field_config = field_config <NEW_LINE> self.dbname = mong_opts['dbname'] if mong_opts['dbname'] else 'ccsdm' <NEW_LINE> self.host = mong_opts['host'] if mong_opts['host'] else 'localhost' <NEW_LINE> self.port = mong_opts['port'] if mong_opts['port'] else 27017 <NEW_LINE> self.months = self._get_stringified_months() <NEW_LINE> self.fin_months = self._get_fin_months() <NEW_LINE> self.qconfig = {} <NEW_LINE> self.aggpipes = [] <NEW_LINE> self.xl_writer = None <NEW_LINE> self.mong_writer = None <NEW_LINE> self.uniq_fields = { 'fiscal_year_id', 'fiscal_quarter_id', 'fiscal_period_id', 'fiscal_month_id', 'fiscal_week_id', 'sales_level_4', 'sales_level_5', 'sales_level_6', 'rm_name', 'od_name', 'segment', 'country', 'region', 'state', 'prod_serv', 'arch1', 'arch2', 'tech_name1', 'tech_name2', 'tech_name3' } <NEW_LINE> self.val_fields = set() <NEW_LINE> <DEDENT> def expunge_all_existing_data(self): <NEW_LINE> <INDENT> self._warn_user() <NEW_LINE> self._expunge() <NEW_LINE> return <NEW_LINE> <DEDENT> def _warn_user(self): <NEW_LINE> <INDENT> recs_planned = self.mong_writer.how_many_docs({}) <NEW_LINE> print("[Info]: {} row(s) existing! {} row(s) planned for trashing!?!".format( self.mong_writer.recs_before(), recs_planned)) <NEW_LINE> return <NEW_LINE> <DEDENT> def _expunge(self): <NEW_LINE> <INDENT> self.mong_writer.trash_many({}) <NEW_LINE> return <NEW_LINE> <DEDENT> def _get_stringified_months(self): <NEW_LINE> <INDENT> months = [] <NEW_LINE> for i in range(1, 13): <NEW_LINE> <INDENT> months.append(str(i).zfill(2)) <NEW_LINE> <DEDENT> return months <NEW_LINE> <DEDENT> def _get_fin_months(self): <NEW_LINE> <INDENT> years = [] <NEW_LINE> for h in range(self.history): <NEW_LINE> <INDENT> years.append(self.cur_yr-h) <NEW_LINE> <DEDENT> return [ str(y) + m for y in years for m in self.months ] <NEW_LINE> <DEDENT> def set_query_config(self): <NEW_LINE> <INDENT> self._set_query_config_for_owner() <NEW_LINE> return <NEW_LINE> <DEDENT> def _set_query_config_for_owner(self): <NEW_LINE> <INDENT> self.qconfig = GT.get_query_config_for_owner(self.owner) <NEW_LINE> return
|
Parent class for the generators
|
62599017d164cc6175821ce2
|
class GenreQuestion(QuestionTemplate): <NEW_LINE> <INDENT> optional_opening = Question(Pos("WP") + Lemma("be") + Question(Pos("DT"))) <NEW_LINE> regex = optional_opening + Question(Lemma("music")) + Lemma("genre") + Pos("IN") + Band() + Question(Pos(".")) <NEW_LINE> def interpret(self, match): <NEW_LINE> <INDENT> genre = MusicGenreOf(match.band) <NEW_LINE> label = LabelOf(genre) <NEW_LINE> return label, "enum"
|
Regex for questions about the genre of a band.
Ex: "What is the music genre of Gorillaz?"
"Music genre of Radiohead"
|
625990176fece00bbaccc71c
|
class CustomController(Controller): <NEW_LINE> <INDENT> def __init__(self, flask_web_app, available_services, config): <NEW_LINE> <INDENT> Controller.__init__(self, flask_web_app, available_services, config) <NEW_LINE> self.exposed_methods += [ self.custom_route_example, self.custom_route_exception_example ] <NEW_LINE> self._init_exposed_methods() <NEW_LINE> <DEDENT> @route("/custom-route/example", methods=['GET']) <NEW_LINE> def custom_route_example(self): <NEW_LINE> <INDENT> return jsonify({"message":"HELLO"}) <NEW_LINE> <DEDENT> @route("/custom-route/exception-example", methods=['GET']) <NEW_LINE> def custom_route_exception_example(self): <NEW_LINE> <INDENT> raise InvalidRequest("Raising exception as a test", status_code=505)
|
Controller for /custom-route/ URL.
This is a proof-of-concept controller. Modify it accordingly.
|
62599017be8e80087fbbfdd8
|
class Site(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.access_points = {} <NEW_LINE> self.logger = logging.getLogger("dyko") <NEW_LINE> try: <NEW_LINE> <INDENT> from logging import NullHandler <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> class NullHandler(logging.Handler): <NEW_LINE> <INDENT> def emit(self, record): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.logger.addHandler(NullHandler()) <NEW_LINE> <DEDENT> def register(self, name, access_point): <NEW_LINE> <INDENT> if name in self.access_points: <NEW_LINE> <INDENT> raise RuntimeError( "Site already has an access point named %r." % name) <NEW_LINE> <DEDENT> self.access_points[name] = access_point <NEW_LINE> access_point.bind(self, name) <NEW_LINE> <DEDENT> def view(self, access_point_name, aliases=None, request=None, order_by=None, select_range=None, distinct=False, aggregate=None, query=None): <NEW_LINE> <INDENT> access_point = self.access_points[access_point_name] <NEW_LINE> if aliases is None: <NEW_LINE> <INDENT> aliases = {"": "*"} <NEW_LINE> <DEDENT> if query is None: <NEW_LINE> <INDENT> chain = [] <NEW_LINE> aliases = dict(((value, key) for key, value in aliases.items())) <NEW_LINE> request = make_request(request) <NEW_LINE> request = _translate_request(request, aliases) <NEW_LINE> aliases = dict(((value, key) for key, value in aliases.items())) <NEW_LINE> chain.append(QuerySelect(aliases)) <NEW_LINE> chain.append(QueryFilter(request)) <NEW_LINE> if distinct: <NEW_LINE> <INDENT> chain.append(QueryDistinct()) <NEW_LINE> <DEDENT> if order_by is not None: <NEW_LINE> <INDENT> chain.append(QueryOrder(order_by)) <NEW_LINE> <DEDENT> if aggregate is not None: <NEW_LINE> <INDENT> chain.append(QueryAggregate(aggregate)) <NEW_LINE> <DEDENT> if select_range is not None: <NEW_LINE> <INDENT> if hasattr(select_range, "__iter__"): <NEW_LINE> <INDENT> select_range = slice(*select_range) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> select_range = slice(select_range) <NEW_LINE> <DEDENT> chain.append(QueryRange(select_range)) <NEW_LINE> <DEDENT> query = QueryChain(chain) <NEW_LINE> <DEDENT> query.validate(access_point.properties) <NEW_LINE> for line in access_point.view(query): <NEW_LINE> <INDENT> for prop_name in [name for name in line if name.startswith("__")]: <NEW_LINE> <INDENT> line.pop(prop_name) <NEW_LINE> <DEDENT> yield line <NEW_LINE> <DEDENT> <DEDENT> def from_repr(self, access_point_name, repr, default=DEFAULT_PARAMETER): <NEW_LINE> <INDENT> access_point = self.access_points[access_point_name] <NEW_LINE> return access_point.loader_from_reference_repr(repr)(None)[0] <NEW_LINE> <DEDENT> create = _delegate_to_acces_point("create") <NEW_LINE> delete = _delegate_to_acces_point("delete") <NEW_LINE> delete_many = _delegate_to_acces_point("delete_many", True) <NEW_LINE> open = _delegate_to_acces_point("open", True) <NEW_LINE> search = _delegate_to_acces_point("search", True) <NEW_LINE> save = _delegate_to_acces_point("save")
|
Kalamar site.
|
625990179b70327d1c57fae8
|
class PostOwnStatus(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self,request,view,obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.user_profile.id == request.user.id
|
Allow users to update their own status.
|
62599017d18da76e235b7801
|
@implementer(IRenderable) <NEW_LINE> class _ComparisonRenderer(util.ComparableMixin, object): <NEW_LINE> <INDENT> compare_attrs = ('fn',) <NEW_LINE> def __init__(self, v1, v2, cstr, comparator): <NEW_LINE> <INDENT> self.v1, self.v2, self.comparator, self.cstr = v1, v2, comparator, cstr <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def getRenderingFor(self, props): <NEW_LINE> <INDENT> v1 = yield props.render(self.v1) <NEW_LINE> v2 = yield props.render(self.v2) <NEW_LINE> defer.returnValue(self.comparator(v1, v2)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%r %r %r' % (self.v1, self.cstr, self.v2)
|
An instance of this class renders a comparison given by a comparator
function with v1 and v2
|
62599017462c4b4f79dbc770
|
class AnalyzerRuntimeError(BaseCmdlrException): <NEW_LINE> <INDENT> pass
|
Other analyzer error.
|
6259901721a7993f00c66ce3
|
class QueueWriter(Thread): <NEW_LINE> <INDENT> def __init__(self, output_queue, parse=True, pace10=1, factor=2): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.output_queue = output_queue <NEW_LINE> self.pace10 = pace10 <NEW_LINE> self.factor = factor <NEW_LINE> self.parse = parse <NEW_LINE> self.should_run = True <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> total_count = 0 <NEW_LINE> random_log_line = log_writer.random_log_line_maker('HTTP_slow', factor=self.factor) <NEW_LINE> while self.should_run: <NEW_LINE> <INDENT> line_count_second10 = 0 <NEW_LINE> start_time_second10 = time.time() <NEW_LINE> while self.should_run and line_count_second10 < self.pace10 and time.time() - start_time_second10 < 0.1: <NEW_LINE> <INDENT> if self.parse: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> log_line = reader.parse_line( random_log_line(date=datetime.datetime.utcnow().strftime('[%d/%b/%Y:%X +0000]'))) <NEW_LINE> <DEDENT> except reader.HTTPFormatError as e: <NEW_LINE> <INDENT> d.displayer.log(self, d.LogLevel.ERROR, e.message) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> log_line = random_log_line(date=datetime.datetime.utcnow().strftime('[%d/%b/%Y:%X +0000]')) <NEW_LINE> <DEDENT> self.output_queue.put(log_line) <NEW_LINE> line_count_second10 += 1 <NEW_LINE> <DEDENT> delta = time.time() - start_time_second10 <NEW_LINE> if delta < 0.1 and line_count_second10 == self.pace10: <NEW_LINE> <INDENT> time.sleep(0.1 - delta) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('putting operations are too slow, reduce pace10, ' 'lines putted this 10th of second:', line_count_second10) <NEW_LINE> <DEDENT> total_count += line_count_second10
|
Used to fill the Statistician queue, to simulate a fast reading and compare the reading speed with or without parsing.
Note
----
pace10 is the pace for 100ms, ie ``10*pace10`` entries are put in the queue every second.
|
625990178c3a8732951f72ca
|
class S(HtmlElement): <NEW_LINE> <INDENT> class PropTypes: <NEW_LINE> <INDENT> role: str
|
Implement the ``s`` HTML tag.
|
6259901721a7993f00c66ce5
|
class ReplaceFooterWithStaticViewlets(UpgradeStep): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.install_upgrade_profile() <NEW_LINE> self.remove_footer_layer() <NEW_LINE> self.remove_footer_portlets() <NEW_LINE> self.remove_footer_portlet_managers() <NEW_LINE> <DEDENT> def remove_footer_layer(self): <NEW_LINE> <INDENT> self.remove_broken_browserlayer('ftw.footer', 'IFtwFooterLayer') <NEW_LINE> <DEDENT> def remove_footer_portlets(self): <NEW_LINE> <INDENT> assignments = (IAnnotations(self.portal) .get('plone.portlets.contextassignments', {})) <NEW_LINE> assignments.pop('ftw.footer.column1', None) <NEW_LINE> assignments.pop('ftw.footer.column2', None) <NEW_LINE> assignments.pop('ftw.footer.column3', None) <NEW_LINE> assignments.pop('ftw.footer.column4', None) <NEW_LINE> <DEDENT> def remove_footer_portlet_managers(self): <NEW_LINE> <INDENT> self.remove_broken_portlet_manager('ftw.footer.column1') <NEW_LINE> self.remove_broken_portlet_manager('ftw.footer.column2') <NEW_LINE> self.remove_broken_portlet_manager('ftw.footer.column3') <NEW_LINE> self.remove_broken_portlet_manager('ftw.footer.column4')
|
Replace footer with static viewlets.
|
62599017be8e80087fbbfddc
|
class PROCESS_INFORMATION(Structure): <NEW_LINE> <INDENT> _fields_ = [ ("hProcess", HANDLE), ("hThread", HANDLE), ("dwProcessId", DWORD), ("dwThreadId", DWORD), ]
|
PROCESS_INFORMATION receives its information
after the target process has been successfully
started.
|
625990176fece00bbaccc720
|
class ForeignBranchFormatTests(TestCaseWithTransport): <NEW_LINE> <INDENT> branch_format = None <NEW_LINE> def test_initialize(self): <NEW_LINE> <INDENT> bzrdir = self.make_bzrdir('dir') <NEW_LINE> self.assertRaises(IncompatibleFormat, self.branch_format.initialize, bzrdir) <NEW_LINE> <DEDENT> def test_get_format_description_type(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.branch_format.get_format_description(), str) <NEW_LINE> <DEDENT> def test_network_name(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.branch_format.network_name(), str)
|
Basic tests for foreign branch format objects.
|
6259901756b00c62f0fb3629
|
class ApiRequestConfig(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Path = None <NEW_LINE> self.Method = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Path = params.get("Path") <NEW_LINE> self.Method = params.get("Method") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
|
api请求配置
|
62599017d18da76e235b7803
|
class BaseSocialModel(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def url(self): <NEW_LINE> <INDENT> current_site = Site.objects.get_current() <NEW_LINE> return "http://{0}/{1}/".format(current_site.domain, base62.encode(self.pk)) <NEW_LINE> <DEDENT> def facebook_og_info(self): <NEW_LINE> <INDENT> raise NotImplementedError("This has not been implemented") <NEW_LINE> <DEDENT> def create_social_message(self, provider): <NEW_LINE> <INDENT> raise NotImplementedError("This has not been implemented")
|
This is an abstract model to be inherited by the main "object" being used in feeds on a social media application.
It expects that object to override the methods below.
|
625990178c3a8732951f72ce
|
class OCNOSBasicModeError(OCNOSError): <NEW_LINE> <INDENT> pass
|
Exception class when failed to set basic mode to trim
|
625990179b70327d1c57faee
|
class DecoderBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, d_model, d_inner_hid, n_head, dropout=0.1): <NEW_LINE> <INDENT> super(DecoderBlock, self).__init__() <NEW_LINE> self.slf_attn = MultiHeadedAttention(head_count=n_head, model_dim=d_model, dropout=dropout) <NEW_LINE> self.ctx_attn = MultiHeadedAttention(head_count=n_head, model_dim=d_model, dropout=dropout) <NEW_LINE> self.pos_ffn = PositionwiseFeedForward(size=d_model, hidden_size=d_inner_hid) <NEW_LINE> self.layer_norm_1 = LayerNorm(d_model) <NEW_LINE> self.layer_norm_2 = LayerNorm(d_model) <NEW_LINE> self.dropout = nn.Dropout(dropout) <NEW_LINE> <DEDENT> def compute_cache(self, enc_output): <NEW_LINE> <INDENT> return self.ctx_attn.compute_cache(enc_output, enc_output) <NEW_LINE> <DEDENT> def forward(self, dec_input, enc_output, slf_attn_mask=None, dec_enc_attn_mask=None, enc_attn_cache=None, self_attn_cache=None): <NEW_LINE> <INDENT> input_batch, input_len, _ = dec_input.size() <NEW_LINE> contxt_batch, contxt_len, _ = enc_output.size() <NEW_LINE> input_norm = self.layer_norm_1(dec_input) <NEW_LINE> all_input = input_norm <NEW_LINE> query, _, self_attn_cache = self.slf_attn(all_input, all_input, input_norm, mask=slf_attn_mask, self_attn_cache=self_attn_cache) <NEW_LINE> query = self.dropout(query) + dec_input <NEW_LINE> query_norm = self.layer_norm_2(query) <NEW_LINE> mid, attn, enc_attn_cache = self.ctx_attn(enc_output, enc_output, query_norm, mask=dec_enc_attn_mask, enc_attn_cache=enc_attn_cache) <NEW_LINE> output = self.pos_ffn(self.dropout(mid) + query) <NEW_LINE> return output, attn, self_attn_cache, enc_attn_cache
|
Compose with three layers
|
625990175166f23b2e24413f
|
class CacheEntry(object): <NEW_LINE> <INDENT> __slots__ = [ 'dirty', 'inode', 'blockno', 'last_write', 'size', 'pos', 'fh', 'removed' ] <NEW_LINE> def __init__(self, inode, blockno, filename, mode='w+b'): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.fh = open(filename, mode, 0) <NEW_LINE> self.dirty = False <NEW_LINE> self.inode = inode <NEW_LINE> self.blockno = blockno <NEW_LINE> self.last_write = 0 <NEW_LINE> self.pos = self.fh.tell() <NEW_LINE> self.size = os.fstat(self.fh.fileno()).st_blocks * 512 <NEW_LINE> <DEDENT> def read(self, size=None): <NEW_LINE> <INDENT> buf = self.fh.read(size) <NEW_LINE> self.pos += len(buf) <NEW_LINE> return buf <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> self.fh.flush() <NEW_LINE> <DEDENT> def seek(self, off): <NEW_LINE> <INDENT> if self.pos != off: <NEW_LINE> <INDENT> self.fh.seek(off) <NEW_LINE> self.pos = off <NEW_LINE> <DEDENT> <DEDENT> def tell(self): <NEW_LINE> <INDENT> return self.pos <NEW_LINE> <DEDENT> def truncate(self, size=None): <NEW_LINE> <INDENT> self.dirty = True <NEW_LINE> self.fh.truncate(size) <NEW_LINE> if size is None: <NEW_LINE> <INDENT> if self.pos < self.size: <NEW_LINE> <INDENT> self.size = self.pos <NEW_LINE> <DEDENT> <DEDENT> elif size < self.size: <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> <DEDENT> def write(self, buf): <NEW_LINE> <INDENT> self.dirty = True <NEW_LINE> self.fh.write(buf) <NEW_LINE> self.pos += len(buf) <NEW_LINE> self.size = max(self.pos, self.size) <NEW_LINE> self.last_write = time.time() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.fh.close() <NEW_LINE> <DEDENT> def unlink(self): <NEW_LINE> <INDENT> os.unlink(self.fh.name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('<%sCacheEntry, inode=%d, blockno=%d>' % ('Dirty ' if self.dirty else '', self.inode, self.blockno))
|
An element in the block cache
Attributes:
-----------
:dirty: entry has been changed since it was last uploaded.
:size: current file size
:pos: current position in file
|
62599017796e427e5384f4ee
|
class DomainAffiliationManager(ObjectManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ObjectManager.__init__(self) <NEW_LINE> self.getters.update({ 'default' : 'get_general', 'domain' : 'get_foreign_key', 'may_log_me_in' : 'get_general', 'user' : 'get_foreign_key', 'username' : 'get_general', }) <NEW_LINE> self.setters.update({ 'default' : 'set_general', 'domain' : 'set_foreign_key', 'may_log_me_in' : 'set_general', 'user' : 'set_foreign_key', 'username' : 'set_general', }) <NEW_LINE> self.my_django_model = facade.models.DomainAffiliation <NEW_LINE> <DEDENT> @service_method <NEW_LINE> def create(self, auth_token, user, domain, username, optional_attributes = None): <NEW_LINE> <INDENT> user_object = self._find_by_id(user, facade.models.User) <NEW_LINE> domain_object = self._find_by_id(domain, facade.models.Domain) <NEW_LINE> o = self.my_django_model(user=user_object, domain=domain_object, username=username) <NEW_LINE> if optional_attributes is not None: <NEW_LINE> <INDENT> for attribute in ['default', 'may_log_me_in']: <NEW_LINE> <INDENT> if attribute in optional_attributes: <NEW_LINE> <INDENT> setattr(o, attribute, optional_attributes[attribute]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> o.save() <NEW_LINE> self.authorizer.check_create_permissions(auth_token, o) <NEW_LINE> return o
|
Manage domain affiliations in the Power Reg system
|
625990179b70327d1c57faf0
|
class RPolynom(RPackage): <NEW_LINE> <INDENT> homepage = "https://cloud.r-project.org/package=polynom" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/polynom_1.4-0.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/polynom" <NEW_LINE> version('1.4-0', sha256='c5b788b26f7118a18d5d8e7ba93a0abf3efa6603fa48603c70ed63c038d3d4dd')
|
A collection of functions to implement a class for univariate polynomial
manipulations.
|
62599017462c4b4f79dbc778
|
class ComputeDate(FSMAction): <NEW_LINE> <INDENT> def execute(self, context, obj): <NEW_LINE> <INDENT> daysOld = context['daysOld'] <NEW_LINE> context['backupDate'] = datetime.datetime.utcnow() - datetime.timedelta(days=daysOld) <NEW_LINE> return 'ok'
|
Compute a stable backup date to use across continuations.
|
625990175166f23b2e244141
|
class GetValueTests(unittest.TestCase, AssertIsMixin): <NEW_LINE> <INDENT> def assertNotFound(self, item, key): <NEW_LINE> <INDENT> self.assertIs(_get_value(item, key), _NOT_FOUND) <NEW_LINE> <DEDENT> def test_dictionary__key_present(self): <NEW_LINE> <INDENT> item = {"foo": "bar"} <NEW_LINE> self.assertEqual(_get_value(item, "foo"), "bar") <NEW_LINE> <DEDENT> def test_dictionary__callable_not_called(self): <NEW_LINE> <INDENT> def foo_callable(self): <NEW_LINE> <INDENT> return "bar" <NEW_LINE> <DEDENT> item = {"foo": foo_callable} <NEW_LINE> self.assertNotEqual(_get_value(item, "foo"), "bar") <NEW_LINE> self.assertTrue(_get_value(item, "foo") is foo_callable) <NEW_LINE> <DEDENT> def test_dictionary__key_missing(self): <NEW_LINE> <INDENT> item = {} <NEW_LINE> self.assertNotFound(item, "missing") <NEW_LINE> <DEDENT> def test_dictionary__attributes_not_checked(self): <NEW_LINE> <INDENT> item = {1: 2, 3: 4} <NEW_LINE> attr_name = "__len__" <NEW_LINE> self.assertEqual(getattr(item, attr_name)(), 2) <NEW_LINE> self.assertNotFound(item, attr_name) <NEW_LINE> <DEDENT> def test_dictionary__dict_subclass(self): <NEW_LINE> <INDENT> class DictSubclass(dict): pass <NEW_LINE> item = DictSubclass() <NEW_LINE> item["foo"] = "bar" <NEW_LINE> self.assertEqual(_get_value(item, "foo"), "bar") <NEW_LINE> <DEDENT> def test_object__attribute_present(self): <NEW_LINE> <INDENT> item = SimpleObject() <NEW_LINE> self.assertEqual(_get_value(item, "foo"), "bar") <NEW_LINE> <DEDENT> def test_object__attribute_missing(self): <NEW_LINE> <INDENT> item = SimpleObject() <NEW_LINE> self.assertNotFound(item, "missing") <NEW_LINE> <DEDENT> def test_object__attribute_is_callable(self): <NEW_LINE> <INDENT> item = SimpleObject() <NEW_LINE> self.assertEqual(_get_value(item, "foo_callable"), "called...") <NEW_LINE> <DEDENT> def test_object__non_built_in_type(self): <NEW_LINE> <INDENT> item = datetime(2012, 1, 2) <NEW_LINE> self.assertEqual(_get_value(item, "day"), 2) <NEW_LINE> <DEDENT> def test_object__dict_like(self): <NEW_LINE> <INDENT> item = DictLike() <NEW_LINE> self.assertEqual(item["foo"], "bar") <NEW_LINE> self.assertNotFound(item, "foo") <NEW_LINE> <DEDENT> def test_built_in_type__integer(self): <NEW_LINE> <INDENT> class MyInt(int): pass <NEW_LINE> cust_int = MyInt(10) <NEW_LINE> pure_int = 10 <NEW_LINE> self.assertEqual(cust_int.__neg__(), -10) <NEW_LINE> self.assertEqual(pure_int.__neg__(), -10) <NEW_LINE> self.assertEqual(_get_value(cust_int, '__neg__'), -10) <NEW_LINE> self.assertNotFound(pure_int, '__neg__') <NEW_LINE> <DEDENT> def test_built_in_type__string(self): <NEW_LINE> <INDENT> class MyStr(str): pass <NEW_LINE> item1 = MyStr('abc') <NEW_LINE> item2 = 'abc' <NEW_LINE> self.assertEqual(item1.upper(), 'ABC') <NEW_LINE> self.assertEqual(item2.upper(), 'ABC') <NEW_LINE> self.assertEqual(_get_value(item1, 'upper'), 'ABC') <NEW_LINE> self.assertNotFound(item2, 'upper') <NEW_LINE> <DEDENT> def test_built_in_type__list(self): <NEW_LINE> <INDENT> class MyList(list): pass <NEW_LINE> item1 = MyList([1, 2, 3]) <NEW_LINE> item2 = [1, 2, 3] <NEW_LINE> self.assertEqual(item1.pop(), 3) <NEW_LINE> self.assertEqual(item2.pop(), 3) <NEW_LINE> self.assertEqual(_get_value(item1, 'pop'), 2) <NEW_LINE> self.assertNotFound(item2, 'pop')
|
Test context._get_value().
|
625990170a366e3fb87dd764
|
class ImbalancedDatasetSampler(torch.utils.data.sampler.Sampler): <NEW_LINE> <INDENT> def __init__(self, dataset, indices=None, num_samples=None, callback_get_label=None): <NEW_LINE> <INDENT> self.indices = list(range(len(dataset))) if indices is None else indices <NEW_LINE> self.callback_get_label = callback_get_label <NEW_LINE> self.num_samples = len(self.indices) if num_samples is None else num_samples <NEW_LINE> label_to_count = {} <NEW_LINE> for idx in self.indices: <NEW_LINE> <INDENT> label = self._get_label(dataset, idx) <NEW_LINE> if label in label_to_count: <NEW_LINE> <INDENT> label_to_count[label] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label_to_count[label] = 1 <NEW_LINE> <DEDENT> <DEDENT> weights = [1.0 / label_to_count[self._get_label(dataset, idx)] for idx in self.indices] <NEW_LINE> self.weights = torch.DoubleTensor(weights) <NEW_LINE> <DEDENT> def _get_label(self, dataset, idx): <NEW_LINE> <INDENT> if isinstance(dataset, torchvision.datasets.MNIST): <NEW_LINE> <INDENT> return dataset.train_labels[idx].item() <NEW_LINE> <DEDENT> elif isinstance(dataset, torchvision.datasets.ImageFolder): <NEW_LINE> <INDENT> return dataset.imgs[idx][1] <NEW_LINE> <DEDENT> elif isinstance(dataset, torch.utils.data.Subset): <NEW_LINE> <INDENT> return dataset.dataset.imgs[idx][1] <NEW_LINE> <DEDENT> elif self.callback_get_label: <NEW_LINE> <INDENT> return self.callback_get_label(dataset, idx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return (self.indices[i] for i in torch.multinomial( self.weights, self.num_samples, replacement=True)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.num_samples <NEW_LINE> <DEDENT> def set_epoch(self, epoch: int): <NEW_LINE> <INDENT> pass
|
Samples elements randomly from a given list of indices for imbalanced dataset
Arguments:
indices (list, optional): a list of indices
num_samples (int, optional): number of samples to draw
callback_get_label func: a callback-like function which takes two arguments - dataset and index
|
62599017be8e80087fbbfde2
|
class Ghost(CastleKilmereMember): <NEW_LINE> <INDENT> def __init__(self, name: str, birthyear: int, sex: str, year_of_death: int, house: str = None): <NEW_LINE> <INDENT> super().__init__(name, birthyear, sex) <NEW_LINE> self.year_of_death = year_of_death <NEW_LINE> if house is not None: <NEW_LINE> <INDENT> self.house = house <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def age(self): <NEW_LINE> <INDENT> now = datetime.datetime.now().year <NEW_LINE> return now - self.birthyear <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return (f"{self.__class__.__name__}({self._name}, " f"birthyear: {self.birthyear}, year of death: {self.year_of_death})")
|
Creates a Castle Kilmere ghost
|
625990175e10d32532ce3fbf
|
class Spectrum1DCollection(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.spectra = list() <NEW_LINE> self.dispersion = None <NEW_LINE> <DEDENT> def append(self, spectrum): <NEW_LINE> <INDENT> self.spectra.append(new_spectrum.spectrum1DBase) <NEW_LINE> <DEDENT> def len(self): <NEW_LINE> <INDENT> return len(self.spectra) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dispersion(self): <NEW_LINE> <INDENT> return self.dispersion <NEW_LINE> <DEDENT> @dispersion.setter <NEW_LINE> def dispersion(self, new_dispersion): <NEW_LINE> <INDENT> if is_instance(new_dispersion, Spectrum1D): <NEW_LINE> <INDENT> self.dispersion = new_dispersion.dispersion <NEW_LINE> <DEDENT> elif is_instance(new_dispersion, list): <NEW_LINE> <INDENT> self.dispersion = np.array(new_dispersion) <NEW_LINE> <DEDENT> elif is_instance(new_dispersion, np.array): <NEW_LINE> <INDENT> self.dispersion = new_dispersion <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("The dispersion specified could is not a known type. Should be a list, a numpy array, or a Spectrum1D object.")
|
A collection object for spectra that share the same dispersion information.
|
625990176fece00bbaccc726
|
class RandomSamplerWithoutReplacement(_BaseSampler): <NEW_LINE> <INDENT> def __init__(self, data_source, seed): <NEW_LINE> <INDENT> super(RandomSamplerWithoutReplacement, self).__init__(seed) <NEW_LINE> self.data_source = data_source <NEW_LINE> self.draws = list(range(len(self.data_source))) <NEW_LINE> <DEDENT> def _generate_draws(self): <NEW_LINE> <INDENT> draws = copy.deepcopy(self.draws) <NEW_LINE> self.rand_engine.shuffle(draws) <NEW_LINE> return draws <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._generate_draws()) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.data_source)
|
Permute the list of items
|
625990178c3a8732951f72d2
|
class Conf(object): <NEW_LINE> <INDENT> def __init__(self, hr_init=75, hr_max=200, hr_min=25, qrs_width=0.1, qrs_thr_init=0.13, qrs_thr_min=0, ref_period=0.2, t_inspect_period=0.36): <NEW_LINE> <INDENT> if hr_min < 0: <NEW_LINE> <INDENT> raise ValueError("'hr_min' must be <= 0") <NEW_LINE> <DEDENT> if not hr_min < hr_init < hr_max: <NEW_LINE> <INDENT> raise ValueError("'hr_min' < 'hr_init' < 'hr_max' must be True") <NEW_LINE> <DEDENT> if qrs_thr_init < qrs_thr_min: <NEW_LINE> <INDENT> raise ValueError("qrs_thr_min must be <= qrs_thr_init") <NEW_LINE> <DEDENT> self.hr_init = hr_init <NEW_LINE> self.hr_max = hr_max <NEW_LINE> self.hr_min = hr_min <NEW_LINE> self.qrs_width = qrs_width <NEW_LINE> self.qrs_radius = self.qrs_width / 2 <NEW_LINE> self.qrs_thr_init = qrs_thr_init <NEW_LINE> self.qrs_thr_min = qrs_thr_min <NEW_LINE> self.ref_period = ref_period <NEW_LINE> self.t_inspect_period = t_inspect_period
|
Initial signal configuration object for this qrs detector
|
62599017bf627c535bcb2221
|
class List(base.MistralLister): <NEW_LINE> <INDENT> def _get_format_function(self): <NEW_LINE> <INDENT> return CodeSourceFormatter.format_list <NEW_LINE> <DEDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(List, self).get_parser(prog_name) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def _get_resources(self, parsed_args): <NEW_LINE> <INDENT> mistral_client = self.app.client_manager.workflow_engine <NEW_LINE> return mistral_client.code_sources.list( marker=parsed_args.marker, limit=parsed_args.limit, sort_keys=parsed_args.sort_keys, sort_dirs=parsed_args.sort_dirs, fields=CodeSourceFormatter.fields(), **base.get_filters(parsed_args) )
|
List all workflows.
|
62599017507cdc57c63a5b12
|
class TaskRegistrationDecoratorTest(TestCase): <NEW_LINE> <INDENT> def test_register_without_parameters(self): <NEW_LINE> <INDENT> def register(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> register_task(force=True)(register) <NEW_LINE> self.assertIn(path(register), TASKS_BY_ID) <NEW_LINE> <DEDENT> def test_register(self): <NEW_LINE> <INDENT> @register_task(force=True) <NEW_LINE> def register(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.assertIn(path(register), TASKS_BY_ID) <NEW_LINE> <DEDENT> def test_registername(self): <NEW_LINE> <INDENT> _id = 'toto' <NEW_LINE> @register_task(_id, force=True) <NEW_LINE> def register(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.assertIn(_id, TASKS_BY_ID) <NEW_LINE> <DEDENT> def test_raise(self): <NEW_LINE> <INDENT> def toto(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> _id = path(toto) <NEW_LINE> register_tasks(force=True, **{_id: 6}) <NEW_LINE> self.assertRaises(TaskError, register_task, toto)
|
Test registration decorator
|
62599018462c4b4f79dbc77c
|
class Projeto: <NEW_LINE> <INDENT> def __init__(self, nome): <NEW_LINE> <INDENT> self.nome = nome <NEW_LINE> self.tarefas = [] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self.tarefas.__iter__() <NEW_LINE> <DEDENT> def add(self, descricao, vencimento=None): <NEW_LINE> <INDENT> self.tarefas.append(Tarefa(descricao, vencimento)) <NEW_LINE> <DEDENT> def pendentes(self): <NEW_LINE> <INDENT> return [tarefa for tarefa in self.tarefas if not tarefa.feito] <NEW_LINE> <DEDENT> def procurar(self, descricao): <NEW_LINE> <INDENT> return next((tarefa for tarefa in self.tarefas if tarefa.descricao == descricao)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.nome} ({len(self.pendentes())} tarefa(s) pendente(s))'
|
Essa classe cria um projeto, onde nele haverão diversas tarefas
e funcionalidades
|
62599018be8e80087fbbfde6
|
class Req(DefaultMunch): <NEW_LINE> <INDENT> __default__ = '' <NEW_LINE> def redirect(self, url, permanent=False, anchor=""): <NEW_LINE> <INDENT> if type(url) == bytes: <NEW_LINE> <INDENT> url = str(url, 'utf8') <NEW_LINE> <DEDENT> url = str(url).strip( ) <NEW_LINE> if not url.startswith('http'): <NEW_LINE> <INDENT> url = "http://%s%s" % (self.get_host(), url) <NEW_LINE> <DEDENT> if '#' in url: <NEW_LINE> <INDENT> url, anchor = url.rsplit('#', 1) <NEW_LINE> <DEDENT> ats = self.error and ['error=%s' % quote(self.error)] or [] <NEW_LINE> if self.warning: <NEW_LINE> <INDENT> ats.append('warning=%s' % quote(self.warning)) <NEW_LINE> <DEDENT> if self.message: <NEW_LINE> <INDENT> ats.append('message=%s' % quote(self.message)) <NEW_LINE> <DEDENT> q = url.find('?') > -1 and "&" or "?" <NEW_LINE> ats = ats and (q + '&'.join(ats)) or "" <NEW_LINE> url = '%s%s%s%s' % (url, ats, anchor and '#' or '', anchor) <NEW_LINE> self.request.setResponseCode(permanent and 301 or 302, None) <NEW_LINE> if type(url) != bytes: <NEW_LINE> <INDENT> url = bytes(bytearray(url, 'utf8')) <NEW_LINE> <DEDENT> self.request.setHeader('Location', url) <NEW_LINE> return " " <NEW_LINE> <DEDENT> def set_cookie(self, id, data="", expires=None, domain=None, path="/", max_age=None, comment=None, secure=None): <NEW_LINE> <INDENT> when = expires and (httpDate(time.time() + expires, rfc='850')) or None <NEW_LINE> self.request.addCookie(id, data, when, domain, path, expires or max_age, comment, secure) <NEW_LINE> <DEDENT> def clear_cookie(self, id): <NEW_LINE> <INDENT> self.set_cookie(id, expires=-3600 * 24 * 365, max_age=0) <NEW_LINE> <DEDENT> def get_host(self): <NEW_LINE> <INDENT> host = self.request.requestHeaders.getRawHeaders('host')[0] <NEW_LINE> try: <NEW_LINE> <INDENT> host = self.request.requestHeaders.getRawHeaders( 'x-forwarded-host')[0] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return str(host) <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return str(self.request.path, 'utf8') <NEW_LINE> <DEDENT> def get_uri(self): <NEW_LINE> <INDENT> return str(self.request.uri, 'utf8') <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return self.__class__(copy(dict(self))) <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> return self.copy()
|
extend the dict object with our own extra methods
|
625990180a366e3fb87dd76b
|
class Fragment36(Fragment): <NEW_LINE> <INDENT> HeaderValues = [ ("CenterX", "f"), ("CenterY", "f"), ("CenterZ", "f"), ("Param2_0", "I"), ("Param2_1", "I"), ("Param2_2", "I"), ("MaxDist", "f"), ("MinX", "f"), ("MinY", "f"), ("MinZ", "f"), ("MaxX", "f"), ("MaxY", "f"), ("MaxZ", "f"), ("VertexCount", "H"), ("TexCoordsCount", "H"), ("NormalCount", "H"), ("ColorCount", "H"), ("PolygonCount", "H"), ("VertexPieceCount", "H"), ("PolygonTexCount", "H"), ("VertexTexCount", "H"), ("Size9", "H"), ("Scale", "H") ] <NEW_LINE> def unpack(self, wld): <NEW_LINE> <INDENT> self.unpackField("Flags", "I") <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> self.unpackReference(wld, "Fragment%d" % i) <NEW_LINE> <DEDENT> self.unpackFields(Fragment36.HeaderValues) <NEW_LINE> scale = 1.0 / float(1 << self.Scale) <NEW_LINE> self.unpackArray("vertices", "hhh", self.VertexCount, self.unpackVertex, scale) <NEW_LINE> self.unpackArray("texCoords", "hh", self.TexCoordsCount) <NEW_LINE> self.unpackArray("normals", "bbb", self.NormalCount, self.unpackNormal) <NEW_LINE> self.unpackArray("colors", "BBBB", self.ColorCount) <NEW_LINE> self.unpackArray("polygons", "HHHH", self.PolygonCount) <NEW_LINE> self.unpackArray("vertexPieces", "HH", self.VertexPieceCount) <NEW_LINE> self.unpackArray("polygonsByTex", "HH", self.PolygonTexCount) <NEW_LINE> self.unpackArray("verticesByTex", "HH", self.VertexTexCount) <NEW_LINE> <DEDENT> def unpackVertex(self, params, scale): <NEW_LINE> <INDENT> return (params[0] * scale, params[1] * scale, params[2] * scale) <NEW_LINE> <DEDENT> def unpackNormal(self, params): <NEW_LINE> <INDENT> return tuple([float(p) / 127.0 for p in params])
|
This type of fragment describes a mesh.
|
62599018507cdc57c63a5b18
|
class ValueIterationAgent(ValueEstimationAgent): <NEW_LINE> <INDENT> def __init__(self, mdp, discount=0.9, iterations=100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> states = self.mdp.getStates() <NEW_LINE> self.values_prev_it = util.Counter() <NEW_LINE> self.values_cur_it = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> iteration = 1 <NEW_LINE> while iteration <= iterations: <NEW_LINE> <INDENT> for state in states: <NEW_LINE> <INDENT> actions = mdp.getPossibleActions(state) <NEW_LINE> if len(actions) < 1: <NEW_LINE> <INDENT> self.values_cur_it[state] = self.values_prev_it[state] <NEW_LINE> continue <NEW_LINE> <DEDENT> bestQvalue = float('-inf') <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> Qvalue = self.calcululateQValue(state, action, self.values_prev_it) <NEW_LINE> if Qvalue > bestQvalue: <NEW_LINE> <INDENT> bestQvalue = Qvalue <NEW_LINE> <DEDENT> <DEDENT> self.values_cur_it[state] = bestQvalue <NEW_LINE> <DEDENT> self.values_prev_it = self.values_cur_it.copy() <NEW_LINE> self.values_cur_it.clear() <NEW_LINE> iteration += 1 <NEW_LINE> <DEDENT> self.values = self.values_prev_it.copy() <NEW_LINE> <DEDENT> def calcululateQValue(self, state, action, Vk): <NEW_LINE> <INDENT> Q_value = 0 <NEW_LINE> succesors = self.mdp.getTransitionStatesAndProbs(state, action) <NEW_LINE> for nextState, prob in succesors: <NEW_LINE> <INDENT> Q_value += prob * (self.mdp.getReward(state, action, nextState) + self.discount * Vk[nextState]) <NEW_LINE> <DEDENT> return Q_value <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.values[state] <NEW_LINE> <DEDENT> def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> Q_value = 0 <NEW_LINE> succesors = self.mdp.getTransitionStatesAndProbs(state,action) <NEW_LINE> for nextState, prob in succesors: <NEW_LINE> <INDENT> Q_value += prob * (self.mdp.getReward(state, action, nextState) + self.discount * self.values[nextState]) <NEW_LINE> <DEDENT> return Q_value <NEW_LINE> <DEDENT> def computeActionFromValues(self, state): <NEW_LINE> <INDENT> bestAction = None <NEW_LINE> bestValue = float('-inf') <NEW_LINE> if self.mdp.isTerminal(state): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> actions = self.mdp.getPossibleActions(state) <NEW_LINE> if len(actions) < 1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for action in actions: <NEW_LINE> <INDENT> curValue = 0 <NEW_LINE> succesors = self.mdp.getTransitionStatesAndProbs(state, action) <NEW_LINE> for nextState, prob in succesors: <NEW_LINE> <INDENT> curValue += self.values[nextState] * prob <NEW_LINE> <DEDENT> if curValue > bestValue: <NEW_LINE> <INDENT> bestValue = curValue <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> <DEDENT> return bestAction <NEW_LINE> util.raiseNotDefined() <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> return self.computeActionFromValues(state) <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.computeQValueFromValues(state, action)
|
* Please read learningAgents.py before reading this.*
A ValueIterationAgent takes a Markov decision process
(see mdp.py) on initialization and runs value iteration
for a given number of iterations using the supplied
discount factor.
|
625990185e10d32532ce3fc3
|
class NetworkConfigurationDiagnosticResponse(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'results': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'results': {'key': 'results', 'type': '[NetworkConfigurationDiagnosticResult]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(NetworkConfigurationDiagnosticResponse, self).__init__(**kwargs) <NEW_LINE> self.results = None
|
Results of network configuration diagnostic on the target resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar results: List of network configuration diagnostic results.
:vartype results:
list[~azure.mgmt.network.v2018_12_01.models.NetworkConfigurationDiagnosticResult]
|
625990188c3a8732951f72da
|
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self,ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load("images/alien.bmp") <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction <NEW_LINE> self.rect.x = self.x <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect)
|
Initialize alien and set its initial position
|
62599018d18da76e235b780a
|
class LoginView(View): <NEW_LINE> <INDENT> def get(self,request): <NEW_LINE> <INDENT> return render(request,'login.html') <NEW_LINE> <DEDENT> def post(self,request): <NEW_LINE> <INDENT> login_form = LoginForm(request.POST) <NEW_LINE> if login_form.is_valid(): <NEW_LINE> <INDENT> username = request.POST.get('username','') <NEW_LINE> password = request.POST.get('password','') <NEW_LINE> user = authenticate(username=username,password=password) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> if user.is_active: <NEW_LINE> <INDENT> login(request,user) <NEW_LINE> return render(request,'index.html') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, 'login.html', {'errmsg': '用户未激活'}) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return render(request,'login.html',{'errmsg':'用户或密码错误'}) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, 'login.html',{'login_form':login_form})
|
登录
|
62599018be8e80087fbbfdec
|
class GetServers_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (DeviceResponse, DeviceResponse.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = DeviceResponse() <NEW_LINE> self.success.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.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('GetServers_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.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__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
|
Attributes:
- success
|
62599018bf627c535bcb222c
|
class SlackInput(HttpInputComponent): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def name(cls): <NEW_LINE> <INDENT> return "slack" <NEW_LINE> <DEDENT> def __init__(self, slack_token, slack_channel=None, errors_ignore_retry=None): <NEW_LINE> <INDENT> self.slack_token = slack_token <NEW_LINE> self.slack_channel = slack_channel <NEW_LINE> self.errors_ignore_retry = errors_ignore_retry or ('http_timeout',) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _is_user_message(slack_event): <NEW_LINE> <INDENT> return (slack_event.get('event') and slack_event.get('event').get('type') == u'message' and slack_event.get('event').get('text') and not slack_event.get('event').get('bot_id')) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _is_button_reply(slack_event): <NEW_LINE> <INDENT> return (slack_event.get('payload') and slack_event['payload'][0] and 'name' in slack_event['payload'][0]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_button_reply(slack_event): <NEW_LINE> <INDENT> return json.loads(slack_event['payload'][0])['actions'][0]['name'] <NEW_LINE> <DEDENT> def process_message(self, on_new_message, text, sender_id): <NEW_LINE> <INDENT> retry_reason = request.headers.environ.get('HTTP_X_SLACK_RETRY_REASON') <NEW_LINE> retry_count = request.headers.environ.get('HTTP_X_SLACK_RETRY_NUM') <NEW_LINE> if retry_count and retry_reason in self.errors_ignore_retry: <NEW_LINE> <INDENT> logger.warning("Received retry #{} request from slack" " due to {}".format(retry_count, retry_reason)) <NEW_LINE> return Response(status=201, headers={'X-Slack-No-Retry': 1}) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> out_channel = SlackBot(self.slack_token) <NEW_LINE> user_msg = UserMessage(text, out_channel, sender_id) <NEW_LINE> on_new_message(user_msg) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error("Exception when trying to handle " "message.{0}".format(e)) <NEW_LINE> logger.error(str(e), exc_info=True) <NEW_LINE> <DEDENT> return make_response() <NEW_LINE> <DEDENT> def blueprint(self, on_new_message): <NEW_LINE> <INDENT> slack_webhook = Blueprint('slack_webhook', __name__) <NEW_LINE> @slack_webhook.route("/", methods=['GET']) <NEW_LINE> def health(): <NEW_LINE> <INDENT> return jsonify({"status": "ok"}) <NEW_LINE> <DEDENT> @slack_webhook.route("/webhook", methods=['GET', 'POST']) <NEW_LINE> def webhook(): <NEW_LINE> <INDENT> request.get_data() <NEW_LINE> if request.json: <NEW_LINE> <INDENT> output = request.json <NEW_LINE> if "challenge" in output: <NEW_LINE> <INDENT> return make_response(output.get("challenge"), 200, {"content_type": "application/json"}) <NEW_LINE> <DEDENT> elif self._is_user_message(output): <NEW_LINE> <INDENT> return self.process_message( on_new_message, text=output['event']['text'], sender_id=output.get('event').get('user')) <NEW_LINE> <DEDENT> <DEDENT> elif request.form: <NEW_LINE> <INDENT> output = dict(request.form) <NEW_LINE> if self._is_button_reply(output): <NEW_LINE> <INDENT> return self.process_message( on_new_message, text=self._get_button_reply(output), sender_id=json.loads( output['payload'][0]).get('user').get('id')) <NEW_LINE> <DEDENT> <DEDENT> return make_response() <NEW_LINE> <DEDENT> return slack_webhook
|
Slack input channel implementation. Based on the HTTPInputChannel.
|
62599018d164cc6175821cfa
|
class ShowConsoleLog(command.Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__ + '.ShowConsoleLog') <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(ShowConsoleLog, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'server', metavar='<server>', help='Name or ID of server to display console log', ) <NEW_LINE> parser.add_argument( '--lines', metavar='<num-lines>', type=int, default=None, help='Number of lines to display from the end of the log ' '(default=all)', ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.log.debug('take_action(%s)' % parsed_args) <NEW_LINE> compute_client = self.app.client_manager.compute <NEW_LINE> server = utils.find_resource( compute_client.servers, parsed_args.server, ) <NEW_LINE> data = server.get_console_output(length=parsed_args.lines + 1) <NEW_LINE> sys.stdout.write(data) <NEW_LINE> return
|
Show console-log command
|
625990185e10d32532ce3fc5
|
class FileActivityLogger(BaseActivityLogger): <NEW_LINE> <INDENT> def __init__(self, activity, **kwargs): <NEW_LINE> <INDENT> super(FileActivityLogger, self).__init__(activity, **kwargs) <NEW_LINE> self.defer_finalize = True <NEW_LINE> self.indexed_meta_keys = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def file_meta(self): <NEW_LINE> <INDENT> meta = {} <NEW_LINE> for key in self.indexed_meta_keys: <NEW_LINE> <INDENT> if key in self.activity.meta: <NEW_LINE> <INDENT> meta[key] = self.activity.meta[key] <NEW_LINE> <DEDENT> <DEDENT> meta['activity_key'] = self.activity.key <NEW_LINE> meta['activity_keys'] = self.activity.keys <NEW_LINE> return meta <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> titan_file = files.File(self.activity.activity_id, _internal=True) <NEW_LINE> titan_file.write( content=protojson.encode_message(self.activity.to_message()), meta=self.file_meta, created=self.activity.timestamp, modified=self.activity.timestamp) <NEW_LINE> super(FileActivityLogger, self).finalize()
|
An activity for logging to Titan Files.
|
62599018a8ecb03325871f9b
|
@patch('projects.views.private.trigger_build', lambda x, basic: None) <NEW_LINE> @patch('readthedocs.projects.views.private.trigger_build', lambda x, basic: None) <NEW_LINE> class MockBuildTestCase(TestCase): <NEW_LINE> <INDENT> pass
|
Mock build triggers for test cases
|
625990185e10d32532ce3fc6
|
class ClusteredModel(object): <NEW_LINE> <INDENT> def __init__(self, info_dict): <NEW_LINE> <INDENT> self.queryset = info_dict.get('queryset', []) <NEW_LINE> self.fields = info_dict.get('fields', ['id']) <NEW_LINE> <DEDENT> def dataset(self): <NEW_LINE> <INDENT> dataset = {} <NEW_LINE> for item in self.queryset.filter(): <NEW_LINE> <INDENT> dataset[item] = ' '.join([str(item.__dict__[field]) for field in self.fields]) <NEW_LINE> <DEDENT> return dataset
|
Wrapper around Model class
building a dataset of instances
|
62599018507cdc57c63a5b20
|
class Solution: <NEW_LINE> <INDENT> def trapRainWater(self, heights): <NEW_LINE> <INDENT> min_heap = [] <NEW_LINE> m,n = len(heights), len(heights[0]) <NEW_LINE> visited = set() <NEW_LINE> for j in range(n): <NEW_LINE> <INDENT> heapq.heappush(min_heap, (heights[0][j], 0, j)) <NEW_LINE> visited.add( (0, j) ) <NEW_LINE> heapq.heappush(min_heap, (heights[m-1][j], m-1, j)) <NEW_LINE> visited.add( (m-1, j) ) <NEW_LINE> <DEDENT> for i in range(1,m-1): <NEW_LINE> <INDENT> heapq.heappush(min_heap, (heights[i][0], i, 0)) <NEW_LINE> visited.add( (i, 0) ) <NEW_LINE> heapq.heappush(min_heap, (heights[i][n-1], i, n-1)) <NEW_LINE> visited.add( (i, n-1) ) <NEW_LINE> <DEDENT> water = 0 <NEW_LINE> while min_heap: <NEW_LINE> <INDENT> lowest, x, y = heapq.heappop(min_heap) <NEW_LINE> for dx,dy in DIR: <NEW_LINE> <INDENT> nx, ny = x + dx, y + dy <NEW_LINE> if (nx, ny) in visited: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not self.within(m,n,nx,ny): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> actual_h = max(lowest, heights[nx][ny]) <NEW_LINE> water += actual_h - heights[nx][ny] <NEW_LINE> heapq.heappush(min_heap, (actual_h, nx, ny)) <NEW_LINE> visited.add( (nx, ny ) ) <NEW_LINE> <DEDENT> <DEDENT> return water <NEW_LINE> <DEDENT> def within(self, m, n, x, y): <NEW_LINE> <INDENT> return 0 <= x < m and 0 <= y < n
|
@param heights: a matrix of integers
@return: an integer
|
62599018462c4b4f79dbc788
|
class AuthenticationMethodBasic(AuthenticationMethod): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AuthenticationMethod.__init__(self) <NEW_LINE> <DEDENT> def authentication_type(self) -> str: <NEW_LINE> <INDENT> return "basic" <NEW_LINE> <DEDENT> def authenticate(self, input_authentication_parameters: dict, reference_authentication_parameters: dict) -> bool: <NEW_LINE> <INDENT> if "password" not in input_authentication_parameters.keys(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> password = input_authentication_parameters["password"] <NEW_LINE> if "password_hash" not in reference_authentication_parameters.keys(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> password_hash = reference_authentication_parameters["password_hash"] <NEW_LINE> return bcrypt.checkpw(password, password_hash) <NEW_LINE> <DEDENT> def generate_reference_authentication_parameters( self, input_authentication_parameters: dict) -> Optional[dict]: <NEW_LINE> <INDENT> if "password" not in input_authentication_parameters.keys(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> password = input_authentication_parameters["password"] <NEW_LINE> password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) <NEW_LINE> return {"password_hash": password_hash}
|
Base class for an authentication method
|
62599018925a0f43d25e8dc0
|
class BaseOrganizer(Participant): <NEW_LINE> <INDENT> objects = models.GeoManager() <NEW_LINE> type = models.ForeignKey('OrganizerType') <NEW_LINE> url = models.URLField(_('url'), null=True, blank=True) <NEW_LINE> notes = models.TextField(_('notes'), null=True, blank=True) <NEW_LINE> facebook_page = models.CharField( _('facebook page'), max_length=256, null=True, blank=True, help_text=('The Facebook page for your organization. Please do not ' 'enter your personal Facebook page.'), ) <NEW_LINE> post_publicly = models.BooleanField(_('post publicly'), default=True, help_text=_("Check this if you want to share your information on the " "lot's page so that your neighbors can reach you and work " "for access together. (If you don't click it, we'll just " "send you updates but keep your information hidden.)"), ) <NEW_LINE> def recent_change_label(self): <NEW_LINE> <INDENT> return 'new organizer: %s' % self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return "%s#organizer-%d" % (self.content_object.get_absolute_url(), self.pk) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def participation_adjective(cls): <NEW_LINE> <INDENT> return 'organized' <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> permissions = ( ('email_organizers', 'Can send an email to all organizers'), )
|
Someone publicly participating in something.
|
625990180a366e3fb87dd775
|
class ProductFilter(forms.Form): <NEW_LINE> <INDENT> FILTER_CHOICES = Filters().get_product_filters() <NEW_LINE> product_filter = forms.ChoiceField(choices=FILTER_CHOICES,required=True) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ProductFilter, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['product_filter'].widget.attrs.update({'class':'form-control','required':'True'})
|
A class that extends Django's default Form class.
This class is used for creating a form used as a product filter.
Attributes
----------
FILTER_CHOICES : list
A list of 2-tuples that contain the filter choice name in the model and user representation name.
product_filter
Represents the product filter.
|
62599018be8e80087fbbfdf4
|
class Enrollment(Edge): <NEW_LINE> <INDENT> pass
|
Represents the relationship between a student and a course in a particular semester
|
625990188c3a8732951f72e5
|
class CHRFScore(Score): <NEW_LINE> <INDENT> def __init__(self, score: float, char_order: int, word_order: int, beta: int): <NEW_LINE> <INDENT> self.beta = beta <NEW_LINE> self.char_order = char_order <NEW_LINE> self.word_order = word_order <NEW_LINE> name = f'chrF{self.beta}' + '+' * self.word_order <NEW_LINE> super().__init__(name, score)
|
A convenience class to represent chrF scores.
:param score: The chrF (chrF++) score.
:param char_order: The character n-gram order.
:param word_order: The word n-gram order. If equals to 2, the metric is referred to as chrF++.
:param beta: Determine the importance of recall w.r.t precision.
|
62599018d164cc6175821d02
|
class CaptchaRegistrationForm(RegistrationForm): <NEW_LINE> <INDENT> @property <NEW_LINE> def form_fields(self): <NEW_LINE> <INDENT> ffields = super(CaptchaRegistrationForm, self).form_fields <NEW_LINE> if len(ffields): <NEW_LINE> <INDENT> ffields = ffields + form.Fields(CaptchaSchema) <NEW_LINE> ffields["captcha"].custom_widget = CaptchaWidget <NEW_LINE> <DEDENT> return ffields
|
Registration form with captacha.
|
62599018507cdc57c63a5b26
|
class BlockDeviceDeployerCreationCalculateNecessaryStateChangesTests( SynchronousTestCase ): <NEW_LINE> <INDENT> def test_no_devices_no_local_datasets(self): <NEW_LINE> <INDENT> dataset_id = unicode(uuid4()) <NEW_LINE> manifestation = Manifestation( dataset=Dataset(dataset_id=dataset_id), primary=True ) <NEW_LINE> node = u"192.0.2.1" <NEW_LINE> other_node = u"192.0.2.2" <NEW_LINE> configuration = Deployment( nodes={ Node( hostname=other_node, manifestations={dataset_id: manifestation}, ) } ) <NEW_LINE> state = DeploymentState(nodes=[]) <NEW_LINE> api = LoopbackBlockDeviceAPI.from_path(self.mktemp()) <NEW_LINE> deployer = BlockDeviceDeployer( hostname=node, block_device_api=api, ) <NEW_LINE> changes = deployer.calculate_changes(configuration, state) <NEW_LINE> self.assertEqual(InParallel(changes=[]), changes) <NEW_LINE> <DEDENT> def test_no_devices_one_dataset(self): <NEW_LINE> <INDENT> dataset_id = unicode(uuid4()) <NEW_LINE> dataset = Dataset(dataset_id=dataset_id) <NEW_LINE> manifestation = Manifestation( dataset=dataset, primary=True ) <NEW_LINE> node = u"192.0.2.1" <NEW_LINE> configuration = Deployment( nodes={ Node( hostname=node, manifestations={dataset_id: manifestation}, ) } ) <NEW_LINE> state = DeploymentState(nodes=[]) <NEW_LINE> api = LoopbackBlockDeviceAPI.from_path(self.mktemp()) <NEW_LINE> deployer = BlockDeviceDeployer( hostname=node, block_device_api=api, ) <NEW_LINE> changes = deployer.calculate_changes(configuration, state) <NEW_LINE> mountpoint = deployer.mountroot.child(dataset_id.encode("ascii")) <NEW_LINE> self.assertEqual( InParallel( changes=[ CreateBlockDeviceDataset( dataset=dataset, mountpoint=mountpoint ) ]), changes ) <NEW_LINE> <DEDENT> def _calculate_changes(self, local_hostname, local_state, desired_configuration): <NEW_LINE> <INDENT> current_cluster_state = DeploymentState(nodes={local_state}) <NEW_LINE> api = LoopbackBlockDeviceAPI.from_path(self.mktemp()) <NEW_LINE> deployer = BlockDeviceDeployer( hostname=local_hostname, block_device_api=api, ) <NEW_LINE> return deployer.calculate_changes( desired_configuration, current_cluster_state ) <NEW_LINE> <DEDENT> def test_match_configuration_to_state_of_datasets(self): <NEW_LINE> <INDENT> expected_hostname = u'192.0.2.123' <NEW_LINE> expected_dataset_id = unicode(uuid4()) <NEW_LINE> local_state = NodeState( hostname=expected_hostname, paths={ expected_dataset_id: FilePath(b"/flocker").child( expected_dataset_id.encode("ascii")), }, manifestations={ expected_dataset_id: Manifestation( primary=True, dataset=Dataset( dataset_id=expected_dataset_id, maximum_size=REALISTIC_BLOCKDEVICE_SIZE, metadata={}, deleted=False, ), ), }, ) <NEW_LINE> desired_configuration = Deployment(nodes=[Node( hostname=expected_hostname, manifestations=local_state.manifestations.transform( (expected_dataset_id, "dataset", "metadata"), {u"name": u"my_volume"} ))]) <NEW_LINE> actual_changes = self._calculate_changes( expected_hostname, local_state, desired_configuration ) <NEW_LINE> expected_changes = InParallel(changes=[]) <NEW_LINE> self.assertEqual(expected_changes, actual_changes)
|
Tests for ``BlockDeviceDeployer.calculate_changes`` in the cases relating
to dataset creation.
|
6259901856b00c62f0fb3643
|
class ListOfOwnedFunctionalComponent(OwnedFunctionalComponent): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> for _s in [OwnedFunctionalComponent]: <NEW_LINE> <INDENT> __swig_setmethods__.update(getattr(_s, '__swig_setmethods__', {})) <NEW_LINE> <DEDENT> __setattr__ = lambda self, name, value: _swig_setattr(self, ListOfOwnedFunctionalComponent, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> for _s in [OwnedFunctionalComponent]: <NEW_LINE> <INDENT> __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {})) <NEW_LINE> <DEDENT> __getattr__ = lambda self, name: _swig_getattr(self, ListOfOwnedFunctionalComponent, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _libsbol.new_ListOfOwnedFunctionalComponent(*args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except __builtin__.Exception: <NEW_LINE> <INDENT> self.this = this <NEW_LINE> <DEDENT> <DEDENT> __swig_destroy__ = _libsbol.delete_ListOfOwnedFunctionalComponent <NEW_LINE> __del__ = lambda self: None
|
Provides interface for an SBOL container Property that is allowed to have more
than one object or value.
templateparam
-------------
* `PropertyType` :
The type of SBOL Property, eg, Text, Int, OwnedObject, etc
|
62599018925a0f43d25e8dc6
|
class PythonzEmailOneliner(PythonzEmailMessage): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def create(cls, subject, text): <NEW_LINE> <INDENT> cls(cls.get_full_subject(subject), text).schedule(cls.recipients('smtp', cls.get_admins_emails()))
|
Простое "однострочное" сообщение.
|
6259901821a7993f00c66d01
|
class Solution2: <NEW_LINE> <INDENT> def addBinary(self, a, b): <NEW_LINE> <INDENT> result = [] <NEW_LINE> i = len(a)-1 <NEW_LINE> j = len(b)-1 <NEW_LINE> add_one = 0 <NEW_LINE> temp_result = 0 <NEW_LINE> while i>=0 or j>=0: <NEW_LINE> <INDENT> temp_result = add_one <NEW_LINE> if i>=0: <NEW_LINE> <INDENT> temp_result += int(a[i]) <NEW_LINE> i-=1 <NEW_LINE> <DEDENT> if j>=0: <NEW_LINE> <INDENT> temp_result += int(b[j]) <NEW_LINE> j-=1 <NEW_LINE> <DEDENT> result.insert(0, str(temp_result%2)) <NEW_LINE> add_one=temp_result//2 <NEW_LINE> <DEDENT> if add_one!=0: <NEW_LINE> <INDENT> result.insert(0, str(add_one)) <NEW_LINE> <DEDENT> return ''.join(result)
|
Slowest!
|
625990186fece00bbaccc73c
|
class Policies(object): <NEW_LINE> <INDENT> __table_args__ = {'mysql_engine':'InnoDB', 'mysql_charset':'utf8'}
|
A SQLAlchemy mix-in for base policies.
|
62599018a8ecb03325871fa5
|
class TimeSeriesEEGFramework(time_series_data.TimeSeriesEEGData, TimeSeriesFramework): <NEW_LINE> <INDENT> def get_space_labels(self): <NEW_LINE> <INDENT> if self.sensors is not None: <NEW_LINE> <INDENT> return list(self.sensors.labels) <NEW_LINE> <DEDENT> return []
|
This class exists to add framework methods to TimeSeriesEEGData.
|
625990189b70327d1c57fb08
|
class Aes(_Cipher): <NEW_LINE> <INDENT> block_size = 16 <NEW_LINE> key_size = None <NEW_LINE> _key_sizes = [16, 24, 32] <NEW_LINE> _native_type = "Aes *" <NEW_LINE> def _set_key(self, direction): <NEW_LINE> <INDENT> if direction == _ENCRYPTION: <NEW_LINE> <INDENT> return _lib.wc_AesSetKey( self._enc, self._key, len(self._key), self._IV, _ENCRYPTION) <NEW_LINE> <DEDENT> if self.mode == MODE_CTR: <NEW_LINE> <INDENT> return _lib.wc_AesSetKey( self._dec, self._key, len(self._key), self._IV, _ENCRYPTION) <NEW_LINE> <DEDENT> return _lib.wc_AesSetKey( self._dec, self._key, len(self._key), self._IV, _DECRYPTION) <NEW_LINE> <DEDENT> def _encrypt(self, destination, source): <NEW_LINE> <INDENT> if self.mode == MODE_CBC: <NEW_LINE> <INDENT> return _lib.wc_AesCbcEncrypt(self._enc, destination, source, len(source)) <NEW_LINE> <DEDENT> elif self.mode == MODE_CTR: <NEW_LINE> <INDENT> return _lib.wc_AesCtrEncrypt(self._enc, destination, source, len(source)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid mode associated to cipher") <NEW_LINE> <DEDENT> <DEDENT> def _decrypt(self, destination, source): <NEW_LINE> <INDENT> if self.mode == MODE_CBC: <NEW_LINE> <INDENT> return _lib.wc_AesCbcDecrypt(self._dec, destination, source, len(source)) <NEW_LINE> <DEDENT> elif self.mode == MODE_CTR: <NEW_LINE> <INDENT> return _lib.wc_AesCtrEncrypt(self._dec, destination, source, len(source)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid mode associated to cipher")
|
The **Advanced Encryption Standard** (AES), a.k.a. Rijndael, is
a symmetric-key cipher standardized by **NIST**.
|
62599018462c4b4f79dbc792
|
@add_metaclass(ABCMeta) <NEW_LINE> class AbstractBinaryUsesSimulationRun(AbstractStartsSynchronized): <NEW_LINE> <INDENT> pass
|
Indicates that the binary run time can be updated
|
62599018462c4b4f79dbc794
|
class ItemList(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Item.objects.all() <NEW_LINE> serializer_class = ItemSerializer <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(last_modified_by=self.request.user)
|
List all the Items or create a new item.
|
625990189b70327d1c57fb0c
|
class ClientSchema(current_app.marshmallow.ModelSchema): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.Client
|
Client model schema
|
62599018507cdc57c63a5b2e
|
class SubtaskStatus(object): <NEW_LINE> <INDENT> def __init__(self, task_id, attempted=None, succeeded=0, failed=0, skipped=0, retried_nomax=0, retried_withmax=0, state=None): <NEW_LINE> <INDENT> self.task_id = task_id <NEW_LINE> if attempted is not None: <NEW_LINE> <INDENT> self.attempted = attempted <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.attempted = succeeded + failed <NEW_LINE> <DEDENT> self.succeeded = succeeded <NEW_LINE> self.failed = failed <NEW_LINE> self.skipped = skipped <NEW_LINE> self.retried_nomax = retried_nomax <NEW_LINE> self.retried_withmax = retried_withmax <NEW_LINE> self.state = state if state is not None else QUEUING <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, d): <NEW_LINE> <INDENT> options = dict(d) <NEW_LINE> task_id = options['task_id'] <NEW_LINE> del options['task_id'] <NEW_LINE> return SubtaskStatus.create(task_id, **options) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, task_id, **options): <NEW_LINE> <INDENT> return cls(task_id, **options) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def increment(self, succeeded=0, failed=0, skipped=0, retried_nomax=0, retried_withmax=0, state=None): <NEW_LINE> <INDENT> self.attempted += (succeeded + failed) <NEW_LINE> self.succeeded += succeeded <NEW_LINE> self.failed += failed <NEW_LINE> self.skipped += skipped <NEW_LINE> self.retried_nomax += retried_nomax <NEW_LINE> self.retried_withmax += retried_withmax <NEW_LINE> if state is not None: <NEW_LINE> <INDENT> self.state = state <NEW_LINE> <DEDENT> <DEDENT> def get_retry_count(self): <NEW_LINE> <INDENT> return self.retried_nomax + self.retried_withmax <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'SubtaskStatus<%r>' % (self.to_dict(),) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(repr(self))
|
Create and return a dict for tracking the status of a subtask.
SubtaskStatus values are:
'task_id' : id of subtask. This is used to pass task information across retries.
'attempted' : number of attempts -- should equal succeeded plus failed
'succeeded' : number that succeeded in processing
'skipped' : number that were not processed.
'failed' : number that failed during processing
'retried_nomax' : number of times the subtask has been retried for conditions that
should not have a maximum count applied
'retried_withmax' : number of times the subtask has been retried for conditions that
should have a maximum count applied
'state' : celery state of the subtask (e.g. QUEUING, PROGRESS, RETRY, FAILURE, SUCCESS)
Object is not JSON-serializable, so to_dict and from_dict methods are provided so that
it can be passed as a serializable argument to tasks (and be reconstituted within such tasks).
In future, we may want to include specific error information
indicating the reason for failure.
Also, we should count up "not attempted" separately from attempted/failed.
|
62599018a8ecb03325871fac
|
class FileXMLHandler(xmlhandler.ContentHandler): <NEW_LINE> <INDENT> def startDocument(self): <NEW_LINE> <INDENT> self._data = [] <NEW_LINE> self._filedata = None <NEW_LINE> self._key = None <NEW_LINE> <DEDENT> def startElement(self, name, attrs): <NEW_LINE> <INDENT> if name == "file": <NEW_LINE> <INDENT> self._filedata = {} <NEW_LINE> self._filedata["name"] = attrs.getValue("name") <NEW_LINE> self._filedata["source"] = attrs.getValue("source") <NEW_LINE> <DEDENT> elif self._filedata != None: <NEW_LINE> <INDENT> if name in ['original', 'md5', 'format', 'album', 'title', 'track', 'size']: <NEW_LINE> <INDENT> self._key = name <NEW_LINE> self._value = [] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def characters(self, content): <NEW_LINE> <INDENT> if self._key != None: <NEW_LINE> <INDENT> self._value.append(content) <NEW_LINE> <DEDENT> <DEDENT> def endElement(self, name): <NEW_LINE> <INDENT> if self._filedata != None: <NEW_LINE> <INDENT> if self._key != None: <NEW_LINE> <INDENT> self._filedata[self._key] = "".join(self._value).strip(" \n") <NEW_LINE> self._key = None <NEW_LINE> <DEDENT> elif name == "file": <NEW_LINE> <INDENT> self._data.append(self._filedata) <NEW_LINE> self._filedata = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def endDocument(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getData(self): <NEW_LINE> <INDENT> return self._data
|
Parser for the _files.xml file.
This one's a little trickier to parse than the meta file, as we have
some mild nesting: file details are children of the file element.
|
625990185166f23b2e244161
|
class ResultSet(list): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ResultSet, self).__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def uniqueIdentifiers(self): <NEW_LINE> <INDENT> ids = [] <NEW_LINE> for item in self: <NEW_LINE> <INDENT> if hasattr(item, 'uniqueIdentifier'): <NEW_LINE> <INDENT> ids.append(item.uniqueIdentifier) <NEW_LINE> <DEDENT> <DEDENT> return ids
|
A list of like object that holds results.
|
625990188c3a8732951f72f1
|
class TechnicalProtection(TechnicalProtectionBaseType_): <NEW_LINE> <INDENT> c_tag = 'TechnicalProtection' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = TechnicalProtectionBaseType_.c_children.copy() <NEW_LINE> c_attributes = TechnicalProtectionBaseType_.c_attributes.copy() <NEW_LINE> c_child_order = TechnicalProtectionBaseType_.c_child_order[:] <NEW_LINE> c_cardinality = TechnicalProtectionBaseType_.c_cardinality.copy()
|
The urn:oasis:names:tc:SAML:2.0:ac:TechnicalProtection element
|
6259901821a7993f00c66d0b
|
class TestRemoveNone(TestCase): <NEW_LINE> <INDENT> def test_removes_all_None_values(self): <NEW_LINE> <INDENT> data = {"None": None, "another_None": None, "keep": "value"} <NEW_LINE> self.assertEquals({"keep": "value"}, utils.remove_None(data))
|
Test `remove_None`.
|
625990189b70327d1c57fb10
|
class UpdateError(JustOneError): <NEW_LINE> <INDENT> pass
|
Exception for JustOne._update_*
|
62599018a8ecb03325871fae
|
class LearningModeCode(Code): <NEW_LINE> <INDENT> code= models.CharField(primary_key=True, max_length=2, verbose_name=u"代码") <NEW_LINE> name = models.CharField(unique=True, max_length=12, verbose_name=u"名称") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = u"学习形式码" <NEW_LINE> verbose_name_plural = u"学习形式码"
|
学习形式码
|
625990186fece00bbaccc746
|
class PlotterAutoClassDocumenter(AutoSummClassDocumenter): <NEW_LINE> <INDENT> priority = AutoSummClassDocumenter.priority + 0.1 <NEW_LINE> def filter_members(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = super(AutoSummClassDocumenter, self).filter_members( *args, **kwargs) <NEW_LINE> if issubclass(self.object, Plotter): <NEW_LINE> <INDENT> fmt_members = defaultdict(set) <NEW_LINE> all_fmt = set(self.object._get_formatoptions()) <NEW_LINE> for i, (mname, member, isattr) in enumerate(ret): <NEW_LINE> <INDENT> if isinstance(member, Formatoption): <NEW_LINE> <INDENT> fmt_members[member.group].add((mname, member, isattr)) <NEW_LINE> all_fmt.remove(mname) <NEW_LINE> <DEDENT> <DEDENT> for fmt in all_fmt: <NEW_LINE> <INDENT> fmto = getattr(self.object, fmt) <NEW_LINE> fmt_members[fmto.group].add((fmt, fmto, True)) <NEW_LINE> <DEDENT> ret.extend( (tup for tup in chain(*map(sorted, fmt_members.values())) if tup not in ret)) <NEW_LINE> <DEDENT> return ret
|
A ClassDocumenter that includes all the formatoption of a plotter
|
625990185e10d32532ce3fcf
|
class failRequest_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'id', None, None, ), ) <NEW_LINE> def __init__(self, id=None,): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.id = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('failRequest_args') <NEW_LINE> if self.id is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('id', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.id) <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__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
|
Attributes:
- id
|
6259901891af0d3eaad3abb3
|
class MemoryError(SerializationError, exceptions.MemoryError): <NEW_LINE> <INDENT> pass
|
Out of memory or unable to load type due to not enough memory
|
62599018d164cc6175821d0f
|
class SSRN(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SSRN, self).__init__() <NEW_LINE> self.name = 'SSRN' <NEW_LINE> self.hc_blocks = nn.ModuleList([norm(mm.Conv1d(args.n_mels, args.Cs, 1, activation_fn=torch.relu))]) <NEW_LINE> self.hc_blocks.extend([norm(mm.HighwayConv1d(args.Cs, args.Cs, 3, dilation=3**i)) for i in range(2)]) <NEW_LINE> self.hc_blocks.extend([norm(mm.ConvTranspose1d(args.Cs, args.Cs, 4, stride=2, padding=1))]) <NEW_LINE> self.hc_blocks.extend([norm(mm.HighwayConv1d(args.Cs, args.Cs, 3, dilation=3**i)) for i in range(2)]) <NEW_LINE> self.hc_blocks.extend([norm(mm.ConvTranspose1d(args.Cs, args.Cs, 4, stride=2, padding=1))]) <NEW_LINE> self.hc_blocks.extend([norm(mm.HighwayConv1d(args.Cs, args.Cs, 3, dilation=3**i)) for i in range(2)]) <NEW_LINE> self.hc_blocks.extend([norm(mm.Conv1d(args.Cs, args.Cs*2, 1))]) <NEW_LINE> self.hc_blocks.extend([norm(mm.HighwayConv1d(args.Cs*2, args.Cs*2, 3, dilation=1)) for i in range(2)]) <NEW_LINE> self.hc_blocks.extend([norm(mm.Conv1d(args.Cs*2, args.n_mags, 1))]) <NEW_LINE> self.hc_blocks.extend([norm(mm.Conv1d(args.n_mags, args.n_mags, 1, activation_fn=torch.relu)) for i in range(2)]) <NEW_LINE> self.hc_blocks.extend([norm(mm.Conv1d(args.n_mags, args.n_mags, 1))]) <NEW_LINE> <DEDENT> def forward(self, Y): <NEW_LINE> <INDENT> Y = Y.transpose(1, 2) <NEW_LINE> Z = Y <NEW_LINE> for i in range(len(self.hc_blocks)): <NEW_LINE> <INDENT> Z = self.hc_blocks[i](Z) <NEW_LINE> <DEDENT> Z = torch.sigmoid(Z) <NEW_LINE> return Z.transpose(1, 2)
|
SSRN
Args:
Y: (N, Ty/r, n_mels)
Returns:
Z: (N, Ty, n_mags)
|
625990189b70327d1c57fb12
|
class Game(Base): <NEW_LINE> <INDENT> __tablename__ = 'game' <NEW_LINE> id = Column(Integer, primary_key = True) <NEW_LINE> name = Column(String(80), nullable = False) <NEW_LINE> description = Column(String(250), nullable = False) <NEW_LINE> price = Column(String(8)) <NEW_LINE> picture = Column(String(250)) <NEW_LINE> time_created = Column(DateTime(timezone=True), server_default=func.now()) <NEW_LINE> genre_id = Column(Integer, ForeignKey('genre.id')) <NEW_LINE> genre = relationship(Genre) <NEW_LINE> user_id = Column(Integer, ForeignKey('user.id')) <NEW_LINE> user = relationship(User) <NEW_LINE> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return{ 'name': self.name, 'description': self.description, 'id': self.id, 'price': self.price, }
|
Corresponds to the Game table
|
62599018a8ecb03325871faf
|
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) <NEW_LINE> self.rect.x = self.x
|
表示单个外星人的类
|
62599018507cdc57c63a5b34
|
class CompletionTests(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.xSmall = numpy.array([[4, 2, 3], [1, 5, 8], [7, 6, 9]]) <NEW_LINE> cls.ySmall = numpy.array([2, 6, 4]) <NEW_LINE> <DEDENT> def test_pass_small(self): <NEW_LINE> <INDENT> PLS.main.pls(self.xSmall, self.ySmall)
|
Tests checking whether the code successfully returns while running PLS2.
|
625990185e10d32532ce3fd0
|
@attr.s <NEW_LINE> class HacsSystem: <NEW_LINE> <INDENT> disabled: bool = False <NEW_LINE> running: bool = False <NEW_LINE> version: str = INTEGRATION_VERSION <NEW_LINE> stage: HacsStage = attr.ib(HacsStage) <NEW_LINE> action: bool = False
|
HACS System info.
|
62599019462c4b4f79dbc79c
|
class AdminController(wsgi.Controller): <NEW_LINE> <INDENT> collection = None <NEW_LINE> valid_status = set([ 'creating', 'available', 'deleting', 'error', 'error_deleting', ]) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AdminController, self).__init__(*args, **kwargs) <NEW_LINE> self.resource_name = self.collection.rstrip('s') <NEW_LINE> self.volume_api = volume.API() <NEW_LINE> <DEDENT> def _update(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _get(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _delete(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def validate_update(self, body): <NEW_LINE> <INDENT> update = {} <NEW_LINE> try: <NEW_LINE> <INDENT> update['status'] = body['status'] <NEW_LINE> <DEDENT> except (TypeError, KeyError): <NEW_LINE> <INDENT> raise exc.HTTPBadRequest("Must specify 'status'") <NEW_LINE> <DEDENT> if update['status'] not in self.valid_status: <NEW_LINE> <INDENT> raise exc.HTTPBadRequest("Must specify a valid status") <NEW_LINE> <DEDENT> return update <NEW_LINE> <DEDENT> def authorize(self, context, action_name): <NEW_LINE> <INDENT> action = '%s_admin_actions:%s' % (self.resource_name, action_name) <NEW_LINE> extensions.extension_authorizer('volume', action)(context) <NEW_LINE> <DEDENT> @wsgi.action('os-reset_status') <NEW_LINE> def _reset_status(self, req, id, body): <NEW_LINE> <INDENT> context = req.environ['cinder.context'] <NEW_LINE> self.authorize(context, 'reset_status') <NEW_LINE> update = self.validate_update(body['os-reset_status']) <NEW_LINE> msg = _("Updating %(resource)s '%(id)s' with '%(update)r'") <NEW_LINE> LOG.debug(msg, {'resource': self.resource_name, 'id': id, 'update': update}) <NEW_LINE> notifier_info = dict(id=id, update=update) <NEW_LINE> notifier = rpc.get_notifier('volumeStatusUpdate') <NEW_LINE> notifier.info(context, self.collection + '.reset_status.start', notifier_info) <NEW_LINE> try: <NEW_LINE> <INDENT> self._update(context, id, update) <NEW_LINE> <DEDENT> except exception.NotFound as e: <NEW_LINE> <INDENT> raise exc.HTTPNotFound(e) <NEW_LINE> <DEDENT> notifier.info(context, self.collection + '.reset_status.end', notifier_info) <NEW_LINE> return webob.Response(status_int=202) <NEW_LINE> <DEDENT> @wsgi.action('os-force_delete') <NEW_LINE> def _force_delete(self, req, id, body): <NEW_LINE> <INDENT> context = req.environ['cinder.context'] <NEW_LINE> self.authorize(context, 'force_delete') <NEW_LINE> try: <NEW_LINE> <INDENT> resource = self._get(context, id) <NEW_LINE> <DEDENT> except exception.NotFound: <NEW_LINE> <INDENT> raise exc.HTTPNotFound() <NEW_LINE> <DEDENT> self._delete(context, resource, force=True) <NEW_LINE> return webob.Response(status_int=202)
|
Abstract base class for AdminControllers.
|
62599019d18da76e235b7817
|
@SAProvider.register_lookup <NEW_LINE> class Overlap(DefaultLookup): <NEW_LINE> <INDENT> lookup_name = "overlap"
|
Overlap Query
|
62599019a8ecb03325871fb2
|
class UserExists(GameException): <NEW_LINE> <INDENT> def msg(self): <NEW_LINE> <INDENT> return jsonify(result="userExists")
|
User already exists
|
62599019bf627c535bcb2244
|
class Player(arcade.Sprite): <NEW_LINE> <INDENT> def __init__(self, image, scale): <NEW_LINE> <INDENT> super().__init__(image, scale) <NEW_LINE> self.speed = 0 <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> angle_rad = math.radians(self.angle) <NEW_LINE> self.angle += self.change_angle <NEW_LINE> self.center_x += -self.speed * math.sin(angle_rad) <NEW_LINE> self.center_y += self.speed * math.cos(angle_rad)
|
Player class
|
6259901956b00c62f0fb3651
|
class Error(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, response=None): <NEW_LINE> <INDENT> self.response = response <NEW_LINE> self.orig_response = None <NEW_LINE> super(Error, self).__init__(msg)
|
Error on PowerVM API Adapter method invocation.
|
6259901991af0d3eaad3abb7
|
class AutojitExtensionCompiler(compileclass.ExtensionCompiler): <NEW_LINE> <INDENT> method_validators = validators.autojit_validators <NEW_LINE> exttype_validators = validators.autojit_type_validators <NEW_LINE> def get_bases(self): <NEW_LINE> <INDENT> return (self.py_class,) <NEW_LINE> <DEDENT> def get_metacls(self): <NEW_LINE> <INDENT> return autojitmeta.create_specialized_metaclass(self.py_class)
|
Compile @autojit extension classes.
|
62599019462c4b4f79dbc79e
|
class AppiumCommand(object): <NEW_LINE> <INDENT> def __init__(self, phone_os): <NEW_LINE> <INDENT> self.phone_os = phone_os <NEW_LINE> <DEDENT> def send_keys(self, element, keys, driver): <NEW_LINE> <INDENT> if self.phone_os == "Android": <NEW_LINE> <INDENT> return AppiumCommandAndroid().send_keys(element, keys, driver) <NEW_LINE> <DEDENT> elif self.phone_os == "iOS": <NEW_LINE> <INDENT> return AppiumCommandIos().send_keys(element, keys, driver) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("The OS is wrong!") <NEW_LINE> <DEDENT> <DEDENT> def get_attribute(self, element, name, driver=None, elem=None): <NEW_LINE> <INDENT> if self.phone_os == "Android": <NEW_LINE> <INDENT> attribute_value = AppiumCommandAndroid().get_attribute(element, name, driver, elem) <NEW_LINE> <DEDENT> elif self.phone_os == "iOS": <NEW_LINE> <INDENT> attribute_value = AppiumCommandIos().get_attribute(element, name, driver, elem) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("The OS is wrong!") <NEW_LINE> <DEDENT> return attribute_value <NEW_LINE> <DEDENT> def hide_keyboard(self, element, driver): <NEW_LINE> <INDENT> if self.phone_os == "Android": <NEW_LINE> <INDENT> attribute_value = AppiumCommandAndroid().hide_keyboard(element, driver) <NEW_LINE> <DEDENT> elif self.phone_os == "iOS": <NEW_LINE> <INDENT> attribute_value = AppiumCommandIos().hide_keyboard(element, driver) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("The OS is wrong!") <NEW_LINE> <DEDENT> return attribute_value <NEW_LINE> <DEDENT> def get_location(self, element): <NEW_LINE> <INDENT> if self.phone_os == "Android": <NEW_LINE> <INDENT> attribute_value = AppiumCommandAndroid().get_location(element) <NEW_LINE> <DEDENT> elif self.phone_os == "iOS": <NEW_LINE> <INDENT> attribute_value = AppiumCommandIos().get_location(element) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("The OS is wrong!") <NEW_LINE> <DEDENT> return attribute_value <NEW_LINE> <DEDENT> def swipe(self, x1, y1, x2, y2, driver, step=900, percent=True): <NEW_LINE> <INDENT> if self.phone_os == "Android": <NEW_LINE> <INDENT> attribute_value = AppiumCommandAndroid().swipe(x1, y1, x2, y2, driver, step, percent) <NEW_LINE> <DEDENT> elif self.phone_os == "iOS": <NEW_LINE> <INDENT> attribute_value = AppiumCommandIos().swipe(x1, y1, x2, y2, driver, step, percent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError("The OS is wrong!") <NEW_LINE> <DEDENT> return attribute_value
|
API.
Re encapsulate the android & ios appium command.
|
62599019925a0f43d25e8dd7
|
@attr.s(repr=False, init=False) <NEW_LINE> class MockLink(link.Link): <NEW_LINE> <INDENT> working_directory = attr.ib() <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(MockLink, self).__init__(**kwargs) <NEW_LINE> self._type = "MockLink" <NEW_LINE> self.working_directory = kwargs.get("working_directory", None) <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> fn = MOCK_FILENAME_FORMAT.format(step_name=self.name) <NEW_LINE> super(MockLink, self).dump(fn) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data): <NEW_LINE> <INDENT> return MockLink(**data)
|
A mock link is the metadata representation of a supply chain step mocked
by a functionary.
Mock links are recorded and stored to a file when a functionary
wraps a command with in_toto_mock.
Mock links also contain materials and products which are hashes of
the file before the command was executed and after the command was executed.
<Attributes>
working_directory:
the path of the directory where the command was executed
|
62599019d164cc6175821d15
|
class PyccelNot(PyccelUnaryOperator): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _precedence = 6 <NEW_LINE> @staticmethod <NEW_LINE> def _calculate_dtype(*args): <NEW_LINE> <INDENT> dtype = NativeBool() <NEW_LINE> precision = -1 <NEW_LINE> return dtype, precision <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _calculate_shape_rank(*args): <NEW_LINE> <INDENT> rank = 0 <NEW_LINE> shape = () <NEW_LINE> return shape, rank <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'not {}'.format(repr(self.args[0]))
|
Class representing a call to the python not operator.
I.e:
not a
is equivalent to:
PyccelNot(a)
Parameters
----------
arg: PyccelAstNode
The argument passed to the operator
|
625990190a366e3fb87dd78d
|
class Headline(scrapy.Item): <NEW_LINE> <INDENT> title = scrapy.Field() <NEW_LINE> body = scrapy.Field()
|
뉴스 헤드라인을 나타내는 Item 객체
|
625990195e10d32532ce3fd3
|
class GetXF0D: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, it): <NEW_LINE> <INDENT> pass
|
Class hierarchy: freestyle.types.UnaryFunction0D > freestyle.types.UnaryFunction0DDouble > GetXF0D
|
625990195166f23b2e24416d
|
class ResubmissionWorkloadFactory(StdBase): <NEW_LINE> <INDENT> def __call__(self, workloadName, arguments): <NEW_LINE> <INDENT> requestName = arguments['OriginalRequestName'] <NEW_LINE> originalRequest = GetRequest.getRequestByName(requestName) <NEW_LINE> helper = loadWorkload(originalRequest) <NEW_LINE> helper.truncate(arguments["RequestName"], arguments["InitialTaskPath"], arguments["ACDCServer"], arguments["ACDCDatabase"], arguments.get("CollectionName")) <NEW_LINE> helper.ignoreOutputModules(arguments.get("IgnoredOutputModules", [])) <NEW_LINE> return helper <NEW_LINE> <DEDENT> def validateSchema(self, schema): <NEW_LINE> <INDENT> requiredFields = ["OriginalRequestName", "InitialTaskPath", "ACDCServer", "ACDCDatabase"] <NEW_LINE> self.requireValidateFields(fields = requiredFields, schema = schema, validate = False)
|
Build Resubmission workloads
|
62599019d18da76e235b781b
|
class MEventMessage(MMessage): <NEW_LINE> <INDENT> def addEventCallback(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getEventNames(*args, **kwargs): <NEW_LINE> <INDENT> pass
|
Class used to register callbacks for event related messages.
|
6259901921a7993f00c66d17
|
class CommunityDestination(Destination): <NEW_LINE> <INDENT> class Implementation(Destination.Implementation): <NEW_LINE> <INDENT> def __init__(self, meta, *candidates): <NEW_LINE> <INDENT> assert isinstance(candidates, tuple), type(candidates) <NEW_LINE> assert len(candidates) >= 0, len(candidates) <NEW_LINE> assert all(isinstance(candidate, Candidate) for candidate in candidates), [type(candidate) for candidate in candidates] <NEW_LINE> super(CommunityDestination.Implementation, self).__init__(meta) <NEW_LINE> self._candidates = candidates <NEW_LINE> <DEDENT> @property <NEW_LINE> def node_count(self): <NEW_LINE> <INDENT> return self._meta._node_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def candidates(self): <NEW_LINE> <INDENT> return self._candidates <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, node_count): <NEW_LINE> <INDENT> assert isinstance(node_count, int) <NEW_LINE> assert node_count >= 0 <NEW_LINE> self._node_count = node_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def node_count(self): <NEW_LINE> <INDENT> return self._node_count <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<%s node_count:%d>" % (self.__class__.__name__, self._node_count)
|
A destination policy where the message is sent to one or more community members selected from
the current candidate list.
At the time of sending at most NODE_COUNT addresses are obtained using
community.yield_random_candidates(...) to receive the message.
|
62599019be8e80087fbbfe0e
|
class CpuFreqTestError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if 'scaling_driver' in message: <NEW_LINE> <INDENT> logging.warning( '## Warning: scaling via CpuFreq non-supported ##') <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> elif 'intel_pstate/status' in message: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.error(message)
|
Exception handling.
|
62599019a8ecb03325871fba
|
class TestNthToLastElement(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.link_list = nth_to_the_last_element_singly_link_list.LinkList() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.link_list = None <NEW_LINE> <DEDENT> def test_happy(self): <NEW_LINE> <INDENT> node_elements = [4, 3, 1, 5, 6, 7, 8] <NEW_LINE> for val in node_elements: <NEW_LINE> <INDENT> self.link_list.add(val) <NEW_LINE> <DEDENT> expected_result = [7, 6] <NEW_LINE> actual_result = [] <NEW_LINE> input_elements = [1, 2] <NEW_LINE> for element in input_elements: <NEW_LINE> <INDENT> actual_result.append( self.link_list.find_kth_to_last_element(k=element) ) <NEW_LINE> <DEDENT> self.assertEqual(expected_result, actual_result) <NEW_LINE> <DEDENT> def test_failure(self): <NEW_LINE> <INDENT> node_elements = [4, 3, 1, 5, 6, 7, 8] <NEW_LINE> for val in node_elements: <NEW_LINE> <INDENT> self.link_list.add(val) <NEW_LINE> <DEDENT> expected_result = [ "Invalid value k: a", "Invalid value k: None", "Invalid value k: -1" ] <NEW_LINE> actual_result = [] <NEW_LINE> input_elements = ['a', None, -1] <NEW_LINE> for element in input_elements: <NEW_LINE> <INDENT> actual_result.append( self.link_list.find_kth_to_last_element(k=element) ) <NEW_LINE> <DEDENT> self.assertEqual(expected_result, actual_result)
|
Test Cases
|
62599019507cdc57c63a5b3d
|
class FieldRule(CustomFieldRule): <NEW_LINE> <INDENT> def checkField(self, fieldObj): <NEW_LINE> <INDENT> return isKV(fieldObj.value)
|
检查整数列表(数组)
|
625990196fece00bbaccc752
|
class GoogleWifiAPI: <NEW_LINE> <INDENT> def __init__(self, host, conditions): <NEW_LINE> <INDENT> uri = 'http://' <NEW_LINE> resource = "{}{}{}".format(uri, host, ENDPOINT) <NEW_LINE> self._request = requests.Request('GET', resource).prepare() <NEW_LINE> self.raw_data = None <NEW_LINE> self.conditions = conditions <NEW_LINE> self.data = { ATTR_CURRENT_VERSION: STATE_UNKNOWN, ATTR_NEW_VERSION: STATE_UNKNOWN, ATTR_UPTIME: STATE_UNKNOWN, ATTR_LAST_RESTART: STATE_UNKNOWN, ATTR_LOCAL_IP: STATE_UNKNOWN, ATTR_STATUS: STATE_UNKNOWN } <NEW_LINE> self.available = True <NEW_LINE> self.update() <NEW_LINE> <DEDENT> @Throttle(MIN_TIME_BETWEEN_UPDATES) <NEW_LINE> def update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with requests.Session() as sess: <NEW_LINE> <INDENT> response = sess.send(self._request, timeout=10) <NEW_LINE> <DEDENT> self.raw_data = response.json() <NEW_LINE> self.data_format() <NEW_LINE> self.available = True <NEW_LINE> <DEDENT> except (ValueError, requests.exceptions.ConnectionError): <NEW_LINE> <INDENT> _LOGGER.warning("Unable to fetch data from Google Wifi") <NEW_LINE> self.available = False <NEW_LINE> self.raw_data = None <NEW_LINE> <DEDENT> <DEDENT> def data_format(self): <NEW_LINE> <INDENT> for attr_key in self.conditions: <NEW_LINE> <INDENT> value = MONITORED_CONDITIONS[attr_key] <NEW_LINE> try: <NEW_LINE> <INDENT> primary_key = value[0][0] <NEW_LINE> sensor_key = value[0][1] <NEW_LINE> if primary_key in self.raw_data: <NEW_LINE> <INDENT> sensor_value = self.raw_data[primary_key][sensor_key] <NEW_LINE> if (attr_key == ATTR_NEW_VERSION and sensor_value == '0.0.0.0'): <NEW_LINE> <INDENT> sensor_value = 'Latest' <NEW_LINE> <DEDENT> elif attr_key == ATTR_UPTIME: <NEW_LINE> <INDENT> sensor_value = round(sensor_value / (3600 * 24), 2) <NEW_LINE> <DEDENT> elif attr_key == ATTR_LAST_RESTART: <NEW_LINE> <INDENT> last_restart = ( dt.now() - timedelta(seconds=sensor_value)) <NEW_LINE> sensor_value = last_restart.strftime( '%Y-%m-%d %H:%M:%S') <NEW_LINE> <DEDENT> elif attr_key == ATTR_STATUS: <NEW_LINE> <INDENT> if sensor_value: <NEW_LINE> <INDENT> sensor_value = 'Online' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sensor_value = 'Offline' <NEW_LINE> <DEDENT> <DEDENT> elif attr_key == ATTR_LOCAL_IP: <NEW_LINE> <INDENT> if not self.raw_data['wan']['online']: <NEW_LINE> <INDENT> sensor_value = STATE_UNKNOWN <NEW_LINE> <DEDENT> <DEDENT> self.data[attr_key] = sensor_value <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> _LOGGER.error("Router does not support %s field. " "Please remove %s from monitored_conditions", sensor_key, attr_key) <NEW_LINE> self.data[attr_key] = STATE_UNKNOWN
|
Get the latest data and update the states.
|
62599019d18da76e235b781c
|
class Entity(dict): <NEW_LINE> <INDENT> __slots__ = ('ent_type', '__ent_id', '__hash', 'links') <NEW_LINE> def __init__(self, ent_type, ent_id): <NEW_LINE> <INDENT> super(Entity, self).__init__() <NEW_LINE> self.ent_type = ent_type <NEW_LINE> self.links = [] <NEW_LINE> self.__ent_id = None <NEW_LINE> self.__hash = None <NEW_LINE> self.ent_id = ent_id <NEW_LINE> <DEDENT> def set_ent_id(self, ent_id): <NEW_LINE> <INDENT> self.__ent_id = ent_id <NEW_LINE> self.__hash = hash(self.__ent_id) <NEW_LINE> <DEDENT> def get_ent_id(self): <NEW_LINE> <INDENT> return self.__ent_id <NEW_LINE> <DEDENT> ent_id = property(get_ent_id, set_ent_id) <NEW_LINE> def __hash__(self): <NEW_LINE> <INDENT> return self.__hash <NEW_LINE> <DEDENT> def iter_by_domains(self, domains): <NEW_LINE> <INDENT> for key, value in self.iteritems(): <NEW_LINE> <INDENT> domain = key[0] <NEW_LINE> if domain in domains: <NEW_LINE> <INDENT> yield key[1], value
|
Represents a single entity.
Keys are tuples of (domain, predicate).
The links attribute is a list to (type, id) tuples, referring to the
keys of entities stored in an Entities class.
No real checking is done to verify that all linked objects exist
or anything like that.
|
625990198c3a8732951f72ff
|
@export <NEW_LINE> class CorreoDialog(QtWidgets.QDialog): <NEW_LINE> <INDENT> def __init__(self, args: Iterable, target: Callable): <NEW_LINE> <INDENT> super(CorreoDialog, self).__init__() <NEW_LINE> self.setWindowTitle("Enviando correo...") <NEW_LINE> self.args = args <NEW_LINE> self.layout = QtWidgets.QVBoxLayout() <NEW_LINE> self.setLayout(self.layout) <NEW_LINE> label = "Enviando correo a: \t<b>%s</b>" % args[0] <NEW_LINE> self.layout.addWidget(QtWidgets.QLabel(label)) <NEW_LINE> self.resize(200, 100) <NEW_LINE> self.setModal(True) <NEW_LINE> self.thread = Thread(target=self.sendCorreo, args=(target,)) <NEW_LINE> self.thread.setDaemon(True) <NEW_LINE> self.finished = False <NEW_LINE> self.exception = None <NEW_LINE> <DEDENT> def closeEvent(self, event): <NEW_LINE> <INDENT> if self.finished: <NEW_LINE> <INDENT> self.thread = None <NEW_LINE> event.accept() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event.ignore() <NEW_LINE> <DEDENT> <DEDENT> def sendCorreo(self, func: Callable): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> func(*self.args) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.exception = Exception("Email error: " + str(e)) <NEW_LINE> print("Error:", self.exception) <NEW_LINE> <DEDENT> self.finished = True <NEW_LINE> self.close() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.thread.start()
|
Clase que representa el dialogo de envio de correos
|
6259901991af0d3eaad3abc1
|
class FileLock(object): <NEW_LINE> <INDENT> def __init__(self, fd, mode=None): <NEW_LINE> <INDENT> if has_fcntl and mode is None: <NEW_LINE> <INDENT> mode = fcntl.LOCK_EX <NEW_LINE> <DEDENT> self.fd = fd <NEW_LINE> self.mode = mode <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if has_fcntl: <NEW_LINE> <INDENT> fcntl.flock(self.fd, self.mode) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> if has_fcntl: <NEW_LINE> <INDENT> fcntl.flock(self.fd, fcntl.LOCK_UN)
|
Simple file locking
On platforms without fcntl, all operations in this class are no-ops.
|
6259901921a7993f00c66d1b
|
class TdmPolicy(TanhMlpPolicy): <NEW_LINE> <INDENT> def __init__( self, env, tdm_normalizer: TdmNormalizer=None, **kwargs ): <NEW_LINE> <INDENT> self.save_init_params(locals()) <NEW_LINE> self.observation_dim = env.observation_space.low.size <NEW_LINE> self.action_dim = env.action_space.low.size <NEW_LINE> self.goal_dim = env.goal_dim <NEW_LINE> super().__init__( input_size=self.observation_dim + self.goal_dim + 1, output_size=self.action_dim, **kwargs ) <NEW_LINE> self.env = env <NEW_LINE> self.tdm_normalizer = tdm_normalizer <NEW_LINE> <DEDENT> def forward( self, observations, goals, num_steps_left, return_preactivations=False, ): <NEW_LINE> <INDENT> if self.tdm_normalizer is not None: <NEW_LINE> <INDENT> observations, _, goals, num_steps_left = ( self.tdm_normalizer.normalize_all( observations, None, goals, num_steps_left ) ) <NEW_LINE> <DEDENT> flat_input = torch.cat((observations, goals, num_steps_left), dim=1) <NEW_LINE> return super().forward( flat_input, return_preactivations=return_preactivations, ) <NEW_LINE> <DEDENT> def get_action(self, ob_np, goal_np, tau_np): <NEW_LINE> <INDENT> actions = self.eval_np( ob_np[None], goal_np[None], tau_np[None], ) <NEW_LINE> return actions[0, :], {}
|
Rather than giving `g`, give `g - goalify(s)` as input.
|
62599019796e427e5384f520
|
class ParquetDataset(data.Dataset): <NEW_LINE> <INDENT> def __init__(self, filename, columns, dtypes=None, batch=None): <NEW_LINE> <INDENT> self._data_input = parquet_ops.parquet_input( filename, ["none", "gz"], columns=columns) <NEW_LINE> self._columns = columns <NEW_LINE> self._dtypes = dtypes <NEW_LINE> self._batch = 0 if batch is None else batch <NEW_LINE> super(ParquetDataset, self).__init__() <NEW_LINE> <DEDENT> def _inputs(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def _as_variant_tensor(self): <NEW_LINE> <INDENT> return parquet_ops.parquet_dataset( self._data_input, self._batch, output_types=self.output_types, output_shapes=self.output_shapes) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_classes(self): <NEW_LINE> <INDENT> return tuple([tensorflow.Tensor for _ in self._columns]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_shapes(self): <NEW_LINE> <INDENT> return tuple( [tensorflow.TensorShape([]) for _ in self._columns] ) if self._batch is None else tuple( [tensorflow.TensorShape([None]) for _ in self._columns] ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_types(self): <NEW_LINE> <INDENT> return self._dtypes
|
A Parquet Dataset that reads the parquet file.
|
625990195e10d32532ce3fd7
|
class ImageUploadInput(object): <NEW_LINE> <INDENT> empty_template = ('<input %(file)s>') <NEW_LINE> data_template = ('<div class="image-thumbnail">' ' <img %(image)s>' ' <input type="checkbox" name="%(marker)s">Delete</input>' ' <input %(text)s>' '</div>' '<input %(file)s>') <NEW_LINE> def __call__(self, field, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('id', field.id) <NEW_LINE> kwargs.setdefault('name', field.name) <NEW_LINE> args = { 'text': html_params(type='hidden', value=field.data, name=field.name), 'file': html_params(type='file', **kwargs), 'marker': '_%s-delete' % field.name } <NEW_LINE> if field.data and isinstance(field.data, string_types): <NEW_LINE> <INDENT> url = self.get_url(field) <NEW_LINE> args['image'] = html_params(src=url) <NEW_LINE> template = self.data_template <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template = self.empty_template <NEW_LINE> <DEDENT> return HTMLString(template % args) <NEW_LINE> <DEDENT> def get_url(self, field): <NEW_LINE> <INDENT> if field.thumbnail_size: <NEW_LINE> <INDENT> filename = field.thumbnail_fn(field.data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = field.data <NEW_LINE> <DEDENT> if field.url_relative_path: <NEW_LINE> <INDENT> filename = urljoin(field.url_relative_path, filename) <NEW_LINE> <DEDENT> return get_url(field.endpoint, filename=filename)
|
Renders a image input chooser field.
You can customize `empty_template` and `data_template` members to customize
look and feel.
|
62599019be8e80087fbbfe14
|
class ReplayBuffer: <NEW_LINE> <INDENT> def __init__(self, buffer_size, batch_size): <NEW_LINE> <INDENT> self.memory = deque(maxlen=buffer_size) <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"]) <NEW_LINE> <DEDENT> def add(self, state, action, reward, next_state, done): <NEW_LINE> <INDENT> e = self.experience(state, action, reward, next_state, done) <NEW_LINE> self.memory.append(e) <NEW_LINE> <DEDENT> def sample(self, batch_size=128): <NEW_LINE> <INDENT> return random.sample(self.memory, k=self.batch_size) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.memory)
|
Fixed-size buffer to store experience tuples.
|
62599019925a0f43d25e8de3
|
class KerasMobileNetDoFn(beam.DoFn): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.model = None <NEW_LINE> <DEDENT> def load_resize_img(self, url): <NEW_LINE> <INDENT> response = requests.get(url) <NEW_LINE> img_bytes = BytesIO(response.content) <NEW_LINE> img = load_img(img_bytes, target_size=(224, 224)) <NEW_LINE> return img <NEW_LINE> <DEDENT> def classify(self, url): <NEW_LINE> <INDENT> original = self.load_resize_img(url) <NEW_LINE> numpy_image = img_to_array(original) <NEW_LINE> image_batch = np.expand_dims(numpy_image, axis=0) <NEW_LINE> processed_image = preprocess_input(image_batch.copy()) <NEW_LINE> labels = [] <NEW_LINE> with self.graph.as_default(): <NEW_LINE> <INDENT> with self.session.as_default(): <NEW_LINE> <INDENT> predictions = self.model.predict(processed_image) <NEW_LINE> labels = decode_predictions(predictions, top=5) <NEW_LINE> <DEDENT> <DEDENT> return labels[0] <NEW_LINE> <DEDENT> def labels_to_dict(self, labels): <NEW_LINE> <INDENT> output = dict() <NEW_LINE> for lbl in labels: <NEW_LINE> <INDENT> (id, name, prob) = lbl <NEW_LINE> output[name] = "%.4f" % prob <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def start_bundle(self, context=None): <NEW_LINE> <INDENT> graph = tf.Graph() <NEW_LINE> with graph.as_default(): <NEW_LINE> <INDENT> session = tf.Session() <NEW_LINE> with session.as_default(): <NEW_LINE> <INDENT> self.model = MobileNet(weights='imagenet') <NEW_LINE> self.graph = graph <NEW_LINE> self.session = session <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def process(self, element): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> image_id, original_url = element.element <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> image_id, original_url = element <NEW_LINE> <DEDENT> print(element) <NEW_LINE> print(original_url) <NEW_LINE> labels = self.classify(original_url) <NEW_LINE> label_map = self.labels_to_dict(labels) <NEW_LINE> yield image_id, original_url, label_map
|
Read files from url and classify using Keras
|
62599019462c4b4f79dbc7ab
|
class Beta(BaseView): <NEW_LINE> <INDENT> template_name = 'beta.html'
|
A master view class to handle Beta reponses.
Currently accepts email addresses and sends them to the administrator.
|
625990190a366e3fb87dd797
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.