code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class _Context(Mapping): <NEW_LINE> <INDENT> def __init__(self, element=None, parent_elements=None): <NEW_LINE> <INDENT> if parent_elements is not None: <NEW_LINE> <INDENT> self.elements = parent_elements[:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.elements = [] <NEW_LINE> <DEDENT> if element is not None: <NEW_LINE> <INDENT> self.elements.append(element) <NEW_LINE> <DEDENT> <DEDENT> def _all_keys(self): <NEW_LINE> <INDENT> return set( itertools.chain.fromiterable(e.keys() for e in self.elements) ) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> for element in reversed(self.elements): <NEW_LINE> <INDENT> found_element = element.find(key) <NEW_LINE> if found_element is not None: <NEW_LINE> <INDENT> return found_element <NEW_LINE> <DEDENT> <DEDENT> raise KeyError(key) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._all_keys) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._all_keys) <NEW_LINE> <DEDENT> def context_pushing_element(self, element): <NEW_LINE> <INDENT> for context_element in self.elements: <NEW_LINE> <INDENT> if context_element == element: <NEW_LINE> <INDENT> raise ValueError( "element {} already in context".format(element) ) <NEW_LINE> <DEDENT> <DEDENT> return _Context(element, self.elements) | An inherited value context.
In FCP XML there is a concept of inheritance down the element heirarchy.
For instance, a ``clip`` element may not specify the ``rate`` locally, but
instead inherit it from the parent ``track`` element.
This object models that as a stack of elements. When a value needs to be
queried from the context, it will be gathered by walking from the top of
the stack until the value is found.
For example, to find the ``rate`` element as an immediate child most
appropriate to the current context, you would do something like::
``my_current_context["./rate"]``
This object can be thought of as immutable. You get a new context when you
push an element. This prevents inadvertant tampering with parent contexts
that may be used at levels above.
This DOES NOT support ``id`` attribute dereferencing, please make sure to
do that prior to using this structure.
.. seealso:: https://developer.apple.com/library/archive/documentation /AppleApplications/Reference/FinalCutPro_XML/Basics/Basics.html# //apple_ref/doc/uid/TP30001154-TPXREF102 | 62598fd3fbf16365ca79455a |
class Form(models.Model): <NEW_LINE> <INDENT> CONFIG_OPTIONS = [ ('save_fs', { 'title': _('Save form submission'), 'process': create_form_submission}), ('email', { 'title': _('E-mail'), 'form_fields': [ ('email', forms.EmailField(_('e-mail address')))], 'process': send_as_mail}), ] <NEW_LINE> title = models.CharField( _('title'), max_length=100, ) <NEW_LINE> config_json = models.TextField( _('config'), blank=True, ) <NEW_LINE> config = JSONFieldDescriptor( 'config_json', ) <NEW_LINE> designer = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('gform_designer'), related_name='gform_designer', ) <NEW_LINE> num_allow = models.PositiveIntegerField( _('submit numbers allowed'), help_text=_('numbers of forms submit times'), default=1, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('form') <NEW_LINE> verbose_name_plural = _('forms') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def form(self): <NEW_LINE> <INDENT> fields = SortedDict(( ('required_css_class', 'required'), ('error_css_class', 'error'))) <NEW_LINE> for field in self.fields.all(): <NEW_LINE> <INDENT> field.add_formfield(fields, self) <NEW_LINE> <DEDENT> return type('Form%s' % self.pk, (forms.Form, BootstrapForm), fields) <NEW_LINE> <DEDENT> def process(self, form, request): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> cfg = dict(self.CONFIG_OPTIONS) <NEW_LINE> for key, config in self.config.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process = cfg[key]['process'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ret[key] = process( model_instance=self, form_instance=form, request=request, config=config ) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def export(self): <NEW_LINE> <INDENT> pass | Basic form models | 62598fd3091ae356687050b9 |
class ElementReferenceType(Enum,IComparable,IFormattable,IConvertible): <NEW_LINE> <INDENT> def __eq__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> REFERENCE_TYPE_CUT_EDGE=None <NEW_LINE> REFERENCE_TYPE_FOREIGN=None <NEW_LINE> REFERENCE_TYPE_INSTANCE=None <NEW_LINE> REFERENCE_TYPE_LINEAR=None <NEW_LINE> REFERENCE_TYPE_MESH=None <NEW_LINE> REFERENCE_TYPE_NONE=None <NEW_LINE> REFERENCE_TYPE_SURFACE=None <NEW_LINE> value__=None | Element reference types.
enum ElementReferenceType,values: REFERENCE_TYPE_CUT_EDGE (5),REFERENCE_TYPE_FOREIGN (3),REFERENCE_TYPE_INSTANCE (4),REFERENCE_TYPE_LINEAR (1),REFERENCE_TYPE_MESH (6),REFERENCE_TYPE_NONE (0),REFERENCE_TYPE_SURFACE (2) | 62598fd3be7bc26dc92520a7 |
@dataclass(frozen=True) <NEW_LINE> class WantedResults: <NEW_LINE> <INDENT> page: int <NEW_LINE> per_page: int <NEW_LINE> total: int <NEW_LINE> sort_key: str <NEW_LINE> sort_dir: str <NEW_LINE> movies: List[Movie] <NEW_LINE> @staticmethod <NEW_LINE> def from_dict(data: dict): <NEW_LINE> <INDENT> movies = [Movie.from_dict(movie) for movie in data.get("records", [])] <NEW_LINE> return WantedResults( page=data.get("page", 0), per_page=data.get("pageSize", 0), total=data.get("totalRecords", 0), sort_key=data.get("sortKey", ""), sort_dir=data.get("sortDirection", ""), movies=movies ) | Object holding wanted episode results from Radarr. | 62598fd3283ffb24f3cf3d1e |
class CBBContact(BroadContact): <NEW_LINE> <INDENT> pass | Broad phase contact using circular bounding boxes. | 62598fd3a219f33f346c6ca5 |
class Sniffer: <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.done = Event() <NEW_LINE> self.success = False <NEW_LINE> self.playbin = gst.element_factory_make('playbin') <NEW_LINE> self.videosink = gst.element_factory_make("fakesink", "videosink") <NEW_LINE> self.playbin.set_property("video-sink", self.videosink) <NEW_LINE> self.audiosink = gst.element_factory_make("fakesink", "audiosink") <NEW_LINE> self.playbin.set_property("audio-sink", self.audiosink) <NEW_LINE> self.bus = self.playbin.get_bus() <NEW_LINE> self.bus.add_signal_watch() <NEW_LINE> self.watch_id = self.bus.connect("message", self.on_bus_message) <NEW_LINE> self.playbin.set_property("uri", gstutil._get_file_url(filename)) <NEW_LINE> self.playbin.set_state(gst.STATE_PAUSED) <NEW_LINE> <DEDENT> def result(self, success_callback, error_callback): <NEW_LINE> <INDENT> def _result(): <NEW_LINE> <INDENT> self.done.wait(1) <NEW_LINE> if self.success: <NEW_LINE> <INDENT> current_video = self.playbin.get_property("current-video") <NEW_LINE> current_audio = self.playbin.get_property("current-audio") <NEW_LINE> if current_video == 0: <NEW_LINE> <INDENT> call_on_ui_thread(success_callback, "video") <NEW_LINE> <DEDENT> elif current_audio == 0: <NEW_LINE> <INDENT> call_on_ui_thread(success_callback, "audio") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> call_on_ui_thread(success_callback, "unplayable") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> call_on_ui_thread(error_callback) <NEW_LINE> <DEDENT> self.disconnect() <NEW_LINE> <DEDENT> thread.start_new_thread(_result, ()) <NEW_LINE> <DEDENT> def on_bus_message(self, bus, message): <NEW_LINE> <INDENT> if message.src == self.playbin: <NEW_LINE> <INDENT> if message.type == gst.MESSAGE_STATE_CHANGED: <NEW_LINE> <INDENT> prev, new, pending = message.parse_state_changed() <NEW_LINE> if new == gst.STATE_PAUSED: <NEW_LINE> <INDENT> self.success = True <NEW_LINE> self.done.set() <NEW_LINE> <DEDENT> <DEDENT> elif message.type == gst.MESSAGE_ERROR: <NEW_LINE> <INDENT> self.success = False <NEW_LINE> self.done.set() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self.bus.disconnect(self.watch_id) <NEW_LINE> self.playbin.set_state(gst.STATE_NULL) <NEW_LINE> del self.bus <NEW_LINE> del self.playbin <NEW_LINE> del self.audiosink <NEW_LINE> del self.videosink | Determines whether a file is "audio", "video", or "unplayable".
| 62598fd3fbf16365ca79455c |
@spec.define_schema('SingleReportSchema') <NEW_LINE> class SingleReportSchema(ReportSchema): <NEW_LINE> <INDENT> values = ma.List(ma.Nested(ReportValuesSchema()), many=True) <NEW_LINE> outages = ma.List( ma.Nested(ReportOutageSchema()), many=True, title="Outages", description=( "List of periods for which the report will not consider " "forecast submissions in analyses." ) ) | For serializing a report with values and outages.
| 62598fd3d8ef3951e32c80ab |
class YumRepository(BaseRepository): <NEW_LINE> <INDENT> _type = REPO_TYPE_YUM | Custom Yum repository | 62598fd3adb09d7d5dc0aa1b |
class MobileAuthTestMixin: <NEW_LINE> <INDENT> def test_no_auth(self): <NEW_LINE> <INDENT> self.logout() <NEW_LINE> self.api_response(expected_response_code=401) | Test Mixin for testing APIs decorated with mobile_view. | 62598fd3a05bb46b3848ad0a |
class Cacher(abc.ABC): <NEW_LINE> <INDENT> def __init__(self, cfg): <NEW_LINE> <INDENT> self.cfg = cfg <NEW_LINE> <DEDENT> async def init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def get_cache(self, key): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def set_cache(self, key, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def del_cache(self, key): <NEW_LINE> <INDENT> pass | The Cacher is the base class that other, more complex and actually used,
abstract Cacher handlers use for their base functions. | 62598fd350812a4eaa620e34 |
class Clock( EDS ): <NEW_LINE> <INDENT> def __init__( self, i2, a = 0x68 ): <NEW_LINE> <INDENT> super().__init__( i2, a ) <NEW_LINE> <DEDENT> def set( self, t=None ): <NEW_LINE> <INDENT> def bcd( x ): <NEW_LINE> <INDENT> return (x % 10) + 16 * (x // 10) <NEW_LINE> <DEDENT> self._write_reg( 0x7, 0 ) <NEW_LINE> self._write_reg( 0x6, bcd( t.tm_year % 100 ) ) <NEW_LINE> self._write_reg( 0x5, 1 + t.tm_wday ) <NEW_LINE> self._write_reg( 0x4, bcd( t.tm_mon ) ) <NEW_LINE> self._write_reg( 0x3, bcd( t.tm_mday ) ) <NEW_LINE> self._write_reg( 0x2, 0x80 | bcd( t.tm_hour ) ) <NEW_LINE> self._write_reg( 0x1, bcd( t.tm_min ) ) <NEW_LINE> self._write_reg( 0x0, bcd( t.tm_sec ) ) <NEW_LINE> <DEDENT> def read( self ): <NEW_LINE> <INDENT> self._write( [0] ) <NEW_LINE> buf = self._read( 7 ) <NEW_LINE> (ss, mm, hh, dd, MM, ww, yy) = (struct.unpack( "7B", buf )) <NEW_LINE> def dec( x ): <NEW_LINE> <INDENT> return (x % 16) + 10 * (x // 16) <NEW_LINE> <DEDENT> return time.struct_time( 2000 + dec( yy ), dec( MM ), dec( dd ), dec( hh & 0x7f ), dec( mm), dec( ss ), -1, -1, -1 ) <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> print( list( self._read( 16 ) ) ) | CLOCK is a HT1382 I2C/3-Wire Real Time Clock with a 32 kHz crystal | 62598fd397e22403b383b3aa |
class Comment(TrelloObject): <NEW_LINE> <INDENT> def __init__(self, info={}): <NEW_LINE> <INDENT> super().__init__({ "name": info.get("memberCreator").get("fullName"), "id": info.get("id") }) <NEW_LINE> self.date = info.get("date") <NEW_LINE> self.text = info.get("data").get("text") <NEW_LINE> <DEDENT> @property <NEW_LINE> def date(self): <NEW_LINE> <INDENT> return self._date <NEW_LINE> <DEDENT> @date.setter <NEW_LINE> def date(self, date=""): <NEW_LINE> <INDENT> self._date = date <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> @text.setter <NEW_LINE> def text(self, info=""): <NEW_LINE> <INDENT> self._text = info <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str( f"{' '*8}💭 " + super().__str__() + f" | Date: {self.date}" f" | Text: {self.text}" ) | Trello Comment object | 62598fd3956e5f7376df58ce |
class Post(News): <NEW_LINE> <INDENT> title = models.CharField(max_length=200) <NEW_LINE> category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) <NEW_LINE> is_approve = models.BooleanField() <NEW_LINE> def get_content_as_markdown(self): <NEW_LINE> <INDENT> return mark_safe(markdown(self.content, safe_mode='escape')) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '"{}" {}'.format(self.title, self.author) | model that describe post | 62598fd38a349b6b436866e2 |
class Location(db.Model, CRUD): <NEW_LINE> <INDENT> __tablename__ = 'locations' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.Text) <NEW_LINE> latitude = db.Column(db.String(30)) <NEW_LINE> longitude = db.Column(db.String(30)) <NEW_LINE> website = db.Column(db.Text) <NEW_LINE> description = db.Column(db.Text) <NEW_LINE> tags = db.Column(db.Text) <NEW_LINE> accessLevel = db.Column(db.Integer, default=3) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Location: {}>'.format(self.name) <NEW_LINE> <DEDENT> def __init__(self, name, latitude, longitude, website, description, tags, accessLevel): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.website = website <NEW_LINE> self.description = description <NEW_LINE> self.tags = tags <NEW_LINE> self.accessLevel = accessLevel | Create a Location table | 62598fd39f28863672818ace |
class ChatSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Chat <NEW_LINE> fields = '__all__' | Serializing all the Chats | 62598fd3a219f33f346c6ca9 |
class NTPClient(object): <NEW_LINE> <INDENT> def request(self, host, version=2, port='ntp'): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> s.settimeout(30) <NEW_LINE> try: <NEW_LINE> <INDENT> sockaddr = socket.getaddrinfo(host, port)[0][4] <NEW_LINE> query = NTPPacket(mode=3, version=version, tx_timestamp=system_to_ntp_time(time.time())) <NEW_LINE> query_packet = query.to_data() <NEW_LINE> s.sendto(query_packet, sockaddr) <NEW_LINE> src_addr = (None, None) <NEW_LINE> while src_addr != sockaddr: <NEW_LINE> <INDENT> (response_packet, src_addr) = s.recvfrom(len(query_packet)) <NEW_LINE> <DEDENT> dest_timestamp = system_to_ntp_time(time.time()) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> s.close() <NEW_LINE> <DEDENT> response = NTPStats(dest_timestamp) <NEW_LINE> response.from_data(response_packet) <NEW_LINE> return response | Client session - for now, a mere wrapper for NTP requests | 62598fd3ab23a570cc2d4fbf |
class RegistrationForm(FlaskForm): <NEW_LINE> <INDENT> email = StringField('Email', validators=[DataRequired(), Email()]) <NEW_LINE> username = StringField('Username', validators=[DataRequired()]) <NEW_LINE> first_name = StringField('First Name', validators=[DataRequired()]) <NEW_LINE> last_name = StringField('Last Name', validators=[DataRequired()]) <NEW_LINE> password = PasswordField('Password', validators=[DataRequired(), EqualTo('confirm_password')]) <NEW_LINE> confirm_password = PasswordField('Confirm Password') <NEW_LINE> submit = SubmitField('Register') <NEW_LINE> def validate_email(self, field): <NEW_LINE> <INDENT> if Employee.query.filter_by(email=field.data).first(): <NEW_LINE> <INDENT> raise ValidationError('Email is already in use.') <NEW_LINE> <DEDENT> <DEDENT> def validate_username(self, field): <NEW_LINE> <INDENT> if Employee.query.filter_by(username=field.data).first(): <NEW_LINE> <INDENT> raise VaidationError('Username is already in use.') | Form for users to create new account | 62598fd38a349b6b436866e4 |
class Exposure(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def interaction(x,y,t): <NEW_LINE> <INDENT> X = np.sum(x) <NEW_LINE> index = np.dot(x / X, y / t) <NEW_LINE> return index <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def isolation(x,t): <NEW_LINE> <INDENT> X = np.sum(x) <NEW_LINE> index = np.dot(x / X, x / t) <NEW_LINE> return index <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def correlation(x,t): <NEW_LINE> <INDENT> T = np.sum(t) <NEW_LINE> X = np.sum(x) <NEW_LINE> P = X / T <NEW_LINE> index = (self.isolation(x, t) - P) / (1 - P) <NEW_LINE> return index | “Exposure measures the degree of
potential contact, or possibility of
interaction, between minority and
majority group members” (Massey
and Denton, p. 287). | 62598fd3d8ef3951e32c80ad |
class Docstring3(Service): <NEW_LINE> <INDENT> name = '_test.docstring3' | Docstring3 Summary
Docstring3 Description
Docstring3 Description2 | 62598fd34527f215b58ea372 |
class MissingABIError(Exception): <NEW_LINE> <INDENT> pass | Raised when the debtor's ABI is not specified and cannot be inferred from
the account. | 62598fd33617ad0b5ee065eb |
class Inequality(_Equality, ABC): <NEW_LINE> <INDENT> eq_il_cmd = compare_cmds.NotEqualCmp | Expression that checks inequality of two expressions | 62598fd3bf627c535bcb1951 |
class GalaxyToken(object): <NEW_LINE> <INDENT> token_type = 'Token' <NEW_LINE> def __init__(self, token=None): <NEW_LINE> <INDENT> self.b_file = to_bytes(C.GALAXY_TOKEN_PATH, errors='surrogate_or_strict') <NEW_LINE> self._config = None <NEW_LINE> self._token = token <NEW_LINE> <DEDENT> @property <NEW_LINE> def config(self): <NEW_LINE> <INDENT> if not self._config: <NEW_LINE> <INDENT> self._config = self._read() <NEW_LINE> <DEDENT> if self._token: <NEW_LINE> <INDENT> self._config['token'] = None if self._token is NoTokenSentinel else self._token <NEW_LINE> <DEDENT> return self._config <NEW_LINE> <DEDENT> def _read(self): <NEW_LINE> <INDENT> action = 'Opened' <NEW_LINE> if not os.path.isfile(self.b_file): <NEW_LINE> <INDENT> open(self.b_file, 'w').close() <NEW_LINE> os.chmod(self.b_file, S_IRUSR | S_IWUSR) <NEW_LINE> action = 'Created' <NEW_LINE> <DEDENT> with open(self.b_file, 'r') as f: <NEW_LINE> <INDENT> config = yaml.safe_load(f) <NEW_LINE> <DEDENT> display.vvv('%s %s' % (action, to_text(self.b_file))) <NEW_LINE> return config or {} <NEW_LINE> <DEDENT> def set(self, token): <NEW_LINE> <INDENT> self._token = token <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return self.config.get('token', None) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> with open(self.b_file, 'w') as f: <NEW_LINE> <INDENT> yaml.safe_dump(self.config, f, default_flow_style=False) <NEW_LINE> <DEDENT> <DEDENT> def headers(self): <NEW_LINE> <INDENT> headers = {} <NEW_LINE> token = self.get() <NEW_LINE> if token: <NEW_LINE> <INDENT> headers['Authorization'] = '%s %s' % (self.token_type, self.get()) <NEW_LINE> <DEDENT> return headers | Class to storing and retrieving local galaxy token | 62598fd3ad47b63b2c5a7d00 |
class Server(models.Model): <NEW_LINE> <INDENT> asset = models.OneToOneField('Asset', on_delete=models.CASCADE) <NEW_LINE> sub_assset_type_choices = ( (0, 'PC服务器'), (1, '刀片机'), (2, '小型机'), ) <NEW_LINE> created_by_choices = ( ('auto', 'Auto'), ('manual', 'Manual'), ) <NEW_LINE> sub_asset_type = models.SmallIntegerField(choices=sub_assset_type_choices, verbose_name="服务器类型", default=0) <NEW_LINE> created_by = models.CharField(choices=created_by_choices, max_length=32, default='auto') <NEW_LINE> hosted_on = models.ForeignKey('self', related_name='hosted_on_server', blank=True, null=True, on_delete=models.CASCADE) <NEW_LINE> model = models.CharField(verbose_name=u'型号', max_length=128, null=True, blank=True) <NEW_LINE> raid_type = models.CharField(u'raid类型', max_length=512, blank=True, null=True) <NEW_LINE> os_type = models.CharField(u'操作系统类型', max_length=64, blank=True, null=True) <NEW_LINE> os_distribution = models.CharField(u'发型版本', max_length=64, blank=True, null=True) <NEW_LINE> os_release = models.CharField(u'操作系统版本', max_length=64, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '服务器' <NEW_LINE> verbose_name_plural = "服务器" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s sn:%s' % (self.asset.name, self.asset.sn) | 服务器设备 | 62598fd3a05bb46b3848ad0e |
class ContentSearchTestCase(UITestCase): <NEW_LINE> <INDENT> @tier2 <NEW_LINE> def test_positive_search_in_cv(self): <NEW_LINE> <INDENT> org = entities.Organization().create() <NEW_LINE> product = entities.Product( name=gen_string('alpha'), organization=org, ).create() <NEW_LINE> yum_repo = entities.Repository( name=gen_string('alpha'), product=product, content_type='yum', url=FAKE_0_YUM_REPO, ).create() <NEW_LINE> yum_repo.sync() <NEW_LINE> content_view = entities.ContentView( name=gen_string('alpha'), organization=org, ).create() <NEW_LINE> content_view.repository = [yum_repo] <NEW_LINE> content_view = content_view.update(['repository']) <NEW_LINE> self.assertEqual(len(content_view.repository), 1) <NEW_LINE> content_view.publish() <NEW_LINE> with Session(self.browser) as session: <NEW_LINE> <INDENT> session.nav.go_to_select_org(org.name) <NEW_LINE> session.nav.go_to_content_search() <NEW_LINE> self.content_search.add_filter('Content Views', content_view.name) <NEW_LINE> self.content_search.add_search_criteria('Packages', '') <NEW_LINE> expected_result = [ ['Content View', content_view.name, True], ['Product', product.name, True], ['Repository', yum_repo.name, True], ['Package', 'bear', False], ['Package', 'cat', False], ] <NEW_LINE> self.content_search.search(expected_result) | Implement tests for content search via UI | 62598fd37cff6e4e811b5ece |
class DeviceTempFile(object): <NEW_LINE> <INDENT> def __init__(self, adb, suffix='', prefix='temp_file', dir='/data/local/tmp'): <NEW_LINE> <INDENT> if None in (dir, prefix, suffix): <NEW_LINE> <INDENT> m = 'Provided None path component. (dir: %s, prefix: %s, suffix: %s)' % ( dir, prefix, suffix) <NEW_LINE> raise ValueError(m) <NEW_LINE> <DEDENT> self._adb = adb <NEW_LINE> self.name = _GenerateName(prefix, suffix, dir) <NEW_LINE> self.name_quoted = cmd_helper.SingleQuote(self.name) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> def delete_temporary_file(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._adb.Shell('rm -f %s' % self.name_quoted, expect_status=None) <NEW_LINE> <DEDENT> except base_error.BaseError as e: <NEW_LINE> <INDENT> logger.warning('Failed to delete temporary file %s: %s', self.name, str(e)) <NEW_LINE> <DEDENT> <DEDENT> threading.Thread( target=delete_temporary_file, name='delete_temporary_file(%s)' % self._adb.GetDeviceSerial()).start() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.close() | A named temporary file on a device.
Behaves like tempfile.NamedTemporaryFile. | 62598fd33617ad0b5ee065ed |
class ParseSpecial: <NEW_LINE> <INDENT> RULES = [ { 'name': 'bbc_genome', 'match': 'genome.ch.bbc.co.uk', 'fields': { 'date': { 'element': lambda e: e.name == 'a' and e['href'].startswith('/schedules') and e.findChildren('span', {'class', 'time'}), 'value': lambda e: str(e.contents[0]).split(',', 1)[-1].strip(), }, 'type': { 'element': lambda e: e.name == 'aside' and 'block' in e.get('class', []) and e.findChildren('img'), 'value': lambda e: 'radioBroadcast' if 'radio' in e.text else 'tvBroadcast', }, }, }, ] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def apply(self, citation: Citation) -> Citation: <NEW_LINE> <INDENT> if 'soup' not in citation.raw: <NEW_LINE> <INDENT> return citation <NEW_LINE> <DEDENT> matchedRules = [rule for rule in ParseSpecial.RULES if self._matchCitation(citation, rule['match'])] <NEW_LINE> for rule in matchedRules: <NEW_LINE> <INDENT> for field in rule['fields']: <NEW_LINE> <INDENT> f = rule['fields'][field] <NEW_LINE> el = citation.raw['soup'].find(f['element']) <NEW_LINE> if not el: continue <NEW_LINE> if callable(f['value']): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> citation[field] = f['value'](el) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(f['value'], (str,)): <NEW_LINE> <INDENT> citation[field] = f['value'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value extractor') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return citation <NEW_LINE> <DEDENT> def _matchCitation(self, citation: Citation, match): <NEW_LINE> <INDENT> if isinstance(match, (str,)): <NEW_LINE> <INDENT> if 'parsedUrl' not in citation.raw: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return citation.raw['parsedUrl'].netloc == match <NEW_LINE> <DEDENT> if isinstance(match, (list,)): <NEW_LINE> <INDENT> if 'parsedUrl' not in citation.raw: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return citation.raw['parsedUrl'].netloc in match <NEW_LINE> <DEDENT> if callable(match): <NEW_LINE> <INDENT> return match(citation) <NEW_LINE> <DEDENT> raise ValueError('Invalid citation matcher') | How to write a special rule
name: Name of the rule
match: Domain(s) this rule will match
This can be a string, a list of strings, or a callable which
will be passed the Citation to do complex matching
fields:
element: Element matcher
A callable that will be passed the current element, and
should return a boolean indicating if it's a match
value: Value extractor
A callable that will be passed the matched element, and
should return a string | 62598fd3283ffb24f3cf3d26 |
class RandomWalk(): <NEW_LINE> <INDENT> def __init__(self, num_points=500): <NEW_LINE> <INDENT> self.num_points = num_points <NEW_LINE> self.x_values = [0] <NEW_LINE> self.y_values = [0] <NEW_LINE> <DEDENT> def fill_walk(self): <NEW_LINE> <INDENT> while len(self.x_values) < self.num_points: <NEW_LINE> <INDENT> x_direction = choice([1, -1]) <NEW_LINE> x_distance = choice([0, 1, 2, 3, 4]) <NEW_LINE> x_step = x_direction * x_distance <NEW_LINE> y_direction = choice([1, -1]) <NEW_LINE> y_distance = choice([0, 1, 2, 3, 4]) <NEW_LINE> y_step = y_direction * y_distance <NEW_LINE> if x_step == 0 and y_step == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> x = self.x_values[-1] + x_step <NEW_LINE> y = self.y_values[-1] + y_step <NEW_LINE> self.x_values.append(x) <NEW_LINE> self.y_values.append(y) | Класс для генерирования случайных блужданий. | 62598fd38a349b6b436866e8 |
class TestUser(unittest.TestCase): <NEW_LINE> <INDENT> def test_get_account_name(self): <NEW_LINE> <INDENT> user = User() <NEW_LINE> self.assertEqual(user.get_account_name(0), "twitter") | Tests for class User. | 62598fd3283ffb24f3cf3d28 |
class Deconv(Affine): <NEW_LINE> <INDENT> def __init__(self, fshape, init, strides={}, padding={}, bias=None, batch_norm=False, activation=None, conv_name='DeconvolutionLayer', bias_name='BiasLayer', act_name='ActivationLayer'): <NEW_LINE> <INDENT> list.__init__(self) <NEW_LINE> self.append(Deconvolution(fshape=fshape, strides=strides, padding=padding, init=init, bsum=batch_norm)) <NEW_LINE> self.add_postfilter_layers(bias, batch_norm, activation, bias_name, act_name) | Same as Conv layer, but implements a composite deconvolution layer | 62598fd350812a4eaa620e38 |
class Landsat(ClassificationDataset): <NEW_LINE> <INDENT> num_classes = 6 <NEW_LINE> def __init__(self, root, split=TRAIN, validation_size=0.2): <NEW_LINE> <INDENT> dataset_path = os.path.join(root, self.name) <NEW_LINE> file_name_train = 'train.csv' <NEW_LINE> file_name_test = 'test.csv' <NEW_LINE> url_train = 'http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/satimage/sat.trn' <NEW_LINE> url_test = 'http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/satimage/sat.tst' <NEW_LINE> download_file(url_train, dataset_path, file_name_train) <NEW_LINE> download_file(url_test, dataset_path, file_name_test) <NEW_LINE> file_path_train = os.path.join(dataset_path, file_name_train) <NEW_LINE> file_path_test = os.path.join(dataset_path, file_name_test) <NEW_LINE> df_train_valid = pd.read_csv(file_path_train, sep=' ', header=None) <NEW_LINE> df_test = pd.read_csv(file_path_test, sep=' ', header=None) <NEW_LINE> df_test.index += len(df_train_valid) <NEW_LINE> df = pd.concat([df_train_valid, df_test]) <NEW_LINE> y_columns = [36] <NEW_LINE> label_encode_df_(df, y_columns[0]) <NEW_LINE> df_train_valid = df.loc[df_train_valid.index, :] <NEW_LINE> df_test = df.loc[df_test.index, :] <NEW_LINE> df_train, df_valid = split_classification_df(df_train_valid, [1 - validation_size, validation_size], 36) <NEW_LINE> normalize_df_(df_train, other_dfs=[df_valid, df_test], skip_column=y_columns[0]) <NEW_LINE> df_res = get_split(df_train, df_valid, df_test, split) <NEW_LINE> self.x, self.y = xy_split(df_res, y_columns) <NEW_LINE> self.y = self.y[:, 0] | # Parameters
root (str): Local path for storing/reading dataset files.
split (str): One of {'train', 'validation', 'test'}
validation_size (float): How large fraction in (0, 1) of the training partition to use for validation. | 62598fd30fa83653e46f5391 |
class TokenIndexer(Generic[TokenType], Registrable): <NEW_LINE> <INDENT> default_implementation = 'single_id' <NEW_LINE> def __init__(self, token_min_padding_length: int = 0) -> None: <NEW_LINE> <INDENT> self._token_min_padding_length: int = token_min_padding_length <NEW_LINE> <DEDENT> def count_vocab_items(self, token: Token, counter: Dict[str, Dict[str, int]]): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def tokens_to_indices(self, tokens: List[Token], vocabulary: Vocabulary, index_name: str) -> Dict[str, List[TokenType]]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_padding_token(self) -> TokenType: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_padding_lengths(self, token: TokenType) -> Dict[str, int]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_token_min_padding_length(self) -> int: <NEW_LINE> <INDENT> return self._token_min_padding_length <NEW_LINE> <DEDENT> def pad_token_sequence(self, tokens: Dict[str, List[TokenType]], desired_num_tokens: Dict[str, int], padding_lengths: Dict[str, int]) -> Dict[str, List[TokenType]]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_keys(self, index_name: str) -> List[str]: <NEW_LINE> <INDENT> return [index_name] <NEW_LINE> <DEDENT> def __eq__(self, other) -> bool: <NEW_LINE> <INDENT> if isinstance(self, other.__class__): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> return NotImplemented | A ``TokenIndexer`` determines how string tokens get represented as arrays of indices in a model.
This class both converts strings into numerical values, with the help of a
:class:`~allennlp.data.vocabulary.Vocabulary`, and it produces actual arrays.
Tokens can be represented as single IDs (e.g., the word "cat" gets represented by the number
34), or as lists of character IDs (e.g., "cat" gets represented by the numbers [23, 10, 18]),
or in some other way that you can come up with (e.g., if you have some structured input you
want to represent in a special way in your data arrays, you can do that here).
Parameters
----------
token_min_padding_length : ``int``, optional (default=``0``)
The minimum padding length required for the :class:`TokenIndexer`. For example,
the minimum padding length of :class:`SingleIdTokenIndexer` is the largest size of
filter when using :class:`CnnEncoder`.
Note that if you set this for one TokenIndexer, you likely have to set it for all
:class:`TokenIndexer` for the same field, otherwise you'll get mismatched tensor sizes. | 62598fd3ab23a570cc2d4fc2 |
class AutomationList(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[Automation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AutomationList, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs['value'] <NEW_LINE> self.next_link = None | List of security automations response.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:param value: Required. The list of security automations under the given scope.
:type value: list[~azure.mgmt.security.models.Automation]
:ivar next_link: The URI to fetch the next page.
:vartype next_link: str | 62598fd34527f215b58ea378 |
class NotAnEmailAddress(schema.ValidationError): <NEW_LINE> <INDENT> pass | This is not a valid email address | 62598fd33617ad0b5ee065f1 |
class DBTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.db = dummy_db(with_scan=True, with_fileset=True, with_file=True) <NEW_LINE> self.tmpclone = None <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.db.disconnect() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> from shutil import rmtree <NEW_LINE> rmtree(self.db.basedir, ignore_errors=True) <NEW_LINE> <DEDENT> def get_test_db(self, db_path=None): <NEW_LINE> <INDENT> if db_path is not None: <NEW_LINE> <INDENT> self.tmpclone = TemporaryCloneDB(db_path) <NEW_LINE> self.db = FSDB(self.tmpclone.tmpdir.name) <NEW_LINE> <DEDENT> self.db.connect() <NEW_LINE> return self.db <NEW_LINE> <DEDENT> def get_test_scan(self): <NEW_LINE> <INDENT> db = self.get_test_db() <NEW_LINE> scan = db.get_scan("myscan_001") <NEW_LINE> return scan <NEW_LINE> <DEDENT> def get_test_fileset(self): <NEW_LINE> <INDENT> scan = self.get_test_scan() <NEW_LINE> fileset = scan.get_fileset("fileset_001") <NEW_LINE> return fileset <NEW_LINE> <DEDENT> def get_test_file(self): <NEW_LINE> <INDENT> fileset = self.get_test_fileset() <NEW_LINE> file = fileset.get_file("test_image") <NEW_LINE> return file | A test database.
Attributes
----------
db : plantdb.FSDB
The temporary directory.
tmpclone : TemporaryCloneDB
A local temporary copy of a test database. | 62598fd3377c676e912f6fce |
class BetchipTestMetaClass(type): <NEW_LINE> <INDENT> def __new__(cls, clsname, bases, dct): <NEW_LINE> <INDENT> if not clsname == 'BetchipTestFramework': <NEW_LINE> <INDENT> if not ('run_test' in dct and 'set_test_params' in dct): <NEW_LINE> <INDENT> raise TypeError("BetchipTestFramework subclasses must override " "'run_test' and 'set_test_params'") <NEW_LINE> <DEDENT> if '__init__' in dct or 'main' in dct: <NEW_LINE> <INDENT> raise TypeError("BetchipTestFramework subclasses may not override " "'__init__' or 'main'") <NEW_LINE> <DEDENT> <DEDENT> return super().__new__(cls, clsname, bases, dct) | Metaclass for BetchipTestFramework.
Ensures that any attempt to register a subclass of `BetchipTestFramework`
adheres to a standard whereby the subclass overrides `set_test_params` and
`run_test` but DOES NOT override either `__init__` or `main`. If any of
those standards are violated, a ``TypeError`` is raised. | 62598fd39f28863672818ad2 |
class Portforwarding(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.serverProtocol = wire.Echo() <NEW_LINE> self.clientProtocol = protocol.Protocol() <NEW_LINE> self.openPorts = [] <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.clientProtocol.transport.loseConnection() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.serverProtocol.transport.loseConnection() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return defer.gatherResults( [defer.maybeDeferred(p.stopListening) for p in self.openPorts]) <NEW_LINE> <DEDENT> def testPortforward(self): <NEW_LINE> <INDENT> realServerFactory = protocol.ServerFactory() <NEW_LINE> realServerFactory.protocol = lambda: self.serverProtocol <NEW_LINE> realServerPort = reactor.listenTCP(0, realServerFactory, interface='127.0.0.1') <NEW_LINE> self.openPorts.append(realServerPort) <NEW_LINE> proxyServerFactory = portforward.ProxyFactory('127.0.0.1', realServerPort.getHost().port) <NEW_LINE> proxyServerPort = reactor.listenTCP(0, proxyServerFactory, interface='127.0.0.1') <NEW_LINE> self.openPorts.append(proxyServerPort) <NEW_LINE> nBytes = 1000 <NEW_LINE> received = [] <NEW_LINE> d = defer.Deferred() <NEW_LINE> def testDataReceived(data): <NEW_LINE> <INDENT> received.extend(data) <NEW_LINE> if len(received) >= nBytes: <NEW_LINE> <INDENT> self.assertEquals(''.join(received), 'x' * nBytes) <NEW_LINE> d.callback(None) <NEW_LINE> <DEDENT> <DEDENT> self.clientProtocol.dataReceived = testDataReceived <NEW_LINE> def testConnectionMade(): <NEW_LINE> <INDENT> self.clientProtocol.transport.write('x' * nBytes) <NEW_LINE> <DEDENT> self.clientProtocol.connectionMade = testConnectionMade <NEW_LINE> clientFactory = protocol.ClientFactory() <NEW_LINE> clientFactory.protocol = lambda: self.clientProtocol <NEW_LINE> reactor.connectTCP( '127.0.0.1', proxyServerPort.getHost().port, clientFactory) <NEW_LINE> return d | Test port forwarding. | 62598fd3ff9c53063f51aaf6 |
class PrepareCorpus(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.corpus_id = kwargs.pop('corpus_id') <NEW_LINE> self.parse = kwargs.pop('parsecls')(**kwargs) <NEW_LINE> self.store = MongoClient()['docs'][self.corpus_id] <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> log.info("Dropping existing %s document...", self.corpus_id) <NEW_LINE> self.store.drop() <NEW_LINE> log.info('Loading documents for corpus %s...', self.corpus_id) <NEW_LINE> for i, doc in enumerate(self.parse()): <NEW_LINE> <INDENT> if i % 250 == 0: <NEW_LINE> <INDENT> log.debug('Processed %i documents...', i) <NEW_LINE> <DEDENT> self.store.insert(doc.json()) <NEW_LINE> <DEDENT> log.info('Import completed for %i documents.', i+1) <NEW_LINE> <DEDENT> APPS=set() <NEW_LINE> @classmethod <NEW_LINE> def Register(cls, c): <NEW_LINE> <INDENT> cls.APPS.add(c) <NEW_LINE> return c <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_arguments(cls, p): <NEW_LINE> <INDENT> p.add_argument('corpus_id', metavar='CORPUS_ID') <NEW_LINE> p.set_defaults(cls=cls) <NEW_LINE> app_name = 'prepare' <NEW_LINE> sp = p.add_subparsers() <NEW_LINE> for c in cls.APPS: <NEW_LINE> <INDENT> name = c.__name__.lower() <NEW_LINE> name = name.replace(app_name,'') <NEW_LINE> csp = sp.add_parser( name, help=c.__doc__.split('\n')[0], description=textwrap.dedent(c.__doc__.rstrip()), formatter_class=argparse.RawDescriptionHelpFormatter) <NEW_LINE> c.add_arguments(csp) <NEW_LINE> <DEDENT> return p | Prepare and inject a corpus. | 62598fd34527f215b58ea37a |
class JPPostalCodeField(RegexField): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': _('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(r'^\d{3}-\d{4}$|^\d{7}$', **kwargs) <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> value = super().clean(value) <NEW_LINE> if value in self.empty_values: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return value.replace('-', '') | A form field that validates its input is a Japanese postcode.
Accepts 7 digits, with or without a hyphen. | 62598fd3d8ef3951e32c80b1 |
class FacebookProfileModel(models.Model): <NEW_LINE> <INDENT> about_me = models.TextField(blank=True, null=True) <NEW_LINE> facebook_id = models.IntegerField(blank=True, null=True) <NEW_LINE> facebook_name = models.CharField(max_length=255, blank=True, null=True) <NEW_LINE> facebook_profile_url = models.TextField(blank=True, null=True) <NEW_LINE> website_url = models.TextField(blank=True, null=True) <NEW_LINE> blog_url = models.TextField(blank=True, null=True) <NEW_LINE> image = models.ImageField(blank=True, null=True, upload_to='profile_images') <NEW_LINE> date_of_birth = models.DateField(blank=True, null=True) <NEW_LINE> if facebook_settings.FACEBOOK_TRACK_RAW_DATA: <NEW_LINE> <INDENT> raw_data = models.TextField(blank=True, null=True) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.user.__unicode__() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True | Abstract class to add to your profile model.
NOTE: If you don't use this this abstract class, make sure you copy/paste
the fields in. | 62598fd3dc8b845886d53a6a |
class CellAreaLocationProvider(AbstractCellLocationProvider): <NEW_LINE> <INDENT> models = (CellArea, ) <NEW_LINE> log_name = 'cell_lac' <NEW_LINE> def prepare_location(self, queried_objects): <NEW_LINE> <INDENT> lac = sorted(queried_objects, key=operator.attrgetter('range'))[0] <NEW_LINE> accuracy = float(max(LAC_MIN_ACCURACY, lac.range)) <NEW_LINE> return self.result_type(lat=lac.lat, lon=lac.lon, accuracy=accuracy) | A CellAreaLocationProvider implements a cell location search
using the CellArea model. | 62598fd33d592f4c4edbb362 |
class DNSResolver(dns.resolver.Resolver): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.reset_ipa_defaults() <NEW_LINE> self.resolve = getattr(super(), "resolve", self.query) <NEW_LINE> self.resolve_address = getattr( super(), "resolve_address", self._resolve_address ) <NEW_LINE> <DEDENT> def reset_ipa_defaults(self): <NEW_LINE> <INDENT> self.timeout = 10 + 2 <NEW_LINE> self.lifetime = min(self.timeout * len(self.nameservers) * 2, 45) <NEW_LINE> self.use_search_by_default = True <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> super().reset() <NEW_LINE> self.reset_ipa_defaults() <NEW_LINE> <DEDENT> def _resolve_address(self, ip_address, *args, **kwargs): <NEW_LINE> <INDENT> return self.resolve( dns.reversename.from_address(ip_address), rdtype=dns.rdatatype.PTR, *args, **kwargs, ) <NEW_LINE> <DEDENT> def read_resolv_conf(self, *args, **kwargs): <NEW_LINE> <INDENT> super().read_resolv_conf(*args, **kwargs) <NEW_LINE> nameservers = list(dict.fromkeys(self.nameservers)) <NEW_LINE> ipv6_loopback = "::1" <NEW_LINE> ipv4_loopback = "127.0.0.1" <NEW_LINE> if ipv6_loopback in nameservers and ipv4_loopback in nameservers: <NEW_LINE> <INDENT> nameservers.remove(ipv4_loopback) <NEW_LINE> <DEDENT> self.nameservers = nameservers | DNS stub resolver compatible with both dnspython < 2.0.0
and dnspython >= 2.0.0.
Set `use_search_by_default` attribute to `True`, which
determines the default for whether the search list configured
in the system's resolver configuration is used for relative
names, and whether the resolver's domain may be added to relative
names.
Increase the default lifetime which determines the number of seconds
to spend trying to get an answer to the question. dnspython 2.0.0
changes this to 5sec, while the previous one was 30sec. | 62598fd3099cdd3c63675635 |
class TestBar(unittest.TestCase): <NEW_LINE> <INDENT> def test_bar_elquals_bar(self): <NEW_LINE> <INDENT> self.assertEqual(bar.echo('foo'), 'foo') | Classe de teste bar | 62598fd3ad47b63b2c5a7d05 |
class Solution: <NEW_LINE> <INDENT> def maxAreaOfIsland(self, grid: List[List[int]]) -> int: <NEW_LINE> <INDENT> if not grid: return 0 <NEW_LINE> row, col = len(grid), len(grid[0]) <NEW_LINE> max_area = 0 <NEW_LINE> for i in range(row): <NEW_LINE> <INDENT> for j in range(col): <NEW_LINE> <INDENT> max_area = max(max_area, self.dfs(grid, i, j)) <NEW_LINE> <DEDENT> <DEDENT> return max_area <NEW_LINE> <DEDENT> def dfs(self, grid, i, j): <NEW_LINE> <INDENT> if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> grid[i][j] = 0 <NEW_LINE> return 1 + self.dfs(grid, i - 1, j) + self.dfs(grid, i + 1, j) + self.dfs(grid, i, j - 1) + self.dfs(grid, i, j + 1) | O(M*N):所有节点只遍历一次。
M*N个节点;每个节点有4条边。 | 62598fd3956e5f7376df58d4 |
class Mixin(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _mixin_attr(cls, name, owner): <NEW_LINE> <INDENT> if name.startswith('__'): <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> val = getattr(cls, name) <NEW_LINE> if is_hook(val): <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> if inspect.ismethod(val): <NEW_LINE> <INDENT> bind_to = val.im_self or owner <NEW_LINE> val = types.MethodType(val.im_func, bind_to) <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def implements_hook(cls, hook): <NEW_LINE> <INDENT> func = getattr(cls, hook, None) <NEW_LINE> if func is not None and getattr(func, 'is_hook', False): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _init_mixin(self, *a, **kw): <NEW_LINE> <INDENT> pass | Mixins are classes that provide attributes and methods to be accessible
by instances they are associated with (at class or instance level).
Mixins are not supposed to be instanced, because their attributes are
transparently proxied to be accessible by instances that have access to
them.
Example: If you learn math, that becomes a mixins of your person. You do
not possess an instance of math, but rather math knowledge is now a part of
your mind, its processes are available to you, and it stores information in
you, such as which concepts you understand, a running tab when counting,
and so on.
You may write a Mixin largely like you would write a parent class, but
there are some notable differences:
* _init_mixin is called during HasMixins initialization.
* Special attribute methods like __getattr__ are never called.
* Decorators are not in the instance MRO, and are not searched by super().
* Mixin methods may not use super(). If mixins use inheritance, you
must use composed parent calls instead: parentClass.same_method(*args) | 62598fd33617ad0b5ee065f5 |
class TestPUTBatchDebitMemosRequest(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 testPUTBatchDebitMemosRequest(self): <NEW_LINE> <INDENT> pass | PUTBatchDebitMemosRequest unit test stubs | 62598fd3377c676e912f6fd0 |
class OrsifrontsTable(FrontsTBase): <NEW_LINE> <INDENT> __tablename__='orsifronts' <NEW_LINE> id=Column(Integer,primary_key=True) <NEW_LINE> name=Column(String) <NEW_LINE> acronym=Column(String) <NEW_LINE> geom=Column(geoLineStrType) | Defines the Orsifonts PostgreSQL table | 62598fd3be7bc26dc92520af |
class ScipyDist(BasePairwiseTransformer): <NEW_LINE> <INDENT> _tags = { "symmetric": True, } <NEW_LINE> def __init__(self, metric="euclidean", p=2, colalign="intersect"): <NEW_LINE> <INDENT> self.metric = metric <NEW_LINE> self.p = p <NEW_LINE> self.colalign = colalign <NEW_LINE> super(ScipyDist, self).__init__() <NEW_LINE> <DEDENT> def _transform(self, X, X2=None): <NEW_LINE> <INDENT> p = self.p <NEW_LINE> metric = self.metric <NEW_LINE> if isinstance(X, pd.DataFrame): <NEW_LINE> <INDENT> X = X.select_dtypes("number").to_numpy(dtype="float") <NEW_LINE> <DEDENT> if isinstance(X2, pd.DataFrame): <NEW_LINE> <INDENT> X2 = X2.select_dtypes("number").to_numpy(dtype="float") <NEW_LINE> <DEDENT> if metric == "minkowski": <NEW_LINE> <INDENT> distmat = cdist(XA=X, XB=X2, metric=metric, p=p) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> distmat = cdist(XA=X, XB=X2, metric=metric) <NEW_LINE> <DEDENT> return distmat | Interface to scipy distances.
computes pairwise distances using scipy.spatial.distance.cdist
includes Euclidean distance and p-norm (Minkowski) distance
note: weighted distances are not supported
Parameters
----------
metric: string or function, as in cdist; default = 'euclidean'
if string, one of: 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard',
'jensenshannon', 'kulsinski', 'mahalanobis', 'matching', 'minkowski',
'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener',
'sokalsneath', 'sqeuclidean', 'yule'
if function, should have signature 1D-np.array x 1D-np.array -> float
p: if metric='minkowski', the "p" in "p-norm", otherwise irrelevant
colalign: string, one of 'intersect' (default), 'force-align', 'none'
controls column alignment if X, X2 passed in fit are pd.DataFrame
columns between X and X2 are aligned via column names
if 'intersect', distance is computed on columns occurring both in X and X2,
other columns are discarded; column ordering in X2 is copied from X
if 'force-align', raises an error if the set of columns in X, X2 differs;
column ordering in X2 is copied from X
if 'none', X and X2 are passed through unmodified (no columns are aligned)
note: this will potentially align "non-matching" columns | 62598fd39f28863672818ad4 |
class Schema(object, metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> def __init__(self, type, other_props=None): <NEW_LINE> <INDENT> if type not in VALID_TYPES: <NEW_LINE> <INDENT> raise SchemaParseException('%r is not a valid Avro type.' % type) <NEW_LINE> <DEDENT> self._props = {} <NEW_LINE> self._props['type'] = type <NEW_LINE> self._type = type <NEW_LINE> if other_props: <NEW_LINE> <INDENT> self._props.update(other_props) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def namespace(self): <NEW_LINE> <INDENT> return self._props.get('namespace', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @property <NEW_LINE> def doc(self): <NEW_LINE> <INDENT> return self._props.get('doc', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def props(self): <NEW_LINE> <INDENT> return MappingProxyType(self._props) <NEW_LINE> <DEDENT> @property <NEW_LINE> def other_props(self): <NEW_LINE> <INDENT> return dict(FilterKeysOut(items=self._props, keys=SCHEMA_RESERVED_PROPS)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.to_json(), cls=MappingProxyEncoder) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def to_json(self, names): <NEW_LINE> <INDENT> raise Exception('Cannot run abstract method.') | Abstract base class for all Schema classes. | 62598fd3a05bb46b3848ad18 |
class ResearchExperimentReplicateListAPIView(ListAPIView): <NEW_LINE> <INDENT> queryset = ResearchExperimentReplicate.objects.all() <NEW_LINE> serializer_class = research_experiment_replicate_serializers['ResearchExperimentReplicateListSerializer'] <NEW_LINE> filter_backends = (DjangoFilterBackend,) <NEW_LINE> filter_class = ResearchExperimentReplicateListFilter <NEW_LINE> pagination_class = APILimitOffsetPagination | API list view. Gets all records API. | 62598fd3fbf16365ca79456e |
class Route53HealthCheckDefinition(nixops.resources.ResourceDefinition): <NEW_LINE> <INDENT> config: Route53HealthCheckOptions <NEW_LINE> @classmethod <NEW_LINE> def get_type(cls): <NEW_LINE> <INDENT> return "aws-route53-health-check" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_resource_type(cls): <NEW_LINE> <INDENT> return "route53HealthChecks" <NEW_LINE> <DEDENT> def __init__(self, name: str, config: nixops.resources.ResourceEval): <NEW_LINE> <INDENT> nixops.resources.ResourceDefinition.__init__(self, name, config) <NEW_LINE> self.access_key_id = self.config.accessKeyId <NEW_LINE> self.ip_address = self.config.ipAddress <NEW_LINE> self.port = self.config.port <NEW_LINE> self.type = self.config.type <NEW_LINE> self.resource_path = self.config.resourcePath <NEW_LINE> self.fqdn = self.config.fullyQualifiedDomainName <NEW_LINE> self.search_string = self.config.searchString <NEW_LINE> self.request_interval = self.config.requestInterval <NEW_LINE> self.failure_threshold = self.config.failureThreshold <NEW_LINE> self.measure_latency = self.config.measureLatency <NEW_LINE> self.inverted = self.config.inverted <NEW_LINE> self.enable_sni = self.config.enableSNI <NEW_LINE> self.regions = self.config.regions <NEW_LINE> self.alarm_indentifier_region = self.config.alarmIdentifier.region <NEW_LINE> self.alarm_indentifier_name = self.config.alarmIdentifier.name <NEW_LINE> self.insufficient_data_health_status = self.config.insufficientDataHealthStatus <NEW_LINE> self.child_health_checks = self.config.childHealthChecks <NEW_LINE> self.health_threshold = self.config.healthThreshold | Definition of an Route53 Health Check. | 62598fd3a219f33f346c6cb7 |
class FieldTypeInstance(InstanceResource): <NEW_LINE> <INDENT> def __init__(self, version, payload, assistant_sid, sid=None): <NEW_LINE> <INDENT> super(FieldTypeInstance, self).__init__(version) <NEW_LINE> self._properties = { 'account_sid': payload.get('account_sid'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'friendly_name': payload.get('friendly_name'), 'links': payload.get('links'), 'assistant_sid': payload.get('assistant_sid'), 'sid': payload.get('sid'), 'unique_name': payload.get('unique_name'), 'url': payload.get('url'), } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'assistant_sid': assistant_sid, 'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = FieldTypeContext( self._version, assistant_sid=self._solution['assistant_sid'], sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def friendly_name(self): <NEW_LINE> <INDENT> return self._properties['friendly_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._properties['links'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def assistant_sid(self): <NEW_LINE> <INDENT> return self._properties['assistant_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_name(self): <NEW_LINE> <INDENT> return self._properties['unique_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def update(self, friendly_name=values.unset, unique_name=values.unset): <NEW_LINE> <INDENT> return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, ) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete() <NEW_LINE> <DEDENT> @property <NEW_LINE> def field_values(self): <NEW_LINE> <INDENT> return self._proxy.field_values <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Preview.Understand.FieldTypeInstance {}>'.format(context) | PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. | 62598fd3d8ef3951e32c80b4 |
class PathNotDirectoryError(Exception): <NEW_LINE> <INDENT> pass | Path is not a directory Error
| 62598fd3283ffb24f3cf3d32 |
class SoundPlayer(Component, IComponent, IDisposable, ISerializable): <NEW_LINE> <INDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetService(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Load(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def LoadAsync(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def MemberwiseClone(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnLoadCompleted(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnSoundLocationChanged(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def OnStreamChanged(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Play(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def PlayLooping(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def PlaySync(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Stop(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self, *__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> CanRaiseEvents = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> DesignMode = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> Events = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> IsLoadCompleted = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> LoadTimeout = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> SoundLocation = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> Stream = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> Tag = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> LoadCompleted = None <NEW_LINE> SoundLocationChanged = None <NEW_LINE> StreamChanged = None | Controls playback of a sound from a .wav file.
SoundPlayer()
SoundPlayer(soundLocation: str)
SoundPlayer(stream: Stream) | 62598fd360cbc95b063647f0 |
class OptionParser(optparse.OptionParser): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> kwargs['option_class'] = OptionWithDefault <NEW_LINE> optparse.OptionParser.__init__(self, **kwargs) <NEW_LINE> <DEDENT> def check_values(self, values, args): <NEW_LINE> <INDENT> for option in self.option_list: <NEW_LINE> <INDENT> if hasattr(option, STREQUIRED) and option.required: <NEW_LINE> <INDENT> if not getattr(values, option.dest): <NEW_LINE> <INDENT> self.error("option {opt} is required".format(opt=str(option))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return optparse.OptionParser.check_values(self, values, args) | Extend optparse.OptionParser | 62598fd3ff9c53063f51aafe |
class RecordNothing: <NEW_LINE> <INDENT> def __call__(self, pop): <NEW_LINE> <INDENT> return | A temporal sampler that does nothing. | 62598fd33617ad0b5ee065fb |
class PAsshProtocol(asyncio.SubprocessProtocol): <NEW_LINE> <INDENT> def __init__(self, hostname: str, exit_future: asyncio.Future, use_stdout: bool): <NEW_LINE> <INDENT> self._hostname = hostname <NEW_LINE> self._prefix = b'[' + hostname.encode('utf-8') + b'] ' <NEW_LINE> self._exit_future = exit_future <NEW_LINE> self._use_stdout = use_stdout <NEW_LINE> self._stdout = bytearray() <NEW_LINE> self._stderr = bytearray() <NEW_LINE> self._exited = False <NEW_LINE> self._closed_stdout = False <NEW_LINE> self._closed_stderr = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def finished(self): <NEW_LINE> <INDENT> return self._exited and self._closed_stdout and self._closed_stderr <NEW_LINE> <DEDENT> def signal_exit(self): <NEW_LINE> <INDENT> if not self.finished: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.flush() <NEW_LINE> self._exit_future.set_result(True) <NEW_LINE> <DEDENT> def pipe_data_received(self, fd, data): <NEW_LINE> <INDENT> if fd == 1: <NEW_LINE> <INDENT> self._stdout.extend(data) <NEW_LINE> if self._use_stdout: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.flush_line(self._stdout, sys.stdout.buffer) <NEW_LINE> <DEDENT> elif fd == 2: <NEW_LINE> <INDENT> self._stderr.extend(data) <NEW_LINE> self.flush_line(self._stderr, sys.stderr.buffer) <NEW_LINE> <DEDENT> <DEDENT> def pipe_connection_lost(self, fd, exc): <NEW_LINE> <INDENT> if fd == 1: <NEW_LINE> <INDENT> self._closed_stdout = True <NEW_LINE> <DEDENT> elif fd == 2: <NEW_LINE> <INDENT> self._closed_stderr = True <NEW_LINE> <DEDENT> self.signal_exit() <NEW_LINE> <DEDENT> def process_exited(self): <NEW_LINE> <INDENT> self._exited = True <NEW_LINE> self.signal_exit() <NEW_LINE> <DEDENT> def get_stdout(self) ->bytes: <NEW_LINE> <INDENT> return bytes(self._stdout) <NEW_LINE> <DEDENT> def flush_line(self, buf: bytearray, out): <NEW_LINE> <INDENT> pos = buf.rfind(b'\n') <NEW_LINE> if pos == -1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> b = bytearray() <NEW_LINE> for line in buf[0:pos+1].splitlines(True): <NEW_LINE> <INDENT> b.extend(self._prefix) <NEW_LINE> b.extend(line) <NEW_LINE> out.write(b) <NEW_LINE> b.clear() <NEW_LINE> <DEDENT> out.flush() <NEW_LINE> del buf[0:pos+1] <NEW_LINE> <DEDENT> def _flush(self, buf: bytearray, out): <NEW_LINE> <INDENT> if len(buf) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> b = bytearray() <NEW_LINE> b.extend(self._prefix) <NEW_LINE> b.extend(buf) <NEW_LINE> b.extend(b'\n') <NEW_LINE> out.write(b) <NEW_LINE> out.flush() <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> if not self._use_stdout: <NEW_LINE> <INDENT> self._flush(self._stdout, sys.stdout.buffer) <NEW_LINE> <DEDENT> self._flush(self._stderr, sys.stderr.buffer) | An asyncio.SubprocessProtocol for PAssh. | 62598fd3ec188e330fdf8d49 |
class HostServiceSystem(ExtensibleManagedObject): <NEW_LINE> <INDENT> def __init__(self, core, name=None, ref=None, type=ManagedObjectTypes.HostServiceSystem): <NEW_LINE> <INDENT> super(HostServiceSystem, self).__init__(core, name=name, ref=ref, type=type) <NEW_LINE> <DEDENT> @property <NEW_LINE> def serviceInfo(self): <NEW_LINE> <INDENT> return self.update('serviceInfo') <NEW_LINE> <DEDENT> def RefreshServices(self): <NEW_LINE> <INDENT> return self.delegate("RefreshServices")() <NEW_LINE> <DEDENT> def RestartService(self, id): <NEW_LINE> <INDENT> return self.delegate("RestartService")(id) <NEW_LINE> <DEDENT> def StartService(self, id): <NEW_LINE> <INDENT> return self.delegate("StartService")(id) <NEW_LINE> <DEDENT> def StopService(self, id): <NEW_LINE> <INDENT> return self.delegate("StopService")(id) <NEW_LINE> <DEDENT> def UninstallService(self, id): <NEW_LINE> <INDENT> return self.delegate("UninstallService")(id) <NEW_LINE> <DEDENT> def UpdateServicePolicy(self, id, policy): <NEW_LINE> <INDENT> return self.delegate("UpdateServicePolicy")(id, policy) | The HostServiceSystem managed object describes the configuration of host
services. This managed object operates in conjunction with the
HostFirewallSystem managed object. | 62598fd39f28863672818ad7 |
class QuantityNodeType(ObjectNodeType): <NEW_LINE> <INDENT> image = ImageResource('quantity') <NEW_LINE> def allows_children(self, node): <NEW_LINE> <INDENT> return False | The resource type for quantities. | 62598fd3091ae356687050d0 |
class MOD09_ObservationsKernels(object): <NEW_LINE> <INDENT> def __init__(self, dates, filenames): <NEW_LINE> <INDENT> if not len(dates) == len(filenames): <NEW_LINE> <INDENT> raise ValueError("{} dates, {} filenames".format( len(dates), len(filenames))) <NEW_LINE> <DEDENT> self.dates = dates <NEW_LINE> self.filenames = filenames <NEW_LINE> <DEDENT> def get_band_data(self, the_date, band_no): <NEW_LINE> <INDENT> QA_OK = np.array([8, 72, 136, 200, 1032, 1288, 2056, 2120, 2184, 2248]) <NEW_LINE> unc = [0.004, 0.015, 0.003, 0.004, 0.013, 0.010, 0.006] <NEW_LINE> try: <NEW_LINE> <INDENT> iloc = self.dates.index(the_date) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> fname = self.filenames[iloc] <NEW_LINE> g = gdal.Open('HDF4_EOS:EOS_GRID:"{}"'.format(fname) + ':MODIS_Grid_500m_2D:sur_refl_b0{}_1'.format(band_no)) <NEW_LINE> refl = g.ReadAsArray()/10000. <NEW_LINE> g = gdal.Open('HDF4_EOS:EOS_GRID:"{}"'.format(fname) + ':MODIS_Grid_1km_2D:state_1km_1') <NEW_LINE> qa = g.ReadAsArray() <NEW_LINE> mask = np.in1d(qa, QA_OK).reshape((1200, 1200)) <NEW_LINE> g = gdal.Open('HDF4_EOS:EOS_GRID:"{}"'.format(fname) + ':MODIS_Grid_1km_2D:SolarZenith_1') <NEW_LINE> sza = g.ReadAsArray()/100. <NEW_LINE> g = gdal.Open('HDF4_EOS:EOS_GRID:"{}"'.format(fname) + ':MODIS_Grid_1km_2D:SolarAzimuth_1') <NEW_LINE> saa = g.ReadAsArray()/100. <NEW_LINE> g = gdal.Open('HDF4_EOS:EOS_GRID:"{}"'.format(fname) + ':MODIS_Grid_1km_2D:SensorZenith_1') <NEW_LINE> vza = g.ReadAsArray()/100. <NEW_LINE> g = gdal.Open('HDF4_EOS:EOS_GRID:"{}"'.format(fname) + ':MODIS_Grid_1km_2D:SensorAzimuth_1') <NEW_LINE> vaa = g.ReadAsArray()/100. <NEW_LINE> raa = vaa - saa <NEW_LINE> raa = zoom(raa, 2, order=0) <NEW_LINE> vza = zoom(vza, 2, order=0) <NEW_LINE> sza = zoom(sza, 2, order=0) <NEW_LINE> mask = zoom(mask, 2, order=0) <NEW_LINE> K = Kernels(vza, sza, raa, LiType="Sparse", doIntegrals=False, normalise=1, RecipFlag=True, RossHS=False, MODISSPARSE=True, RossType="Thick") <NEW_LINE> uncertainty = refl*0 + unc[band_no-1] <NEW_LINE> data_object = MOD09_data(refl, mask, uncertainty, K, sza, vza, raa) <NEW_LINE> return data_object | A generic M*D09 data reader | 62598fd3ff9c53063f51ab00 |
class TapTrans(Transition): <NEW_LINE> <INDENT> def __init__(self,cube=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.cube = cube <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.running: return <NEW_LINE> super().start() <NEW_LINE> self.robot.erouter.add_listener(self,TapEvent,self.cube) <NEW_LINE> <DEDENT> def handle_event(self,event): <NEW_LINE> <INDENT> if self.cube: <NEW_LINE> <INDENT> self.fire(event) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.handle = self.robot.conn.loop.call_later(Transition.default_value_delay, self.fire, event) | Transition fires when a cube is tapped. | 62598fd38a349b6b436866f6 |
class UserProfileFeedViewset(viewsets.ModelViewSet): <NEW_LINE> <INDENT> authentication_classes = (TokenAuthentication,) <NEW_LINE> serializer_class = ProfileFeedSerializer <NEW_LINE> permission_classes = (UpdateOwnStatusPermission, IsAuthenticatedOrReadOnly) <NEW_LINE> queryset = ProfileFeedModel.objects.all() <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user_profile=self.request.user) | Handles creating, reading and updating profile feeds | 62598fd3ec188e330fdf8d4b |
class _LMemo(OperatorMatcher): <NEW_LINE> <INDENT> def __init__(self, matcher): <NEW_LINE> <INDENT> super(_LMemo, self).__init__() <NEW_LINE> self._arg(matcher=matcher) <NEW_LINE> self.__caches = {} <NEW_LINE> self.__state = State.singleton() <NEW_LINE> <DEDENT> def _match(self, stream): <NEW_LINE> <INDENT> key = (stream, self.__state.hash) <NEW_LINE> if key not in self.__caches: <NEW_LINE> <INDENT> self.__caches[key] = PerStreamCache(self.matcher) <NEW_LINE> <DEDENT> return self.__caches[key]._match(stream) | A memoizer for grammars that do have left recursion. | 62598fd355399d3f056269d1 |
class ProjectsManager(base.Manager): <NEW_LINE> <INDENT> resource_class = Project <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(ProjectsManager, self).__init__(client) <NEW_LINE> self.roles_manager = RolesManager(client) <NEW_LINE> self.quotas_manager = QuotasManager(client) <NEW_LINE> self.licenses_manager = LicenseManager(client) <NEW_LINE> self.token_manager = TokensManager(client) <NEW_LINE> self.subnets_manager = SubnetManager(client) <NEW_LINE> self.fips_manager = FloatingIPManager(client) <NEW_LINE> <DEDENT> def list(self, return_raw=False): <NEW_LINE> <INDENT> return self._list('/projects', 'projects', return_raw=return_raw) <NEW_LINE> <DEDENT> def create(self, name, quotas=None, auto_quotas=False, return_raw=False): <NEW_LINE> <INDENT> body = {"project": {"name": name, "auto_quotas": auto_quotas}} <NEW_LINE> if quotas: <NEW_LINE> <INDENT> body["project"]["quotas"] = quotas <NEW_LINE> <DEDENT> return self._post('/projects', body, 'project', return_raw=return_raw) <NEW_LINE> <DEDENT> def show(self, project_id, return_raw=False): <NEW_LINE> <INDENT> return self._get('/projects/{}'.format(project_id), 'project', return_raw=return_raw) <NEW_LINE> <DEDENT> @process_theme_params <NEW_LINE> def update(self, project_id, name=None, cname=None, color=None, logo=None, brand_color=None, reset_cname=False, reset_color=False, reset_logo=False, reset_theme=False, reset_brand_color=None, return_raw=False): <NEW_LINE> <INDENT> body = {"project": {"theme": {}}} <NEW_LINE> if name: <NEW_LINE> <INDENT> body["project"]["name"] = name <NEW_LINE> <DEDENT> if cname: <NEW_LINE> <INDENT> body["project"]["custom_url"] = cname <NEW_LINE> <DEDENT> if color: <NEW_LINE> <INDENT> body["project"]["theme"]["color"] = color <NEW_LINE> <DEDENT> if logo: <NEW_LINE> <INDENT> body["project"]["theme"]["logo"] = logo <NEW_LINE> <DEDENT> if brand_color: <NEW_LINE> <INDENT> body["project"]["theme"]["brand_color"] = brand_color <NEW_LINE> <DEDENT> if reset_cname: <NEW_LINE> <INDENT> body["project"]["custom_url"] = "" <NEW_LINE> <DEDENT> if reset_color: <NEW_LINE> <INDENT> body["project"]["theme"]["color"] = "" <NEW_LINE> <DEDENT> if reset_logo: <NEW_LINE> <INDENT> body["project"]["theme"]["logo"] = "" <NEW_LINE> <DEDENT> if reset_brand_color: <NEW_LINE> <INDENT> body["project"]["theme"]["brand_color"] = "" <NEW_LINE> <DEDENT> if reset_theme: <NEW_LINE> <INDENT> body["project"]["theme"].update({"color": "", "logo": "", "brand_color": ""}) <NEW_LINE> <DEDENT> if not body["project"]["theme"]: <NEW_LINE> <INDENT> body["project"].pop("theme") <NEW_LINE> <DEDENT> return self._patch('/projects/{}'.format(project_id), body, 'project', return_raw=return_raw) <NEW_LINE> <DEDENT> def delete(self, project_id): <NEW_LINE> <INDENT> self._delete('/projects/{}'.format(project_id)) <NEW_LINE> <DEDENT> def delete_many(self, project_ids, raise_if_not_found=True): <NEW_LINE> <INDENT> for project_id in project_ids: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.delete(project_id) <NEW_LINE> log.info("Project %s has been deleted", project_id) <NEW_LINE> <DEDENT> except ClientException as err: <NEW_LINE> <INDENT> if raise_if_not_found: <NEW_LINE> <INDENT> raise err <NEW_LINE> <DEDENT> log.error("%s %s", err, project_id) | Manager class for manipulating project. | 62598fd3be7bc26dc92520b3 |
class TestTasks(unittest.TestCase): <NEW_LINE> <INDENT> @patch.object(tasks, 'vmware') <NEW_LINE> def test_show_ok(self, fake_vmware): <NEW_LINE> <INDENT> fake_vmware.show_jumpbox.return_value = {'worked': True} <NEW_LINE> output = tasks.show(username='bob') <NEW_LINE> expected = {'content' : {'worked': True}, 'error': None, 'params': {}} <NEW_LINE> self.assertEqual(output, expected) <NEW_LINE> <DEDENT> @patch.object(tasks, 'vmware') <NEW_LINE> def test_show_value_error(self, fake_vmware): <NEW_LINE> <INDENT> fake_vmware.show_jumpbox.side_effect = [ValueError("testing")] <NEW_LINE> output = tasks.show(username='bob') <NEW_LINE> expected = {'content' : {}, 'error': 'testing', 'params': {}} <NEW_LINE> self.assertEqual(output, expected) <NEW_LINE> <DEDENT> @patch.object(tasks, 'vmware') <NEW_LINE> def test_create_ok(self, fake_vmware): <NEW_LINE> <INDENT> fake_vmware.create_jumpbox.return_value = {'worked': True} <NEW_LINE> output = tasks.create(username='bob', network='someNetwork') <NEW_LINE> expected = {'content' : {'worked': True}, 'error': None, 'params': {}} <NEW_LINE> self.assertEqual(output, expected) <NEW_LINE> <DEDENT> @patch.object(tasks, 'vmware') <NEW_LINE> def test_create_value_error(self, fake_vmware): <NEW_LINE> <INDENT> fake_vmware.create_jumpbox.side_effect = [ValueError("testing")] <NEW_LINE> output = tasks.create(username='bob', network='someNetwork') <NEW_LINE> expected = {'content' : {}, 'error': 'testing', 'params': {}} <NEW_LINE> self.assertEqual(output, expected) <NEW_LINE> <DEDENT> @patch.object(tasks, 'vmware') <NEW_LINE> def test_delete_ok(self, fake_vmware): <NEW_LINE> <INDENT> fake_vmware.delete_jumpbox.return_value = {'worked': True} <NEW_LINE> output = tasks.delete(username='bob') <NEW_LINE> expected = {'content' : {'worked': True}, 'error': None, 'params': {}} <NEW_LINE> self.assertEqual(output, expected) <NEW_LINE> <DEDENT> @patch.object(tasks, 'vmware') <NEW_LINE> def test_delete_value_error(self, fake_vmware): <NEW_LINE> <INDENT> fake_vmware.delete_jumpbox.side_effect = [ValueError("testing")] <NEW_LINE> output = tasks.delete(username='bob') <NEW_LINE> expected = {'content' : {}, 'error': 'testing', 'params': {}} <NEW_LINE> self.assertEqual(output, expected) | A set of test cases for tasks.py | 62598fd3656771135c489b28 |
class MockDateTime(datetime.datetime): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def now(cls, tz=None): <NEW_LINE> <INDENT> return cls.today() <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> result = super(MockDateTime, self).__sub__(other) <NEW_LINE> if hasattr(result, "timetuple"): <NEW_LINE> <INDENT> return MockDateTime.fromtimestamp(time.mktime(result.timetuple())) <NEW_LINE> <DEDENT> return result | class for mocking datetime.datetime | 62598fd360cbc95b063647f4 |
class InstallLib(_install_lib.install_lib): <NEW_LINE> <INDENT> user_options = _install_lib.install_lib.user_options + [] <NEW_LINE> boolean_options = _install_lib.install_lib.boolean_options + [] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> _install_lib.install_lib.initialize_options(self) <NEW_LINE> if _option_defaults.has_key('install_lib'): <NEW_LINE> <INDENT> for opt_name, default in _option_defaults['install_lib']: <NEW_LINE> <INDENT> setattr(self, opt_name, default) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> _install_lib.install_lib.finalize_options(self) <NEW_LINE> if _option_inherits.has_key('install_lib'): <NEW_LINE> <INDENT> for parent, opt_name in _option_inherits['install_lib']: <NEW_LINE> <INDENT> self.set_undefined_options(parent, (opt_name, opt_name)) <NEW_LINE> <DEDENT> <DEDENT> if _option_finalizers.has_key('install_lib'): <NEW_LINE> <INDENT> for func in _option_finalizers['install_lib'].values(): <NEW_LINE> <INDENT> func(self) | Extended lib installer | 62598fd3ad47b63b2c5a7d0b |
class ButtonGroup(Element): <NEW_LINE> <INDENT> def __init__(self, size=None, vertical=False, justified=False, cl=None, ident=None, style=None, attrs=None): <NEW_LINE> <INDENT> super().__init__(cl=cl, ident=ident, style=style, attrs=attrs) <NEW_LINE> self.size = size <NEW_LINE> self.vertical = vertical <NEW_LINE> self.justified = justified <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<ButtonGroup(size=" + self.size + ")>" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> output = [ "<div " ] <NEW_LINE> if self.ident: <NEW_LINE> <INDENT> output.append('id="') <NEW_LINE> output.append(self.ident) <NEW_LINE> output.append('" ') <NEW_LINE> <DEDENT> output.append('class="') <NEW_LINE> classes = [ "btn-group" ] <NEW_LINE> if self.cl: <NEW_LINE> <INDENT> classes.append(self.cl) <NEW_LINE> <DEDENT> if self.justified: <NEW_LINE> <INDENT> classes.append("btn-group-justified") <NEW_LINE> <DEDENT> if self.vertical: <NEW_LINE> <INDENT> classes.append("btn-group-vertical") <NEW_LINE> <DEDENT> if self.size: <NEW_LINE> <INDENT> if self.size == "large" or self.size == "lg": <NEW_LINE> <INDENT> classes.append("btn-group-lg") <NEW_LINE> <DEDENT> elif self.size == "small" or self.size == "sm": <NEW_LINE> <INDENT> classes.append("btn-group-sm") <NEW_LINE> <DEDENT> elif self.size == "xsmall" or self.size == "xs": <NEW_LINE> <INDENT> classes.append("btn-group-xs") <NEW_LINE> <DEDENT> <DEDENT> output.append(" ".join(classes)) <NEW_LINE> output.append('" role="group"') <NEW_LINE> if self.style: <NEW_LINE> <INDENT> output.append(' style="') <NEW_LINE> output.append(self.style) <NEW_LINE> output.append('"') <NEW_LINE> <DEDENT> if self.attrs: <NEW_LINE> <INDENT> for k in self.attrs.keys(): <NEW_LINE> <INDENT> output.append(' ' + k + '="' + self.attrs[k] + '"') <NEW_LINE> <DEDENT> <DEDENT> output.append(">") <NEW_LINE> for child in self._children: <NEW_LINE> <INDENT> if self.justified and type(child) == Button: <NEW_LINE> <INDENT> bgrp = ButtonGroup() <NEW_LINE> bgrp.addelement(child) <NEW_LINE> output.append(str(bgrp)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output.append(str(child)) <NEW_LINE> <DEDENT> <DEDENT> output.append("</div>") <NEW_LINE> return "".join(output) | Implements a button group <div class="btn-group"> | 62598fd38a349b6b436866f8 |
class LongThrower(ThrowerAnt): <NEW_LINE> <INDENT> name = 'Long' <NEW_LINE> implemented = True <NEW_LINE> food_cost = 2 <NEW_LINE> min_range = 5 <NEW_LINE> def nearest_bee(self, hive): <NEW_LINE> <INDENT> return ThrowerAnt.nearest_bee(self,hive) | A ThrowerAnt that only throws leaves at Bees at least 5 places away. | 62598fd33d592f4c4edbb36f |
class ToDo(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def load_data(): <NEW_LINE> <INDENT> read_file = open("C:\\users\\feliciam\\documents\\_PythonClass\\Module06\\Todo.txt", "r") <NEW_LINE> file_lst = [] <NEW_LINE> for line in read_file: <NEW_LINE> <INDENT> current_task, current_priority = line.split(",") <NEW_LINE> file_dict = {current_task: current_priority} <NEW_LINE> file_lst.append(file_dict) <NEW_LINE> <DEDENT> return file_lst <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def display_lst(lst): <NEW_LINE> <INDENT> for item in lst: <NEW_LINE> <INDENT> print(item) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def user_mod(mod_lst, write_file, old_length): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> user_choice = input("What would you like to do? ") <NEW_LINE> if user_choice == "1": <NEW_LINE> <INDENT> task = input("Please enter the task: ") <NEW_LINE> priority = input("What is its priority (high/low)? ") <NEW_LINE> mod_dict = {task: priority} <NEW_LINE> mod_lst.append(mod_dict) <NEW_LINE> <DEDENT> elif user_choice == "2": <NEW_LINE> <INDENT> erase_task = input("Which task would you like to erase? ") <NEW_LINE> try: <NEW_LINE> <INDENT> mod_lst.remove("Task: " + erase_task) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> print("That Task does not exist in the list!") <NEW_LINE> <DEDENT> <DEDENT> elif user_choice == "3": <NEW_LINE> <INDENT> for mod_dict in mod_lst: <NEW_LINE> <INDENT> if mod_lst.index(mod_dict) > (old_length - 1): <NEW_LINE> <INDENT> for element in mod_dict: <NEW_LINE> <INDENT> write_file.write("Task: " + element + ", Priority: " + mod_dict.get(element) + "\n") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("You did not choose a valid option. Please try again.") <NEW_LINE> continue | This class containts all functions to manage a simple To-Do list | 62598fd3ad47b63b2c5a7d0c |
@python_2_unicode_compatible <NEW_LINE> class Comment(TimeStampedModel): <NEW_LINE> <INDENT> message = models.TextField() <NEW_LINE> creator = models.ForeignKey(user_models.User, null = True,on_delete=models.CASCADE) <NEW_LINE> image = models.ForeignKey(Image, null = True,on_delete=models.CASCADE, related_name = 'comments') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.message | Comment Model | 62598fd3ab23a570cc2d4fca |
class ProjectInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ProjectName = None <NEW_LINE> self.ProjectCreatorUin = None <NEW_LINE> self.ProjectCreateTime = None <NEW_LINE> self.ProjectResume = None <NEW_LINE> self.OwnerUin = None <NEW_LINE> self.ProjectId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ProjectName = params.get("ProjectName") <NEW_LINE> self.ProjectCreatorUin = params.get("ProjectCreatorUin") <NEW_LINE> self.ProjectCreateTime = params.get("ProjectCreateTime") <NEW_LINE> self.ProjectResume = params.get("ProjectResume") <NEW_LINE> self.OwnerUin = params.get("OwnerUin") <NEW_LINE> self.ProjectId = params.get("ProjectId") | Content of the ProjectInfo parameter. ProjectInfo is an element of Certificates array which is returned by DescribeCertificates.
| 62598fd3ec188e330fdf8d4f |
@typechecked <NEW_LINE> class Property(PropertyABC): <NEW_LINE> <INDENT> def __init__( self, name: str, value: PropertyTypes, src: PropertyTypes = None, ): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._value = value <NEW_LINE> self._src = src <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self) -> PropertyTypes: <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @property <NEW_LINE> def value_export(self) -> str: <NEW_LINE> <INDENT> return self._export(self._value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def src(self) -> PropertyTypes: <NEW_LINE> <INDENT> return self._src <NEW_LINE> <DEDENT> @property <NEW_LINE> def src_export(self) -> str: <NEW_LINE> <INDENT> return self._export(self._src) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _import(cls, value: str) -> PropertyTypes: <NEW_LINE> <INDENT> value = value.strip() <NEW_LINE> if value.isnumeric(): <NEW_LINE> <INDENT> return int(value) <NEW_LINE> <DEDENT> if value.strip() == "" or value == "-" or value.lower() == "none": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return float(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _export(self, value: PropertyTypes) -> str: <NEW_LINE> <INDENT> return "-" if value is None else str(value) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_params(cls, name, value, src) -> PropertyABC: <NEW_LINE> <INDENT> return cls( name=name, value=cls._import(value), src=cls._import(src), ) | Immutable. | 62598fd3956e5f7376df58da |
class BagObj(object): <NEW_LINE> <INDENT> def __init__(self, obj): <NEW_LINE> <INDENT> self._obj = weakref.proxy(obj) <NEW_LINE> <DEDENT> def __getattribute__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return object.__getattribute__(self, '_obj')[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(key) <NEW_LINE> <DEDENT> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return object.__getattribute__(self, '_obj').keys() | BagObj(obj)
Convert attribute look-ups to getitems on the object passed in.
Parameters
----------
obj : class instance
Object on which attribute look-up is performed.
Examples
--------
>>> from numpy.lib.npyio import BagObj as BO
>>> class BagDemo(object):
... def __getitem__(self, key): # An instance of BagObj(BagDemo)
... # will call this method when any
... # attribute look-up is required
... result = "Doesn't matter what you want, "
... return result + "you're gonna get this"
...
>>> demo_obj = BagDemo()
>>> bagobj = BO(demo_obj)
>>> bagobj.hello_there
"Doesn't matter what you want, you're gonna get this"
>>> bagobj.I_can_be_anything
"Doesn't matter what you want, you're gonna get this" | 62598fd3bf627c535bcb1968 |
class LightSourceTab(BaseWidget): <NEW_LINE> <INDENT> _lightsource = None <NEW_LINE> _update_function = None <NEW_LINE> def __init__(self, update_function=None): <NEW_LINE> <INDENT> super().__init__("Light Source Tab") <NEW_LINE> self._update_function = update_function <NEW_LINE> self._device_select = ControlCombo( label="Light Source" ) <NEW_LINE> self._custom = ControlEmptyWidget() <NEW_LINE> self._device_select.changed_event = self._on_device_change <NEW_LINE> self._device_select.add_item('None', None) <NEW_LINE> for class_type in LightSource.__subclasses__(): <NEW_LINE> <INDENT> self._device_select.add_item(class_type.__name__, class_type) <NEW_LINE> <DEDENT> <DEDENT> def _on_device_change(self): <NEW_LINE> <INDENT> device = self._device_select.value <NEW_LINE> if callable(device): <NEW_LINE> <INDENT> self._lightsource = device() <NEW_LINE> self._custom.value = self._lightsource.get_custom_config() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._lightsource = None <NEW_LINE> self._custom.value = None <NEW_LINE> <DEDENT> if callable(self._update_function): <NEW_LINE> <INDENT> self._update_function({'lightsource': self._lightsource}) | Tab to select the lightsource device | 62598fd3fbf16365ca794578 |
class AddExpression(SymbolExpression): <NEW_LINE> <INDENT> def __init__(self, left, right): <NEW_LINE> <INDENT> super().__init__(left, right) <NEW_LINE> <DEDENT> def interpreter(self, var): <NEW_LINE> <INDENT> return self._left.interpreter(var) + self._right.interpreter(var) | 加法解析器 | 62598fd355399d3f056269d5 |
class Test_drop_table: <NEW_LINE> <INDENT> @pytest.fixture() <NEW_LINE> def fake_entity(self): <NEW_LINE> <INDENT> class FakeEntity(Entity): <NEW_LINE> <INDENT> metas = { 'table_name': 'lolol' } <NEW_LINE> PartitionKey = KeyField() <NEW_LINE> RowKey = KeyField() <NEW_LINE> f1 = FloatField() <NEW_LINE> <DEDENT> return FakeEntity <NEW_LINE> <DEDENT> """test delete""" <NEW_LINE> @pytest.fixture() <NEW_LINE> def fake_ts(self): <NEW_LINE> <INDENT> class TS: <NEW_LINE> <INDENT> def delete_table(*args, **kwargs): <NEW_LINE> <INDENT> assert kwargs['table_name'] == 'lolol' <NEW_LINE> assert kwargs['fail_not_exist'] == 'haha' <NEW_LINE> raise MemoryError('called delete_table') <NEW_LINE> <DEDENT> <DEDENT> return TS() <NEW_LINE> <DEDENT> def test_call_delete_table(self, fake_entity, fake_ts): <NEW_LINE> <INDENT> with pytest.raises(MemoryError) as e: <NEW_LINE> <INDENT> fake_entity.drop_table(fail_not_exist='haha', ts=fake_ts) <NEW_LINE> <DEDENT> assert 'called delete_table' in str(e) | test drop_table | 62598fd3dc8b845886d53a78 |
class Unparser(iast.NodeVisitor): <NEW_LINE> <INDENT> def process(self, tree): <NEW_LINE> <INDENT> self.tokens = [] <NEW_LINE> super().process(tree) <NEW_LINE> return ''.join(self.tokens) <NEW_LINE> <DEDENT> def visit_BinOp(self, node): <NEW_LINE> <INDENT> self.tokens.append('(') <NEW_LINE> self.visit(node.left) <NEW_LINE> self.tokens.append(' ') <NEW_LINE> self.visit(node.op) <NEW_LINE> self.tokens.append(' ') <NEW_LINE> self.visit(node.right) <NEW_LINE> self.tokens.append(')') <NEW_LINE> <DEDENT> def visit_Neg(self, node): <NEW_LINE> <INDENT> self.tokens.append('-(') <NEW_LINE> self.visit(node.value) <NEW_LINE> self.tokens.append(')') <NEW_LINE> <DEDENT> def visit_Num(self, node): <NEW_LINE> <INDENT> self.tokens.append(str(node.n)) <NEW_LINE> <DEDENT> def visit_Var(self, node): <NEW_LINE> <INDENT> self.tokens.append(node.id) <NEW_LINE> <DEDENT> def op_helper(self, node): <NEW_LINE> <INDENT> map = {'Add': '+', 'Sub': '-', 'Mult': '*', 'Div': '/'} <NEW_LINE> self.tokens.append(map[node.__class__.__name__]) <NEW_LINE> <DEDENT> visit_Add = visit_Sub = visit_Mult = visit_Div = op_helper | Turns AST back into an expression string. | 62598fd3ab23a570cc2d4fcb |
class BookInstance(models.Model): <NEW_LINE> <INDENT> id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') <NEW_LINE> book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) <NEW_LINE> imprint = models.CharField(max_length=200) <NEW_LINE> due_back = models.DateField(null=True, blank=True) <NEW_LINE> LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) <NEW_LINE> status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability') <NEW_LINE> borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['due_back'] <NEW_LINE> permissions = (("can_mark_returned", "Set book as returned"),) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{0} ({1})'.format(self.id, self.book.title) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_overdue(self): <NEW_LINE> <INDENT> if self.due_back and date.today() > self.due_back: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Model representing a specific copy of a book (i.e. that can be borrowed from the library) | 62598fd39f28863672818adb |
class FieldType(db.Model): <NEW_LINE> <INDENT> __tablename__ = "field_type" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(32), index=True) <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Field Type %r>' % self.name <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other is not None and self.id == other.id | Model for the type of a Field | 62598fd3a219f33f346c6cc3 |
class ChannelOfCloseIndex(Index): <NEW_LINE> <INDENT> def cal(self, theKLineList, theRefDays = 0): <NEW_LINE> <INDENT> indexList = [] <NEW_LINE> for i in range(theKLineList.getLen()): <NEW_LINE> <INDENT> if i < self.getParam1(): <NEW_LINE> <INDENT> indexList.append(self.__calSlice(theKLineList.getList()[0:i + 1])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indexList.append(self.__calSlice( theKLineList.getList()[i + 1 - self.getParam1() : i + 1])) <NEW_LINE> <DEDENT> <DEDENT> return Index._reffer(indexList, theRefDays) <NEW_LINE> <DEDENT> def __calSlice(self, theListSlice): <NEW_LINE> <INDENT> theHigh = theListSlice[0].close() <NEW_LINE> theLow = theListSlice[0].close() <NEW_LINE> for i in range(len(theListSlice)): <NEW_LINE> <INDENT> if i >= self.getParam1(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if theListSlice[i].close() > theHigh: <NEW_LINE> <INDENT> theHigh = theListSlice[i].close() <NEW_LINE> <DEDENT> if theListSlice[i].close() < theLow: <NEW_LINE> <INDENT> theLow = theListSlice[i].close() <NEW_LINE> <DEDENT> <DEDENT> return [theHigh, theLow] | 过去N日通道指标类(不考虑盘中最高最低价,仅考虑收盘价),仅包含一个参数:通道日长param1, | 62598fd47cff6e4e811b5ee7 |
class NoSuchTileError(Exception): <NEW_LINE> <INDENT> def __init__(self, lat, lon): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.lat = lat <NEW_LINE> self.lon = lon <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "No SRTM tile for %d, %d available!" % (self.lat, self.lon) | Raised when there is no tile for a region. | 62598fd4ad47b63b2c5a7d0e |
class axSharer(object): <NEW_LINE> <INDENT> def map_vals(self,): <NEW_LINE> <INDENT> return set(self.map.flatten()) <NEW_LINE> <DEDENT> def __init__(self, saxes, share_map=False): <NEW_LINE> <INDENT> self.saxes = saxes <NEW_LINE> self.map = np.zeros(saxes.n, dtype=np.uint16) <NEW_LINE> self.map[:] = share_map <NEW_LINE> self._share_ax = {} <NEW_LINE> <DEDENT> def __getitem__(self, ind): <NEW_LINE> <INDENT> return self.map[ind] <NEW_LINE> <DEDENT> def __setitem__(self, ind, val): <NEW_LINE> <INDENT> self.map[ind] = val <NEW_LINE> <DEDENT> def __call__(self, iv, ih): <NEW_LINE> <INDENT> mapVal = self.map[iv, ih] <NEW_LINE> if not mapVal: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif mapVal in self._share_ax: <NEW_LINE> <INDENT> return self._share_ax[mapVal] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> axs = self.saxes.axes[self.map == mapVal] <NEW_LINE> if np.any(axs): <NEW_LINE> <INDENT> self._share_ax[mapVal] = axs[np.nonzero(axs)][0] <NEW_LINE> return self._share_ax[mapVal] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return | A class for handling sharing of axes. | 62598fd4ad47b63b2c5a7d0f |
class CalendarUserProfile(Profile_abstract): <NEW_LINE> <INDENT> manager = models.ForeignKey(Manager, verbose_name=_("manager"), help_text=_("select manager"), related_name="manager_of_calendar_user") <NEW_LINE> calendar_setting = models.ForeignKey(CalendarSetting, verbose_name=_('calendar settings')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> permissions = ( ("view_calendar_user", _('can see Calendar User list')), ) <NEW_LINE> db_table = 'calendar_user_profile' <NEW_LINE> app_label = 'user_profile' <NEW_LINE> verbose_name = _("calendar user profile") <NEW_LINE> verbose_name_plural = _("calendar user profiles") <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % str(self.user) | This defines extra features for the AR_user
**Attributes**:
* ``calendar_setting`` - appointment reminder settings
**Name of DB table**: calendar_user_profile | 62598fd4656771135c489b30 |
class XalocMachineInfo(Equipment): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> Equipment.__init__(self, name) <NEW_LINE> self.values_dict = {} <NEW_LINE> self.values_dict["mach_current"] = None <NEW_LINE> self.values_dict["mach_status"] = "" <NEW_LINE> self.values_dict["topup_remaining"] = "" <NEW_LINE> self.chan_mach_current = None <NEW_LINE> self.chan_mach_status = None <NEW_LINE> self.chan_topup_remaining = None <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.chan_mach_current = self.get_channel_object("MachCurrent") <NEW_LINE> if self.chan_mach_current is not None: <NEW_LINE> <INDENT> self.chan_mach_current.connect_signal( "update", self.mach_current_changed ) <NEW_LINE> <DEDENT> self.chan_mach_status = self.get_channel_object("MachStatus") <NEW_LINE> if self.chan_mach_status is not None: <NEW_LINE> <INDENT> self.chan_mach_status.connect_signal("update", self.mach_status_changed) <NEW_LINE> <DEDENT> self.chan_topup_remaining = self.get_channel_object("TopUpRemaining") <NEW_LINE> if self.chan_topup_remaining is not None: <NEW_LINE> <INDENT> self.chan_topup_remaining.connect_signal( "update", self.topup_remaining_changed ) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logging.getLogger().warning("%s: cannot read machine info", self.name()) <NEW_LINE> <DEDENT> <DEDENT> def mach_current_changed(self, value): <NEW_LINE> <INDENT> if ( self.values_dict["mach_current"] is None or abs(self.values_dict["mach_current"] - value) > 0.10 ): <NEW_LINE> <INDENT> self.values_dict["mach_current"] = value <NEW_LINE> self.re_emit_values() <NEW_LINE> <DEDENT> <DEDENT> def mach_status_changed(self, status): <NEW_LINE> <INDENT> self.values_dict["mach_status"] = str(status) <NEW_LINE> self.re_emit_values() <NEW_LINE> <DEDENT> def topup_remaining_changed(self, value): <NEW_LINE> <INDENT> self.values_dict["topup_remaining"] = value <NEW_LINE> self.re_emit_values() <NEW_LINE> <DEDENT> def re_emit_values(self): <NEW_LINE> <INDENT> values_to_send = [] <NEW_LINE> values_to_send.append(self.values_dict["mach_current"]) <NEW_LINE> values_to_send.append(self.values_dict["mach_status"]) <NEW_LINE> values_to_send.append(self.values_dict["topup_remaining"]) <NEW_LINE> self.emit("valuesChanged", values_to_send) <NEW_LINE> <DEDENT> def get_mach_current(self): <NEW_LINE> <INDENT> return self.chan_mach_current.get_value() <NEW_LINE> <DEDENT> def get_mach_status(self): <NEW_LINE> <INDENT> return self.chan_mach_status.get_value() <NEW_LINE> <DEDENT> def get_topup_remaining(self): <NEW_LINE> <INDENT> return self.chan_topup_remaining.get_value() | Descript. : Displays actual information about the machine status. | 62598fd4091ae356687050da |
class Historic(NamedTuple): <NEW_LINE> <INDENT> entity: str <NEW_LINE> name: str <NEW_LINE> time: ApproxTimeSpan | Contains information about currency withdrawal event. | 62598fd4adb09d7d5dc0aa39 |
class IsOwner(BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if isinstance(obj, Bucketlist): <NEW_LINE> <INDENT> return obj.owner == request.user <NEW_LINE> <DEDENT> return obj.owner == request.user | Custom permission class to allow only bucketlist owner to edit them | 62598fd4283ffb24f3cf3d41 |
@pyblish.api.log <NEW_LINE> class SelectFtrack(pyblish.api.Selector): <NEW_LINE> <INDENT> hosts = ['*'] <NEW_LINE> version = (0, 1, 0) <NEW_LINE> def process_context(self, context): <NEW_LINE> <INDENT> decodedEventData = json.loads( base64.b64decode( os.environ.get('FTRACK_CONNECT_EVENT') ) ) <NEW_LINE> taskid = decodedEventData.get('selection')[0]['entityId'] <NEW_LINE> ftrackData = pyblish_ftrack_utils.getData(taskid) <NEW_LINE> context.set_data('ftrackData', value=ftrackData) <NEW_LINE> try: <NEW_LINE> <INDENT> (prefix, version) = pyblish_utils.version_get(filename, 'v') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.log.warning('Cannot publish workfile which is not versioned.') <NEW_LINE> return <NEW_LINE> <DEDENT> context.set_data('version', value=version) <NEW_LINE> context.set_data('vprefix', value=prefix) <NEW_LINE> self.log.info('Found ftrack data') | Collects ftrack data from FTRACK_CONNECT_EVENT | 62598fd4dc8b845886d53a7e |
class QuarterEnd(QuarterOffset): <NEW_LINE> <INDENT> _outputName = 'QuarterEnd' <NEW_LINE> _default_startingMonth = 3 <NEW_LINE> _prefix = 'Q' <NEW_LINE> _day_opt = 'end' | DateOffset increments between business Quarter dates.
startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ...
startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ...
startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... | 62598fd40fa83653e46f53a9 |
@attr.s <NEW_LINE> class LTEData: <NEW_LINE> <INDENT> websession = attr.ib() <NEW_LINE> modem_data = attr.ib(init=False, factory=dict) <NEW_LINE> def get_modem_data(self, config): <NEW_LINE> <INDENT> return self.modem_data.get(config[CONF_HOST]) | Shared state. | 62598fd4be7bc26dc92520b8 |
class ModelSaver(Callback): <NEW_LINE> <INDENT> def __init__(self, keep_recent=10, keep_freq=0.5, checkpoint_dir=None, var_collections=tf.GraphKeys.GLOBAL_VARIABLES): <NEW_LINE> <INDENT> self.keep_recent = keep_recent <NEW_LINE> self.keep_freq = keep_freq <NEW_LINE> if not isinstance(var_collections, list): <NEW_LINE> <INDENT> var_collections = [var_collections] <NEW_LINE> <DEDENT> self.var_collections = var_collections <NEW_LINE> if checkpoint_dir is None: <NEW_LINE> <INDENT> checkpoint_dir = logger.LOG_DIR <NEW_LINE> <DEDENT> assert os.path.isdir(checkpoint_dir), checkpoint_dir <NEW_LINE> self.checkpoint_dir = checkpoint_dir <NEW_LINE> <DEDENT> def _setup_graph(self): <NEW_LINE> <INDENT> vars = [] <NEW_LINE> for key in self.var_collections: <NEW_LINE> <INDENT> vars.extend(tf.get_collection(key)) <NEW_LINE> <DEDENT> self.path = os.path.join(self.checkpoint_dir, 'model') <NEW_LINE> self.saver = tf.train.Saver( var_list=vars, max_to_keep=self.keep_recent, keep_checkpoint_every_n_hours=self.keep_freq, write_version=tf.train.SaverDef.V2) <NEW_LINE> self.meta_graph_written = False <NEW_LINE> <DEDENT> def _trigger(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not self.meta_graph_written: <NEW_LINE> <INDENT> self.saver.export_meta_graph( os.path.join(self.checkpoint_dir, 'graph-{}.meta'.format(logger.get_time_str())), collection_list=self.graph.get_all_collection_keys()) <NEW_LINE> self.meta_graph_written = True <NEW_LINE> <DEDENT> self.saver.save( tf.get_default_session(), self.path, global_step=tf.train.get_global_step(), write_meta_graph=False) <NEW_LINE> logger.info("Model saved to %s." % tf.train.get_checkpoint_state(self.checkpoint_dir).model_checkpoint_path) <NEW_LINE> <DEDENT> except (OSError, IOError): <NEW_LINE> <INDENT> logger.exception("Exception in ModelSaver.trigger_epoch!") | Save the model every epoch. | 62598fd48a349b6b43686702 |
class MetreManager: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def is_fornyrdhislag(text: str) -> bool: <NEW_LINE> <INDENT> lines = [line for line in text.split("\n") if line] <NEW_LINE> return len(lines) == 8 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_ljoodhhaattr(text: str) -> bool: <NEW_LINE> <INDENT> lines = [line for line in text.split("\n") if line] <NEW_LINE> return len(lines) == 6 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def load_poem_from_paragraphs(paragraphs: List[str]): <NEW_LINE> <INDENT> poem = [] <NEW_LINE> for paragraph in paragraphs: <NEW_LINE> <INDENT> if MetreManager.is_fornyrdhislag(paragraph): <NEW_LINE> <INDENT> fnl = Fornyrdhislag() <NEW_LINE> fnl.from_short_lines_text(paragraph) <NEW_LINE> fnl.syllabify(old_norse_syllabifier.hierarchy) <NEW_LINE> fnl.to_phonetics() <NEW_LINE> poem.append(fnl) <NEW_LINE> <DEDENT> elif MetreManager.is_ljoodhhaattr(paragraph): <NEW_LINE> <INDENT> lh = Ljoodhhaattr() <NEW_LINE> lh.from_short_lines_text(paragraph) <NEW_LINE> lh.syllabify(old_norse_syllabifier.hierarchy) <NEW_LINE> lh.to_phonetics() <NEW_LINE> poem.append(lh) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stanza = UnspecifiedStanza() <NEW_LINE> stanza.from_short_lines_text(paragraph) <NEW_LINE> stanza.syllabify(old_norse_syllabifier.hierarchy) <NEW_LINE> stanza.to_phonetics() <NEW_LINE> poem.append(stanza) <NEW_LINE> <DEDENT> <DEDENT> return poem | Handles different kinds of meter in Old Norse poetry.
* Fornyrðislag
* Ljóðaháttr | 62598fd4956e5f7376df58de |
class Teacher(Person): <NEW_LINE> <INDENT> def __init__(self, fName, lName, tchID, tchPIN): <NEW_LINE> <INDENT> if util.valid_name_check(lName): <NEW_LINE> <INDENT> if util.valid_name_check(fName): <NEW_LINE> <INDENT> if util.valid_id_check(tchID): <NEW_LINE> <INDENT> if util.valid_pin_check(tchPIN): <NEW_LINE> <INDENT> super().__init__(lName, fName) <NEW_LINE> self._tchID = tchID <NEW_LINE> self._tchPIN = tchPIN <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Bad attribute input: ' + str(tchPIN)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Bad attribute input: ' + str(tchID)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Bad attribute input: ' + str(fName)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Bad attribute input: ' + str(lName)) <NEW_LINE> <DEDENT> <DEDENT> '''Functions to change individual characteristics of an teacher object''' <NEW_LINE> def set_tchID(self, tchID): <NEW_LINE> <INDENT> self._tchID = tchID <NEW_LINE> <DEDENT> def set_tchPIN(self, tchPIN): <NEW_LINE> <INDENT> self._tchPIN = tchPIN <NEW_LINE> <DEDENT> '''Function to create output string based off an teacher class''' <NEW_LINE> def display(self): <NEW_LINE> <INDENT> return (str(self._fName) + '\n' + str(self._lName) + '\n' + str(self._tchID) + '\n' + str(self._tchPIN)) | Teacher class constructor | 62598fd4377c676e912f6fda |
class MakeMenuItem: <NEW_LINE> <INDENT> def __init__(self, menu, id): <NEW_LINE> <INDENT> self.menu = menu <NEW_LINE> self.id = id <NEW_LINE> <DEDENT> def checked(self, check=None): <NEW_LINE> <INDENT> return self.menu.checked(self.id, check) <NEW_LINE> <DEDENT> def toggle(self): <NEW_LINE> <INDENT> checked = not self.checked() <NEW_LINE> self.checked(checked) <NEW_LINE> return checked <NEW_LINE> <DEDENT> def enabled(self, enable=None): <NEW_LINE> <INDENT> return self.menu.enabled(self.id, enable) <NEW_LINE> <DEDENT> def label(self, label=None): <NEW_LINE> <INDENT> return self.menu.label(self.id, label) | A menu item for a menu managed by MakeMenu.
| 62598fd4adb09d7d5dc0aa3d |
class spells: <NEW_LINE> <INDENT> spells_dict = { 'Expelliarmus' : 'disarms your enemy by knocking their want out of their hand.' , 'Lumos' : 'Use your wand as a light.' , 'Nox' : 'Put out the light on your wand.' , 'Protego' : 'Shield charm used whild duelling.' , 'Accio' : 'Summons whatever you say after the spell to fly into your hand.' , 'Stupefy' : 'Stun your opponent.' , 'Wingardium Leviosa' : 'Make things levitate' , 'Petrificus Totalus' : 'Temporarily bind and paralyze your opponent.' , 'Expecto Patronum' : 'Summons your patronus to repel evil dementors that want to suck out your soul. Should assign an animal to the patronus (eg. wolf, stag, bear, etc.).' , 'Reparo' : 'Repair things that are broken.' } <NEW_LINE> counter = 0 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.counter += 1 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> message = f'This is the super Class for magical spells used at Hogwarts school.' <NEW_LINE> return message <NEW_LINE> <DEDENT> def get_all_spells(self): <NEW_LINE> <INDENT> return self.spells_dict | This Class has a dictionary of spells that can be learned.
Also contains a method called get_all_spells that returns this dictionary. | 62598fd4099cdd3c63675640 |
class XYZTransform(AffineTransform): <NEW_LINE> <INDENT> function_range = CoordinateSystem(lps_output_coordnames, name='world') <NEW_LINE> def __init__(self, affine, axis_names, lps=True): <NEW_LINE> <INDENT> affine = np.asarray(affine) <NEW_LINE> if affine.shape != (4,4): <NEW_LINE> <INDENT> raise ValueError('affine must be a 4x4 matrix representing ' 'an affine transformation ' 'in homogeneous coordinates') <NEW_LINE> <DEDENT> if lps: <NEW_LINE> <INDENT> xyz = lps_output_coordnames <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xyz = ras_output_coordnames <NEW_LINE> <DEDENT> AffineTransform.__init__(self, CS(axis_names, name='voxel'), CS(xyz, name='world'), affine) <NEW_LINE> <DEDENT> def reordered_range(self, order, name=''): <NEW_LINE> <INDENT> raise NotImplementedError("the XYZ world coordinates are always " "either %s or %s so they can't be " "reordered" % (lps_output_coordnames, ras_output_coordnames)) <NEW_LINE> <DEDENT> def renamed_range(self, newnames, name=''): <NEW_LINE> <INDENT> raise NotImplementedError("the XYZ world coordinates are always " "either %s or %s so they can't be " "renamed" % (lps_output_coordnames, ras_output_coordnames)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s_split = AffineTransform.__repr__(self).split('\n') <NEW_LINE> s_split[0] = 'XYZTransform(' <NEW_LINE> return '\n'.join(s_split) | Affine transform with x, y, z being L<->R, P<->A, I<->S
That is, the X axis is left to right or right to left, the Y axis is
anterior to posterior or posterior to anterior, and the Z axis is
inferior to superior or superior to inferior. | 62598fd40fa83653e46f53ab |
class Sub(UserNotice): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Sub(channel: {self.channel}, user: {self.display_name})" | This class is the exact same as class:UserNotice: except with a different name.
Created for specific msg_id of sub.
Should not be manually created in most cases. | 62598fd497e22403b383b3cc |
class ZonaPagosConfirmView(viewsets.GenericViewSet): <NEW_LINE> <INDENT> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> id_comercio = request.GET.get('id_comercio') <NEW_LINE> id_pago = request.GET.get('id_pago') <NEW_LINE> if id_pago and id_comercio: <NEW_LINE> <INDENT> transaction = Transaction.objects.get(id_pago=id_pago) <NEW_LINE> transaction.status = "pending" <NEW_LINE> transaction.save() <NEW_LINE> TransactionStatus.objects.create(transaction=transaction, status=transaction.status, details="pago hecho") <NEW_LINE> data = TransactionSerializer(transaction).data <NEW_LINE> response = Response(data, status=status.HTTP_200_OK) <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = Response({'error': "check parameters"}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> return response | Zona pagos view to confirm payments | 62598fd4ab23a570cc2d4fcf |
class LangTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> DATA_DIR = os.path.dirname(data_dir) <NEW_LINE> self.langs_to_test = [] <NEW_LINE> for fn in glob(f'{DATA_DIR}/*.*sv'): <NEW_LINE> <INDENT> if fn.endswith('csv'): <NEW_LINE> <INDENT> delimiter = ',' <NEW_LINE> <DEDENT> elif fn.endswith('psv'): <NEW_LINE> <INDENT> delimiter = '|' <NEW_LINE> <DEDENT> elif fn.endswith('tsv'): <NEW_LINE> <INDENT> delimiter = '\t' <NEW_LINE> <DEDENT> with open(fn, encoding="utf-8") as csvfile: <NEW_LINE> <INDENT> reader = csv.reader(csvfile, delimiter=delimiter) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> if len(row) < 4: <NEW_LINE> <INDENT> LOGGER.warning(f'Row in {fn} containing values {row} does not have the right values. Please check your data.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.langs_to_test.append(row) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def test_io(self): <NEW_LINE> <INDENT> error_count = 0 <NEW_LINE> for test in self.langs_to_test: <NEW_LINE> <INDENT> transducer = make_g2p(test[0], test[1]) <NEW_LINE> output_string = transducer(test[2]).output_string.strip() <NEW_LINE> if output_string != test[3].strip(): <NEW_LINE> <INDENT> LOGGER.warning("test_langs.py: mapping error: {} from {} to {} should be {}, got {}".format(test[2], test[0], test[1], test[3], output_string)) <NEW_LINE> if error_count == 0: <NEW_LINE> <INDENT> first_failed_test = test <NEW_LINE> <DEDENT> error_count += 1 <NEW_LINE> <DEDENT> <DEDENT> if error_count > 0: <NEW_LINE> <INDENT> transducer = make_g2p(first_failed_test[0], first_failed_test[1]) <NEW_LINE> self.assertEqual(transducer(first_failed_test[2]).output_string.strip(), first_failed_test[3].strip()) | Basic Test for individual lookup tables.
Test files (in g2p/tests/public/data) are either .csv, .psv, or
.tsv files, the only difference being the delimiter used (comma,
pipe, or tab).
Each line in the test file consists of SOURCE,TARGET,INPUT,OUTPUT | 62598fd4bf627c535bcb1972 |
class LocalSecondaryIndex(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "IndexName": (str, True), "KeySchema": ([KeySchema], True), "Projection": (Projection, True), } | `LocalSecondaryIndex <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-lsi.html>`__ | 62598fd4ad47b63b2c5a7d14 |
class TestV1beta2ControllerRevision(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 testV1beta2ControllerRevision(self): <NEW_LINE> <INDENT> pass | V1beta2ControllerRevision unit test stubs | 62598fd4283ffb24f3cf3d45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.