code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class FakeBazel(object): <NEW_LINE> <INDENT> def __init__(self, bazel_binary_path, bazelrc): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def command(self, command_name, args=None, collect_memory=False): <NEW_LINE> <INDENT> args = args or [] <NEW_LINE> fake_log('Executing Bazel command: bazel %s %s' % (command_name, ' '.join(args)))
Fake class for utils.Bazel
62598ff24c3428357761ab5e
class _EnchantObject(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._this = None <NEW_LINE> if _e is not None: <NEW_LINE> <INDENT> self._init_this() <NEW_LINE> <DEDENT> <DEDENT> def _check_this(self,msg=None): <NEW_LINE> <INDENT> if self._this is None: <NEW_LINE> <INDENT> if msg is None: <NEW_LINE> <INDENT> msg = "%s unusable: the underlying C-library object has been freed." <NEW_LINE> msg = msg % (self.__class__.__name__,) <NEW_LINE> <DEDENT> raise Error(msg) <NEW_LINE> <DEDENT> <DEDENT> def _init_this(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _raise_error(self,default="Unspecified Error",eclass=enchant_errors.Error): <NEW_LINE> <INDENT> raise eclass(default) <NEW_LINE> <DEDENT> _raise_error._DOC_ERRORS = ["eclass"] <NEW_LINE> def __getstate__(self): <NEW_LINE> <INDENT> state = self.__dict__.copy() <NEW_LINE> state["_this"] = None <NEW_LINE> return state <NEW_LINE> <DEDENT> def __setstate__(self,state): <NEW_LINE> <INDENT> self.__dict__.update(state) <NEW_LINE> self._init_this()
Base class for enchant objects. This class implements some general functionality for interfacing with the '_enchant' C-library in a consistent way. All public objects from the 'enchant' module are subclasses of this class. All enchant objects have an attribute '_this' which contains the pointer to the underlying C-library object. The method '_check_this' can be called to ensure that this point is not None, raising an exception if it is.
62598ff23cc13d1c6d466007
class PlayerCellInfo(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.is_hidden = True <NEW_LINE> self._adjacent_mines = 0 <NEW_LINE> self.is_flagged = False <NEW_LINE> <DEDENT> def count_adjacent_mines(self): <NEW_LINE> <INDENT> if(self.is_hidden): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._adjacent_mines <NEW_LINE> <DEDENT> <DEDENT> def get_game_char(self): <NEW_LINE> <INDENT> cell_char = '0' <NEW_LINE> if self.is_flagged: <NEW_LINE> <INDENT> cell_char = 'F' <NEW_LINE> <DEDENT> elif self.is_hidden: <NEW_LINE> <INDENT> cell_char = '-' <NEW_LINE> <DEDENT> elif self.has_mine: <NEW_LINE> <INDENT> cell_char = 'X' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cell_char = str(self._adjacent_mines) <NEW_LINE> <DEDENT> return cell_char
Representation of what a player knows about a specific game cell Lack's any hidden internal game state information
62598ff226238365f5fad417
class STMTRS(Aggregate): <NEW_LINE> <INDENT> curdef = OneOf(*CURRENCY_CODES, required=True) <NEW_LINE> bankacctfrom = SubAggregate(BANKACCTFROM, required=True) <NEW_LINE> banktranlist = SubAggregate(BANKTRANLIST) <NEW_LINE> banktranlistp = Unsupported() <NEW_LINE> ledgerbal = SubAggregate(LEDGERBAL, required=True) <NEW_LINE> availbal = SubAggregate(AVAILBAL) <NEW_LINE> cashadvbalamt = Decimal() <NEW_LINE> intrate = Decimal() <NEW_LINE> ballist = SubAggregate(BALLIST) <NEW_LINE> mktginfo = String(360) <NEW_LINE> @property <NEW_LINE> def account(self): <NEW_LINE> <INDENT> return self.bankacctfrom <NEW_LINE> <DEDENT> @property <NEW_LINE> def transactions(self): <NEW_LINE> <INDENT> return self.banktranlist <NEW_LINE> <DEDENT> @property <NEW_LINE> def balance(self): <NEW_LINE> <INDENT> return self.ledgerbal
OFX section 11.4.2.2
62598ff2187af65679d2a054
class EditForm(base.EditForm): <NEW_LINE> <INDENT> form_fields = form.Fields(IBannersPortlet) <NEW_LINE> form_fields['banner_folder'].custom_widget = UberSelectionWidget
Edit form for the banners portlet.
62598ff326238365f5fad41b
class SVCDescriptor(): <NEW_LINE> <INDENT> def __init__(self, name, display_name, username, ip, port): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.display_name = display_name <NEW_LINE> self.username = username <NEW_LINE> self.ip = ip <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return _("Storage %(display_name)s (%(username)s@%(ip)s:%(port)s)") % {'display_name': self.display_name, 'username': self.username, 'ip': self.ip, 'port': self.port }
This class captures enough information to describe a SVC/Storwize controller. It is passed to SVC-related exceptions (SVCException subclasses), so that the consumers of the exception can easily tell which storage provider the exception originated from.
62598ff3187af65679d2a055
class TestSimplifyVersion(object): <NEW_LINE> <INDENT> def test_normal_releases(self): <NEW_LINE> <INDENT> assert barman.utils.simplify_version("9.1.2") == "9.1" <NEW_LINE> assert barman.utils.simplify_version("10.1") == "10" <NEW_LINE> <DEDENT> def test_dev_releases(self): <NEW_LINE> <INDENT> assert barman.utils.simplify_version("9.1devel") == "9.1" <NEW_LINE> assert barman.utils.simplify_version("10devel") == "10" <NEW_LINE> <DEDENT> def test_rc_releases(self): <NEW_LINE> <INDENT> assert barman.utils.simplify_version("9.1rc1") == "9.1" <NEW_LINE> assert barman.utils.simplify_version("10rc1") == "10" <NEW_LINE> <DEDENT> def test_beta_releases(self): <NEW_LINE> <INDENT> assert barman.utils.simplify_version("9.1beta4") == "9.1" <NEW_LINE> assert barman.utils.simplify_version("10beta4") == "10"
Tests for simplify_version function
62598ff3187af65679d2a056
class Nurse(Enemy): <NEW_LINE> <INDENT> def __init__(self, g, pos): <NEW_LINE> <INDENT> Enemy.__init__(self, g, pos, 'nurse') <NEW_LINE> hitSoundFile = os.path.join("effects", "critter6.wav") <NEW_LINE> self.birdhit = pygame.mixer.Sound(hitSoundFile) <NEW_LINE> self.health = 2 <NEW_LINE> self.speed = 4 <NEW_LINE> self.direction = random.randint(0, 2) % 2 <NEW_LINE> self.mode = 'walking' <NEW_LINE> self.changedDirLastTick = 0 <NEW_LINE> <DEDENT> def loop(self, g, r): <NEW_LINE> <INDENT> canhitplayer = 0 <NEW_LINE> self.pos = g.screen_to_tile((self.rect.x - g.view.x + 16, self.rect.y - g.view.y + 32)) <NEW_LINE> belowpos = g.clayer[self.pos[1] ][self.pos[0]] <NEW_LINE> if belowpos != 1: <NEW_LINE> <INDENT> if self.changedDirLastTick: <NEW_LINE> <INDENT> self.rect.y += 10 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.direction = not self.direction <NEW_LINE> self.changedDirLastTick = 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.changedDirLastTick = 0 <NEW_LINE> <DEDENT> if self.mode == 'walking': <NEW_LINE> <INDENT> frme = 1 + (self.timer / 4) % 4 <NEW_LINE> self.image = g.images['nurse'][0].subsurface((frme * 32, 0, 32, 32)) <NEW_LINE> self.rect.x += self.speed <NEW_LINE> if self.direction == 1: <NEW_LINE> <INDENT> self.rect.x -= self.speed * 2 <NEW_LINE> <DEDENT> self.btimer += 1 <NEW_LINE> if self.btimer < 10: <NEW_LINE> <INDENT> self.direction = 0 <NEW_LINE> if self.rect.x > g.player.rect.x: <NEW_LINE> <INDENT> self.direction = 1 <NEW_LINE> <DEDENT> <DEDENT> if self.btimer > 150: <NEW_LINE> <INDENT> self.btimer = 0 <NEW_LINE> self.mode = 'idle' <NEW_LINE> <DEDENT> dy = self.rect.x - g.player.rect.x <NEW_LINE> dh = self.rect.y - g.player.rect.y <NEW_LINE> if dy < 30 and dy > -30: <NEW_LINE> <INDENT> if dh < 30 and dh > -30: <NEW_LINE> <INDENT> self.mode = 'attack' <NEW_LINE> self.timer = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif self.mode == 'idle': <NEW_LINE> <INDENT> self.image = g.images['nurse'][0].subsurface((0, 0, 32, 32)) <NEW_LINE> self.btimer += 1 <NEW_LINE> if self.btimer > 40: <NEW_LINE> <INDENT> self.btimer = 0 <NEW_LINE> self.mode = 'walking' <NEW_LINE> <DEDENT> <DEDENT> elif self.mode == 'attack': <NEW_LINE> <INDENT> frme = (self.timer / 4) <NEW_LINE> self.image = g.images['nurse'][0].subsurface((frme * 32, 32, 32, 32)) <NEW_LINE> if frme > 3: <NEW_LINE> <INDENT> canhitplayer = 1 <NEW_LINE> <DEDENT> if frme >= 4: <NEW_LINE> <INDENT> self.btimer = 0 <NEW_LINE> self.mode = 'walking' <NEW_LINE> <DEDENT> <DEDENT> elif self.mode == 'death': <NEW_LINE> <INDENT> self.destroy() <NEW_LINE> <DEDENT> self.loop_hit_death(g, r, 1, canhitplayer) <NEW_LINE> <DEDENT> def rebound(self, h): <NEW_LINE> <INDENT> self.direction = not self.direction <NEW_LINE> self.mode = 'walking'
Nurse. runs around trying to stab you
62598ff3627d3e7fe0e07765
@attr('shard_1') <NEW_LINE> class BadComponentTest(ContainerBase): <NEW_LINE> <INDENT> __test__ = False <NEW_LINE> def get_bad_html_content(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def populate_course_fixture(self, course_fixture): <NEW_LINE> <INDENT> course_fixture.add_children( XBlockFixtureDesc('chapter', 'Test Section').add_children( XBlockFixtureDesc('sequential', 'Test Subsection').add_children( XBlockFixtureDesc('vertical', 'Test Unit').add_children( XBlockFixtureDesc('html', 'Unit HTML', data=self.get_bad_html_content()), XBlockFixtureDesc('problem', 'Unit Problem', data='<problem></problem>') ) ) ) ) <NEW_LINE> <DEDENT> def test_html_comp_visible(self): <NEW_LINE> <INDENT> unit = self.go_to_unit_page() <NEW_LINE> verify_ordering(self, unit, [{"": ["Unit HTML", "Unit Problem"]}])
Tests that components with bad content do not break the Unit page.
62598ff34c3428357761ab6c
class StdOutListener(StreamListener): <NEW_LINE> <INDENT> def on_data(self, raw_data): <NEW_LINE> <INDENT> print(raw_data) <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_error(self, status_code): <NEW_LINE> <INDENT> print(status_code)
Docstring
62598ff33cc13d1c6d466015
class UpdateAPIView(mixins.UpdateModelMixin, GenericAPIView): <NEW_LINE> <INDENT> def put(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.update(request, *args, **kwargs) <NEW_LINE> <DEDENT> def patch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.partial_update(request, *args, **kwargs)
Adaptation of DRF UpdateAPIView
62598ff326238365f5fad425
class PyNodesSocket(bpy.types.NodeSocket, NodeSocket): <NEW_LINE> <INDENT> bl_idname = "PyNodesSocket" <NEW_LINE> parameter_types = parameter_types_all
Generic pynodes socket
62598ff34c3428357761ab70
class Polyhedron_QQ_polymake(Polyhedron_polymake, Polyhedron_QQ): <NEW_LINE> <INDENT> pass
Polyhedra over `\QQ` with polymake. INPUT: - ``Vrep`` -- a list ``[vertices, rays, lines]`` or ``None`` - ``Hrep`` -- a list ``[ieqs, eqns]`` or ``None`` EXAMPLES:: sage: p = Polyhedron(vertices=[(0,0),(1,0),(0,1)], # optional - polymake ....: rays=[(1,1)], lines=[], ....: backend='polymake', base_ring=QQ) sage: TestSuite(p).run() # optional - polymake
62598ff3091ae356687054e4
class Sampling(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def call(self, inputs): <NEW_LINE> <INDENT> z_mean, z_log_var = inputs <NEW_LINE> batch = tf.shape(z_mean)[0] <NEW_LINE> dim = tf.shape(z_mean)[1] <NEW_LINE> epsilon = tf.keras.backend.random_normal(shape=(batch, dim)) <NEW_LINE> return z_mean + tf.exp(0.5 * z_log_var) * epsilon
Uses (z_mean, z_log_var) to sample z, the vector encoding a digit.
62598ff3627d3e7fe0e0776d
@dns.immutable.immutable <NEW_LINE> class SPF(dns.rdtypes.txtbase.TXTBase): <NEW_LINE> <INDENT> pass
SPF record
62598ff34c3428357761ab76
class AgentExtRpcCallback(object): <NEW_LINE> <INDENT> RPC_API_VERSION = '1.0' <NEW_LINE> START_TIME = timeutils.utcnow() <NEW_LINE> def __init__(self, plugin=None): <NEW_LINE> <INDENT> self.plugin = plugin <NEW_LINE> <DEDENT> def report_state(self, context, **kwargs): <NEW_LINE> <INDENT> time = kwargs['time'] <NEW_LINE> time = timeutils.parse_strtime(time) <NEW_LINE> if self.START_TIME > time: <NEW_LINE> <INDENT> LOG.debug(_("Message with invalid timestamp received")) <NEW_LINE> return <NEW_LINE> <DEDENT> agent_state = kwargs['agent_state']['agent_state'] <NEW_LINE> if not self.plugin: <NEW_LINE> <INDENT> self.plugin = manager.NeutronManager.get_plugin() <NEW_LINE> <DEDENT> self.plugin.create_or_update_agent(context, agent_state)
Processes the rpc report in plugin implementations.
62598ff3627d3e7fe0e0776f
class UrlBase(object): <NEW_LINE> <INDENT> def __init__(self, source=None): <NEW_LINE> <INDENT> self.urls = list(map(Url, source.urls)) if source else [] <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return [url.serialize() for url in self.urls] <NEW_LINE> <DEDENT> def to_struct(self): <NEW_LINE> <INDENT> return [url.to_struct() for url in self.urls] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_struct(cls, struct): <NEW_LINE> <INDENT> return [Url.from_struct(url) for url in struct] <NEW_LINE> <DEDENT> def unserialize(self, data): <NEW_LINE> <INDENT> self.urls = [Url().unserialize(item) for item in data] <NEW_LINE> <DEDENT> def get_url_list(self): <NEW_LINE> <INDENT> return self.urls <NEW_LINE> <DEDENT> def set_url_list(self, url_list): <NEW_LINE> <INDENT> self.urls = url_list <NEW_LINE> <DEDENT> def _merge_url_list(self, acquisition): <NEW_LINE> <INDENT> url_list = self.urls[:] <NEW_LINE> for addendum in acquisition.get_url_list(): <NEW_LINE> <INDENT> for url in url_list: <NEW_LINE> <INDENT> equi = url.is_equivalent(addendum) <NEW_LINE> if equi == IDENTICAL: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif equi == EQUAL: <NEW_LINE> <INDENT> url.merge(addendum) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.urls.append(addendum) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_url(self, url): <NEW_LINE> <INDENT> self.urls.append(url) <NEW_LINE> <DEDENT> def remove_url(self, url): <NEW_LINE> <INDENT> if url in self.urls: <NEW_LINE> <INDENT> self.urls.remove(url) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
Base class for url-aware objects.
62598ff315fb5d323ce7f612
class ServiceThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, service): <NEW_LINE> <INDENT> super(ServiceThread, self).__init__() <NEW_LINE> self.service = service <NEW_LINE> self.log = log_register('service_thread') <NEW_LINE> self._started = False <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> super(ServiceThread, self).start() <NEW_LINE> self._started = True <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if hasattr(self.service, 'name'): <NEW_LINE> <INDENT> name = self.service.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = self.service.__class__.__name__ <NEW_LINE> <DEDENT> self.log.debug("running ServiceThread '%s'" % name) <NEW_LINE> self.name = name <NEW_LINE> if trace: <NEW_LINE> <INDENT> sys.settrace(trace) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.service.run() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> exc_info = sys.exc_info() <NEW_LINE> backtrace = '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info()))) <NEW_LINE> self.log.error("Exception in main loop. backtrace: %s" % backtrace) <NEW_LINE> os._exit(-1) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if not self._started: <NEW_LINE> <INDENT> self.log.error("Attempted to stop ServiceThread '%s' before it was started." % self.service.__class__.__name__) <NEW_LINE> os._exit(-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.service.stop()
Sometimes a single service may have multiple threads of execution. Use this class rather than the bare threading.Thread to help Chroma keep track of your threads. This wraps a Thread-like object which has a `run` and `stop` method, passed in at construction time`
62598ff3c4546d3d9def76ee
class EB_OpenSSL(ConfigureMake): <NEW_LINE> <INDENT> def configure_step(self, cmd_prefix=''): <NEW_LINE> <INDENT> cmd = "%s %s./config --prefix=%s threads shared %s" % (self.cfg['preconfigopts'], cmd_prefix, self.installdir, self.cfg['configopts']) <NEW_LINE> (out, _) = run_cmd(cmd, log_all=True, simple=False) <NEW_LINE> return out <NEW_LINE> <DEDENT> def sanity_check_step(self): <NEW_LINE> <INDENT> custom_paths = {'files':["lib64/%s" % x for x in ['engines', 'libcrypto.a', 'libcrypto.so', 'libcrypto.so.1.0.0', 'libssl.a', 'libssl.so', 'libssl.so.1.0.0']] + ['bin/openssl'], 'dirs': [] } <NEW_LINE> super(EB_OpenSSL, self).sanity_check_step(custom_paths=custom_paths)
Support for building OpenSSL
62598ff33cc13d1c6d466021
class BasePlugin(SimpleItem, PropertyManager): <NEW_LINE> <INDENT> zmi_icon = 'fas fa-puzzle-piece' <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> manage_options = (({'label': 'Activate', 'action': 'manage_activateInterfacesForm'},) + SimpleItem.manage_options + PropertyManager.manage_options) <NEW_LINE> prefix = '' <NEW_LINE> _properties = (dict(id='prefix', type='string', mode='w', label='Optional Prefix'),) <NEW_LINE> security.declareProtected(ManageUsers, 'manage_activateInterfacesForm') <NEW_LINE> manage_activateInterfacesForm = PageTemplateFile( 'www/bpActivateInterfaces', globals(), __name__='manage_activateInterfacesForm') <NEW_LINE> @security.protected(ManageUsers) <NEW_LINE> def listInterfaces(self): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for iface in flattenInterfaces(providedBy(self)): <NEW_LINE> <INDENT> results.append(iface.__name__) <NEW_LINE> <DEDENT> return results <NEW_LINE> <DEDENT> @security.protected(ManageUsers) <NEW_LINE> def testImplements(self, interface): <NEW_LINE> <INDENT> return interface.providedBy(self) <NEW_LINE> <DEDENT> @security.protected(ManageUsers) <NEW_LINE> def manage_activateInterfaces(self, interfaces, RESPONSE=None): <NEW_LINE> <INDENT> pas_instance = self._getPAS() <NEW_LINE> plugins = pas_instance._getOb('plugins') <NEW_LINE> active_interfaces = [] <NEW_LINE> for iface_name in interfaces: <NEW_LINE> <INDENT> active_interfaces.append(plugins._getInterfaceFromName( iface_name)) <NEW_LINE> <DEDENT> pt = plugins._plugin_types <NEW_LINE> id = self.getId() <NEW_LINE> for type in pt: <NEW_LINE> <INDENT> ids = plugins.listPluginIds(type) <NEW_LINE> if id not in ids and type in active_interfaces: <NEW_LINE> <INDENT> plugins.activatePlugin(type, id) <NEW_LINE> <DEDENT> elif id in ids and type not in active_interfaces: <NEW_LINE> <INDENT> plugins.deactivatePlugin(type, id) <NEW_LINE> <DEDENT> <DEDENT> if RESPONSE is not None: <NEW_LINE> <INDENT> RESPONSE.redirect('%s/manage_workspace' '?manage_tabs_message=' 'Interface+activations+updated.' % self.absolute_url()) <NEW_LINE> <DEDENT> <DEDENT> @security.private <NEW_LINE> def _getPAS(self): <NEW_LINE> <INDENT> return aq_parent(aq_inner(self)) <NEW_LINE> <DEDENT> @security.private <NEW_LINE> def _invalidatePrincipalCache(self, id): <NEW_LINE> <INDENT> pas = self._getPAS() <NEW_LINE> if pas is not None and hasattr(aq_base(pas), 'ZCacheable_invalidate'): <NEW_LINE> <INDENT> view_name = createViewName('_findUser', id) <NEW_LINE> pas.ZCacheable_invalidate(view_name) <NEW_LINE> <DEDENT> <DEDENT> @security.private <NEW_LINE> def applyTransform(self, value): <NEW_LINE> <INDENT> pas = self._getPAS() <NEW_LINE> if pas is not None: <NEW_LINE> <INDENT> return pas.applyTransform(value) <NEW_LINE> <DEDENT> return value
Base class for all PluggableAuthService Plugins
62598ff3627d3e7fe0e07777
class TenantRequestFactoryTestCase(TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> tenant = TenantModel(schema_name="tenant1") <NEW_LINE> tenant.save(verbosity=0) <NEW_LINE> DomainModel.objects.create(tenant=tenant, domain="tenant1.test.com", is_primary=True) <NEW_LINE> cls.request = TenantRequestFactory(tenant) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> for tenant in TenantModel.objects.all(): <NEW_LINE> <INDENT> tenant.delete(force_drop=True) <NEW_LINE> <DEDENT> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> request = self.request.get("/not/important/") <NEW_LINE> self.assertEqual(request.build_absolute_uri("/whatever/"), "http://tenant1.test.com/whatever/") <NEW_LINE> <DEDENT> def test_post(self): <NEW_LINE> <INDENT> request = self.request.post("/not/important/") <NEW_LINE> self.assertEqual(request.build_absolute_uri("/whatever/"), "http://tenant1.test.com/whatever/") <NEW_LINE> <DEDENT> def test_put(self): <NEW_LINE> <INDENT> request = self.request.put("/not/important/") <NEW_LINE> self.assertEqual(request.build_absolute_uri("/whatever/"), "http://tenant1.test.com/whatever/") <NEW_LINE> <DEDENT> def test_patch(self): <NEW_LINE> <INDENT> request = self.request.patch("/not/important/") <NEW_LINE> self.assertEqual(request.build_absolute_uri("/whatever/"), "http://tenant1.test.com/whatever/") <NEW_LINE> <DEDENT> def test_delete(self): <NEW_LINE> <INDENT> request = self.request.delete("/not/important/") <NEW_LINE> self.assertEqual(request.build_absolute_uri("/whatever/"), "http://tenant1.test.com/whatever/")
Test the behavior of the TenantRequestFactory.
62598ff3ad47b63b2c5a8127
class BaseModel(gobject.GObject): <NEW_LINE> <INDENT> __gtype_name__ = "BaseModel" <NEW_LINE> __gsignals__ = { "loaded": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), "saved": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()), } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> gobject.GObject.__init__(self) <NEW_LINE> <DEDENT> def is_modified(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def loaded(self): <NEW_LINE> <INDENT> self.emit('loaded') <NEW_LINE> <DEDENT> def saved(self): <NEW_LINE> <INDENT> self.emit('saved')
Base class for all models.
62598ff326238365f5fad435
class ImageInfo(JObject): <NEW_LINE> <INDENT> NO_COLOR = None <NEW_LINE> HISTOGRAM_MATCHING_OFF = 'off' <NEW_LINE> HISTOGRAM_MATCHING_EQUALIZE = 'equalize' <NEW_LINE> HISTOGRAM_MATCHING_NORMALIZE = 'normalize' <NEW_LINE> def __init__(self, obj): <NEW_LINE> <INDENT> JObject.__init__(self, obj) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> JObject.__del__(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def newImageInfo(colorPaletteDef): <NEW_LINE> <INDENT> return ImageInfo(ImageInfo_newImageInfoPalette(colorPaletteDef._obj)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def newImageInfo(rgbChannelDef): <NEW_LINE> <INDENT> return ImageInfo(ImageInfo_newImageInfoRGB(rgbChannelDef._obj)) <NEW_LINE> <DEDENT> def getColorPaletteDef(self): <NEW_LINE> <INDENT> return ColorPaletteDef(ImageInfo_getColorPaletteDef(self._obj)) <NEW_LINE> <DEDENT> def getRgbChannelDef(self): <NEW_LINE> <INDENT> return RGBChannelDef(ImageInfo_getRgbChannelDef(self._obj)) <NEW_LINE> <DEDENT> def getNoDataColor(self): <NEW_LINE> <INDENT> return Color(ImageInfo_getNoDataColor(self._obj)) <NEW_LINE> <DEDENT> def setNoDataColor(self, noDataColor): <NEW_LINE> <INDENT> ImageInfo_setNoDataColor(self._obj, noDataColor._obj) <NEW_LINE> return <NEW_LINE> <DEDENT> def setHistogramMatching(self, histogramMatching): <NEW_LINE> <INDENT> ImageInfo_setHistogramMatching(self._obj, histogramMatching._obj) <NEW_LINE> return <NEW_LINE> <DEDENT> def isLogScaled(self): <NEW_LINE> <INDENT> return ImageInfo_isLogScaled(self._obj) <NEW_LINE> <DEDENT> def setLogScaled(self, logScaled): <NEW_LINE> <INDENT> ImageInfo_setLogScaled(self._obj, logScaled) <NEW_LINE> return <NEW_LINE> <DEDENT> def getColors(self): <NEW_LINE> <INDENT> return Color(ImageInfo_getColors(self._obj)) <NEW_LINE> <DEDENT> def getColorComponentCount(self): <NEW_LINE> <INDENT> return ImageInfo_getColorComponentCount(self._obj) <NEW_LINE> <DEDENT> def createIndexColorModel(self, scaling): <NEW_LINE> <INDENT> return IndexColorModel(ImageInfo_createIndexColorModel(self._obj, scaling._obj)) <NEW_LINE> <DEDENT> def createComponentColorModel(self): <NEW_LINE> <INDENT> return ComponentColorModel(ImageInfo_createComponentColorModel(self._obj)) <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return Object(ImageInfo_clone(self._obj)) <NEW_LINE> <DEDENT> def createDeepCopy(self): <NEW_LINE> <INDENT> return ImageInfo(ImageInfo_createDeepCopy(self._obj)) <NEW_LINE> <DEDENT> def dispose(self): <NEW_LINE> <INDENT> ImageInfo_dispose(self._obj) <NEW_LINE> return <NEW_LINE> <DEDENT> def setColors(self, colors): <NEW_LINE> <INDENT> ImageInfo_setColors(self._obj, colors._obj) <NEW_LINE> return <NEW_LINE> <DEDENT> def setColorPaletteDef(self, colorPaletteDef, minSample, maxSample, autoDistribute): <NEW_LINE> <INDENT> ImageInfo_setColorPaletteDef(self._obj, colorPaletteDef._obj, minSample, maxSample, autoDistribute) <NEW_LINE> return <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getHistogramMatching(mode): <NEW_LINE> <INDENT> return ImageInfo_HistogramMatching(ImageInfo_getHistogramMatching(mode))
This class contains information about how a product's raster data node is displayed as an image.
62598ff4187af65679d2a064
class EDTestCasePluginUnitExecShiftImagev1_0(EDTestCasePluginUnit): <NEW_LINE> <INDENT> def __init__(self, _strTestName=None): <NEW_LINE> <INDENT> EDTestCasePluginUnit.__init__(self, "EDPluginExecShiftImagev1_0") <NEW_LINE> <DEDENT> def testCheckParameters(self): <NEW_LINE> <INDENT> xsDataInput = XSDataInputShiftImage() <NEW_LINE> edPluginExecShiftImage = self.createPlugin() <NEW_LINE> edPluginExecShiftImage.setDataInput(xsDataInput) <NEW_LINE> edPluginExecShiftImage.checkParameters() <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self.addTestMethod(self.testCheckParameters)
Those are all units tests for the EDNA Exec plugin ShiftImagev1_0
62598ff43cc13d1c6d466029
class BrownbagUserListView(generics.ListAPIView): <NEW_LINE> <INDENT> serializer_class = UserSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return User.objects.filter(brownbag__isnull=True)
A view for getting a list of users who have not done brownbag
62598ff4627d3e7fe0e0777d
class Ui_client_gui(object): <NEW_LINE> <INDENT> def setupUi(self, client_gui): <NEW_LINE> <INDENT> client_gui.setObjectName("client_gui") <NEW_LINE> client_gui.resize(384, 256) <NEW_LINE> self.centralwidget = QtGui.QWidget(client_gui) <NEW_LINE> self.centralwidget.setObjectName("centralwidget") <NEW_LINE> self.gridLayout = QtGui.QGridLayout(self.centralwidget) <NEW_LINE> self.gridLayout.setObjectName("gridLayout") <NEW_LINE> self.con_button = QtGui.QPushButton(self.centralwidget) <NEW_LINE> self.con_button.setObjectName("con_button") <NEW_LINE> self.gridLayout.addWidget(self.con_button, 0, 0, 1, 1) <NEW_LINE> self.con_label = QtGui.QLabel(self.centralwidget) <NEW_LINE> self.con_label.setObjectName("con_label") <NEW_LINE> self.gridLayout.addWidget(self.con_label, 0, 1, 1, 1) <NEW_LINE> self.label = QtGui.QLabel(self.centralwidget) <NEW_LINE> self.label.setObjectName("label") <NEW_LINE> self.gridLayout.addWidget(self.label, 1, 0, 1, 1) <NEW_LINE> self.message_client = QtGui.QLineEdit(self.centralwidget) <NEW_LINE> self.message_client.setObjectName("message_client") <NEW_LINE> self.gridLayout.addWidget(self.message_client, 1, 1, 1, 1) <NEW_LINE> self.send_button = QtGui.QPushButton(self.centralwidget) <NEW_LINE> self.send_button.setObjectName("send_button") <NEW_LINE> self.gridLayout.addWidget(self.send_button, 2, 1, 1, 1) <NEW_LINE> self.label_2 = QtGui.QLabel(self.centralwidget) <NEW_LINE> self.label_2.setObjectName("label_2") <NEW_LINE> self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1) <NEW_LINE> self.chat_client = QtGui.QTextBrowser(self.centralwidget) <NEW_LINE> self.chat_client.setObjectName("chat_client") <NEW_LINE> self.gridLayout.addWidget(self.chat_client, 4, 0, 1, 2) <NEW_LINE> client_gui.setCentralWidget(self.centralwidget) <NEW_LINE> self.statusbar = QtGui.QStatusBar(client_gui) <NEW_LINE> self.statusbar.setObjectName("statusbar") <NEW_LINE> client_gui.setStatusBar(self.statusbar) <NEW_LINE> self.retranslateUi(client_gui) <NEW_LINE> QtCore.QMetaObject.connectSlotsByName(client_gui) <NEW_LINE> <DEDENT> def retranslateUi(self, client_gui): <NEW_LINE> <INDENT> client_gui.setWindowTitle(QtGui.QApplication.translate("client_gui", "Client ", None, QtGui.QApplication.UnicodeUTF8)) <NEW_LINE> self.con_button.setText(QtGui.QApplication.translate("client_gui", "Connect", None, QtGui.QApplication.UnicodeUTF8)) <NEW_LINE> self.con_label.setText(QtGui.QApplication.translate("client_gui", "Status: Not connected", None, QtGui.QApplication.UnicodeUTF8)) <NEW_LINE> self.label.setText(QtGui.QApplication.translate("client_gui", "Message:", None, QtGui.QApplication.UnicodeUTF8)) <NEW_LINE> self.send_button.setText(QtGui.QApplication.translate("client_gui", "Send", None, QtGui.QApplication.UnicodeUTF8)) <NEW_LINE> self.label_2.setText(QtGui.QApplication.translate("client_gui", "Chat:", None, QtGui.QApplication.UnicodeUTF8))
Class for the client GUI
62598ff4ad47b63b2c5a812c
class MusicObject(dict): <NEW_LINE> <INDENT> def __init__(self, id, name, kind, full): <NEW_LINE> <INDENT> self['id'] = id <NEW_LINE> self['name'] = name <NEW_LINE> self['kind'] = kind <NEW_LINE> self['full'] = full <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def play(songs, breakpoint=-1): <NEW_LINE> <INDENT> conf_path = join(common.CONFIG_DIR, 'mpv_input.conf') <NEW_LINE> if not isfile(conf_path): <NEW_LINE> <INDENT> common.w.goodbye('No mpv_input.conf found.') <NEW_LINE> <DEDENT> common.v.replace({'songs': songs[:]}) <NEW_LINE> common.w.display() <NEW_LINE> i = 1 <NEW_LINE> for song in songs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = common.mc.get_stream_url(song['id']) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> common.w.goodbye( 'Access denied: Is your device ID set correctly?' ) <NEW_LINE> <DEDENT> common.w.now_playing( '(%d/%d) %s (%s)' % (i, len(songs), str(song), song['time']) ) <NEW_LINE> try: <NEW_LINE> <INDENT> ret = call( ['mpv', '--really-quiet', '--input-conf', conf_path, url] ) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> ret = 11 <NEW_LINE> <DEDENT> if ret == 11: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> common.v['songs'].pop(0) <NEW_LINE> common.w.display() <NEW_LINE> <DEDENT> return i
A dict representing a song, artist, or album.
62598ff4187af65679d2a065
class SimpleDataExplorer: <NEW_LINE> <INDENT> def __init__(self, **params): <NEW_LINE> <INDENT> self._raw_data = pd.DataFrame() <NEW_LINE> self._columns_slice = [] <NEW_LINE> self._report_file = '' <NEW_LINE> self._boxplot_group = '' <NEW_LINE> self._parse_args(**params) <NEW_LINE> <DEDENT> def _parse_args(self, **params): <NEW_LINE> <INDENT> if 'data_file' in params and 'source' in params: <NEW_LINE> <INDENT> raise ValueError("Parameters 'file_name' and 'source' cannot be" "provided simultaneously") <NEW_LINE> <DEDENT> file_name = params.get('data_file', '') <NEW_LINE> if file_name: <NEW_LINE> <INDENT> reader_config = params.get('source_config', {}) <NEW_LINE> source = CsvDataSource(file_name, reader_config=reader_config) <NEW_LINE> source.prepare() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> source = params['source'] <NEW_LINE> <DEDENT> raw_data = source.data <NEW_LINE> columns_slice = params.get('columns_slice', []) <NEW_LINE> if columns_slice == 'all': <NEW_LINE> <INDENT> columns_slice = list(source.data.columns) <NEW_LINE> <DEDENT> self._raw_data = raw_data <NEW_LINE> self._columns_slice = columns_slice <NEW_LINE> self._boxplot_group = params.get('boxplot_group', None) <NEW_LINE> prefix = os.path.splitext(file_name)[0] <NEW_LINE> default_report_name = prefix + "_report.pdf" <NEW_LINE> self._report_file = params.get('report_file', default_report_name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def plotted_slice(self): <NEW_LINE> <INDENT> columns = self._columns_slice <NEW_LINE> if self._boxplot_group: <NEW_LINE> <INDENT> columns.append(self._boxplot_group) <NEW_LINE> <DEDENT> return self._raw_data[columns] <NEW_LINE> <DEDENT> @property <NEW_LINE> def dataset(self): <NEW_LINE> <INDENT> return self._raw_data <NEW_LINE> <DEDENT> @property <NEW_LINE> def report_file(self): <NEW_LINE> <INDENT> return self._report_file <NEW_LINE> <DEDENT> @report_file.setter <NEW_LINE> def report_file(self, value: str): <NEW_LINE> <INDENT> self._report_file = value <NEW_LINE> <DEDENT> def generate_report(self): <NEW_LINE> <INDENT> report = DataExplorationReport(self._report_file) <NEW_LINE> stats = self._raw_data.describe().transpose() <NEW_LINE> stats["median"] = self._raw_data.median() <NEW_LINE> text = "Records count: " + str(stats["count"][0]) <NEW_LINE> report.add_element(PlainTextEntry(text=text)) <NEW_LINE> del stats["count"] <NEW_LINE> df_without_index = stats.reset_index() <NEW_LINE> report.add_element(TextualTableEntry(table=df_without_index)) <NEW_LINE> sliced_data = self.plotted_slice <NEW_LINE> for column in self._columns_slice: <NEW_LINE> <INDENT> plots = DistributionPlotsEntry( data=sliced_data, column=column, by=self._boxplot_group) <NEW_LINE> report.add_element(plots) <NEW_LINE> <DEDENT> report.generate()
Calculates statistics on provided data set.
62598ff426238365f5fad43b
class OrderOperationRecord(models.Model): <NEW_LINE> <INDENT> order_sn = models.CharField(max_length=17, verbose_name='订单号', help_text='订单号') <NEW_LINE> status = models.IntegerField(choices=OPERATION_STATUS, default=1, verbose_name='订单状态', help_text='订单状态') <NEW_LINE> operator = models.IntegerField(default=0, verbose_name='操作员', help_text='操作员') <NEW_LINE> execution_detail = models.CharField(blank=True, null=True, max_length=100, verbose_name='执行明细', help_text='执行明细') <NEW_LINE> progress = models.CharField(blank=True, null=True, max_length=30, verbose_name='当前进度', help_text='当前进度') <NEW_LINE> time_consuming = models.FloatField(blank=True, null=True, verbose_name='耗时', help_text='耗时', default=0.0) <NEW_LINE> is_abnormal = models.BooleanField(default=False, verbose_name='是否异常', help_text='是否异常') <NEW_LINE> add_time = models.DateTimeField(default=timezone.now, verbose_name='添加时间') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '订单操作' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.order_sn
订单状态操作记录表
62598ff4627d3e7fe0e0777f
class WorkflowResult(AttributeClass): <NEW_LINE> <INDENT> workflow_id = Attribute( docstring="The id of the workflow associated with this result.", type_hint=str, ) <NEW_LINE> value = Attribute( docstring="The estimated value of the property and the uncertainty " "in that value.", type_hint=unit.Measurement, optional=True, ) <NEW_LINE> gradients = Attribute( docstring="The gradients of the estimated value with respect to the " "specified force field parameters.", type_hint=list, default_value=[], ) <NEW_LINE> exceptions = Attribute( docstring="Any exceptions raised by the layer while estimating the " "property.", type_hint=list, default_value=[], ) <NEW_LINE> data_to_store = Attribute( docstring="Paths to the data objects to store.", type_hint=list, default_value=[], ) <NEW_LINE> def validate(self, attribute_type=None): <NEW_LINE> <INDENT> super(WorkflowResult, self).validate(attribute_type) <NEW_LINE> assert all(isinstance(x, ParameterGradient) for x in self.gradients) <NEW_LINE> assert all(isinstance(x, tuple) for x in self.data_to_store) <NEW_LINE> assert all(len(x) == 2 for x in self.data_to_store) <NEW_LINE> assert all(all(isinstance(y, str) for y in x) for x in self.data_to_store) <NEW_LINE> assert all(isinstance(x, EvaluatorException) for x in self.exceptions)
The result of executing a `Workflow` as part of a `WorkflowGraph`.
62598ff4091ae356687054f8
@method_decorator(admin_login_required, name='dispatch') <NEW_LINE> class AdminDeleteClient(generics.DestroyAPIView): <NEW_LINE> <INDENT> serializer_class = ClientListSerializer <NEW_LINE> model = ClientModel <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.query_params = None <NEW_LINE> self.return_response = Response(["HTTP 400 BAD REQUEST", "Must provide a valid query"], status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def destroy(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.query_params = request.query_params.dict() <NEW_LINE> self.queryset = self.model.objects.get(**self.query_params) <NEW_LINE> self.perform_destroy(self.queryset) <NEW_LINE> self.return_response = Response(status=status.HTTP_204_NO_CONTENT) <NEW_LINE> <DEDENT> except exceptions.ObjectDoesNotExist as e: <NEW_LINE> <INDENT> self.return_response = Response( ["HTTP 400 BAD REQUEST", "{}".format("Object Not Found")]) <NEW_LINE> <DEDENT> return self.return_response
Admin view for Deleting a single client
62598ff426238365f5fad443
class Spider(Firefox): <NEW_LINE> <INDENT> def __init__(self, name, home_page): <NEW_LINE> <INDENT> super(Spider, self).__init__(name, home_page) <NEW_LINE> <DEDENT> def parse_page(self): <NEW_LINE> <INDENT> news_ele = self.driver.find_element_by_id('news') <NEW_LINE> news_ele = news_ele.find_elements_by_class_name('Q-tpList') <NEW_LINE> item_list = [] <NEW_LINE> for x in news_ele: <NEW_LINE> <INDENT> title_ele = x.find_element_by_tag_name('h3') <NEW_LINE> title_ele = title_ele.find_element_by_tag_name('a') <NEW_LINE> title = title_ele.text <NEW_LINE> if not title or title in self.items_dict: continue <NEW_LINE> self.logger.info(title) <NEW_LINE> url = title_ele.get_attribute("href") <NEW_LINE> item_data = self.item.copy() <NEW_LINE> item_data['title'] = title <NEW_LINE> item_data['url'] = url <NEW_LINE> item_list.append(item_data) <NEW_LINE> <DEDENT> for x in item_list: <NEW_LINE> <INDENT> self.get_page(x['url']) <NEW_LINE> x['catalog'], x['source'], x['datetime'], x['content'] = self.parse_detail_page() <NEW_LINE> <DEDENT> for x in item_list: <NEW_LINE> <INDENT> self.save_item(x) <NEW_LINE> <DEDENT> <DEDENT> def parse_detail_page(self): <NEW_LINE> <INDENT> info_ele = self.driver.find_element_by_class_name('a_Info') <NEW_LINE> catalog_ele = info_ele.find_element_by_xpath('span[@class="a_catalog"]/a') <NEW_LINE> try: <NEW_LINE> <INDENT> source_ele = info_ele.find_element_by_xpath('span[@class="a_source"]/a') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> source_ele = info_ele.find_element_by_xpath('span[@class="a_source"]') <NEW_LINE> <DEDENT> time_ele = info_ele.find_element_by_xpath('span[@class="a_time"]') <NEW_LINE> content_ele = self.driver.find_element_by_id('Cnt-Main-Article-QQ') <NEW_LINE> content_ele = content_ele.find_elements_by_xpath('p[@class="text"]') <NEW_LINE> content = '' <NEW_LINE> for x in content_ele: <NEW_LINE> <INDENT> if not x.text: continue <NEW_LINE> content += x.text.strip() <NEW_LINE> if len(content) >= 64: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return catalog_ele.text, source_ele.text, time_ele.text, content
docstring for Spider
62598ff43cc13d1c6d466033
class ParsableErrorMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, app): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> <DEDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> state = {} <NEW_LINE> def replacement_start_response(status, headers, exc_info=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> status_code = int(status.split(' ')[0]) <NEW_LINE> state['status_code'] = status_code <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> raise Exception(_( 'ErrorDocumentMiddleware received an invalid ' 'status %s') % status) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (state['status_code'] // 100) not in (2, 3): <NEW_LINE> <INDENT> headers = [(h, v) for (h, v) in headers if h not in ('Content-Length', 'Content-Type')] <NEW_LINE> <DEDENT> state['headers'] = headers <NEW_LINE> return start_response(status, headers, exc_info) <NEW_LINE> <DEDENT> <DEDENT> app_iter = self.app(environ, replacement_start_response) <NEW_LINE> if (state['status_code'] // 100) not in (2, 3): <NEW_LINE> <INDENT> req = webob.Request(environ) <NEW_LINE> if ( req.accept.best_match( ['application/json', 'application/xml']) == 'application/xml' ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> body = [ et.ElementTree.tostring( et.ElementTree.Element( 'error_message', text='\n'.join(app_iter)))] <NEW_LINE> <DEDENT> except et.ElementTree.ParseError as err: <NEW_LINE> <INDENT> LOG.error('Error parsing HTTP response: %s', err) <NEW_LINE> body = ['<error_message>%s' '</error_message>' % state['status_code']] <NEW_LINE> <DEDENT> state['headers'].append(('Content-Type', 'application/xml')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if six.PY3: <NEW_LINE> <INDENT> app_iter = [i.decode('utf-8') for i in app_iter] <NEW_LINE> <DEDENT> body = [jsonutils.dumps( {'error_message': '\n'.join(app_iter)})] <NEW_LINE> if six.PY3: <NEW_LINE> <INDENT> body = [item.encode('utf-8') for item in body] <NEW_LINE> <DEDENT> state['headers'].append(('Content-Type', 'application/json')) <NEW_LINE> <DEDENT> state['headers'].append(('Content-Length', str(len(body[0])))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> body = app_iter <NEW_LINE> <DEDENT> return body
Replace error body with something the client can parse.
62598ff44c3428357761ab8e
class Cell(object): <NEW_LINE> <INDENT> def __init__(self, pos, cell_type, edm_cells, province, town_flag=False): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> if not len(edm_cells) == 6: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.edm_cells = edm_cells <NEW_LINE> if not province: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.province = province <NEW_LINE> self.cell_type = cell_type <NEW_LINE> self.town_flag = town_flag <NEW_LINE> self.soldier = None <NEW_LINE> self.factory = None <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.pos.x, self.pos.y)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.pos == other.pos <NEW_LINE> <DEDENT> def build_soldier(self): <NEW_LINE> <INDENT> if not self.province: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> soldier_to_update = self.soldier <NEW_LINE> if soldier_to_update: <NEW_LINE> <INDENT> if soldier_to_update.level == 6: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> if self.province.supplies > 0: <NEW_LINE> <INDENT> if self.soldier: <NEW_LINE> <INDENT> if self.soldier.level == self.soldier.max_level: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.soldier.upgrade() <NEW_LINE> self.province.supplies -= 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> new_soldier = Soldier(owner=self.province.owner) <NEW_LINE> self.append_soldier(new_soldier) <NEW_LINE> self.province.supplies -= 1 <NEW_LINE> <DEDENT> self.province.update() <NEW_LINE> <DEDENT> <DEDENT> def append_soldier(self, soldier): <NEW_LINE> <INDENT> if not self.soldier: <NEW_LINE> <INDENT> self.soldier = soldier <NEW_LINE> soldier.cur_cell = self <NEW_LINE> <DEDENT> <DEDENT> def destroy_town(self): <NEW_LINE> <INDENT> assert isinstance(self.province.town, Town) <NEW_LINE> if self.town_flag: <NEW_LINE> <INDENT> self.province.town.destroy() <NEW_LINE> <DEDENT> <DEDENT> def build_factory(self): <NEW_LINE> <INDENT> if not self.factory: <NEW_LINE> <INDENT> self.factory = Factory(cell=self) <NEW_LINE> <DEDENT> <DEDENT> def destroy_factory(self): <NEW_LINE> <INDENT> assert isinstance(self.factory, Factory) <NEW_LINE> self.factory.destroy() <NEW_LINE> <DEDENT> def destroy_buildings(self): <NEW_LINE> <INDENT> if self.factory: <NEW_LINE> <INDENT> self.destroy_factory() <NEW_LINE> <DEDENT> <DEDENT> def change_to_province(self, new_province): <NEW_LINE> <INDENT> assert self.province <NEW_LINE> self.province.remove_cell(self) <NEW_LINE> new_province.append_cell(self) <NEW_LINE> assert new_province.province_cells <NEW_LINE> assert new_province.size() > 0 <NEW_LINE> <DEDENT> def get_image_key(self): <NEW_LINE> <INDENT> if self.province: <NEW_LINE> <INDENT> if self.province.is_land is False: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> assert self.province.owner <NEW_LINE> return 'cell_' + str(self.province.owner.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.cell_type: <NEW_LINE> <INDENT> if self.cell_type > 0: <NEW_LINE> <INDENT> return 'cell_' + str(self.cell_type) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None
The map consists of a 2-dimensional array (dict) of cells there is no smaller step on the map than a cell
62598ff426238365f5fad445
class Delete(base.DeleteCommand): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> command_lib.AddNamespaceResourceArg(parser, 'to delete') <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> namespace_ref = args.CONCEPTS.namespace.Parse() <NEW_LINE> namespace_name = namespace_ref.RelativeName() <NEW_LINE> console_io.PromptContinue( message='Namespace {name} will be deleted'.format(name=namespace_name), cancel_on_no=True) <NEW_LINE> namespace = policy_api.Delete(namespace_name) <NEW_LINE> log.DeletedResource(namespace_name) <NEW_LINE> return namespace
Delete a Kubernetes Managed Namespace.
62598ff44c3428357761ab90
class DateRange(object): <NEW_LINE> <INDENT> def __init__(self, start, end): <NEW_LINE> <INDENT> self.start = min(start, end) <NEW_LINE> self.end = max(start, end) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'DateRange({start} to {end})'.format(start=self.start, end=self.end) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.start == other.start and self.end == other.end <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.start < other.start <NEW_LINE> <DEDENT> def contains_date(self, date): <NEW_LINE> <INDENT> return self.start <= date <= self.end <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def date_range_overlap(date_range_1, date_range_2): <NEW_LINE> <INDENT> return max(date_range_1.start, date_range_2.start) <= min(date_range_1.end, date_range_2.end) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def merge_date_ranges(date_ranges): <NEW_LINE> <INDENT> sorted_by_lower_bound = sorted(date_ranges) <NEW_LINE> merged = [] <NEW_LINE> for later_start_date in sorted_by_lower_bound: <NEW_LINE> <INDENT> if not merged: <NEW_LINE> <INDENT> merged.append(later_start_date) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> earlier_start_date = merged[-1] <NEW_LINE> if later_start_date.start <= (earlier_start_date.end + datetime.timedelta(1)): <NEW_LINE> <INDENT> upper_bound = max(earlier_start_date.end, later_start_date.end) <NEW_LINE> merged[-1] = DateRange(earlier_start_date.start, upper_bound) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> merged.append(later_start_date) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return merged
DateRange object. Taking start, end as input.
62598ff4091ae35668705502
class FancyTriMesh(LUTBase): <NEW_LINE> <INDENT> scalar_visibility = Bool(False, desc='show scalar visibility') <NEW_LINE> color = vtk_color_trait((0.5, 1.0, 0.5)) <NEW_LINE> tube_radius = Float(0.0, desc='radius of the tubes') <NEW_LINE> sphere_radius = Float(0.0, desc='radius of the spheres') <NEW_LINE> tube_filter = Instance(tvtk.TubeFilter, (), {'vary_radius':'vary_radius_off', 'number_of_sides':6}) <NEW_LINE> sphere_source = Instance(tvtk.SphereSource, (), {'theta_resolution':12, 'phi_resolution':12}) <NEW_LINE> def __init__(self, triangles, points, scalars=None, **traits): <NEW_LINE> <INDENT> super(FancyTriMesh, self).__init__(**traits) <NEW_LINE> self.points = points <NEW_LINE> self.pd = make_triangle_polydata(triangles, points, scalars) <NEW_LINE> self._tube_radius_changed(self.tube_radius) <NEW_LINE> self._sphere_radius_changed(self.sphere_radius) <NEW_LINE> scalar_vis = self.scalar_visibility <NEW_LINE> self.extract_filter = tvtk.ExtractEdges(input=self.pd) <NEW_LINE> extract_f = self.extract_filter <NEW_LINE> self.tube_filter.trait_set(input=extract_f.output, radius=self.tube_radius) <NEW_LINE> edge_mapper = tvtk.PolyDataMapper(input=self.tube_filter.output, lookup_table=self.lut, scalar_visibility=scalar_vis) <NEW_LINE> edge_actor = _make_actor(mapper=edge_mapper) <NEW_LINE> edge_actor.property.color = self.color <NEW_LINE> self.sphere_source.radius = self.sphere_radius <NEW_LINE> spheres = tvtk.Glyph3D(scaling=0, source=self.sphere_source.output, input=extract_f.output) <NEW_LINE> sphere_mapper = tvtk.PolyDataMapper(input=spheres.output, lookup_table=self.lut, scalar_visibility=scalar_vis) <NEW_LINE> sphere_actor = _make_actor(mapper=sphere_mapper) <NEW_LINE> sphere_actor.property.color = self.color <NEW_LINE> if scalars is not None: <NEW_LINE> <INDENT> rs = numpy.ravel(scalars) <NEW_LINE> dr = min(rs), max(rs) <NEW_LINE> self.lut.table_range = dr <NEW_LINE> edge_mapper.scalar_range = dr <NEW_LINE> sphere_mapper.scalar_range = dr <NEW_LINE> <DEDENT> self.actors.extend([edge_actor, sphere_actor]) <NEW_LINE> <DEDENT> def _scalar_visibility_changed(self, val): <NEW_LINE> <INDENT> if self.actors: <NEW_LINE> <INDENT> for i in self.actors: <NEW_LINE> <INDENT> i.mapper.scalar_visibility = val <NEW_LINE> <DEDENT> <DEDENT> self.render() <NEW_LINE> <DEDENT> def _tube_radius_changed(self, val): <NEW_LINE> <INDENT> points = self.points <NEW_LINE> if val < 1.0e-9: <NEW_LINE> <INDENT> val = (max(numpy.ravel(points)) - min(numpy.ravel(points)))/250.0 <NEW_LINE> <DEDENT> self.tube_radius = val <NEW_LINE> self.tube_filter.radius = val <NEW_LINE> self.render() <NEW_LINE> <DEDENT> def _sphere_radius_changed(self, val): <NEW_LINE> <INDENT> points = self.points <NEW_LINE> if val < 1.0e-9: <NEW_LINE> <INDENT> val = (max(numpy.ravel(points)) - min(numpy.ravel(points)))/100.0 <NEW_LINE> <DEDENT> self.sphere_radius = val <NEW_LINE> self.sphere_source.radius = val <NEW_LINE> self.render() <NEW_LINE> <DEDENT> def _color_changed(self, val): <NEW_LINE> <INDENT> if self.actors: <NEW_LINE> <INDENT> self.actors[0].property.color = val <NEW_LINE> <DEDENT> self.render()
Shows a mesh of triangles and draws the edges as tubes and points as balls.
62598ff4c4546d3d9def76fa
class AcousticGuitarFractionFeature(InstrumentFractionFeature): <NEW_LINE> <INDENT> id = 'I12' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> super().__init__(dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Acoustic Guitar Fraction' <NEW_LINE> self.description = ('Fraction of all Note Ons belonging to acoustic guitar patches ' '(General MIDI patches 25 and 26).') <NEW_LINE> self.isSequential = True <NEW_LINE> self.dimensions = 1 <NEW_LINE> self._targetPrograms = [24, 25]
A feature extractor that extracts the fraction of all Note Ons belonging to acoustic guitar patches (General MIDI patches 25 and 26). >>> s1 = stream.Stream() >>> s1.append(instrument.AcousticGuitar()) >>> s1.repeatAppend(note.Note(), 3) >>> s1.append(instrument.Tuba()) >>> s1.append(note.Note()) >>> fe = features.jSymbolic.AcousticGuitarFractionFeature(s1) >>> fe.extract().vector [0.75]
62598ff4091ae35668705504
class Antecedente(BaseModel): <NEW_LINE> <INDENT> patologicos = models.TextField(u'Patológicos', blank=True) <NEW_LINE> quirurgicos = models.TextField(u'Quirúrgicos', blank=True) <NEW_LINE> traumaticos = models.TextField(u'Traumáticos', blank=True) <NEW_LINE> alergicos = models.TextField(u'Alérgicos', blank=True) <NEW_LINE> heredo_familiar = models.TextField(u'Heredo familiar', blank=True) <NEW_LINE> habitos_fisiologicos = models.TextField(u'Hábitos fisiológicos', blank=True) <NEW_LINE> habitos_patologicos = models.TextField(u'Hábitos patológicos', blank=True) <NEW_LINE> medicaciones = models.TextField(u'Medicaciones', blank=True) <NEW_LINE> estudios_complementarios = models.TextField(u'Estudios complementarios', blank=True) <NEW_LINE> menarca = models.DateField(u'MENARCA', null=True) <NEW_LINE> fum = models.DateField(u'FUM', null=True) <NEW_LINE> tipo_partos = models.TextField(u'Tipo de partos', blank=True) <NEW_LINE> observaciones = models.TextField(u'Observaciones', blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"Antecedentes de {}".format( self.paciente.persona) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = u"antecedente" <NEW_LINE> verbose_name_plural = u"antecedentes"
Representa la historia médica del paciente. Contiene datos médicos y relevantes sobre el paciente.
62598ff4187af65679d2a06c
class JoinRideSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> passenger = serializers.IntegerField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Ride <NEW_LINE> fields = ('passenger',) <NEW_LINE> <DEDENT> def validate_passenger(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(pk=data) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> raise serializers.ValidationERror('Invalid passenger') <NEW_LINE> <DEDENT> circle = self.context['circle'] <NEW_LINE> try: <NEW_LINE> <INDENT> membership = Membership.objects.get( user=user, circle=circle, is_active=True ) <NEW_LINE> <DEDENT> except Membership.DoesNotExists: <NEW_LINE> <INDENT> raise serializers.ValidationError('User is not active member of the circle') <NEW_LINE> <DEDENT> self.context['user'] = user <NEW_LINE> self.context['member'] = membership <NEW_LINE> return data <NEW_LINE> <DEDENT> def validate(self, data): <NEW_LINE> <INDENT> ride = self.context['ride'] <NEW_LINE> if ride.departure_date <= timezone.now(): <NEW_LINE> <INDENT> raise serializers.ValidationError("You can't join this ride now") <NEW_LINE> <DEDENT> if ride.available_seats < 1: <NEW_LINE> <INDENT> raise serializers.ValidationError('Ride is already full') <NEW_LINE> <DEDENT> if Ride.objects.filter(passengers__pk=data['passenger']): <NEW_LINE> <INDENT> raise serializers.ValidationError('Passenger is already in this trip') <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def update(self, instace, data): <NEW_LINE> <INDENT> ride = self.context['ride'] <NEW_LINE> user = self.context['user'] <NEW_LINE> ride.passengers.add(user) <NEW_LINE> profile = user.profile <NEW_LINE> profile.rides_taken += 1 <NEW_LINE> profile.save() <NEW_LINE> member = self.context['member'] <NEW_LINE> member.rides_taken += 1 <NEW_LINE> member.save() <NEW_LINE> circle = self.context['circle'] <NEW_LINE> circle.rides_taken += 1 <NEW_LINE> circle.save() <NEW_LINE> return ride
Join ride serializer
62598ff4c4546d3d9def76fc
class Base64JsonField(models.TextField): <NEW_LINE> <INDENT> __metaclass__ = models.SubfieldBase <NEW_LINE> def get_prep_value(self, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> return 'base64:' + base64.encodestring(json.dumps(value)) <NEW_LINE> <DEDENT> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if value is not None and isinstance(value, basestring): <NEW_LINE> <INDENT> value = str(value) <NEW_LINE> if value.startswith('base64:'): <NEW_LINE> <INDENT> value = value.split(':')[1] <NEW_LINE> prepared_data = json.loads(base64.decodestring(value)) <NEW_LINE> return json.loads(prepared_data) <NEW_LINE> <DEDENT> <DEDENT> elif value is not None and isinstance(value, dict): <NEW_LINE> <INDENT> value = json.dumps(value) <NEW_LINE> return value <NEW_LINE> <DEDENT> return value
Base64JsonField is a custom field intended to store a JSON data in a Base64 format to a text column in relational databases. Stored data are first serialized into a JSON string representation and then encoded into a Base64 format. When retrieving this data, same logic is applied in a reverse order.
62598ff4187af65679d2a06e
class TriggerTimeSeriesDataPlot(TimeSeriesDataPlot): <NEW_LINE> <INDENT> type = 'trigger-timeseries' <NEW_LINE> data = 'triggers' <NEW_LINE> def process(self): <NEW_LINE> <INDENT> (plot, axes) = self.init_plot() <NEW_LINE> ax = axes[0] <NEW_LINE> labels = self.pargs.pop('labels', self.channels) <NEW_LINE> if isinstance(labels, (unicode, str)): <NEW_LINE> <INDENT> labels = labels.split(',') <NEW_LINE> <DEDENT> labels = map(lambda s: str(s).strip('\n '), labels) <NEW_LINE> for label, channel in zip(labels, self.channels): <NEW_LINE> <INDENT> label = label.replace('_', r'\_') <NEW_LINE> if self.state and not self.all_data: <NEW_LINE> <INDENT> valid = self.state.active <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> valid = SegmentList([self.span]) <NEW_LINE> <DEDENT> data = get_timeseries(channel, valid, query=False) <NEW_LINE> if not len(data): <NEW_LINE> <INDENT> ax.plot([0], [0], visible=False, label=label) <NEW_LINE> continue <NEW_LINE> <DEDENT> color = None <NEW_LINE> for ts in data: <NEW_LINE> <INDENT> if self.pargs['logy']: <NEW_LINE> <INDENT> ts.value[ts.value == 0] = 1e-100 <NEW_LINE> <DEDENT> if color is None: <NEW_LINE> <INDENT> line = ax.plot_timeseries(ts, label=label)[0] <NEW_LINE> color = line.get_color() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax.plot_timeseries(ts, color=color, label=None) <NEW_LINE> <DEDENT> <DEDENT> if hasattr(data[0].channel, 'amplitude_range'): <NEW_LINE> <INDENT> self.pargs.setdefault('ylim', data[0].channel.amplitude_range) <NEW_LINE> <DEDENT> <DEDENT> for yval in self.pargs['hline']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yval = float(yval) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax.plot([self.start, self.end], [yval, yval], linestyle='--', color='red') <NEW_LINE> <DEDENT> <DEDENT> legendargs = self.parse_legend_kwargs() <NEW_LINE> for key, val in self.pargs.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(ax, 'set_%s' % key)(val) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> setattr(ax, key, val) <NEW_LINE> <DEDENT> <DEDENT> if len(self.channels) > 1: <NEW_LINE> <INDENT> plot.add_legend(ax=ax, **legendargs) <NEW_LINE> <DEDENT> if not plot.colorbars: <NEW_LINE> <INDENT> plot.add_colorbar(ax=ax, visible=False) <NEW_LINE> <DEDENT> if self.state: <NEW_LINE> <INDENT> self.add_state_segments(ax) <NEW_LINE> <DEDENT> return self.finalize()
Custom time-series plot to handle discontiguous `TimeSeries`.
62598ff43cc13d1c6d46603d
@config(compat="linux", cat="manage", tags=["hide", "rootkit", "stealth"]) <NEW_LINE> class HideProcessModule(PupyModule): <NEW_LINE> <INDENT> dependencies=["pupystealth"] <NEW_LINE> def init_argparse(self): <NEW_LINE> <INDENT> self.arg_parser = PupyArgumentParser(prog="hide_process", description=self.__doc__) <NEW_LINE> self.arg_parser.add_argument('--argv', default="/bin/bash", help='change the new process argv') <NEW_LINE> <DEDENT> def run(self, args): <NEW_LINE> <INDENT> self.client.conn.modules['pupystealth.change_argv'].change_argv(argv=args.argv) <NEW_LINE> self.success("process argv and env changed !")
Edit current process argv & env not to look suspicious
62598ff44c3428357761ab98
class Module: <NEW_LINE> <INDENT> def __init__(self, name: str, owner = None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self._owner = owner <NEW_LINE> self.ports: Dict[str, Port] = {} <NEW_LINE> self.gates: Dict[str, Gate] = {} <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}{}('{}')".format(ownerPrefix(self._owner), self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def _addPort(self, name: str): <NEW_LINE> <INDENT> if name in self.ports: <NEW_LINE> <INDENT> raise ValueError("A port indexed by '{}' already exists.".format(name)) <NEW_LINE> <DEDENT> port = Port(name, owner=self) <NEW_LINE> self.ports[name] = port <NEW_LINE> self.gates[name + "In"] = port.input <NEW_LINE> self.gates[name + "Out"] = port.output <NEW_LINE> <DEDENT> def _addGate(self, name: str): <NEW_LINE> <INDENT> if name in self.gates: <NEW_LINE> <INDENT> raise ValueError("A gate indexed by '{}' already exists.".format(name)) <NEW_LINE> <DEDENT> self.gates[name] = Gate(name, owner=self)
Modules are used to model components that interact with each other, as for example network stack layers. A module has a number of ports and gates that can be used to exchange data with it and connect it to other modules. Modules provide the methods :meth:`_addPort` and :meth:`_addGate` that allow to add ports and gates, which can be accessed via the :attr:`ports` and the :attr:`gates` dictionaries. Note: Modules may have both ports (for bidirectional connections) and individual gates (for unidirectional connections). When a port is added by :meth:`_addPort`, its two gates are also added to the :attr:`gates` dictionary. Attributes: name(str): The Module's name ports(Dict[str, Port]): The Module's outer Ports gates(Dict[str, Gate]): The Module's outer Gates .. automethod:: _addPort .. automethod:: _addGate
62598ff4ad47b63b2c5a8140
class ClonesRecombModel(Target): <NEW_LINE> <INDENT> def __init__(self, infile, outfile): <NEW_LINE> <INDENT> Target.__init__(self) <NEW_LINE> self.infile = infile <NEW_LINE> self.outfile = outfile <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> clones = pickle.load(gzip.open(self.infile, 'rb')) <NEW_LINE> recomb_model = get_recomb_stats(clones) <NEW_LINE> pickle.dump(recomb_model, gzip.open(self.outfile, 'wb'))
Get the recomb_model related counts for a subset of clones Return a "RecomModel" obj picked to outfile
62598ff43cc13d1c6d46603f
class IntegrationTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> cleanTestDir() <NEW_LINE> self.dirac = Dirac() <NEW_LINE> gLogger.setLevel("DEBUG") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass
Base class for the integration and regression tests
62598ff4c4546d3d9def76ff
class DeleteContact(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Google/Contacts/DeleteContact') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return DeleteContactInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return DeleteContactResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return DeleteContactChoreographyExecution(session, exec_id, path)
Create a new instance of the DeleteContact Choreography. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
62598ff4627d3e7fe0e07795
class ActiveCache(object): <NEW_LINE> <INDENT> __cached_value__ = None <NEW_LINE> __initialised__ = False <NEW_LINE> def __init__(self, start_immediate=False): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> self.notify_queues = [] <NEW_LINE> if start_immediate: <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> <DEDENT> def start(self, notify_queue=None): <NEW_LINE> <INDENT> if not self.initialised: <NEW_LINE> <INDENT> logger.debug("Active Cache initialising") <NEW_LINE> if notify_queue: <NEW_LINE> <INDENT> self.notify_queues.append(notify_queue) <NEW_LINE> <DEDENT> <DEDENT> if not self.running: <NEW_LINE> <INDENT> logger.debug("Active cache set to RUNNING") <NEW_LINE> self.running = True <NEW_LINE> trigger_thread = threading.Thread(target=self.__monitor) <NEW_LINE> trigger_thread.setDaemon(True) <NEW_LINE> trigger_thread.start() <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> logger.debug("Active cache STOPPING") <NEW_LINE> self.run = False <NEW_LINE> <DEDENT> def __monitor(self): <NEW_LINE> <INDENT> while self.running: <NEW_LINE> <INDENT> self.refresh_cache() <NEW_LINE> if not self.initialised: <NEW_LINE> <INDENT> self.initialised = True <NEW_LINE> while self.notify_queues: <NEW_LINE> <INDENT> self.notify_queues.pop().put(0) <NEW_LINE> <DEDENT> <DEDENT> self.trigger() <NEW_LINE> <DEDENT> <DEDENT> def _set_value(self, x): <NEW_LINE> <INDENT> self.__cached_value__ = x <NEW_LINE> <DEDENT> def _get_value(self): <NEW_LINE> <INDENT> if not self.initialised: <NEW_LINE> <INDENT> q = Queue() <NEW_LINE> self.start(q) <NEW_LINE> q.get() <NEW_LINE> <DEDENT> return self.__cached_value__ <NEW_LINE> <DEDENT> value = property(_get_value, _set_value) <NEW_LINE> def _set_initialised(self, b): <NEW_LINE> <INDENT> self.__initialised__ = b <NEW_LINE> <DEDENT> def _get_initialised(self): <NEW_LINE> <INDENT> return self.__initialised__ <NEW_LINE> <DEDENT> initialised = property(_get_initialised, _set_initialised)
Abstract class (requires an implementation of `refresh_cache`) that caches the result of `refresh_cache` and actively refreshes it whenever a trigger occurs (as managed by the implementation of `trigger`). The regeneration happens off thread and when complete the cache reference is updated. Thus there is never a block whilst a referesh happens. The trigger to refresh comes from a call to the blocking method `trigger` returning. This is called from a dedicated thread. It is important for thread safety that code using the cached object understands the reference can change at any time, so it should be bound to a name in the local namespace and then used, rather than referenced multiple times from the cahce in one routine. To make concrete, subclass and implement: * refresh_cache(self) * trigger(self)
62598ff4187af65679d2a072
class OpensStreetMapService(MapService): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> MapService.__init__(self) <NEW_LINE> <DEDENT> def calc_url(self): <NEW_LINE> <INDENT> place = self._get_first_place()[0] <NEW_LINE> latitude, longitude = self._lat_lon(place) <NEW_LINE> if longitude and latitude: <NEW_LINE> <INDENT> self.url = "http://www.openstreetmap.org/" "?lat=%s&lon=%s&zoom=15" % (latitude, longitude) <NEW_LINE> return <NEW_LINE> <DEDENT> location = get_main_location(self.database, place) <NEW_LINE> city = location.get(PlaceType.CITY) <NEW_LINE> country = location.get(PlaceType.COUNTRY) <NEW_LINE> if city and country: <NEW_LINE> <INDENT> self.url = "http://nominatim.openstreetmap.org/" "search.php?q=%s%%2C%s" % (city, country) <NEW_LINE> return <NEW_LINE> <DEDENT> titledescr = place_displayer.display(self.database, place) <NEW_LINE> self.url = "http://nominatim.openstreetmap.org/" "search.php?q=%s" % '+'.join(titledescr.split())
Map service using http://openstreetmap.org Resource: http://wiki.openstreetmap.org/wiki/Nominatim
62598ff4ad47b63b2c5a8147
class DBForm(object): <NEW_LINE> <INDENT> def fetch_data(self, req): <NEW_LINE> <INDENT> data = req.GET.mixed() <NEW_LINE> filter = dict((col.name, data.get(col.name)) for col in sa.orm.class_mapper(self.entity).primary_key) <NEW_LINE> self.value = req.GET and self.entity.query.filter_by(**filter).first() or None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def insert_or_update(cls, data): <NEW_LINE> <INDENT> sautil.update_or_create(cls.entity, data)
Base mixin class for DB related form widgets Provides helper methods for fetching and storing data to a model
62598ff4627d3e7fe0e07799
class World(object): <NEW_LINE> <INDENT> def add_foodspot(self, foodspot): <NEW_LINE> <INDENT> self.foodspots.add((foodspot.x, foodspot.y)) <NEW_LINE> <DEDENT> def remove_foodspot(self, foodspot): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.foodspots.remove((foodspot.x,foodspot.y)) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def reset_foodspots(self): <NEW_LINE> <INDENT> global STEP <NEW_LINE> self.foodspots = set() <NEW_LINE> [self.foodspots.add((x,y)) for x in range(0,600,STEP) for y in range(0,480,STEP) if not (x >= 240 and x <= 300 and y == 210)] <NEW_LINE> <DEDENT> def addfood(self): <NEW_LINE> <INDENT> global STEP <NEW_LINE> X = 0 <NEW_LINE> coordinate = random.sample(self.foodspots, 1) <NEW_LINE> self.foodspot = pygame.Rect(coordinate[X], (STEP, STEP)) <NEW_LINE> screen.blit("food", self.foodspot) <NEW_LINE> <DEDENT> def foodhit(self, head): <NEW_LINE> <INDENT> return self.foodspot.colliderect(head) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> global WORLDRECT <NEW_LINE> screen.erase(WORLDRECT) <NEW_LINE> <DEDENT> def introtext(self): <NEW_LINE> <INDENT> screen.blit("introtext_line1", pygame.Rect(115, 190, 400, 300)) <NEW_LINE> screen.blit("introtext_line2", pygame.Rect(115, 230, 400, 300)) <NEW_LINE> <DEDENT> def add_to_world(self, obj, rect): <NEW_LINE> <INDENT> screen.blit(obj, rect) <NEW_LINE> <DEDENT> def remove_from_world(self, rect): <NEW_LINE> <INDENT> screen.erase(rect)
Objekt för spelplan Objektet har koll på ytor på spelplanen som är tillgängliga att lägga ut mat på. Objektet ser även till att lägga ut äpplet på spelplanen samt sparar äpplets koordinat. Koordinaten sparas för att kunna kontrollera när ormens huvud kolliderar med äpplet. Objektet är superklass till Namedialog som anropar dess metoder add_to_world och erase_from_world.
62598ff526238365f5fad45d
class DimMapping(object): <NEW_LINE> <INDENT> def __init__(self, dimension, regex='(.*)', separator=None): <NEW_LINE> <INDENT> self.dimension = dimension <NEW_LINE> self.regex = regex <NEW_LINE> self.separator = separator <NEW_LINE> self.cregex = re.compile(regex) if regex != '(.*)' else None <NEW_LINE> <DEDENT> def map_value(self, source_value): <NEW_LINE> <INDENT> if self.cregex: <NEW_LINE> <INDENT> match_groups = self.cregex.match(source_value) <NEW_LINE> if match_groups: <NEW_LINE> <INDENT> return DynamicCheckHelper._normalize_dim_value( self.separator.join(match_groups.groups())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return DynamicCheckHelper._normalize_dim_value(source_value)
Describes how to transform dictionary like metadata attached to a metric into Monasca dimensions
62598ff5091ae35668705519
class oaiharvest_production_sync(oaiharvest_harvest_repositories): <NEW_LINE> <INDENT> object_type = "workflow" <NEW_LINE> record_workflow = "oaiharvest_production_sync_record" <NEW_LINE> workflow = [ write_something_generic("Initialization", [task_update_progress, write_message]), init_harvesting, write_something_generic("Starting", [task_update_progress, write_message]), foreach(get_repositories_list(), "repository"), [ write_something_generic("Harvesting", [task_update_progress, write_message]), harvest_records, write_something_generic("Reading Files", [task_update_progress, write_message]), foreach(get_obj_extra_data_key("harvested_files_list")), [ write_something_generic("Creating Workflows", [task_update_progress, write_message]), workflow_if(num_workflow_running_greater(10), neg=True), [ start_async_workflow("oaiharvest_production_sync_record", preserve_data=True, preserve_extra_data_keys=["repository"]), write_something_generic( ["Workflow started: ", get_nb_workflow_created], [task_update_progress, write_message]), ], workflow_else, [ write_something_generic( ["Max simultaneous workflows reached: ", "Waiting for one to finish"], [task_update_progress, write_message]), wait_for_a_workflow_to_complete(0.05), start_async_workflow("oaiharvest_production_sync_record", preserve_data=True, preserve_extra_data_keys=["repository"]), write_something_generic(["Workflow started :", get_nb_workflow_created, " "], [task_update_progress, write_message]), ], ], end_for ], end_for, write_something_generic(["Processing : ", get_nb_workflow_created, " records"], [task_update_progress, write_message]), simple_for(0, get_nb_workflow_created, 1), [ wait_for_a_workflow_to_complete(), write_something_generic([get_workflows_progress, " % Complete"], [task_update_progress, write_message]), ], end_for, write_something_generic("Finishing", [task_update_progress, write_message]), workflows_reviews(stop_if_error=True), update_last_update(get_repositories_list()) ]
Main workflow for harvesting arXiv via OAI-PMH (oaiharvester).
62598ff53cc13d1c6d46604f
class ID_ (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = pyxb.binding.datatypes.ID <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_SIMPLE <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'ID') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 364, 2) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __id = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'id'), 'id', '__httpschemas_xmlsoap_orgsoapencoding_ID__id', pyxb.binding.datatypes.ID) <NEW_LINE> __id._DeclarationLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 62, 4) <NEW_LINE> __id._UseLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 62, 4) <NEW_LINE> id = property(__id.value, __id.set, None, None) <NEW_LINE> __href = pyxb.binding.content.AttributeUse(pyxb.namespace.ExpandedName(None, 'href'), 'href', '__httpschemas_xmlsoap_orgsoapencoding_ID__href', pyxb.binding.datatypes.anyURI) <NEW_LINE> __href._DeclarationLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 63, 4) <NEW_LINE> __href._UseLocation = pyxb.utils.utility.Location('/tmp/pyxbdist.mqXn05k/PyXB-1.2.4/pyxb/bundles/wssplat/schemas/soapenc.xsd', 63, 4) <NEW_LINE> href = property(__href.value, __href.set, None, None) <NEW_LINE> _AttributeWildcard = pyxb.binding.content.Wildcard(process_contents=pyxb.binding.content.Wildcard.PC_lax, namespace_constraint=(pyxb.binding.content.Wildcard.NC_not, 'http://schemas.xmlsoap.org/soap/encoding/')) <NEW_LINE> _ElementMap.update({ }) <NEW_LINE> _AttributeMap.update({ __id.name() : __id, __href.name() : __href })
Complex type {http://schemas.xmlsoap.org/soap/encoding/}ID with content type SIMPLE
62598ff5c4546d3d9def7706
class MacOSXTTSPlugin(plugin.TTSPlugin): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> plugin.TTSPlugin.__init__(self, *args, **kwargs) <NEW_LINE> self._logger = logging.getLogger(__name__) <NEW_LINE> self._logger.warning("This TTS plugin doesn't have multilanguage " + "support!") <NEW_LINE> <DEDENT> def say(self, phrase): <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f: <NEW_LINE> <INDENT> fname = f.name <NEW_LINE> <DEDENT> cmd = [EXECUTABLE, '-o', fname, '--file-format=WAVE', str(phrase)] <NEW_LINE> self._logger.debug('Executing %s', ' '.join([pipes.quote(arg) for arg in cmd])) <NEW_LINE> with tempfile.SpooledTemporaryFile() as f: <NEW_LINE> <INDENT> subprocess.call(cmd, stdout=f, stderr=f) <NEW_LINE> f.seek(0) <NEW_LINE> output = f.read() <NEW_LINE> if output: <NEW_LINE> <INDENT> self._logger.debug("Output was: '%s'", output) <NEW_LINE> <DEDENT> <DEDENT> with open(fname, 'rb') as f: <NEW_LINE> <INDENT> data = f.read() <NEW_LINE> <DEDENT> os.remove(fname) <NEW_LINE> return data
Uses the OS X built-in 'say' command
62598ff5c4546d3d9def7707
class ServerSettings(BaseSettings): <NEW_LINE> <INDENT> def _add_console_arguments(self): <NEW_LINE> <INDENT> super(ServerSettings, self)._add_console_arguments() <NEW_LINE> self._parser.add_argument( '--style', default='Nematus', help='API style; see `README.md` (default: Nematus)') <NEW_LINE> self._parser.add_argument( '--host', default='0.0.0.0', help='host address (default: %(default)s)') <NEW_LINE> self._parser.add_argument( '--port', type=int, default=8080, metavar='INT', help='host port (default: %(default)s)') <NEW_LINE> self._parser.add_argument( '--threads', type=int, default=4, metavar='INT', help='number of threads (default: %(default)s)') <NEW_LINE> self._parser.add_argument( '-p', '--num_processes', type=int, default=1, metavar='INT', help="number of processes (default: %(default)s)")
Console interface for server mode Most parameters required in default mode are provided with each translation request to the server (see `nematus/server/request.py`).
62598ff5627d3e7fe0e077a9
class VIEW3D_OT_imperial_measurement(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.imperial_measure" <NEW_LINE> bl_label = "Imperial Measurement" <NEW_LINE> bl_options = { 'REGISTER', 'UNDO' } <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> bpy.context.scene.unit_settings.system = 'IMPERIAL' <NEW_LINE> return {'FINISHED'}
Sets World Units to Imperial to input Inches and Feet
62598ff5c4546d3d9def7709
class EventMapper(object): <NEW_LINE> <INDENT> event_mapper = {"CUSTOMER": (Customers, CustomersMapper, CustomerData), "SITE_VISIT": (SiteVisits, SiteVisitMapper, SiteVisitDataStore), "ORDER": (Orders, OrderMapper,OrderData), "IMAGE": (ImageUpload, ImageMapper, ImageData)} <NEW_LINE> def __init__(self, logger=None): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.t = 10 <NEW_LINE> <DEDENT> def Ingest(self, e, D): <NEW_LINE> <INDENT> event_name = e["type"] <NEW_LINE> if self.logger: <NEW_LINE> <INDENT> self.logger.info(e) <NEW_LINE> self.logger.debug(event_name) <NEW_LINE> <DEDENT> if(event_name in self.event_mapper): <NEW_LINE> <INDENT> mapper_object = self.event_mapper[event_name][1] <NEW_LINE> val = mapper_object.map_to_model(e, self.event_mapper[event_name][0]() ) <NEW_LINE> data_store = self.event_mapper[event_name][2] <NEW_LINE> data_store.add_data(val, D) <NEW_LINE> <DEDENT> <DEDENT> def TopXSimpleLTVCustomers(self, x, D): <NEW_LINE> <INDENT> top_valued_customers = list() <NEW_LINE> customer_data = self.event_mapper["CUSTOMER"][2].get_data(D) <NEW_LINE> order_data = self.event_mapper["ORDER"][2].get_data(D) <NEW_LINE> site_visit_data = self.event_mapper["SITE_VISIT"][2].get_data(D) <NEW_LINE> ltv_customer = [] <NEW_LINE> date_utils = DateUtil() <NEW_LINE> weeks = date_utils.get_weeks(D.max_date, D.min_date) <NEW_LINE> if weeks < 52 : <NEW_LINE> <INDENT> weeks = 52 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> weeks = int(weeks) <NEW_LINE> <DEDENT> for customer_id in customer_data.keys(): <NEW_LINE> <INDENT> if customer_id in order_data and customer_id in site_visit_data: <NEW_LINE> <INDENT> total_amount = order_data[customer_id]["total_amount"] <NEW_LINE> total_visit = site_visit_data[customer_id]["site_visit"] <NEW_LINE> customer_expenditures_per_visit = float(total_amount) / float(total_visit) <NEW_LINE> number_of_site_visits_per_week = float(total_visit)/float(weeks) <NEW_LINE> a = customer_expenditures_per_visit * number_of_site_visits_per_week <NEW_LINE> ltv = 52 * a * self.t <NEW_LINE> if self.logger: <NEW_LINE> <INDENT> self.logger.info("ltv value: " + str(ltv) + " customer id: " + customer_id) <NEW_LINE> <DEDENT> heapq.heappush(ltv_customer, (ltv, customer_id)) <NEW_LINE> <DEDENT> <DEDENT> customers = heapq.nlargest(x, ltv_customer) <NEW_LINE> for customer in customers: <NEW_LINE> <INDENT> top_valued_customers.append(customer[1]) <NEW_LINE> <DEDENT> return top_valued_customers
Class creates in-memory data structure and evaluates top x valued customers using simple ltv
62598ff53cc13d1c6d466058
class TwitterListener(StreamListener): <NEW_LINE> <INDENT> def __init__(self, fetched_tweets_filename): <NEW_LINE> <INDENT> self.fetched_tweets_filename = fetched_tweets_filename <NEW_LINE> <DEDENT> def on_data(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print(data) <NEW_LINE> with open(self.fetched_tweets_filename, 'a') as tf: <NEW_LINE> <INDENT> tf.write(data) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> print( "error on_data %s" % str(e)) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> def on_error(self, status_code): <NEW_LINE> <INDENT> if status_code == 420: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> print(status_code)
" A basic listener class that fetches the data from the API
62598ff5627d3e7fe0e077ab
class TransportProtocolAdapter(TransportAdapter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TransportProtocolAdapter, self).__init__() <NEW_LINE> protocol_scenarios = [ ('HTTP/1.0', dict(_protocol_version='HTTP/1.0')), ('HTTP/1.1', dict(_protocol_version='HTTP/1.1')), ] <NEW_LINE> self.scenarios = tests.multiply_scenarios(self.scenarios, protocol_scenarios)
Generate the same test for each protocol implementation. In addition to the transport adaptatation that we inherit from.
62598ff5c4546d3d9def770a
class FastaFile(object): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self._fasta_file = None <NEW_LINE> try: <NEW_LINE> <INDENT> with g2g_utils.silence(filter_fai, sys.stderr): <NEW_LINE> <INDENT> self._fasta_file = pysam.FastaFile(self.filename) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self._fasta_file = pysam.FastaFile(self.filename) <NEW_LINE> <DEDENT> self.fai = FAI(self.filename) <NEW_LINE> self.haploid = False <NEW_LINE> self.diploid = False <NEW_LINE> for record in self.fai.records: <NEW_LINE> <INDENT> if record.endswith(('_L', '_R')): <NEW_LINE> <INDENT> self.diploid = True <NEW_LINE> self.haploid = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not self.diploid: <NEW_LINE> <INDENT> self.haploid = True <NEW_LINE> <DEDENT> <DEDENT> def is_diploid(self): <NEW_LINE> <INDENT> return self.diploid <NEW_LINE> <DEDENT> def is_haploid(self): <NEW_LINE> <INDENT> return self.haploid <NEW_LINE> <DEDENT> def fetch_list(self, reference=None, start=None, end=None, region=None): <NEW_LINE> <INDENT> _start = 0 if start < 0 else start <NEW_LINE> return list(self._fasta_file.fetch(reference=reference, start=_start, end=end, region=region)) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self._fasta_file, name)
Encapsulate a Fasta file Delegation used with `pysam.FastaFile`
62598ff515fb5d323ce7f650
class ModelValidator(object): <NEW_LINE> <INDENT> def __init__(self, validator, my_latest_bet, latest_bets, target_estimate): <NEW_LINE> <INDENT> self.model_of = validator <NEW_LINE> self.weight = validator.weight <NEW_LINE> self.my_latest_bet = my_latest_bet <NEW_LINE> self.target_estimate = target_estimate <NEW_LINE> self.latest_observed_bets = latest_bets <NEW_LINE> <DEDENT> def my_estimate(self): <NEW_LINE> <INDENT> return model_utils.get_estimate_from_latest_messages(self.latest_observed_bets, self.target_estimate) <NEW_LINE> <DEDENT> def show(self, bet): <NEW_LINE> <INDENT> assert isinstance(bet, ModelBet), "expected a bet!" <NEW_LINE> assert bet.estimate == self.target_estimate, "should only show bets on the target_estimate!" <NEW_LINE> self.latest_observed_bets[bet.sender] = bet <NEW_LINE> <DEDENT> def make_new_latest_bet(self): <NEW_LINE> <INDENT> if self.my_latest_bet.estimate == self.target_estimate: <NEW_LINE> <INDENT> return True, self.my_latest_bet <NEW_LINE> <DEDENT> if self.my_estimate() == self.target_estimate: <NEW_LINE> <INDENT> self.my_latest_bet = ModelBet(self.target_estimate, self.model_of) <NEW_LINE> return True, self.my_latest_bet <NEW_LINE> <DEDENT> return False, None
Simulates a model validator.
62598ff5ad47b63b2c5a8160
class AisleTurnEnv(PlanEnv): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> path, costmap = path_and_costmap_from_config(config) <NEW_LINE> super(AisleTurnEnv, self).__init__(costmap, path, config.env_params) <NEW_LINE> <DEDENT> def get_robot(self): <NEW_LINE> <INDENT> return self._robot
Robotic Planning Environment in which the task is to turn right into an aisle based on provided config (of type AisleTurnEnvParams), that specifies the geometry of the turn.
62598ff54c3428357761abbd
class User: <NEW_LINE> <INDENT> def __init__(self, username, password): <NEW_LINE> <INDENT> self.username=username <NEW_LINE> self.password=password
used to create an object containing username and password
62598ff515fb5d323ce7f657
class TestWriteFile(object): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.r1 = remote.Remote('r1', ssh=Mock()) <NEW_LINE> self.c = cluster.Cluster( remotes=[ (self.r1, ['foo', 'bar']), ], ) <NEW_LINE> <DEDENT> @patch("teuthology.orchestra.remote.RemoteShell.write_file") <NEW_LINE> def test_write_file(self, m_write_file): <NEW_LINE> <INDENT> self.c.write_file("filename", "content") <NEW_LINE> m_write_file.assert_called_with("filename", "content") <NEW_LINE> <DEDENT> @patch("teuthology.orchestra.remote.RemoteShell.write_file") <NEW_LINE> def test_fails_with_invalid_perms(self, m_write_file): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.c.write_file("filename", "content", sudo=False, perms="invalid") <NEW_LINE> <DEDENT> <DEDENT> @patch("teuthology.orchestra.remote.RemoteShell.write_file") <NEW_LINE> def test_fails_with_invalid_owner(self, m_write_file): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.c.write_file("filename", "content", sudo=False, owner="invalid") <NEW_LINE> <DEDENT> <DEDENT> @patch("teuthology.orchestra.remote.RemoteShell.write_file") <NEW_LINE> def test_with_sudo(self, m_write_file): <NEW_LINE> <INDENT> self.c.write_file("filename", "content", sudo=True) <NEW_LINE> m_write_file.assert_called_with("filename", "content", sudo=True, owner=None, mode=None)
Tests for cluster.write_file
62598ff5187af65679d2a082
class USAddress(models.Model): <NEW_LINE> <INDENT> address_lines = JSONField(default=empty_list) <NEW_LINE> street = models.CharField(max_length=128, null=True) <NEW_LINE> city = models.CharField(max_length=64, null=True) <NEW_LINE> state = USPostalCodeField(null=True) <NEW_LINE> zip_code = models.CharField(max_length=10, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True
An abstract representation of a United States Address.
62598ff5627d3e7fe0e077b9
class DeleteReferenceImageRequest(proto.Message): <NEW_LINE> <INDENT> name = proto.Field(proto.STRING, number=1,)
Request message for the ``DeleteReferenceImage`` method. Attributes: name (str): Required. The resource name of the reference image to delete. Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``
62598ff63cc13d1c6d466068
class TestListingElectricalaudioB5(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.board_id = 6 <NEW_LINE> self.posts_per_page = 20 <NEW_LINE> self.html_path = os.path.join('tests', 'electricalaudio.f5.htm') <NEW_LINE> with open(self.html_path, 'r') as f: <NEW_LINE> <INDENT> self.page_html = f.read() <NEW_LINE> <DEDENT> self.topics = parsers.parse_threads_listing_page( html=self.page_html, board_id=self.board_id, posts_per_page=self.posts_per_page ) <NEW_LINE> return <NEW_LINE> <DEDENT> def test_number_of_threads_found(self): <NEW_LINE> <INDENT> self.assertEqual(len(self.topics), 51) <NEW_LINE> <DEDENT> def test_locked_detection(self): <NEW_LINE> <INDENT> self.assertEqual(self.topics[0]['locked'], False) <NEW_LINE> self.assertEqual(self.topics[1]['locked'], False) <NEW_LINE> self.assertEqual(self.topics[2]['locked'], False) <NEW_LINE> self.assertEqual(self.topics[3]['locked'], False) <NEW_LINE> self.assertEqual(self.topics[4]['locked'], False) <NEW_LINE> self.assertEqual(self.topics[25]['locked'], False) <NEW_LINE> self.assertEqual(self.topics[50]['locked'], False) <NEW_LINE> return <NEW_LINE> <DEDENT> def test_announcement_detection(self): <NEW_LINE> <INDENT> self.assertEqual(self.topics[0]['thread_type'], 'announce') <NEW_LINE> self.assertEqual(self.topics[1]['thread_type'], 'sticky') <NEW_LINE> self.assertEqual(self.topics[2]['thread_type'], 'sticky') <NEW_LINE> self.assertEqual(self.topics[3]['thread_type'], 'sticky') <NEW_LINE> self.assertEqual(self.topics[4]['thread_type'], 'normal') <NEW_LINE> self.assertEqual(self.topics[5]['thread_type'], 'normal') <NEW_LINE> self.assertEqual(self.topics[25]['thread_type'], 'normal') <NEW_LINE> self.assertEqual(self.topics[50]['thread_type'], 'normal') <NEW_LINE> return <NEW_LINE> <DEDENT> def test_topic_id_detection(self): <NEW_LINE> <INDENT> self.assertEqual(self.topics[0]['topic_id'], 63483) <NEW_LINE> self.assertEqual(self.topics[1]['topic_id'], 491) <NEW_LINE> self.assertEqual(self.topics[2]['topic_id'], 55031) <NEW_LINE> self.assertEqual(self.topics[3]['topic_id'], 34722) <NEW_LINE> self.assertEqual(self.topics[4]['topic_id'], 51141) <NEW_LINE> self.assertEqual(self.topics[50]['topic_id'], 67172) <NEW_LINE> return
phpBB v3 http://www.electricalaudio.com/phpBB3/viewforum.php?f=5 Normal viewforum page
62598ff6ad47b63b2c5a816a
class IReadWriteTestsMixin: <NEW_LINE> <INDENT> def getFileReader(self, content): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def getFileWriter(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def getFileContent(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def test_read(self): <NEW_LINE> <INDENT> content = b'wobble\n' <NEW_LINE> consumer = TestConsumer() <NEW_LINE> def cbGet(reader): <NEW_LINE> <INDENT> return reader.send(consumer).addCallback(cbSend) <NEW_LINE> <DEDENT> def cbSend(res): <NEW_LINE> <INDENT> self.assertEqual(b"".join(consumer.buffer), content) <NEW_LINE> <DEDENT> return self.getFileReader(content).addCallback(cbGet) <NEW_LINE> <DEDENT> def test_write(self): <NEW_LINE> <INDENT> content = b'elbbow\n' <NEW_LINE> def cbGet(writer): <NEW_LINE> <INDENT> return writer.receive().addCallback(cbReceive, writer) <NEW_LINE> <DEDENT> def cbReceive(consumer, writer): <NEW_LINE> <INDENT> producer = TestProducer(content, consumer) <NEW_LINE> consumer.registerProducer(None, True) <NEW_LINE> producer.start() <NEW_LINE> consumer.unregisterProducer() <NEW_LINE> return writer.close().addCallback(cbClose) <NEW_LINE> <DEDENT> def cbClose(ignored): <NEW_LINE> <INDENT> self.assertEqual(self.getFileContent(), content) <NEW_LINE> <DEDENT> return self.getFileWriter().addCallback(cbGet)
Generic tests for the C{IReadFile} and C{IWriteFile} interfaces.
62598ff64c3428357761abc6
class OrgHomeView(View): <NEW_LINE> <INDENT> def get(self, request, org_id): <NEW_LINE> <INDENT> current_page = "home" <NEW_LINE> courses_org = CourseOrg.objects.get(id=int(org_id)) <NEW_LINE> has_fav = False <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if UserFavorite.objects.filter(user=request.user, fav_id=courses_org.id, fav_type=2): <NEW_LINE> <INDENT> has_fav = True <NEW_LINE> <DEDENT> <DEDENT> all_courses = courses_org.course_set.all()[:2] <NEW_LINE> all_teacher = courses_org.teacher_set.all()[:2] <NEW_LINE> return render(request, 'org-detail-homepage.html', { 'all_courses': all_courses, 'all_teacher': all_teacher, 'courses_org': courses_org, 'current_page': current_page, 'has_fav': has_fav })
机构首页
62598ff64c3428357761abc8
class componentSettings(MayaQWidgetDockableMixin, guide.componentMainSettings): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> self.toolName = TYPE <NEW_LINE> pyqt.deleteInstances(self, MayaQDockWidget) <NEW_LINE> super(self.__class__, self).__init__(parent=parent) <NEW_LINE> self.setup_componentSettingWindow() <NEW_LINE> self.create_componentControls() <NEW_LINE> self.populate_componentControls() <NEW_LINE> self.create_componentLayout() <NEW_LINE> self.create_componentConnections() <NEW_LINE> <DEDENT> def setup_componentSettingWindow(self): <NEW_LINE> <INDENT> self.mayaMainWindow = pyqt.maya_main_window() <NEW_LINE> self.setObjectName(self.toolName) <NEW_LINE> self.setWindowFlags(QtCore.Qt.Window) <NEW_LINE> self.setWindowTitle(TYPE) <NEW_LINE> self.resize(280, 350) <NEW_LINE> <DEDENT> def create_componentControls(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def populate_componentControls(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def create_componentLayout(self): <NEW_LINE> <INDENT> self.settings_layout = QtWidgets.QVBoxLayout() <NEW_LINE> self.settings_layout.addWidget(self.tabs) <NEW_LINE> self.settings_layout.addWidget(self.close_button) <NEW_LINE> self.setLayout(self.settings_layout) <NEW_LINE> <DEDENT> def create_componentConnections(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def dockCloseEventTriggered(self): <NEW_LINE> <INDENT> pyqt.deleteInstances(self, MayaQDockWidget)
Create the component setting window
62598ff6c4546d3d9def7715
class translate(_edit_command): <NEW_LINE> <INDENT> def __init__(self, language): <NEW_LINE> <INDENT> if language not in ly.pitch.pitchInfo: <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> self.language = language <NEW_LINE> <DEDENT> def edit(self, opts, cursor): <NEW_LINE> <INDENT> import ly.pitch.translate <NEW_LINE> try: <NEW_LINE> <INDENT> changed = ly.pitch.translate.translate(cursor, self.language, opts.default_language) <NEW_LINE> <DEDENT> except ly.pitch.PitchNameNotAvailable as pna: <NEW_LINE> <INDENT> raise ValueError(format(pna)) <NEW_LINE> <DEDENT> if not changed: <NEW_LINE> <INDENT> version = ly.docinfo.DocInfo(cursor.document).version() <NEW_LINE> ly.pitch.translate.insert_language(cursor.document, self.language, version)
translate pitch names
62598ff615fb5d323ce7f661
class DynamicAllowedContentFTI(FactoryTypeInformation): <NEW_LINE> <INDENT> meta_type = "DynamicAllowedContentFTI for InnerContentContainer" <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> security.declarePublic('allowType') <NEW_LINE> def allowType(self, contentType): <NEW_LINE> <INDENT> atool = getToolByName(self, 'archetype_tool') <NEW_LINE> types = [ti for ti in atool.listRegisteredTypes() if ti['portal_type'] == contentType] <NEW_LINE> return len(types) > 0 and atool.typeImplementsInterfaces(types[0], (IBaseInnerContent,))
Allow content to be added if it implements BaseInnercontentProxy
62598ff6091ae3566870553a
class VariableItem(Item): <NEW_LINE> <INDENT> __slots__ = ('_name', '_getitem_func') <NEW_LINE> def __init__(self, name, getitem_func=operator.getitem): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._getitem_func = getitem_func <NEW_LINE> <DEDENT> def evaluate(self, ns): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ns[self._name] <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> raise _EvaluationError("Can't find variable '{}'".format(self._name)) from e <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._name.upper()
A named variable that's accessed in the namespace. If a getitem_func is given, it is called when this item is accessed using the item syntax ``[n]``, with this item as first argument, and then the specified index.
62598ff64c3428357761abca
class UserState: <NEW_LINE> <INDENT> __slots__ = [ 'user', 'level', 'points', 'actual_coins', 'potential_coins', 'achievements', 'last_changed' ] <NEW_LINE> def __init__(self, user: User, level: int, points: Decimal, actual_coins: Decimal, potential_coins: Decimal, achievements: list, last_changed: datetime) -> None: <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.level = level <NEW_LINE> self.points = points <NEW_LINE> self.actual_coins = actual_coins <NEW_LINE> self.potential_coins = potential_coins <NEW_LINE> self.achievements = {a.id: a for a in achievements} <NEW_LINE> self.last_changed = last_changed <NEW_LINE> self._validate() <NEW_LINE> <DEDENT> def _validate(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert self.user is not None, 'User must be present.' <NEW_LINE> assert self.level >= 0, 'Level value must be zero or greater.' <NEW_LINE> assert self.points >= Decimal(0), 'Points value must be zero or greater.' <NEW_LINE> assert self.actual_coins >= Decimal(0), 'Actual coins value must be zero or greater.' <NEW_LINE> assert self.potential_coins >= Decimal(0), 'Potential coins value must be zero or greater.' <NEW_LINE> assert isinstance(self.achievements, dict), 'Achievements value must be a dict' <NEW_LINE> assert isinstance(self.last_changed, datetime), 'Last changed value must be a datetime' <NEW_LINE> <DEDENT> except AssertionError as e: <NEW_LINE> <INDENT> raise InvalidUserStateException(e) <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self) -> dict: <NEW_LINE> <INDENT> return { 'user': self.user.username, 'level': self.level, 'points': self.points, 'actual_coins': self.actual_coins, 'potential_coins': self.potential_coins, 'achievements': [r.to_dict() for r in self.achievements.values()], 'last_changed': self.last_changed.strftime("%d.%m.%Y %H:%M:%S") } <NEW_LINE> <DEDENT> def __eq__(self, o: object) -> bool: <NEW_LINE> <INDENT> if isinstance(o, UserState): <NEW_LINE> <INDENT> return o.user.id == self.user.id and o.level == self.level and o.points == self.points and o.actual_coins == self.actual_coins and o.potential_coins == self.potential_coins and (set(o.achievements.keys()) == set(self.achievements.keys())) and o.last_changed == self.last_changed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, o: object) -> bool: <NEW_LINE> <INDENT> return not self == o <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return 'UserState({user}, {level}, {points}, {act_coins}, ' '{pot_coins}, {badges}, {changed})' .format(user=self.user.id, level=self.level, points=self.points, act_coins=self.actual_coins, pot_coins=self.potential_coins, badges=self.achievements.keys(), changed=self.last_changed) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return str(self)
An aggregation of all the stuff user has gotten working on projects so far.
62598ff6627d3e7fe0e077c5
class IsOwnerOrAdmin(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.user.is_staff: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return obj.username == request.user.username
Custom permission to only allow owners of an object to edit. Admin users however have access to all.
62598ff64c3428357761abce
class SerializerTestCase(TestCase): <NEW_LINE> <INDENT> def test_create_method(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Serializer tests - Only testing the create method because everything else is inherited from DRF
62598ff6187af65679d2a08a
class SetForest(object): <NEW_LINE> <INDENT> def __init__(self, items): <NEW_LINE> <INDENT> self.nodes = {item: SetForestNode(item) for item in items} <NEW_LINE> <DEDENT> def find(self, item): <NEW_LINE> <INDENT> node = self.nodes[item] <NEW_LINE> if node.data is not node.parent: <NEW_LINE> <INDENT> node.parent = self.nodes[self.find(node.parent)].data <NEW_LINE> <DEDENT> return node.parent <NEW_LINE> <DEDENT> def union(self, node_a, node_b): <NEW_LINE> <INDENT> root_a = self.nodes[self.find(node_a)] <NEW_LINE> root_b = self.nodes[self.find(node_b)] <NEW_LINE> root_b.parent = root_a.data
Implementation of a Disjoint Set Forest to use the Union-Find algorithms.
62598ff6ad47b63b2c5a8176
class XMLReader(): <NEW_LINE> <INDENT> def __init__(self, xml): <NEW_LINE> <INDENT> self.ns_tei = {'tei': "http://www.tei-c.org/ns/1.0"} <NEW_LINE> self.ns_xml = {'xml': "http://www.w3.org/XML/1998/namespace"} <NEW_LINE> self.ns_tcf = {'tcf': "http://www.dspin.de/data/textcorpus"} <NEW_LINE> self.nsmap = { 'tei': "http://www.tei-c.org/ns/1.0", 'xml': "http://www.w3.org/XML/1998/namespace", 'tcf': "http://www.dspin.de/data/textcorpus" } <NEW_LINE> self.file = xml <NEW_LINE> try: <NEW_LINE> <INDENT> self.original = ET.parse(self.file) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.original = ET.fromstring(self.file.encode('utf8')) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> r = requests.get(self.file) <NEW_LINE> self.original = ET.fromstring(r.text) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> self.tree = ET.parse(self.file) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.tree = ET.fromstring(self.file.encode('utf8')) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> r = requests.get(self.file) <NEW_LINE> self.tree = ET.fromstring(r.text) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.parsed_file = "parsing didn't work" <NEW_LINE> <DEDENT> <DEDENT> def return_byte_like_object(self): <NEW_LINE> <INDENT> return ET.tostring(self.tree, encoding="utf-8") <NEW_LINE> <DEDENT> def return_string(self): <NEW_LINE> <INDENT> return self.return_byte_like_object().decode('utf-8') <NEW_LINE> <DEDENT> def tree_to_file(self, file=None): <NEW_LINE> <INDENT> if file: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H-%M-%S') <NEW_LINE> file = "{}.xml".format(timestamp) <NEW_LINE> <DEDENT> with open(file, 'wb') as f: <NEW_LINE> <INDENT> f.write(ET.tostring(self.tree)) <NEW_LINE> <DEDENT> return file
a class to read an process tei-documents
62598ff615fb5d323ce7f667
class TestMonetaryFormat(TestOdootilCommon): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(TestMonetaryFormat, cls).setUpClass() <NEW_LINE> cls.currency = cls.env.ref('base.EUR') <NEW_LINE> cls.language = cls.env.ref('base.lang_en') <NEW_LINE> cls.get_monetary_format = cls.Odootil.get_monetary_format <NEW_LINE> cls.env.ref('base.lang_lt').active = True <NEW_LINE> <DEDENT> def test_01_monetary_format(self): <NEW_LINE> <INDENT> self.assertEqual( self.get_monetary_format(self.currency, 1000.0), '1,000.00') <NEW_LINE> self.currency.rounding = 0.1 <NEW_LINE> self.assertEqual( self.get_monetary_format(self.currency, 1000.05), '1,000.1') <NEW_LINE> self.currency.rounding = 0.001 <NEW_LINE> self.assertEqual( self.get_monetary_format(self.currency, 1000.00045), '1,000.000') <NEW_LINE> self.currency.rounding = 0.0001 <NEW_LINE> self.assertEqual( self.get_monetary_format(self.currency, 1000.00005), '1,000.0001') <NEW_LINE> self.assertEqual(self.get_monetary_format( self.currency, 10000.0, use_symbol=True), '10,000.0000 €') <NEW_LINE> self.currency.position = 'before' <NEW_LINE> self.assertEqual(self.get_monetary_format( self.currency, 10000.0, use_symbol=True), '€ 10,000.0000') <NEW_LINE> <DEDENT> def test_02_monetary_format(self): <NEW_LINE> <INDENT> self.assertEqual( self.get_monetary_format(self.currency, 1000.0), '1,000.00') <NEW_LINE> self.language.thousands_sep = '@' <NEW_LINE> self.assertEqual( self.get_monetary_format(self.currency, 1000.0), '1@000.00') <NEW_LINE> self.language.decimal_point = ',' <NEW_LINE> self.assertEqual( self.get_monetary_format(self.currency, 1000.0), '1@000,00') <NEW_LINE> self.language.grouping = '[4,0]' <NEW_LINE> self.assertEqual( self.get_monetary_format(self.currency, 10000.0), '1@0000,00') <NEW_LINE> self.assertEqual(self.get_monetary_format( self.currency, 10000.0, lang_code='lt_LT'), '10.000,00')
Class to test monetary formating.
62598ff626238365f5fad489
class TestDocumentAssignmentResponse(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 DocumentAssignmentResponse( id = 46530 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return DocumentAssignmentResponse( ) <NEW_LINE> <DEDENT> <DEDENT> def testDocumentAssignmentResponse(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)
DocumentAssignmentResponse unit test stubs
62598ff63cc13d1c6d46607a
class NagiosPlugins(object): <NEW_LINE> <INDENT> def __init__(self, config_file): <NEW_LINE> <INDENT> self.plugins = configurator.read(config_file, configspec='configspecs/nagios_plugins.cfg', list_values=False) <NEW_LINE> <DEDENT> def launch_plugin(self): <NEW_LINE> <INDENT> for plugin in self.plugins: <NEW_LINE> <INDENT> command = [os.path.join(self.plugins[plugin]['path'], plugin)] <NEW_LINE> for option_cmd in self.plugins[plugin]: <NEW_LINE> <INDENT> if option_cmd not in ['path']: <NEW_LINE> <INDENT> command.append('--%s=%s' % (option_cmd, self.plugins[plugin][option_cmd], )) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> nagios_plugin = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> logging.error("[nagios_plugins]: '%s' executable is missing", command[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return_value = nagios_plugin.communicate()[0].strip() <NEW_LINE> return_code = nagios_plugin.returncode <NEW_LINE> logging.log(STATUSES[return_code][1], "[nagios_plugins][%s] (%s status): %s", os.path.basename(command[0]), STATUSES[return_code][0], return_value) <NEW_LINE> yield {'return_code': int(return_code), 'return_value': str(return_value), 'time_stamp': int(time.time()), 'service_description': plugin}
Class to handle each nagios-plugin
62598ff615fb5d323ce7f66d
class Package(setup_boilerplate.Package): <NEW_LINE> <INDENT> name = 'benchmarker' <NEW_LINE> description = 'performance benchamrking framework' <NEW_LINE> url = "https://benchmarker.blackbird.pw/" <NEW_LINE> classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Scientific/Engineering'] <NEW_LINE> keywords = ['performance', 'benchmarking', 'neural network']
Package metadata.
62598ff6c4546d3d9def771c
class BalancedGradientBoostingClassifier(BaseBalancedClassifier): <NEW_LINE> <INDENT> def __init__(self, loss='deviance', learning_rate=0.1, n_estimators=100, subsample=1.0, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_depth=3, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, hybrid_model=False, ensemble_scheme='avg'): <NEW_LINE> <INDENT> super().__init__(hybrid_model=hybrid_model, ensemble_scheme=ensemble_scheme) <NEW_LINE> self.n_estimators = n_estimators <NEW_LINE> self.learning_rate = learning_rate <NEW_LINE> self.loss = loss <NEW_LINE> self.min_samples_split = min_samples_split <NEW_LINE> self.min_samples_leaf = min_samples_leaf <NEW_LINE> self.min_weight_fraction_leaf = min_weight_fraction_leaf <NEW_LINE> self.subsample = subsample <NEW_LINE> self.max_features = max_features <NEW_LINE> self.max_depth = max_depth <NEW_LINE> self.init = init <NEW_LINE> self.random_state = random_state <NEW_LINE> self.verbose = verbose <NEW_LINE> self.max_leaf_nodes = max_leaf_nodes <NEW_LINE> <DEDENT> def _create_estimator(self): <NEW_LINE> <INDENT> return GradientBoostingClassifier(loss=self.loss, learning_rate=self.learning_rate, n_estimators=self.n_estimators, min_samples_split=self.min_samples_split, min_samples_leaf=self.min_samples_leaf, min_weight_fraction_leaf=self.min_weight_fraction_leaf, max_depth=self.max_depth, init=self.init, subsample=self.subsample, max_features=self.max_features, random_state=self.random_state, verbose=self.verbose, max_leaf_nodes=self.max_leaf_nodes)
Ensemble of gradient boosting classifiers trained on data where ratio of classes is close to 50%. Multiple datasets are created such that samples of one class appear roughly as often as samples of the other class in each dataset. A gradient boosting classifier is trained on each balanced dataset. Parameters ---------- hybrid_model : bool, optional To include unbalanced model scores in balanced ensemble scores. ensemble_scheme : {'avg' | 'majority_voting'} How to combine probability estimates from ensemble classifiers. If `avg` prediction probabilities from base classifiers are averaged.
62598ff615fb5d323ce7f66f
@widgets.register <NEW_LINE> class TimeSeriesViewer(widgets.DOMWidget): <NEW_LINE> <INDENT> _view_name = Unicode('TimeSeriesView').tag(sync=True) <NEW_LINE> _model_name = Unicode('TimeSeriesModel').tag(sync=True) <NEW_LINE> _view_module = Unicode('tfma_widget_js').tag(sync=True) <NEW_LINE> _model_module = Unicode('tfma_widget_js').tag(sync=True) <NEW_LINE> _view_module_version = Unicode('^0.1.0').tag(sync=True) <NEW_LINE> _model_module_version = Unicode('^0.1.0').tag(sync=True) <NEW_LINE> data = List([]).tag(sync=True) <NEW_LINE> config = Dict(dict()).tag(sync=True)
The time series visualization widget.
62598ff63cc13d1c6d466080
class StateHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def initialize(self, pipes): <NEW_LINE> <INDENT> self.pipes = pipes <NEW_LINE> <DEDENT> def get(self, pid, service_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pipe = self.pipes.repository[pid] <NEW_LINE> state = None <NEW_LINE> services = pipe.services <NEW_LINE> for service in services: <NEW_LINE> <INDENT> name = str(service.__class__.__name__) <NEW_LINE> if name.lower() == service_name.lower(): <NEW_LINE> <INDENT> state = { name: service.get_state() } <NEW_LINE> <DEDENT> <DEDENT> if state is None: <NEW_LINE> <INDENT> msg = "Service '{}' not found in pipe '{}'".format(service_name, pid) <NEW_LINE> self.set_status(404, msg) <NEW_LINE> self.finish() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_status(200) <NEW_LINE> self.set_header("Content-Type", "application/json; charset=UTF-8") <NEW_LINE> self.finish(json.dumps(state, default=default_repr)) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.set_status(404, "Pipe not found") <NEW_LINE> self.finish()
API handler to get back pipe states
62598ff60a366e3fb87dd328
class RiskFire(Risk): <NEW_LINE> <INDENT> risk_type = RiskType.FIRE <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.start_date = '2015-01-01' <NEW_LINE> self.end_date = '2018-01-01' <NEW_LINE> self.dataset_name = 'FIRMS' <NEW_LINE> self.dataset_band_name = 'T21' <NEW_LINE> self.range_min = 300 <NEW_LINE> self.range_max = 510 <NEW_LINE> ee.Initialize() <NEW_LINE> self.image_collection = ee.ImageCollection(self.dataset_name). filter(ee.Filter.date(self.start_date, self.end_date)). select(self.dataset_band_name) <NEW_LINE> <DEDENT> def get_risk_score(self, lon, lat, radius): <NEW_LINE> <INDENT> self.nparray = image_coll_to_np_array(self.image_collection, lon, lat, radius) <NEW_LINE> self.nparray = map_linearly_from(self.nparray, self.range_min, self.range_max) <NEW_LINE> return np.mean(self.nparray)
Fire risk
62598ff6c4546d3d9def7720
class RandomStrategy(Strategy): <NEW_LINE> <INDENT> def insert(self, pnode, token, per_salience_list): <NEW_LINE> <INDENT> rand_index = random.randrange(0, len(per_salience_list)) <NEW_LINE> per_salience_list.insert(rand_index, (pnode, token)) <NEW_LINE> <DEDENT> def resort(self, per_saliance_list): <NEW_LINE> <INDENT> random.shuffle(per_saliance_list)
Inserisce gli elementi in ordine casuale di attivazione per gli elementi con lo stesso salience
62598ff64c3428357761abe0
class DQN_Ensemble(BaseBstrapDQN): <NEW_LINE> <INDENT> def _act_train(self, agent_net, name): <NEW_LINE> <INDENT> action = self._act_eval_vote(agent_net, name) <NEW_LINE> self.plot_conf.set_train_spec(dict(eval_actions=self.plot_conf.true_eval_spec["eval_actions"])) <NEW_LINE> return dict(action=action) <NEW_LINE> <DEDENT> def _act_eval(self, agent_net, name): <NEW_LINE> <INDENT> return dict(action=tf.identity(self.train_dict["action"], name=name))
Ensemble policy from Boostrapped DQN
62598ff63cc13d1c6d466086
class Param(object): <NEW_LINE> <INDENT> def __init__(self, variable, default=None, name=None, mutable=False, strict=False, allow_downcast=None, implicit=None, borrow=None): <NEW_LINE> <INDENT> self.variable = variable <NEW_LINE> self.default = default <NEW_LINE> self.name = name <NEW_LINE> self.mutable = mutable <NEW_LINE> if borrow is None: <NEW_LINE> <INDENT> self.borrow = self.mutable <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.borrow = borrow <NEW_LINE> <DEDENT> if self.mutable and not self.borrow: <NEW_LINE> <INDENT> raise AssertionError( "Symbolic input for variable %s (name=%s) has " "flags mutable=True, borrow=False. This combination is " "incompatible since mutable=True implies that the " "input variable may be both aliased (borrow=True) and " "overwritten.", variable, name) <NEW_LINE> <DEDENT> self.strict = strict <NEW_LINE> self.allow_downcast = allow_downcast <NEW_LINE> self.implicit = implicit
Parameters ---------- variable A variable in an expression graph to use as a compiled-function parameter. default The default value to use at call-time (can also be a Container where the function will find a value at call-time). name : str A string to identify this parameter from function kwargs. mutable : bool True : function is allowed to modify this argument. borrow Whether the function is allowed to alias some output to this input. Using None (default) means we re-use the same value as the `mutable` flag. False: do not permit any output to be aliased to the input. strict : bool False : function arguments may be copied or cast to match the type required by the parameter `variable`. True : function arguments must exactly match the type required by `variable`. allow_downcast : bool or None Only applies if `strict` is False. True : allow assigned value to lose precision when cast during assignment. False : never allow precision loss. None : only allow downcasting of a Python float to a scalar floatX. implicit See help(theano.io.In)
62598ff6091ae35668705552
class LeafNode(Node): <NEW_LINE> <INDENT> def __init__(self, vector, dimension, depth,right_child=None,left_child=None,ID = None): <NEW_LINE> <INDENT> super(LeafNode, self).__init__(dimension, depth,right_child,left_child,ID) <NEW_LINE> self.vector = vector
This is a class that encodes a node within a kd-tree. Will have a right and left neighbor, which are also nodes. The node object also keeps track of which dimension data structure it is in.
62598ff6c4546d3d9def7722
class Label(PygameWidget): <NEW_LINE> <INDENT> def __init__(self, text, font="Times New Roman", size=36, bold=False, color=(10, 10, 10)): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.font = pygame.font.SysFont(font, size) <NEW_LINE> self.color = color <NEW_LINE> self.setBold(bold) <NEW_LINE> <DEDENT> def buildSurface(self): <NEW_LINE> <INDENT> return self.font.render(self.text, 1, self.color) <NEW_LINE> <DEDENT> def setBold(self, bold): <NEW_LINE> <INDENT> self.font.set_bold(bold) <NEW_LINE> <DEDENT> def setText(self, text): <NEW_LINE> <INDENT> self.text = text
Represents a text label displayed via Pygame
62598ff7091ae35668705554
class Literal(Expression): <NEW_LINE> <INDENT> pass
Un valor literal como 2, 2.5, o "dos"
62598ff715fb5d323ce7f67b
class TableParser(BoundedParser): <NEW_LINE> <INDENT> headers = ContainerConfig.table['headers'] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> BoundedParser.__init__(self) <NEW_LINE> self.columns = list() <NEW_LINE> <DEDENT> def parseheader(self, reader): <NEW_LINE> <INDENT> reader.nextline() <NEW_LINE> while self.startswithheader(reader): <NEW_LINE> <INDENT> self.parseparameter(reader) <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> def startswithheader(self, reader): <NEW_LINE> <INDENT> for start in TableParser.headers: <NEW_LINE> <INDENT> if reader.currentline().strip().startswith(start): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Parse the whole table
62598ff726238365f5fad49b
class Conferences(object): <NEW_LINE> <INDENT> openapi_types = { 'copyright': 'str', 'teams': 'list[Conference]' } <NEW_LINE> attribute_map = { 'copyright': 'copyright', 'teams': 'teams' } <NEW_LINE> def __init__(self, copyright=None, teams=None): <NEW_LINE> <INDENT> self._copyright = None <NEW_LINE> self._teams = None <NEW_LINE> self.discriminator = None <NEW_LINE> if copyright is not None: <NEW_LINE> <INDENT> self.copyright = copyright <NEW_LINE> <DEDENT> if teams is not None: <NEW_LINE> <INDENT> self.teams = teams <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def copyright(self): <NEW_LINE> <INDENT> return self._copyright <NEW_LINE> <DEDENT> @copyright.setter <NEW_LINE> def copyright(self, copyright): <NEW_LINE> <INDENT> self._copyright = copyright <NEW_LINE> <DEDENT> @property <NEW_LINE> def teams(self): <NEW_LINE> <INDENT> return self._teams <NEW_LINE> <DEDENT> @teams.setter <NEW_LINE> def teams(self, teams): <NEW_LINE> <INDENT> self._teams = teams <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Conferences): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598ff7091ae35668705558
class ListMemberAppsResult(bb.Struct): <NEW_LINE> <INDENT> __slots__ = [ '_linked_api_apps_value', '_linked_api_apps_present', ] <NEW_LINE> _has_required_fields = True <NEW_LINE> def __init__(self, linked_api_apps=None): <NEW_LINE> <INDENT> self._linked_api_apps_value = None <NEW_LINE> self._linked_api_apps_present = False <NEW_LINE> if linked_api_apps is not None: <NEW_LINE> <INDENT> self.linked_api_apps = linked_api_apps <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def linked_api_apps(self): <NEW_LINE> <INDENT> if self._linked_api_apps_present: <NEW_LINE> <INDENT> return self._linked_api_apps_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("missing required field 'linked_api_apps'") <NEW_LINE> <DEDENT> <DEDENT> @linked_api_apps.setter <NEW_LINE> def linked_api_apps(self, val): <NEW_LINE> <INDENT> val = self._linked_api_apps_validator.validate(val) <NEW_LINE> self._linked_api_apps_value = val <NEW_LINE> self._linked_api_apps_present = True <NEW_LINE> <DEDENT> @linked_api_apps.deleter <NEW_LINE> def linked_api_apps(self): <NEW_LINE> <INDENT> self._linked_api_apps_value = None <NEW_LINE> self._linked_api_apps_present = False <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(ListMemberAppsResult, self)._process_custom_annotations(annotation_type, field_path, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'ListMemberAppsResult(linked_api_apps={!r})'.format( self._linked_api_apps_value, )
:ivar team.ListMemberAppsResult.linked_api_apps: List of third party applications linked by this team member.
62598ff7627d3e7fe0e077e1
class ProjectListBox(npyscreen.BoxTitle): <NEW_LINE> <INDENT> _contained_widget = ProjectList
Box holding the ProjectList.
62598ff7091ae3566870555a
class ProductionConfig(BaseConfig): <NEW_LINE> <INDENT> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> LOG_FORMAT = "json"
Production configuration
62598ff7c4546d3d9def7726
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> nParticles = self.numParticles <NEW_LINE> positions = self.legalPositions <NEW_LINE> self.particles=[] <NEW_LINE> weight=1 <NEW_LINE> for i in range(0,self.numParticles): <NEW_LINE> <INDENT> j = i%len(positions) <NEW_LINE> self.particles.append([positions[j], weight]) <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> jail = self.getJailPosition(); <NEW_LINE> if (noisyDistance == None): <NEW_LINE> <INDENT> for p in self.particles: <NEW_LINE> <INDENT> p[0] = jail <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> allPossible = [] <NEW_LINE> for p in self.particles: <NEW_LINE> <INDENT> trueDistance = util.manhattanDistance(p[0], pacmanPosition) <NEW_LINE> p[1] = p[1] * emissionModel[trueDistance] <NEW_LINE> <DEDENT> """Check Null Weights""" <NEW_LINE> sumWeights=0; <NEW_LINE> for p in self.particles: <NEW_LINE> <INDENT> sumWeights+=p[1] <NEW_LINE> <DEDENT> if sumWeights == 0: <NEW_LINE> <INDENT> self.initializeUniformly(gameState) <NEW_LINE> return <NEW_LINE> <DEDENT> """Define aggregate weights of locations""" <NEW_LINE> aggregateWeights = util.Counter() <NEW_LINE> for p in self.particles: <NEW_LINE> <INDENT> aggregateWeights[p[0]] += p[1] <NEW_LINE> <DEDENT> """resample on weights""" <NEW_LINE> nParticles = self.numParticles <NEW_LINE> while nParticles > 0: <NEW_LINE> <INDENT> allPossible.append([util.sample(aggregateWeights), 1]) <NEW_LINE> nParticles-=1 <NEW_LINE> <DEDENT> self.particles=allPossible <NEW_LINE> <DEDENT> def elapseTime(self, gameState): <NEW_LINE> <INDENT> beliefs = self.getBeliefDistribution() <NEW_LINE> for particle in self.particles: <NEW_LINE> <INDENT> oldPos=particle[0] <NEW_LINE> newPosDist=self.getPositionDistribution(self.setGhostPosition(gameState, oldPos)) <NEW_LINE> particle[0] = util.sample(newPosDist); <NEW_LINE> <DEDENT> <DEDENT> def getBeliefDistribution(self): <NEW_LINE> <INDENT> beliefs = util.Counter() <NEW_LINE> for particlePosition in self.particles: <NEW_LINE> <INDENT> beliefs[particlePosition[0]] += 1 <NEW_LINE> <DEDENT> beliefs.normalize() <NEW_LINE> return beliefs
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.
62598ff7627d3e7fe0e077e3
class OptionsError(Error): <NEW_LINE> <INDENT> pass
Error with the options framework.
62598ff715fb5d323ce7f683