code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Environment: <NEW_LINE> <INDENT> def __init__(self, polygons): <NEW_LINE> <INDENT> self.polygons = polygons <NEW_LINE> min_x, max_x, min_y, max_y = np.inf, -np.inf, np.inf, -np.inf <NEW_LINE> for polygon in self.polygons: <NEW_LINE> <INDENT> for vertex in polygon.vertices: <NEW_LINE> <INDENT> min_x = min(min_x, vertex[0]) <NEW_LINE> max_x = max(max_x, vertex[0]) <NEW_LINE> min_y = min(min_y, vertex[1]) <NEW_LINE> max_y = max(max_y, vertex[1]) <NEW_LINE> <DEDENT> <DEDENT> self.coord_bounds = (min_x, max_x, min_y, max_y) <NEW_LINE> self.width = max_x - min_x <NEW_LINE> self.height = max_y - min_y <NEW_LINE> self.num_clear_calls = 0 <NEW_LINE> <DEDENT> def clear_coords(self, x, y): <NEW_LINE> <INDENT> return all(not poly.contains_coords(x, y) for poly in self.polygons) <NEW_LINE> <DEDENT> def clear(self, robot): <NEW_LINE> <INDENT> self.num_clear_calls += 1 <NEW_LINE> return all(not robot.intersects_polygon(poly) for poly in self.polygons) <NEW_LINE> <DEDENT> def link_coords(self, position_start, position_end, step_size): <NEW_LINE> <INDENT> dist = np.linalg.norm(position_start - position_end) <NEW_LINE> num_steps = max(np.ceil(dist / step_size), 3) <NEW_LINE> for x, y in zip(np.linspace(position_start[0], position_end[0], num_steps), np.linspace(position_start[1], position_end[1], num_steps)): <NEW_LINE> <INDENT> if not self.clear_coords(x, y): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def link(self, robot_start, robot_end, step_size): <NEW_LINE> <INDENT> workspace_pt1 = robot_start.configuration() <NEW_LINE> workspace_pt2 = robot_end.configuration() <NEW_LINE> dist = np.linalg.norm(workspace_pt1 - workspace_pt2) <NEW_LINE> num_steps = max(np.ceil(dist / step_size), 3) <NEW_LINE> robot = robot_start <NEW_LINE> for x, y, angle in zip(np.linspace(workspace_pt1[0], workspace_pt2[0], num_steps), np.linspace(workspace_pt1[1], workspace_pt2[1], num_steps), np.linspace(workspace_pt1[2], workspace_pt2[2], num_steps)): <NEW_LINE> <INDENT> robot.move(x, y, angle) <NEW_LINE> if not self.clear(robot): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def draw(self, color): <NEW_LINE> <INDENT> for polygon in self.polygons: <NEW_LINE> <INDENT> polygon.draw(color) <NEW_LINE> <DEDENT> <DEDENT> def bounds(self): <NEW_LINE> <INDENT> return self.coord_bounds
ProblemConfigurations description of the environment, given by a list of polygons.
62598fa38e71fb1e983bb94b
class Group(models.Model): <NEW_LINE> <INDENT> class Meta(object): <NEW_LINE> <INDENT> verbose_name = u"Група" <NEW_LINE> verbose_name_plural = u"Групи" <NEW_LINE> <DEDENT> title = models.CharField( max_length=256, blank=False, verbose_name=u"Назва групи") <NEW_LINE> leader = models.OneToOneField('Student', verbose_name=u"Староста", blank=True, null=True, on_delete=models.SET_NULL) <NEW_LINE> students_count = models.IntegerField( verbose_name=u"Number of Students", default= 0, blank=False, ) <NEW_LINE> notes = models.TextField( blank=True, verbose_name=u"Додаткові нотатки") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> if self.leader: <NEW_LINE> <INDENT> return u"%s (%s %s)" % (self.title, self.leader.first_name,self.leader.last_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u"%s" % self.title
Group Model
62598fa345492302aabfc36a
class ModelMutatedDuringJobError(base_validation_errors.BaseAuditError): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> message = ( 'published_on=%r is later than the audit job\'s start time' % ( model.published_on)) <NEW_LINE> super(ModelMutatedDuringJobError, self).__init__(message, model)
Error class for models mutated during a job.
62598fa33539df3088ecc14e
class Humanoid(base.Task): <NEW_LINE> <INDENT> def __init__(self, move_speed, pure_state, random=None): <NEW_LINE> <INDENT> self._move_speed = move_speed <NEW_LINE> self._pure_state = pure_state <NEW_LINE> super(Humanoid, self).__init__(random=random) <NEW_LINE> <DEDENT> def initialize_episode(self, physics): <NEW_LINE> <INDENT> penetrating = True <NEW_LINE> while penetrating: <NEW_LINE> <INDENT> randomizers.randomize_limited_and_rotational_joints(physics, self.random) <NEW_LINE> physics.after_reset() <NEW_LINE> penetrating = physics.data.ncon > 0 <NEW_LINE> <DEDENT> super(Humanoid, self).initialize_episode(physics) <NEW_LINE> <DEDENT> def get_observation(self, physics): <NEW_LINE> <INDENT> obs = collections.OrderedDict() <NEW_LINE> if self._pure_state: <NEW_LINE> <INDENT> obs['position'] = physics.position() <NEW_LINE> obs['velocity'] = physics.velocity() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obs['joint_angles'] = physics.joint_angles() <NEW_LINE> obs['head_height'] = physics.head_height() <NEW_LINE> obs['extremities'] = physics.extremities() <NEW_LINE> obs['torso_vertical'] = physics.torso_vertical_orientation() <NEW_LINE> obs['com_velocity'] = physics.center_of_mass_velocity() <NEW_LINE> obs['velocity'] = physics.velocity() <NEW_LINE> <DEDENT> return obs <NEW_LINE> <DEDENT> def get_reward(self, physics): <NEW_LINE> <INDENT> standing = rewards.tolerance(physics.head_height(), bounds=(_STAND_HEIGHT, float('inf')), margin=_STAND_HEIGHT/4) <NEW_LINE> upright = rewards.tolerance(physics.torso_upright(), bounds=(0.9, float('inf')), sigmoid='linear', margin=1.9, value_at_margin=0) <NEW_LINE> stand_reward = standing * upright <NEW_LINE> small_control = rewards.tolerance(physics.control(), margin=1, value_at_margin=0, sigmoid='quadratic').mean() <NEW_LINE> small_control = (4 + small_control) / 5 <NEW_LINE> if self._move_speed == 0: <NEW_LINE> <INDENT> horizontal_velocity = physics.center_of_mass_velocity()[[0, 1]] <NEW_LINE> dont_move = rewards.tolerance(horizontal_velocity, margin=2).mean() <NEW_LINE> return small_control * stand_reward * dont_move <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> com_velocity = np.linalg.norm(physics.center_of_mass_velocity()[[0, 1]]) <NEW_LINE> move = rewards.tolerance(com_velocity, bounds=(self._move_speed, float('inf')), margin=self._move_speed, value_at_margin=0, sigmoid='linear') <NEW_LINE> move = (5*move + 1) / 6 <NEW_LINE> return small_control * stand_reward * move
A humanoid task.
62598fa3498bea3a75a579bc
class SaImmAttrDefinitionT(Structure): <NEW_LINE> <INDENT> _fields_ = [('attrName', SaImmAttrNameT), ('attrValueType', SaImmValueTypeT), ('attrFlags', SaImmAttrFlagsT), ('attrNtfId', SaUint32T), ('attrDefaultValue', SaImmAttrValueT)]
Contain characteristics of an attribute belonging to an object class.
62598fa33eb6a72ae038a4de
class HelloView(tk.Frame): <NEW_LINE> <INDENT> def __init__(self, parent, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(parent, *args, **kwargs) <NEW_LINE> self.name = tk.StringVar() <NEW_LINE> self.hello_string = tk.StringVar() <NEW_LINE> self.hello_string.set("Hello") <NEW_LINE> name_label = ttk.Label(self, text="Name:") <NEW_LINE> name_entry = ttk.Entry(self, textvariable=self.name) <NEW_LINE> ch_button = ttk.Button( self, text="Change", command=self.on_change) <NEW_LINE> hello_label = ttk.Label( self, textvariable=self.hello_string, font=( "TkDefaultFont", 64), wraplength=600) <NEW_LINE> name_label.grid(row=0, column=0, sticky=tk.W) <NEW_LINE> name_entry.grid(row=0, column=1, sticky=(tk.W + tk.E)) <NEW_LINE> ch_button.grid(row=0, column=2, sticky=tk.E) <NEW_LINE> hello_label.grid(row=1, column=0, columnspan=3) <NEW_LINE> self.columnconfigure(1, weight=1) <NEW_LINE> <DEDENT> def on_change(self): <NEW_LINE> <INDENT> if self.name.get().strip(): <NEW_LINE> <INDENT> self.hello_string.set("Hello " + self.name.get()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.hello_string.set("Hello World")
A friendly little module
62598fa3be383301e0253692
class Room(object): <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.grid = {} <NEW_LINE> <DEDENT> def fetch(self, x, y): <NEW_LINE> <INDENT> return self.grid.setdefault((x, y), ' ') <NEW_LINE> <DEDENT> def store(self, x, y, c): <NEW_LINE> <INDENT> self.grid[(x, y)] = c <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> buf = '' <NEW_LINE> for y in range(0, self.size): <NEW_LINE> <INDENT> line = '' <NEW_LINE> for x in range(0, self.size): <NEW_LINE> <INDENT> line += self.fetch(x, y) <NEW_LINE> <DEDENT> buf += line + '\n' <NEW_LINE> <DEDENT> return buf.rstrip('\n')
A square grid of characters. >>> r = Room(3) >>> r.store(0, 0, 'a') >>> r.store(1, 0, 'b') >>> r.store(2, 0, 'c') >>> r.store(0, 1, '-') >>> r.store(0, 2, 'A') >>> r.store(2, 2, 'Z') >>> print r abc - A Z
62598fa34f88993c371f0457
class Person(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.status='hungry' <NEW_LINE> self.defense=100+lmao['durability'] <NEW_LINE> self.atk=1+lmao['atk'] <NEW_LINE> self.xp=300 <NEW_LINE> self.health=500+self.defense <NEW_LINE> self.know=0+lmao['atk'] <NEW_LINE> <DEDENT> def attack(self, some_animal): <NEW_LINE> <INDENT> some_animal.health-=self.atk <NEW_LINE> print("attacking") <NEW_LINE> <DEDENT> def defend(self, some_animal): <NEW_LINE> <INDENT> self.health-=some_animal.atk
All elements of person
62598fa3f548e778e596b43e
class ProductionConfig(Config): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> TESTING = False
Production configurations
62598fa3baa26c4b54d4f14b
class PluginTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(PluginTestCase, self).setUp() <NEW_LINE> self.old_horizon_config = conf.HORIZON_CONFIG <NEW_LINE> conf.HORIZON_CONFIG = conf.LazySettings() <NEW_LINE> base.Horizon._urls() <NEW_LINE> self.client.get("/") <NEW_LINE> self._discovered_dashboards = base.Horizon._registry.keys() <NEW_LINE> self._discovered_panels = {} <NEW_LINE> for dash in self._discovered_dashboards: <NEW_LINE> <INDENT> panels = base.Horizon._registry[dash]._registry.keys() <NEW_LINE> self._discovered_panels[dash] = panels <NEW_LINE> <DEDENT> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(PluginTestCase, self).tearDown() <NEW_LINE> conf.HORIZON_CONFIG = self.old_horizon_config <NEW_LINE> base.HorizonSite._instance = None <NEW_LINE> del base.Horizon <NEW_LINE> base.Horizon = base.HorizonSite() <NEW_LINE> reload(import_module("horizon")) <NEW_LINE> for dash in self._discovered_dashboards: <NEW_LINE> <INDENT> base.Horizon.register(dash) <NEW_LINE> for panel in self._discovered_panels[dash]: <NEW_LINE> <INDENT> dash.register(panel) <NEW_LINE> <DEDENT> <DEDENT> self._reload_urls() <NEW_LINE> <DEDENT> def _reload_urls(self): <NEW_LINE> <INDENT> urlresolvers.clear_url_caches() <NEW_LINE> reload(import_module(settings.ROOT_URLCONF)) <NEW_LINE> base.Horizon._urls()
The ``PluginTestCase`` class is for use with tests which deal with the pluggable dashboard and panel configuration, it takes care of backing up and restoring the Horizon configuration.
62598fa3e5267d203ee6b7a7
class MemcacheStore(OpenIDStore): <NEW_LINE> <INDENT> def storeAssociation(self, server_url, assoc): <NEW_LINE> <INDENT> for handle in [assoc.handle, None]: <NEW_LINE> <INDENT> memcache.set(assoc_key(server_url, handle), assoc, assoc.getExpiresIn()) <NEW_LINE> <DEDENT> <DEDENT> def getAssociation(self, server_url, handle=None): <NEW_LINE> <INDENT> return memcache.get(assoc_key(server_url, handle)) <NEW_LINE> <DEDENT> def removeAssociation(self, server_url, handle): <NEW_LINE> <INDENT> return bool(memcache.delete(assoc_key(server_url, handle))) <NEW_LINE> <DEDENT> def useNonce(self, server_url, timestamp, salt): <NEW_LINE> <INDENT> key = nonce_key(server_url, timestamp, salt) <NEW_LINE> return bool(memcache.add(key, '-', NONCE_TTL)) <NEW_LINE> <DEDENT> def cleanupAssociations(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def cleanupNonces(self): <NEW_LINE> <INDENT> pass
Memcached-backed OpenID authentication store.
62598fa3b7558d58954634c9
class CodeImageIterator(object): <NEW_LINE> <INDENT> def __init__(self, size, stepsize): <NEW_LINE> <INDENT> self.stepsize = stepsize <NEW_LINE> self.imageSize = size <NEW_LINE> self.size = size[0] + size[0] % stepsize, size[1] + size[1] % stepsize <NEW_LINE> self.code = codeForLength((size[0] / stepsize) * (size[1] / stepsize)) <NEW_LINE> self.counter = 0 <NEW_LINE> <DEDENT> def ravel(self,x,y): <NEW_LINE> <INDENT> x /= self.stepsize <NEW_LINE> y /= self.stepsize <NEW_LINE> return self.size[0] / self.stepsize * y + x <NEW_LINE> <DEDENT> def unravel(self, number): <NEW_LINE> <INDENT> x = (number % (self.size[0] / self.stepsize)) * self.stepsize <NEW_LINE> y = (number / (self.size[0] / self.stepsize)) * self.stepsize <NEW_LINE> return x,y <NEW_LINE> <DEDENT> def generator(self): <NEW_LINE> <INDENT> for counter in range(self.code.wordlength): <NEW_LINE> <INDENT> def brightP(x, y): <NEW_LINE> <INDENT> if x % self.stepsize == 0 and y % self.stepsize == 0: <NEW_LINE> <INDENT> i = self.ravel(x,y) <NEW_LINE> return 1. if counter in self.code.encode(i) else 0. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0. <NEW_LINE> <DEDENT> <DEDENT> yield ( numpy.array([[brightP(x,y) for x in range(self.imageSize[0])] for y in range(self.imageSize[1])]) ) <NEW_LINE> <DEDENT> <DEDENT> def allPixels(self): <NEW_LINE> <INDENT> i,j = numpy.mgrid[0:self.imageSize[1],0:self.imageSize[0]] <NEW_LINE> return ((i % self.stepsize == 0) & (j % self.stepsize == 0)).astype(float) <NEW_LINE> <DEDENT> def lookupPixel(self, word): <NEW_LINE> <INDENT> number = self.code.lookup(word) <NEW_LINE> if number is not None: <NEW_LINE> <INDENT> x,y = self.unravel(number) <NEW_LINE> return x, y <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Generates a sequence of cv2 images (binary arrays) in which numbered pixels flicker their respective number in a binary code.
62598fa33d592f4c4edbad68
class VueSame: <NEW_LINE> <INDENT> def __init__(self,same): <NEW_LINE> <INDENT> self.__same=same <NEW_LINE> self.__fen=Tk() <NEW_LINE> self.__fen.title("SAMEEEEEEEEEEEEE") <NEW_LINE> self.__images=[] <NEW_LINE> for i in range(self.__same.nbcouleur()): <NEW_LINE> <INDENT> self.__images.append(PhotoImage(file="img/medium_sphere"+str(i+1)+".gif")) <NEW_LINE> <DEDENT> self.__images.append(PhotoImage(file="img/medium_spherevide.gif")) <NEW_LINE> self.__listebutton=[] <NEW_LINE> for i in range(self.__same.nblig()): <NEW_LINE> <INDENT> self.__listebutton.append([]) <NEW_LINE> for j in range(self.__same.nbcol()): <NEW_LINE> <INDENT> self.__listebutton[i].append(Button(self.__fen,image=self.__images[self.__same.couleur(i,j)],command=self.creer_controleur_btn(i,j))) <NEW_LINE> self.__listebutton[i][j].grid(row=i,column=j) <NEW_LINE> <DEDENT> <DEDENT> self.__lbscore = Label(self.__fen, text=str(self.__same.score())) <NEW_LINE> self.__lbscore.grid(row=int(self.__same.nblig()/2) - 1,column=self.__same.nbcol()) <NEW_LINE> nouvellepartie=Button(self.__fen,text="Nouvelle partie",command=self.newgame) <NEW_LINE> nouvellepartie.grid(row=int(self.__same.nblig()/2),column=self.__same.nbcol()) <NEW_LINE> quitter=Button(self.__fen,text="Quitter",command=self.__fen.destroy) <NEW_LINE> quitter.grid(row=int(self.__same.nblig()/2)+1,column=self.__same.nbcol()) <NEW_LINE> mainloop() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> for i in range(self.__same.nblig()): <NEW_LINE> <INDENT> for j in range(self.__same.nbcol()): <NEW_LINE> <INDENT> self.__listebutton[i][j].config(image=self.__images[self.__same.couleur(i,j)]) <NEW_LINE> <DEDENT> <DEDENT> self.__lbscore["text"] = str(self.__same.score()) <NEW_LINE> <DEDENT> def newgame(self): <NEW_LINE> <INDENT> self.__same.nouvelle_partie() <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def creer_controleur_btn(self,i,j): <NEW_LINE> <INDENT> def controleur_btn(): <NEW_LINE> <INDENT> self.__same.supprime_bille(i,j) <NEW_LINE> self.update() <NEW_LINE> <DEDENT> return controleur_btn
Defini la vue du jeu
62598fa35fdd1c0f98e5de33
class GroupViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> permission_classes = [permissions.IsAuthenticated, TokenHasScope] <NEW_LINE> required_scopes = ['groups'] <NEW_LINE> queryset = Group.objects.all() <NEW_LINE> serializer_class = GroupSerializer
Group View
62598fa3435de62698e9bc8f
class SerializerException(SDKError): <NEW_LINE> <INDENT> pass
Encountered an issue when seralizing a request or event
62598fa3b7558d58954634ca
class Button(BaseButton): <NEW_LINE> <INDENT> class JS(object): <NEW_LINE> <INDENT> def _init_phosphor_and_node(self): <NEW_LINE> <INDENT> self.phosphor = window.phosphor.createWidget('button') <NEW_LINE> self.node = self.phosphor.node <NEW_LINE> self.node.addEventListener('click', self.mouse_click, 0) <NEW_LINE> <DEDENT> @event.connect('text') <NEW_LINE> def __text_changed(self, *events): <NEW_LINE> <INDENT> self.node.innerHTML = events[-1].new_value
A push button.
62598fa367a9b606de545e66
class Establishment(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'establishments' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(255)) <NEW_LINE> location = db.Column(db.String(255)) <NEW_LINE> description = db.Column(db.Text()) <NEW_LINE> open_time = db.Column(db.Time()) <NEW_LINE> end_time = db.Column(db.Time()) <NEW_LINE> img_url = db.Column(db.String(255)) <NEW_LINE> def __init__(self, name, location, description, open_time, end_time, img_url): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.location = location <NEW_LINE> self.description = description <NEW_LINE> self.open_time = open_time <NEW_LINE> self.end_time = end_time <NEW_LINE> self.img_url = img_url <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_all(): <NEW_LINE> <INDENT> return Establishment.query.all() <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> db.session.delete(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Establishments: {}>".format(self.name)
This class represents the establishments table.
62598fa391af0d3eaad39ca9
class testEnum_args(TBase): <NEW_LINE> <INDENT> def __init__(self, thing=None,): <NEW_LINE> <INDENT> self.thing = thing <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - thing
62598fa3925a0f43d25e7eda
class Post(db.Model): <NEW_LINE> <INDENT> subject = db.StringProperty(required = True) <NEW_LINE> content = db.TextProperty(required = True) <NEW_LINE> created = db.DateTimeProperty(auto_now_add = True) <NEW_LINE> last_modified = db.DateTimeProperty(auto_now = True) <NEW_LINE> user_id = db.StringProperty(required = True) <NEW_LINE> likes = db.StringListProperty() <NEW_LINE> parent_post = db.StringProperty() <NEW_LINE> def render(self): <NEW_LINE> <INDENT> self._render_text = self.content.replace('\n', '<br>') <NEW_LINE> return render_str("post.html", p = self)
Post : This is Post Class, which holds blog post information. And helps to store/retrieve User data from database Attributes : subject(str) : This is subject line of the post content(txt) : This is content of the post. created(text) : This is date of the post. user_id : This is user_id, who wrote blog post. likes : show likes of the post
62598fa345492302aabfc36d
class StaticHelperTest(StaticTests): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self._old_views_urlpatterns = urls.urlpatterns[:] <NEW_LINE> urls.urlpatterns += static('/media/', document_root=media_dir) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super().tearDown() <NEW_LINE> urls.urlpatterns = self._old_views_urlpatterns <NEW_LINE> <DEDENT> def test_prefix(self): <NEW_LINE> <INDENT> self.assertEqual(static('test')[0].pattern.regex.pattern, '^test(?P<path>.*)$') <NEW_LINE> <DEDENT> @override_settings(DEBUG=False) <NEW_LINE> def test_debug_off(self): <NEW_LINE> <INDENT> self.assertEqual(static('test'), []) <NEW_LINE> <DEDENT> def test_empty_prefix(self): <NEW_LINE> <INDENT> with self.assertRaisesMessage(ImproperlyConfigured, 'Empty static prefix not permitted'): <NEW_LINE> <INDENT> static('') <NEW_LINE> <DEDENT> <DEDENT> def test_special_prefix(self): <NEW_LINE> <INDENT> self.assertEqual(static('http://example.org'), []) <NEW_LINE> self.assertEqual(static('//example.org'), [])
Test case to make sure the static URL pattern helper works as expected
62598fa392d797404e388ab3
class Command(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._help = kwargs['help'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def help(self): <NEW_LINE> <INDENT> return self._help <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def do(self, message, subreddit): <NEW_LINE> <INDENT> pass
An abstract base class representing a Discord bot command Requires the method `do (self, message, subreddit)` to be implemented by all inheriting classes. Also requires `help` data to be passed to Command at creation time.
62598fa32c8b7c6e89bd3661
class ReadTest(unittest.TestCase): <NEW_LINE> <INDENT> loaded_db = 0 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> load_database("GenBank/cor6_6.gb") <NEW_LINE> self.server = BioSeqDatabase.open_database( driver=DBDRIVER, user=DBUSER, passwd=DBPASSWD, host=DBHOST, db=TESTDB ) <NEW_LINE> self.db = self.server["biosql-test"] <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.server.close() <NEW_LINE> destroy_database() <NEW_LINE> del self.db <NEW_LINE> del self.server <NEW_LINE> <DEDENT> def test_server(self): <NEW_LINE> <INDENT> server = self.server <NEW_LINE> self.assertIn("biosql-test", server) <NEW_LINE> self.assertEqual(1, len(server)) <NEW_LINE> self.assertEqual(["biosql-test"], list(server.keys())) <NEW_LINE> del server["biosql-test"] <NEW_LINE> self.assertEqual(0, len(server)) <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> del server["non-existant-name"] <NEW_LINE> <DEDENT> <DEDENT> def test_get_db_items(self): <NEW_LINE> <INDENT> db = self.db <NEW_LINE> items = list(db.values()) <NEW_LINE> keys = list(db) <NEW_LINE> length = len(items) <NEW_LINE> self.assertEqual(length, len(db)) <NEW_LINE> self.assertEqual(length, len(list(db.items()))) <NEW_LINE> self.assertEqual(length, len(list(db))) <NEW_LINE> self.assertEqual(length, len(list(db.values()))) <NEW_LINE> for (k1, r1), (k2, r2) in zip(zip(keys, items), db.items()): <NEW_LINE> <INDENT> self.assertEqual(k1, k2) <NEW_LINE> self.assertEqual(r1.id, r2.id) <NEW_LINE> <DEDENT> for k in keys: <NEW_LINE> <INDENT> del db[k] <NEW_LINE> <DEDENT> self.assertEqual(0, len(db)) <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> del db["non-existant-name"] <NEW_LINE> <DEDENT> <DEDENT> def test_lookup_items(self): <NEW_LINE> <INDENT> self.db.lookup(accession="X62281") <NEW_LINE> try: <NEW_LINE> <INDENT> self.db.lookup(accession="Not real") <NEW_LINE> raise AssertionError("No problem on fake id retrieval") <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.db.lookup(display_id="ATKIN2") <NEW_LINE> try: <NEW_LINE> <INDENT> self.db.lookup(display_id="Not real") <NEW_LINE> raise AssertionError("No problem on fake id retrieval") <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.db.lookup(primary_id="16353") <NEW_LINE> try: <NEW_LINE> <INDENT> self.db.lookup(primary_id="Not Real") <NEW_LINE> raise AssertionError("No problem on fake primary id retrieval") <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass
Test reading a database from an already built database.
62598fa3dd821e528d6d8dd1
class Organization(TimeStampedModel): <NEW_LINE> <INDENT> key = models.CharField( help_text=_('The string value of an org key identifying this organization in the LMS.'), unique=True, max_length=64, db_index=True, ) <NEW_LINE> display_name = models.CharField( help_text=_('The display name of this organization.'), max_length=128, ) <NEW_LINE> programs = models.ManyToManyField(Program, related_name='organizations', through='ProgramOrganization') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.display_name)
Represents the organization offering one or more courses and/or programs. At present, Studio (edx-platform) hosts the source of truth for this data; a minimal subset of that data is replicated into this system in order to enforce referential integrity internally.
62598fa3dd821e528d6d8dd0
class VnicWwnnHistory(ManagedObject): <NEW_LINE> <INDENT> consts = VnicWwnnHistoryConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = MoMeta("VnicWwnnHistory", "vnicWwnnHistory", "wwnn-history", VersionMeta.Version212a, "InputOutput", 0x1f, [], ["read-only"], [u'vnicFcNode'], [], [None]) <NEW_LINE> prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version212a, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "oldwwnn": MoPropertyMeta("oldwwnn", "oldwwnn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, 0, 256, r"""(([A-Fa-f0-9][A-Fa-f0-9]:){7}[A-Fa-f0-9][A-Fa-f0-9])|0""", [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } <NEW_LINE> prop_map = { "childAction": "child_action", "dn": "dn", "oldwwnn": "oldwwnn", "rn": "rn", "sacl": "sacl", "status": "status", } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.child_action = None <NEW_LINE> self.oldwwnn = None <NEW_LINE> self.sacl = None <NEW_LINE> self.status = None <NEW_LINE> ManagedObject.__init__(self, "VnicWwnnHistory", parent_mo_or_dn, **kwargs)
This is VnicWwnnHistory class.
62598fa3a8ecb033258710ab
class EditorOverlay(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_property(self, name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_property(self, name, value): <NEW_LINE> <INDENT> pass
This class represents properties that can be applied to one or more ranges of text. This can be used to change the display properties of the text (colors, fonts,...) or store any user-specific attributes that can be retrieved later. GPS itself uses overlays to do syntax highlighting. If two or more overlays are applied to the same range of text, the final colors and fonts of the text depends on the priorities of these overlays and the order in which they were applied to the buffer.
62598fa356ac1b37e6302088
class Titulo(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=255) <NEW_LINE> descripcion = models.TextField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['nombre', ] <NEW_LINE> db_table = 'oeu\".\"titulo' <NEW_LINE> verbose_name = "Título" <NEW_LINE> verbose_name_plural = "Títulos"
Modelo para gestionar los titulos que se otorgan en las IEU.
62598fa367a9b606de545e67
class UserIdentifier(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str' } <NEW_LINE> attribute_map = { 'id': 'id' } <NEW_LINE> def __init__(self, id=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self.id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `id`, must not be `None`") <NEW_LINE> <DEDENT> self._id = id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, UserIdentifier): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa3009cb60464d013c1
class TemplateVersionRequestDTO(object): <NEW_LINE> <INDENT> openapi_types = { 'comments': 'str', 'template_id': 'str' } <NEW_LINE> attribute_map = { 'comments': 'comments', 'template_id': 'templateId' } <NEW_LINE> def __init__(self, comments=None, template_id=None): <NEW_LINE> <INDENT> self._comments = None <NEW_LINE> self._template_id = None <NEW_LINE> self.discriminator = None <NEW_LINE> if comments is not None: <NEW_LINE> <INDENT> self.comments = comments <NEW_LINE> <DEDENT> if template_id is not None: <NEW_LINE> <INDENT> self.template_id = template_id <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def comments(self): <NEW_LINE> <INDENT> return self._comments <NEW_LINE> <DEDENT> @comments.setter <NEW_LINE> def comments(self, comments): <NEW_LINE> <INDENT> self._comments = comments <NEW_LINE> <DEDENT> @property <NEW_LINE> def template_id(self): <NEW_LINE> <INDENT> return self._template_id <NEW_LINE> <DEDENT> @template_id.setter <NEW_LINE> def template_id(self, template_id): <NEW_LINE> <INDENT> self._template_id = template_id <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, TemplateVersionRequestDTO): <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.
62598fa3796e427e5384e630
@keras_export('keras.layers.ELU') <NEW_LINE> class ELU(Layer): <NEW_LINE> <INDENT> def __init__(self, alpha=1.0, **kwargs): <NEW_LINE> <INDENT> super(ELU, self).__init__(**kwargs) <NEW_LINE> self.supports_masking = True <NEW_LINE> self.alpha = K.cast_to_floatx(alpha) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> return K.elu(inputs, self.alpha) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = {'alpha': float(self.alpha)} <NEW_LINE> base_config = super(ELU, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items())) <NEW_LINE> <DEDENT> @tf_utils.shape_type_conversion <NEW_LINE> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> return input_shape
Exponential Linear Unit. It follows: `f(x) = alpha * (exp(x) - 1.) for x < 0`, `f(x) = x for x >= 0`. Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Arguments: alpha: scale for the negative factor.
62598fa3a8370b77170f0276
class EncryptionUI(Tk): <NEW_LINE> <INDENT> def __init__(self,all_data): <NEW_LINE> <INDENT> Tk.__init__(self) <NEW_LINE> self.all_data=all_data <NEW_LINE> self.title("QuEST Encryption tool") <NEW_LINE> self.console=TDCFrames.AllConsole(self,self.all_data) <NEW_LINE> self.setting_frame=TDCFrames.SettingsFrame(self,self.all_data) <NEW_LINE> self.console.pack(side=BOTTOM) <NEW_LINE> self.setting_frame.pack(side=TOP)
classdocs
62598fa31b99ca400228f47d
class AsyncRequestHandler: <NEW_LINE> <INDENT> _dResponseClasses = {EncodeableType.ReadResponse: ReadResponse, EncodeableType.WriteResponse: WriteResponse, EncodeableType.BrowseResponse: BrowseResponse, } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._dRequestContexts = {} <NEW_LINE> self._dPendingResponses = {} <NEW_LINE> self._sSkipResponse = set() <NEW_LINE> <DEDENT> def _send_request(self, idx, request): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def send_generic_request(self, idx, request, bWaitResponse): <NEW_LINE> <INDENT> reqCtx = int(request.requestContext) <NEW_LINE> self._dRequestContexts[reqCtx] = request <NEW_LINE> request.timestampSent = time.time() <NEW_LINE> self._send_request(idx, request) <NEW_LINE> if bWaitResponse: <NEW_LINE> <INDENT> self._sSkipResponse.add(reqCtx) <NEW_LINE> return self._wait_for_response(request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return request <NEW_LINE> <DEDENT> <DEDENT> def _on_response(self, responsePayload, responseContext, timestamp): <NEW_LINE> <INDENT> assert responseContext in self._dRequestContexts, 'Unknown requestContext {}.'.format(responseContext) <NEW_LINE> request = self._dRequestContexts.pop(responseContext) <NEW_LINE> try: <NEW_LINE> <INDENT> if responsePayload is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> encType = ffi.cast('SOPC_EncodeableType**', responsePayload) <NEW_LINE> response = self._dResponseClasses.get(encType[0], Response)(responsePayload) <NEW_LINE> response.timestampReceived = timestamp <NEW_LINE> request.response = response <NEW_LINE> response.request = request <NEW_LINE> if responseContext not in self._sSkipResponse: <NEW_LINE> <INDENT> self.on_generic_response(request, response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._sSkipResponse.remove(responseContext) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> request.eventResponseReceived.set() <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> def on_generic_response(self, request, response): <NEW_LINE> <INDENT> assert request.requestContext not in self._dPendingResponses, 'A request with context {} is still waiting for a response'.format(request.requestContext) <NEW_LINE> self._dPendingResponses[request.requestContext] = response <NEW_LINE> <DEDENT> def _wait_for_response(self, request): <NEW_LINE> <INDENT> request.eventResponseReceived.wait() <NEW_LINE> return request.response <NEW_LINE> <DEDENT> def get_response(self, request): <NEW_LINE> <INDENT> return self._dPendingResponses.pop(request.requestContext, None)
MixIn that implements asynchronous request handling: associates a response to a request. This should be derived to implement the `_send_request` method. See `request.LibSubAsyncRequestHandler` and `request.LocalAsyncRequestHandler`.
62598fa31f037a2d8b9e3f86
class Chunk_collector (object): <NEW_LINE> <INDENT> collector_is_simple = False <NEW_LINE> chunk_extensions = None <NEW_LINE> def __init__ (self, collector, set_terminator, headers=None): <NEW_LINE> <INDENT> self.chunk_collector = collector <NEW_LINE> self.set_terminator = set_terminator <NEW_LINE> self.collector_headers = headers or {} <NEW_LINE> self.collect_incoming_data = self.chunk_collect_size <NEW_LINE> self.chunk_size = '' <NEW_LINE> self.chunk_trailers = None <NEW_LINE> self.chunk_trailer = '' <NEW_LINE> self.set_terminator ('\r\n') <NEW_LINE> <DEDENT> def get_terminator (self): <NEW_LINE> <INDENT> return '\r\n' <NEW_LINE> <DEDENT> def chunk_collect_size (self, data): <NEW_LINE> <INDENT> self.chunk_size += data <NEW_LINE> <DEDENT> def chunk_collect_trailers (self, data): <NEW_LINE> <INDENT> self.chunk_trailer += data <NEW_LINE> <DEDENT> def found_terminator (self): <NEW_LINE> <INDENT> if self.chunk_size == None: <NEW_LINE> <INDENT> self.set_terminator ('\r\n') <NEW_LINE> self.chunk_size = '' <NEW_LINE> self.collect_incoming_data = self.chunk_collect_size <NEW_LINE> return False <NEW_LINE> <DEDENT> if self.chunk_size == '0': <NEW_LINE> <INDENT> if self.chunk_trailers == None: <NEW_LINE> <INDENT> self.chunk_trailers = [] <NEW_LINE> self.collect_incoming_data = self.chunk_collect_trailers <NEW_LINE> return False <NEW_LINE> <DEDENT> elif self.chunk_trailer: <NEW_LINE> <INDENT> self.chunk_trailers.append (self.chunk_trailer) <NEW_LINE> self.chunk_trailer = '' <NEW_LINE> return False <NEW_LINE> <DEDENT> elif self.chunk_trailers: <NEW_LINE> <INDENT> self.collector_headers.update ( headers_map (self.chunk_trailers) ) <NEW_LINE> <DEDENT> <DEDENT> elif self.chunk_size != '': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ( self.chunk_size, self.chunk_extensions ) = self.chunk_size.split (';', 1) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.set_terminator ( int (self.chunk_size, 16) + 2 ) <NEW_LINE> self.chunk_size = None <NEW_LINE> self.collect_incoming_data = self.chunk_collector.collect_incoming_data <NEW_LINE> return False <NEW_LINE> <DEDENT> self.chunk_collector.found_terminator () <NEW_LINE> del self.set_terminator, self.collect_incoming_data <NEW_LINE> return True
a wrapping collector for chunked transfer encoding
62598fa3e5267d203ee6b7a9
class FSFlipCommand: <NEW_LINE> <INDENT> def GetResources(self): <NEW_LINE> <INDENT> icon = os.path.join(iconPath, 'IconFlip.svg') <NEW_LINE> return { 'Pixmap': icon, 'MenuText': "Invert fastener", 'ToolTip': "Invert fastener orientation" } <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> selObjs = self.GetSelection() <NEW_LINE> if len(selObjs) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for selObj in selObjs: <NEW_LINE> <INDENT> FreeCAD.Console.PrintLog("sel obj: " + str(selObj.invert) + "\n") <NEW_LINE> selObj.invert = not selObj.invert <NEW_LINE> <DEDENT> FreeCAD.ActiveDocument.recompute() <NEW_LINE> return <NEW_LINE> <DEDENT> def IsActive(self): <NEW_LINE> <INDENT> selObjs = self.GetSelection() <NEW_LINE> return len(selObjs) > 0 <NEW_LINE> <DEDENT> def GetSelection(self): <NEW_LINE> <INDENT> screwObj = [] <NEW_LINE> for selobj in Gui.Selection.getSelectionEx(): <NEW_LINE> <INDENT> obj = selobj.Object <NEW_LINE> if hasattr(obj, 'Proxy') and isinstance(obj.Proxy, FSBaseObject): <NEW_LINE> <INDENT> if obj.baseObject is not None: <NEW_LINE> <INDENT> screwObj.append(obj) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return screwObj
Flip Screw command
62598fa33617ad0b5ee05fef
class ExpressionFunction(GenericFunction): <NEW_LINE> <INDENT> functions = {k: getattr(np, k) for k in {'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'exp', 'exp2', 'log', 'log2', 'log10', 'array', 'min', 'minimum', 'max', 'maximum', 'pi', 'e', 'sum', 'prod'}} <NEW_LINE> def __init__(self, expression, dim_domain=1, shape_range=(), parameter_type=None, name=None): <NEW_LINE> <INDENT> self.expression = expression <NEW_LINE> code = compile(expression, '<expression>', 'eval') <NEW_LINE> functions = self.functions <NEW_LINE> mapping = lambda x, mu=None: eval(code, functions, {'x': x, 'mu': mu}) <NEW_LINE> super().__init__(mapping, dim_domain, shape_range, parameter_type, name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'ExpressionFunction({}, {}, {}, {})'.format(self.expression, repr(self.parameter_type), self.shape_range, self.parameter_type) <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return (ExpressionFunction, (self.expression, self.dim_domain, self.shape_range, self.parameter_type, getattr(self, '_name', None)))
Turns a Python expression given as a string into a |Function|. Some |NumPy| arithmetic functions like 'sin', 'log', 'min' are supported. For a full list see the `functions` class attribute. .. warning:: :meth:`eval` is used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction! Parameters ---------- expression A Python expression of one variable `x` and a parameter `mu` given as a string. dim_domain The dimension of the domain. shape_range The shape of the values returned by the expression. parameter_type The |ParameterType| the expression accepts. name The name of the function.
62598fa3498bea3a75a579bf
class MethodSignatureProcessor(object): <NEW_LINE> <INDENT> def __init__(self, class_dict, ext_type, method_maker, validators): <NEW_LINE> <INDENT> self.class_dict = class_dict <NEW_LINE> self.ext_type = ext_type <NEW_LINE> self.method_maker = method_maker <NEW_LINE> self.validators = validators <NEW_LINE> <DEDENT> def update_signature(self, method): <NEW_LINE> <INDENT> argtypes = method_argtypes(method, self.ext_type, method.signature.args) <NEW_LINE> restype = method.signature.return_type <NEW_LINE> method.signature = typesystem.function(restype, argtypes) <NEW_LINE> method.signature = self.method_maker.make_method_type(method) <NEW_LINE> <DEDENT> def get_method_signatures(self): <NEW_LINE> <INDENT> methods = [] <NEW_LINE> for method_name, method in sorted(self.class_dict.iteritems()): <NEW_LINE> <INDENT> method = process_signature(method, method_name) <NEW_LINE> if method is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for validator in self.validators: <NEW_LINE> <INDENT> validator.validate(method, self.ext_type) <NEW_LINE> <DEDENT> if method.signature is None: <NEW_LINE> <INDENT> method.signature = self.method_maker.default_signature( method, self.ext_type) <NEW_LINE> <DEDENT> if method.signature is not None: <NEW_LINE> <INDENT> self.update_signature(method) <NEW_LINE> <DEDENT> methods.append(method) <NEW_LINE> <DEDENT> return methods
Processes signatures of extension types.
62598fa39c8ee823130400bd
class Event: <NEW_LINE> <INDENT> def __init__(self, name, date=None, place=None, distance=None, url=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.date = date <NEW_LINE> self.place = place <NEW_LINE> self.distance = distance <NEW_LINE> self.url = url <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{} ({}, {}): {}'.format(self.name, self.place, date_with_dots(self.date), self.distance) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def to_tuple(self): <NEW_LINE> <INDENT> return self.name, str(self.date), self.place, self.distance, self.url
Class with information about events: name, date, place, distance(s) and URL
62598fa3a79ad16197769efd
class ObsData(object): <NEW_LINE> <INDENT> swagger_types = { 'feature': 'object', 'geometry': 'object', 'scalar_data': 'ScalarData' } <NEW_LINE> attribute_map = { 'feature': 'feature', 'geometry': 'geometry', 'scalar_data': 'scalarData' } <NEW_LINE> def __init__(self, feature=None, geometry=None, scalar_data=None): <NEW_LINE> <INDENT> self._feature = None <NEW_LINE> self._geometry = None <NEW_LINE> self._scalar_data = None <NEW_LINE> if feature is not None: <NEW_LINE> <INDENT> self.feature = feature <NEW_LINE> <DEDENT> if geometry is not None: <NEW_LINE> <INDENT> self.geometry = geometry <NEW_LINE> <DEDENT> if scalar_data is not None: <NEW_LINE> <INDENT> self.scalar_data = scalar_data <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def feature(self): <NEW_LINE> <INDENT> return self._feature <NEW_LINE> <DEDENT> @feature.setter <NEW_LINE> def feature(self, feature): <NEW_LINE> <INDENT> self._feature = feature <NEW_LINE> <DEDENT> @property <NEW_LINE> def geometry(self): <NEW_LINE> <INDENT> return self._geometry <NEW_LINE> <DEDENT> @geometry.setter <NEW_LINE> def geometry(self, geometry): <NEW_LINE> <INDENT> self._geometry = geometry <NEW_LINE> <DEDENT> @property <NEW_LINE> def scalar_data(self): <NEW_LINE> <INDENT> return self._scalar_data <NEW_LINE> <DEDENT> @scalar_data.setter <NEW_LINE> def scalar_data(self, scalar_data): <NEW_LINE> <INDENT> self._scalar_data = scalar_data <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ObsData): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa355399d3f056263bf
class NewWindow(Toplevel): <NEW_LINE> <INDENT> def __init__(self, file, master): <NEW_LINE> <INDENT> super().__init__(master) <NEW_LINE> self.title("Underlying Data") <NEW_LINE> self.geometry("1000x500") <NEW_LINE> self.file = file <NEW_LINE> self.fill_window() <NEW_LINE> <DEDENT> def fill_window(self): <NEW_LINE> <INDENT> s = ttk.Style() <NEW_LINE> s.configure("Json.Treeview", rowheight = 55) <NEW_LINE> if self.file[-4:] == "json": <NEW_LINE> <INDENT> tv1 = ttk.Treeview(self, style="Json.Treeview") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tv1 = ttk.Treeview(self) <NEW_LINE> <DEDENT> tv1.place(relheight=1, relwidth=1) <NEW_LINE> treescrolly = tk.Scrollbar(self, orient="vertical", command=tv1.yview) <NEW_LINE> treescrollx = tk.Scrollbar(self, orient="horizontal", command=tv1.xview) <NEW_LINE> tv1.configure(xscrollcommand=treescrollx.set, yscrollcommand=treescrolly.set) <NEW_LINE> treescrollx.pack(side="bottom", fill="x") <NEW_LINE> treescrolly.pack(side="right", fill="y") <NEW_LINE> if self.file[-4:] == "json": <NEW_LINE> <INDENT> tv1.place(relheight=1, relwidth=1) <NEW_LINE> with open(self.file) as f: <NEW_LINE> <INDENT> data = json.load(f) <NEW_LINE> <DEDENT> data1 = list(data.keys()) <NEW_LINE> data2 = list(data.values()) <NEW_LINE> df_data = {"Policy Type": data1, "Description of High Quality Policy": data2} <NEW_LINE> df = pd.DataFrame(data=df_data) <NEW_LINE> tv1["column"] = list(df.columns) <NEW_LINE> tv1["show"] = "headings" <NEW_LINE> for column in tv1["columns"]: <NEW_LINE> <INDENT> tv1.heading(column, text=column) <NEW_LINE> <DEDENT> df_rows = df.to_numpy().tolist() <NEW_LINE> for row in df_rows: <NEW_LINE> <INDENT> print(row) <NEW_LINE> new_lst = row[1].split() <NEW_LINE> if len(new_lst) > 30: <NEW_LINE> <INDENT> new_lst.insert(round(len(new_lst) / 3), "\n") <NEW_LINE> new_lst.insert(round(2 * len(new_lst) / 3), "\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_lst.insert(round(len(new_lst) / 2), "\n") <NEW_LINE> <DEDENT> row[1] = " ".join(new_lst) <NEW_LINE> tv1.insert("", "end", values=row) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> df = pd.read_csv(self.file) <NEW_LINE> tv1["column"] = list(df.columns) <NEW_LINE> tv1["show"] = "headings" <NEW_LINE> for column in tv1["columns"]: <NEW_LINE> <INDENT> tv1.heading(column, text=column) <NEW_LINE> <DEDENT> df_rows = df.to_numpy().tolist() <NEW_LINE> for row in df_rows: <NEW_LINE> <INDENT> tv1.insert("", "end", values=row)
Adapted from https://www.geeksforgeeks.org/open-a-new-window-with-a-button-in-python-tkinter/ and https://gist.github.com/RamonWill/0686bd8c793e2e755761a8f20a42c762 This class was built to allow a new window to open with information uploaded from a csv or json present in the new window. It was utilized to allow a user of our program to see the underlying data affecting our outputs.
62598fa32ae34c7f260aaf7d
class tokensGoogle(object): <NEW_LINE> <INDENT> listaTokens = [] <NEW_LINE> linha = 0 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.listaTokens.append("AIzaSyCWhAnQ80OxbOCineGjTzaL0obPgswJKq8") <NEW_LINE> self.listaTokens.append("AIzaSyB2mD3gR8vXSmWIgCQpkDAjF4ySJMMaH6U") <NEW_LINE> self.listaTokens.append("AIzaSyDlNhU4Wjbxc_iJ8ipO9P6TGWCfPu4B-9c") <NEW_LINE> self.linha = 0 <NEW_LINE> <DEDENT> def getTokenAtual(self): <NEW_LINE> <INDENT> return self.listaTokens[self.linha] <NEW_LINE> <DEDENT> def updateToken(self): <NEW_LINE> <INDENT> self.linha = self.linha + 1
description of class
62598fa301c39578d7f12c1c
class IterFile(object): <NEW_LINE> <INDENT> __slots__ = ('_iter', '_buf') <NEW_LINE> def __init__(self, it): <NEW_LINE> <INDENT> self._iter = iter(it) <NEW_LINE> self._buf = '' <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.readline, '') <NEW_LINE> <DEDENT> def read(self, size=None): <NEW_LINE> <INDENT> if self._iter is None: <NEW_LINE> <INDENT> raise IOError('read from closed file') <NEW_LINE> <DEDENT> while size is None or len(self._buf) < size: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._buf += self._iter.next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if size is None: <NEW_LINE> <INDENT> data = self._buf <NEW_LINE> self._buf = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self._buf[:size] <NEW_LINE> self._buf = self._buf[size:] <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self._iter is None: <NEW_LINE> <INDENT> raise IOError('read from closed file') <NEW_LINE> <DEDENT> i = -1 <NEW_LINE> start = 0 <NEW_LINE> while i < 0: <NEW_LINE> <INDENT> i = self._buf.find('\n', start) <NEW_LINE> start = len(self._buf) <NEW_LINE> try: <NEW_LINE> <INDENT> self._buf += self._iter.next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if i < 0: <NEW_LINE> <INDENT> data = self._buf <NEW_LINE> self._buf = '' <NEW_LINE> return data <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> data = self._buf[:i] <NEW_LINE> self._buf = self._buf[i:] <NEW_LINE> return data <NEW_LINE> <DEDENT> def readlines(self, hint=None): <NEW_LINE> <INDENT> if self._iter is None: <NEW_LINE> <INDENT> raise IOError('read from closed file') <NEW_LINE> <DEDENT> return list(self) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._iter = None <NEW_LINE> self._buf = None
A file like-object wrapping an iterator that yields strings. Take an iterable, for example: >>> def hello_iter(): ... yield 'hello ' ... yield 'world!' ... Wrap it in IterFile, and turn it into a file-like object: >>> file_like = IterFile(hello_iter()) >>> file_like.read() 'hello world!'
62598fa3be8e80087fbbeefe
class RateCountModel(BaseModel): <NEW_LINE> <INDENT> __tablename__ = 'rate_count' <NEW_LINE> category = Column('category', Enum(UserCategory)) <NEW_LINE> problem_uid = Column('problem_uid', Integer, ForeignKey(ProblemModel.uid, onupdate='CASCADE', ondelete='CASCADE')) <NEW_LINE> index = Column('index', Integer, index=True) <NEW_LINE> count = Column('count', Integer) <NEW_LINE> score = Column('score', Integer) <NEW_LINE> __primarykey__ = [category, problem_uid, index]
Rate accepted count model.
62598fa30c0af96317c5621f
class ObjectTypeMibTableTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> ast = parserFactory()().parse(self.__class__.__doc__)[0] <NEW_LINE> mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True) <NEW_LINE> self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, {mibInfo.name: symtable}, genTexts=True) <NEW_LINE> codeobj = compile(pycode, 'test', 'exec') <NEW_LINE> self.ctx = {'mibBuilder': MibBuilder()} <NEW_LINE> exec(codeobj, self.ctx, self.ctx) <NEW_LINE> <DEDENT> def testObjectTypeTableClass(self): <NEW_LINE> <INDENT> self.assertEqual( self.ctx['testTable'].__class__.__name__, 'MibTable', 'bad table class' ) <NEW_LINE> <DEDENT> def testObjectTypeTableRowClass(self): <NEW_LINE> <INDENT> self.assertEqual( self.ctx['testEntry'].__class__.__name__, 'MibTableRow', 'bad table row class' ) <NEW_LINE> <DEDENT> def testObjectTypeTableColumnClass(self): <NEW_LINE> <INDENT> self.assertEqual( self.ctx['testIndex'].__class__.__name__, 'MibTableColumn', 'bad table column class' ) <NEW_LINE> <DEDENT> def testObjectTypeTableRowIndex(self): <NEW_LINE> <INDENT> self.assertEqual( self.ctx['testEntry'].getIndexNames(), ((0, 'TEST-MIB', 'testIndex'),), 'bad table index' )
TEST-MIB DEFINITIONS ::= BEGIN IMPORTS OBJECT-TYPE FROM SNMPv2-SMI; testTable OBJECT-TYPE SYNTAX SEQUENCE OF TestEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Test table" ::= { 1 3 } testEntry OBJECT-TYPE SYNTAX TestEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Test row" INDEX { testIndex } ::= { testTable 1 } TestEntry ::= SEQUENCE { testIndex INTEGER, testValue OCTET STRING } testIndex OBJECT-TYPE SYNTAX INTEGER MAX-ACCESS read-create STATUS current DESCRIPTION "Test column" ::= { testEntry 1 } testValue OBJECT-TYPE SYNTAX OCTET STRING MAX-ACCESS read-create STATUS current DESCRIPTION "Test column" ::= { testEntry 2 } END
62598fa367a9b606de545e68
class Requirements(object): <NEW_LINE> <INDENT> def __init__(self, is_admin=None, services=None): <NEW_LINE> <INDENT> self.is_admin = is_admin <NEW_LINE> self.services = services or ["trove"] <NEW_LINE> self.services = [str(service) for service in self.services] <NEW_LINE> <DEDENT> def satisfies(self, reqs): <NEW_LINE> <INDENT> if reqs.is_admin is not None: <NEW_LINE> <INDENT> if reqs.is_admin != self.is_admin: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> for service in reqs.services: <NEW_LINE> <INDENT> if service not in self.services: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "is_admin=%s, services=%s" % (self.is_admin, self.services)
Defines requirements a test has of a user.
62598fa3d7e4931a7ef3bf38
class didyoumean_contextmanager(object): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, type_, value, traceback): <NEW_LINE> <INDENT> assert (type_ is None) == (value is None) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> if isinstance(value, type_): <NEW_LINE> <INDENT> add_suggestions_to_exception(type_, value, traceback) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> value = type_(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = type_(*value) <NEW_LINE> <DEDENT> add_suggestions_to_exception(type_, value, traceback) <NEW_LINE> raise value
Context manager to add suggestions to exceptions. To use it, create a context: with didyoumean_contextmanager(): some_code.
62598fa34f88993c371f0459
class CallTime: <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> self.Entries = [] <NEW_LINE> <DEDENT> def Measure(self, args, avs): <NEW_LINE> <INDENT> time_start = timeit.default_timer() <NEW_LINE> retval = self.func(*args) <NEW_LINE> time_end = timeit.default_timer() <NEW_LINE> self.Entries.append([self.func.__name__, time_end - time_start, avs] ) <NEW_LINE> return retval <NEW_LINE> <DEDENT> def AppendToLastEntry(self, val): <NEW_LINE> <INDENT> if len(self.Entries) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> entry = self.Entries[ len(self.Entries) - 1 ] <NEW_LINE> if entry[2] is None: <NEW_LINE> <INDENT> entry[2] = [val] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entry[2].append(val) <NEW_LINE> <DEDENT> <DEDENT> def Save_Append(self, filename): <NEW_LINE> <INDENT> with open(filename, "a") as FileObject: <NEW_LINE> <INDENT> for entry in self.Entries: <NEW_LINE> <INDENT> str_func = entry[0] <NEW_LINE> str_time = str(entry[1]) <NEW_LINE> str_avs = "" <NEW_LINE> if not entry[2] is None: <NEW_LINE> <INDENT> for av in entry[2]: <NEW_LINE> <INDENT> str_avs += ", " + str(av) <NEW_LINE> <DEDENT> <DEDENT> FileObject.write( str_func + ", " + str_time + str_avs + "\n" ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def Measure_Single( func, args, avs): <NEW_LINE> <INDENT> time_start = timeit.default_timer() <NEW_LINE> retval = func(*args) <NEW_LINE> time_end = timeit.default_timer() <NEW_LINE> print_str = func.__name__ + ", " + str(time_end - time_start) <NEW_LINE> if not avs is None: <NEW_LINE> <INDENT> for av in avs: <NEW_LINE> <INDENT> print_str += ", " + str(av) <NEW_LINE> <DEDENT> <DEDENT> print( print_str ) <NEW_LINE> return retval
Description: Simple timer class. Time function calls and saves to CSV file. Usage: func = CallTime.Test args = (1, 2, 3) CallTime.Measure_Single( func, args, args ) or func = Test # any valid function name ... args = (1, 2, 3) obj_ct = CallTime(func) obj_ct.Measure( args, args ) obj_ct.Measure( args, None ) obj_ct.Save_Append( "ct-test.txt" )
62598fa37047854f4633f276
class PasswordChangeView(LoginRequiredMixin, SuccessMessageMixin, FormView): <NEW_LINE> <INDENT> template_name = 'change_password.html' <NEW_LINE> model = User <NEW_LINE> form_class = PasswordChangeForm <NEW_LINE> success_url = reverse_lazy('accounts:password_change_done') <NEW_LINE> def get_form_kwargs(self): <NEW_LINE> <INDENT> kwargs = super().get_form_kwargs() <NEW_LINE> kwargs['user'] = self.request.user <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> form.save() <NEW_LINE> update_session_auth_hash(self.request, form.user) <NEW_LINE> return super().form_valid(form)
更新密码(登录状态下,个人修改自己的密码) https://docs.djangoproject.com/zh-hans/2.2/topics/auth/customizing/ https://it.ismy.fun/2019/08/09/django-change-password-views/ 密码修改后不会自动退出
62598fa3009cb60464d013c2
class TradeChannelCheckFail(CommandError): <NEW_LINE> <INDENT> pass
Exception raised checks.tradereport fails
62598fa399cbb53fe6830d72
class CropRenderer(BaseRenderer): <NEW_LINE> <INDENT> def __init__(self, width, height, bleed=0., *args, **kwargs): <NEW_LINE> <INDENT> self.width = int(width) <NEW_LINE> self.height = int(height) <NEW_LINE> self.bleed = float(bleed) <NEW_LINE> super(CropRenderer, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return ( self.bleed == other.bleed and self.width == other.width and self.height == other.height ) <NEW_LINE> <DEDENT> def deconstruct(self): <NEW_LINE> <INDENT> path,args,kwargs = super(CropRenderer,self).deconstruct() <NEW_LINE> args = (self.width, self.height) + args <NEW_LINE> kwargs.update({ 'bleed':self.bleed, }) <NEW_LINE> return path,args,kwargs <NEW_LINE> <DEDENT> def _render(self, image): <NEW_LINE> <INDENT> return ImageOps.fit(image, (self.width, self.height), Image.ANTIALIAS, self.bleed, (0.5, 0.5))
Renders an image cropped to a given width and height.
62598fa3cc0a2c111447aead
class TempgresDatabaseService: <NEW_LINE> <INDENT> def __init__(self, url, **kwargs): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.response = None <NEW_LINE> self.data = kwargs <NEW_LINE> if self.url: <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> logger.warning( "Tempgres will use the database information " "which has been supllied in kwargs!" ) <NEW_LINE> <DEDENT> self._post() <NEW_LINE> <DEDENT> if self.response is None: <NEW_LINE> <INDENT> if not kwargs: <NEW_LINE> <INDENT> raise ValueError("Data dictionary must be supplied") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._parse() <NEW_LINE> <DEDENT> <DEDENT> def _post(self): <NEW_LINE> <INDENT> self.response = requests.post(url=self.url) <NEW_LINE> if not (self.response.status_code == requests.codes.ok): <NEW_LINE> <INDENT> self.response.raise_for_status() <NEW_LINE> <DEDENT> <DEDENT> def _parse(self): <NEW_LINE> <INDENT> if (self.response is None): <NEW_LINE> <INDENT> raise ValueError("No response exsists!") <NEW_LINE> <DEDENT> parsed = self.response.text.splitlines() <NEW_LINE> if not (len(parsed) == 5): <NEW_LINE> <INDENT> raise TypeError("Response does not conform to expected format!") <NEW_LINE> <DEDENT> self.data['USER'] = parsed[0] <NEW_LINE> self.data['PASSWORD'] = parsed[1] <NEW_LINE> self.data['HOST'] = parsed[2] <NEW_LINE> self.data['PORT'] = parsed[3] <NEW_LINE> self.data['NAME'] = parsed[4] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> a = [] <NEW_LINE> for k in self.data.keys(): <NEW_LINE> <INDENT> a.append("{}: {}".format(k, self.data[k])) <NEW_LINE> <DEDENT> return "\n".join(a) <NEW_LINE> <DEDENT> def setdefault(self, key, value): <NEW_LINE> <INDENT> return self.data.setdefault(key, value) <NEW_LINE> <DEDENT> def __getitem__(self, value): <NEW_LINE> <INDENT> return self.data[value] <NEW_LINE> <DEDENT> def __contains__(self, value): <NEW_LINE> <INDENT> return value in self.data <NEW_LINE> <DEDENT> def get(self, key, value=None): <NEW_LINE> <INDENT> return self.data.get(key, value)
Connection to a tempgres service instance defined by an URL.
62598fa357b8e32f5250806a
class BaseCompound(Expression): <NEW_LINE> <INDENT> __slots__ = 'terms', <NEW_LINE> operator = None <NEW_LINE> def __init__(self, terms): <NEW_LINE> <INDENT> self.terms = terms <NEW_LINE> <DEDENT> def _render(self): <NEW_LINE> <INDENT> scoped_terms = [term.render(self.precedence) for term in self.terms] <NEW_LINE> if len(scoped_terms) == 1: <NEW_LINE> <INDENT> return scoped_terms[0] <NEW_LINE> <DEDENT> if len(self.terms) > 4 or any(isinstance(t, (BaseCompound, NamedSubquery, InSet)) for t in self.terms): <NEW_LINE> <INDENT> delim = ' {}\n'.format(self.operator) <NEW_LINE> indented = [self.indent(t) for t in scoped_terms] <NEW_LINE> return delim.join(indented).lstrip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> delim = ' {} '.format(self.operator) <NEW_LINE> return delim.join(scoped_terms).lstrip()
Combine multiple expressions with a single operator.
62598fa33539df3088ecc152
class BinaryClassifier(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_features, hidden_dim, output_dim): <NEW_LINE> <INDENT> super(BinaryClassifier, self).__init__() <NEW_LINE> self.fc1 = nn.Linear(input_features, hidden_dim) <NEW_LINE> self.fc2 = nn.Linear(hidden_dim, output_dim) <NEW_LINE> self.dropout = nn.Dropout(0.3) <NEW_LINE> self.sigmoid = nn.Sigmoid() <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> relu = F.relu(self.fc1(x)) <NEW_LINE> relu = self.dropout(relu) <NEW_LINE> relu = self.fc2(out) <NEW_LINE> class_score = self.sigmoid(relu) <NEW_LINE> return class_score
Define a neural network that performs binary classification. The network should accept your number of features as input, and produce a single sigmoid value, that can be rounded to a label: 0 or 1, as output. Notes on training: To train a binary classifier in PyTorch, use BCELoss. BCELoss is binary cross entropy loss, documentation: https://pytorch.org/docs/stable/nn.html#torch.nn.BCELoss
62598fa33cc13d1c6d46560a
class GunExperiment(GaussianExperiment): <NEW_LINE> <INDENT> def _get_data(self, model=None, *args, **kwargs): <NEW_LINE> <INDENT> sim = Gun(**kwargs) <NEW_LINE> simdata = sim({'eos': model}) <NEW_LINE> return simdata[0], simdata[1][0], np.zeros(simdata[0].shape) <NEW_LINE> <DEDENT> def get_sigma(self): <NEW_LINE> <INDENT> return np.diag(np.ones(self.shape()) * self.get_option('exp_var'))
A class representing pseudo experimental data for a gun show
62598fa3460517430c431faa
class MSWingParms(XMLContainer): <NEW_LINE> <INDENT> XMLTAG = 'Mswing_Parms' <NEW_LINE> total_span = Float(low=0.1, high=10000., iotype='in', xmltag='Total_Span', desc='') <NEW_LINE> total_proj_span = Float(low=0.1, high=10000., iotype='in', xmltag='Total_Proj_Span', desc='') <NEW_LINE> avg_chord = Float(low=0.1, high=10000., iotype='in', xmltag='Avg_Chord', desc='Average chord.') <NEW_LINE> total_area = Float(low=1., high=1000000., iotype='in', xmltag='Total_Area', desc='') <NEW_LINE> sweep_off = Float(iotype='in', xmltag='Sweep_Off', desc='Sweep offset.') <NEW_LINE> rounded_tips = Bool(False, iotype='in', xmltag='Round_End_Cap_Flag', desc='') <NEW_LINE> deg_per_seg = Int(9, low=1, high=30, units='deg', iotype='in', xmltag='Deg_Per_Seg', desc='Degrees per segment in blend.') <NEW_LINE> max_num_segs = Int(iotype='in', xmltag='Max_Num_Seg', desc='Max number of segments in blend.') <NEW_LINE> rel_dihedral_flag = Bool(False, iotype='in', xmltag='Rel_Dihedral_Flag', desc='') <NEW_LINE> rel_twist_flag = Bool(False, iotype='in', xmltag='Rel_Twist_Flag', desc='') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(MSWingParms, self).__init__(self.XMLTAG)
XML parameters specific to a Multi-Section Wing.
62598fa3e5267d203ee6b7ab
class Responses(Route): <NEW_LINE> <INDENT> name = "form_responses" <NEW_LINE> path = "/{form_id:str}/responses" <NEW_LINE> @requires(["authenticated"]) <NEW_LINE> @api.validate( resp=Response(HTTP_200=ResponseList), tags=["forms", "responses"] ) <NEW_LINE> async def get(self, request: Request) -> JSONResponse: <NEW_LINE> <INDENT> form_id = request.path_params["form_id"] <NEW_LINE> await discord.verify_response_access(form_id, request) <NEW_LINE> cursor = request.state.db.responses.find( {"form_id": form_id} ) <NEW_LINE> responses = [ FormResponse(**response) for response in await cursor.to_list(None) ] <NEW_LINE> return JSONResponse([response.dict() for response in responses]) <NEW_LINE> <DEDENT> @requires(["authenticated", "admin"]) <NEW_LINE> @api.validate( json=ResponseIdList, resp=Response( HTTP_200=OkayResponse, HTTP_404=ErrorMessage, HTTP_400=ErrorMessage ), tags=["forms", "responses"] ) <NEW_LINE> async def delete(self, request: Request) -> JSONResponse: <NEW_LINE> <INDENT> if not await request.state.db.forms.find_one( {"_id": request.path_params["form_id"]} ): <NEW_LINE> <INDENT> return JSONResponse({"error": "not_found"}, status_code=404) <NEW_LINE> <DEDENT> data = await request.json() <NEW_LINE> response_ids = ResponseIdList(**data) <NEW_LINE> ids = set(response_ids.ids) <NEW_LINE> cursor = request.state.db.responses.find( {"_id": {"$in": list(ids)}} ) <NEW_LINE> entries = [ FormResponse(**submission) for submission in await cursor.to_list(None) ] <NEW_LINE> actual_ids = {entry.id for entry in entries} <NEW_LINE> if len(ids) != len(actual_ids): <NEW_LINE> <INDENT> return JSONResponse( { "error": "responses_not_found", "ids": list(ids - actual_ids) }, status_code=404 ) <NEW_LINE> <DEDENT> if any(entry.form_id != request.path_params["form_id"] for entry in entries): <NEW_LINE> <INDENT> return JSONResponse( { "error": "wrong_form", "ids": list( entry.id for entry in entries if entry.id != request.path_params["form_id"] ) }, status_code=400 ) <NEW_LINE> <DEDENT> await request.state.db.responses.delete_many( { "_id": {"$in": list(actual_ids)} } ) <NEW_LINE> return JSONResponse({"status": "ok"})
Returns all form responses by form ID.
62598fa39c8ee823130400be
class Sim(Treant): <NEW_LINE> <INDENT> _treanttype = 'Sim' <NEW_LINE> def __init__(self, sim, categories=None, tags=None): <NEW_LINE> <INDENT> super(Sim, self).__init__(sim, categories=categories, tags=tags) <NEW_LINE> self._universedef = metadata.UniverseDefinition(self) <NEW_LINE> self._universe = None <NEW_LINE> self._args = None <NEW_LINE> self._atomselections = metadata.AtomSelections(self, parent=self) <NEW_LINE> self._make_simdir() <NEW_LINE> self._data = Data(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<{}: '{}'>".format(self._treanttype, self.name) <NEW_LINE> <DEDENT> def _make_simdir(self): <NEW_LINE> <INDENT> abspath = self._path.absolute() <NEW_LINE> simdir = abspath / os.path.join(TREANTDIR_NAME, SIMDIR_NAME) <NEW_LINE> if not simdir.exists(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> makedirs(simdir, exist_ok=True) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno == 13: <NEW_LINE> <INDENT> raise OSError(13, "Permission denied; " + "cannot create '{}'".format(simdir)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def _simdir(self): <NEW_LINE> <INDENT> return os.path.join(self.abspath, TREANTDIR_NAME, SIMDIR_NAME) <NEW_LINE> <DEDENT> @property <NEW_LINE> def universe(self): <NEW_LINE> <INDENT> _args = self.universedef._args <NEW_LINE> if _args != self._args: <NEW_LINE> <INDENT> self._args = _args <NEW_LINE> kwargs = self.universedef.kwargs <NEW_LINE> if _args is None: <NEW_LINE> <INDENT> self._universe = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._universe = mda.Universe(*_args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return self._universe <NEW_LINE> <DEDENT> @universe.setter <NEW_LINE> def universe(self, universe): <NEW_LINE> <INDENT> self.universedef.update(universe) <NEW_LINE> self._universe = universe <NEW_LINE> <DEDENT> @property <NEW_LINE> def universedef(self): <NEW_LINE> <INDENT> return self._universedef <NEW_LINE> <DEDENT> @property <NEW_LINE> def atomselections(self): <NEW_LINE> <INDENT> return self._atomselections <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data
The Sim object is an interface to data for a single simulation. `sim` should be a base directory of a new or existing Sim. An existing Sim will be regenerated if a state file is found. If no state file is found, a new Sim will be created. A Tree object may also be used in the same way as a directory string. If multiple Treant state files are in the given directory, a :exc:`MultipleTreantsError` will be raised; specify the full path to the desired state file to regenerate the desired Treant in this case. It is generally better to avoid having multiple state files in the same directory. Use the `new` keyword to force generation of a new Sim at the given path. Parameters ---------- sim : str or Tree Base directory of a new or existing Sim; will regenerate a Sim if a state file is found, but will genereate a new one otherwise; may also be a Tree object categories : dict dictionary with user-defined keys and values; used to give Sims distinguishing characteristics tags : list list with user-defined values; like categories, but useful for adding many distinguishing descriptors
62598fa37047854f4633f277
class UnorderedLaminate(MembraneLaminate): <NEW_LINE> <INDENT> def is_symmetric(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def __init__(self, layup, material): <NEW_LINE> <INDENT> assert isinstance(material, TransverseIsotropicPlyMaterial) <NEW_LINE> assert all(isinstance(x, tuple) for x in layup) <NEW_LINE> assert all(c > 0 for (a, c) in layup) <NEW_LINE> self._material = material <NEW_LINE> self._layup = layup <NEW_LINE> d = {} <NEW_LINE> for (a, c) in layup: <NEW_LINE> <INDENT> if a in d: <NEW_LINE> <INDENT> d[a] += c <NEW_LINE> <DEDENT> else: d[a] = c <NEW_LINE> <DEDENT> unique_layup = sorted(d.items(), key=lambda x: x[0]) <NEW_LINE> rad_layup = [(math.radians(a), c) for(a, c) in unique_layup] <NEW_LINE> layers = [] <NEW_LINE> for (ang, cnt) in rad_layup: <NEW_LINE> <INDENT> lyr = LayerWithExplicitThickness(self, ang, material, cnt*material.t) <NEW_LINE> layers.append(lyr) <NEW_LINE> <DEDENT> self._layers = tuple(layers) <NEW_LINE> <DEDENT> def get_layer_by_angle(self, alpha_deg): <NEW_LINE> <INDENT> alpha_rad = math.radians(alpha_deg) <NEW_LINE> angles = [layer.angle() for layer in self._layers] <NEW_LINE> try: <NEW_LINE> <INDENT> idx = angles.index(alpha_rad) <NEW_LINE> return self._layers[idx] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def num_layers(self): <NEW_LINE> <INDENT> return len(self._layers)
Defines a laminate where layer count and orientations are given, but not stacking sequence. Works for single material only. Works for in-plane properties only.
62598fa3e5267d203ee6b7ac
class InlineResponse20014(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'message': 'list[str]' } <NEW_LINE> attribute_map = { 'id': 'id', 'message': 'message' } <NEW_LINE> def __init__(self, id=None, message=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._message = None <NEW_LINE> self.discriminator = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if message is not None: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def message(self): <NEW_LINE> <INDENT> return self._message <NEW_LINE> <DEDENT> @message.setter <NEW_LINE> def message(self, message): <NEW_LINE> <INDENT> self._message = message <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(InlineResponse20014, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse20014): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa3e1aae11d1e7ce772
class SystemRebootError(Exception): <NEW_LINE> <INDENT> pass
There was a problem executing a system reboot
62598fa338b623060ffa8f33
@dataclass(order=True) <NEW_LINE> class OkOutgoingMessage(LinterFix): <NEW_LINE> <INDENT> Schema: ClassVar[Type[marshmallow.Schema]] = marshmallow.Schema <NEW_LINE> recipient: OkRecipient <NEW_LINE> message: OkMessage
Класс данных для хранения информации об исходящем сообщении ОК.
62598fa3a17c0f6771d5c0d8
class LinearTriInterpolator(TriInterpolator): <NEW_LINE> <INDENT> def __init__(self, triangulation, z, trifinder=None): <NEW_LINE> <INDENT> TriInterpolator.__init__(self, triangulation, z, trifinder) <NEW_LINE> self._plane_coefficients = self._triangulation.calculate_plane_coefficients(self._z) <NEW_LINE> self._multi_interp = np.vectorize(self._single_interp, otypes=[np.float]) <NEW_LINE> <DEDENT> def __call__(self, x, y): <NEW_LINE> <INDENT> x = np.asarray(x, dtype=np.float64) <NEW_LINE> y = np.asarray(y, dtype=np.float64) <NEW_LINE> if x.shape != y.shape: <NEW_LINE> <INDENT> raise ValueError("x and y must be equal-shaped arrays") <NEW_LINE> <DEDENT> tris = self._trifinder(x, y) <NEW_LINE> z = self._multi_interp(x, y, tris) <NEW_LINE> return np.ma.masked_invalid(z, copy=False) <NEW_LINE> <DEDENT> def _single_interp(self, x, y, tri): <NEW_LINE> <INDENT> if tri == -1: <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self._plane_coefficients[tri,0] * x + self._plane_coefficients[tri,1] * y + self._plane_coefficients[tri,2])
A LinearTriInterpolator performs linear interpolation on a triangular grid. Each triangle is represented by a plane so that an interpolated value at point (x,y) lies on the plane of the triangle containing (x,y). Interpolated values are therefore continuous across the triangulation, but their first derivatives are discontinuous at edges between triangles.
62598fa344b2445a339b68bd
class HelpedWidget(Frame): <NEW_LINE> <INDENT> def __init__(self, master, help): <NEW_LINE> <INDENT> Frame.__init__(self, master) <NEW_LINE> self.help = help <NEW_LINE> <DEDENT> def helpme(self): <NEW_LINE> <INDENT> from tkMessageBox import showinfo <NEW_LINE> showinfo(self.help, parent=self)
This class simply binds the 'help' function
62598fa3be8e80087fbbef00
class DeliveryMeterSensor(YoulessBaseSensor): <NEW_LINE> <INDENT> _attr_native_unit_of_measurement = ENERGY_KILO_WATT_HOUR <NEW_LINE> _attr_device_class = DEVICE_CLASS_ENERGY <NEW_LINE> _attr_state_class = STATE_CLASS_TOTAL_INCREASING <NEW_LINE> def __init__( self, coordinator: DataUpdateCoordinator, device: str, dev_type: str ) -> None: <NEW_LINE> <INDENT> super().__init__( coordinator, device, "delivery", "Power delivery", f"delivery_{dev_type}" ) <NEW_LINE> self._type = dev_type <NEW_LINE> self._attr_name = f"Power delivery {dev_type}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def get_sensor(self) -> YoulessSensor | None: <NEW_LINE> <INDENT> if self.coordinator.data.delivery_meter is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return getattr(self.coordinator.data.delivery_meter, f"_{self._type}", None)
The Youless delivery meter value sensor.
62598fa3435de62698e9bc94
class ItemsApiTestCasesGetAllItems(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.factory = RequestFactory() <NEW_LINE> test_utils.setup() <NEW_LINE> test_utils.create_dummyuser() <NEW_LINE> test_utils.create_items("Item A") <NEW_LINE> test_utils.create_items("Item B") <NEW_LINE> test_utils.create_api_token(timezone.now() + timezone.timedelta(hours=1)) <NEW_LINE> <DEDENT> def test_items_view_valid_token_and_request_exp_200(self): <NEW_LINE> <INDENT> request = self.factory.get("/items/") <NEW_LINE> request.META["HTTP_AUTHORIZATION"] = "APIToken" <NEW_LINE> response = items.items_view(request) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK)
TestCase for items view
62598fa3236d856c2adc938a
class BartEncoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, config: BartConfig, embed_tokens): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.dropout = config.dropout <NEW_LINE> self.layerdrop = config.encoder_layerdrop <NEW_LINE> embed_dim = embed_tokens.embedding_dim <NEW_LINE> self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0 <NEW_LINE> self.padding_idx = embed_tokens.padding_idx <NEW_LINE> self.max_source_positions = config.max_position_embeddings <NEW_LINE> self.embed_tokens = embed_tokens <NEW_LINE> if config.static_position_embeddings: <NEW_LINE> <INDENT> self.embed_positions = SinusoidalPositionalEmbedding( config.max_position_embeddings, embed_dim, self.padding_idx ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.embed_positions = LearnedPositionalEmbedding( config.max_position_embeddings, embed_dim, self.padding_idx, config.extra_pos_embeddings, ) <NEW_LINE> <DEDENT> self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.encoder_layers)]) <NEW_LINE> self.layernorm_embedding = LayerNorm(embed_dim) if config.normalize_embedding else nn.Identity() <NEW_LINE> self.layer_norm = LayerNorm(config.d_model) if config.add_final_layer_norm else None <NEW_LINE> <DEDENT> def forward( self, input_ids, attention_mask=None, output_attentions=False, output_hidden_states=False, return_dict=False ): <NEW_LINE> <INDENT> if attention_mask is not None: <NEW_LINE> <INDENT> attention_mask = invert_mask(attention_mask) <NEW_LINE> <DEDENT> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <NEW_LINE> embed_pos = self.embed_positions(input_ids) <NEW_LINE> x = inputs_embeds + embed_pos <NEW_LINE> x = self.layernorm_embedding(x) <NEW_LINE> x = F.dropout(x, p=self.dropout, training=self.training) <NEW_LINE> x = x.transpose(0, 1) <NEW_LINE> encoder_states = [] if output_hidden_states else None <NEW_LINE> all_attentions = () if output_attentions else None <NEW_LINE> for encoder_layer in self.layers: <NEW_LINE> <INDENT> if output_hidden_states: <NEW_LINE> <INDENT> encoder_states.append(x) <NEW_LINE> <DEDENT> dropout_probability = random.uniform(0, 1) <NEW_LINE> if self.training and (dropout_probability < self.layerdrop): <NEW_LINE> <INDENT> attn = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x, attn = encoder_layer(x, attention_mask, output_attentions=output_attentions) <NEW_LINE> <DEDENT> if output_attentions: <NEW_LINE> <INDENT> all_attentions = all_attentions + (attn,) <NEW_LINE> <DEDENT> <DEDENT> if self.layer_norm: <NEW_LINE> <INDENT> x = self.layer_norm(x) <NEW_LINE> <DEDENT> if output_hidden_states: <NEW_LINE> <INDENT> encoder_states.append(x) <NEW_LINE> encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states) <NEW_LINE> <DEDENT> x = x.transpose(0, 1) <NEW_LINE> if not return_dict: <NEW_LINE> <INDENT> return tuple(v for v in [x, encoder_states, all_attentions] if v is not None) <NEW_LINE> <DEDENT> return BaseModelOutput(last_hidden_state=x, hidden_states=encoder_states, attentions=all_attentions)
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a :class:`EncoderLayer`. Args: config: BartConfig
62598fa3adb09d7d5dc0a42a
class Dummy1x1ExampleBottomShortcutsWidget(Dummy1x1ExampleMainWidget): <NEW_LINE> <INDENT> placeholder_uid = 'bottom_shortcuts'
Dummy1x1 plugin widget for Example layout (placeholder `bottom_shortcuts`).
62598fa307f4c71912baf2e3
class SubWorkflow1(WorkflowRunner) : <NEW_LINE> <INDENT> def workflow(self2) : <NEW_LINE> <INDENT> self2.addTask("A",getSleepCmd()+["5"]) <NEW_LINE> self2.addTask("B","boogyman!",dependencies="A")
This workflow should fail.
62598fa38e7ae83300ee8f40
class OBJECT_OT_images_half_res(Operator): <NEW_LINE> <INDENT> bl_idname = "apogee.textures_half_size" <NEW_LINE> bl_label = "half size textures" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> preferences = context.preferences <NEW_LINE> addon_prefs = preferences.addons[__name__].preferences <NEW_LINE> change_images_path(self, context,resolution=addon_prefs.half_res) <NEW_LINE> return {'FINISHED'}
Change the path of all the textures in file to half of their resolution
62598fa376e4537e8c3ef44c
class GPMeanFunction(ABC): <NEW_LINE> <INDENT> def __init__(self, input_dim: int, use_single_gp: bool = False): <NEW_LINE> <INDENT> self.dimensionality = tf.constant(input_dim, dtype=tf.int32) <NEW_LINE> self._initialize_variables(use_single_gp) <NEW_LINE> return <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _initialize_variables(self, use_single_gp: bool = False) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def compute_mean_function(self, xx: tf.Tensor) -> tf.Tensor: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def compute_derivative_mean_function(self, xx: tf.Tensor) -> tf.Tensor: <NEW_LINE> <INDENT> pass
Abstract class for the mean functions in the GP.
62598fa3627d3e7fe0e06d4c
class TestResp2448145Root(): <NEW_LINE> <INDENT> def test_resp2448145_root_serialization(self): <NEW_LINE> <INDENT> resp2448145_root_model_json = {} <NEW_LINE> resp2448145_root_model_json['active'] = True <NEW_LINE> resp2448145_root_model_json['enabled'] = True <NEW_LINE> resp2448145_root_model_json['last_active'] = 38 <NEW_LINE> resp2448145_root_model = Resp2448145Root.from_dict(resp2448145_root_model_json) <NEW_LINE> assert resp2448145_root_model != False <NEW_LINE> resp2448145_root_model_dict = Resp2448145Root.from_dict(resp2448145_root_model_json).__dict__ <NEW_LINE> resp2448145_root_model2 = Resp2448145Root(**resp2448145_root_model_dict) <NEW_LINE> assert resp2448145_root_model == resp2448145_root_model2 <NEW_LINE> resp2448145_root_model_json2 = resp2448145_root_model.to_dict() <NEW_LINE> assert resp2448145_root_model_json2 == resp2448145_root_model_json
Test Class for Resp2448145Root
62598fa3dd821e528d6d8dd4
class AmcData(object): <NEW_LINE> <INDENT> logger = logging.getLogger('AmcData') <NEW_LINE> logger.setLevel(logging.DEBUG) <NEW_LINE> formatter = logging.Formatter('%(levelname)s %(asctime)s %(name)s Line: %(lineno)d | %(message)s') <NEW_LINE> handler = logging.StreamHandler() <NEW_LINE> handler.setFormatter(formatter) <NEW_LINE> logger.addHandler(handler) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.frames = OrderedDict()
This is a class that contains data in the AMC Mocap data format.
62598fa33539df3088ecc154
class TestFloat: <NEW_LINE> <INDENT> obj = 4.2 <NEW_LINE> common = [ (obj, obj), (None, 0.0), ("1.0", 1.0), ("1.1", 1.1), ] <NEW_LINE> data_value = [ ] + common <NEW_LINE> value_data = [ ] + common <NEW_LINE> @pytest.mark.parametrize("data,value", data_value) <NEW_LINE> def test_to_value(self, data, value): <NEW_LINE> <INDENT> assert value == Float.to_value(data) <NEW_LINE> <DEDENT> def test_to_value_error(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> Integer.to_value("abc") <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.parametrize("value,data", value_data) <NEW_LINE> def test_to_data(self, value, data): <NEW_LINE> <INDENT> assert data == Float.to_data(value)
Unit tests for the `Float` converter.
62598fa3a8370b77170f027a
class LPStorage(JSONLP): <NEW_LINE> <INDENT> def __init__( self, name, capacity: int, var_capacity: Union[Variable, float], flow_in: float, var_flow_in: Union[Variable, float], flow_out: float, var_flow_out: Union[Variable, float], cost: float = 0, init_capacity: int = 0, eff: float = 0.99, ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.capacity = capacity <NEW_LINE> self.var_capacity = var_capacity <NEW_LINE> self.flow_in = flow_in <NEW_LINE> self.var_flow_in = var_flow_in <NEW_LINE> self.flow_out = flow_out <NEW_LINE> self.var_flow_out = var_flow_out <NEW_LINE> self.cost = cost <NEW_LINE> self.init_capacity = init_capacity <NEW_LINE> self.eff = eff <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(dict, factory=None): <NEW_LINE> <INDENT> return LPStorage(**dict)
Storage element
62598fa316aa5153ce4003a2
class EntityFormatter(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _list_objects(obj_list): <NEW_LINE> <INDENT> columns = [] <NEW_LINE> data = (obj._get_generic_data() for obj in obj_list) <NEW_LINE> if obj_list: <NEW_LINE> <INDENT> columns = obj_list[0]._get_generic_columns() <NEW_LINE> <DEDENT> return columns, data <NEW_LINE> <DEDENT> def _get_generic_data(self): <NEW_LINE> <INDENT> return self._get_formatted_data() <NEW_LINE> <DEDENT> def _get_generic_columns(self): <NEW_LINE> <INDENT> return self.columns <NEW_LINE> <DEDENT> def _get_formatted_entity(self): <NEW_LINE> <INDENT> return self.columns, self._get_formatted_data() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> data = self._get_formatted_data() <NEW_LINE> table = prettytable.PrettyTable(field_names=('Field', 'Value'), print_empty=False) <NEW_LINE> table.padding_width = 1 <NEW_LINE> table.align['Field'] = 'l' <NEW_LINE> table.align['Value'] = 'l' <NEW_LINE> for name, value in zip(self.columns, data): <NEW_LINE> <INDENT> table.add_row((name, value)) <NEW_LINE> <DEDENT> return table.get_string(fields=('Field', 'Value')) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> columns, data = self._get_formatted_entity() <NEW_LINE> return dict((key, value) for (key, value) in zip(columns, data))
Base Mixin class providing functions that format entities for display. Must be used in conjunction with a Formatter mixin that provides the function _get_formatted_data().
62598fa3aad79263cf42e680
class CreateTokenRequest(object): <NEW_LINE> <INDENT> _names = { "mtype":'type', "card":'card' } <NEW_LINE> def __init__(self, mtype='card', card=None): <NEW_LINE> <INDENT> self.mtype = mtype <NEW_LINE> self.card = card <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dictionary(cls, dictionary): <NEW_LINE> <INDENT> if dictionary is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> mtype = dictionary.get("type") if dictionary.get("type") else 'card' <NEW_LINE> card = mundiapi.models.create_card_token_request.CreateCardTokenRequest.from_dictionary(dictionary.get('card')) if dictionary.get('card') else None <NEW_LINE> return cls(mtype, card)
Implementation of the 'CreateTokenRequest' model. Token data Attributes: mtype (string): Token type card (CreateCardTokenRequest): Card data
62598fa33d592f4c4edbad6e
class LaunchApkTool: <NEW_LINE> <INDENT> __DIRECTORY = "apktool" <NEW_LINE> __FILE = "apktool.jar" <NEW_LINE> def __init__(self, logger: Logger = default_logger): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.apktool = os.path.join( os.path.dirname(__file__), "..", LaunchApkTool.__DIRECTORY, LaunchApkTool.__FILE ) <NEW_LINE> self.logger.debug("apktool path: %s", self.apktool) <NEW_LINE> <DEDENT> def execute(self, input_filepath: str, output_directory: str): <NEW_LINE> <INDENT> self.logger.info("Executing apktool...") <NEW_LINE> self.logger.info("Creating %s/smali/...", output_directory) <NEW_LINE> self.logger.info("Creating %s/AndroidManifest.xml...", output_directory) <NEW_LINE> self.logger.info("Creating %s/res/...", output_directory) <NEW_LINE> self.logger.info("Creating %s/assets/...", output_directory) <NEW_LINE> command = "java -jar {} -q decode -f {} -o {}".format( self.apktool, input_filepath, output_directory ) <NEW_LINE> self.logger.debug("apktool command: `%s`", command) <NEW_LINE> return os.system(command)
Extract the (decrypted) AndroidManifest.xml, the resources and generate the disassembled smali files.
62598fa3d486a94d0ba2be73
class Human(Auxiliary, Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.do_run = True <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.do_run = False <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while self.do_run: <NEW_LINE> <INDENT> move_mouse() <NEW_LINE> click_mouse() <NEW_LINE> USER32.EnumWindows(EnumWindowsProc(foreach_window), 0) <NEW_LINE> KERNEL32.Sleep(1000)
Human after all
62598fa330dc7b766599f6ee
class IoK8sApiCoreV1PersistentVolumeClaimStatus(object): <NEW_LINE> <INDENT> swagger_types = { 'access_modes': 'list[str]', 'capacity': 'dict(str, IoK8sApimachineryPkgApiResourceQuantity)', 'conditions': 'list[IoK8sApiCoreV1PersistentVolumeClaimCondition]', 'phase': 'str' } <NEW_LINE> attribute_map = { 'access_modes': 'accessModes', 'capacity': 'capacity', 'conditions': 'conditions', 'phase': 'phase' } <NEW_LINE> def __init__(self, access_modes=None, capacity=None, conditions=None, phase=None): <NEW_LINE> <INDENT> self._access_modes = None <NEW_LINE> self._capacity = None <NEW_LINE> self._conditions = None <NEW_LINE> self._phase = None <NEW_LINE> if access_modes is not None: <NEW_LINE> <INDENT> self.access_modes = access_modes <NEW_LINE> <DEDENT> if capacity is not None: <NEW_LINE> <INDENT> self.capacity = capacity <NEW_LINE> <DEDENT> if conditions is not None: <NEW_LINE> <INDENT> self.conditions = conditions <NEW_LINE> <DEDENT> if phase is not None: <NEW_LINE> <INDENT> self.phase = phase <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def access_modes(self): <NEW_LINE> <INDENT> return self._access_modes <NEW_LINE> <DEDENT> @access_modes.setter <NEW_LINE> def access_modes(self, access_modes): <NEW_LINE> <INDENT> self._access_modes = access_modes <NEW_LINE> <DEDENT> @property <NEW_LINE> def capacity(self): <NEW_LINE> <INDENT> return self._capacity <NEW_LINE> <DEDENT> @capacity.setter <NEW_LINE> def capacity(self, capacity): <NEW_LINE> <INDENT> self._capacity = capacity <NEW_LINE> <DEDENT> @property <NEW_LINE> def conditions(self): <NEW_LINE> <INDENT> return self._conditions <NEW_LINE> <DEDENT> @conditions.setter <NEW_LINE> def conditions(self, conditions): <NEW_LINE> <INDENT> self._conditions = conditions <NEW_LINE> <DEDENT> @property <NEW_LINE> def phase(self): <NEW_LINE> <INDENT> return self._phase <NEW_LINE> <DEDENT> @phase.setter <NEW_LINE> def phase(self, phase): <NEW_LINE> <INDENT> self._phase = phase <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, IoK8sApiCoreV1PersistentVolumeClaimStatus): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa38c0ade5d55dc35e0
class TransmitShipments(ServiceBase): <NEW_LINE> <INDENT> URL ="https://{server}/rs/{customer}/{mobo}/manifest" <NEW_LINE> log = logging.getLogger('canada_post.service.contract_shipping' '.TransmitShipments') <NEW_LINE> headers = {'Accept': "application/vnd.cpc.manifest-v7+xml", 'Content-Type': 'application/vnd.cpc.manifest-v7+xml', 'Accept-language': 'en-CA', } <NEW_LINE> def get_url(self): <NEW_LINE> <INDENT> return self.URL.format(server=self.get_server(), customer=self.auth.customer_number, mobo=self.auth.customer_number) <NEW_LINE> <DEDENT> def __call__(self, origin, group_ids, name=None, detailed=True, excluded_shipments=[]): <NEW_LINE> <INDENT> transmit = etree.Element( "transmit-set", xmlns="http://www.canadapost.ca/ws/manifest-v7") <NEW_LINE> add_child = add_child_factory(transmit) <NEW_LINE> groups = add_child('group-ids') <NEW_LINE> for group_id in group_ids: <NEW_LINE> <INDENT> add_child('group-id', groups).text = unicode(group_id) <NEW_LINE> <DEDENT> add_child('requested-shipping-point').text = unicode(origin.postal_code) <NEW_LINE> add_child('detailed-manifests').text = 'true' if detailed else 'false' <NEW_LINE> add_child("method-of-payment").text = "Account" <NEW_LINE> address = add_child('manifest-address') <NEW_LINE> add_child('manifest-company', address).text = origin.company <NEW_LINE> if name: <NEW_LINE> <INDENT> add_child('manifest-name', address).text = name <NEW_LINE> <DEDENT> add_child('phone-number', address).text = unicode(origin.phone) <NEW_LINE> details = add_child('address-details', address) <NEW_LINE> add_child('address-line-1', details).text = origin.address1 <NEW_LINE> add_child('address-line-2', details).text = origin.address2 <NEW_LINE> add_child('city', details).text = origin.city <NEW_LINE> add_child('prov-state', details).text = origin.province <NEW_LINE> add_child('postal-zip-code', details).text = unicode(origin.postal_code) <NEW_LINE> if excluded_shipments: <NEW_LINE> <INDENT> excluded = add_child('excluded-shipments') <NEW_LINE> for shipment in excluded_shipments: <NEW_LINE> <INDENT> add_child('shipment-id', excluded).text = unicode(shipment) <NEW_LINE> <DEDENT> <DEDENT> url = self.get_url() <NEW_LINE> self.log.info("Using url %s", url) <NEW_LINE> request = etree.tostring(transmit, pretty_print=self.auth.debug) <NEW_LINE> self.log.debug("Request xml: %s", request) <NEW_LINE> response = requests.post(url=url, data=request, headers=self.headers, auth=self.userpass()) <NEW_LINE> self.log.info("Request returned with status %s", response.status_code) <NEW_LINE> self.log.debug("Request returned content: %s", response.content) <NEW_LINE> if not response.ok: <NEW_LINE> <INDENT> response.raise_for_status() <NEW_LINE> <DEDENT> restree = etree.XML(response.content.replace(' xmlns="', ' xmlnamespace="')) <NEW_LINE> links = [dict(link.attrib) for link in restree.getchildren()] <NEW_LINE> return links
Used to specify shipments to be included in a manifest. Inclusion in a manifest is specified by group. Specific shipments may be excluded if desired. http://www.canadapost.ca/cpo/mc/business/productsservices/developers/services/shippingmanifest/transmitshipments.jsf
62598fa3dd821e528d6d8dd5
class Binding(BindingBase): <NEW_LINE> <INDENT> pass
A binding from an (interface, annotation) to a provider in a scope.
62598fa3cb5e8a47e493c0c7
class Signalizable(GObject.GObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> GObject.GObject.__init__(self) <NEW_LINE> <DEDENT> def install_signal(self, signal): <NEW_LINE> <INDENT> if not GObject.signal_lookup(signal, self.__class__): <NEW_LINE> <INDENT> GObject.signal_new(signal, self.__class__, GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_PYOBJECT,))
This class represents a GObject-like signalized object
62598fa3435de62698e9bc95
class ContextWrapper(object): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.context.push() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self,type,value,traceback): <NEW_LINE> <INDENT> self.context.pop()
Context Manager Wrapper for CUDA Contexts!
62598fa3a8370b77170f027b
class WishartCholesky(_WishartOperatorPD): <NEW_LINE> <INDENT> def __init__(self, df, scale, cholesky_input_output_matrices=False, validate_args=False, allow_nan_stats=True, name="WishartCholesky"): <NEW_LINE> <INDENT> parameters = locals() <NEW_LINE> with ops.name_scope(name, values=[scale]) as ns: <NEW_LINE> <INDENT> super(WishartCholesky, self).__init__( df=df, scale_operator_pd=operator_pd_cholesky.OperatorPDCholesky( scale, verify_pd=validate_args), cholesky_input_output_matrices=cholesky_input_output_matrices, validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=ns) <NEW_LINE> <DEDENT> self._parameters = parameters
The matrix Wishart distribution on positive definite matrices. This distribution is defined by a scalar degrees of freedom `df` and a lower, triangular Cholesky factor which characterizes the scale matrix. Using WishartCholesky is a constant-time improvement over WishartFull. It saves an O(nbk^3) operation, i.e., a matrix-product operation for sampling and a Cholesky factorization in log_prob. For most use-cases it often saves another O(nbk^3) operation since most uses of Wishart will also use the Cholesky factorization. #### Mathematical Details The probability density function (pdf) is, ```none pdf(X; df, scale) = det(X)**(0.5 (df-k-1)) exp(-0.5 tr[inv(scale) X]) / Z Z = 2**(0.5 df k) |det(scale)|**(0.5 df) Gamma_k(0.5 df) ``` where: * `df >= k` denotes the degrees of freedom, * `scale` is a symmetric, positive definite, `k x k` matrix, * `Z` is the normalizing constant, and, * `Gamma_k` is the [multivariate Gamma function]( https://en.wikipedia.org/wiki/Multivariate_gamma_function). #### Examples ```python # Initialize a single 3x3 Wishart with Cholesky factored scale matrix and 5 # degrees-of-freedom.(*) df = 5 chol_scale = tf.cholesky(...) # Shape is [3, 3]. dist = tf.contrib.distributions.WishartCholesky(df=df, scale=chol_scale) # Evaluate this on an observation in R^3, returning a scalar. x = ... # A 3x3 positive definite matrix. dist.prob(x) # Shape is [], a scalar. # Evaluate this on a two observations, each in R^{3x3}, returning a length two # Tensor. x = [x0, x1] # Shape is [2, 3, 3]. dist.prob(x) # Shape is [2]. # Initialize two 3x3 Wisharts with Cholesky factored scale matrices. df = [5, 4] chol_scale = tf.cholesky(...) # Shape is [2, 3, 3]. dist = tf.contrib.distributions.WishartCholesky(df=df, scale=chol_scale) # Evaluate this on four observations. x = [[x0, x1], [x2, x3]] # Shape is [2, 2, 3, 3]. dist.prob(x) # Shape is [2, 2]. # (*) - To efficiently create a trainable covariance matrix, see the example # in tf.contrib.distributions.matrix_diag_transform. ```
62598fa3adb09d7d5dc0a42c
class SpatialRepresentationType(models.Model): <NEW_LINE> <INDENT> identifier = models.CharField(max_length=255, editable=False) <NEW_LINE> description = models.CharField(max_length=255, editable=False) <NEW_LINE> gn_description = models.CharField('GeoNode description', max_length=255) <NEW_LINE> is_choice = models.BooleanField(default=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "{0}".format(self.gn_description) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ("identifier",) <NEW_LINE> verbose_name_plural = 'Metadata Spatial Representation Types'
Metadata information about the spatial representation type. It should reflect a list of codes from TC211 See: http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml <CodeListDictionary gml:id="MD_SpatialRepresentationTypeCode">
62598fa36aa9bd52df0d4d6b
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> apps = [] <NEW_LINE> models_d = {} <NEW_LINE> tables_list = [] <NEW_LINE> for app in settings.INSTALLED_APPS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> app_label = app.split('.')[-1] <NEW_LINE> apps.append(app_label) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> for app_label in apps: <NEW_LINE> <INDENT> if app_label in ['legacy']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not getattr(settings, 'SOCIAL_AUTH_USER_MODEL', None): <NEW_LINE> <INDENT> if app_label in ['social_auth']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> app = get_app(app_label) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> app = None <NEW_LINE> <DEDENT> if app: <NEW_LINE> <INDENT> for model in get_models(app, include_auto_created=True): <NEW_LINE> <INDENT> models_d[model._meta.db_table] = model <NEW_LINE> tables_list.append(model._meta.db_table) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> tables_list.remove('mig_help_files_helpfile_t4_to_t5') <NEW_LINE> if 'auth_message' in tables_list: <NEW_LINE> <INDENT> tables_list.remove('auth_message') <NEW_LINE> <DEDENT> related_tables = {} <NEW_LINE> for table in tables_list: <NEW_LINE> <INDENT> related_tables[table] = [field.remote_field.model._meta.db_table for field in models_d[table]._meta.fields if isinstance(field, (ForeignKey, OneToOneField)) and field.remote_field.model._meta.db_table != table ] <NEW_LINE> <DEDENT> sorted_list = [] <NEW_LINE> for table in tables_list: <NEW_LINE> <INDENT> if not related_tables[table]: <NEW_LINE> <INDENT> sorted_list.append(table) <NEW_LINE> <DEDENT> <DEDENT> n = 100 <NEW_LINE> while n > 1: <NEW_LINE> <INDENT> for key in related_tables: <NEW_LINE> <INDENT> for rel_table in related_tables[key]: <NEW_LINE> <INDENT> if rel_table in sorted_list: <NEW_LINE> <INDENT> related_tables[key].remove(rel_table) <NEW_LINE> <DEDENT> <DEDENT> if not related_tables[key]: <NEW_LINE> <INDENT> del related_tables[key] <NEW_LINE> <DEDENT> <DEDENT> for table in tables_list: <NEW_LINE> <INDENT> if table not in sorted_list and ( table not in related_tables): <NEW_LINE> <INDENT> sorted_list.append(table) <NEW_LINE> <DEDENT> <DEDENT> if not related_tables: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> n = n - 1 <NEW_LINE> <DEDENT> if related_tables: <NEW_LINE> <INDENT> print("ERROR: Sorting not completed.") <NEW_LINE> <DEDENT> print('-', '\n- '.join(sorted_list))
Generate a list of tables and sort them based on the relations for db migration from mysql to postgresql. Usage: manage.py list_tables
62598fa330bbd722464698c8
class UniquePart(models.Model): <NEW_LINE> <INDENT> objects = UniquePartManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('part', 'serial') <NEW_LINE> <DEDENT> part = models.ForeignKey(Part, on_delete=models.CASCADE) <NEW_LINE> creation_date = models.DateField(auto_now_add=True, editable=False) <NEW_LINE> serial = models.IntegerField() <NEW_LINE> customer = models.ForeignKey(Customer, blank=True, null=True) <NEW_LINE> PART_IN_PROGRESS = 0 <NEW_LINE> PART_IN_STOCK = 10 <NEW_LINE> PART_SHIPPED = 20 <NEW_LINE> PART_RETURNED = 30 <NEW_LINE> PART_DAMAGED = 40 <NEW_LINE> PART_DESTROYED = 50 <NEW_LINE> PART_STATUS_CODES = { PART_IN_PROGRESS: _("In progress"), PART_IN_STOCK: _("In stock"), PART_SHIPPED: _("Shipped"), PART_RETURNED: _("Returned"), PART_DAMAGED: _("Damaged"), PART_DESTROYED: _("Destroyed") } <NEW_LINE> status = models.IntegerField(default=PART_IN_PROGRESS, choices=PART_STATUS_CODES.items()) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.part.name
A unique instance of a Part object. Used for tracking parts based on serial numbers, and tracking all events in the life of a part
62598fa38e7ae83300ee8f43
class UserRegSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> code = serializers.CharField(label="验证码", write_only=True, required=True, max_length=4, min_length=4, error_messages={ "blank": "请输入验证码", "required": "请输入验证码", "max_length": "验证码格式错误", "min_length": "验证码格式错误" }, help_text="验证码") <NEW_LINE> username = serializers.CharField(label="用户名", help_text="用户名", required=True, allow_blank=False, validators=[UniqueValidator(queryset=User.objects.all(), message="用户已经存在")]) <NEW_LINE> password = serializers.CharField( style={'input_type': 'password'}, help_text="密码", label="密码", write_only=True, ) <NEW_LINE> def validate_code(self, code): <NEW_LINE> <INDENT> verify_code = VerifyCode.objects.filter(mobile=self.initial_data["username"]).order_by("-add_time") <NEW_LINE> if verify_code: <NEW_LINE> <INDENT> last_record = verify_code[0] <NEW_LINE> five_minute_ago = datetime.now() - timedelta(hours=0, minutes=5, seconds=0) <NEW_LINE> if five_minute_ago > last_record.add_time: <NEW_LINE> <INDENT> raise serializers.ValidationError("验证码过期") <NEW_LINE> <DEDENT> if last_record.code != code: <NEW_LINE> <INDENT> raise serializers.ValidationError("验证码错误") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise serializers.ValidationError("验证码错误") <NEW_LINE> <DEDENT> <DEDENT> def validate(self, attrs): <NEW_LINE> <INDENT> attrs["mobile"] = attrs["username"] <NEW_LINE> del attrs["code"] <NEW_LINE> return attrs <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ("username", "code", "mobile", "password")
用户注册序列化
62598fa33c8af77a43b67e92
class Main(FlyAI): <NEW_LINE> <INDENT> def __init__(self, args, logger): <NEW_LINE> <INDENT> print('main func init') <NEW_LINE> set_seed(cfg.SOLVER.SEED) <NEW_LINE> cfg.OUTPUT_DIR = MODEL_PATH <NEW_LINE> cfg.DATASETS.ROOT_DIR = os.path.join(sys.path[0], 'data', 'input', DataID) <NEW_LINE> os.environ["CUDA_VISIBLE_DEVICES"] = str(cfg.MODEL.DEVICE_ID) <NEW_LINE> self.cfg = cfg <NEW_LINE> self.args = args <NEW_LINE> self.logger = logger <NEW_LINE> <DEDENT> def download_data(self): <NEW_LINE> <INDENT> data_helper = DataHelper() <NEW_LINE> data_helper.download_from_ids("ButterflyClassification") <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> config_file = './configs/'+args.CONFIG <NEW_LINE> self.cfg.merge_from_file(config_file) <NEW_LINE> logger.info("Running with config:\n{}".format(self.cfg)) <NEW_LINE> train_loader, valid_loader, num_class = make_dataloader(self.cfg) <NEW_LINE> model = make_model(self.cfg, num_class) <NEW_LINE> loss_func, center_criterion = make_loss(self.cfg, num_class) <NEW_LINE> optimizer, optimizer_center = make_optimizer( cfg, model, center_criterion) <NEW_LINE> if cfg.SOLVER.TYPE == 'warmup': <NEW_LINE> <INDENT> scheduler = WarmupMultiStepLR(optimizer, self.cfg.SOLVER.STEPS, self.cfg.SOLVER.GAMMA, self.cfg.SOLVER.WARMUP_FACTOR, self.cfg.SOLVER.WARMUP_EPOCHS, self.cfg.SOLVER.WARMUP_METHOD) <NEW_LINE> <DEDENT> elif cfg.SOLVER.TYPE == 'warmup_exp': <NEW_LINE> <INDENT> scheduler_exp = lr_scheduler.ExponentialLR(optimizer, gamma=0.85) <NEW_LINE> scheduler = GradualWarmupScheduler( optimizer, multiplier=10, total_epoch=self.cfg.SOLVER.WARMUP_EPOCHS, after_scheduler=scheduler_exp) <NEW_LINE> <DEDENT> elif cfg.SOLVER.TYPE == 'warmup_cos': <NEW_LINE> <INDENT> scheduler = WarmupCosineLR(optimizer, max_iters=cfg.SOLVER.MAX_EPOCHS, warmup_factor= 0.001, warmup_iters=cfg.SOLVER.WARMUP_EPOCHS ) <NEW_LINE> <DEDENT> if not os.path.exists(self.cfg.TBOUTPUT_DIR): <NEW_LINE> <INDENT> os.mkdir(self.cfg.TBOUTPUT_DIR) <NEW_LINE> <DEDENT> writer = SummaryWriter(self.cfg.TBOUTPUT_DIR, filename_suffix=cfg.MODEL.NAME) <NEW_LINE> self.logger.info('start training') <NEW_LINE> train_val_fun(self.cfg, model, train_loader, valid_loader,loss_func, center_criterion, scheduler, optimizer, optimizer_center, writer, self.logger, val=cfg.IF_VAL) <NEW_LINE> torch.cuda.empty_cache()
项目中必须继承FlyAI类,否则线上运行会报错。
62598fa366673b3332c3026a
class IEC104_IO_C_CI_NA_1(IEC104_IO_Packet): <NEW_LINE> <INDENT> name = 'C_CI_NA_1' <NEW_LINE> _DEFINED_IN = [IEC104_IO_Packet.DEFINED_IN_IEC_101, IEC104_IO_Packet.DEFINED_IN_IEC_104] <NEW_LINE> _IEC104_IO_TYPE_ID = IEC104_IO_ID_C_CI_NA_1 <NEW_LINE> fields_desc = IEC104_IE_QCC.informantion_element_fields
counter interrogation command EN 60870-5-101:2003, sec. 7.3.4.2 (p. 108)
62598fa376e4537e8c3ef44f
class Identifier(object): <NEW_LINE> <INDENT> def set(self, source): <NEW_LINE> <INDENT> self.a, self.formatfile = path.splitext(source) <NEW_LINE> self.d = { '.txt': self.metod_txt, '.format_1': self.metod_2, '.format_2': self.metod_3 }
Суперкласс идентификатор для определения формата переданного файла и координации метода чтения/записи
62598fa367a9b606de545e6d
class TestFunctions(unittest.TestCase): <NEW_LINE> <INDENT> def test_find_grating_insr_retr(self): <NEW_LINE> <INDENT> [action, grating, tstart, tstop] = find_grating_insr_retr(0) <NEW_LINE> k = 100 <NEW_LINE> print(str(action[k]) + '<-->' + str(grating[k]) + '<-->' + str(tstart[k]) + '<-->' + str(tstop[k])) <NEW_LINE> <DEDENT> def test_extract_each_drift_data(self): <NEW_LINE> <INDENT> begin = 646978280 <NEW_LINE> end = 646978300 <NEW_LINE> out = extract_each_drift_data(begin, end) <NEW_LINE> print(str(out[0][0][:10])) <NEW_LINE> <DEDENT> def test_fit_polinom_to_center(self): <NEW_LINE> <INDENT> begin = 646978280 <NEW_LINE> end = 646978300 <NEW_LINE> out = extract_each_drift_data(begin, end) <NEW_LINE> start = 646978291 <NEW_LINE> stop = 646978314 <NEW_LINE> [estimates, diff_data, f_time, sec1, sec2, sec3] = fit_polinom_to_center(out[0], start, stop) <NEW_LINE> print(str(estimates[:10])) <NEW_LINE> print(str(diff_data[:10])) <NEW_LINE> print(str(sec1)) <NEW_LINE> print(str(sec2)) <NEW_LINE> print(str(sec3)) <NEW_LINE> <DEDENT> def test_convert_to_stime(self): <NEW_LINE> <INDENT> ttime = "2000160.04125300" <NEW_LINE> stime = convert_to_stime(ttime) <NEW_LINE> print("TIME FORMAT CONVERSION: " + str(ttime) + '<--->' + str(stime))
testing functions
62598fa3627d3e7fe0e06d4e
class update_managed_post(Updater, GenerateUpdateMixin): <NEW_LINE> <INDENT> def execute(self, **options): <NEW_LINE> <INDENT> (restart, update_list) = self.generate_update(True) <NEW_LINE> return restart, update_list
Update managed entries
62598fa3d7e4931a7ef3bf3d
class ActiveDOMsTask(CnCSingleThreadTask): <NEW_LINE> <INDENT> __NAME = "ActiveDOMs" <NEW_LINE> __PERIOD = 60 <NEW_LINE> REPORT_NAME = "ActiveReport" <NEW_LINE> REPORT_PERIOD = 600 <NEW_LINE> def create_detail_timer(self, task_mgr): <NEW_LINE> <INDENT> return task_mgr.create_interval_timer(self.REPORT_NAME, self.REPORT_PERIOD) <NEW_LINE> <DEDENT> def initialize_thread(self, runset, dashlog, live_moni): <NEW_LINE> <INDENT> return ActiveDOMThread(runset, dashlog, live_moni) <NEW_LINE> <DEDENT> @classproperty <NEW_LINE> def name(cls): <NEW_LINE> <INDENT> return cls.__NAME <NEW_LINE> <DEDENT> @classproperty <NEW_LINE> def period(cls): <NEW_LINE> <INDENT> return cls.__PERIOD <NEW_LINE> <DEDENT> def task_failed(self): <NEW_LINE> <INDENT> self.log_error("ERROR: %s thread seems to be stuck," " monitoring will not be done" % self.name)
Essentially a timer, so every REPORT_PERIOD an ActiveDOMsThread is created and run. This sends three chunks of information off to live: 'totalDOMS' which is a count of the total number of active doms in the array along with a count of the number of doms (active or inactive). 'LBMOverflows' which is a dictionary relating string number to the total number of lbm overflows for a given string
62598fa345492302aabfc372
class HardTripletLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, margin= 1 ): <NEW_LINE> <INDENT> super(HardTripletLoss, self).__init__() <NEW_LINE> self.margin = margin <NEW_LINE> <DEDENT> def forward(self, attributes, embeddings, labels): <NEW_LINE> <INDENT> relations = _pairwise_distance(attributes, embeddings ,labels) <NEW_LINE> mask_pos=_get_anchor_positive_triplet_mask(relations, labels).float() <NEW_LINE> valid_positive_dist = relations * mask_pos <NEW_LINE> hardest_positive_dist, _ = torch.max(valid_positive_dist, 0 ,keepdim=True) <NEW_LINE> mask_neg=_get_anchor_negative_triplet_mask(relations, labels).float() <NEW_LINE> max_anchor_negative_dist, _ = torch.max(relations, 0 , keepdim=True) <NEW_LINE> anchor_negative_dist = relations + max_anchor_negative_dist * (1.0 - mask_neg) <NEW_LINE> hardest_negative_dist, _ = torch.min(anchor_negative_dist, 0 , keepdim=True) <NEW_LINE> triplet_loss_all = F.relu(hardest_positive_dist - hardest_negative_dist + self.margin) <NEW_LINE> num_hard_triplets = torch.sum(torch.gt(triplet_loss_all, 1e-16).float()) <NEW_LINE> triplet_loss = torch.sum(triplet_loss_all) / (num_hard_triplets + 1e-16) <NEW_LINE> return triplet_loss
Hard/Hardest Triplet Loss (pytorch implementation of https://omoindrot.github.io/triplet-loss) For each anchor, we get the hardest positive and hardest negative to form a triplet.
62598fa3d6c5a102081e1fe8
class ImproperXmlFormatError(ProjexError): <NEW_LINE> <INDENT> def __init__( self, location ): <NEW_LINE> <INDENT> msg = '"%s" contains improperly formated xml data.' % location <NEW_LINE> ProjexError.__init__( self, msg )
Thrown when the XML file cannot be parsed.
62598fa3e5267d203ee6b7af
class GroupMeterInviteInfoView(RetrieveAPIView): <NEW_LINE> <INDENT> serializer_class = GroupMeterInviteInfoSerializer <NEW_LINE> GET_permissions = [permissions.IsAuthenticated] <NEW_LINE> lookup_field = 'invitation_key' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return GroupMeter.objects.filter(allow_invite=True)
View to get group meter information when joining a group, based on the invitation key of a group. Available request methods: GET `GET`: Returns basic group meter info to show user what group he is joining
62598fa316aa5153ce4003a4
class ModLogForm(DocumentForm): <NEW_LINE> <INDENT> buffered = BooleanField(required=False) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ModLogForm, self).__init__(*args, **kwargs) <NEW_LINE> self = bootstrap_tooltips(self, exclude='repository_choices') <NEW_LINE> repo_lst = BaseAbstractRepository.get_data_repositories() <NEW_LINE> data_repo_lst = list() <NEW_LINE> for rep in repo_lst: <NEW_LINE> <INDENT> data_repo_lst.append((rep.id, rep.repo_name,)) <NEW_LINE> <DEDENT> self.fields['repository_choices'] = ChoiceField(choices=data_repo_lst, required=False) <NEW_LINE> repo_lst = BaseAbstractRepository.get_syslog_repositories() <NEW_LINE> syslog_repo_lst = list() <NEW_LINE> syslog_repo_lst.append(("","")) <NEW_LINE> for rep in repo_lst: <NEW_LINE> <INDENT> syslog_repo_lst.append((rep.id, rep.repo_name,)) <NEW_LINE> <DEDENT> self.fields['repository_syslog'] = ChoiceField(choices=syslog_repo_lst, required=False) <NEW_LINE> <DEDENT> def clean_repository_choices(self): <NEW_LINE> <INDENT> data = self.cleaned_data.get('repository_choices') <NEW_LINE> self.cleaned_data['data_repository'] = data <NEW_LINE> return data <NEW_LINE> <DEDENT> def clean_repository_syslog(self): <NEW_LINE> <INDENT> data = self.cleaned_data.get('repository_syslog') <NEW_LINE> if data: <NEW_LINE> <INDENT> self.cleaned_data['syslog_repository'] = data <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> document = ModLog <NEW_LINE> widgets = { 'name' : TextInput(attrs={'class':'form-control'}), 'format' : TextInput(attrs={'class': 'form-control'}), }
Mod Log form representation
62598fa37047854f4633f27b
class DiseaseSynonym(Base): <NEW_LINE> <INDENT> table_suffix = "disease__synonym" <NEW_LINE> __tablename__ = TABLE_PREFIX + table_suffix <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> disease__id = foreign_key_to('disease') <NEW_LINE> synonym = Column(String(255)) <NEW_LINE> disease = relationship(Disease, back_populates="synonyms") <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.synonym
Synonyms to Disease vocabulary (MEDIC) reference: - `CTD Disease synonym <http://ctdbase.org/downloads/#alldiseases>`_
62598fa356b00c62f0fb2754
class BiosVfXPTPrefetch(ManagedObject): <NEW_LINE> <INDENT> consts = BiosVfXPTPrefetchConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = { "classic": MoMeta("BiosVfXPTPrefetch", "biosVfXPTPrefetch", "xpt-prefetch", VersionMeta.Version311d, "InputOutput", 0x1f, [], ["admin"], [u'biosPlatformDefaults', u'biosSettings'], [], ["Get", "Set"]), } <NEW_LINE> prop_meta = { "classic": { "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version311d, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version311d, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version311d, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), "vp_xpt_prefetch": MoPropertyMeta("vp_xpt_prefetch", "vpXPTPrefetch", "string", VersionMeta.Version311d, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["Disabled", "Enabled", "disabled", "enabled", "platform-default"], []), }, } <NEW_LINE> prop_map = { "classic": { "dn": "dn", "rn": "rn", "status": "status", "vpXPTPrefetch": "vp_xpt_prefetch", }, } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.status = None <NEW_LINE> self.vp_xpt_prefetch = None <NEW_LINE> ManagedObject.__init__(self, "BiosVfXPTPrefetch", parent_mo_or_dn, **kwargs)
This is BiosVfXPTPrefetch class.
62598fa3dd821e528d6d8dd7
class SimpleBase (object) : <NEW_LINE> <INDENT> @rus.takes ('SimpleBase') <NEW_LINE> @rus.returns (rus.nothing) <NEW_LINE> def __init__ (self) : <NEW_LINE> <INDENT> if not hasattr (self, '_apitype') : <NEW_LINE> <INDENT> self._apitype = self._get_apitype () <NEW_LINE> <DEDENT> self._logger = ru.get_logger ('radical.saga') <NEW_LINE> self._id = ru.generate_id (self._get_apitype (), mode=ru.ID_SIMPLE) <NEW_LINE> <DEDENT> @rus.takes ('SimpleBase') <NEW_LINE> @rus.returns (basestring) <NEW_LINE> def _get_apitype (self) : <NEW_LINE> <INDENT> mname_1 = self.__module__ <NEW_LINE> cname = self.__class__.__name__ <NEW_LINE> mname_1_elems = mname_1.split ('.') <NEW_LINE> mname_1_elems.pop () <NEW_LINE> mname_2 = '.'.join (mname_1_elems) <NEW_LINE> for mod_cname, mod_class in inspect.getmembers (sys.modules[mname_2]) : <NEW_LINE> <INDENT> if mod_cname == cname and inspect.isclass (mod_class) and isinstance (self, mod_class) : <NEW_LINE> <INDENT> apitype = "%s.%s" % (mname_2, cname) <NEW_LINE> return apitype <NEW_LINE> <DEDENT> <DEDENT> apitype = "%s.%s" % (mname_1, cname) <NEW_LINE> return apitype
This is a very simple API base class which just initializes the self._logger and self._engine members, but does not perform any further initialization, nor any adaptor binding. This base is used for API classes which are not backed by multiple adaptors (no session, tasks, etc).
62598fa3e1aae11d1e7ce774
class State(IntEnum): <NEW_LINE> <INDENT> CONNECTING=0 <NEW_LINE> OPEN=1 <NEW_LINE> CLOSING=2 <NEW_LINE> CLOSED=3
Eventbus state see https://github.com/vert-x3/vertx-bus-bower/blob/master/vertx-eventbus.js
62598fa338b623060ffa8f37