code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class RegisterCallbackResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_CallbackID(self): <NEW_LINE> <INDENT> return self._output.get('CallbackID', None) <NEW_LINE> <DEDENT> def get_CallbackURL(self): <NEW_LINE> <INDENT> return self._output.get('CallbackURL', None) | A ResultSet with methods tailored to the values returned by the RegisterCallback Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 625990598e71fb1e983bd078 |
class GateDefinition(AbstractGate): <NEW_LINE> <INDENT> @property <NEW_LINE> def ideal_unitary(self): <NEW_LINE> <INDENT> return self._ideal_unitary <NEW_LINE> <DEDENT> def _ideal_unitary_pygsti(self, parms): <NEW_LINE> <INDENT> if parms: <NEW_LINE> <INDENT> return self._ideal_unitary(*parms) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> import numpy <NEW_LINE> return numpy.identity(2 ** len(self.quantum_parameters)) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def used_qubits(self): <NEW_LINE> <INDENT> for p in self._parameters: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not p.classical: <NEW_LINE> <INDENT> yield p <NEW_LINE> <DEDENT> <DEDENT> except JaqalError: <NEW_LINE> <INDENT> yield p <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def quantum_parameters(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [param for param in self.parameters if not param.classical] <NEW_LINE> <DEDENT> except JaqalError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise JaqalError("Gate {self.name} has a parameter with unknown type") <NEW_LINE> <DEDENT> @property <NEW_LINE> def classical_parameters(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [param for param in self.parameters if param.classical] <NEW_LINE> <DEDENT> except JaqalError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> raise JaqalError("Gate {self.name} has a parameter with unknown type") | Base: :class:`AbstractGate`
Represents a gate that's implemented by a pulse sequence in a gate definition file. | 62599059498bea3a75a590d3 |
@python_2_unicode_compatible <NEW_LINE> class CourseOrg(models.Model): <NEW_LINE> <INDENT> CATEGORY_CHOICES = ( ('pxjg', "培训机构"), ('gr', "个人"), ('gx', "高校") ) <NEW_LINE> name = models.CharField(max_length=50, verbose_name="机构名称") <NEW_LINE> desc = models.TextField(verbose_name="机构描述") <NEW_LINE> category = models.CharField(verbose_name="机构类别", max_length=20, default="pxjg", choices=CATEGORY_CHOICES) <NEW_LINE> click_nums = models.IntegerField(default=0, verbose_name="点击数") <NEW_LINE> fav_nums = models.IntegerField(default=0, verbose_name="收藏数") <NEW_LINE> image = models.ImageField(upload_to="org/%Y/%m", verbose_name="封面图", max_length=100, storage=ImageStorage()) <NEW_LINE> address = models.CharField(max_length=150, verbose_name="机构地址") <NEW_LINE> city = models.ForeignKey("CityDict", verbose_name="所在城市") <NEW_LINE> students = models.IntegerField(default=0, verbose_name="学生人数") <NEW_LINE> course_nums = models.IntegerField(default=0, verbose_name="课程数") <NEW_LINE> add_time = models.DateTimeField(auto_now_add=True, verbose_name="添加时间") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_teacher_nums(self): <NEW_LINE> <INDENT> return self.teacher_set.count() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "课程机构" <NEW_LINE> verbose_name_plural = verbose_name | 课程机构Model | 6259905901c39578d7f1420e |
class ApiKeyListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[ApiKey]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["ApiKey"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApiKeyListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link | The result of a request to list API keys.
:ivar value: The collection value.
:vartype value: list[~app_configuration_management_client.models.ApiKey]
:ivar next_link: The URI that can be used to request the next set of paged results.
:vartype next_link: str | 625990594a966d76dd5f04a0 |
class DefineSrvCommand(object): <NEW_LINE> <INDENT> def __init__(self, serv, name, alias=None): <NEW_LINE> <INDENT> self.serv = serv <NEW_LINE> self.name = name <NEW_LINE> if alias is None: <NEW_LINE> <INDENT> alias = [] <NEW_LINE> <DEDENT> self.alias = alias <NEW_LINE> if not self.name in serv.cmds: <NEW_LINE> <INDENT> serv.cmds[self.name] = None <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, cls): <NEW_LINE> <INDENT> logger.verbose("DefineCommand %s:%s" % (self.name, cls)) <NEW_LINE> cmd = cls() <NEW_LINE> self.serv.cmds[self.name] = cmd <NEW_LINE> for alias in self.alias: <NEW_LINE> <INDENT> self.serv.cmds[alias] = cmd <NEW_LINE> <DEDENT> return cls | decorator that allows to "register" commands on-the-fly
| 625990598e7ae83300eea63c |
class RevisionReplayer(object): <NEW_LINE> <INDENT> def __init__(self, document, initial_revision_id=1): <NEW_LINE> <INDENT> self.document = document <NEW_LINE> self.content = Content() <NEW_LINE> self.current_revision_id = 0 <NEW_LINE> self.to_revision(initial_revision_id) <NEW_LINE> <DEDENT> def to_revision(self, target_revision_id): <NEW_LINE> <INDENT> for revision in self.document.revisions[self.current_revision_id+1:target_revision_id+1]: <NEW_LINE> <INDENT> self.content.apply(revision) <NEW_LINE> <DEDENT> self.current_revision_id = target_revision_id | Document/content wrapper optimized for stepping forwards and backwards through revisions | 6259905915baa72349463542 |
class IItemWithName(IItem): <NEW_LINE> <INDENT> pass | Item with name.
| 62599059379a373c97d9a5d3 |
class Sidedef(WADStruct): <NEW_LINE> <INDENT> _fields_ = [ ("off_x", ctypes.c_int16), ("off_y", ctypes.c_int16), ("tx_up", ctypes.c_char * 8), ("tx_low", ctypes.c_char * 8), ("tx_mid", ctypes.c_char * 8), ("sector", ctypes.c_uint16) ] <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.tx_up = self.tx_low = self.tx_mid = "-" <NEW_LINE> super().__init__(*args, **kwargs) | Represents a map sidedef. | 62599059462c4b4f79dbcfb4 |
class iterator: <NEW_LINE> <INDENT> def __init__(self, node): <NEW_LINE> <INDENT> self._nd = node <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Iterator[key=" + repr(self.key()) + ' value=' + repr(self.value()) + "]" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._nd == other._nd <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self._nd == other._nd <NEW_LINE> <DEDENT> def key(self): <NEW_LINE> <INDENT> return self._nd.key <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return self._nd.val <NEW_LINE> <DEDENT> def prev(self): <NEW_LINE> <INDENT> other = self._nd.predecessor() <NEW_LINE> if other is not None: <NEW_LINE> <INDENT> return _OrderedMap.iterator(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def next(self): <NEW_LINE> <INDENT> other = self._nd.successor() <NEW_LINE> if other is not None: <NEW_LINE> <INDENT> return _OrderedMap.iterator(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Encapsulation of a position in the map | 625990591b99ca400229000f |
class PatronStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.Auth = channel.unary_unary( '/Patron/Auth', request_serializer=Patron__pb2.AuthRequest.SerializeToString, response_deserializer=Patron__pb2.BooleanMessageReply.FromString, ) <NEW_LINE> self.ResetPassword = channel.unary_unary( '/Patron/ResetPassword', request_serializer=Patron__pb2.ResetPasswordRequest.SerializeToString, response_deserializer=Patron__pb2.BooleanMessageReply.FromString, ) <NEW_LINE> self.BeginShutdown = channel.unary_unary( '/Patron/BeginShutdown', request_serializer=Patron__pb2.BeginShutdownRequest.SerializeToString, response_deserializer=Patron__pb2.BooleanMessageReply.FromString, ) <NEW_LINE> self.TotalUserCount = channel.unary_unary( '/Patron/TotalUserCount', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=Patron__pb2.UserCountReply.FromString, ) <NEW_LINE> self.IsShutdownComplete = channel.unary_unary( '/Patron/IsShutdownComplete', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=Patron__pb2.BooleanMessageReply.FromString, ) | Missing associated documentation comment in .proto file. | 6259905932920d7e50bc75f6 |
class SpearmanDistance(Distance): <NEW_LINE> <INDENT> def __init__(self, absolute): <NEW_LINE> <INDENT> self.absolute = absolute <NEW_LINE> <DEDENT> def __call__(self, e1, e2=None, axis=1): <NEW_LINE> <INDENT> x1 = _orange_to_numpy(e1) <NEW_LINE> x2 = _orange_to_numpy(e2) <NEW_LINE> if x2 is None: <NEW_LINE> <INDENT> x2 = x1 <NEW_LINE> <DEDENT> if x1.ndim == 1 or x2.ndim == 1: <NEW_LINE> <INDENT> axis = 0 <NEW_LINE> slc = len(x1) if x1.ndim > 1 else 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slc = len(x1) if axis == 1 else x1.shape[1] <NEW_LINE> <DEDENT> transpose = False <NEW_LINE> if x1.ndim == 2 and x2.ndim == 1: <NEW_LINE> <INDENT> x1, x2 = x2, x1 <NEW_LINE> slc = len(e1) if x1.ndim > 1 else 1 <NEW_LINE> transpose = True <NEW_LINE> <DEDENT> rho, _ = stats.spearmanr(x1, x2, axis=axis) <NEW_LINE> if self.absolute: <NEW_LINE> <INDENT> dist = (1. - np.abs(rho)) / 2. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dist = (1. - rho) / 2. <NEW_LINE> <DEDENT> if isinstance(dist, np.float): <NEW_LINE> <INDENT> dist = np.array([[dist]]) <NEW_LINE> <DEDENT> elif isinstance(dist, np.ndarray): <NEW_LINE> <INDENT> dist = dist[:slc, slc:] <NEW_LINE> <DEDENT> if transpose: <NEW_LINE> <INDENT> dist = dist.T <NEW_LINE> <DEDENT> if isinstance(e1, data.Table) or isinstance(e1, data.RowInstance): <NEW_LINE> <INDENT> dist = DistMatrix(dist, e1, e2, axis) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dist = DistMatrix(dist) <NEW_LINE> <DEDENT> return dist | Generic Spearman's rank correlation coefficient. | 625990590a50d4780f706896 |
class TestPortal(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def subprocess_run( cls, cmd, capture_output=None, check=None): <NEW_LINE> <INDENT> return subprocess.CompletedProcess(args='foo', returncode=0) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> config = ({'SQLALCHEMY_DATABASE_URI': 'sqlite:///:memory:'}) <NEW_LINE> self.app = create_app(test_config=config) <NEW_LINE> with self.app.app_context(): <NEW_LINE> <INDENT> database.init_db() <NEW_LINE> <DEDENT> auth.subprocess.run = TestPortal.subprocess_run <NEW_LINE> <DEDENT> def test_home(self): <NEW_LINE> <INDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> response = client.get('/') <NEW_LINE> self.assertEqual(200, response.status_code) <NEW_LINE> <DEDENT> <DEDENT> def test_login_with_good_pw(self): <NEW_LINE> <INDENT> min_session_expiration = datetime.fromtimestamp( time.time() + User.SESSION_DURATION) <NEW_LINE> with self.app.test_client() as client: <NEW_LINE> <INDENT> client.post('/login', data={ 'username': 'test', 'password': 'test'}, follow_redirects=True) <NEW_LINE> self.assertEqual(current_user.username, 'test') <NEW_LINE> self.assertEqual(current_user.ip_addr, '127.0.0.1') <NEW_LINE> self.assertTrue(current_user.is_authenticated) <NEW_LINE> user = User.query.filter_by(username=current_user.username).first() <NEW_LINE> self.assertLess(min_session_expiration, user.session_expiration) <NEW_LINE> self.assertEqual('127.0.0.1', user.ip_addr) <NEW_LINE> <DEDENT> <DEDENT> def test_login_with_bad_pw(self): <NEW_LINE> <INDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> client.post('/login', data={ 'username': 'test', 'password': 'bad'}, follow_redirects=True) <NEW_LINE> self.assertFalse(current_user.is_authenticated) <NEW_LINE> <DEDENT> <DEDENT> def test_sessions(self): <NEW_LINE> <INDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> response = client.get('/sessions') <NEW_LINE> self.assertEqual(b'', response.data) <NEW_LINE> <DEDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> client.post('/login', data={ 'username': 'test', 'password': 'test'}, follow_redirects=True) <NEW_LINE> <DEDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> response = client.get('/sessions') <NEW_LINE> self.assertEqual(b'test 127.0.0.1\n', response.data) <NEW_LINE> <DEDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> client.post('/login', data={ 'username': 'foo', 'password': 'bar'}, follow_redirects=True) <NEW_LINE> <DEDENT> with self.app.test_client() as client: <NEW_LINE> <INDENT> response = client.get('/sessions') <NEW_LINE> self.assertEqual(b'test 127.0.0.1\nfoo 127.0.0.1\n', response.data) | Unit tests for portal. | 6259905999cbb53fe683248e |
class User(Dateable, BASE): <NEW_LINE> <INDENT> __tablename__ = 'user' <NEW_LINE> login = Column(String, unique=True, nullable=False, info={'trim': True}) <NEW_LINE> firstname = Column(String) <NEW_LINE> lastname = Column(String) <NEW_LINE> email = Column(String) <NEW_LINE> password = Column('password', MyPassword) <NEW_LINE> groups = relationship('Group', secondary='user_group', backref='users') <NEW_LINE> def __init__(self, login="", password=""): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.login = login <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def by_login(cls, login): <NEW_LINE> <INDENT> session = cls.get_session() <NEW_LINE> return session.query(User).filter(User.login == login).first() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def by_login_password(cls, login, password): <NEW_LINE> <INDENT> query = cls.get_session().query(User) <NEW_LINE> filter1 = query.filter(User.login == login) <NEW_LINE> return filter1.filter(User.password == password).first() | User model | 62599059d486a94d0ba2d577 |
class VirtualNetworkListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetwork]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None) | Response for the ListVirtualNetworks API service call.
:param value: Gets a list of VirtualNetwork resources in a resource group.
:type value: list[~azure.mgmt.network.v2018_07_01.models.VirtualNetwork]
:param next_link: The URL to get the next set of results.
:type next_link: str | 62599059507cdc57c63a6354 |
class AbstractFieldReader(BaseReader): <NEW_LINE> <INDENT> def __init__(self, file_path, field_separator, result_order=11): <NEW_LINE> <INDENT> super(AbstractFieldReader, self).__init__(file_path, field_separator) <NEW_LINE> self.ordering = result_order <NEW_LINE> self.logger = logging.getLogger("AbstactFieldReader") <NEW_LINE> <DEDENT> def result_scores(self, items): <NEW_LINE> <INDENT> raise NotImplementedError('abstract') <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> items = super(AbstractFieldReader, self).next() <NEW_LINE> return self.result_scores(items) <NEW_LINE> <DEDENT> def _confidence(self, items): <NEW_LINE> <INDENT> new_items, confidence = self._pop_item_as(float, items) <NEW_LINE> assert 0.0 < confidence <= 1.0, "confidence not in range ]0..1] %s" % self._at_line_x_in_file_y() <NEW_LINE> return new_items, confidence <NEW_LINE> <DEDENT> def _rank(self, items): <NEW_LINE> <INDENT> new_items, rank = self._pop_item_as(int, items) <NEW_LINE> assert rank > 0, "rank must be > 0 %s" % self._at_line_x_in_file_y() <NEW_LINE> return new_items, rank <NEW_LINE> <DEDENT> def _pop_item_as(self, Type, my_list): <NEW_LINE> <INDENT> new_list = list(my_list) <NEW_LINE> try: <NEW_LINE> <INDENT> item = Type(new_list.pop()) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.logger.critical("item not type %s %s" % ( Type.__name__, self._at_line_x_in_file_y() )) <NEW_LINE> self.logger.warning("possibly unexpected result file columns?") <NEW_LINE> self.logger.info("check command line options (--help)!") <NEW_LINE> raise <NEW_LINE> <DEDENT> return new_list, item <NEW_LINE> <DEDENT> def _at_line_x_in_file_y(self): <NEW_LINE> <INDENT> return "at line %i in file '%s'" % ( self.line_number, self.file.basename ) | Read lines returning DOI, result_list, rank, confidence tuples.
If the file is_gold_standard, confidence is None.
If the file has_intrinsic_ranking or is_gold_standard, rank is None.
Reports and raises ValueErrors if the rank or confidence is not as
expected.
Asserts the correct value range for rank and confidence. | 625990590fa83653e46f6495 |
class EMreusedUS(bpy.types.PropertyGroup): <NEW_LINE> <INDENT> epoch: prop.StringProperty( name="epoch", description="Epoch", default="Untitled") <NEW_LINE> em_element: prop.StringProperty( name="em_element", description="", default="Empty") | Group of properties representing an item in the list | 625990599c8ee82313040c62 |
class Movie(): <NEW_LINE> <INDENT> def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self): <NEW_LINE> <INDENT> webbrowser.open(self.trailer_youtube_url) | This class provides a way to store movie related information.
This class was adapted from the course "Full Stack Web Developer"
by Alain Boisvert on Sunday 30 July 2017.
Attributes:
movie_title: Title of the movie.
movie_storyline: Storyline of the movie.
poster_image: Poster URL of the movie from the wikipedia site.
trailer_youtude: Trailer URL of the movie from the youtube site. | 62599059f7d966606f749390 |
class Sender(tk.Frame): <NEW_LINE> <INDENT> def __init__(self,parent,root,user_name): <NEW_LINE> <INDENT> tk.Frame.__init__(self,parent) <NEW_LINE> self.root = root <NEW_LINE> self.parent = parent <NEW_LINE> self.user_name = user_name <NEW_LINE> self.title = tk.Label(self,text="Select Files ",relief='solid',fg='blue',bg='red',font=("arial",16,"bold")) <NEW_LINE> self.title.pack(fill=tk.BOTH,padx=2,pady=2) <NEW_LINE> self.files = [] <NEW_LINE> self.add_files = tk.Button(self,text="Add",relief=tk.GROOVE,fg='red',bg='orange',font=("arial",16,"bold"),command=self.add_files_to_send,padx=20) <NEW_LINE> self.add_files.place(x=10,y=100) <NEW_LINE> self.remove_file = tk.Button(self,text="Remove",relief=tk.GROOVE,fg='red',bg='orange',font=("arial",16,"bold"),command=self.remove_files,padx=20) <NEW_LINE> self.remove_file.place(x=150,y=100) <NEW_LINE> self.remove_all_file = tk.Button(self,text="Remove All",relief=tk.GROOVE,fg='red',bg='orange',font=("arial",16,"bold"),command=self.remove_all_files,padx=20) <NEW_LINE> self.remove_all_file.place(x=330,y=100) <NEW_LINE> self.file_list_box = tk.Listbox(self,height = 15, width = 52, bg = "white", activestyle = 'dotbox', font = "Helvetica", fg = "black",selectmode = "multiple") <NEW_LINE> self.file_list_box.insert(1, "/home/ram/s") <NEW_LINE> self.file_list_box.insert(2, "/home/ram/Marksheet.pdf") <NEW_LINE> self.file_list_box.insert(3, "/home/ram/Mywork/Python-Networking/SocketProgramming/Hack-Basic/pic1.jpg") <NEW_LINE> self.file_list_box.place(x=12,y=150) <NEW_LINE> print(self.file_list_box.get(0,tk.END)) <NEW_LINE> self.back =tk.Button(self,text="Back",relief=tk.GROOVE,fg='red',bg='orange',font=("arial",16,"bold"),command=lambda:self.root.show_frame("home_page")) <NEW_LINE> self.back.pack(fill=tk.BOTH,side=tk.BOTTOM,padx=2,pady=25) <NEW_LINE> self.send =tk.Button(self,text="Send",relief=tk.GROOVE,fg='red',bg='orange',font=("arial",16,"bold"),command=self.root.connect_to_send) <NEW_LINE> self.send.pack(fill=tk.BOTH,side=tk.BOTTOM,padx=2,pady=10) <NEW_LINE> <DEDENT> def add_files_to_send(self): <NEW_LINE> <INDENT> files = tkFileDialog.askopenfilenames(parent=self,title='Choose a file') <NEW_LINE> print(files) <NEW_LINE> for file in files: <NEW_LINE> <INDENT> self.file_list_box.insert(0,file.split("/")[-1]) <NEW_LINE> <DEDENT> <DEDENT> def remove_files(self): <NEW_LINE> <INDENT> items = self.file_list_box.curselection() <NEW_LINE> print(items) <NEW_LINE> for index in items[::-1]: <NEW_LINE> <INDENT> self.file_list_box.delete(index) <NEW_LINE> <DEDENT> <DEDENT> def remove_all_files(self): <NEW_LINE> <INDENT> self.file_list_box.delete(0,tk.END) | Send page
---------
add or remove files to send | 62599059d7e4931a7ef3d62f |
class ISOCountryCode(SchemaNode): <NEW_LINE> <INDENT> schema_type = StringType <NEW_LINE> default = '' <NEW_LINE> missing = drop <NEW_LINE> validator = Regex(r'^[A-Z][A-Z]$|^$') <NEW_LINE> def deserialize(self, cstruct=null): <NEW_LINE> <INDENT> if cstruct == '': <NEW_LINE> <INDENT> return cstruct <NEW_LINE> <DEDENT> return super().deserialize(cstruct) | An ISO 3166-1 alpha-2 country code (two uppercase ASCII letters).
Example value: US | 62599059a17c0f6771d5d679 |
class AnObject(BaseEntityMixin): <NEW_LINE> <INDENT> title = Column(Unicode(100), nullable=False) <NEW_LINE> headline = Column(UnicodeText, nullable=False) <NEW_LINE> description = Column(UnicodeText, nullable=True) <NEW_LINE> primary_key = Column(Unicode(256), nullable=False, unique=True) <NEW_LINE> url = Column(Unicode(2042), nullable=True) <NEW_LINE> thumbnail = Column(Unicode(2042)) <NEW_LINE> active = Column(Boolean, default=False) <NEW_LINE> @validates('title') <NEW_LINE> def validate_title(self, key, title): <NEW_LINE> <INDENT> assert len(title) >= 4 or len( title) <= 256, 'Must be 4 to 256 characters long.' <NEW_LINE> return title | Anything with text and meta.
Note: At the time, I'm not enforcing any authorship norms. Those
are to be defined on their respective ORM classes. | 6259905956ac1b37e63037bf |
class DebugStatsdClient(BaseStatsdClient): <NEW_LINE> <INDENT> def __init__( self, level: int = logging.INFO, logger: logging.Logger = logger, inner: Optional[BaseStatsdClient] = None, **kwargs: Any, ) -> None: <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.level = level <NEW_LINE> self.logger = logger <NEW_LINE> self.inner = inner <NEW_LINE> <DEDENT> def _emit_packet(self, packet: str) -> None: <NEW_LINE> <INDENT> self.logger.log(self.level, "> %s", packet) <NEW_LINE> if self.inner: <NEW_LINE> <INDENT> self.inner._emit_packet(packet) | Verbose client for development or debugging purposes.
All Statsd packets will be logged and optionally forwarded to a wrapped
client. | 6259905963b5f9789fe86722 |
class GalaxyApiAccess: <NEW_LINE> <INDENT> def __init__(self, galaxy_url, api_key): <NEW_LINE> <INDENT> self._base_url = galaxy_url <NEW_LINE> self._key = api_key <NEW_LINE> self._max_tries = 5 <NEW_LINE> <DEDENT> def _make_url(self, rel_url, params=None): <NEW_LINE> <INDENT> if not params: <NEW_LINE> <INDENT> params = dict() <NEW_LINE> <DEDENT> params['key'] = self._key <NEW_LINE> vals = urllib.parse.urlencode(params) <NEW_LINE> return ("%s%s" % (self._base_url, rel_url), vals) <NEW_LINE> <DEDENT> def _get(self, url, params=None): <NEW_LINE> <INDENT> url, params = self._make_url(url, params) <NEW_LINE> num_tries = 0 <NEW_LINE> while 1: <NEW_LINE> <INDENT> response = urllib.request.urlopen("%s?%s" % (url, params)) <NEW_LINE> try: <NEW_LINE> <INDENT> out = json.loads(response.read()) <NEW_LINE> break <NEW_LINE> <DEDENT> except ValueError as msg: <NEW_LINE> <INDENT> if num_tries > self._max_tries: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> time.sleep(3) <NEW_LINE> num_tries += 1 <NEW_LINE> <DEDENT> <DEDENT> return out <NEW_LINE> <DEDENT> def _post(self, url, data, params=None, need_return=True): <NEW_LINE> <INDENT> url, params = self._make_url(url, params) <NEW_LINE> request = urllib.request.Request("%s?%s" % (url, params), headers = {'Content-Type' : 'application/json'}, data = json.dumps(data)) <NEW_LINE> response = urllib.request.urlopen(request) <NEW_LINE> try: <NEW_LINE> <INDENT> data = json.loads(response.read()) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if need_return: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> def run_details(self, run_bc, run_date=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> details = self._get("/nglims/api_run_details", dict(run=run_bc)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Could not find information in Galaxy for run: %s" % run_bc) <NEW_LINE> <DEDENT> if "error" in details and run_date is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> details = self._get("/nglims/api_run_details", dict(run=run_date)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Could not find information in Galaxy for run: %s" % run_date) <NEW_LINE> <DEDENT> <DEDENT> return details <NEW_LINE> <DEDENT> def sequencing_projects(self): <NEW_LINE> <INDENT> return self._get("/nglims/api_projects") <NEW_LINE> <DEDENT> def sqn_run_summary(self, run_info): <NEW_LINE> <INDENT> return self._post("/nglims/api_upload_sqn_run_summary", data=run_info) <NEW_LINE> <DEDENT> def sqn_report(self, start_date, end_date): <NEW_LINE> <INDENT> return self._get("/nglims/api_sqn_report", dict(start=start_date, end=end_date)) | Simple front end for accessing Galaxy's REST API.
| 625990593539df3088ecd84c |
class LayerParametersDict(OrderedDict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._tensors = set() <NEW_LINE> super(LayerParametersDict, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> key = self._canonicalize_key(key) <NEW_LINE> tensors = key if isinstance(key, (tuple, list)) else (key,) <NEW_LINE> key_collisions = self._tensors.intersection(tensors) <NEW_LINE> if key_collisions: <NEW_LINE> <INDENT> raise ValueError("Key(s) already present: {}".format(key_collisions)) <NEW_LINE> <DEDENT> self._tensors.update(tensors) <NEW_LINE> super(LayerParametersDict, self).__setitem__(key, value) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> key = self._canonicalize_key(key) <NEW_LINE> self._tensors.remove(key) <NEW_LINE> super(LayerParametersDict, self).__delitem__(key) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> key = self._canonicalize_key(key) <NEW_LINE> return super(LayerParametersDict, self).__getitem__(key) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> key = self._canonicalize_key(key) <NEW_LINE> return super(LayerParametersDict, self).__contains__(key) <NEW_LINE> <DEDENT> def _canonicalize_key(self, key): <NEW_LINE> <INDENT> if isinstance(key, (list, tuple)): <NEW_LINE> <INDENT> return tuple(key) <NEW_LINE> <DEDENT> return key | An OrderedDict where keys are Tensors or tuples of Tensors.
Ensures that no Tensor is associated with two different keys. | 625990594e4d5625663739b8 |
class Avion(OznakaINaziv, Kolekcija): <NEW_LINE> <INDENT> def __init__(self, ID, naziv, duzina, sirina, visina, raspon_krila, godiste, nosivost, relacija): <NEW_LINE> <INDENT> OznakaINaziv.__init__(self, ID, naziv) <NEW_LINE> Kolekcija.__init__(self, duzina, sirina, visina) <NEW_LINE> self.raspon_krila = raspon_krila <NEW_LINE> self.godiste = godiste <NEW_LINE> self.nosivost = nosivost <NEW_LINE> self.relacija = relacija <NEW_LINE> self.se_nalazi = None <NEW_LINE> self.zahtev_smestanje = None <NEW_LINE> self.zahtev_transport = [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.se_nalazi: <NEW_LINE> <INDENT> naziv_hangara = self.se_nalazi.naziv <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> naziv_hangara = 'Van Aerodroma' <NEW_LINE> <DEDENT> return 'Avion - Oznaka: {}, Naziv: {}, Godiste: {}, ' 'Duzina: {}, Raspon krila: {}, Visina: {}, ' 'Nosivost: {}, Relacija: {}, Nalazi se: {}'.format(self.id, self.naziv, self.godiste, str(self.duzina), str( self.raspon_krila), str(self.visina), str( self.nosivost), self.relacija, naziv_hangara) | Pravi objekat Aviona. Mogu da se dodaju Prostori za robu. Avion opisuju
ID, Naziv, Duzina, Sirina, Visina i Prostori za robu koje sadrzi | 6259905901c39578d7f1420f |
class APIDictWrapper(object): <NEW_LINE> <INDENT> _apidict = {} <NEW_LINE> def __init__(self, apidict): <NEW_LINE> <INDENT> self._apidict = apidict <NEW_LINE> <DEDENT> def __getattribute__(self, attr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return object.__getattribute__(self, attr) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> if attr not in self._apidict: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return self._apidict[attr] <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(self, item) <NEW_LINE> <DEDENT> except (AttributeError, TypeError) as e: <NEW_LINE> <INDENT> raise KeyError(e) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return hasattr(self, item) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get(self, item, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return getattr(self, item) <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<%s: %s>" % (self.__class__.__name__, self._apidict) <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if hasattr(other, '_apidict'): <NEW_LINE> <INDENT> return cmp(self._apidict, other._apidict) <NEW_LINE> <DEDENT> return cmp(self._apidict, other) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return self._apidict | Simple wrapper for api dictionaries
Some api calls return dictionaries. This class provides identical
behavior as APIResourceWrapper, except that it will also behave as a
dictionary, in addition to attribute accesses.
Attribute access is the preferred method of access, to be
consistent with api resource objects from novaclient. | 62599059adb09d7d5dc0bb1b |
class TestReporting(unittest.TestCase): <NEW_LINE> <INDENT> @patch('upload.result_upload.upload_result') <NEW_LINE> def test_process_folder(self, mock_upload): <NEW_LINE> <INDENT> report_config = self._report_config_example() <NEW_LINE> reporting.process_folder( 'test_runners/pytorch/unittest_files/results/basic', report_config=report_config) <NEW_LINE> test_result = mock_upload.call_args[0][0] <NEW_LINE> self.assertEqual(test_result['test_harness'], 'pytorch') <NEW_LINE> self.assertEqual(test_result['test_environment'], report_config['test_environment']) <NEW_LINE> self.assertEqual(test_result['test_id'], 'resnet50.gpu_1.32.real') <NEW_LINE> results = mock_upload.call_args[0][1] <NEW_LINE> self.assertEqual(results[0]['result'], 280.91838703453595) <NEW_LINE> arg_test_info = mock_upload.call_args[1]['test_info'] <NEW_LINE> self.assertEqual(arg_test_info['accel_cnt'], 2) <NEW_LINE> self.assertEqual(arg_test_info['cmd'], 'python blahblah.py -arg foo') <NEW_LINE> arg_extras = mock_upload.call_args[1]['extras'] <NEW_LINE> self.assertIn('config', arg_extras) <NEW_LINE> self.assertIn('batches_sampled', arg_extras) <NEW_LINE> <DEDENT> def test_parse_result_file(self): <NEW_LINE> <INDENT> result = reporting.parse_result_file( 'test_runners/pytorch/unittest_files/results/basic/' 'worker_0_stdout.txt') <NEW_LINE> self.assertEqual(result['imgs_sec'], 280.91838703453595) <NEW_LINE> self.assertEqual(result['batches_sampled'], 91) <NEW_LINE> self.assertEqual(result['test_id'], 'resnet50.gpu_1.32.real') <NEW_LINE> self.assertEqual(result['gpu'], 2) <NEW_LINE> self.assertEqual(result['data_type'], 'real') <NEW_LINE> self.assertIn('config', result) <NEW_LINE> <DEDENT> def _mock_config(self, test_id): <NEW_LINE> <INDENT> config = {} <NEW_LINE> config['test_id'] = test_id <NEW_LINE> config['batch_size'] = 128 <NEW_LINE> config['gpus'] = 2 <NEW_LINE> config['model'] = 'resnet50' <NEW_LINE> config['cmd'] = 'python some_script.py --arg0=foo --arg1=bar' <NEW_LINE> return config <NEW_LINE> <DEDENT> def _mock_result(self, test_id, imgs_sec): <NEW_LINE> <INDENT> result = {} <NEW_LINE> result['config'] = self._mock_config(test_id) <NEW_LINE> result['imgs_sec'] = imgs_sec <NEW_LINE> result['test_id'] = test_id <NEW_LINE> result['gpu'] = 2 <NEW_LINE> result['batches_sampled'] = 100 <NEW_LINE> return result <NEW_LINE> <DEDENT> def _report_config_example(self): <NEW_LINE> <INDENT> report_config = {} <NEW_LINE> report_config['test_environment'] = 'unit_test_env' <NEW_LINE> report_config['accel_type'] = 'GTX 940' <NEW_LINE> report_config['platform'] = 'test_platform_name' <NEW_LINE> report_config['framework_version'] = 'v1.5RC0-dev20171027' <NEW_LINE> cpu_info = {} <NEW_LINE> cpu_info['model_name'] = 'Intel XEON 2600E 2.8Ghz' <NEW_LINE> cpu_info['core_count'] = 36 <NEW_LINE> cpu_info['socket_count'] = 1 <NEW_LINE> report_config['cpu_info'] = cpu_info <NEW_LINE> return report_config | Tests for pytorch reporting module. | 62599059be8e80087fbc0634 |
@base.vectorize <NEW_LINE> class movint(base.Instruction): <NEW_LINE> <INDENT> __slots__ = ["code"] <NEW_LINE> code = base.opcodes['MOVINT'] <NEW_LINE> arg_format = ['ciw','ci'] | Assigns register $ci_i$ the value in the register $ci_j$. | 62599059460517430c432b2a |
class exp_polar(ExpBase): <NEW_LINE> <INDENT> is_polar = True <NEW_LINE> is_comparable = False <NEW_LINE> def _eval_Abs(self): <NEW_LINE> <INDENT> from sympy import expand_mul <NEW_LINE> return sqrt( expand_mul(self * self.conjugate()) ) <NEW_LINE> <DEDENT> def _eval_evalf(self, prec): <NEW_LINE> <INDENT> from sympy import im, pi, re <NEW_LINE> i = im(self.args[0]) <NEW_LINE> if i <= -pi or i > pi: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> res = exp(self.args[0])._eval_evalf(prec) <NEW_LINE> if i > 0 and im(res) < 0: <NEW_LINE> <INDENT> return re(res) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def _eval_power(self, other): <NEW_LINE> <INDENT> return self.func(self.args[0]*other) <NEW_LINE> <DEDENT> def _eval_is_real(self): <NEW_LINE> <INDENT> if self.args[0].is_real: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def as_base_exp(self): <NEW_LINE> <INDENT> if self.args[0] == 0: <NEW_LINE> <INDENT> return self, S(1) <NEW_LINE> <DEDENT> return ExpBase.as_base_exp(self) | Represent a 'polar number' (see g-function Sphinx documentation).
``exp_polar`` represents the function
`Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
`z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
the main functions to construct polar numbers.
>>> from sympy import exp_polar, pi, I, exp
The main difference is that polar numbers don't "wrap around" at `2 \pi`:
>>> exp(2*pi*I)
1
>>> exp_polar(2*pi*I)
exp_polar(2*I*pi)
apart from that they behave mostly like classical complex numbers:
>>> exp_polar(2)*exp_polar(3)
exp_polar(5)
See also
========
sympy.simplify.simplify.powsimp
sympy.functions.elementary.complexes.polar_lift
sympy.functions.elementary.complexes.periodic_argument
sympy.functions.elementary.complexes.principal_branch | 62599059d7e4931a7ef3d631 |
class IOException(Exception): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'msg', None, None, ), (2, TType.STRING, 'stack', None, None, ), (3, TType.STRING, 'clazz', None, None, ), ) <NEW_LINE> def __init__(self, msg=None, stack=None, clazz=None,): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> self.stack = stack <NEW_LINE> self.clazz = clazz <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.msg = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.stack = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.clazz = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('IOException') <NEW_LINE> if self.msg is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('msg', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.msg) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.stack is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('stack', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.stack) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.clazz is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('clazz', TType.STRING, 3) <NEW_LINE> oprot.writeString(self.clazz) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Generic I/O error
Attributes:
- msg: Error message.
- stack: Textual representation of the call stack.
- clazz: The Java class of the Exception (may be a subclass) | 6259905963d6d428bbee3d60 |
@python_2_unicode_compatible <NEW_LINE> class Trigger(models.Model): <NEW_LINE> <INDENT> name = models.CharField(u'触发器名', max_length=16) <NEW_LINE> triggeritems = models.ManyToManyField(TriggerItem, verbose_name=u'触发器条目') <NEW_LINE> level_choices = ( ('info', u'消息'), ('debug', u'调试'), ('danger', u'危险'), ('disaster', u'灾难'), ) <NEW_LINE> level = models.CharField(u'事件级别', choices=level_choices, max_length=16) <NEW_LINE> memo = models.TextField(u"备注", blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | 触发器 | 6259905999cbb53fe6832491 |
class BaseValidator(object): <NEW_LINE> <INDENT> def _validate(self, filehandle, metadata): <NEW_LINE> <INDENT> raise NotImplementedError("_validate not implemented") <NEW_LINE> <DEDENT> def __call__(self, filehandle, metadata): <NEW_LINE> <INDENT> return self._validate(filehandle, metadata) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> return AndValidator(self, other) <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return OrValidator(self, other) <NEW_LINE> <DEDENT> def __invert__(self): <NEW_LINE> <INDENT> return NegatedValidator(self) | BaseValidator class for flask_transfer. Provides utility methods for
combining validators together. Subclasses should implement `_validates`.
Validators can signal failure in one of two ways:
* Raise UploadError with a message
* Return non-Truthy value.
Raising UploadError is the preferred method, as it allows a more descriptive
message to reach the caller, however by supporting returning Falsey values,
lambdas can be used as validators as well. | 625990593eb6a72ae038bc11 |
class TalkSubmissionForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Talk <NEW_LINE> exclude = ('status', 'type') <NEW_LINE> field_args = { 'name': {'label': 'Title'}, 'description': { 'label': 'Description', 'description': ( 'If your talk is accepted this will be made public. It ' 'should be one paragraph. This field is rendered as ' 'reStructuredText.' ), }, 'level': {'label': 'Experience Level'}, 'duration': {'label': 'Duration'}, 'abstract': { 'label': 'Abstract', 'description': ( 'Detailed overview. Will be made public if your talk is ' 'accepted.' ), }, 'outline': { 'label': 'Outline', 'description': ( 'Sections and key points of the talk meant to give the ' 'program committee an overview. This field is rendered ' 'as reStructuredText.' ), }, 'additional_requirements': { 'label': 'Additional Notes', 'description': ( "Any other information you'd like the program committee " "to know, e.g., additional context and resources, " "previous speaking experiences, etc. This will not be " "shared publicly." ), }, 'recording_release': { 'label': 'Recording Release', 'validators': (Optional(),), }, } <NEW_LINE> <DEDENT> duration = QuerySelectField(query_factory=duration_query_factory) | Form for editing :class:`~pygotham.models.Talk` instances. | 62599059379a373c97d9a5d6 |
class CustomFormatter(logging.Formatter, object): <NEW_LINE> <INDENT> def format(self, record): <NEW_LINE> <INDENT> if record.levelno == LOG_LEVEL_TASK.level: <NEW_LINE> <INDENT> temp = '*' * (90 - len(record.msg) - 25) <NEW_LINE> self._fmt = "\n\n[%(asctime)s] %(levelname)s - [%(message)s] " + temp + "\n\n" <NEW_LINE> self.datefmt = "%m/%d/%Y %H:%M:%S" <NEW_LINE> <DEDENT> elif record.levelno in [logging.INFO, LOG_LEVEL_FILE.level]: <NEW_LINE> <INDENT> self._fmt = "%(message)s" <NEW_LINE> self.datefmt = "" <NEW_LINE> <DEDENT> elif record.levelno in [logging.WARNING]: <NEW_LINE> <INDENT> self._fmt = "%(levelname)s - %(message)s" <NEW_LINE> self.datefmt = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fmt = "[%(asctime)s] %(levelname)s - %(message)s" <NEW_LINE> self.datefmt = "%m/%d/%Y %H:%M:%S" <NEW_LINE> <DEDENT> return super(CustomFormatter, self).format(record) | Custom formatter to handle different logging formats based on logging level
Python 2.6 workaround - logging.Formatter class does not use new-style class
and causes 'TypeError: super() argument 1 must be type, not classobj' so
we use multiple inheritance to get around the problem. | 62599059627d3e7fe0e0843f |
class DecryptionError(Exception): <NEW_LINE> <INDENT> pass | Raised when a message could not be decrypted. | 6259905907d97122c4218256 |
class StandardNormal(Distribution): <NEW_LINE> <INDENT> def __init__(self, shape, device='cpu'): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.device = device <NEW_LINE> self._shape = torch.Size(shape) <NEW_LINE> self._log_z = 0.5 * np.prod(shape) * np.log(2 * np.pi) <NEW_LINE> <DEDENT> def _log_prob(self, inputs, context): <NEW_LINE> <INDENT> if inputs.shape[1:] != self._shape: <NEW_LINE> <INDENT> raise ValueError( "Expected input of shape {}, got {}".format( self._shape, inputs.shape[1:] ) ) <NEW_LINE> <DEDENT> neg_energy = -0.5 * torchutils.sum_except_batch(inputs.to(self.device) ** 2, num_batch_dims=1) <NEW_LINE> return neg_energy - self._log_z <NEW_LINE> <DEDENT> def _sample(self, num_samples, context): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> return torch.randn(num_samples, *self._shape).to(self.device) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context_size = context.shape[0] <NEW_LINE> samples = torch.randn(context_size * num_samples, *self._shape).to(self.device) <NEW_LINE> return torchutils.split_leading_dim(samples, [context_size, num_samples]) <NEW_LINE> <DEDENT> <DEDENT> def _mean(self, context): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> return torch.zeros(self._shape).to(self.device) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return torch.zeros(context.shape[0], *self._shape).to(self.device) | A multivariate Normal with zero mean and unit covariance. | 62599059e76e3b2f99fd9fb1 |
class UserRegistration(Resource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.user_parser = reqparse.RequestParser() <NEW_LINE> self.user_parser.add_argument("firstname", type=str, required=True) <NEW_LINE> self.user_parser.add_argument("lastname", type=str, required=True) <NEW_LINE> self.user_parser.add_argument("user_role", type=str, required=True) <NEW_LINE> self.user_parser.add_argument("username", type=str, required=True) <NEW_LINE> self.user_parser.add_argument("email", type=str, required=True) <NEW_LINE> self.user_parser.add_argument("password", type=str, required=True) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> data = self.user_parser.parse_args() <NEW_LINE> firstname = data["firstname"] <NEW_LINE> lastname = data["lastname"] <NEW_LINE> user_role = data["user_role"] <NEW_LINE> username = data["username"] <NEW_LINE> email = data["email"] <NEW_LINE> password = data["password"] <NEW_LINE> users.add_users(firstname, lastname, user_role, username,email, password) <NEW_LINE> return { "message": "Sign up successful" }, 201 | Class for user registration | 62599059004d5f362081fac6 |
class EscapeText(six.text_type, EscapeData): <NEW_LINE> <INDENT> __new__ = allow_lazy(six.text_type.__new__, six.text_type) | A unicode string object that should be HTML-escaped when output. | 62599059baa26c4b54d50856 |
class TwoWordNonPSDProbe(Probe): <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> print('TwoWordNonPSDProbe') <NEW_LINE> super(TwoWordNonPSDProbe, self).__init__() <NEW_LINE> self.args = args <NEW_LINE> self.probe_rank = args['probe']['maximum_rank'] <NEW_LINE> self.model_dim = args['model']['hidden_dim'] <NEW_LINE> self.proj = nn.Parameter(data = torch.zeros(self.model_dim, self.model_dim)) <NEW_LINE> nn.init.uniform_(self.proj, -0.05, 0.05) <NEW_LINE> self.to(args['device']) <NEW_LINE> self.print_param_count() <NEW_LINE> <DEDENT> def forward(self, batch): <NEW_LINE> <INDENT> batchlen, seqlen, rank = batch.size() <NEW_LINE> batch_square = batch.unsqueeze(2).expand(batchlen, seqlen, seqlen, rank) <NEW_LINE> diffs = (batch_square - batch_square.transpose(1,2)).view(batchlen*seqlen*seqlen, rank) <NEW_LINE> psd_transformed = torch.matmul(diffs, self.proj).view(batchlen*seqlen*seqlen,1,rank) <NEW_LINE> dists = torch.bmm(psd_transformed, diffs.view(batchlen*seqlen*seqlen, rank, 1)) <NEW_LINE> dists = dists.view(batchlen, seqlen, seqlen) <NEW_LINE> return dists | Computes a bilinear function of difference vectors.
For a batch of sentences, computes all n^2 pairs of scores
for each sentence in the batch. | 62599059dd821e528d6da459 |
class Account(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'account' <NEW_LINE> username = db.Column(db.String(30), primary_key=True) <NEW_LINE> contact_email = db.Column(db.String(100), nullable=False) <NEW_LINE> first_name = db.Column(db.String(100), nullable=False, default='') <NEW_LINE> last_name = db.Column(db.String(100), nullable=False, default='') <NEW_LINE> is_superuser = db.Column(db.Boolean, default=False, nullable=False) <NEW_LINE> def __init__(self, username, contact_email, first_name=None, last_name=None, is_superuser=False): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.contact_email = contact_email <NEW_LINE> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.is_superuser = is_superuser <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Account ({}, {}, {}, {}, {})>'.format( self.username, self.first_name, self.last_name, self.contact_email, self.is_superuser) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def username_exists(username): <NEW_LINE> <INDENT> return Account.query.filter_by(username=username).first() is not None | Basic user account | 62599059b5575c28eb7137a5 |
class Command(NoArgsCommand): <NEW_LINE> <INDENT> def handle_noargs(self, **options): <NEW_LINE> <INDENT> fixtures_dir = os.path.join(settings.PROJECT_ROOT, 'demo', 'fixtures') <NEW_LINE> fixture_file = os.path.join(fixtures_dir, 'demo.json') <NEW_LINE> image_src_dir = os.path.join(fixtures_dir, 'images') <NEW_LINE> image_dest_dir = os.path.join(settings.MEDIA_ROOT, 'original_images') <NEW_LINE> call_command('loaddata', fixture_file, verbosity=0) <NEW_LINE> if not os.path.isdir(image_dest_dir): <NEW_LINE> <INDENT> os.makedirs(image_dest_dir) <NEW_LINE> <DEDENT> for filename in os.listdir(image_src_dir): <NEW_LINE> <INDENT> shutil.copy(os.path.join(image_src_dir, filename), image_dest_dir) | Import Wagtail fixtures | 6259905901c39578d7f14210 |
class InteractionException(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message | An exception to be raised when an interaction with a web page fails
Attributes
----------
message : str
The message detailing why the exception was raised | 6259905915baa72349463546 |
class BinaryTruePositives(keras.layers.Layer): <NEW_LINE> <INDENT> def __init__(self, name='true_positives', **kwargs): <NEW_LINE> <INDENT> super(BinaryTruePositives, self).__init__(name=name, **kwargs) <NEW_LINE> self.true_positives = keras.backend.variable(value=0, dtype='int32') <NEW_LINE> <DEDENT> def reset_states(self): <NEW_LINE> <INDENT> keras.backend.set_value(self.true_positives, 0) <NEW_LINE> <DEDENT> def __call__(self, y_true, y_pred): <NEW_LINE> <INDENT> y_true = math_ops.cast(y_true, 'int32') <NEW_LINE> y_pred = math_ops.cast(math_ops.round(y_pred), 'int32') <NEW_LINE> correct_preds = math_ops.cast(math_ops.equal(y_pred, y_true), 'int32') <NEW_LINE> true_pos = math_ops.cast( math_ops.reduce_sum(correct_preds * y_true), 'int32') <NEW_LINE> current_true_pos = self.true_positives * 1 <NEW_LINE> self.add_update( state_ops.assign_add(self.true_positives, true_pos), inputs=[y_true, y_pred]) <NEW_LINE> return current_true_pos + true_pos | Stateful Metric to count the total true positives over all batches.
Assumes predictions and targets of shape `(samples, 1)`.
Arguments:
threshold: Float, lower limit on prediction value that counts as a
positive class prediction.
name: String, name for the metric. | 6259905910dbd63aa1c72153 |
class Simulator(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='simulator') <NEW_LINE> parser.add_argument('conf', type=str, help='config file') <NEW_LINE> args = parser.parse_args() <NEW_LINE> config = args.conf <NEW_LINE> confmod = imp.load_source('conf','configs/' + config + '.py') <NEW_LINE> self.conf = confmod.config <NEW_LINE> self.model = mujoco_py.MjModel(self.conf['modelfile']) <NEW_LINE> gofast = False <NEW_LINE> self.viewer = mujoco_py.MjViewer(visible=True, init_width=480, init_height=480, go_fast=gofast) <NEW_LINE> self.viewer.start() <NEW_LINE> self.viewer.set_model(self.model) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> for t in range(self.conf['T']): <NEW_LINE> <INDENT> self.model.data.ctrl = np.zeros_like(self.model.data.ctrl) <NEW_LINE> self.viewer.loop_once() <NEW_LINE> self.model.step() | Cross Entropy Method Stochastic Optimizer | 62599059379a373c97d9a5d7 |
class ValidationCurves(): <NEW_LINE> <INDENT> def __init__(self, X, y, estimator, hyperparameter, metric, validation, pipeline=False, metric_name='metric', pipeline_step=-1): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.y = y <NEW_LINE> self.estimator = estimator <NEW_LINE> self.hyperparameter = hyperparameter <NEW_LINE> self.metric = metric <NEW_LINE> self.validation = validation <NEW_LINE> self.pipeline = pipeline <NEW_LINE> self.metric_name = metric_name <NEW_LINE> self.pipeline_step = pipeline_step <NEW_LINE> self.table = None <NEW_LINE> <DEDENT> def __computation(self, param_values): <NEW_LINE> <INDENT> guardar = [] <NEW_LINE> for param in param_values: <NEW_LINE> <INDENT> if self.pipeline: <NEW_LINE> <INDENT> self.estimator[self.pipeline_step].set_params(**{self.hyperparameter: param}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.estimator.set_params(**{self.hyperparameter: param}) <NEW_LINE> <DEDENT> validacao_cruzada = cross_validate(self.estimator, self.X, self.y, scoring=self.metric, cv = self.validation, return_train_score=True, n_jobs=-1) <NEW_LINE> treino = np.mean(validacao_cruzada['train_score']) <NEW_LINE> teste = np.mean(validacao_cruzada['test_score']) <NEW_LINE> hyper = param <NEW_LINE> guardar.append((hyper, treino, teste)) <NEW_LINE> print(self.hyperparameter, ' = ', param) <NEW_LINE> print(f'Train: {np.round(treino, 3)} | Validation: {np.round(teste, 3)}\n') <NEW_LINE> <DEDENT> return guardar <NEW_LINE> <DEDENT> def validation_curves(self, param_values, figsize=(8,5), ylim=None): <NEW_LINE> <INDENT> self.table = pd.DataFrame(self.__computation(param_values), columns=[self.hyperparameter,'Train','Validation']) <NEW_LINE> melt = pd.melt(self.table, id_vars=self.hyperparameter, value_vars=['Train','Validation'], value_name='Score', var_name='Set') <NEW_LINE> f, ax = plt.subplots(figsize=figsize) <NEW_LINE> sn.pointplot(x=self.hyperparameter, y='Score', hue='Set', data=melt, ax=ax) <NEW_LINE> ax.set_title(self.metric_name.title()) if not isinstance(self.metric, str) else ax.set_title(self.metric.title()) <NEW_LINE> ax.set(ylim=ylim) | Assessment of the performace of machine learning models.
parameters:
X - Pandas dataframe.
y - target.
estimator - The machine learning algorithm chosen.
hyperparameter - String with the name of the hyperparameter that will be evaluated.
metric - Metric chosen for the assessment. It can be a string like: 'accuracy', 'neg_mean_absolute_error' or
build with the make_scorer function.
validation - cross validation, it can be a integer number or a function like: KFold, RepeatedKFold, etc.
pipeline - Dafault 'False'. it need to be set as 'True' if a pipeline is used.
metric_name - String representing the name of the chosen metric.
It will be the title of the plot when thre make_scorer function is used.
pipeline_step - The defalut is -1 for the last step in the process, usualy the ML algorithm.
But it is possible to access the intermediarie steps, for instance, the components of a PCA.
method:
validation_curves - Plot the graph with the conplexity lines visualization. | 62599059adb09d7d5dc0bb1d |
class OneTimeTieredPricingOverride(object): <NEW_LINE> <INDENT> swagger_types = { 'quantity': 'float', 'tiers': 'list[ChargeTier]' } <NEW_LINE> attribute_map = { 'quantity': 'quantity', 'tiers': 'tiers' } <NEW_LINE> def __init__(self, quantity=None, tiers=None): <NEW_LINE> <INDENT> self._quantity = None <NEW_LINE> self._tiers = None <NEW_LINE> self.discriminator = None <NEW_LINE> if quantity is not None: <NEW_LINE> <INDENT> self.quantity = quantity <NEW_LINE> <DEDENT> if tiers is not None: <NEW_LINE> <INDENT> self.tiers = tiers <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def quantity(self): <NEW_LINE> <INDENT> return self._quantity <NEW_LINE> <DEDENT> @quantity.setter <NEW_LINE> def quantity(self, quantity): <NEW_LINE> <INDENT> if quantity is not None and quantity < 0: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `quantity`, must be a value greater than or equal to `0`") <NEW_LINE> <DEDENT> self._quantity = quantity <NEW_LINE> <DEDENT> @property <NEW_LINE> def tiers(self): <NEW_LINE> <INDENT> return self._tiers <NEW_LINE> <DEDENT> @tiers.setter <NEW_LINE> def tiers(self, tiers): <NEW_LINE> <INDENT> self._tiers = tiers <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> 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, OneTimeTieredPricingOverride): <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. | 62599059be8e80087fbc0636 |
class CornersProblem(search.SearchProblem): <NEW_LINE> <INDENT> def __init__(self, startingGameState): <NEW_LINE> <INDENT> self.walls = startingGameState.getWalls() <NEW_LINE> self.startingPosition = startingGameState.getPacmanPosition() <NEW_LINE> top, right = self.walls.height-2, self.walls.width-2 <NEW_LINE> self.corners = ((1,1), (1,top), (right, 1), (right, top)) <NEW_LINE> for corner in self.corners: <NEW_LINE> <INDENT> if not startingGameState.hasFood(*corner): <NEW_LINE> <INDENT> print('Warning: no food in corner ' + str(corner)) <NEW_LINE> <DEDENT> <DEDENT> self._expanded = 0 <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> <DEDENT> def getStartState(self): <NEW_LINE> <INDENT> return self.startingPosition, self.corners <NEW_LINE> <DEDENT> def isGoalState(self, state): <NEW_LINE> <INDENT> return not len(state[1]) <NEW_LINE> <DEDENT> def getSuccessors(self, state): <NEW_LINE> <INDENT> successors = [] <NEW_LINE> for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]: <NEW_LINE> <INDENT> x, y = state[0] <NEW_LINE> dx, dy = Actions.directionToVector(action) <NEW_LINE> nextx, nexty = int(x + dx), int(y + dy) <NEW_LINE> if not self.walls[nextx][nexty]: <NEW_LINE> <INDENT> corners = filter(lambda x: x != (nextx, nexty), state[1]) <NEW_LINE> nextState = (nextx, nexty), tuple(corners) <NEW_LINE> successors += [(nextState, action, 1)] <NEW_LINE> <DEDENT> <DEDENT> self._expanded += 1 <NEW_LINE> return successors <NEW_LINE> <DEDENT> def getCostOfActions(self, actions): <NEW_LINE> <INDENT> if actions == None: return 999999 <NEW_LINE> x,y= self.startingPosition <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> dx, dy = Actions.directionToVector(action) <NEW_LINE> x, y = int(x + dx), int(y + dy) <NEW_LINE> if self.walls[x][y]: return 999999 <NEW_LINE> <DEDENT> return len(actions) | This search problem finds paths through all four corners of a layout.
You must select a suitable state space and successor function | 62599059460517430c432b2b |
class DefaultHandler(RateLimitHandler): <NEW_LINE> <INDENT> ca_lock = Lock() <NEW_LINE> cache = {} <NEW_LINE> cache_hit_callback = None <NEW_LINE> timeouts = {} <NEW_LINE> @staticmethod <NEW_LINE> def with_cache(function): <NEW_LINE> <INDENT> @wraps(function) <NEW_LINE> def wrapped(cls, _cache_key, _cache_ignore, _cache_timeout, **kwargs): <NEW_LINE> <INDENT> def clear_timeouts(): <NEW_LINE> <INDENT> for key in list(cls.timeouts): <NEW_LINE> <INDENT> if timer() - cls.timeouts[key] > _cache_timeout: <NEW_LINE> <INDENT> del cls.timeouts[key] <NEW_LINE> del cls.cache[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if _cache_ignore: <NEW_LINE> <INDENT> return function(cls, **kwargs) <NEW_LINE> <DEDENT> with cls.ca_lock: <NEW_LINE> <INDENT> clear_timeouts() <NEW_LINE> if _cache_key in cls.cache: <NEW_LINE> <INDENT> if cls.cache_hit_callback: <NEW_LINE> <INDENT> cls.cache_hit_callback(_cache_key) <NEW_LINE> <DEDENT> return cls.cache[_cache_key] <NEW_LINE> <DEDENT> <DEDENT> result = function(cls, **kwargs) <NEW_LINE> if result.status_code not in (200, 302): <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> with cls.ca_lock: <NEW_LINE> <INDENT> cls.timeouts[_cache_key] = timer() <NEW_LINE> cls.cache[_cache_key] = result <NEW_LINE> return result <NEW_LINE> <DEDENT> <DEDENT> return wrapped <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def clear_cache(cls): <NEW_LINE> <INDENT> with cls.ca_lock: <NEW_LINE> <INDENT> cls.cache = {} <NEW_LINE> cls.timeouts = {} <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def evict(cls, urls): <NEW_LINE> <INDENT> if isinstance(urls, text_type): <NEW_LINE> <INDENT> urls = [urls] <NEW_LINE> <DEDENT> urls = set(normalize_url(url) for url in urls) <NEW_LINE> retval = False <NEW_LINE> with cls.ca_lock: <NEW_LINE> <INDENT> for key in list(cls.cache): <NEW_LINE> <INDENT> if key[0] in urls: <NEW_LINE> <INDENT> retval = True <NEW_LINE> del cls.cache[key] <NEW_LINE> del cls.timeouts[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return retval | Extends the RateLimitHandler to add thread-safe caching support. | 625990593617ad0b5ee076fd |
class Asset(PrimaryKeyModel, Serializable): <NEW_LINE> <INDENT> physical_asset = models.ForeignKey('AssetPhysical', db_constraint=False, max_length=32, blank=True, null=True, db_column='c_asset_physical_id') <NEW_LINE> name = models.CharField(max_length=200, blank=True, null=True, db_column='c_name') <NEW_LINE> business_id = models.CharField(max_length=32, null=True, db_column='c_business_id', db_index=True) <NEW_LINE> business_type = models.CharField(max_length=200, null=True, db_column='c_business_type') <NEW_LINE> business_sort = models.IntegerField(null=True, db_column='n_business_sort') <NEW_LINE> extension = models.CharField(max_length=200, blank=True, null=True, db_column='c_extension') <NEW_LINE> date_added = models.DateTimeField(blank=True, null=True, default=timezone.now, db_column='d_added') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 't_sys_asset' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | 系统文件,文件的虚拟结构 | 62599059d99f1b3c44d06c53 |
class CreateOrder(CreateAPIView): <NEW_LINE> <INDENT> permission_classes = (Customer,) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._order_service = OrderService() <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> serializer = OrderCreateSerializer(data = request.data) <NEW_LINE> if not serializer.is_valid(): <NEW_LINE> <INDENT> return BAD_REQUEST(serializer.errors) <NEW_LINE> <DEDENT> order_is_valid = self._order_service.validate(**serializer.validated_data) <NEW_LINE> if not order_is_valid: <NEW_LINE> <INDENT> return BAD_REQUEST('LMAO you\'re cheating') <NEW_LINE> <DEDENT> self._order_service.create(request.appuser_id, **serializer.validated_data) <NEW_LINE> return CREATED() | Create an order | 6259905932920d7e50bc75fa |
class factory_callable(MetadataDictDirective): <NEW_LINE> <INDENT> key = FACTORY_CALLABLE_KEY <NEW_LINE> def factory(self, field_name, func): <NEW_LINE> <INDENT> return {field_name: func} | Directive used to define a callable returning a yafowil widget for a
schema field. | 625990590a50d4780f706898 |
class Xfsinfo(AutotoolsPackage, XorgPackage): <NEW_LINE> <INDENT> homepage = "http://cgit.freedesktop.org/xorg/app/xfsinfo" <NEW_LINE> xorg_mirror_path = "app/xfsinfo-1.0.5.tar.gz" <NEW_LINE> version('1.0.5', sha256='56a0492ed2cde272dc8f4cff4ba0970ccb900e51c10bb8ec62747483d095fd69') <NEW_LINE> depends_on('libfs') <NEW_LINE> depends_on('[email protected]:') <NEW_LINE> depends_on('pkgconfig', type='build') <NEW_LINE> depends_on('util-macros', type='build') | xfsinfo is a utility for displaying information about an X font
server. It is used to examine the capabilities of a server, the
predefined values for various parameters used in communicating between
clients and the server, and the font catalogues and alternate servers
that are available. | 6259905930dc7b76659a0d59 |
class NVTEnsemble(NVEEnsemble): <NEW_LINE> <INDENT> def __init__(self, dt, temp, thermostat=None, fixcom=False): <NEW_LINE> <INDENT> super(NVTEnsemble,self).__init__(dt=dt,temp=temp, fixcom=fixcom) <NEW_LINE> if thermostat is None: <NEW_LINE> <INDENT> self.thermostat = Thermostat() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.thermostat = thermostat <NEW_LINE> <DEDENT> <DEDENT> def bind(self, beads, nm, cell, bforce, prng): <NEW_LINE> <INDENT> super(NVTEnsemble,self).bind(beads, nm, cell, bforce, prng) <NEW_LINE> fixdof = None <NEW_LINE> if self.fixcom: <NEW_LINE> <INDENT> fixdof = 3 <NEW_LINE> <DEDENT> deppipe(self,"ntemp", self.thermostat,"temp") <NEW_LINE> deppipe(self,"dt", self.thermostat, "dt") <NEW_LINE> if isinstance(self.thermostat,ThermoNMGLE) or isinstance(self.thermostat,ThermoNMGLEG) or isinstance(self.thermostat,ThermoPILE_L) or isinstance(self.thermostat,ThermoPILE_G): <NEW_LINE> <INDENT> self.thermostat.bind(nm=self.nm,prng=prng,fixdof=fixdof ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.thermostat.bind(beads=self.beads,prng=prng, fixdof=fixdof) <NEW_LINE> <DEDENT> dget(self,"econs").add_dependency(dget(self.thermostat, "ethermo")) <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> self.ttime = -time.time() <NEW_LINE> self.thermostat.step() <NEW_LINE> self.rmcom() <NEW_LINE> self.ttime += time.time() <NEW_LINE> self.ptime = -time.time() <NEW_LINE> self.pstep() <NEW_LINE> self.ptime += time.time() <NEW_LINE> self.qtime = -time.time() <NEW_LINE> self.qcstep() <NEW_LINE> self.nm.free_qstep() <NEW_LINE> self.qtime += time.time() <NEW_LINE> self.ptime -= time.time() <NEW_LINE> self.pstep() <NEW_LINE> self.ptime += time.time() <NEW_LINE> self.ttime -= time.time() <NEW_LINE> self.thermostat.step() <NEW_LINE> self.rmcom() <NEW_LINE> self.ttime += time.time() <NEW_LINE> <DEDENT> def get_econs(self): <NEW_LINE> <INDENT> return NVEEnsemble.get_econs(self) + self.thermostat.ethermo | Ensemble object for constant temperature simulations.
Has the relevant conserved quantity and normal mode propagator for the
constant temperature ensemble. Contains a thermostat object containing the
algorithms to keep the temperature constant.
Attributes:
thermostat: A thermostat object to keep the temperature constant.
Depend objects:
econs: Conserved energy quantity. Depends on the bead kinetic and
potential energy, the spring potential energy and the heat
transferred to the thermostat. | 625990591f037a2d8b9e5345 |
class SqlComment(Base): <NEW_LINE> <INDENT> __tablename__ = 'comments' <NEW_LINE> id = sqla.Column(sqla.String, primary_key=True) <NEW_LINE> nid = sqla.Column(sqla.Integer) <NEW_LINE> comment_text = sqla.Column(sqla.String) <NEW_LINE> comment_signature = sqla.Column(sqla.String) <NEW_LINE> posting_date = sqla.Column(sqla.DateTime) <NEW_LINE> post_url = sqla.Column(sqla.String) <NEW_LINE> votes = sqla.Column(sqla.Integer) <NEW_LINE> last_seen = sqla.Column(sqla.DateTime) <NEW_LINE> desaparecido = sqla.Column(sqla.Boolean) <NEW_LINE> false_desaparecido = sqla.Column(sqla.Boolean) <NEW_LINE> when_desaparecido = sqla.Column(sqla.DateTime) <NEW_LINE> def __init__(self, item): <NEW_LINE> <INDENT> self.nid = item['_id'] <NEW_LINE> self.comment_text = item.get('testo') <NEW_LINE> self.comment_signature = item.get('firma') <NEW_LINE> self.posting_date = item.get('data') <NEW_LINE> self.post_url = item.get('post') <NEW_LINE> self.votes = item.get('voti') <NEW_LINE> self.last_seen = datetime.now() <NEW_LINE> self.desaparecido=False <NEW_LINE> self.false_desaparecido=False <NEW_LINE> self.id = "%s+%s" % (self.post_url, self.nid) | Object used to store a comment in a DB | 625990598da39b475be0479a |
class RegistroF210(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'F210'), CampoNumerico(2, 'VL_CUS_ORC', obrigatorio=True), CampoNumerico(3, 'VL_EXC', obrigatorio=True), CampoNumerico(4, 'VL_CUS_ORC_AJU', obrigatorio=True), CampoNumerico(5, 'VL_BC_CRED', obrigatorio=True), CampoNumerico(6, 'CST_PIS', obrigatorio=True), CampoNumerico(7, 'ALIQ_PIS'), CampoNumerico(8, 'VL_CRED_PIS_UTIL'), CampoNumerico(9, 'CST_COFINS', obrigatorio=True), CampoNumerico(10, 'ALIQ_COFINS'), CampoNumerico(11, 'VL_CRED_COFINS_UTIL'), ] <NEW_LINE> nivel = 4 | Operações da Atividade Imobiliária – Custo Orçado da Unidade Imobiliária Vendida | 6259905907f4c71912bb09ef |
class LocalizedObjectAnnotation(proto.Message): <NEW_LINE> <INDENT> mid = proto.Field(proto.STRING, number=1,) <NEW_LINE> language_code = proto.Field(proto.STRING, number=2,) <NEW_LINE> name = proto.Field(proto.STRING, number=3,) <NEW_LINE> score = proto.Field(proto.FLOAT, number=4,) <NEW_LINE> bounding_poly = proto.Field(proto.MESSAGE, number=5, message=geometry.BoundingPoly,) | Set of detected objects with bounding boxes.
Attributes:
mid (str):
Object ID that should align with
EntityAnnotation mid.
language_code (str):
The BCP-47 language code, such as "en-US" or "sr-Latn". For
more information, see
http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
name (str):
Object name, expressed in its ``language_code`` language.
score (float):
Score of the result. Range [0, 1].
bounding_poly (google.cloud.vision_v1p4beta1.types.BoundingPoly):
Image region to which this object belongs.
This must be populated. | 62599059097d151d1a2c2620 |
class IntelPart(): <NEW_LINE> <INDENT> def __init__(self, family:str, device:str): <NEW_LINE> <INDENT> self.family = family <NEW_LINE> self.device = device <NEW_LINE> <DEDENT> def as_tuple(self): <NEW_LINE> <INDENT> return ( self.family, self.device, ) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.as_tuple() == other.as_tuple() <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.as_tuple()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"<{self.__class__.__name__:s} {self.family:s} {self.device}>" | Intel/Altera FPGA model name specification | 62599059a8ecb033258727cc |
class Number(float): <NEW_LINE> <INDENT> def __neg__(self): <NEW_LINE> <INDENT> n = float.__new__(self.__class__, -float(self)) <NEW_LINE> return n | A floating-point number without dimension. | 625990594e4d5625663739bb |
class Pad(Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.source = rtmidi.MidiIn() <NEW_LINE> self.score = 0.0 <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self.source.get_port_count() > 0: <NEW_LINE> <INDENT> self.source.open_port(1) <NEW_LINE> self.loop = True <NEW_LINE> compteur , acc , score = 0.0, 0.0 , 0.0 <NEW_LINE> toWatt = 2 <NEW_LINE> while(self.loop): <NEW_LINE> <INDENT> time.sleep(0.01) <NEW_LINE> data = self.source.get_message() <NEW_LINE> compteur += 0.01 <NEW_LINE> if data: <NEW_LINE> <INDENT> acc += 1 <NEW_LINE> <DEDENT> if compteur > 0.4: <NEW_LINE> <INDENT> self.score = self.score + acc - self.score <NEW_LINE> self.score = self.score * toWatt <NEW_LINE> acc , compteur = 0.0 , 0.0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.loop = False | docstring for Pad | 62599059dd821e528d6da45a |
class Controller(abc.ABC): <NEW_LINE> <INDENT> VIEW = None <NEW_LINE> def get(self, **kwargs): <NEW_LINE> <INDENT> return abort(404) <NEW_LINE> <DEDENT> def post(self, **kwargs): <NEW_LINE> <INDENT> return abort(404) <NEW_LINE> <DEDENT> def put(self, **kwargs): <NEW_LINE> <INDENT> return abort(404) <NEW_LINE> <DEDENT> def delete(self, **kwargs): <NEW_LINE> <INDENT> return abort(404) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.__class__.__name__) | Controller base class | 625990593539df3088ecd851 |
class GAKHcoin(Bitcoin): <NEW_LINE> <INDENT> name = 'gakhcoin' <NEW_LINE> symbols = ('GAKH', ) <NEW_LINE> nodes = ("46.166.168.155", ) <NEW_LINE> port = 7829 | Class with all the necessary GAKHcoin network information based on
https://github.com/gakh/GAKHcoin/blob/master/src/net.cpp
(date of access: 02/15/2018) | 625990598a43f66fc4bf3742 |
class VGG2L(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self, idim: int, odim: int, pos_enc: torch.nn.Module = None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.vgg2l = torch.nn.Sequential( torch.nn.Conv2d(1, 64, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.Conv2d(64, 64, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.MaxPool2d((3, 2)), torch.nn.Conv2d(64, 128, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.Conv2d(128, 128, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.MaxPool2d((2, 2)), ) <NEW_LINE> if pos_enc is not None: <NEW_LINE> <INDENT> self.output = torch.nn.Sequential( torch.nn.Linear(128 * ((idim // 2) // 2), odim), pos_enc ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.output = torch.nn.Linear(128 * ((idim // 2) // 2), odim) <NEW_LINE> <DEDENT> <DEDENT> def forward( self, x: torch.Tensor, x_mask: torch.Tensor ) -> Union[ Tuple[torch.Tensor, torch.Tensor], Tuple[Tuple[torch.Tensor, torch.Tensor], torch.Tensor], ]: <NEW_LINE> <INDENT> x = x.unsqueeze(1) <NEW_LINE> x = self.vgg2l(x) <NEW_LINE> b, c, t, f = x.size() <NEW_LINE> x = self.output(x.transpose(1, 2).contiguous().view(b, t, c * f)) <NEW_LINE> if x_mask is not None: <NEW_LINE> <INDENT> x_mask = self.create_new_mask(x_mask) <NEW_LINE> <DEDENT> return x, x_mask <NEW_LINE> <DEDENT> def create_new_mask(self, x_mask: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> x_t1 = x_mask.size(2) - (x_mask.size(2) % 3) <NEW_LINE> x_mask = x_mask[:, :, :x_t1][:, :, ::3] <NEW_LINE> x_t2 = x_mask.size(2) - (x_mask.size(2) % 2) <NEW_LINE> x_mask = x_mask[:, :, :x_t2][:, :, ::2] <NEW_LINE> return x_mask | VGG2L module for custom encoder.
Args:
idim: Dimension of inputs
odim: Dimension of outputs
pos_enc: Positional encoding class | 625990597cff6e4e811b6ff8 |
class StackedAlternatingLstm(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_size: int, hidden_size: int, num_layers: int, recurrent_dropout_probability: float = 0.0, use_highway: bool = True, use_input_projection_bias: bool = True) -> None: <NEW_LINE> <INDENT> super(StackedAlternatingLstm, self).__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.num_layers = num_layers <NEW_LINE> layers = [] <NEW_LINE> lstm_input_size = input_size <NEW_LINE> for layer_index in range(num_layers): <NEW_LINE> <INDENT> go_forward = True if layer_index % 2 == 0 else False <NEW_LINE> layer = AugmentedLstm(lstm_input_size, hidden_size, go_forward, recurrent_dropout_probability=recurrent_dropout_probability, use_highway=use_highway, use_input_projection_bias=use_input_projection_bias) <NEW_LINE> lstm_input_size = hidden_size <NEW_LINE> self.add_module('layer_{}'.format(layer_index), layer) <NEW_LINE> layers.append(layer) <NEW_LINE> <DEDENT> self.lstm_layers = layers <NEW_LINE> <DEDENT> def forward(self, inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None): <NEW_LINE> <INDENT> if not initial_state: <NEW_LINE> <INDENT> hidden_states = [None] * len(self.lstm_layers) <NEW_LINE> <DEDENT> elif initial_state[0].size()[0] != len(self.lstm_layers): <NEW_LINE> <INDENT> raise ConfigurationError("Initial states were passed to forward() but the number of " "initial states does not match the number of layers.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hidden_states = list(zip(initial_state[0].split(1, 0), initial_state[1].split(1, 0))) <NEW_LINE> <DEDENT> output_sequence = inputs <NEW_LINE> final_states = [] <NEW_LINE> for i, state in enumerate(hidden_states): <NEW_LINE> <INDENT> layer = getattr(self, 'layer_{}'.format(i)) <NEW_LINE> output_sequence, final_state = layer(output_sequence, state) <NEW_LINE> final_states.append(final_state) <NEW_LINE> <DEDENT> final_state_tuple = (torch.cat(state_list, 0) for state_list in zip(*final_states)) <NEW_LINE> return output_sequence, final_state_tuple | A stacked LSTM with LSTM layers which alternate between going forwards over
the sequence and going backwards. This implementation is based on the
description in `Deep Semantic Role Labelling - What works and what's next
<https://homes.cs.washington.edu/~luheng/files/acl2017_hllz.pdf>`_ .
Parameters
----------
input_size : int, required
The dimension of the inputs to the LSTM.
hidden_size : int, required
The dimension of the outputs of the LSTM.
num_layers : int, required
The number of stacked LSTMs to use.
recurrent_dropout_probability: float, optional (default = 0.0)
The dropout probability to be used in a dropout scheme as stated in
`A Theoretically Grounded Application of Dropout in Recurrent Neural Networks
<https://arxiv.org/abs/1512.05287>`_ .
use_input_projection_bias : bool, optional (default = True)
Whether or not to use a bias on the input projection layer. This is mainly here
for backwards compatibility reasons and will be removed (and set to False)
in future releases.
Returns
-------
output_accumulator : PackedSequence
The outputs of the interleaved LSTMs per timestep. A tensor of shape
(batch_size, max_timesteps, hidden_size) where for a given batch
element, all outputs past the sequence length for that batch are
zero tensors. | 62599059d53ae8145f919a16 |
class EmptyMaxMindFile: <NEW_LINE> <INDENT> def __init__(self, _): <NEW_LINE> <INDENT> utils.LOGGER.warning("Cannot find Maxmind database files") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def lookup(_): <NEW_LINE> <INDENT> return {} | Stub to replace MaxMind databases parsers. Used when a file is
missing to emit a warning message and return empty results. | 625990590fa83653e46f649b |
class Xfd(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "http://cgit.freedesktop.org/xorg/app/xfd" <NEW_LINE> url = "https://www.x.org/archive/individual/app/xfd-1.1.2.tar.gz" <NEW_LINE> version('1.1.2', '12fe8f7c3e71352bf22124ad56d4ceaf') <NEW_LINE> depends_on('libxaw') <NEW_LINE> depends_on('fontconfig') <NEW_LINE> depends_on('libxft') <NEW_LINE> depends_on('libxrender') <NEW_LINE> depends_on('libxmu') <NEW_LINE> depends_on('libxt') <NEW_LINE> depends_on('[email protected]:', type='build') <NEW_LINE> depends_on('pkgconfig', type='build') <NEW_LINE> depends_on('util-macros', type='build') | xfd - display all the characters in a font using either the
X11 core protocol or libXft2. | 62599059baa26c4b54d50859 |
class CheckboxTextboxDialog(CheckboxDialog): <NEW_LINE> <INDENT> def __init__(self, title, description, checkbox_text, checkbox_value, textbox_value, default_button, other_button): <NEW_LINE> <INDENT> super(CheckboxTextboxDialog, self).__init__(title, description, checkbox_text, checkbox_value, default_button, other_button) <NEW_LINE> self.textbox_value = textbox_value <NEW_LINE> <DEDENT> def run_callback(self, choice, checkbox_value=False, textbox_value=""): <NEW_LINE> <INDENT> self.textbox_value = textbox_value <NEW_LINE> super(CheckboxTextboxDialog, self).run_callback(choice, checkbox_value) | Like ``CheckboxDialog`` but also with a text area. Used for
capturing bug report data. | 62599059a79ad1619776b598 |
class KoruzaMonitor(registration.bases.NodeMonitoringRegistryItem): <NEW_LINE> <INDENT> serial_number = models.CharField(max_length=50, null=True) <NEW_LINE> mcu_connected = models.NullBooleanField() <NEW_LINE> motor_x = models.IntegerField(null=True) <NEW_LINE> motor_y = models.IntegerField(null=True) <NEW_LINE> accel_x_range1 = models.FloatField(null=True) <NEW_LINE> accel_x_range1_maximum = models.FloatField(null=True) <NEW_LINE> accel_x_range2 = models.FloatField(null=True) <NEW_LINE> accel_x_range2_maximum = models.FloatField(null=True) <NEW_LINE> accel_x_range3 = models.FloatField(null=True) <NEW_LINE> accel_x_range3_maximum = models.FloatField(null=True) <NEW_LINE> accel_x_range4 = models.FloatField(null=True) <NEW_LINE> accel_x_range4_maximum = models.FloatField(null=True) <NEW_LINE> accel_y_range1 = models.FloatField(null=True) <NEW_LINE> accel_y_range1_maximum = models.FloatField(null=True) <NEW_LINE> accel_y_range2 = models.FloatField(null=True) <NEW_LINE> accel_y_range2_maximum = models.FloatField(null=True) <NEW_LINE> accel_y_range3 = models.FloatField(null=True) <NEW_LINE> accel_y_range3_maximum = models.FloatField(null=True) <NEW_LINE> accel_y_range4 = models.FloatField(null=True) <NEW_LINE> accel_y_range4_maximum = models.FloatField(null=True) <NEW_LINE> accel_z_range1 = models.FloatField(null=True) <NEW_LINE> accel_z_range1_maximum = models.FloatField(null=True) <NEW_LINE> accel_z_range2 = models.FloatField(null=True) <NEW_LINE> accel_z_range2_maximum = models.FloatField(null=True) <NEW_LINE> accel_z_range3 = models.FloatField(null=True) <NEW_LINE> accel_z_range3_maximum = models.FloatField(null=True) <NEW_LINE> accel_z_range4 = models.FloatField(null=True) <NEW_LINE> accel_z_range4_maximum = models.FloatField(null=True) <NEW_LINE> class RegistryMeta: <NEW_LINE> <INDENT> registry_id = 'irnas.koruza' | KORUZA reported data. | 62599059f7d966606f749393 |
class TestWasInit(unittest.TestCase): <NEW_LINE> <INDENT> def test_returns_int(self): <NEW_LINE> <INDENT> self.assertIs(type(SDL_WasInit(0)), int) | Tests SDL_WasInit() | 6259905999cbb53fe6832495 |
class ResourceProviderOperation(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'is_data_action': {'readonly': True}, 'origin': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'ResourceProviderOperationDisplay'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, 'origin': {'key': 'origin', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ResourceProviderOperation, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.display = kwargs.get('display', None) <NEW_LINE> self.is_data_action = None <NEW_LINE> self.origin = None | Supported operation of this resource provider.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Operation name, in format of {provider}/{resource}/{operation}.
:type name: str
:param display: Display metadata associated with the operation.
:type display:
~azure.mgmt.kubernetesconfiguration.v2021_11_01_preview.models.ResourceProviderOperationDisplay
:ivar is_data_action: The flag that indicates whether the operation applies to data plane.
:vartype is_data_action: bool
:ivar origin: Origin of the operation.
:vartype origin: str | 62599059cb5e8a47e493cc61 |
@dataclass <NEW_LINE> class LearningRateDecay(Callback): <NEW_LINE> <INDENT> start: (int, list, tuple) <NEW_LINE> duration: int = 1 <NEW_LINE> factor: float = 0.1 <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> assert isinstance(self.start, (list, tuple, range, type(None))), "start must be a list or range or None" <NEW_LINE> self.start = [] if self.start is None else list(self.start) <NEW_LINE> <DEDENT> def init(self, exp): <NEW_LINE> <INDENT> self.learning_rate_setter = exp.set_learning_rate <NEW_LINE> self.learning_rate_getter = exp.get_learning_rate <NEW_LINE> self.learning_rate = self.learning_rate_getter() <NEW_LINE> self.batch_count = sum([len(subset.keys)//exp.batch_size for subset in exp.subsets if subset.type & SubsetType.TRAIN]) <NEW_LINE> self.start = [epoch_start * self.batch_count for epoch_start in self.start] <NEW_LINE> self.duration = self.duration * self.batch_count <NEW_LINE> assert all([not isinstance(cb, LearningRateWarmUp) for cb in exp.cfg['callbacks']]), f"{self.__class__} is incompatible with LearningRateWarmUp" <NEW_LINE> <DEDENT> def compute_factor(self, step): <NEW_LINE> <INDENT> step_factor = 1.0 <NEW_LINE> for start in self.start: <NEW_LINE> <INDENT> stop = start + self.duration <NEW_LINE> if step >= stop: <NEW_LINE> <INDENT> step_factor *= self.factor <NEW_LINE> <DEDENT> elif start < step < stop: <NEW_LINE> <INDENT> step_factor *= self.factor ** ((step - start)/self.duration) <NEW_LINE> <DEDENT> <DEDENT> return step_factor <NEW_LINE> <DEDENT> def on_batch_begin(self, cycle_type, epoch, batch, **_): <NEW_LINE> <INDENT> if cycle_type == SubsetType.TRAIN and self.start: <NEW_LINE> <INDENT> self.learning_rate_setter(self.learning_rate * self.compute_factor(step=epoch*self.batch_count + batch)) | Decay learning rate by a given factor spread on every batch for a given
number of epochs.
This callback is incompatible with a `LearningRateWarmUp` callback
because learning rate is set from both callbacks at the beginning of
each batch.
start and duration are expressed in epochs here | 6259905976e4537e8c3f0b42 |
class MinimalPackageSet(Model): <NEW_LINE> <INDENT> NAME = "minimal-package-set" <NEW_LINE> VENDOR = "source{d}" <NEW_LINE> DESCRIPTION = "Model that contains a set of libraries and their occurences in docker images." <NEW_LINE> LICENSE = "ODbL-1.0" <NEW_LINE> def construct(self, packages: pd.DataFrame, python_package_names: pd.DataFrame, default_packages: {str: [str]}=None): <NEW_LINE> <INDENT> self._packages = packages <NEW_LINE> self._python_package_names = python_package_names <NEW_LINE> if default_packages is not None: <NEW_LINE> <INDENT> self._default_packages = default_packages <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> default_packages = {distro: [] for distro in list(native_libs.groupby('distro').count().index)} <NEW_LINE> for lib in liboccurence.index.get_level_values('name'): <NEW_LINE> <INDENT> for distro in liboccurence.ix[lib].index: <NEW_LINE> <INDENT> if liboccurence[lib, distro] == nimage[distro]: <NEW_LINE> <INDENT> defaultlibs[distro] += [lib] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._default_packages = default_packages <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def search_by_name(name): <NEW_LINE> <INDENT> return names[ names.str.contains(r'' + re.escape(name.lower()) + r'', case=False) ].to_dict(orient='values') <NEW_LINE> <DEDENT> def get_minimal_libs(python_lib, quantile=0.95): <NEW_LINE> <INDENT> lib_images = libraries[libraries['name'] == python_lib]['image'] <NEW_LINE> co_occurences = libraries[libraries['type'] == 'native'] <NEW_LINE> co_occurences = co_occurences[co_occurences.image.isin(lib_images)] <NEW_LINE> quantiles = co_occurences.groupby(['name', 'distro'])[ 'image'].count().unstack().quantile(q=quantile) <NEW_LINE> cooc = co_occurences.groupby(['name', 'distro'])[ 'image'].count().unstack() <NEW_LINE> libs = {} <NEW_LINE> for index in quantiles.index: <NEW_LINE> <INDENT> libs[index] = cooc[index][cooc[index] >= quantiles[index]].index <NEW_LINE> <DEDENT> required_packages = {distro: set() for distro in defaultlibs} <NEW_LINE> for distro in libs: <NEW_LINE> <INDENT> required_packages[distro] = set(libs[distro])-set(defaultlibs[distro]) <NEW_LINE> <DEDENT> return required_packages | Simple co-occurence based model that finds minimal native package set needed to run
a python package. | 625990593cc13d1c6d466cf6 |
class Experiment: <NEW_LINE> <INDENT> def __init__(self, z, line, energy_eV, kratio=0.0, standard='', analyzed=True): <NEW_LINE> <INDENT> self._z = z <NEW_LINE> self._line = line <NEW_LINE> self._energy_eV = energy_eV <NEW_LINE> self._kratio = kratio <NEW_LINE> self._standard = standard <NEW_LINE> self._analyzed = analyzed <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> line = {LINE_KA: 'Ka', LINE_KB: 'Kb', LINE_LA: 'La', LINE_LB: 'Lb', LINE_MA: 'Ma', LINE_MB: 'Mb'}[self.line] <NEW_LINE> energy_keV = self.energy_eV / 1e3 <NEW_LINE> standard = self.standard if self.standard else 'pure' <NEW_LINE> extra = 'analyzed' if self.is_analyzed() else 'not analyzed' <NEW_LINE> return '<Experiment(%s %s, %s kV, kratio=%.4f, standard=%s, %s)>' % (symbol(self.z), line, energy_keV, self.kratio, standard, extra) <NEW_LINE> <DEDENT> def is_analyzed(self): <NEW_LINE> <INDENT> return self._analyzed <NEW_LINE> <DEDENT> @property <NEW_LINE> def z(self): <NEW_LINE> <INDENT> return self._z <NEW_LINE> <DEDENT> @property <NEW_LINE> def line(self): <NEW_LINE> <INDENT> return self._line <NEW_LINE> <DEDENT> @property <NEW_LINE> def energy_eV(self): <NEW_LINE> <INDENT> return self._energy_eV <NEW_LINE> <DEDENT> @property <NEW_LINE> def kratio(self): <NEW_LINE> <INDENT> return self._kratio <NEW_LINE> <DEDENT> @property <NEW_LINE> def standard(self): <NEW_LINE> <INDENT> return self._standard | Object to store experimental parameters and measurements.
Once created an experiment object is immutable. | 625990596e29344779b01c02 |
class NoDbTestRunner(DjangoTestSuiteRunner): <NEW_LINE> <INDENT> def setup_databases(self, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def teardown_databases(self, old_config, **kwargs): <NEW_LINE> <INDENT> pass | A test runner to test without memory database creation | 62599059498bea3a75a590d7 |
class GraphOptions(object): <NEW_LINE> <INDENT> x_axis_data = None <NEW_LINE> y_axis_data = None <NEW_LINE> def __init__(self, x_axis_data, y_axis_data): <NEW_LINE> <INDENT> self.x_axis_data = x_axis_data <NEW_LINE> self.y_axis_data = y_axis_data <NEW_LINE> <DEDENT> @property <NEW_LINE> def x_axis_label(self): <NEW_LINE> <INDENT> return 'Time (min)' if self.x_axis_data == 'time' else 'Distance (km)' <NEW_LINE> <DEDENT> @property <NEW_LINE> def y_axis_label(self): <NEW_LINE> <INDENT> return 'Speed (km/h)' if self.y_axis_data == 'speed' else 'Pace (min/km)' | GraphOptions allow to set the value for the x and y axis | 625990593539df3088ecd852 |
class CustomStructure(Structure): <NEW_LINE> <INDENT> _defaults_ = {} <NEW_LINE> _translation_ = {} <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> Structure.__init__(self) <NEW_LINE> self.__field_names = [ f for (f, t) in self._fields_] <NEW_LINE> self.update(self._defaults_) <NEW_LINE> <DEDENT> def update(self, dict): <NEW_LINE> <INDENT> for k, v in dict.items(): <NEW_LINE> <INDENT> if k in self.__field_names: <NEW_LINE> <INDENT> setattr(self, k, self.__translate(k, v)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('No such member: ' + k) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> if k in self.__field_names: <NEW_LINE> <INDENT> return self.__translate_back(k, getattr(self, k)) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> if k in self.__field_names: <NEW_LINE> <INDENT> setattr(self, k, self.__translate(k, v)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('No such member: ' + k) <NEW_LINE> <DEDENT> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self.__field_names <NEW_LINE> <DEDENT> def __translate(self, k, v): <NEW_LINE> <INDENT> if k in self._translation_: <NEW_LINE> <INDENT> if v in self._translation_[k]: <NEW_LINE> <INDENT> return self._translation_[k][v] <NEW_LINE> <DEDENT> <DEDENT> return v <NEW_LINE> <DEDENT> def __translate_back(self, k, v): <NEW_LINE> <INDENT> if k in self._translation_: <NEW_LINE> <INDENT> for tk, tv in self._translation_[k].items(): <NEW_LINE> <INDENT> if tv == v: <NEW_LINE> <INDENT> return tk <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return v | This class extends the functionality of the ctype's structure
class by adding custom default values to the fields and a way of translating
field types. | 6259905910dbd63aa1c72155 |
class WorkerData(object): <NEW_LINE> <INDENT> def __init__(self, input, starttime=None, failure=""): <NEW_LINE> <INDENT> self.input = input <NEW_LINE> self.starttime = starttime or walltime() <NEW_LINE> self.failure = failure | Simple class which stores data about a running ``p_iter_fork``
worker.
This just stores three attributes:
- ``input``: the input value used by this worker
- ``starttime``: the walltime when this worker started
- ``failure``: an optional message indicating the kind of failure
EXAMPLES::
sage: from sage.parallel.use_fork import WorkerData
sage: W = WorkerData(42); W
<sage.parallel.use_fork.WorkerData object at ...>
sage: W.starttime # random
1499330252.463206 | 6259905915baa72349463549 |
class Unit(object): <NEW_LINE> <INDENT> def __init__(self, crawler, parent, tags, level, typ, pattern, parent_tag_indices=None): <NEW_LINE> <INDENT> self.crawler = crawler <NEW_LINE> self.parent = parent <NEW_LINE> self.tags = tags <NEW_LINE> self.level = level <NEW_LINE> self.typ = typ <NEW_LINE> self.pattern = pattern <NEW_LINE> self.parent_tag_indices = parent_tag_indices <NEW_LINE> self.children_units = [] <NEW_LINE> self.irregular = False <NEW_LINE> self.label = None <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> text = "" <NEW_LINE> if self.typ == 0: <NEW_LINE> <INDENT> for tag in self.tags: <NEW_LINE> <INDENT> text += " " + util.text_from_el(tag) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for ind, tag in enumerate(self.tags): <NEW_LINE> <INDENT> if ind not in self.parent_tag_indices: <NEW_LINE> <INDENT> text += " " + util.text_from_el(tag) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return text.strip() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return unicode(self).encode('utf-8') <NEW_LINE> <DEDENT> def get_tags_interval(self): <NEW_LINE> <INDENT> tags_in_parent = filter(lambda x : isinstance(x, Tag), self.parent.contents) <NEW_LINE> start = 0 <NEW_LINE> stop = 0 <NEW_LINE> ind = 0 <NEW_LINE> if len(self.tags) == 1: <NEW_LINE> <INDENT> index = tags_in_parent.index(self.tags[0]) <NEW_LINE> return (index, index) <NEW_LINE> <DEDENT> for t in tags_in_parent: <NEW_LINE> <INDENT> if t == self.tags[0]: <NEW_LINE> <INDENT> start = ind <NEW_LINE> <DEDENT> if t == self.tags[-1]: <NEW_LINE> <INDENT> stop = ind <NEW_LINE> break <NEW_LINE> <DEDENT> ind += 1 <NEW_LINE> <DEDENT> if stop < start: <NEW_LINE> <INDENT> stop = start <NEW_LINE> <DEDENT> return (start, stop) <NEW_LINE> <DEDENT> def get_level_one_tags_count(self): <NEW_LINE> <INDENT> tags_in_parent = filter(lambda x : isinstance(x, Tag), self.parent.contents) <NEW_LINE> count = 0 <NEW_LINE> for t in self.tags: <NEW_LINE> <INDENT> if t in tags_in_parent: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> return count | Unit is a set of elements (for example [p, p, div]) which is found to be repeated. | 6259905999cbb53fe6832496 |
class ProblemReport(AgentMessage): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> handler_class = HANDLER_CLASS <NEW_LINE> message_type = PROBLEM_REPORT <NEW_LINE> schema_class = "ProblemReportSchema" <NEW_LINE> <DEDENT> def __init__( self, *, msg_catalog: str = None, locale: str = None, explain_ltxt: str = None, explain_l10n: Mapping[str, str] = None, problem_items: Sequence[Mapping[str, str]] = None, who_retries: str = None, fix_hint_ltxt: Mapping[str, str] = None, impact: str = None, where: str = None, time_noticed: str = None, tracking_uri: str = None, escalation_uri: str = None, **kwargs, ): <NEW_LINE> <INDENT> super(ProblemReport, self).__init__(**kwargs) <NEW_LINE> self.msg_catalog = msg_catalog <NEW_LINE> self.locale = locale <NEW_LINE> self.explain_ltxt = explain_ltxt <NEW_LINE> self.explain_l10n = explain_l10n <NEW_LINE> self.problem_items = problem_items <NEW_LINE> self.who_retries = who_retries <NEW_LINE> self.fix_hint_ltxt = fix_hint_ltxt <NEW_LINE> self.impact = impact <NEW_LINE> self.where = where <NEW_LINE> self.time_noticed = time_noticed <NEW_LINE> self.tracking_uri = tracking_uri <NEW_LINE> self.escalation_uri = escalation_uri | Base class representing a generic problem report message. | 62599059009cb60464d02aec |
class RadioButton(Gtk.RadioButton): <NEW_LINE> <INDENT> def __init__(self, group, label): <NEW_LINE> <INDENT> Gtk.RadioButton.__init__(self, group, label) | A radio button | 625990599c8ee82313040c66 |
class Git_API_handler(Git_handler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> my_data = json.loads(self.request.body) <NEW_LINE> current_path = my_data["current_path"] <NEW_LINE> showtoplevel = self.git.showtoplevel(current_path) <NEW_LINE> if(showtoplevel['code'] != 0): <NEW_LINE> <INDENT> self.finish(json.dumps(showtoplevel)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> branch = self.git.branch(current_path) <NEW_LINE> log = self.git.log(current_path) <NEW_LINE> status = self.git.status(current_path) <NEW_LINE> result = { "code": showtoplevel['code'], 'data': { 'showtoplevel': showtoplevel, 'branch': branch, 'log': log, 'status': status}} <NEW_LINE> self.finish(json.dumps(result)) | A single class to give you 4 git commands combined:
1. git showtoplevel
2. git branch
3. git log
4. git status
Class is used in the refresh method | 625990594428ac0f6e659af3 |
class ConfirmationMessage(ProtocolMessage): <NEW_LINE> <INDENT> def __init__(self, confirmed_resources): <NEW_LINE> <INDENT> ProtocolMessage.__init__(self) <NEW_LINE> if type(confirmed_resources) is not list: <NEW_LINE> <INDENT> raise ValueError('confirmed_resources must be a list of str') <NEW_LINE> <DEDENT> for element in confirmed_resources: <NEW_LINE> <INDENT> if type(element) is not str: <NEW_LINE> <INDENT> raise ValueError('confirmed_resources must be a list of str') <NEW_LINE> <DEDENT> <DEDENT> self.data['confirmed_resources'] = confirmed_resources <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, message_dict): <NEW_LINE> <INDENT> return cls(message_dict['confirmed_resources']) | Confirm subscriptions | 62599059cb5e8a47e493cc62 |
class PerlEncodeLocale(PerlPackage): <NEW_LINE> <INDENT> homepage = "http://search.cpan.org/~gaas/Encode-Locale-1.05/lib/Encode/Locale.pm" <NEW_LINE> url = "http://search.cpan.org/CPAN/authors/id/G/GA/GAAS/Encode-Locale-1.05.tar.gz" <NEW_LINE> version('1.05', sha256='176fa02771f542a4efb1dbc2a4c928e8f4391bf4078473bd6040d8f11adb0ec1') | Determine the locale encoding | 62599059004d5f362081fac9 |
class Task(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> category = models.ForeignKey(Category, on_delete=models.CASCADE) <NEW_LINE> details = models.TextField() <NEW_LINE> deadline = models.DateTimeField() <NEW_LINE> archive = models.BooleanField(default=False) <NEW_LINE> targets = models.ManyToManyField('people.Staff', blank=True) <NEW_LINE> groups = models.ManyToManyField(Group, blank=True) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> modified = models.DateTimeField(auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name + ' due ' + str(self.deadline) <NEW_LINE> <DEDENT> def get_all_targets(self): <NEW_LINE> <INDENT> target_by_users = self.targets.all().order_by('user__last_name') <NEW_LINE> target_groups = self.groups.all() <NEW_LINE> target_by_groups = User.objects.all().filter(groups__in=target_groups).distinct().order_by('last_name') <NEW_LINE> all_targets = target_by_users <NEW_LINE> for user in target_by_groups: <NEW_LINE> <INDENT> staff = Staff.objects.all().filter(user=user) <NEW_LINE> all_targets = all_targets | staff <NEW_LINE> <DEDENT> all_targets = all_targets.distinct() <NEW_LINE> return all_targets <NEW_LINE> <DEDENT> def is_urgent(self): <NEW_LINE> <INDENT> now = datetime.datetime.utcnow().replace(tzinfo=utc) <NEW_LINE> seconds_left = (self.deadline - now).total_seconds() <NEW_LINE> return bool(seconds_left < 60 * 60 * 24 * 7) <NEW_LINE> <DEDENT> def is_overdue(self): <NEW_LINE> <INDENT> now = datetime.datetime.utcnow().replace(tzinfo=utc) <NEW_LINE> seconds_left = (self.deadline - now).total_seconds() <NEW_LINE> return bool(seconds_left < 0) | A task that members of staff will be allocated
These are usually much smaller than Activities and are deadline driven
name a name for the task
category see the Category model
details a potentially large area of text giving more information
deadline the time by which the task should be completed
archive whether the task is completed / archived
targets those staff the task is allocated to
See also the TaskCompletion model. Note that targets should not be removed
on completion. | 62599059e76e3b2f99fd9fb7 |
class MinimizerIndexer(object): <NEW_LINE> <INDENT> def __init__(self, targetString, w, k, t): <NEW_LINE> <INDENT> self.targetString = targetString <NEW_LINE> self.w = w <NEW_LINE> self.k = k <NEW_LINE> self.t = t <NEW_LINE> self.minimizerMap = {} <NEW_LINE> self.minmerOccurrences = {} <NEW_LINE> print('Value of t:', self.t) <NEW_LINE> baseSet = set('ACGT') <NEW_LINE> for i in range(len(targetString)-self.w+1): <NEW_LINE> <INDENT> minmer = str() <NEW_LINE> candidateMinmers = list() <NEW_LINE> for j in range(self.w-self.k+1): <NEW_LINE> <INDENT> candidateMinmer = targetString[i+j:i+j+self.k] <NEW_LINE> candidateMinmers.append((candidateMinmer, i+j)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> minmerTuple = min(candidateMinmers) <NEW_LINE> minmer = minmerTuple[0] <NEW_LINE> site = minmerTuple[1] <NEW_LINE> if set(minmer) <= baseSet: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if site not in self.minmerOccurrences[minmer]: <NEW_LINE> <INDENT> self.minmerOccurrences[minmer].append(site) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.minmerOccurrences[minmer] = list() <NEW_LINE> self.minmerOccurrences[minmer].append(site) <NEW_LINE> <DEDENT> if len(self.minmerOccurrences[minmer]) > self.t: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.minimizerMap[minmer] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if site not in self.minimizerMap[minmer]: <NEW_LINE> <INDENT> self.minimizerMap[minmer].append(site) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.minimizerMap[minmer] = [site] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getMatches(self, searchString): <NEW_LINE> <INDENT> yieldedSites = list() <NEW_LINE> for i in range(len(searchString)-self.w+1): <NEW_LINE> <INDENT> minmer = str() <NEW_LINE> sites = list() <NEW_LINE> for j in range(self.w-self.k+1): <NEW_LINE> <INDENT> candidateMinmer = searchString[i+j:i+j+self.k] <NEW_LINE> if not minmer or candidateMinmer < minmer: <NEW_LINE> <INDENT> minmer = candidateMinmer <NEW_LINE> sites = [int(i+j)] <NEW_LINE> <DEDENT> <DEDENT> if sites[0] not in yieldedSites and self.minimizerMap.get(minmer): <NEW_LINE> <INDENT> yieldedSites.append(sites[0]) <NEW_LINE> yield (sites[0], self.minimizerMap[minmer]) | Simple minimizer based substring-indexer.
Please read: https://doi.org/10.1093/bioinformatics/bth408
Related to idea of min-hash index and other "sketch" methods. | 62599059627d3e7fe0e08445 |
class CreatePostView(LoginRequiredMixin, CreateView): <NEW_LINE> <INDENT> template_name = 'posts/new.html' <NEW_LINE> form_class = PostForm <NEW_LINE> success_url = reverse_lazy('posts:feed') <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['user'] = self.request.user <NEW_LINE> context['profile'] = self.request.user.profile <NEW_LINE> return context | Create a new post | 6259905956ac1b37e63037c3 |
class IFikaUser(Interface): <NEW_LINE> <INDENT> pass | Adapter to extend functionality of base fika users.
| 6259905976e4537e8c3f0b44 |
class AnimatedProgressBar(ProgressBar): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AnimatedProgressBar, self).__init__(*args, **kwargs) <NEW_LINE> self.stdout = kwargs.get('stdout', sys.stdout) <NEW_LINE> <DEDENT> def show_progress(self): <NEW_LINE> <INDENT> if hasattr(self.stdout, 'isatty') and self.stdout.isatty(): <NEW_LINE> <INDENT> self.stdout.write('\r') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stdout.write('\n') <NEW_LINE> <DEDENT> self.stdout.write(str(self)) <NEW_LINE> self.stdout.flush() <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> self.stdout.write('\n') | Extends ProgressBar to allow you to use it straighforward on a script.
Accepts an extra keyword argument named `stdout` (by default use sys.stdout)
and may be any file-object to which send the progress status. | 62599059435de62698e9d3bc |
class TestDestinyDefinitionsDestinyObjectiveDefinition(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDestinyDefinitionsDestinyObjectiveDefinition(self): <NEW_LINE> <INDENT> pass | DestinyDefinitionsDestinyObjectiveDefinition unit test stubs | 6259905923849d37ff85267e |
class KNearestNeighbor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train(self, X, y): <NEW_LINE> <INDENT> self.X_train = X <NEW_LINE> self.y_train = y <NEW_LINE> <DEDENT> def predict(self, X, k=1, num_loops=0): <NEW_LINE> <INDENT> if num_loops == 0: <NEW_LINE> <INDENT> dists = self.compute_distances_no_loops(X) <NEW_LINE> <DEDENT> elif num_loops == 1: <NEW_LINE> <INDENT> dists = self.compute_distances_one_loop(X) <NEW_LINE> <DEDENT> elif num_loops == 2: <NEW_LINE> <INDENT> dists = self.compute_distances_two_loops(X) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value %d for num_loops' % num_loops) <NEW_LINE> <DEDENT> return self.predict_labels(dists, k=k) <NEW_LINE> <DEDENT> def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> for j in range(num_train): <NEW_LINE> <INDENT> dists[i,j]=np.sqrt(np.sum(np.square(self.X_train[j,:]-X[i,:]))) <NEW_LINE> <DEDENT> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_one_loop(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> dists[i] = np.sqrt(np.sum(np.square(self.X_train-X[i]),axis=1)) <NEW_LINE> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> mul = np.dot(X,self.X_train.T) <NEW_LINE> test_norm = np.sum(np.square(X),axis=1,keepdims=True) <NEW_LINE> test_norm = np.tile(test_norm,(1,num_train)) <NEW_LINE> train_norm = np.sum(np.square(self.X_train),axis=1) <NEW_LINE> train_norm = np.tile(train_norm,(num_test,1)) <NEW_LINE> dists=np.sqrt(test_norm+train_norm-2*mul) <NEW_LINE> return dists <NEW_LINE> <DEDENT> def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> closest_y = self.y_train[np.argsort(dists[i])[:k]] <NEW_LINE> y_pred[i] = np.argmax(np.bincount(closest_y)) <NEW_LINE> <DEDENT> return y_pred | a kNN classifier with L2 distance | 6259905901c39578d7f14213 |
class AnnualFuelCost(BSElement): <NEW_LINE> <INDENT> element_type = "xs:decimal" | Annual cost of the resource ($) | 62599059462c4b4f79dbcfbe |
class StaticModule(DashboardModuleViewBase): <NEW_LINE> <INDENT> pass | Render a static template | 62599059d6c5a102081e36d9 |
class BaseUnaryOp(CSTNode, ABC): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> whitespace_after: BaseParenthesizableWhitespace <NEW_LINE> def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "BaseUnaryOp": <NEW_LINE> <INDENT> return self.__class__( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) <NEW_LINE> <DEDENT> def _codegen_impl(self, state: CodegenState) -> None: <NEW_LINE> <INDENT> state.add_token(self._get_token()) <NEW_LINE> self.whitespace_after._codegen(state) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _get_token(self) -> str: <NEW_LINE> <INDENT> ... | Any node that has a static value used in a :class:`UnaryOperation` expression. | 625990592ae34c7f260ac6a0 |
class BasicTypeInfo(TypeInformation, ABC): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def STRING_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo(get_gateway().jvm .org.apache.flink.api.common.typeinfo.BasicTypeInfo.STRING_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def BOOLEAN_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.BOOLEAN_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def BYTE_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.BYTE_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def SHORT_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.SHORT_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def INT_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.INT_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def LONG_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.LONG_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def FLOAT_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.FLOAT_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def DOUBLE_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.DOUBLE_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def CHAR_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.CHAR_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def BIG_INT_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.BIG_INT_TYPE_INFO) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def BIG_DEC_TYPE_INFO(): <NEW_LINE> <INDENT> return WrapperTypeInfo( get_gateway().jvm.org.apache.flink.api.common.typeinfo.BasicTypeInfo.BIG_DEC_TYPE_INFO) | Type information for primitive types (int, long, double, byte, ...), String, BigInteger,
and BigDecimal. | 6259905956b00c62f0fb3e84 |
class menuimage(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, screen, spritetype="", imagename="", position = (), transparent = False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.image = import_image(spritetype, imagename) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> if transparent: <NEW_LINE> <INDENT> self.image.set_colorkey(self.image.get_at((0,0))) <NEW_LINE> <DEDENT> if position == (): <NEW_LINE> <INDENT> self.rect.left = 0 <NEW_LINE> self.rect.top = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect.left = position[0] <NEW_LINE> self.rect.top = position[1] <NEW_LINE> <DEDENT> <DEDENT> def update_image(self, spritetype, imagename): <NEW_LINE> <INDENT> centre = self.rect.center <NEW_LINE> self.image = import_image(spritetype, imagename) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.image.set_colorkey(self.image.get_at((0,0))) <NEW_LINE> self.mask = pygame.mask.from_surface(self.image) <NEW_LINE> self.rect.center = centre | Class to display all menu images as sprites. | 625990590a50d4780f70689b |
class EntersXEnsemble(ExitsXEnsemble): <NEW_LINE> <INDENT> def _str(self): <NEW_LINE> <INDENT> domain = 'exists x[t], x[t+1] ' <NEW_LINE> result = 'such that x[t] not in {0} and x[t+1] in {0}'.format( self._volume) <NEW_LINE> return domain + result <NEW_LINE> <DEDENT> def __call__(self, trajectory, trusted=None, candidate=False): <NEW_LINE> <INDENT> subtraj = trajectory <NEW_LINE> for i in range(len(subtraj) - 1): <NEW_LINE> <INDENT> frame_i = subtraj.get_as_proxy(i) <NEW_LINE> if not self._volume(frame_i): <NEW_LINE> <INDENT> frame_iplus = subtraj.get_as_proxy(i + 1) <NEW_LINE> if self._volume(frame_iplus): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False | Represents an ensemble where two successive frames from the selected
frames of the trajectory crossing from outside to inside the given volume. | 62599059a17c0f6771d5d67e |
class ElectricEngine(Engine): <NEW_LINE> <INDENT> pass | Electric engine. | 62599059004d5f362081faca |
class RetryableException(ElongException): <NEW_LINE> <INDENT> pass | 可以重试的异常,如网络连接错误等 | 6259905956ac1b37e63037c4 |
class RichText(Object): <NEW_LINE> <INDENT> implements(IRichText, IFromUnicode) <NEW_LINE> default_mime_type = 'text/html' <NEW_LINE> output_mime_type = 'text/x-html-safe' <NEW_LINE> allowed_mime_types = None <NEW_LINE> max_length = None <NEW_LINE> def __init__(self, default_mime_type='text/html', output_mime_type='text/x-html-safe', allowed_mime_types=None, max_length=None, schema=IRichTextValue, **kw ): <NEW_LINE> <INDENT> self.default_mime_type = default_mime_type <NEW_LINE> self.output_mime_type = output_mime_type <NEW_LINE> self.allowed_mime_types = allowed_mime_types <NEW_LINE> self.max_length = max_length <NEW_LINE> if 'default' in kw: <NEW_LINE> <INDENT> default = kw['default'] <NEW_LINE> if isinstance(default, unicode): <NEW_LINE> <INDENT> kw['default'] = self.fromUnicode(default) <NEW_LINE> kw['default'].readonly = True <NEW_LINE> <DEDENT> <DEDENT> super(RichText, self).__init__(schema=schema, **kw) <NEW_LINE> <DEDENT> def fromUnicode(self, str): <NEW_LINE> <INDENT> return RichTextValue( raw=str, mimeType=self.default_mime_type, outputMimeType=self.output_mime_type, encoding='utf-8', ) <NEW_LINE> <DEDENT> def _validate(self, value): <NEW_LINE> <INDENT> if self.allowed_mime_types and value.mimeType not in self.allowed_mime_types: <NEW_LINE> <INDENT> raise WrongType(value, self.allowed_mime_types) <NEW_LINE> <DEDENT> if self.max_length is not None and len(value.raw) > self.max_length: <NEW_LINE> <INDENT> raise Invalid(u'Text is too long. (Maximum %s characters.)' % self.max_length) <NEW_LINE> <DEDENT> if not self.constraint(value): <NEW_LINE> <INDENT> raise ConstraintNotSatisfied(value) | Text field that also stores MIME type
| 6259905991f36d47f223196d |
class TestSignIn(FunctionalTestCase): <NEW_LINE> <INDENT> def test_happy_path(self): <NEW_LINE> <INDENT> self.browser.visit('/') <NEW_LINE> self.browser.click_link_by_partial_text('Sign In') <NEW_LINE> self.browser.fill_form( { 'name': 'Alyssa P. Hacker' }, form_id='sign-in-form', ) <NEW_LINE> self.browser.find_by_css('#sign-in-form button').first.click() <NEW_LINE> signed_in_students = self.browser.find_by_id( 'signed-in-students').first <NEW_LINE> self.assertIn('Alyssa P. Hacker', signed_in_students.text) | A student should be able to:
- go to the home page
- see (and click) a link for signing in
- fill out the sign in form
- see themselves as signed in | 6259905932920d7e50bc7600 |
class TestPitch(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.new_user = User(username = "Adano") <NEW_LINE> self.new_blog = Blog(title = "blog", user = self.new_user) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> Blog.query.delete() <NEW_LINE> User.query.delete() <NEW_LINE> Comment.query.delete() <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.new_blog, Blog)) <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> self.assertEquals(self.new_blog.title, "blog") <NEW_LINE> <DEDENT> def test_save_blog(self): <NEW_LINE> <INDENT> self.new_blog.save_blog() <NEW_LINE> blogs = Blog.query.all() <NEW_LINE> self.assertTrue(len(blogs) > 0) <NEW_LINE> <DEDENT> def test_relationship_user(self): <NEW_LINE> <INDENT> user = self.new_blog.blog.username <NEW_LINE> self.assertTrue(user == "Adano") | This is the class which we will use to do tests for the Pitch | 6259905955399d3f05627ada |
class Player: <NEW_LINE> <INDENT> def __init__(self, text, x, y, score): <NEW_LINE> <INDENT> self.turtle = turtle.Turtle() <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.text = text <NEW_LINE> self.score = score <NEW_LINE> self.num_clicks = 0 <NEW_LINE> self.turn = False <NEW_LINE> self.winner = False <NEW_LINE> self.draw_player() <NEW_LINE> self.draw_score() <NEW_LINE> <DEDENT> def draw_player(self): <NEW_LINE> <INDENT> self.turtle.penup() <NEW_LINE> self.turtle.hideturtle() <NEW_LINE> self.turtle.goto(self.x, self.y) <NEW_LINE> self.turtle.color("white") <NEW_LINE> self.turtle.write(self.text, align="right", font=("Arial", 25, "bold")) <NEW_LINE> <DEDENT> def draw_score(self): <NEW_LINE> <INDENT> self.turtle.clear() <NEW_LINE> self.draw_player() <NEW_LINE> self.turtle.penup() <NEW_LINE> self.turtle.hideturtle() <NEW_LINE> self.turtle.goto(self.x, self.y) <NEW_LINE> self.turtle.write(("Drank: " + str(self.score)), align="left", font=("Arial", 20, "bold")) | Used to create instances of player object.
Has methods to calculate the beers drunk by each players
and draws them on the screen | 6259905901c39578d7f14214 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.