code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
@isaCard <NEW_LINE> class CriticalInfoCard(myuwCard): <NEW_LINE> <INDENT> def __init__(self, email=True, directory=True, residency=True): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.directory = directory <NEW_LINE> self.residency = residency <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @packElement <NEW_LINE> def fromElement(cls, e, date): <NEW_LINE> <INDENT> headers = e.find_elements_by_xpath('.//span[@class="notice-title"]') <NEW_LINE> titles = [e.text for e in headers] <NEW_LINE> email = 'Set Up UW Email' in titles <NEW_LINE> directory = 'Update Student Directory' in titles <NEW_LINE> residency = 'Non-Resident Classification' in titles <NEW_LINE> return cls(email, directory, residency) <NEW_LINE> <DEDENT> autoDiffs = { 'email': 'Set Up UW Email notice', 'directory': 'Student Directory notice', 'residency': 'Residency notice', } | Update Critical Info Card | 6259906e4428ac0f6e659da6 |
class TestSetup(unittest.TestCase): <NEW_LINE> <INDENT> layer = PAS_PLUGINS_Authomatic_PLONE_INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer["portal"] <NEW_LINE> self.installer = get_installer(self.portal, self.layer["request"]) <NEW_LINE> <DEDENT> def test_product_installed(self): <NEW_LINE> <INDENT> self.assertTrue(self.installer.is_product_installed("pas.plugins.authomatic")) <NEW_LINE> self.assertIn("authomatic", self.portal.acl_users) <NEW_LINE> <DEDENT> def test_uninstall(self): <NEW_LINE> <INDENT> self.installer.uninstall_product("pas.plugins.authomatic") <NEW_LINE> self.assertFalse(self.installer.is_product_installed("pas.plugins.authomatic")) <NEW_LINE> <DEDENT> def test_browserlayer(self): <NEW_LINE> <INDENT> from pas.plugins.authomatic.interfaces import IPasPluginsAuthomaticLayer <NEW_LINE> from plone.browserlayer import utils <NEW_LINE> self.assertTrue(IPasPluginsAuthomaticLayer in utils.registered_layers()) | Test that pas.plugins.authomatic is properly installed. | 6259906e97e22403b383c776 |
class ResolutionKnowledgeBase(KnowledgeBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.rules = [] <NEW_LINE> <DEDENT> def print_kb(self): <NEW_LINE> <INDENT> print(self.rules) <NEW_LINE> <DEDENT> def add_to_kb(self, query): <NEW_LINE> <INDENT> query = self.string_to_set(query) <NEW_LINE> for rule in self.rules: <NEW_LINE> <INDENT> if query == rule: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> self.rules.append(query) <NEW_LINE> <DEDENT> def string_to_set(self, query): <NEW_LINE> <INDENT> query = query.split('v') <NEW_LINE> query_as_set = set() <NEW_LINE> for elem in query: <NEW_LINE> <INDENT> query_as_set.add(elem) <NEW_LINE> <DEDENT> return query_as_set | Derived class used that represents the knowledge base when using
resolution. | 6259906e627d3e7fe0e086fb |
class SimpleClient(EWrapper, EClient): <NEW_LINE> <INDENT> def __init__(self, addr, port, client_id): <NEW_LINE> <INDENT> EClient. __init__(self, self) <NEW_LINE> self.connect(addr, port, client_id) <NEW_LINE> thread = Thread(target=self.run) <NEW_LINE> thread.start() <NEW_LINE> <DEDENT> @iswrapper <NEW_LINE> def currentTime(self, cur_time): <NEW_LINE> <INDENT> t = datetime.fromtimestamp(cur_time) <NEW_LINE> print('Current time: {}'.format(t)) <NEW_LINE> <DEDENT> @iswrapper <NEW_LINE> def error(self, req_id, code, msg): <NEW_LINE> <INDENT> print('Error {}: {}'.format(code, msg)) | Serves as the client and the wrapper | 6259906eaad79263cf430028 |
class CommentField(Field): <NEW_LINE> <INDENT> configuration = {"label": "", "value": "", "name": "", "height": 80, "width": 50 } <NEW_LINE> def __init__(self, data, event): <NEW_LINE> <INDENT> if not isinstance(data, dict): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> Field.__init__(self, data, event) <NEW_LINE> self.check_values() <NEW_LINE> self.create_label() <NEW_LINE> self.set_homogeneous(False) <NEW_LINE> self.set_spacing(10) <NEW_LINE> scrolled_window = Gtk.ScrolledWindow() <NEW_LINE> scrolled_window.set_min_content_height(self.data["height"]) <NEW_LINE> scrolled_window.set_min_content_width(self.data["width"]) <NEW_LINE> scrolled_window.set_shadow_type(Gtk.ShadowType.ETCHED_IN) <NEW_LINE> self.field = Gtk.TextView() <NEW_LINE> self.field.set_left_margin(10) <NEW_LINE> self.field.set_right_margin(10) <NEW_LINE> self.field.set_wrap_mode(Gtk.WrapMode.WORD) <NEW_LINE> if event is not None: <NEW_LINE> <INDENT> self.field.connect("focus-out-event", event) <NEW_LINE> <DEDENT> self.text_buffer = self.field.get_buffer() <NEW_LINE> self.text_buffer.set_text(self.data["value"]) <NEW_LINE> scrolled_window.add(self.field) <NEW_LINE> self.add(scrolled_window) <NEW_LINE> self.show_all() <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.text_buffer.get_text( self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), True) <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> self.text_buffer.set_text(value) | This class contains methods related the CommentField class. | 6259906e379a373c97d9a893 |
class ItemCategory(LoggedModel): <NEW_LINE> <INDENT> event = models.ForeignKey( Event, on_delete=models.CASCADE, related_name='categories', ) <NEW_LINE> name = I18nCharField( max_length=255, verbose_name=_("Category name"), ) <NEW_LINE> internal_name = models.CharField( verbose_name=_("Internal name"), help_text=_("If you set this, this will be used instead of the public name in the backend."), blank=True, null=True, max_length=255 ) <NEW_LINE> description = I18nTextField( blank=True, verbose_name=_("Category description") ) <NEW_LINE> position = models.IntegerField( default=0 ) <NEW_LINE> is_addon = models.BooleanField( default=False, verbose_name=_('Products in this category are add-on products'), help_text=_('If selected, the products belonging to this category are not for sale on their own. They can ' 'only be bought in combination with a product that has this category configured as a possible ' 'source for add-ons.') ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Product category") <NEW_LINE> verbose_name_plural = _("Product categories") <NEW_LINE> ordering = ('position', 'id') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> name = self.internal_name or self.name <NEW_LINE> if self.is_addon: <NEW_LINE> <INDENT> return _('{category} (Add-On products)').format(category=str(name)) <NEW_LINE> <DEDENT> return str(name) <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> super().delete(*args, **kwargs) <NEW_LINE> if self.event: <NEW_LINE> <INDENT> self.event.cache.clear() <NEW_LINE> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> super().save(*args, **kwargs) <NEW_LINE> if self.event: <NEW_LINE> <INDENT> self.event.cache.clear() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def sortkey(self): <NEW_LINE> <INDENT> return self.position, self.id <NEW_LINE> <DEDENT> def __lt__(self, other) -> bool: <NEW_LINE> <INDENT> return self.sortkey < other.sortkey | Items can be sorted into these categories.
:param event: The event this category belongs to
:type event: Event
:param name: The name of this category
:type name: str
:param position: An integer, used for sorting
:type position: int | 6259906e1b99ca400229016f |
class ChartTool(Folder): <NEW_LINE> <INDENT> meta_type = 'Naaya Chart Tool' <NEW_LINE> portal_id = 'portal_chart' <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> _properties = ( {'id': 'title', 'type': 'string', 'mode': 'w', 'label': 'Title'}, ) <NEW_LINE> manage_options = ( {'label':'Contents', 'action':'manage_main'}, {'label': 'View', 'action': 'index_html'}, ) <NEW_LINE> xmlswfchart = PageTemplateFile('zpt/xmlswfchart.zpt', globals()) <NEW_LINE> def __init__(self, id, **kw): <NEW_LINE> <INDENT> Folder.__init__(self, id) <NEW_LINE> self.manage_changeProperties(**kw) <NEW_LINE> <DEDENT> security.declarePrivate('loadXmlSwfChartsFiles') <NEW_LINE> def loadXmlSwfChartsFiles(self): <NEW_LINE> <INDENT> self.manage_addProduct['LocalFS'].manage_addLocalFS('XmlSwfCharts', '', join(dirname(__file__), 'XmlSwfCharts')) <NEW_LINE> <DEDENT> security.declarePublic('render') <NEW_LINE> def render(self, data_url, width=400, height=250): <NEW_LINE> <INDENT> charts_url = '%s/charts.swf?%s' % (self.XmlSwfCharts.absolute_url(), urllib.urlencode({'library_path': self.XmlSwfCharts.absolute_url() + '/' + 'charts_library', 'xml_source': data_url})) <NEW_LINE> return self.xmlswfchart(charts_url=charts_url, width=width, height=height) | Tool for generating charts
Usage example (ZPT):
<span tal:replace="structure python: here.portal_chart.render(here.chart_data.absolute_url())">
CHART
</span> | 6259906e091ae356687064a8 |
class ProductionConfig(Config): <NEW_LINE> <INDENT> TOKEN_EXPIRE_HOURS = 1 <NEW_LINE> BCRYPT_LOG_ROUNDS = 13 <NEW_LINE> PRESERVE_CONTEXT_ON_EXCEPTION = True | Production configuration. | 6259906e8a43f66fc4bf3a07 |
class TaxesNotAppliedToPartner(APIView): <NEW_LINE> <INDENT> permission_classes = [permissions.IsAuthenticatedOrReadOnly] <NEW_LINE> def get_object(self, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Partner.objects.get(id=id) <NEW_LINE> <DEDENT> except Partner.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, id, format=None): <NEW_LINE> <INDENT> taxes = (self.get_object(id)).taxes.all() <NEW_LINE> serializer = PartnerTaxSerializer(taxes, many=True, context={'request': request}) <NEW_LINE> return Response(serializer.data) | Retrouvez la/les taxe(s) pour laquelle/lesquelles le partenaire est exempté | 6259906e5fcc89381b266d91 |
@_enum(*_module_filetype_map.keys()) <NEW_LINE> class ModuleFileType(object): <NEW_LINE> <INDENT> def __init__(self, name, value): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._value == other._value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}.{}'.format(self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name.lower() <NEW_LINE> <DEDENT> COMPILED = None <NEW_LINE> DYNAMIC = None <NEW_LINE> extensions = None <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> SOURCE = None <NEW_LINE> UNKNOWN = None | A module file type. | 6259906e21bff66bcd7244db |
class TimingTextReporter(VerboseTextReporter): <NEW_LINE> <INDENT> def stopTest(self, method): <NEW_LINE> <INDENT> super(TimingTextReporter, self).stopTest(method) <NEW_LINE> self.write("(%.03f secs)\n" % self._lastTime) | Prints out each test as it is running, followed by the time taken for each
test to run. | 6259906e796e427e5384ffeb |
class CommandsPlugin(Plugin): <NEW_LINE> <INDENT> def get_dependencies(self) -> typing.Iterable[str]: <NEW_LINE> <INDENT> return { 'dewi_commands.commands.ImageHandlerCommandsPlugin', 'dewi_commands.commands.checksums.ChecksumsPlugin', 'dewi_commands.commands.dice.DicePlugin', 'dewi_commands.commands.edit.edit.EditPlugin', 'dewi_commands.commands.fetchcovidhu.FetchCovidHuPlugin', 'dewi_commands.commands.filesync.FileSyncPlugin', 'dewi_commands.commands.find.FindPlugin', 'dewi_commands.commands.hash.HashPlugin', 'dewi_commands.commands.http.HttpPlugin', 'dewi_commands.commands.jsonformatter.JSonFormatterPlugin', 'dewi_commands.commands.license.LicensePlugin', 'dewi_commands.commands.lithurgical.LithurgicalPlugin', 'dewi_commands.commands.primes.PrimesPlugin', 'dewi_commands.commands.split_zorp_log.SplitZorpLogPlugin', 'dewi_commands.commands.sysinfo.SysInfoPlugin', 'dewi_commands.commands.stocks.StocksPlugin', 'dewi_commands.commands.worktime.WorktimePlugin', } <NEW_LINE> <DEDENT> def load(self, c: Context): <NEW_LINE> <INDENT> pass | Commands of DEWI | 6259906e7b180e01f3e49c9e |
class AutoRestDurationTestService(object): <NEW_LINE> <INDENT> def __init__( self, base_url=None): <NEW_LINE> <INDENT> self.config = AutoRestDurationTestServiceConfiguration(base_url) <NEW_LINE> self._client = ServiceClient(None, self.config) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self.api_version = '1.0.0' <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.duration = DurationOperations( self._client, self.config, self._serialize, self._deserialize) | Test Infrastructure for AutoRest
:ivar config: Configuration for client.
:vartype config: AutoRestDurationTestServiceConfiguration
:ivar duration: Duration operations
:vartype duration: .operations.DurationOperations
:param str base_url: Service URL | 6259906e5fdd1c0f98e5f7fa |
class ParticleFilter(InferenceModule): <NEW_LINE> <INDENT> def __init__(self, ghostAgent, numParticles=300): <NEW_LINE> <INDENT> InferenceModule.__init__(self, ghostAgent); <NEW_LINE> self.setNumParticles(numParticles) <NEW_LINE> <DEDENT> def setNumParticles(self, numParticles): <NEW_LINE> <INDENT> self.numParticles = numParticles <NEW_LINE> <DEDENT> def initializeUniformly(self, gameState): <NEW_LINE> <INDENT> self.particleList = [] <NEW_LINE> for particle in range(1, self.numParticles + 1): <NEW_LINE> <INDENT> index = particle % len(self.legalPositions) <NEW_LINE> pos = self.legalPositions[index] <NEW_LINE> self.particleList.append(pos) <NEW_LINE> <DEDENT> <DEDENT> def observe(self, observation, gameState): <NEW_LINE> <INDENT> noisyDistance = observation <NEW_LINE> emissionModel = busters.getObservationDistribution(noisyDistance) <NEW_LINE> pacmanPosition = gameState.getPacmanPosition() <NEW_LINE> myList = [] <NEW_LINE> if noisyDistance is None: <NEW_LINE> <INDENT> for j in range(self.numParticles): <NEW_LINE> <INDENT> myList.append(self.getJailPosition()) <NEW_LINE> <DEDENT> self.particleList = myList <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> weight = util.Counter() <NEW_LINE> totalweight = 0 <NEW_LINE> for particle in self.particleList: <NEW_LINE> <INDENT> td = emissionModel[util.manhattanDistance(particle, pacmanPosition)] <NEW_LINE> weight[particle] += td <NEW_LINE> totalweight += td <NEW_LINE> <DEDENT> if totalweight == 0: <NEW_LINE> <INDENT> self.initializeUniformly(gameState) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> myList = [] <NEW_LINE> weight.normalize() <NEW_LINE> for key in weight: <NEW_LINE> <INDENT> num = (int) (weight[key] * self.numParticles) <NEW_LINE> for i in range(num): <NEW_LINE> <INDENT> myList.append(key) <NEW_LINE> <DEDENT> <DEDENT> self.particleList = myList <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def elapseTime(self, gameState): <NEW_LINE> <INDENT> self.particleList[:] = [util.sample(self.getPositionDistribution(self.setGhostPosition(gameState, x))) for x in self.particleList] <NEW_LINE> <DEDENT> def getBeliefDistribution(self): <NEW_LINE> <INDENT> myDict = util.Counter() <NEW_LINE> for loc in self.particleList: <NEW_LINE> <INDENT> myDict[loc] += 1/ (float)(self.numParticles) <NEW_LINE> <DEDENT> return myDict | A particle filter for approximately tracking a single ghost.
Useful helper functions will include random.choice, which chooses
an element from a list uniformly at random, and util.sample, which
samples a key from a Counter by treating its values as probabilities. | 6259906e2ae34c7f260ac95e |
class RemoveUserFromProjectHandler(AuthedTemplateHandler): <NEW_LINE> <INDENT> def get(self, task_id, user_id): <NEW_LINE> <INDENT> user_key = ndb.Key(urlsafe=user_id) <NEW_LINE> task_key = ndb.Key(urlsafe=task_id) <NEW_LINE> task = task_key.get() <NEW_LINE> if not task.is_top_level: <NEW_LINE> <INDENT> return self.abort(403, detail="Can only remove users from projects") <NEW_LINE> <DEDENT> if not user_key in task.users: <NEW_LINE> <INDENT> return self.abort(404, detail='User not assigned to project') <NEW_LINE> <DEDENT> if not is_admin(self.user_entity): <NEW_LINE> <INDENT> return self.abort(403, detail="Need admin permissions") <NEW_LINE> <DEDENT> task.users.remove(user_key) <NEW_LINE> task.put() <NEW_LINE> self.session.add_flash('User successfully removed from task') <NEW_LINE> redirect_url = self.uri_for('task-view', task_id=task.key.urlsafe()) <NEW_LINE> return self.redirect(redirect_url) | POST only route allowing to delete users from projects | 6259906e8e7ae83300eea904 |
class JarBuilder(object): <NEW_LINE> <INDENT> def __init__(self, jarfile, sourcedir, tsa): <NEW_LINE> <INDENT> self.libjars = [] <NEW_LINE> self.tsa = tsa <NEW_LINE> self.jarfile = Path(jarfile) <NEW_LINE> self.sourcedir = Path(sourcedir) <NEW_LINE> self.sources = list(self.sourcedir.listdir('*.java')) <NEW_LINE> self.jarcontent = [Path('Manifest.txt')] <NEW_LINE> self.jarcontent += [ Path(x) for x in self.sourcedir.listdir('*.class')] <NEW_LINE> <DEDENT> def add_lib(self, pth): <NEW_LINE> <INDENT> self.libjars.append(Path(pth)) <NEW_LINE> <DEDENT> def build_jar(self, outdir, alias): <NEW_LINE> <INDENT> flags = '-storepass "`cat ~/.secret/.keystore_password`"' <NEW_LINE> if self.tsa: <NEW_LINE> <INDENT> flags += ' -tsa {0}'.format(self.tsa) <NEW_LINE> <DEDENT> def run_signer(jarfile): <NEW_LINE> <INDENT> local("jarsigner %s %s %s" % (flags, jarfile, alias)) <NEW_LINE> local("jarsigner -verify %s" % jarfile) <NEW_LINE> <DEDENT> outdir = Path(outdir) <NEW_LINE> jarfile = outdir.child(self.jarfile) <NEW_LINE> if jarfile.needs_update(self.jarcontent): <NEW_LINE> <INDENT> jarcontent = [x.replace("$", r"\$") for x in self.jarcontent] <NEW_LINE> local("jar cvfm %s %s" % (jarfile, ' '.join(jarcontent))) <NEW_LINE> <DEDENT> run_signer(jarfile) <NEW_LINE> for libfile in self.libjars: <NEW_LINE> <INDENT> jarfile = outdir.child(libfile.name) <NEW_LINE> if not jarfile.exists() or libfile.needs_update([jarfile]): <NEW_LINE> <INDENT> libfile.copy(jarfile) <NEW_LINE> <DEDENT> run_signer(jarfile) <NEW_LINE> <DEDENT> <DEDENT> def build_classes(self): <NEW_LINE> <INDENT> flags = "-Xlint:unchecked" <NEW_LINE> if len(self.libjars): <NEW_LINE> <INDENT> cp = ':'.join(self.libjars) <NEW_LINE> flags += " -classpath %s" % cp <NEW_LINE> <DEDENT> for src in self.sources: <NEW_LINE> <INDENT> local("javac %s %s" % (flags, src)) | Holds the information needed for building a Java Archive (`.jar`)
file.
| 6259906ed486a94d0ba2d834 |
class FunctionTyped(Function): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.pop('direct',None) <NEW_LINE> super(FunctionTyped, self).__init__(*args, **kwargs) <NEW_LINE> self.direct = True <NEW_LINE> self.cursor_factory = simpycity.handle.TypedCursor | A Postgresql function that returns row(s) having only a single (typically composite) column | 6259906e167d2b6e312b81c9 |
class IImioSmartwebCoreLayer( IImioSmartwebCommonLayer, IPloneAppContenttypesLayer, ILayerSpecific, IThemeSpecific, ICollectiveMessagesviewletLayer, ): <NEW_LINE> <INDENT> pass | Marker interface that defines a browser layer. | 6259906e097d151d1a2c28e6 |
class Compose: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nodes = [] <NEW_LINE> self.hierarchy = None <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self._get_node(item) <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> return self._get_node(item) <NEW_LINE> <DEDENT> def _get_node(self, name): <NEW_LINE> <INDENT> for node in self.nodes: <NEW_LINE> <INDENT> if node.name == name: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_comparisons(self, item, comparisons=None, precision=4, random_index='dd', iterations=100, tolerance=0.0001, cr=True): <NEW_LINE> <INDENT> if isinstance(item, ahpy.Compare): <NEW_LINE> <INDENT> self.nodes.append(item) <NEW_LINE> <DEDENT> elif isinstance(item, (list, tuple)): <NEW_LINE> <INDENT> for i in item: <NEW_LINE> <INDENT> if isinstance(i, ahpy.Compare): <NEW_LINE> <INDENT> self.nodes.append(i) <NEW_LINE> <DEDENT> elif isinstance(i, str): <NEW_LINE> <INDENT> self.nodes.append(ahpy.Compare(*item)) <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nodes.append(ahpy.Compare(*i)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.nodes.append(ahpy.Compare(item, comparisons, precision, random_index, iterations, tolerance, cr)) <NEW_LINE> <DEDENT> <DEDENT> def add_hierarchy(self, hierarchy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.hierarchy = hierarchy <NEW_LINE> for name in self.hierarchy.keys(): <NEW_LINE> <INDENT> children = [self._get_node(child_name) for child_name in self.hierarchy[name]] <NEW_LINE> self._get_node(name).add_children(children) <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> msg = 'All comparisons must be added to the Compose object before adding a hierarchy.' <NEW_LINE> raise AttributeError(msg) <NEW_LINE> <DEDENT> <DEDENT> def report(self, name=None, show=False, verbose=False): <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> report = self._get_node(name).report(complete=False, show=show, verbose=verbose) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> report = self._get_node(list(self.hierarchy.keys())[0]).report(complete=True, show=show, verbose=verbose) <NEW_LINE> <DEDENT> return report | This class provides an alternative way to build a hierarchy of Compare objects using a dictionary
of parent-child relationships, as well as an alternative way to build Compare objects using a list or tuple
of the necessary inputs. | 6259906e4a966d76dd5f075f |
class ValidationError(Exception): <NEW_LINE> <INDENT> pass | Raised when an object fails validation checks. | 6259906ea05bb46b3848bd67 |
class ListAuth(Lister): <NEW_LINE> <INDENT> def take_action(self, args): <NEW_LINE> <INDENT> result = self.app.workspace.auth <NEW_LINE> header = ['auth_id', 'type'] <NEW_LINE> body = [] <NEW_LINE> for k, v in result.items(): <NEW_LINE> <INDENT> body.append((k, v['type'])) <NEW_LINE> <DEDENT> return [header, body] | List all authentication methods in current workspace | 6259906ebaa26c4b54d50b20 |
class UdwPsclickSession: <NEW_LINE> <INDENT> def __init__(self, schema): <NEW_LINE> <INDENT> pass | udw中newcookiesort对应日志的结构化解析parser。可以移植海源的newcookiesort_parser, | 6259906e5fdd1c0f98e5f7fc |
class SuppressValidator(ValidatorBase): <NEW_LINE> <INDENT> property_names = ValidatorBase.property_names + ['external_validator'] <NEW_LINE> external_validator = fields.MethodField( 'external_validator', title="External Validator", description=( "Ignored, as a validator isn't used here."), default="", required=0, enabled=0) <NEW_LINE> def need_validate(self, field, key, REQUEST): <NEW_LINE> <INDENT> return 0 | A validator that is actually not used.
| 6259906e99cbb53fe683275e |
class GetServerDeliveryMessages(AdminService): <NEW_LINE> <INDENT> class SimpleIO(AdminSIO): <NEW_LINE> <INDENT> input_required = 'sub_key' <NEW_LINE> output_optional = List('msg_list') <NEW_LINE> <DEDENT> def handle(self): <NEW_LINE> <INDENT> ps_tool = self.pubsub.get_pubsub_tool_by_sub_key(self.request.input.sub_key) <NEW_LINE> self.response.payload.msg_list = ps_tool.pull_messages(self.request.input.sub_key) | Returns a list of messages to be delivered to input endpoint. The messages must exist on current server.
| 6259906ea8370b77170f1c3e |
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(128), unique=True) <NEW_LINE> email = db.Column(db.String(64), unique=True) <NEW_LINE> password = db.Column(db.String(64), unique=True) <NEW_LINE> role_id = db.Column(db.Integer, db.ForeignKey(Role.id)) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return 'User:%s %s %s %s %s' % (self.id, self.name, self.email, self.password, self.role_id) | 用户表 多 | 6259906ee1aae11d1e7cf447 |
class DeploymentNotFoundException(DeploymentException): <NEW_LINE> <INDENT> pass | Deployment is not found exception | 6259906e32920d7e50bc78bd |
class GaussianS(Sregion): <NEW_LINE> <INDENT> def __init__(self, beg, end, weight, sd, h=1.0, coupled=True, label=0): <NEW_LINE> <INDENT> if math.isinf(sd): <NEW_LINE> <INDENT> raise ValueError("fwdpy11.GaussianS: sd not finite") <NEW_LINE> <DEDENT> if math.isnan(sd): <NEW_LINE> <INDENT> raise ValueError("fwdpy11.GaussianS: sd not a number") <NEW_LINE> <DEDENT> self.sd = float(sd) <NEW_LINE> super(GaussianS, self).__init__(beg, end, weight, h, coupled, label) <NEW_LINE> <DEDENT> def callback(self): <NEW_LINE> <INDENT> from .fwdpp_extensions import makeGaussianSH <NEW_LINE> return makeGaussianSH(self.sd, self.h) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> x = 'regions.GaussianS(beg=%s,end=%s,weight=%s,' <NEW_LINE> x += 'sd=%s,h=%s,coupled=%s,label=%s)' <NEW_LINE> return x % (self.b, self.e, self.w, self.sd, self.h, self.c, self.l) | Gaussian distribution on selection coefficients
(effect sizes for sims of quantitative traits)
Attributes:
* b: the beginning of the region
* e: the end of the region
* w: the "weight" assigned to the region
* sd: the standard deviation
* h: the dominance ter
* l: A label assigned to the region.
Labels must be integers, and can be used to
'tag' mutations arising in different regions.
The mean is zero.
See :func:`evolve_regions` for how this class may be used to
parameterize a simulation | 6259906e4527f215b58eb5db |
class ESNHardLimiter(ESN): <NEW_LINE> <INDENT> def predict(self, X, testLen=None): <NEW_LINE> <INDENT> y = ESN.predict(self, X, testLen) <NEW_LINE> y = np.array([self.alphabet[np.argmin( [abs(yi - i) for i in self.alphabet])] for yi in y]) <NEW_LINE> if self.outSize == None: <NEW_LINE> <INDENT> y = y.reshape(y.shape[0]) <NEW_LINE> <DEDENT> return y | Builds an Echo State Network with hard limiter to adjust output
Subclass of ESN; Changes predict method
Parameters
----------
resSize : float, optional (default=1000)
The number of nodes in the reservoir.
a : float, optional (default=0.3)
Leak rate of the neurons.
initLen : float, optional (default=0)
Number of steps for initialization of reservoir. If no option
passed then length of input divided by 10 is used. | 6259906ef9cc0f698b1c5f06 |
class Post(models.Model): <NEW_LINE> <INDENT> STATUS_CHOICES = ( (1, _('Draft')), (2, _('Public')), ) <NEW_LINE> title = models.CharField(_('title'), max_length=200) <NEW_LINE> slug = models.SlugField(_('slug'), unique=True) <NEW_LINE> author = models.ForeignKey(User,related_name="blog_for") <NEW_LINE> body = models.TextField(_('body')) <NEW_LINE> tease = models.TextField(_('tease'), blank=True) <NEW_LINE> status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2) <NEW_LINE> allow_comments = models.BooleanField(_('allow comments'), default=True) <NEW_LINE> publish = models.DateTimeField(_('publish')) <NEW_LINE> created = models.DateTimeField(_('created'), auto_now_add=True) <NEW_LINE> modified = models.DateTimeField(_('modified'), auto_now=True) <NEW_LINE> categories = models.ManyToManyField(Category, blank=True) <NEW_LINE> tags = TagField() <NEW_LINE> objects = PublicManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('post') <NEW_LINE> verbose_name_plural = _('posts') <NEW_LINE> db_table = 'blog_posts' <NEW_LINE> ordering = ('-publish',) <NEW_LINE> get_latest_by = 'publish' <NEW_LINE> <DEDENT> class Admin: <NEW_LINE> <INDENT> list_display = ('title', 'publish', 'status') <NEW_LINE> list_filter = ('publish', 'categories', 'status') <NEW_LINE> search_fields = ('title', 'body') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s' % self.title <NEW_LINE> <DEDENT> @permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return ('blog_detail', None, { 'slug': self.slug }) <NEW_LINE> <DEDENT> def get_previous_post(self): <NEW_LINE> <INDENT> return self.get_previous_by_publish(status__gte=2) <NEW_LINE> <DEDENT> def get_next_post(self): <NEW_LINE> <INDENT> return self.get_next_by_publish(status__gte=2) | Post model. | 6259906e66673b3332c31c75 |
class CreateGroupResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.GroupId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.GroupId = params.get("GroupId") <NEW_LINE> self.RequestId = params.get("RequestId") | CreateGroup response structure.
| 6259906e76e4537e8c3f0dfb |
class Response(object): <NEW_LINE> <INDENT> def __init__(self, clicker_id=None, response=None, click_time=None, seq_num=None, command=None): <NEW_LINE> <INDENT> if click_time is None: <NEW_LINE> <INDENT> self.click_time = time.time() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.click_time = click_time <NEW_LINE> <DEDENT> if command is not None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.clicker_id = clicker_id <NEW_LINE> self.response = response <NEW_LINE> self.seq_num = seq_num <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(other) is Response: <NEW_LINE> <INDENT> return self.clicker_id == other.clicker_id and self.response == other.response and self.seq_num == other.seq_num <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if type(other) is Response: <NEW_LINE> <INDENT> return self.clicker_id != other.clicker_id or self.response != other.response or self.seq_num != other.seq_num <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{0}: {1} ({2} at {3})".format(self.clicker_id, self.response, self.seq_num, self.click_time) | Keeps track of all relavent information about a clicker response | 6259906e2c8b7c6e89bd505d |
class CliffGridworld(BaseGridworld): <NEW_LINE> <INDENT> def __init__(self, width=12, height=4, start_state=(0,0), goal_state=(11,0), terminal_states=[(x,0) for x in range(1,11)]): <NEW_LINE> <INDENT> super().__init__(width, height, start_state, goal_state, terminal_states) <NEW_LINE> <DEDENT> def get_state_reward_transition(self, state, action): <NEW_LINE> <INDENT> next_state = np.array(state) + np.array(action) <NEW_LINE> next_state = self._clip_state_to_grid(next_state) <NEW_LINE> next_state = int(next_state[0]), int(next_state[1]) <NEW_LINE> if next_state in self.terminal_states: <NEW_LINE> <INDENT> next_state = self.start_state <NEW_LINE> reward = -100 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reward = -1 <NEW_LINE> <DEDENT> return next_state, reward | Example 6.6 | 6259906e1f037a2d8b9e54a6 |
class derivfuncfloat(derivbase, funcfloat): <NEW_LINE> <INDENT> def __init__(self, func, n, accuracy, scaledown, funcstr=None, memoize=None, memo=None): <NEW_LINE> <INDENT> self.n = int(n) <NEW_LINE> self.accuracy = float(accuracy) <NEW_LINE> self.scaledown = float(scaledown) <NEW_LINE> if funcstr: <NEW_LINE> <INDENT> self.funcstr = str(funcstr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.funcstr = e.unusedarg() <NEW_LINE> <DEDENT> if memoize is not None: <NEW_LINE> <INDENT> self.memoize = memoize <NEW_LINE> <DEDENT> if memo is None: <NEW_LINE> <INDENT> self.memo = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.memo = memo <NEW_LINE> <DEDENT> self.other_func = func <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return integfunc(self.other_func, self.n, self.accuracy, self.scaledown, self.funcstr, self.memoize, self.memo) <NEW_LINE> <DEDENT> @rabbit <NEW_LINE> def calc(self, x=None): <NEW_LINE> <INDENT> if x is None: <NEW_LINE> <INDENT> return self.other_func.call([]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.other_func.call([x]) | Implements A Derivative Function Of A Fake Function. | 6259906e38b623060ffaa48f |
class Test_3_to_2(calculate_error, unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> param_ref = np.array([0.5, 0.5, 0.5]) <NEW_LINE> Q_ref = linear_model1(param_ref) <NEW_LINE> sampler = bsam.sampler(linear_model1) <NEW_LINE> input_samples = sample.sample_set(3) <NEW_LINE> input_samples.set_domain(np.repeat([[0.0, 1.0]], 3, axis=0)) <NEW_LINE> input_samples = sampler.random_sample_set( 'random', input_samples, num_samples=1E3) <NEW_LINE> disc = sampler.compute_QoI_and_create_discretization(input_samples, globalize=True) <NEW_LINE> simpleFunP.regular_partition_uniform_distribution_rectangle_scaled( data_set=disc, Q_ref=Q_ref, rect_scale=0.5) <NEW_LINE> num = disc.check_nums() <NEW_LINE> disc._output_sample_set.set_error_estimates(0.01 * np.ones((num, 2))) <NEW_LINE> jac = np.zeros((num, 2, 3)) <NEW_LINE> jac[:, :, :] = np.array( [[0.506, 0.463], [0.253, 0.918], [0.085, 0.496]]).transpose() <NEW_LINE> disc._input_sample_set.set_jacobians(jac) <NEW_LINE> self.disc = disc | Testing :meth:`bet.calculateP.calculateError` on a
3 to 2 map. | 6259906ea05bb46b3848bd68 |
class MultipleWaiter(Waiter): <NEW_LINE> <INDENT> __slots__ = ['_values'] <NEW_LINE> def __init__(self, hub=None): <NEW_LINE> <INDENT> Waiter.__init__(self, hub) <NEW_LINE> self._values = [] <NEW_LINE> <DEDENT> def switch(self, value): <NEW_LINE> <INDENT> self._values.append(value) <NEW_LINE> Waiter.switch(self, True) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> if not self._values: <NEW_LINE> <INDENT> Waiter.get(self) <NEW_LINE> Waiter.clear(self) <NEW_LINE> <DEDENT> return self._values.pop(0) | An internal extension of Waiter that can be used if multiple objects
must be waited on, and there is a chance that in between waits greenlets
might be switched out. All greenlets that switch to this waiter
will have their value returned.
This does not handle exceptions or throw methods. | 6259906e56b00c62f0fb4145 |
class MarkdownMarkupFilter(MarkupFilter): <NEW_LINE> <INDENT> title = 'Markdown' <NEW_LINE> use_pygments = False <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import pygments <NEW_LINE> self.use_pygments = True <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def render(self, text, **kwargs): <NEW_LINE> <INDENT> from markdown import markdown <NEW_LINE> if self.use_pygments: <NEW_LINE> <INDENT> text = markdown(text, ['codehilite'], **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = markdown(text, **kwargs) <NEW_LINE> <DEDENT> return text | Applies Markdown conversion to a string, and returns the HTML. If the
pygments library is installed, it highlights code blocks with it. | 6259906e7047854f46340c2f |
class Person(BaseModel): <NEW_LINE> <INDENT> logger.info("Specifying details for the Person class.") <NEW_LINE> person_name = CharField(primary_key=True, max_length=30) <NEW_LINE> lives_in_town = CharField(max_length=40) <NEW_LINE> nickname = CharField(max_length=20, null=True) | This class defines Person, which maintains details of someone
for whom we want to research career to date. | 6259906e3d592f4c4edbc759 |
class PublicUserAPITests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_create_valid_user_success(self): <NEW_LINE> <INDENT> playload = { "name": "Test User", "email": "[email protected]", "password": "test12345", } <NEW_LINE> res = self.client.post(CREATE_USER_URL, playload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_201_CREATED) <NEW_LINE> user = get_user_model().objects.get(**res.data) <NEW_LINE> self.assertTrue(user.check_password(playload["password"])) <NEW_LINE> self.assertNotIn("password", res.data) <NEW_LINE> <DEDENT> def test_existing_user(self): <NEW_LINE> <INDENT> playload = { "name": "Test User", "email": "[email protected]", "password": "test12345", } <NEW_LINE> create_user(**playload) <NEW_LINE> res = self.client.post(CREATE_USER_URL, playload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_password_too_short(self): <NEW_LINE> <INDENT> playload = {"name": "Test User", "email": "[email protected]", "password": "test"} <NEW_LINE> res = self.client.post(CREATE_USER_URL, playload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> user_exist = get_user_model().objects.filter(email=playload["email"]).exists() <NEW_LINE> self.assertFalse(user_exist) <NEW_LINE> <DEDENT> def test_create_token_for_user(self): <NEW_LINE> <INDENT> payload = { "name": "John Doe", "email": "[email protected]", "password": "john1234", } <NEW_LINE> create_user(**payload) <NEW_LINE> payload_login = {"email": "[email protected]", "password": "john1234"} <NEW_LINE> res = self.client.post(CREATE_TOKEN_URL, payload_login) <NEW_LINE> self.assertIn("access", res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_create_token_invalid_credential(self): <NEW_LINE> <INDENT> payload = { "name": "John Doe", "email": "[email protected]", "password": "john1234", } <NEW_LINE> create_user(**payload) <NEW_LINE> payload_login = {"email": "[email protected]", "password": "john1234"} <NEW_LINE> res = self.client.post(CREATE_TOKEN_URL, payload_login) <NEW_LINE> self.assertNotIn("access", res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> def test_create_token_no_user(self): <NEW_LINE> <INDENT> payload = {"email": "[email protected]", "password": "jane12345"} <NEW_LINE> res = self.client.post(CREATE_TOKEN_URL, payload) <NEW_LINE> self.assertNotIn("access", res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> def test_create_token_missing_fields(self): <NEW_LINE> <INDENT> res = self.client.post(CREATE_TOKEN_URL, {"email": "test", "password": ""}) <NEW_LINE> self.assertNotIn("access", res.data) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_retrive_user_unauthorized(self): <NEW_LINE> <INDENT> res = self.client.get(ME_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test user's api (public) | 6259906e009cb60464d02daf |
class gThread(threading.Thread, wx.EvtHandler): <NEW_LINE> <INDENT> requestId = 0 <NEW_LINE> def __init__(self, requestQ=None, resultQ=None, **kwds): <NEW_LINE> <INDENT> wx.EvtHandler.__init__(self) <NEW_LINE> self.terminate = False <NEW_LINE> threading.Thread.__init__(self, **kwds) <NEW_LINE> if requestQ is None: <NEW_LINE> <INDENT> self.requestQ = Queue.Queue() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.requestQ = requestQ <NEW_LINE> <DEDENT> if resultQ is None: <NEW_LINE> <INDENT> self.resultQ = Queue.Queue() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.resultQ = resultQ <NEW_LINE> <DEDENT> self.setDaemon(True) <NEW_LINE> self.Bind(EVT_CMD_DONE, self.OnDone) <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def Run(self, *args, **kwds): <NEW_LINE> <INDENT> gThread.requestId += 1 <NEW_LINE> self.requestQ.put((gThread.requestId, args, kwds)) <NEW_LINE> return gThread.requestId <NEW_LINE> <DEDENT> def GetId(self): <NEW_LINE> <INDENT> return gThread.requestId + 1 <NEW_LINE> <DEDENT> def SetId(self, id): <NEW_LINE> <INDENT> gThread.requestId = id <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> requestId, args, kwds = self.requestQ.get() <NEW_LINE> for key in ('callable', 'ondone', 'userdata'): <NEW_LINE> <INDENT> if key in kwds: <NEW_LINE> <INDENT> vars()[key] = kwds[key] <NEW_LINE> del kwds[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vars()[key] = None <NEW_LINE> <DEDENT> <DEDENT> requestTime = time.time() <NEW_LINE> ret = None <NEW_LINE> exception = None <NEW_LINE> time.sleep(.01) <NEW_LINE> if self.terminate: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> ret = vars()['callable'](*args, **kwds) <NEW_LINE> if self.terminate: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.resultQ.put((requestId, ret)) <NEW_LINE> event = wxCmdDone(ondone=vars()['ondone'], kwds=kwds, args=args, ret=ret, exception=exception, userdata=vars()['userdata'], pid=requestId) <NEW_LINE> wx.PostEvent(self, event) <NEW_LINE> <DEDENT> <DEDENT> def OnDone(self, event): <NEW_LINE> <INDENT> if event.ondone: <NEW_LINE> <INDENT> event.ondone(event) <NEW_LINE> <DEDENT> <DEDENT> def Terminate(self): <NEW_LINE> <INDENT> self.terminate = True | Thread for various backends | 6259906ef548e778e596ce05 |
class Participant(models.Model): <NEW_LINE> <INDENT> game = models.ForeignKey(Event) <NEW_LINE> players = models.ManyToManyField(User, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.game.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'Participants' | Lists of participants for each game. | 6259906e4a966d76dd5f0762 |
class son(common.Common): <NEW_LINE> <INDENT> specialchars = u"ɲŋšžãõẽĩƝŊŠŽÃÕẼĨ" | This class represents Songhai. | 6259906e92d797404e389797 |
class Float(Numeric): <NEW_LINE> <INDENT> __visit_name__ = "float" <NEW_LINE> scale = None <NEW_LINE> def __init__( self, precision=None, asdecimal=False, decimal_return_scale=None ): <NEW_LINE> <INDENT> self.precision = precision <NEW_LINE> self.asdecimal = asdecimal <NEW_LINE> self.decimal_return_scale = decimal_return_scale <NEW_LINE> <DEDENT> def result_processor(self, dialect, coltype): <NEW_LINE> <INDENT> if self.asdecimal: <NEW_LINE> <INDENT> return processors.to_decimal_processor_factory( decimal.Decimal, self._effective_decimal_return_scale ) <NEW_LINE> <DEDENT> elif dialect.supports_native_decimal: <NEW_LINE> <INDENT> return processors.to_float <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Type representing floating point types, such as ``FLOAT`` or ``REAL``.
This type returns Python ``float`` objects by default, unless the
:paramref:`.Float.asdecimal` flag is set to True, in which case they
are coerced to ``decimal.Decimal`` objects.
.. note::
The :class:`.Float` type is designed to receive data from a database
type that is explicitly known to be a floating point type
(e.g. ``FLOAT``, ``REAL``, others)
and not a decimal type (e.g. ``DECIMAL``, ``NUMERIC``, others).
If the database column on the server is in fact a Numeric
type, such as ``DECIMAL`` or ``NUMERIC``, use the :class:`.Numeric`
type or a subclass, otherwise numeric coercion between
``float``/``Decimal`` may or may not function as expected. | 6259906e71ff763f4b5e9021 |
class SignRepresentation_abstract(Representation_abstract): <NEW_LINE> <INDENT> def __init__(self, group, base_ring, sign_function=None): <NEW_LINE> <INDENT> self.sign_function = sign_function <NEW_LINE> if sign_function is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sign_function = self._default_sign <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise TypeError("a sign function must be given") <NEW_LINE> <DEDENT> <DEDENT> cat = Modules(base_ring).WithBasis().FiniteDimensional() <NEW_LINE> Representation_abstract.__init__(self, group, base_ring, ["v"], category=cat) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Sign representation of {} over {}".format( self._semigroup, self.base_ring() ) <NEW_LINE> <DEDENT> def side(self): <NEW_LINE> <INDENT> return "twosided" <NEW_LINE> <DEDENT> class Element(CombinatorialFreeModule.Element): <NEW_LINE> <INDENT> def _acted_upon_(self, scalar, self_on_left=False): <NEW_LINE> <INDENT> if isinstance(scalar, Element): <NEW_LINE> <INDENT> P = self.parent() <NEW_LINE> if P._semigroup.has_coerce_map_from(scalar.parent()): <NEW_LINE> <INDENT> scalar = P._semigroup(scalar) <NEW_LINE> return self if P.sign_function(scalar) > 0 else -self <NEW_LINE> <DEDENT> ret = CombinatorialFreeModule.Element._acted_upon_(self, scalar, self_on_left) <NEW_LINE> if ret is not None: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> if P._semigroup_algebra.has_coerce_map_from(scalar.parent()): <NEW_LINE> <INDENT> if not self: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> sum_scalar_coeff = 0 <NEW_LINE> scalar = P._semigroup_algebra(scalar) <NEW_LINE> for ms, cs in scalar: <NEW_LINE> <INDENT> sum_scalar_coeff += P.sign_function(ms) * cs <NEW_LINE> <DEDENT> return sum_scalar_coeff * self <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> return CombinatorialFreeModule.Element._acted_upon_( self, scalar, self_on_left ) | Generic implementation of a sign representation.
The sign representation of a semigroup `S` over a commutative ring
`R` is the `1`-dimensional `R`-module on which every element of `S`
acts by 1 if order of element is even (including 0) or -1 if order of element if odd.
This is simultaneously a left and right representation.
INPUT:
- ``permgroup`` -- a permgroup
- ``base_ring`` -- the base ring for the representation
- ``sign_function`` -- a function which returns 1 or -1 depending on the elements sign
REFERENCES:
- :wikipedia:`Representation_theory_of_the_symmetric_group` | 6259906eac7a0e7691f73d61 |
class ListDocumentTest(GSoCDjangoTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.init() <NEW_LINE> self.data.createHost() <NEW_LINE> <DEDENT> def testListDocument(self): <NEW_LINE> <INDENT> url = '/gsoc/documents/' + self.gsoc.key().name() <NEW_LINE> response = self.get(url) <NEW_LINE> self.assertGSoCTemplatesUsed(response) <NEW_LINE> response = self.getListResponse(url, 0) <NEW_LINE> self.assertIsJsonResponse(response) <NEW_LINE> data = response.context['data'][''] <NEW_LINE> self.assertEqual(1, len(data)) | Test document list page.
| 6259906e66673b3332c31c77 |
class MessageVoiceId(ServerMessage): <NEW_LINE> <INDENT> def clientAction(self, dummyClient, move): <NEW_LINE> <INDENT> if Sound.enabled: <NEW_LINE> <INDENT> move.player.voice = Voice.locate(move.source) <NEW_LINE> if not move.player.voice: <NEW_LINE> <INDENT> return Message.ClientWantsVoiceData, move.source | we got a voice id from the server. If we have no sounds for
this voice, ask the server | 6259906e1b99ca4002290172 |
class Bin(): <NEW_LINE> <INDENT> def __init__(self, posixdate): <NEW_LINE> <INDENT> self.posixdate = posixdate <NEW_LINE> self.datalist = [] <NEW_LINE> self.aurorasighting = "" <NEW_LINE> self.stormthreshold = "" <NEW_LINE> self.carrington_rotation = "" <NEW_LINE> <DEDENT> def average_datalist(self): <NEW_LINE> <INDENT> avgvalue = 0 <NEW_LINE> if len(self.datalist) > 0: <NEW_LINE> <INDENT> for item in self.datalist: <NEW_LINE> <INDENT> avgvalue = float(avgvalue) + float(item) <NEW_LINE> <DEDENT> avgvalue = avgvalue / float(len(self.datalist)) <NEW_LINE> avgvalue = round(avgvalue, 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> avgvalue = 0 <NEW_LINE> <DEDENT> return avgvalue <NEW_LINE> <DEDENT> def minmax_datalist(self): <NEW_LINE> <INDENT> temp = sorted(self.datalist) <NEW_LINE> if len(temp) > 0: <NEW_LINE> <INDENT> rangevalue = float(temp[len(temp)-1]) - float(temp[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rangevalue = 0 <NEW_LINE> <DEDENT> rangevalue = round(rangevalue, 5) <NEW_LINE> return rangevalue <NEW_LINE> <DEDENT> def posix2utc(self): <NEW_LINE> <INDENT> utctime = time.gmtime(int(float(self.posixdate))) <NEW_LINE> utctime = time.strftime('%Y-%m-%d %H:%M', utctime) <NEW_LINE> return utctime <NEW_LINE> <DEDENT> def print_csv_header(self): <NEW_LINE> <INDENT> returnstring = "Date/Time(UTC), Geomagnetic Activity, Storm Detected, Aurora Sighted, Carrington Rotation Marker" <NEW_LINE> return returnstring <NEW_LINE> <DEDENT> def print_values(self): <NEW_LINE> <INDENT> returnstring = str(self.posix2utc()) + "," + str(self.minmax_datalist()) + "," + str(self.stormthreshold) + "," + str(self.aurorasighting) + "," + str(self.carrington_rotation) <NEW_LINE> return returnstring | DataBin - This objects allows us to crate a bin of values.
Calculates the average value of the bin | 6259906e167d2b6e312b81cb |
class AmongUs2: <NEW_LINE> <INDENT> def __init__(self,citizens_list,angels_list,devils_list): <NEW_LINE> <INDENT> self.citizens_list=citizens_list <NEW_LINE> self.angels_list=angels_list <NEW_LINE> self.devils_list=devils_list | contains info about game at a given point of time | 6259906eadb09d7d5dc0bde4 |
class EditProfileView(generics.UpdateAPIView): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = EditProfileSerializer <NEW_LINE> permission_classes = (PrivateTokenAccessPermission, ) <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> return self.request.user <NEW_LINE> <DEDENT> def update(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(EditProfileView, self).update(request, *args, **kwargs) | API for Profile Detail | 6259906e3539df3088ecdb16 |
class NonExistingExternalProgram(ExternalProgram): <NEW_LINE> <INDENT> def __init__(self, name: str = 'nonexistingprogram') -> None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.command = [None] <NEW_LINE> self.path = None <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> r = '<{} {!r} -> {!r}>' <NEW_LINE> return r.format(self.__class__.__name__, self.name, self.command) <NEW_LINE> <DEDENT> def found(self) -> bool: <NEW_LINE> <INDENT> return False | A program that will never exist | 6259906e7d847024c075dc57 |
class DataGenerator(keras.utils.Sequence): <NEW_LINE> <INDENT> def __init__(self, id_list, example_count=270, batch_size=32, mean=0, disper=1): <NEW_LINE> <INDENT> self.id_list = id_list <NEW_LINE> self.example_count = example_count <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.mean = mean <NEW_LINE> self.disper = disper <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> num = index % len(self.id_list) <NEW_LINE> ind = self.id_list[num] <NEW_LINE> p = re.compile('/([0-9]+)_([0-9]+)') <NEW_LINE> num_list = [p.search(file).group(2) for file in glob.glob('./../Data/train_db/%s*' % ind)] <NEW_LINE> x1 = pd.read_csv(name(ind, num_list[0]), delimiter=' ', header=None).drop([0,1,402],axis=1) <NEW_LINE> x1 = (x1 - self.mean)/self.disper <NEW_LINE> l = [] <NEW_LINE> for i in range(int(self.batch_size/2)): <NEW_LINE> <INDENT> name1 = '' <NEW_LINE> rand1 = random.randint(1,len(num_list)-1) <NEW_LINE> name1 = name(ind,num_list[rand1]) <NEW_LINE> x_same = pd.read_csv(name1 , delimiter=' ', header=None).drop([0,1,402],axis=1) <NEW_LINE> x_same = (x_same - self.mean)/self.disper <NEW_LINE> x_same['label'] = 1 <NEW_LINE> l.append(x_same) <NEW_LINE> num2=num <NEW_LINE> name2 = '' <NEW_LINE> while num2 == num or not os.path.isfile(name2): <NEW_LINE> <INDENT> rand2 = random.randint(0,self.example_count-1) <NEW_LINE> rand3 = random.randint(0,len(self.id_list)-1) <NEW_LINE> num2 = rand3 <NEW_LINE> ind2 = self.id_list[num2] <NEW_LINE> name2 = name(ind2,rand2) <NEW_LINE> <DEDENT> x_another = pd.read_csv(name2, delimiter=' ', header=None).drop([0,1,402],axis=1) <NEW_LINE> x_another = (x_another - self.mean)/self.disper <NEW_LINE> x_another['label'] = 0 <NEW_LINE> l.append(x_another) <NEW_LINE> <DEDENT> partners = pd.concat(l, axis=0) <NEW_LINE> X = cros(x1, partners) <NEW_LINE> y = X.pop('label') <NEW_LINE> return X.values, y.values <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.id_list) <NEW_LINE> <DEDENT> def on_epoch_end(self): <NEW_LINE> <INDENT> pass | Generates data for Keras | 6259906e23849d37ff85292f |
class PubPlanView(TemplateView): <NEW_LINE> <INDENT> template_name = 'publication-plan.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.year = int(self.kwargs['year']) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.year = timezone.now().year <NEW_LINE> <DEDENT> queryset = Issue.objects.filter(publication_date__year=self.year) <NEW_LINE> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['issue_list'] = self.get_queryset().reverse() <NEW_LINE> context['year'] = self.year <NEW_LINE> return context | Publication plan | 6259906e5166f23b2e244c4e |
class SelfPasswordChangeForm(forms.Form): <NEW_LINE> <INDENT> password = forms.CharField( required=True, min_length=6, max_length=20, error_messages={ "required": u"密码不能为空" }) <NEW_LINE> confirm_password = forms.CharField( required=True, min_length=6, max_length=20, error_messages={ "required": u"确认密码不能为空" }) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(SelfPasswordChangeForm, self).clean() <NEW_LINE> password = cleaned_data.get("password") <NEW_LINE> confirm_password = cleaned_data.get("confirm_password") <NEW_LINE> if password != confirm_password: <NEW_LINE> <INDENT> raise forms.ValidationError("两次密码输入不一致") | 用户自行修改密码 | 6259906e5fdd1c0f98e5f800 |
class PyNbclient(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://jupyter.org/" <NEW_LINE> pypi = "nbclient/nbclient-0.5.0.tar.gz" <NEW_LINE> version('0.5.0', sha256='8ad52d27ba144fca1402db014857e53c5a864a2f407be66ca9d74c3a56d6591d') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('py-setuptools', type='build') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('py-async-generator', type=('build', 'run')) <NEW_LINE> depends_on('py-nest-asyncio', type=('build', 'run')) | A client library for executing notebooks.
Formally nbconvert's ExecutePreprocessor. | 6259906e4c3428357761bb2d |
class ItemError(PlaidError): <NEW_LINE> <INDENT> pass | There is invalid information about an item or it is not supported. | 6259906e7d43ff248742804f |
class DateSerializerWithTimezone(Serializer): <NEW_LINE> <INDENT> def format_datetime(self, data): <NEW_LINE> <INDENT> if is_naive(data) or self.datetime_formatting == 'rfc-2822': <NEW_LINE> <INDENT> return super(DateSerializerWithTimezone, self).format_datetime(data) <NEW_LINE> <DEDENT> return data.isoformat() | Our own serializer to format datetimes in ISO 8601 but with timezone
offset. | 6259906e4428ac0f6e659dad |
class Product(models.Model): <NEW_LINE> <INDENT> product_id = models.AutoField(primary_key=True) <NEW_LINE> product_name = models.CharField( max_length=200, verbose_name="Product Name" ) <NEW_LINE> product_slug = models.CharField( max_length=400, unique=True, verbose_name="Product SLUG" ) <NEW_LINE> product_url = models.URLField( max_length=500, unique=True, verbose_name="Product URL", null=True ) <NEW_LINE> product_api_url = models.URLField( max_length=500, verbose_name="Product API URL", null=True ) <NEW_LINE> product_server = models.URLField( max_length=500, verbose_name="Product Server" ) <NEW_LINE> product_build_system = models.CharField( max_length=200, null=True, verbose_name="Release Build System" ) <NEW_LINE> product_build_tags = ArrayField( models.CharField(max_length=200, blank=True), default=list, null=True, verbose_name="Release Build Tags" ) <NEW_LINE> product_build_tags_last_updated = models.DateTimeField(null=True) <NEW_LINE> src_pkg_format = models.CharField( max_length=50, null=True, verbose_name="Source Package Format" ) <NEW_LINE> top_url = models.URLField(max_length=500, verbose_name="Top URL") <NEW_LINE> web_url = models.URLField(max_length=500, null=True, verbose_name="Web URL") <NEW_LINE> krb_service = models.CharField( max_length=200, null=True, blank=True, verbose_name="Kerberos Service" ) <NEW_LINE> auth_type = models.CharField(max_length=200, null=True, blank=True, verbose_name="Auth Type") <NEW_LINE> amqp_server = models.CharField( max_length=500, null=True, blank=True, verbose_name="AMQP Server" ) <NEW_LINE> msgbus_exchange = models.CharField( max_length=200, null=True, blank=True, verbose_name="Message Bus Exchange" ) <NEW_LINE> major_milestones = ArrayField( models.CharField(max_length=1000, blank=True), default=list, null=True, verbose_name="Major Milestones" ) <NEW_LINE> product_phases = ArrayField( models.CharField(max_length=200, blank=True), default=list, null=True, verbose_name="Release Stream Phases" ) <NEW_LINE> product_status = models.BooleanField(verbose_name="Enable/Disable") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.product_name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = TABLE_PREFIX + 'products' <NEW_LINE> verbose_name = "Product" | Product Model | 6259906ea8370b77170f1c42 |
class ClassList(models.Model): <NEW_LINE> <INDENT> branch = models.ForeignKey("Branch") <NEW_LINE> course = models.ForeignKey("Course") <NEW_LINE> class_type_choices = ((0,'脱产'),(1,'周末'),(2,'网络班')) <NEW_LINE> class_type = models.SmallIntegerField(choices=class_type_choices,default=0) <NEW_LINE> semester = models.SmallIntegerField(verbose_name="学期") <NEW_LINE> teachers = models.ManyToManyField("UserProfile",verbose_name="讲师") <NEW_LINE> start_date = models.DateField("开班日期") <NEW_LINE> graduate_date = models.DateField("毕业日期",blank=True,null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "%s(%s)期" %(self.course.name,self.semester) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('branch','class_type','course','semester') | 班级列表 | 6259906ef548e778e596ce07 |
class BrowsableAPIRenderer(renderers.BrowsableAPIRenderer): <NEW_LINE> <INDENT> def get_default_renderer(self, view): <NEW_LINE> <INDENT> renderer = super(BrowsableAPIRenderer, self).get_default_renderer(view) <NEW_LINE> if view.request.method == 'OPTIONS' and not isinstance(renderer, renderers.JSONRenderer): <NEW_LINE> <INDENT> return renderers.JSONRenderer() <NEW_LINE> <DEDENT> return renderer <NEW_LINE> <DEDENT> def get_content(self, renderer, data, accepted_media_type, renderer_context): <NEW_LINE> <INDENT> if isinstance(data, SafeText): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> return super(BrowsableAPIRenderer, self).get_content(renderer, data, accepted_media_type, renderer_context) <NEW_LINE> <DEDENT> def get_context(self, data, accepted_media_type, renderer_context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(renderer_context['view'], '_raw_data_response_status', renderer_context['response'].status_code) <NEW_LINE> setattr(renderer_context['view'], '_request', renderer_context['request']) <NEW_LINE> return super(BrowsableAPIRenderer, self).get_context(data, accepted_media_type, renderer_context) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> delattr(renderer_context['view'], '_raw_data_response_status') <NEW_LINE> delattr(renderer_context['view'], '_request') <NEW_LINE> <DEDENT> <DEDENT> def get_raw_data_form(self, data, view, method, request): <NEW_LINE> <INDENT> if request.method in {'OPTIONS', 'DELETE'}: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> setattr(view, '_raw_data_form_marker', True) <NEW_LINE> setattr(view, '_raw_data_request_method', request.method) <NEW_LINE> return super(BrowsableAPIRenderer, self).get_raw_data_form(data, view, method, request) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> delattr(view, '_raw_data_form_marker') <NEW_LINE> delattr(view, '_raw_data_request_method') <NEW_LINE> <DEDENT> <DEDENT> def get_rendered_html_form(self, data, view, method, request): <NEW_LINE> <INDENT> obj = getattr(view, 'object', None) <NEW_LINE> if obj is None and hasattr(view, 'get_object') and hasattr(view, 'retrieve'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> view.object = view.get_object() <NEW_LINE> obj = view.object <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> obj = None <NEW_LINE> <DEDENT> <DEDENT> with override_method(view, request, method) as request: <NEW_LINE> <INDENT> if not self.show_form_for_method(view, method, request, obj): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if method in ('DELETE', 'OPTIONS'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_filter_form(self, data, view, request): <NEW_LINE> <INDENT> return | Customizations to the default browsable API renderer. | 6259906e009cb60464d02db1 |
class Manager(object): <NEW_LINE> <INDENT> def __init__(self, app): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.parser = argparse.ArgumentParser(description="Manage %s" % self.app.app.capitalize()) <NEW_LINE> self.parsers = self.parser.add_subparsers(dest='sub_command') <NEW_LINE> self.handlers = {} <NEW_LINE> self.command(self.app.run) <NEW_LINE> <DEDENT> def command(self, func, name=None): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> name = func.__name__ <NEW_LINE> <DEDENT> header = '\n'.join([s.strip() for s in (func.__doc__ or '').split('\n') if not s.strip().startswith(':') and len(s.strip()) > 0]) <NEW_LINE> parser = self.parsers.add_parser(name, description=header) <NEW_LINE> sig = inspect.signature(func) <NEW_LINE> args_docs = dict(PARAM_RE.findall(func.__doc__ or "")) <NEW_LINE> for param in sig.parameters.values(): <NEW_LINE> <INDENT> if param.name in ['module', 'app']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> arg_name = param.name.replace('_', '-').lower() <NEW_LINE> arg_help = args_docs.get(param.name, '') <NEW_LINE> if param.default is param.empty: <NEW_LINE> <INDENT> parser.add_argument(arg_name, help=arg_help) <NEW_LINE> continue <NEW_LINE> <DEDENT> if isinstance(param.default, bool): <NEW_LINE> <INDENT> if param.default is True: <NEW_LINE> <INDENT> parser.add_argument("--no-{}".format(arg_name), dest=param.name, action="store_false", help="Disable {}".format((arg_help or param.name).lower())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parser.add_argument("--{}".format(arg_name), dest=param.name, action="store_true", help="Enable {}".format((arg_help or param.name).lower())) <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> parser.add_argument("--" + arg_name, type=param.annotation if param.annotation is not param.empty else type(param.default), default=param.default, help="{} {}".format(arg_help, param.default)) <NEW_LINE> <DEDENT> self.handlers[name] = func <NEW_LINE> <DEDENT> def up(self, *args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> args = sys.argv[1:] <NEW_LINE> <DEDENT> args = self.parser.parse_args(args) <NEW_LINE> handler = self.handlers.get(args.sub_command, None) <NEW_LINE> if not handler: <NEW_LINE> <INDENT> self.parser.print_help() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _args = vars(args) <NEW_LINE> _args.pop('sub_command') <NEW_LINE> inner_param = { 'app': self.app } <NEW_LINE> parameters = inspect.signature(handler).parameters.keys() <NEW_LINE> for k, v in inner_param.items(): <NEW_LINE> <INDENT> if k in parameters: <NEW_LINE> <INDENT> _args[k] = v <NEW_LINE> <DEDENT> <DEDENT> return handler(**_args) | example.py
```python
from nougat import Nougat
app = Nougat()
async def middleware(response):
response.content = 'Hello world'
app.use(middleware)
app.manager.up()
```
then just run `python example.py run`, the server is starting. | 6259906e7b25080760ed8920 |
@op <NEW_LINE> class Shrs(Binop): <NEW_LINE> <INDENT> mode = "get_irn_mode(irn_left)" <NEW_LINE> flags = [] | Returns its first operands bits shifted right by the amount of the 2nd
operand. The leftmost bit (usually the sign bit) stays the same
(sign extension).
The right input (shift amount) must be an unsigned integer value.
If the result mode has modulo_shift!=0, then the effective shift amount is
the right input modulo this modulo_shift amount. | 6259906e442bda511e95d995 |
class DeleteReportsView(LoginRequiredMixin, UserPassesTestMixin, TemplateView): <NEW_LINE> <INDENT> login_url = 'usuarios:login' <NEW_LINE> def test_func(self): <NEW_LINE> <INDENT> return self.request.user.usuariosgrexco.tipo == 'A' <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> data = dict(request.POST) <NEW_LINE> id_reporte = data['reporte'][0] <NEW_LINE> if Reportes.objects.filter(id=id_reporte): <NEW_LINE> <INDENT> reporte = Reportes.objects.get(id=id_reporte) <NEW_LINE> try: <NEW_LINE> <INDENT> reporte.delete() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return JsonResponse({'error': e}, status=400) <NEW_LINE> <DEDENT> mensaje_ok = 'Se eliminó el Reporte: {}'.format(reporte.nombre) <NEW_LINE> return JsonResponse({'ok': mensaje_ok}, status=200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return JsonResponse( {'error': '¡El reporte No existe!'}, status=400) | Vista para Eliminar un reporte
Recibe por POST un objetoJSON:
{'reporte': [id_reporte]} | 6259906e97e22403b383c77e |
class ShutterContactSensor(SHCEntity, BinarySensorEntity): <NEW_LINE> <INDENT> def __init__(self, device: SHCDevice, parent_id: str, entry_id: str) -> None: <NEW_LINE> <INDENT> super().__init__(device, parent_id, entry_id) <NEW_LINE> switcher = { "ENTRANCE_DOOR": DEVICE_CLASS_DOOR, "REGULAR_WINDOW": DEVICE_CLASS_WINDOW, "FRENCH_WINDOW": DEVICE_CLASS_DOOR, "GENERIC": DEVICE_CLASS_WINDOW, } <NEW_LINE> self._attr_device_class = switcher.get( self._device.device_class, DEVICE_CLASS_WINDOW ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._device.state == SHCShutterContact.ShutterContactService.State.OPEN | Representation of an SHC shutter contact sensor. | 6259906ed486a94d0ba2d839 |
class PreprocessAllFiles(luigi.WrapperTask): <NEW_LINE> <INDENT> input_path: str = os.path.join("data", "raw") <NEW_LINE> output_path: str = os.path.join("data", "processed") <NEW_LINE> def requires(self) -> Generator[luigi.Task, None, None]: <NEW_LINE> <INDENT> for filename in os.listdir(self.input_path): <NEW_LINE> <INDENT> csv_input_path: str = os.path.join(self.input_path, filename) <NEW_LINE> csv_output_path: str = os.path.join(self.output_path, filename) <NEW_LINE> yield Preprocess(input_path=csv_input_path, output_path=csv_output_path) | Applies defined preprocessing steps to all files in the selected folder. | 6259906e4f6381625f19a0e6 |
class OnsetDetectionFunction(Analyzer): <NEW_LINE> <INDENT> implements(IAnalyzer) <NEW_LINE> def __init__(self, blocksize=1024, stepsize=None): <NEW_LINE> <INDENT> super(OnsetDetectionFunction, self).__init__() <NEW_LINE> self.input_blocksize = blocksize <NEW_LINE> if stepsize: <NEW_LINE> <INDENT> self.input_stepsize = stepsize <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.input_stepsize = blocksize / 2 <NEW_LINE> <DEDENT> self.parents.append(Spectrogram(blocksize=self.input_blocksize, stepsize=self.input_stepsize)) <NEW_LINE> <DEDENT> @interfacedoc <NEW_LINE> def setup(self, channels=None, samplerate=None, blocksize=None, totalframes=None): <NEW_LINE> <INDENT> super(OnsetDetectionFunction, self).setup(channels, samplerate, blocksize, totalframes) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @interfacedoc <NEW_LINE> def id(): <NEW_LINE> <INDENT> return "odf" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @interfacedoc <NEW_LINE> def name(): <NEW_LINE> <INDENT> return "Onset Detection Function" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @interfacedoc <NEW_LINE> def unit(): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def process(self, frames, eod=False): <NEW_LINE> <INDENT> return frames, eod <NEW_LINE> <DEDENT> def post_process(self): <NEW_LINE> <INDENT> spectrogram = self.process_pipe.results['spectrogram_analyzer'].data <NEW_LINE> S = signal.lfilter(signal.hann(15)[8:], 1, abs(spectrogram), axis=0) <NEW_LINE> import matplotlib.pyplot as plt <NEW_LINE> np.maximum(S, 1e-9, out=S) <NEW_LINE> S = np.log10(S) <NEW_LINE> np.maximum(S, 1e-3, out=S) <NEW_LINE> df_filter = signal.fir_filter_design.remez(31, [0, 0.5], [Pi], type='differentiator') <NEW_LINE> S_diff = signal.lfilter(df_filter, 1, S, axis=0) <NEW_LINE> S_diff[S_diff < 1e-10] = 0 <NEW_LINE> odf_diff = S_diff.sum(axis=1) <NEW_LINE> odf_median = np.median(odf_diff) <NEW_LINE> if odf_median: <NEW_LINE> <INDENT> odf_diff = odf_diff / odf_median <NEW_LINE> <DEDENT> odf = self.new_result(data_mode='value', time_mode='framewise') <NEW_LINE> odf.data_object.value = odf_diff <NEW_LINE> self.process_pipe.results.add(odf) | Onset Detection Function analyzer | 6259906e8a43f66fc4bf3a0f |
class BinaryExchangeType_(SamlBase): <NEW_LINE> <INDENT> c_tag = 'BinaryExchangeType' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_value_type = {'base': 'string'} <NEW_LINE> c_children = SamlBase.c_children.copy() <NEW_LINE> c_attributes = SamlBase.c_attributes.copy() <NEW_LINE> c_child_order = SamlBase.c_child_order[:] <NEW_LINE> c_cardinality = SamlBase.c_cardinality.copy() <NEW_LINE> c_attributes['ValueType'] = ('value_type', 'anyURI', True) <NEW_LINE> c_attributes['EncodingType'] = ('encoding_type', 'anyURI', True) <NEW_LINE> def __init__(self, value_type=None, encoding_type=None, text=None, extension_elements=None, extension_attributes=None, ): <NEW_LINE> <INDENT> SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes, ) <NEW_LINE> self.value_type=value_type <NEW_LINE> self.encoding_type=encoding_type | The http://docs.oasis-open.org/ws-sx/ws-trust/200512/:BinaryExchangeType element | 6259906eadb09d7d5dc0bde6 |
class HandleShipmentException(Wizard): <NEW_LINE> <INDENT> __name__ = 'purchase.handle.shipment.exception' <NEW_LINE> start_state = 'ask' <NEW_LINE> ask = StateView('purchase.handle.shipment.exception.ask', 'purchase.handle_shipment_exception_ask_view_form', [ Button('Cancel', 'end', 'tryton-cancel'), Button('Ok', 'handle', 'tryton-ok', default=True), ]) <NEW_LINE> handle = StateTransition() <NEW_LINE> def default_ask(self, fields): <NEW_LINE> <INDENT> Purchase = Pool().get('purchase.purchase') <NEW_LINE> purchase = Purchase(Transaction().context['active_id']) <NEW_LINE> moves = [] <NEW_LINE> for line in purchase.lines: <NEW_LINE> <INDENT> skip = set(line.moves_ignored + line.moves_recreated) <NEW_LINE> for move in line.moves: <NEW_LINE> <INDENT> if move.state == 'cancel' and move not in skip: <NEW_LINE> <INDENT> moves.append(move.id) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return { 'recreate_moves': moves, 'domain_moves': moves, } <NEW_LINE> <DEDENT> def transition_handle(self): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Purchase = pool.get('purchase.purchase') <NEW_LINE> PurchaseLine = pool.get('purchase.line') <NEW_LINE> to_recreate = self.ask.recreate_moves <NEW_LINE> domain_moves = self.ask.domain_moves <NEW_LINE> purchase = Purchase(Transaction().context['active_id']) <NEW_LINE> for line in purchase.lines: <NEW_LINE> <INDENT> moves_ignored = [] <NEW_LINE> moves_recreated = [] <NEW_LINE> skip = set(line.moves_ignored) <NEW_LINE> skip.update(line.moves_recreated) <NEW_LINE> for move in line.moves: <NEW_LINE> <INDENT> if move not in domain_moves or move in skip: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if move in to_recreate: <NEW_LINE> <INDENT> moves_recreated.append(move.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> moves_ignored.append(move.id) <NEW_LINE> <DEDENT> <DEDENT> PurchaseLine.write([line], { 'moves_ignored': [('add', moves_ignored)], 'moves_recreated': [('add', moves_recreated)], }) <NEW_LINE> <DEDENT> Purchase.process([purchase]) <NEW_LINE> return 'end' | Handle Shipment Exception | 6259906e38b623060ffaa491 |
class Vector2: <NEW_LINE> <INDENT> def __init__(self, x=0, y=0): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y | Class for storing pair of values. | 6259906e3539df3088ecdb18 |
class TestSnapshotPattern(manager.ScenarioTest): <NEW_LINE> <INDENT> def _boot_image(self, image_id): <NEW_LINE> <INDENT> security_groups = [{'name': self.security_group['name']}] <NEW_LINE> create_kwargs = { 'key_name': self.keypair['name'], 'security_groups': security_groups } <NEW_LINE> return self.create_server(image=image_id, create_kwargs=create_kwargs) <NEW_LINE> <DEDENT> def _add_keypair(self): <NEW_LINE> <INDENT> self.keypair = self.create_keypair() <NEW_LINE> <DEDENT> def _write_timestamp(self, server_or_ip): <NEW_LINE> <INDENT> ssh_client = self.get_remote_client(server_or_ip) <NEW_LINE> ssh_client.exec_command('date > /tmp/timestamp; sync') <NEW_LINE> self.timestamp = ssh_client.exec_command('cat /tmp/timestamp') <NEW_LINE> <DEDENT> def _check_timestamp(self, server_or_ip): <NEW_LINE> <INDENT> ssh_client = self.get_remote_client(server_or_ip) <NEW_LINE> got_timestamp = ssh_client.exec_command('cat /tmp/timestamp') <NEW_LINE> self.assertEqual(self.timestamp, got_timestamp) <NEW_LINE> <DEDENT> @test.idempotent_id('608e604b-1d63-4a82-8e3e-91bc665c90b4') <NEW_LINE> @testtools.skipUnless(CONF.compute_feature_enabled.snapshot, 'Snapshotting is not available.') <NEW_LINE> @test.services('compute', 'network', 'image') <NEW_LINE> def test_snapshot_pattern(self): <NEW_LINE> <INDENT> self._add_keypair() <NEW_LINE> self.security_group = self._create_security_group() <NEW_LINE> server = self._boot_image(CONF.compute.image_ref) <NEW_LINE> if CONF.compute.use_floatingip_for_ssh: <NEW_LINE> <INDENT> fip_for_server = self.create_floating_ip(server) <NEW_LINE> self._write_timestamp(fip_for_server['ip']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._write_timestamp(server) <NEW_LINE> <DEDENT> snapshot_image = self.create_server_snapshot(server=server) <NEW_LINE> server_from_snapshot = self._boot_image(snapshot_image['id']) <NEW_LINE> if CONF.compute.use_floatingip_for_ssh: <NEW_LINE> <INDENT> fip_for_snapshot = self.create_floating_ip(server_from_snapshot) <NEW_LINE> self._check_timestamp(fip_for_snapshot['ip']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._check_timestamp(server_from_snapshot) | This test is for snapshotting an instance and booting with it.
The following is the scenario outline:
* boot a instance and create a timestamp file in it
* snapshot the instance
* boot a second instance from the snapshot
* check the existence of the timestamp file in the second instance | 6259906e2c8b7c6e89bd5062 |
class StataValueLabel: <NEW_LINE> <INDENT> def __init__(self, catarray): <NEW_LINE> <INDENT> self.labname = catarray.name <NEW_LINE> categories = catarray.cat.categories <NEW_LINE> self.value_labels = list(zip(np.arange(len(categories)), categories)) <NEW_LINE> self.value_labels.sort(key=lambda x: x[0]) <NEW_LINE> self.text_len = np.int32(0) <NEW_LINE> self.off = [] <NEW_LINE> self.val = [] <NEW_LINE> self.txt = [] <NEW_LINE> self.n = 0 <NEW_LINE> for vl in self.value_labels: <NEW_LINE> <INDENT> category = vl[1] <NEW_LINE> if not isinstance(category, str): <NEW_LINE> <INDENT> category = str(category) <NEW_LINE> warnings.warn(value_label_mismatch_doc.format(catarray.name), ValueLabelTypeMismatch) <NEW_LINE> <DEDENT> self.off.append(self.text_len) <NEW_LINE> self.text_len += len(category) + 1 <NEW_LINE> self.val.append(vl[0]) <NEW_LINE> self.txt.append(category) <NEW_LINE> self.n += 1 <NEW_LINE> <DEDENT> if self.text_len > 32000: <NEW_LINE> <INDENT> raise ValueError('Stata value labels for a single variable must ' 'have a combined length less than 32,000 ' 'characters.') <NEW_LINE> <DEDENT> self.off = np.array(self.off, dtype=np.int32) <NEW_LINE> self.val = np.array(self.val, dtype=np.int32) <NEW_LINE> self.len = 4 + 4 + 4 * self.n + 4 * self.n + self.text_len <NEW_LINE> <DEDENT> def _encode(self, s): <NEW_LINE> <INDENT> return s.encode(self._encoding) <NEW_LINE> <DEDENT> def generate_value_label(self, byteorder, encoding): <NEW_LINE> <INDENT> self._encoding = encoding <NEW_LINE> bio = BytesIO() <NEW_LINE> null_string = '\x00' <NEW_LINE> null_byte = b'\x00' <NEW_LINE> bio.write(struct.pack(byteorder + 'i', self.len)) <NEW_LINE> labname = self._encode(_pad_bytes(self.labname[:32], 33)) <NEW_LINE> bio.write(labname) <NEW_LINE> for i in range(3): <NEW_LINE> <INDENT> bio.write(struct.pack('c', null_byte)) <NEW_LINE> <DEDENT> bio.write(struct.pack(byteorder + 'i', self.n)) <NEW_LINE> bio.write(struct.pack(byteorder + 'i', self.text_len)) <NEW_LINE> for offset in self.off: <NEW_LINE> <INDENT> bio.write(struct.pack(byteorder + 'i', offset)) <NEW_LINE> <DEDENT> for value in self.val: <NEW_LINE> <INDENT> bio.write(struct.pack(byteorder + 'i', value)) <NEW_LINE> <DEDENT> for text in self.txt: <NEW_LINE> <INDENT> bio.write(self._encode(text + null_string)) <NEW_LINE> <DEDENT> bio.seek(0) <NEW_LINE> return bio.read() | Parse a categorical column and prepare formatted output
Parameters
-----------
value : int8, int16, int32, float32 or float64
The Stata missing value code
Attributes
----------
string : string
String representation of the Stata missing value
value : int8, int16, int32, float32 or float64
The original encoded missing value
Methods
-------
generate_value_label | 6259906f4428ac0f6e659daf |
class LineGlyph(XyGlyph): <NEW_LINE> <INDENT> width = Int(default=2) <NEW_LINE> dash = Enum(DashPattern, default='solid') <NEW_LINE> def __init__(self, x=None, y=None, line_color=None, width=None, dash=None, **kwargs): <NEW_LINE> <INDENT> kwargs['x'] = x <NEW_LINE> kwargs['y'] = y <NEW_LINE> kwargs['line_color'] = line_color or self.line_color <NEW_LINE> kwargs['width'] = width or self.width <NEW_LINE> kwargs['dash'] = dash or self.dash <NEW_LINE> super(LineGlyph, self).__init__(**kwargs) <NEW_LINE> self.setup() <NEW_LINE> <DEDENT> def build_source(self): <NEW_LINE> <INDENT> if self.x is None: <NEW_LINE> <INDENT> x = self.y.index <NEW_LINE> data = dict(x_values=x, y_values=self.y) <NEW_LINE> <DEDENT> elif self.y is None: <NEW_LINE> <INDENT> y = self.x.index <NEW_LINE> data = dict(x_values=self.x, y_values=y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = dict(x_values=self.x, y_values=self.y) <NEW_LINE> <DEDENT> return ColumnDataSource(data) <NEW_LINE> <DEDENT> def build_renderers(self): <NEW_LINE> <INDENT> glyph = Line(x='x_values', y='y_values', line_color=self.line_color, line_alpha=self.line_alpha, line_width=self.width, line_dash=self.dash) <NEW_LINE> yield GlyphRenderer(glyph=glyph) | Represents a group of data as a line. | 6259906fd268445f2663a79b |
class App(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.content = "" <NEW_LINE> self.startTime = 0 <NEW_LINE> <DEDENT> def launchApp(self): <NEW_LINE> <INDENT> cmd2 = 'adb shell am start -W -n com.mfcar.dealer/.ui.splash.SplashActivity' <NEW_LINE> self.content = os.popen(cmd2) <NEW_LINE> return self.content <NEW_LINE> <DEDENT> def StopApp(self): <NEW_LINE> <INDENT> cmd = 'adb shell am force-stop com.mfcar.dealer' <NEW_LINE> os.popen(cmd) <NEW_LINE> <DEDENT> def GetLaunchedTime(self): <NEW_LINE> <INDENT> for line in self.content.readlines(): <NEW_LINE> <INDENT> if "ThisTime" in line: <NEW_LINE> <INDENT> self.startTime = line.split(":")[1] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return self.startTime | 运行类 | 6259906f8e7ae83300eea90c |
class TestQueueNonExisting(base.V1FunctionalTestBase): <NEW_LINE> <INDENT> server_class = base.MarconiServer <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(TestQueueNonExisting, self).setUp() <NEW_LINE> self.base_url = '{0}/{1}'.format(self.cfg.marconi.url, "v1") <NEW_LINE> self.queue_url = (self.base_url + '/queues/0a5b1b85-4263-11e3-b034-28cfe91478b9') <NEW_LINE> self.client.set_base_url(self.queue_url) <NEW_LINE> self.header = helpers.create_marconi_headers(self.cfg) <NEW_LINE> self.headers_response_empty = set(['location']) <NEW_LINE> self.header = helpers.create_marconi_headers(self.cfg) <NEW_LINE> <DEDENT> def test_get_queue(self): <NEW_LINE> <INDENT> result = self.client.get() <NEW_LINE> self.assertEqual(result.status_code, 404) <NEW_LINE> <DEDENT> def test_get_stats(self): <NEW_LINE> <INDENT> result = self.client.get('/stats') <NEW_LINE> self.assertEqual(result.status_code, 404) <NEW_LINE> <DEDENT> def test_get_metadata(self): <NEW_LINE> <INDENT> result = self.client.get('/metadata') <NEW_LINE> self.assertEqual(result.status_code, 404) <NEW_LINE> <DEDENT> def test_get_messages(self): <NEW_LINE> <INDENT> result = self.client.get('/messages') <NEW_LINE> self.assertEqual(result.status_code, 204) <NEW_LINE> <DEDENT> def test_post_messages(self): <NEW_LINE> <INDENT> doc = [{"ttl": 200, "body": {"Home": ""}}] <NEW_LINE> result = self.client.post('/messages', data=doc) <NEW_LINE> self.assertEqual(result.status_code, 404) <NEW_LINE> <DEDENT> def test_claim_messages(self): <NEW_LINE> <INDENT> doc = {"ttl": 200, "grace": 300} <NEW_LINE> result = self.client.post('/claims', data=doc) <NEW_LINE> self.assertEqual(result.status_code, 204) <NEW_LINE> <DEDENT> def test_delete_queue(self): <NEW_LINE> <INDENT> result = self.client.delete() <NEW_LINE> self.assertEqual(result.status_code, 204) | Test Actions on non existing queue. | 6259906f91f36d47f2231acd |
class ArchiveBaseClass(object): <NEW_LINE> <INDENT> _compression = False <NEW_LINE> _ext = ".ext" <NEW_LINE> _mimetype = "" <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._tar_ext = ".tar" <NEW_LINE> <DEDENT> @property <NEW_LINE> def support_compression(self): <NEW_LINE> <INDENT> return self._compression <NEW_LINE> <DEDENT> @property <NEW_LINE> def file_ext(self): <NEW_LINE> <INDENT> return self._ext <NEW_LINE> <DEDENT> @property <NEW_LINE> def mimetype(self): <NEW_LINE> <INDENT> return self._mimetype <NEW_LINE> <DEDENT> def _create_tmp_tar(self, filelist): <NEW_LINE> <INDENT> _, tmpfile = tempfile.mkstemp(suffix=self._tar_ext) <NEW_LINE> tar = tarfile.open(tmpfile, "w") <NEW_LINE> for name in filelist: <NEW_LINE> <INDENT> pieces = name.rsplit('/', 2) <NEW_LINE> arcname = "%s/%s" % (pieces[-2], pieces[-1]) <NEW_LINE> tar.add(name, arcname=arcname) <NEW_LINE> <DEDENT> tar.close() <NEW_LINE> return tmpfile <NEW_LINE> <DEDENT> def create_archive(self, outfilename, filelist): <NEW_LINE> <INDENT> raise NotImplementedError() | Base class for archive classes. | 6259906ff9cc0f698b1c5f09 |
class PrintBvrFund(models.TransientModel): <NEW_LINE> <INDENT> _name = 'print.bvr.fund' <NEW_LINE> product_id = fields.Many2one( 'product.product', domain=[ ('fund_id', '!=', False), ('categ_id', '!=', 3), ('categ_id', '!=', 5)]) <NEW_LINE> draw_background = fields.Boolean() <NEW_LINE> state = fields.Selection([('new', 'new'), ('pdf', 'pdf')], default='new') <NEW_LINE> pdf = fields.Boolean() <NEW_LINE> pdf_name = fields.Char(default='fund.pdf') <NEW_LINE> pdf_download = fields.Binary(readonly=True) <NEW_LINE> preprinted = fields.Boolean( help='Enable if you print on a payment slip that already has company ' 'information printed on it.' ) <NEW_LINE> @api.onchange('pdf') <NEW_LINE> def onchange_pdf(self): <NEW_LINE> <INDENT> if self.pdf: <NEW_LINE> <INDENT> self.draw_background = True <NEW_LINE> self.preprinted = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.draw_background = False <NEW_LINE> <DEDENT> <DEDENT> @api.multi <NEW_LINE> def print_report(self): <NEW_LINE> <INDENT> partners = self.env['res.partner'].browse( self.env.context.get('active_ids')) <NEW_LINE> data = { 'doc_ids': partners.ids, 'product_id': self.product_id.id, 'background': self.draw_background, 'preprinted': self.preprinted, 'amount': False, 'communication': False } <NEW_LINE> report = 'report_compassion.bvr_fund' <NEW_LINE> if self.pdf: <NEW_LINE> <INDENT> self.pdf_name = self.product_id.name + '.pdf' <NEW_LINE> self.pdf_download = base64.b64encode( self.env['report'].with_context( must_skip_send_to_printer=True).get_pdf( partners.ids, report, data=data)) <NEW_LINE> self.state = 'pdf' <NEW_LINE> return { 'name': 'Download report', 'type': 'ir.actions.act_window', 'res_model': self._name, 'res_id': self.id, 'view_mode': 'form', 'target': 'new', 'context': self.env.context, } <NEW_LINE> <DEDENT> return self.env['report'].get_action(partners.ids, report, data) | Wizard for selecting a product and print
payment slip of a partner. | 6259906f3539df3088ecdb19 |
class Model(nn.Layer, ModelBase): <NEW_LINE> <INDENT> def __init___(self): <NEW_LINE> <INDENT> super(Model, self).__init__() <NEW_LINE> <DEDENT> def sync_weights_to(self, target_model, decay=0.0): <NEW_LINE> <INDENT> assert not target_model is self, "cannot copy between identical model" <NEW_LINE> assert isinstance(target_model, Model) <NEW_LINE> assert self.__class__.__name__ == target_model.__class__.__name__, "must be the same class for params syncing!" <NEW_LINE> assert (decay >= 0 and decay <= 1) <NEW_LINE> target_vars = dict(target_model.named_parameters()) <NEW_LINE> for name, var in self.named_parameters(): <NEW_LINE> <INDENT> target_data = decay * target_vars[name] + (1 - decay) * var <NEW_LINE> target_vars[name] = target_data <NEW_LINE> <DEDENT> target_model.set_state_dict(target_vars) <NEW_LINE> <DEDENT> def get_weights(self): <NEW_LINE> <INDENT> weights = self.state_dict() <NEW_LINE> for key in weights.keys(): <NEW_LINE> <INDENT> weights[key] = weights[key].numpy() <NEW_LINE> <DEDENT> return weights <NEW_LINE> <DEDENT> def set_weights(self, weights): <NEW_LINE> <INDENT> old_weights = self.state_dict() <NEW_LINE> assert len(old_weights) == len( weights), '{} params are expected, but got {}'.format( len(old_weights), len(weights)) <NEW_LINE> new_weights = collections.OrderedDict() <NEW_LINE> for key in old_weights.keys(): <NEW_LINE> <INDENT> assert key in weights, 'key: {} is expected to be in weights.'.format( key) <NEW_LINE> assert old_weights[key].shape == list( weights[key].shape ), 'key \'{}\' expects the data with shape {}, but gets {}'.format( key, old_weights[key].shape, list(weights[key].shape)) <NEW_LINE> new_weights[key] = paddle.to_tensor(weights[key]) <NEW_LINE> <DEDENT> self.set_state_dict(new_weights) | | `alias`: ``parl.Model``
| `alias`: ``parl.core.paddle.agent.Model``
| ``Model`` is a base class of PARL for the neural network.
A ``Model`` is usually a policy or Q-value function, which predicts
an action or an estimate according to the environmental observation.
| To use the ``PaddlePaddle2.0`` backend model, user needs to call
``super(Model, self).__init__()`` at the beginning of ``__init__``
function.
| ``Model`` supports duplicating a ``Model`` instance in a pythonic way:
| ``copied_model = copy.deepcopy(model)``
Example:
.. code-block:: python
import parl
import paddle.nn as nn
class Policy(parl.Model):
def __init__(self):
super(Policy, self).__init__()
self.fc = nn.Linear(input_dim=100, output_dim=32)
def policy(self, obs):
out = self.fc(obs)
return out
policy = Policy()
copied_policy = copy.deepcopy(policy)
Attributes:
model_id(str): each model instance has its unique model_id.
Public Functions:
- ``sync_weights_to``: synchronize parameters of the current model
to another model.
- ``get_weights``: return a list containing all the parameters of
the current model.
- ``set_weights``: copy parameters from ``set_weights()`` to the model.
- ``forward``: define the computations of a neural network. **Should**
be overridden by all subclasses. | 6259906fd486a94d0ba2d83b |
class DSRScorecardReport(base_models.DSRScorecardReport): <NEW_LINE> <INDENT> serial_number = models.CharField(max_length=5) <NEW_LINE> goals = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> target = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> actual = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> measures = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> weight = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> total_score = models.CharField(max_length=255, null=True, blank=True) <NEW_LINE> class Meta(base_models.DSRScorecardReport.Meta): <NEW_LINE> <INDENT> app_label = _APP_NAME | details of report | 6259906f01c39578d7f14373 |
class EncryptionSetIdentity(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'principal_id': {'readonly': True}, 'tenant_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'principal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, type: Optional[Union[str, "DiskEncryptionSetIdentityType"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(EncryptionSetIdentity, self).__init__(**kwargs) <NEW_LINE> self.type = type <NEW_LINE> self.principal_id = None <NEW_LINE> self.tenant_id = None | The managed identity for the disk encryption set. It should be given permission on the key vault before it can be used to encrypt disks.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The type of Managed Identity used by the DiskEncryptionSet. Only SystemAssigned is
supported for new creations. Disk Encryption Sets can be updated with Identity type None during
migration of subscription to a new Azure Active Directory tenant; it will cause the encrypted
resources to lose access to the keys. Possible values include: "SystemAssigned", "None".
:vartype type: str or ~azure.mgmt.compute.v2021_12_01.models.DiskEncryptionSetIdentityType
:ivar principal_id: The object id of the Managed Identity Resource. This will be sent to the RP
from ARM via the x-ms-identity-principal-id header in the PUT request if the resource has a
systemAssigned(implicit) identity.
:vartype principal_id: str
:ivar tenant_id: The tenant id of the Managed Identity Resource. This will be sent to the RP
from ARM via the x-ms-client-tenant-id header in the PUT request if the resource has a
systemAssigned(implicit) identity.
:vartype tenant_id: str | 6259906f1b99ca4002290174 |
class MAVLink_status_gps_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_STATUS_GPS <NEW_LINE> name = 'STATUS_GPS' <NEW_LINE> fieldnames = ['csFails', 'gpsQuality', 'msgsType', 'posStatus', 'magVar', 'magDir', 'modeInd'] <NEW_LINE> ordered_fieldnames = [ 'magVar', 'csFails', 'gpsQuality', 'msgsType', 'posStatus', 'magDir', 'modeInd' ] <NEW_LINE> format = '<fHBBBbB' <NEW_LINE> native_format = bytearray('<fHBBBbB', 'ascii') <NEW_LINE> orders = [1, 2, 3, 4, 0, 5, 6] <NEW_LINE> lengths = [1, 1, 1, 1, 1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0, 0, 0, 0, 0] <NEW_LINE> crc_extra = 51 <NEW_LINE> def __init__(self, csFails, gpsQuality, msgsType, posStatus, magVar, magDir, modeInd): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_status_gps_message.id, MAVLink_status_gps_message.name) <NEW_LINE> self._fieldnames = MAVLink_status_gps_message.fieldnames <NEW_LINE> self.csFails = csFails <NEW_LINE> self.gpsQuality = gpsQuality <NEW_LINE> self.msgsType = msgsType <NEW_LINE> self.posStatus = posStatus <NEW_LINE> self.magVar = magVar <NEW_LINE> self.magDir = magDir <NEW_LINE> self.modeInd = modeInd <NEW_LINE> <DEDENT> def pack(self, mav, force_mavlink1=False): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 51, struct.pack('<fHBBBbB', self.magVar, self.csFails, self.gpsQuality, self.msgsType, self.posStatus, self.magDir, self.modeInd), force_mavlink1=force_mavlink1) | This contains the status of the GPS readings | 6259906faad79263cf430033 |
class Meta: <NEW_LINE> <INDENT> model = Kunde <NEW_LINE> fields = ['template'] | Eine Klasse zur Repräsentation der Metadaten
...
Attributes
----------
model : Kunde
Kundenobjekt
fields : string
Template-Feld | 6259906f097d151d1a2c28ee |
class PublisherForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Publisher <NEW_LINE> fields = ('pub_id', 'pub_name', 'city') | Form for adding a publisher
| 6259906f38b623060ffaa492 |
class ApproximateQAgent(PacmanQAgent): <NEW_LINE> <INDENT> def __init__(self, extractor='IdentityExtractor', **args): <NEW_LINE> <INDENT> self.featExtractor = util.lookup(extractor, globals())() <NEW_LINE> PacmanQAgent.__init__(self, **args) <NEW_LINE> self.weights = util.Counter() <NEW_LINE> <DEDENT> def getWeights(self): <NEW_LINE> <INDENT> return self.weights <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> q = 0 <NEW_LINE> feats = self.featExtractor.getFeatures(state, action) <NEW_LINE> for feat in feats: <NEW_LINE> <INDENT> q += self.weights[feat] * feats[feat] <NEW_LINE> <DEDENT> return q <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> feats = self.featExtractor.getFeatures(state, action) <NEW_LINE> difference = (reward + self.discount * self.getValue(nextState)) - self.getQValue(state, action) <NEW_LINE> for feat in feats: <NEW_LINE> <INDENT> self.weights[feat] = self.weights[feat] + self.alpha * difference * feats[feat] <NEW_LINE> <DEDENT> <DEDENT> def final(self, state): <NEW_LINE> <INDENT> PacmanQAgent.final(self, state) <NEW_LINE> if self.episodesSoFar == self.numTraining: <NEW_LINE> <INDENT> pass | ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is. | 6259906f7047854f46340c34 |
class OrderedSet(collections.MutableSet): <NEW_LINE> <INDENT> def __init__(self, iterable=None): <NEW_LINE> <INDENT> self.end = end = [] <NEW_LINE> end += [None, end, end] <NEW_LINE> self.map = {} <NEW_LINE> if iterable is not None: <NEW_LINE> <INDENT> self |= iterable <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.map) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self.map <NEW_LINE> <DEDENT> def add(self, key): <NEW_LINE> <INDENT> if key not in self.map: <NEW_LINE> <INDENT> end = self.end <NEW_LINE> curr = end[1] <NEW_LINE> curr[2] = end[1] = self.map[key] = [key, curr, end] <NEW_LINE> <DEDENT> <DEDENT> def discard(self, key): <NEW_LINE> <INDENT> if key in self.map: <NEW_LINE> <INDENT> key, prev, _next = self.map.pop(key) <NEW_LINE> prev[2] = _next <NEW_LINE> _next[1] = prev <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> end = self.end <NEW_LINE> curr = end[2] <NEW_LINE> while curr is not end: <NEW_LINE> <INDENT> yield curr[0] <NEW_LINE> curr = curr[2] <NEW_LINE> <DEDENT> <DEDENT> def __reversed__(self): <NEW_LINE> <INDENT> end = self.end <NEW_LINE> curr = end[1] <NEW_LINE> while curr is not end: <NEW_LINE> <INDENT> yield curr[0] <NEW_LINE> curr = curr[1] <NEW_LINE> <DEDENT> <DEDENT> def pop(self, last=True): <NEW_LINE> <INDENT> if not self: <NEW_LINE> <INDENT> raise KeyError('set is empty') <NEW_LINE> <DEDENT> key = self.end[1][0] if last else self.end[2][0] <NEW_LINE> self.discard(key) <NEW_LINE> return key <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if not self: <NEW_LINE> <INDENT> return '%s()' % (self.__class__.__name__,) <NEW_LINE> <DEDENT> return '%s(%r)' % (self.__class__.__name__, list(self)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, OrderedSet): <NEW_LINE> <INDENT> return len(self) == len(other) and list(self) == list(other) <NEW_LINE> <DEDENT> return set(self) == set(other) | Ordered set | 6259906f56b00c62f0fb414b |
class Action: <NEW_LINE> <INDENT> __slots__ = ( 'namespaced_type', 'goal', 'result', 'feedback', 'send_goal_service', 'get_result_service', 'feedback_message', 'implicit_includes') <NEW_LINE> def __init__( self, namespaced_type: NamespacedType, goal: Message, result: Message, feedback: Message ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> assert isinstance(namespaced_type, NamespacedType) <NEW_LINE> self.namespaced_type = namespaced_type <NEW_LINE> assert isinstance(goal, Message) <NEW_LINE> assert goal.structure.namespaced_type.namespaces == namespaced_type.namespaces <NEW_LINE> assert goal.structure.namespaced_type.name == namespaced_type.name + ACTION_GOAL_SUFFIX <NEW_LINE> self.goal = goal <NEW_LINE> assert isinstance(result, Message) <NEW_LINE> assert result.structure.namespaced_type.namespaces == namespaced_type.namespaces <NEW_LINE> assert result.structure.namespaced_type.name == namespaced_type.name + ACTION_RESULT_SUFFIX <NEW_LINE> self.result = result <NEW_LINE> assert isinstance(feedback, Message) <NEW_LINE> assert feedback.structure.namespaced_type.namespaces == namespaced_type.namespaces <NEW_LINE> assert feedback.structure.namespaced_type.name == namespaced_type.name + ACTION_FEEDBACK_SUFFIX <NEW_LINE> self.feedback = feedback <NEW_LINE> self.implicit_includes = [ Include('builtin_interfaces/msg/Time.idl'), Include('unique_identifier_msgs/msg/UUID.idl'), ] <NEW_LINE> goal_id_type = NamespacedType( namespaces=['unique_identifier_msgs', 'msg'], name='UUID') <NEW_LINE> goal_service_name = namespaced_type.name + ACTION_GOAL_SERVICE_SUFFIX <NEW_LINE> self.send_goal_service = Service( NamespacedType( namespaces=namespaced_type.namespaces, name=goal_service_name), request=Message(Structure( NamespacedType( namespaces=namespaced_type.namespaces, name=goal_service_name + SERVICE_REQUEST_MESSAGE_SUFFIX), members=[ Member(goal_id_type, 'goal_id'), Member(goal.structure.namespaced_type, 'goal')] )), response=Message(Structure( NamespacedType( namespaces=namespaced_type.namespaces, name=goal_service_name + SERVICE_RESPONSE_MESSAGE_SUFFIX), members=[ Member(BasicType('boolean'), 'accepted'), Member( NamespacedType(['builtin_interfaces', 'msg'], 'Time'), 'stamp')] )), ) <NEW_LINE> result_service_name = namespaced_type.name + ACTION_RESULT_SERVICE_SUFFIX <NEW_LINE> self.get_result_service = Service( NamespacedType( namespaces=namespaced_type.namespaces, name=result_service_name), request=Message(Structure( NamespacedType( namespaces=namespaced_type.namespaces, name=result_service_name + SERVICE_REQUEST_MESSAGE_SUFFIX), members=[Member(goal_id_type, 'goal_id')] )), response=Message(Structure( NamespacedType( namespaces=namespaced_type.namespaces, name=result_service_name + SERVICE_RESPONSE_MESSAGE_SUFFIX), members=[ Member(BasicType('int8'), 'status'), Member(result.structure.namespaced_type, 'result')] )), ) <NEW_LINE> self.feedback_message = Message(Structure( NamespacedType( namespaces=namespaced_type.namespaces, name=namespaced_type.name + ACTION_FEEDBACK_MESSAGE_SUFFIX), members=[ Member(goal_id_type, 'goal_id'), Member(feedback.structure.namespaced_type, 'feedback')] )) | A namespaced type of an action including the derived types. | 6259906f7d847024c075dc5b |
class PSFResultSet(result.ResultDict): <NEW_LINE> <INDENT> def __init__(self, resultdir=None): <NEW_LINE> <INDENT> runlist = [] <NEW_LINE> self.runs = {} <NEW_LINE> self.resultnames = [] <NEW_LINE> self.resultdir = resultdir <NEW_LINE> runobjfile = os.path.join(resultdir,"runObjFile") <NEW_LINE> if os.path.exists(runobjfile): <NEW_LINE> <INDENT> self.runObjFile = psf.PSFReader(runobjfile, asc=True) <NEW_LINE> self.runObjFile.open() <NEW_LINE> for runName in self.runObjFile.getValueNames(): <NEW_LINE> <INDENT> run = PSFRun(runName, self.runObjFile.getValuesByName(runName), self.runObjFile.getValuePropertiesByName(runName)) <NEW_LINE> runlist.append(run) <NEW_LINE> self.runs[runName] = run <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> run = PSFRun('Run1', {'logName': ['logFile'], 'parent': '', 'sweepVariable': [] }, {}) <NEW_LINE> self.runs['Run1'] = run <NEW_LINE> runlist.append(run) <NEW_LINE> <DEDENT> for run in runlist: <NEW_LINE> <INDENT> if self.runs.has_key(run.parentName): <NEW_LINE> <INDENT> parent = self.runs[run.parentName] <NEW_LINE> run.setParent(parent) <NEW_LINE> parent.addChild(run) <NEW_LINE> <DEDENT> run.openLogs(resultdir) <NEW_LINE> <DEDENT> <DEDENT> def isfamily(self): <NEW_LINE> <INDENT> return self.runs.has_key("Root") <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> if not self.isfamily(): <NEW_LINE> <INDENT> return self.runs['Run1'].getLogFile().getValueNames() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for run in self.runs.values(): <NEW_LINE> <INDENT> if run.isLeaf(): <NEW_LINE> <INDENT> return run.getLogFile().getValueNames() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> if self.isfamily(): <NEW_LINE> <INDENT> return self.runs['Root'].getResult(name, self.resultdir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.runs['Run1'].getResult(name, self.resultdir) | PSFResultSet class handles a PSF result directory
A PSFResultSet may contain one or more runs (PSFRun objects) which in turn
contain one or more results (PSFResult). | 6259906f8da39b475be04a6b |
class Nlopt(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://nlopt.readthedocs.io" <NEW_LINE> url = "https://github.com/stevengj/nlopt/archive/v2.5.0.tar.gz" <NEW_LINE> git = "https://github.com/stevengj/nlopt.git" <NEW_LINE> version('develop', branch='master') <NEW_LINE> version('2.5.0', 'ada08c648bf9b52faf8729412ff6dd6d') <NEW_LINE> variant('shared', default=True, description='Enables the build of shared libraries') <NEW_LINE> variant('python', default=True, description='Build python wrappers') <NEW_LINE> variant('guile', default=False, description='Enable Guile support') <NEW_LINE> variant('octave', default=False, description='Enable GNU Octave support') <NEW_LINE> variant('cxx', default=False, description='Build the C++ routines') <NEW_LINE> variant("matlab", default=False, description="Build the Matlab bindings.") <NEW_LINE> depends_on('[email protected]:', type='build', when='@develop') <NEW_LINE> depends_on('python', when='+python') <NEW_LINE> depends_on('py-numpy', when='+python', type=('build', 'run')) <NEW_LINE> depends_on('swig', when='+python') <NEW_LINE> depends_on('guile', when='+guile') <NEW_LINE> depends_on('octave', when='+octave') <NEW_LINE> depends_on('matlab', when='+matlab') <NEW_LINE> def cmake_args(self): <NEW_LINE> <INDENT> spec = self.spec <NEW_LINE> args = [] <NEW_LINE> if '+python' in spec: <NEW_LINE> <INDENT> args.append("-DPYTHON_EXECUTABLE=%s" % spec['python'].command.path) <NEW_LINE> <DEDENT> if '-shared' in spec: <NEW_LINE> <INDENT> args.append('-DBUILD_SHARED_LIBS:Bool=OFF') <NEW_LINE> <DEDENT> if '+cxx' in spec: <NEW_LINE> <INDENT> args.append('-DNLOPT_CXX:BOOL=ON') <NEW_LINE> <DEDENT> if '+matlab' in spec: <NEW_LINE> <INDENT> args.append("-DMatlab_ROOT_DIR=%s" % spec['matlab'].command.path) <NEW_LINE> <DEDENT> return args | NLopt is a free/open-source library for nonlinear optimization,
providing a common interface for a number of different free optimization
routines available online as well as original implementations of various
other algorithms. | 6259906f7b180e01f3e49ca3 |
class TestHomeAppliance(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return HomeAppliance( data = home_connect_sdk.models.home_appliance_data.HomeAppliance_data( ha_id = '0', name = '0', type = '0', brand = '0', vib = '0', enumber = '0', connected = True, ) ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return HomeAppliance( data = home_connect_sdk.models.home_appliance_data.HomeAppliance_data( ha_id = '0', name = '0', type = '0', brand = '0', vib = '0', enumber = '0', connected = True, ), ) <NEW_LINE> <DEDENT> <DEDENT> def testHomeAppliance(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | HomeAppliance unit test stubs | 6259906f435de62698e9d684 |
class OrderSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> order_detail = OrderDetailSerializer(many=True, read_only=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Order <NEW_LINE> fields = ['id', 'user', 'status', 'total', 'created', 'order_detail'] | Order Serializer | 6259906f2ae34c7f260ac968 |
class ScriptEngine(object): <NEW_LINE> <INDENT> executor = ('%s %s' % ('Restricted Python', sys.version.split('\n')[0])).strip() <NEW_LINE> repository = None <NEW_LINE> _scripts = None <NEW_LINE> __allowedBuiltins = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.repository = dict() <NEW_LINE> self._scripts = dict() <NEW_LINE> self.__allowedBuiltins = safe_builtins.copy() <NEW_LINE> self.__allowedBuiltins['_getitem_'] = guarded_getitem <NEW_LINE> <DEDENT> def _hash(self, name, value): <NEW_LINE> <INDENT> result = sha256(value.encode()) <NEW_LINE> return name.encode() + result.digest() <NEW_LINE> <DEDENT> def compile(self, name, script): <NEW_LINE> <INDENT> key = name <NEW_LINE> cacheItem = self.repository.get(key, None) <NEW_LINE> if cacheItem is None: <NEW_LINE> <INDENT> byteCode = compile_restricted(script, filename=name, mode='exec') <NEW_LINE> self.repository[key] = [time.time(), name, byteCode] <NEW_LINE> self._scripts[key] = script <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cacheItem[0] = time.time() <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> def execute(self, key, env=None, limit=10000): <NEW_LINE> <INDENT> _, _, code = self.repository[key] <NEW_LINE> try: <NEW_LINE> <INDENT> if limit is None: <NEW_LINE> <INDENT> exec(code, self.__allowedBuiltins, env) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with time_limit(limit): <NEW_LINE> <INDENT> exec(code, self.__allowedBuiltins, env) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except TimeoutError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> lines = self._scripts[key].split('\n') <NEW_LINE> tb = sys.exc_info()[2] <NEW_LINE> while tb: <NEW_LINE> <INDENT> if tb.tb_frame.f_code.co_filename == key: <NEW_LINE> <INDENT> debugText = '\n'.join(['%1s%4d: %s' % ('>' if i+1 == tb.tb_lineno else '', i+1, lines[i]) for i in range(0,len(lines))]) <NEW_LINE> raise RuntimeError('%s, line %d in\n%s' % (ex, tb.tb_lineno, debugText)).with_traceback(tb.tb_next) <NEW_LINE> <DEDENT> tb = tb.tb_next | classdocs | 6259906f4a966d76dd5f0768 |
class ArtifactParserTests(test_lib.GRRBaseTest): <NEW_LINE> <INDENT> def testValidation(self): <NEW_LINE> <INDENT> artifact_test.ArtifactTest.LoadTestArtifacts() <NEW_LINE> for p_cls in parsers.Parser.classes: <NEW_LINE> <INDENT> parser = parsers.Parser.classes[p_cls] <NEW_LINE> parser.Validate() | Test parsers validate. | 6259906f67a9b606de5476e2 |
class EventClass(object): <NEW_LINE> <INDENT> _subclass_map = {} <NEW_LINE> def __init__(self, log_session, event_trace): <NEW_LINE> <INDENT> if (isinstance(event_trace, LP_EVENT_TRACE)): <NEW_LINE> <INDENT> header = event_trace.contents.Header <NEW_LINE> user_data, user_data_length = (event_trace.contents.MofData, event_trace.contents.MofDataLength) <NEW_LINE> <DEDENT> elif (isinstance(event_trace, LP_EVENT_RECORD)): <NEW_LINE> <INDENT> header = event_trace.contents.EventHeader <NEW_LINE> user_data, user_data_length = (event_trace.contents.UserData, event_trace.contents.UserDataLength) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Unrecognized event format") <NEW_LINE> <DEDENT> self.process_id = header.ProcessId <NEW_LINE> self.thread_id = header.ThreadId <NEW_LINE> self.raw_time_stamp = header.TimeStamp <NEW_LINE> self.time_stamp = log_session.SessionTimeToTime(header.TimeStamp) <NEW_LINE> reader = binary_buffer.BinaryBufferReader(user_data, user_data_length) <NEW_LINE> for name, field in self._fields_: <NEW_LINE> <INDENT> setattr(self, name, field(log_session, reader)) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def Get(guid, version, event_type): <NEW_LINE> <INDENT> key = guid, version, event_type <NEW_LINE> return EventClass._subclass_map.get(key, None) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def Set(guid, version, event_type, subclass): <NEW_LINE> <INDENT> key = guid, version, event_type <NEW_LINE> EventClass._subclass_map[key] = subclass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetEventTypes(cls): <NEW_LINE> <INDENT> return cls._event_types_ | Base class for event classes.
The EventClass class is used to transform an event data buffer into a set of
named attributes on the object. Classes that want to parse event data should
derive from this class and define the _fields_ property:
class MyEventClass(EventClass):
_fields_ = [('IntField', field.Int32),
('StringField', field.String)]
The constructor iterates over the _fields_ property and invokes the function
defined in the second half of the tuple. The return value is assigned as a
named attribute of this class, the name being the first half of the tuple. The
function in the second half of the tuple should take a TraceLogSession and a
BinaryBufferReader as parameters and should return a mixed value.
Subclasses must also define the _event_types_ list. This will cause the
subclass to be registered in the the EventClass's subclass map for each event
listed in _event_types_. This is used by the log consumer to identify the
proper event class to create when handling a particular log event.
Attributes:
process_id: The ID of the process that generated the event.
thread_id: The ID of the thread that generated the event.
raw_time_stamp: The raw time stamp of the ETW event.
time_stamp: The timestamp of the event (in seconds since 01-01-1970). | 6259906f0a50d4780f706a00 |
class GuestbookEntryCreate(AjaxableResponseMixin, GuestbookEntryFormMixin, GuestbookMixin, CreateView): <NEW_LINE> <INDENT> form_class = GuestbookEntryForm <NEW_LINE> context_object_name = 'form' <NEW_LINE> template_name = 'guestbook/guestbook_form.html' <NEW_LINE> status = 'create' <NEW_LINE> form_title = 'Add a Note' <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> account_notes_count = GuestbookEntry.objects.filter(created_by=request.user).count() <NEW_LINE> if account_notes_count < self.notes_limit: <NEW_LINE> <INDENT> return super(GuestbookEntryCreate, self).get(request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = None <NEW_LINE> context_dict = self.get_context_data(form=form) <NEW_LINE> return self.render_to_response(context_dict) <NEW_LINE> <DEDENT> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> form.instance.created_by = self.request.user <NEW_LINE> return super(GuestbookEntryCreate, self).form_valid(form) | This is for creating a guestbook entry with or without Ajax. | 6259906f32920d7e50bc78c5 |
class PublicRecipeApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_auth_required(self): <NEW_LINE> <INDENT> response = self.client.get(RECIPES_URL) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) | Test unauthorized recipe API access | 6259906f8e7ae83300eea90f |
class personne: <NEW_LINE> <INDENT> def __init__(self, nom, prenom): <NEW_LINE> <INDENT> self.nom = nom <NEW_LINE> self.prenom = prenom <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Le nom est {} {}".format(self.prenom, self.nom) | Objet qui représente une personne | 6259906f7b25080760ed8922 |
class BankShort: <NEW_LINE> <INDENT> def __init__(self, account: str = None, name: str = None, bic: str = None, corr_acc: str = None): <NEW_LINE> <INDENT> self.__account = account <NEW_LINE> self.__name = name <NEW_LINE> self.__bic = bic <NEW_LINE> self.__corr_acc = corr_acc <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ('<%s ' % self.__class__.__name__) + ' '.join( ['%s:%s' % (k.replace('_' + self.__class__.__name__, '').lstrip('_'), str(self.__dict__[k])) for k in self.__dict__]) + '>' <NEW_LINE> <DEDENT> @property <NEW_LINE> def account(self) -> str: <NEW_LINE> <INDENT> return self.__account <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> @property <NEW_LINE> def bic(self) -> str: <NEW_LINE> <INDENT> return self.__bic <NEW_LINE> <DEDENT> @property <NEW_LINE> def corr_acc(self) -> str: <NEW_LINE> <INDENT> return self.__corr_acc | Короткие банковские реквизиты.
Номер счета, Название банка, БИК и корр. счёт. | 6259906ffff4ab517ebcf099 |
class PersonVehicle(models.Model): <NEW_LINE> <INDENT> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True) <NEW_LINE> vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT) <NEW_LINE> person = models.ForeignKey(Person, on_delete=models.PROTECT) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{} {}".format(self.vehicle, self.person) | PersonVehicle register the relatioship between a vehicle in a person,
in other words the owner of the vehicle at a given point in time | 6259906f4e4d562566373c86 |
class RegistroC405(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'C405'), CampoData(2, 'DT_DOC'), Campo(3, 'CRO'), Campo(4, 'CRZ'), Campo(5, 'NUM_COO_FIN'), Campo(6, 'GT_FIN'), CampoNumerico(7, 'VL_BRT'), ] <NEW_LINE> nivel = 3 | REDUÇÃO Z (CÓDIGO 02 E 2D) | 6259906fd486a94d0ba2d83e |
class Neighborhood(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def origin_of_dim(dim): <NEW_LINE> <INDENT> return tuple([0 for _ in range(dim)]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def flatten(l): <NEW_LINE> <INDENT> list_type = type(l) <NEW_LINE> l = list(l) <NEW_LINE> i = 0 <NEW_LINE> while i < len(l): <NEW_LINE> <INDENT> while isinstance(l[i], list): <NEW_LINE> <INDENT> if not l[i]: <NEW_LINE> <INDENT> l.pop(i) <NEW_LINE> i -= 1 <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> l[i:i + 1] = l[i] <NEW_LINE> <DEDENT> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return list_type(l) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def neighborhood_generator(r, d, l=list()): <NEW_LINE> <INDENT> if d == 0: <NEW_LINE> <INDENT> return tuple(l) <NEW_LINE> <DEDENT> return [Neighborhood.neighborhood_generator(r, d-1, l + [x]) for x in range(-r, r+1)] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def von_neuman_neighborhood(radius=1, dim=2, include_origin=True): <NEW_LINE> <INDENT> def within_legal_taxi_distance(p): <NEW_LINE> <INDENT> return sum([abs(x) for x in list(p)]) <= radius <NEW_LINE> <DEDENT> points = list(filter(within_legal_taxi_distance, Neighborhood.flatten(Neighborhood.neighborhood_generator(radius, dim)))) <NEW_LINE> if not include_origin: <NEW_LINE> <INDENT> points.remove(Neighborhood.origin_of_dim(dim)) <NEW_LINE> <DEDENT> return points <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def moore_neighborhood(radius=1, dim=2, include_origin=True): <NEW_LINE> <INDENT> points = Neighborhood.flatten(Neighborhood.neighborhood_generator(radius, dim)) <NEW_LINE> if not include_origin: <NEW_LINE> <INDENT> points.remove(Neighborhood.origin_of_dim(dim)) <NEW_LINE> <DEDENT> return points <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def compute_halo(point_list): <NEW_LINE> <INDENT> halo = None <NEW_LINE> if len(point_list) > 0: <NEW_LINE> <INDENT> dim = len(point_list[0]) <NEW_LINE> halo = numpy.array([(0, 0) for x in range(dim)]) <NEW_LINE> for point in point_list: <NEW_LINE> <INDENT> for d in range(dim): <NEW_LINE> <INDENT> if halo[d][0] < abs(point[d]): <NEW_LINE> <INDENT> halo[d][0] = abs(point[d]) <NEW_LINE> <DEDENT> if halo[d][1] < abs(point[d]): <NEW_LINE> <INDENT> halo[d][1] = abs(point[d]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return tuple(halo) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def compute_from_indices(matrix, mid_point=None): <NEW_LINE> <INDENT> matrix = numpy.array(matrix) <NEW_LINE> neighbor_points = [] <NEW_LINE> coefficients = [] <NEW_LINE> it = numpy.nditer(matrix, flags=['multi_index']) <NEW_LINE> dim = len(matrix.shape) <NEW_LINE> if mid_point is None: <NEW_LINE> <INDENT> mid_point = [x // 2 for x in matrix.shape] <NEW_LINE> <DEDENT> while not it.finished: <NEW_LINE> <INDENT> value = it[0] <NEW_LINE> index = it.multi_index <NEW_LINE> if value != 0: <NEW_LINE> <INDENT> relative_point = tuple([it.multi_index[d]-mid_point[d] for d in range(dim)]) <NEW_LINE> neighbor_points.append(relative_point) <NEW_LINE> coefficients.append(matrix[index]) <NEW_LINE> <DEDENT> it.iternext() <NEW_LINE> <DEDENT> halo = Neighborhood.compute_halo(neighbor_points) <NEW_LINE> return neighbor_points, coefficients, halo | convenience class for defining and testing neighborhoods | 6259906ff548e778e596ce0c |
class Package: <NEW_LINE> <INDENT> def __init__(self, package_name): <NEW_LINE> <INDENT> self.pkg = get_distribution(package_name) <NEW_LINE> self.result = namedtuple( "Result", [ "name", "environment", "description_license", "classifier_licenses", "lgtm", ], ) <NEW_LINE> self.result.name = "{0}".format(self.pkg.project_name) <NEW_LINE> self.result.environment = sys.executable.split(os.sep)[-3] <NEW_LINE> self.service_path = "https://lgtm.com/api/v1.0/projects/" <NEW_LINE> <DEDENT> def get_lgtm_result(self, url_identifier): <NEW_LINE> <INDENT> if url_identifier: <NEW_LINE> <INDENT> full_path = "{0}{1}".format(self.service_path, url_identifier) <NEW_LINE> time.sleep(1) <NEW_LINE> response = requests.get(full_path, headers={"Accept": "application/json"}) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> for each_lang in json.loads(response.text).get("languages", []): <NEW_LINE> <INDENT> if each_lang.get("language", None) == "python": <NEW_LINE> <INDENT> return each_lang <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return {} <NEW_LINE> <DEDENT> def lgtm_query(self, line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = urlparse(line[line.find("https://") :]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return self.get_lgtm_result(None) <NEW_LINE> <DEDENT> whitelist = ("github.com",) <NEW_LINE> if all( ( any( ( line.startswith("Project-URL: Source"), line.startswith("Home-page"), ) ), url.netloc in whitelist, ) ): <NEW_LINE> <INDENT> return self.get_lgtm_result("g{0}".format(url.path)) <NEW_LINE> <DEDENT> return self.get_lgtm_result(None) <NEW_LINE> <DEDENT> def filters(self, line): <NEW_LINE> <INDENT> return { "lgtm": self.lgtm_query(line), "licenses": compress( (line[9:], line[23:].replace("OSI Approved", "").replace(" :: ", "")), (line.startswith("License:"), line.startswith("Classifier: License")), ), } <NEW_LINE> <DEDENT> def get_pkg_details(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lines = self.pkg.get_metadata_lines("METADATA") <NEW_LINE> <DEDENT> except (OSError, KeyError): <NEW_LINE> <INDENT> lines = self.pkg.get_metadata_lines("PKG-INFO") <NEW_LINE> <DEDENT> return map(self.filters, lines) <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> lgtm = dict() <NEW_LINE> classifiers = list() <NEW_LINE> for each in self.get_pkg_details(): <NEW_LINE> <INDENT> lgtm.update(each["lgtm"]) <NEW_LINE> classifiers.extend(filter(None, each["licenses"])) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.result.description_license = classifiers.pop(0) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.result.classifier_licenses = classifiers <NEW_LINE> self.result.lgtm = lgtm <NEW_LINE> return self.result | It creates a pkg_resources.DistInfoDistribution (setuptools) object
and extracts the necessary information from its metadata attributes
and classifiers. | 6259906f7c178a314d78e82b |
class ROSTopicIOException(ROSTopicException): <NEW_LINE> <INDENT> pass | ros_datafeed errors related to network I/O failures | 6259906fa17c0f6771d5d7e9 |
class VmSnapshot: <NEW_LINE> <INDENT> def __init__(self, items): <NEW_LINE> <INDENT> self.__dict__.update(items) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, apiclient, vmid, snapshotmemory="false", name=None, description=None): <NEW_LINE> <INDENT> cmd = createVMSnapshot.createVMSnapshotCmd() <NEW_LINE> cmd.virtualmachineid = vmid <NEW_LINE> if snapshotmemory: <NEW_LINE> <INDENT> cmd.snapshotmemory = snapshotmemory <NEW_LINE> <DEDENT> if name: <NEW_LINE> <INDENT> cmd.name = name <NEW_LINE> <DEDENT> if description: <NEW_LINE> <INDENT> cmd.description = description <NEW_LINE> <DEDENT> return VmSnapshot(apiclient.createVMSnapshot(cmd).__dict__) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def list(cls, apiclient, **kwargs): <NEW_LINE> <INDENT> cmd = listVMSnapshot.listVMSnapshotCmd() <NEW_LINE> [setattr(cmd, k, v) for k, v in list(kwargs.items())] <NEW_LINE> if 'account' in list(kwargs.keys()) and 'domainid' in list(kwargs.keys()): <NEW_LINE> <INDENT> cmd.listall = True <NEW_LINE> <DEDENT> return (apiclient.listVMSnapshot(cmd)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def revertToSnapshot(cls, apiclient, vmsnapshotid): <NEW_LINE> <INDENT> cmd = revertToVMSnapshot.revertToVMSnapshotCmd() <NEW_LINE> cmd.vmsnapshotid = vmsnapshotid <NEW_LINE> return apiclient.revertToVMSnapshot(cmd) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def deleteVMSnapshot(cls, apiclient, vmsnapshotid): <NEW_LINE> <INDENT> cmd = deleteVMSnapshot.deleteVMSnapshotCmd() <NEW_LINE> cmd.vmsnapshotid = vmsnapshotid <NEW_LINE> return apiclient.deleteVMSnapshot(cmd) | Manage VM Snapshot life cycle | 6259906faad79263cf430035 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.