code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class CMakeBuildTaskSettings(object): <NEW_LINE> <INDENT> REMEMBER_NAMES = ["build_config", "config"] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.build_config = None <NEW_LINE> self.config = None <NEW_LINE> self._initialized = False <NEW_LINE> for name, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.build_config = None <NEW_LINE> self.config = None <NEW_LINE> self._initialized = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def initialized(self): <NEW_LINE> <INDENT> return self._initialized <NEW_LINE> <DEDENT> def init_with_context_config(self, ctx_config): <NEW_LINE> <INDENT> if not self.initialized: <NEW_LINE> <INDENT> self.build_config = getattr(ctx_config, "build_config", None) <NEW_LINE> self._initialized = True <NEW_LINE> <DEDENT> <DEDENT> def remember_value(self, name, value): <NEW_LINE> <INDENT> remembered_value = getattr(self, name, None) <NEW_LINE> value = value or remembered_value <NEW_LINE> if value: <NEW_LINE> <INDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def remember_data(self, data): <NEW_LINE> <INDENT> for name in self.REMEMBER_NAMES: <NEW_LINE> <INDENT> if name in data: <NEW_LINE> <INDENT> value = data[name] <NEW_LINE> data[name] = self.remember_value(name, value) <NEW_LINE> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> def needs_remember(self, data): <NEW_LINE> <INDENT> for name in self.REMEMBER_NAMES: <NEW_LINE> <INDENT> if name in data: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def remember_build_config(self, value): <NEW_LINE> <INDENT> return self.remember_value("build_config", value) <NEW_LINE> <DEDENT> def remember_config(self, value): <NEW_LINE> <INDENT> return self.remember_value("config", value) | Shared inter-task configuration for CMake build task(s).
.. code-block:: sh
# -- NOTE: Test task should "inherit" the config value of the build task
$ cmake-build build --build-config=Release test
$ cmake-build build --config=Release test | 62599078a17c0f6771d5d88c |
class User(AbstractUser): <NEW_LINE> <INDENT> avatar = models.ImageField(upload_to='avatars/', blank=True, null=True) <NEW_LINE> class Meta(AbstractUser.Meta): <NEW_LINE> <INDENT> swappable = 'AUTH_USER_MODEL' | Users within the Django authentication system are represented by this
model.
Username, password and email are required. Other fields are optional. | 625990788a349b6b43687c17 |
class Solution: <NEW_LINE> <INDENT> def validWordSquare(self, words): <NEW_LINE> <INDENT> if not words: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> n = len(words) <NEW_LINE> row = 0 <NEW_LINE> while row < n: <NEW_LINE> <INDENT> l = len(words[row]) <NEW_LINE> col = 0 <NEW_LINE> while col < l: <NEW_LINE> <INDENT> if words[row][col] != words[col][row]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> col += 1 <NEW_LINE> <DEDENT> row += 1 <NEW_LINE> <DEDENT> return True | @param words: a list of string
@return: a boolean | 625990787c178a314d78e8c9 |
class LibraryRedirectPage(base.BaseHandler): <NEW_LINE> <INDENT> URL_PATH_ARGS_SCHEMAS = {} <NEW_LINE> HANDLER_ARGS_SCHEMAS = { 'GET': {} } <NEW_LINE> @acl_decorators.open_access <NEW_LINE> def get(self): <NEW_LINE> <INDENT> self.redirect('/community-library') | An old 'gallery' page that should redirect to the library index page. | 625990781f5feb6acb1645b3 |
class ErrorUnavailable(grpc.RpcError, grpc.Call): <NEW_LINE> <INDENT> pass | ErrorUnavailable exception | 625990785fdd1c0f98e5f93a |
@immutable <NEW_LINE> class Lesson(Serializable): <NEW_LINE> <INDENT> id: int = IntegerField(key="Id", required=False) <NEW_LINE> date: DateTime = ChildField(DateTime, key="Date", required=False) <NEW_LINE> time: TimeSlot = ChildField(TimeSlot, key="TimeSlot", required=False) <NEW_LINE> room: LessonRoom = ChildField(LessonRoom, key="Room", required=False) <NEW_LINE> teacher: Teacher = ChildField(Teacher, key="TeacherPrimary", required=False) <NEW_LINE> second_teacher: Teacher = ChildField( Teacher, key="TeacherSecondary", required=False ) <NEW_LINE> subject: Subject = ChildField(Subject, key="Subject", required=False) <NEW_LINE> event: str = StringField(key="Event", required=False) <NEW_LINE> changes: LessonChanges = ChildField(LessonChanges, key="Change", required=False) <NEW_LINE> team_class: TeamClass = ChildField(TeamClass, key="Clazz", required=False) <NEW_LINE> pupil_alias: str = StringField(key="PupilAlias", required=False) <NEW_LINE> group: TeamVirtual = ChildField(TeamVirtual, key="Distribution", required=False) <NEW_LINE> visible: bool = BooleanField(key="Visible", required=False) <NEW_LINE> @classmethod <NEW_LINE> async def get( cls, api, last_sync, deleted, date_from, date_to, **kwargs ) -> Union[AsyncIterator["Lesson"], List[int]]: <NEW_LINE> <INDENT> if date_from is None: <NEW_LINE> <INDENT> date_from = datetime.date.today() <NEW_LINE> <DEDENT> if date_to is None: <NEW_LINE> <INDENT> date_to = date_from <NEW_LINE> <DEDENT> data = await api.helper.get_list( DATA_TIMETABLE, FilterType.BY_PUPIL, deleted=deleted, date_from=date_from, date_to=date_to, last_sync=last_sync, **kwargs, ) <NEW_LINE> for lesson in data: <NEW_LINE> <INDENT> yield Lesson.load(lesson) | A lesson.
:var int ~.id: lesson's ID
:var `~vulcan.model.DateTime` ~.date: lesson's date
:var `~vulcan.model.TimeSlot` ~.time: lesson's time
:var `~vulcan.data.LessonRoom` ~.room: classroom, in which is the lesson
:var `~vulcan.model.Teacher` ~.teacher: teacher of the lesson
:var `~vulcan.model.Teacher` ~.second_teacher: second teacher of the lesson
:var `~vulcan.model.Subject` ~.subject: subject on the lesson
:var str ~.event: an event happening during this lesson
:var `~vulcan.data.LessonChanges` ~.changes: lesson changes
:var `~vulcan.model.TeamClass` ~.team_class: the class that has the lesson
:var str ~.pupil_alias: pupil alias
:var `~vulcan.model.TeamVirtual` ~.group: group, that has the lesson
:var bool ~.visible: lesson visibility (whether the timetable applies to the given student) | 625990785fc7496912d48f48 |
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **kwargs): <NEW_LINE> <INDENT> clear_scheduled_jobs() <NEW_LINE> register_scheduled_jobs() | Deletes then Re-creates repeated jobs. | 6259907844b2445a339b763c |
class Command(object): <NEW_LINE> <INDENT> def __init__(self, name, args=()): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> if name in globals(): <NEW_LINE> <INDENT> self.function = globals()[name] <NEW_LINE> <DEDENT> elif name in _commands: <NEW_LINE> <INDENT> self.function = _commands[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('No such command') <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.function(*args, **kwargs) | Command class
name: name of the command
function: function of the command | 6259907801c39578d7f14413 |
class Weather(object): <NEW_LINE> <INDENT> def __init__(self, temp, dewpoint, humidity, wind_speed, wind_direction, description, image_url, visibility, windchill, pressure): <NEW_LINE> <INDENT> self.temp = temp <NEW_LINE> self.dewpoint = dewpoint <NEW_LINE> self.humidity = humidity <NEW_LINE> self.wind_speed = wind_speed <NEW_LINE> self.wind_direction = wind_direction <NEW_LINE> self.description = description <NEW_LINE> self.image_url = image_url <NEW_LINE> self.visibility = visibility <NEW_LINE> self.windchill = windchill <NEW_LINE> self.pressure = pressure <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "<Weather: {}F and {}>".format(self.temperature, self.description) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> string = self.__unicode__() <NEW_LINE> if not PYTHON_3: <NEW_LINE> <INDENT> return string.encode('utf-8') <NEW_LINE> <DEDENT> return string <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = self.__unicode__() <NEW_LINE> if not PYTHON_3: <NEW_LINE> <INDENT> return string.encode('utf-8') <NEW_LINE> <DEDENT> return string <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return {'temperature': self.temp, 'dewpoint': self.dewpoint, 'humidity': self.humidity, 'wind_speed': self.wind_speed, 'wind_direction': self.wind_direction, 'description': self.description, 'image_url': self.image_url, 'visibility': self.visibility, 'windchill': self.windchill, 'pressure': self.pressure} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _from_json(json_data): <NEW_LINE> <INDENT> return Weather(_parse_int(json_data.get('Temp', 0)), _parse_int(json_data.get('Dewp', 0)), _parse_int(json_data.get('Relh', 0)), _parse_int(json_data.get('Winds', 0)), _parse_int(json_data.get('Windd', 0)), json_data.get('Weather', ''), json_data.get('Weatherimage', ''), _parse_float(json_data.get('Visibility', 0.0)), _parse_int(json_data.get('WindChill', 0)), _parse_float(json_data.get('SLP', 0.0))) | A structured representation the current weather. | 625990787d43ff24874280f3 |
class ProductItemView(BrowserView): <NEW_LINE> <INDENT> pass | Product Item
| 625990784f88993c371f1200 |
class Constraint(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) >= 2: <NEW_LINE> <INDENT> if isinstance(args[0], str): <NEW_LINE> <INDENT> source = pm.ls(args[0]) <NEW_LINE> if len(source) < 1: <NEW_LINE> <INDENT> raise ValueError("More than one object matches name: {}".format(args[0])) <NEW_LINE> <DEDENT> self.source = source[0] <NEW_LINE> <DEDENT> elif isinstance(args[0], pm.nt.Transform): <NEW_LINE> <INDENT> self.source = args[0] <NEW_LINE> <DEDENT> self.target = args[1] <NEW_LINE> <DEDENT> for key in ('source', 'target', 'name'): <NEW_LINE> <INDENT> if key in kwargs: <NEW_LINE> <INDENT> setattr(self, key, kwargs[key]) <NEW_LINE> <DEDENT> <DEDENT> self._nodes = list() | Base class for a constraint. | 62599078283ffb24f3cf525e |
class RegWriter(object): <NEW_LINE> <INDENT> def __init__(self, dbase): <NEW_LINE> <INDENT> self.dbase = dbase <NEW_LINE> <DEDENT> def save(self, filename): <NEW_LINE> <INDENT> create_backup_file(filename) <NEW_LINE> ofile = open(filename, "w") <NEW_LINE> if self.dbase.array_is_reg: <NEW_LINE> <INDENT> array = "reg" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> array = "mem" <NEW_LINE> <DEDENT> ofile.write('<?xml version="1.0"?>\n') <NEW_LINE> ofile.write('<module name="%s" coverage="%d" internal="%d">\n' % (self.dbase.module_name, int(self.dbase.coverage), int(self.dbase.internal_only))) <NEW_LINE> ofile.write(' <base addr_width="%d" ' % self.dbase.address_bus_width) <NEW_LINE> ofile.write('data_width="%d"/>\n' % self.dbase.data_bus_width) <NEW_LINE> self.write_port_information(ofile) <NEW_LINE> overview = cleanup(self.dbase.overview_text) <NEW_LINE> if overview: <NEW_LINE> <INDENT> ofile.write(" <overview>%s</overview>\n" % overview) <NEW_LINE> <DEDENT> if self.dbase.owner: <NEW_LINE> <INDENT> ofile.write(" <owner>%s</owner>\n" % self.dbase.owner) <NEW_LINE> <DEDENT> if self.dbase.descriptive_title: <NEW_LINE> <INDENT> ofile.write(" <title>%s</title>\n" % self.dbase.descriptive_title) <NEW_LINE> <DEDENT> if self.dbase.organization: <NEW_LINE> <INDENT> ofile.write(" <org>%s</org>\n" % self.dbase.organization) <NEW_LINE> <DEDENT> ofile.write(" <array>%s</array>\n" % array) <NEW_LINE> self.write_signal_list(ofile) <NEW_LINE> ofile.write('</module>\n') <NEW_LINE> ofile.close() <NEW_LINE> <DEDENT> def write_port_information(self, ofile): <NEW_LINE> <INDENT> ofile.write(' <ports>\n') <NEW_LINE> ofile.write(' <interface>%d</interface>\n' % int(self.dbase.use_interface)) <NEW_LINE> ofile.write(' <addr>%s</addr>\n' % self.dbase.address_bus_name) <NEW_LINE> ofile.write(' <data_in>%s</data_in>\n' % self.dbase.write_data_name) <NEW_LINE> ofile.write( ' <data_out>%s</data_out>\n' % self.dbase.read_data_name) <NEW_LINE> ofile.write( ' <be active="%d">%s</be>\n' % (self.dbase.byte_strobe_active_level, self.dbase.byte_strobe_name)) <NEW_LINE> ofile.write(' <wr>%s</wr>\n' % self.dbase.write_strobe_name) <NEW_LINE> ofile.write(' <ack>%s</ack>\n' % self.dbase.acknowledge_name) <NEW_LINE> ofile.write(' <rd>%s</rd>\n' % self.dbase.read_strobe_name) <NEW_LINE> ofile.write(' <clk>%s</clk>\n' % self.dbase.clock_name) <NEW_LINE> ofile.write(' <reset active="%d">%s</reset>\n' % (self.dbase.reset_active_level, self.dbase.reset_name)) <NEW_LINE> ofile.write(' </ports>\n') <NEW_LINE> <DEDENT> def write_signal_list(self, ofile): <NEW_LINE> <INDENT> for reg in self.dbase.get_all_registers(): <NEW_LINE> <INDENT> write_register(ofile, reg) | Writes the XML file. | 625990784527f215b58eb67f |
class Permissions(object): <NEW_LINE> <INDENT> deserialized_types = { 'consent_token': 'str', 'scopes': 'dict(str, ask_sdk_model.scope.Scope)' } <NEW_LINE> attribute_map = { 'consent_token': 'consentToken', 'scopes': 'scopes' } <NEW_LINE> def __init__(self, consent_token=None, scopes=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.consent_token = consent_token <NEW_LINE> self.scopes = scopes <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.value <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Permissions): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | Contains a consentToken allowing the skill access to information that the customer has consented to provide, such as address information. Note that the consentToken is deprecated. Use the apiAccessToken available in the context object to determine the user’s permissions.
:param consent_token: A token listing all the permissions granted for this user
:type consent_token: (optional) str
:param scopes: A map where the key is a LoginWithAmazon(LWA) scope and value is a list of key:value pairs which describe the state of user actions on the LWA scope. For e.g. \"scopes\" :{ \"alexa::devices:all:geolocation:read\":{\"status\":\"GRANTED\"}} This value of \"alexa::devices:all:geolocation:read\" will determine if the Geolocation data access is granted by the user, or else it will show a card of type AskForPermissionsConsent to the user to get this permission.
:type scopes: (optional) dict(str, ask_sdk_model.scope.Scope) | 62599078dc8b845886d54f78 |
class TransformerInfo(IdentifiedObject): <NEW_LINE> <INDENT> def __init__(self, Transformers=None, WindingInfos=None, *args, **kw_args): <NEW_LINE> <INDENT> self._Transformers = [] <NEW_LINE> self.Transformers = [] if Transformers is None else Transformers <NEW_LINE> self._WindingInfos = [] <NEW_LINE> self.WindingInfos = [] if WindingInfos is None else WindingInfos <NEW_LINE> super(TransformerInfo, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = [] <NEW_LINE> _attr_types = {} <NEW_LINE> _defaults = {} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["Transformers", "WindingInfos"] <NEW_LINE> _many_refs = ["Transformers", "WindingInfos"] <NEW_LINE> def getTransformers(self): <NEW_LINE> <INDENT> return self._Transformers <NEW_LINE> <DEDENT> def setTransformers(self, value): <NEW_LINE> <INDENT> for x in self._Transformers: <NEW_LINE> <INDENT> x.TransformerInfo = None <NEW_LINE> <DEDENT> for y in value: <NEW_LINE> <INDENT> y._TransformerInfo = self <NEW_LINE> <DEDENT> self._Transformers = value <NEW_LINE> <DEDENT> Transformers = property(getTransformers, setTransformers) <NEW_LINE> def addTransformers(self, *Transformers): <NEW_LINE> <INDENT> for obj in Transformers: <NEW_LINE> <INDENT> obj.TransformerInfo = self <NEW_LINE> <DEDENT> <DEDENT> def removeTransformers(self, *Transformers): <NEW_LINE> <INDENT> for obj in Transformers: <NEW_LINE> <INDENT> obj.TransformerInfo = None <NEW_LINE> <DEDENT> <DEDENT> def getWindingInfos(self): <NEW_LINE> <INDENT> return self._WindingInfos <NEW_LINE> <DEDENT> def setWindingInfos(self, value): <NEW_LINE> <INDENT> for x in self._WindingInfos: <NEW_LINE> <INDENT> x.TransformerInfo = None <NEW_LINE> <DEDENT> for y in value: <NEW_LINE> <INDENT> y._TransformerInfo = self <NEW_LINE> <DEDENT> self._WindingInfos = value <NEW_LINE> <DEDENT> WindingInfos = property(getWindingInfos, setWindingInfos) <NEW_LINE> def addWindingInfos(self, *WindingInfos): <NEW_LINE> <INDENT> for obj in WindingInfos: <NEW_LINE> <INDENT> obj.TransformerInfo = self <NEW_LINE> <DEDENT> <DEDENT> def removeWindingInfos(self, *WindingInfos): <NEW_LINE> <INDENT> for obj in WindingInfos: <NEW_LINE> <INDENT> obj.TransformerInfo = None | Set of transformer data, from an equipment library.
| 6259907876e4537e8c3f0f3d |
class SslTest(IgniteTest): <NEW_LINE> <INDENT> @cluster(num_nodes=3) <NEW_LINE> @ignite_versions(str(DEV_BRANCH), str(LATEST)) <NEW_LINE> def test_ssl_connection(self, ignite_version): <NEW_LINE> <INDENT> shared_root = get_shared_root_path(self.test_context.globals) <NEW_LINE> server_ssl = SslParams(shared_root, key_store_jks=DEFAULT_SERVER_KEYSTORE) <NEW_LINE> server_configuration = IgniteConfiguration( version=IgniteVersion(ignite_version), ssl_params=server_ssl, connector_configuration=ConnectorConfiguration(ssl_enabled=True, ssl_params=server_ssl)) <NEW_LINE> ignite = IgniteService(self.test_context, server_configuration, num_nodes=2, startup_timeout_sec=180) <NEW_LINE> client_configuration = server_configuration._replace( client_mode=True, ssl_params=SslParams(shared_root, key_store_jks=DEFAULT_CLIENT_KEYSTORE), connector_configuration=None) <NEW_LINE> app = IgniteApplicationService( self.test_context, client_configuration, java_class_name="org.apache.ignite.internal.ducktest.tests.smoke_test.SimpleApplication", startup_timeout_sec=180) <NEW_LINE> admin_ssl = SslParams(shared_root, key_store_jks=DEFAULT_ADMIN_KEYSTORE) <NEW_LINE> control_utility = ControlUtility(cluster=ignite, ssl_params=admin_ssl) <NEW_LINE> ignite.start() <NEW_LINE> app.start() <NEW_LINE> control_utility.cluster_state() <NEW_LINE> app.stop() <NEW_LINE> ignite.stop() | Ssl test. | 625990787c178a314d78e8ca |
class Target(object): <NEW_LINE> <INDENT> def __init__(self, target): <NEW_LINE> <INDENT> self.platform = target[0] <NEW_LINE> if len(target) > 1: <NEW_LINE> <INDENT> self.options = target[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.options = None <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.platform <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.platform == other.platform and self.options == other.options <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) | The type of acl to be rendered from this policy file. | 625990785fc7496912d48f49 |
class ProxyDualSlider(ProxyControl): <NEW_LINE> <INDENT> declaration = ForwardTyped(lambda: DualSlider) <NEW_LINE> def set_minimum(self, minimum): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_maximum(self, maximum): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_low_value(self, value): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_high_value(self, value): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_tick_position(self, position): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_tick_interval(self, interval): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_orientation(self, orientation): <NEW_LINE> <INDENT> raise NotImplementedError | The abstract definition of a proxy Slider object.
| 625990785166f23b2e244d95 |
class CzechAccountNumberFieldAnonymizer(NumericFieldAnonymizer): <NEW_LINE> <INDENT> use_smart_method = False <NEW_LINE> max_anonymization_range = 10000 <NEW_LINE> def __init__(self, *args, use_smart_method=False, **kwargs): <NEW_LINE> <INDENT> self.use_smart_method = use_smart_method <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def get_encrypted_value(self, value, encryption_key: str): <NEW_LINE> <INDENT> account = CzechAccountNumber.parse(value) <NEW_LINE> if self.use_smart_method and account.check_account_format(): <NEW_LINE> <INDENT> return str(account.brute_force_next(self.get_numeric_encryption_key(encryption_key))) <NEW_LINE> <DEDENT> account.num = int(encrypt_text(encryption_key, str(account.num), NUMBERS)) <NEW_LINE> return str(account) <NEW_LINE> <DEDENT> def get_decrypted_value(self, value: Any, encryption_key: str): <NEW_LINE> <INDENT> account = CzechAccountNumber.parse(value) <NEW_LINE> if self.use_smart_method and account.check_account_format(): <NEW_LINE> <INDENT> return str(account.brute_force_prev(self.get_numeric_encryption_key(encryption_key))) <NEW_LINE> <DEDENT> account.num = int(decrypt_text(encryption_key, str(account.num), NUMBERS)) <NEW_LINE> return str(account) | Anonymization for czech account number.
Setting `use_smart_method=True` retains valid format for encrypted value using this
have significant effect on performance. | 62599078bf627c535bcb2e8d |
class TestPODTemplateFields(PODTemplateIntegrationTest): <NEW_LINE> <INDENT> def test_class_registration(self): <NEW_LINE> <INDENT> from collective.documentgenerator.content.pod_template import PODTemplate <NEW_LINE> self.assertTrue(self.test_podtemplate.__class__ == PODTemplate) <NEW_LINE> <DEDENT> def test_schema_registration(self): <NEW_LINE> <INDENT> portal_types = api.portal.get_tool('portal_types') <NEW_LINE> podtemplate_type = portal_types.get(self.test_podtemplate.portal_type) <NEW_LINE> self.assertTrue('IPODTemplate' in podtemplate_type.schema) <NEW_LINE> <DEDENT> def test_odt_file_attribute(self): <NEW_LINE> <INDENT> test_podtemplate = aq_base(self.test_podtemplate) <NEW_LINE> self.assertTrue(hasattr(test_podtemplate, 'odt_file')) <NEW_LINE> <DEDENT> def test_odt_file_field_display(self): <NEW_LINE> <INDENT> self.browser.open(self.test_podtemplate.absolute_url()) <NEW_LINE> contents = self.browser.contents <NEW_LINE> msg = "field 'odt_file' is not displayed" <NEW_LINE> self.assertTrue('id="form-widgets-odt_file"' in contents, msg) <NEW_LINE> msg = "field 'odt_file' is not translated" <NEW_LINE> self.assertTrue('Canevas' in contents, msg) <NEW_LINE> <DEDENT> def test_odt_file_field_edit(self): <NEW_LINE> <INDENT> contents = self._edit_object(self.test_podtemplate) <NEW_LINE> msg = "field 'odt_file' is not editable" <NEW_LINE> self.assertTrue('Canevas' in contents, msg) <NEW_LINE> <DEDENT> def test_initial_md5_attribute(self): <NEW_LINE> <INDENT> test_podtemplate = aq_base(self.test_podtemplate) <NEW_LINE> self.assertTrue(hasattr(test_podtemplate, 'initial_md5')) <NEW_LINE> <DEDENT> def test_initial_md5_field_display(self): <NEW_LINE> <INDENT> self.browser.open(self.test_podtemplate.absolute_url()) <NEW_LINE> contents = self.browser.contents <NEW_LINE> msg = "field 'initial_md5' is displayed" <NEW_LINE> self.assertTrue('id="form-widgets-initial_md5"' not in contents, msg) <NEW_LINE> <DEDENT> def test_initial_md5_field_edit(self): <NEW_LINE> <INDENT> contents = self._edit_object(self.test_podtemplate) <NEW_LINE> msg = "field 'initial_md5' is editable" <NEW_LINE> self.assertTrue('md5' not in contents, msg) <NEW_LINE> <DEDENT> def test_enabled_attribute(self): <NEW_LINE> <INDENT> test_podtemplate = aq_base(self.test_podtemplate) <NEW_LINE> self.assertTrue(hasattr(test_podtemplate, 'enabled')) <NEW_LINE> <DEDENT> def test_enabled_field_display(self): <NEW_LINE> <INDENT> self.browser.open(self.test_podtemplate.absolute_url()) <NEW_LINE> contents = self.browser.contents <NEW_LINE> msg = "field 'enabled' is not displayed" <NEW_LINE> self.assertTrue('id="form-widgets-enabled"' in contents, msg) <NEW_LINE> msg = "field 'enabled' is not translated" <NEW_LINE> self.assertTrue('Activé' in contents, msg) <NEW_LINE> <DEDENT> def test_enabled_field_edit(self): <NEW_LINE> <INDENT> contents = self._edit_object(self.test_podtemplate) <NEW_LINE> msg = "field 'enabled' is not editable" <NEW_LINE> self.assertTrue('Activé' in contents, msg) | Test schema fields declaration. | 62599078adb09d7d5dc0bf28 |
class Mod(VBA_Object): <NEW_LINE> <INDENT> def __init__(self, original_str, location, tokens): <NEW_LINE> <INDENT> super(Mod, self).__init__(original_str, location, tokens) <NEW_LINE> self.arg = tokens[0][::2] <NEW_LINE> <DEDENT> def eval(self, context, params=None): <NEW_LINE> <INDENT> return reduce(lambda x, y: x % y, eval_args(self.arg, context)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ' mod '.join(map(repr, self.arg)) | VBA Modulo using the operator 'Mod' | 625990781b99ca4002290215 |
class LabelModel(nn.Module): <NEW_LINE> <INDENT> def forward(self, *args): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def estimate_label_model(self, *args, config=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_label_distribution(self, *args): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_most_probable_labels(self, *args): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _do_estimate_label_model(self, batches, config): <NEW_LINE> <INDENT> optimizer = torch.optim.SGD( self.parameters(), lr=config.step_size, momentum=config.momentum, weight_decay=0) <NEW_LINE> if config.step_schedule is not None and config.step_size_mult is not None: <NEW_LINE> <INDENT> scheduler = torch.optim.lr_scheduler.MultiStepLR( optimizer, config.step_schedule, gamma=config.step_size_mult) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scheduler = None <NEW_LINE> <DEDENT> for epoch in range(config.epochs): <NEW_LINE> <INDENT> logging.info('Epoch {}/{}'.format(epoch + 1, config.epochs)) <NEW_LINE> if scheduler is not None: <NEW_LINE> <INDENT> scheduler.step() <NEW_LINE> <DEDENT> self.train() <NEW_LINE> running_loss = 0.0 <NEW_LINE> for i_batch, inputs in enumerate(batches): <NEW_LINE> <INDENT> optimizer.zero_grad() <NEW_LINE> log_likelihood = self(*inputs) <NEW_LINE> loss = -1 * torch.mean(log_likelihood) <NEW_LINE> loss += self._get_regularization_loss() <NEW_LINE> loss.backward() <NEW_LINE> optimizer.step() <NEW_LINE> running_loss += loss.item() <NEW_LINE> <DEDENT> epoch_loss = running_loss / len(batches) <NEW_LINE> logging.info('Train Loss: %.6f', epoch_loss) <NEW_LINE> <DEDENT> <DEDENT> def _get_regularization_loss(self): <NEW_LINE> <INDENT> return 0.0 | Parent class for all generative label models.
Concrete subclasses should implement at least forward(),
estimate_label_model(), and get_label_distribution(). | 625990797d43ff24874280f4 |
class NumberOfPublicAttributes(Metric): <NEW_LINE> <INDENT> requires = ('Fields',) <NEW_LINE> def visitClass(self, node, *args): <NEW_LINE> <INDENT> node.NumberOfPublicAttributes = sum( 1 for name in node.Fields if not name.startswith('_') ) | Number of public attributes of a (Class)
This is computed by the accesses to self.* that are not methods | 625990793317a56b869bf225 |
class TestLimitHourActionSend(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 testLimitHourActionSend(self): <NEW_LINE> <INDENT> pass | LimitHourActionSend unit test stubs | 62599079009cb60464d02efd |
class WorkerFoundNoSuchLocation(WorkerError): <NEW_LINE> <INDENT> pass | A worker was unable to find a location for the user. | 625990793346ee7daa338340 |
class CopySheetToAnotherSpreadsheetRequest(TypedDict): <NEW_LINE> <INDENT> destinationSpreadsheetId: str | The request to copy a sheet across spreadsheets. | 625990795fcc89381b266e3a |
class FormulaTester(object): <NEW_LINE> <INDENT> def __init__(self, check_code, box_answers, unit_tests): <NEW_LINE> <INDENT> check_code = check_code.replace('from calc import evaluator', 'from latex2dnd.calc import evaluator') <NEW_LINE> self.code = check_code <NEW_LINE> self.env = {} <NEW_LINE> try: <NEW_LINE> <INDENT> self.mod = import_from_string(check_code) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> sys.stderr.write("Failed to evaluate DDformula script code! Err=%s\n" % (str(err))) <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> for ut in unit_tests: <NEW_LINE> <INDENT> ut['expected_ans'] = self.make_expected_ans(ut['target_assignments']) <NEW_LINE> <DEDENT> self.unit_tests = [{'etype': 'correct', 'expected_ans': self.make_expected_ans(box_answers) }] <NEW_LINE> self.unit_tests += unit_tests <NEW_LINE> <DEDENT> def make_expected_ans(self, target_assignments): <NEW_LINE> <INDENT> return [ {draggable_id: target_id} for target_id, draggable_id in list(target_assignments.items()) ] <NEW_LINE> <DEDENT> def run_tests(self): <NEW_LINE> <INDENT> cnt = 0 <NEW_LINE> print("---------- Running %d DD formula unit tests ----------" % len(self.unit_tests)) <NEW_LINE> self.test_results = [] <NEW_LINE> for ut in self.unit_tests: <NEW_LINE> <INDENT> cnt += 1 <NEW_LINE> ret = self.test_answer(ut['etype'], ut['expected_ans']) <NEW_LINE> self.test_results.append(ret) <NEW_LINE> if ret['test_ok']: <NEW_LINE> <INDENT> print("DDformula test [%d] OK" % cnt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = "DDformula test [%d] ERROR! FAILURE on %s" % (cnt, ut) <NEW_LINE> print(msg) <NEW_LINE> raise Exception(msg) <NEW_LINE> <DEDENT> <DEDENT> return self.test_results <NEW_LINE> <DEDENT> def test_answer(self, etype, expected_ans): <NEW_LINE> <INDENT> assert etype=="correct" or etype=="incorrect" <NEW_LINE> ret = None <NEW_LINE> try: <NEW_LINE> <INDENT> ret = self.mod.dnd_check_function(None, json.dumps(expected_ans)) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print("ERROR in testing dnd check function: %s" % str(err)) <NEW_LINE> print("etype=%s" % etype) <NEW_LINE> print("expected_ans=%s" % expected_ans) <NEW_LINE> raise Exception("DDformula failure on %s" % json.dumps(expected_ans)) <NEW_LINE> <DEDENT> ret['test_etype'] = etype <NEW_LINE> ret['test_expected_ans'] = expected_ans <NEW_LINE> ret['test_ok'] = True <NEW_LINE> if etype=="correct" and not ret['ok']: <NEW_LINE> <INDENT> sys.stderr.write("ERROR in DND formula unit test:\n") <NEW_LINE> sys.stderr.write(" Expected %s to be CORRECT, but instead ret=%s\n" % (expected_ans, ret)) <NEW_LINE> ret['test_ok'] = False <NEW_LINE> <DEDENT> if etype=="incorrect" and ret['ok']: <NEW_LINE> <INDENT> sys.stderr.write("ERROR in DND formula unit test:\n") <NEW_LINE> sys.stderr.write(" Expected %s to be INCORRECT, but instead ret=%s\n" % (expected_ans, ret)) <NEW_LINE> ret['test_ok'] = False <NEW_LINE> <DEDENT> return ret | Evaluate python script for DDformula answer checking, and perform unit tests on it. | 625990798e7ae83300eeaa4c |
class ChallengeResource(Resource): <NEW_LINE> <INDENT> body = jose.Field('body', decoder=ChallengeBody.from_json) <NEW_LINE> authzr_uri = jose.Field('authzr_uri') <NEW_LINE> @property <NEW_LINE> def uri(self): <NEW_LINE> <INDENT> return self.body.uri | Challenge Resource.
:ivar acme.messages.ChallengeBody body:
:ivar str authzr_uri: URI found in the 'up' ``Link`` header. | 62599079e1aae11d1e7cf4f0 |
class DrainHandler(org.vertx.java.core.Handler): <NEW_LINE> <INDENT> def __init__(self, handler): <NEW_LINE> <INDENT> self.handler = handler <NEW_LINE> <DEDENT> def handle(self, nothing=None): <NEW_LINE> <INDENT> self.handler() | Drain handler | 625990791f5feb6acb1645b7 |
class ObstructionMap(object): <NEW_LINE> <INDENT> LEFT = 'LEFT' <NEW_LINE> RIGHT = 'RIGHT' <NEW_LINE> TOP = 'TOP' <NEW_LINE> BOTTOM = 'BOTTOM' <NEW_LINE> CENTER = 'CENTER' <NEW_LINE> HIGHPRIORITIES = ['person', 'chair', 'stop sign'] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.obstructions = defaultdict(list) <NEW_LINE> self.highprios = [] <NEW_LINE> <DEDENT> def clearMap(self): <NEW_LINE> <INDENT> self.obstructions.clear() <NEW_LINE> self.highprios = [] <NEW_LINE> <DEDENT> def addToMap(self, className, x, y, distance): <NEW_LINE> <INDENT> side = self.xToSide(x) <NEW_LINE> obs = ObstructionInfo() <NEW_LINE> obs.className = className <NEW_LINE> obs.distance = distance <NEW_LINE> obs.position = (x, y) <NEW_LINE> self.obstructions[side].append(obs) <NEW_LINE> if obs.className in self.HIGHPRIORITIES: <NEW_LINE> <INDENT> self.highprios.append(obs) <NEW_LINE> <DEDENT> <DEDENT> def xToSide(self, xCoord): <NEW_LINE> <INDENT> if xCoord < 40: <NEW_LINE> <INDENT> return ObstructionMap.LEFT <NEW_LINE> <DEDENT> elif xCoord > 80: <NEW_LINE> <INDENT> return ObstructionMap.RIGHT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ObstructionMap.CENTER <NEW_LINE> <DEDENT> <DEDENT> def getClosest(self): <NEW_LINE> <INDENT> if len(self.obstructions) is 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> closestObject = ObstructionInfo() <NEW_LINE> for side in self.obstructions: <NEW_LINE> <INDENT> for obs in self.obstructions[side]: <NEW_LINE> <INDENT> if obs.distance < closestObject.distance: <NEW_LINE> <INDENT> closestObject = obs <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return closestObject <NEW_LINE> <DEDENT> def getClosestOnSide(self, side): <NEW_LINE> <INDENT> if len(self.obstructions) is 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if side not in self.obstructions: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> closestObject = ObstructionInfo() <NEW_LINE> for obs in self.obstructions[side]: <NEW_LINE> <INDENT> if obs.distance < closestObject.distance: <NEW_LINE> <INDENT> closestObject = obs <NEW_LINE> <DEDENT> <DEDENT> return closestObject <NEW_LINE> <DEDENT> def getHighPriorities(self): <NEW_LINE> <INDENT> return self.highprios | TODO: Write down class information
Store objects into a dict?
Or a numpy type of array? Numpy can get things by distance
This class could be our decision maker also. Probably more efficient
to make decisions as things are added
Obstructions
LEFT, RIGHT | 625990795166f23b2e244d97 |
class Container: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.contents = [] <NEW_LINE> <DEDENT> def add(self, to_add: object) -> None: <NEW_LINE> <INDENT> self.contents.append(to_add) <NEW_LINE> <DEDENT> def remove(self) -> object: <NEW_LINE> <INDENT> raise NotImplementedError("You must define this specifically for your" "container subclass!") <NEW_LINE> <DEDENT> def is_empty(self) -> bool: <NEW_LINE> <INDENT> return self.contents == [] | A class to represent the types of containers such as Stack and Sack. | 62599079bf627c535bcb2e8f |
class ValidationException(Exception): <NEW_LINE> <INDENT> pass | An exception which can be thrown to show the consequences of the
validation function. | 625990793d592f4c4edbc83e |
class DescribeDeviceResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Device = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Device") is not None: <NEW_LINE> <INDENT> self.Device = DeviceInfo() <NEW_LINE> self.Device._deserialize(params.get("Device")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId") | DescribeDevice返回参数结构体
| 625990793346ee7daa338341 |
class OfferingSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> parent_course_title = serializers.SerializerMethodField('get_parent_title') <NEW_LINE> calculated_title = serializers.SerializerMethodField('get_calculated_title') <NEW_LINE> parent_course_id = serializers.SerializerMethodField('get_parent_course') <NEW_LINE> offering_link = serializers.HyperlinkedIdentityField(view_name='offering-detail') <NEW_LINE> instructors = serializers.SerializerMethodField('instructors_list_to_dicts') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Offering <NEW_LINE> lookup_field = 'course_sec_id' <NEW_LINE> <DEDENT> def get_calculated_title(self, obj): <NEW_LINE> <INDENT> if obj.title: <NEW_LINE> <INDENT> return obj.title <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return obj.course.long_title <NEW_LINE> <DEDENT> <DEDENT> def get_parent_title(self, obj): <NEW_LINE> <INDENT> return obj.course.long_title <NEW_LINE> <DEDENT> def get_parent_course(self, obj): <NEW_LINE> <INDENT> return obj.course.id <NEW_LINE> <DEDENT> def instructors_list_to_dicts(self, obj): <NEW_LINE> <INDENT> return [{ "name": i.profile.get_display_name, "profile_url": reverse('people_profile_detail', args=[i.profile.user.username])} for i in obj.instructors.all() ] | Serialized representation of a course offering, with calculated fields | 62599079be7bc26dc9252b36 |
class QuestionSubmission(messages.Message): <NEW_LINE> <INDENT> question_urlsafe_key = messages.StringField(1, required=True) <NEW_LINE> selected_answer = messages.MessageField(Answer, 2, required=True) <NEW_LINE> more_info_text = messages.StringField(3) | QuestionSubmission ProtoRPC Message.
Attributes:
question_urlsafe_key: str, The urlsafe ndb.Key for a
survey_models.Survey instace.
selected_answer: Answer, The answer a user selected.
more_info_text: str, the extra info optionally provided for the given
Answer. | 625990797b180e01f3e49d46 |
class UsageRule(_messages.Message): <NEW_LINE> <INDENT> allowUnregisteredCalls = _messages.BooleanField(1) <NEW_LINE> selector = _messages.StringField(2) <NEW_LINE> skipServiceControl = _messages.BooleanField(3) | Usage configuration rules for the service. NOTE: Under development.
Use this rule to configure unregistered calls for the service.
Unregistered calls are calls that do not contain consumer project
identity. (Example: calls that do not contain an API key). By default, API
methods do not allow unregistered calls, and each method call must be
identified by a consumer project identity. Use this rule to allow/disallow
unregistered calls. Example of an API that wants to allow unregistered
calls for entire service. usage: rules: - selector: "*"
allow_unregistered_calls: true Example of a method that wants to allow
unregistered calls. usage: rules: - selector:
"google.example.library.v1.LibraryService.CreateBook"
allow_unregistered_calls: true
Fields:
allowUnregisteredCalls: True, if the method allows unregistered calls;
false otherwise.
selector: Selects the methods to which this rule applies. Use '*' to
indicate all methods in all APIs. Refer to selector for syntax
details.
skipServiceControl: True, if the method should skip service control. If
so, no control plane feature (like quota and billing) will be enabled. | 625990795fdd1c0f98e5f940 |
class DisplayMessage(Message): <NEW_LINE> <INDENT> def __init__(self, sender_icon, sender_id, t, message_type, text, img_path=None): <NEW_LINE> <INDENT> super(DisplayMessage, self).__init__(sender_icon, sender_id, None, t, message_type) <NEW_LINE> self.text = text <NEW_LINE> self.img_path = img_path | Class for text that will be displayed in messagesLW.
Also store this in Chat.history_message
Member Variables:
text: str content of the message
img_path: if self is for displaying ImageMessage,
then we should display the image in messagesLW. | 6259907991f36d47f2231b70 |
class JSONLDSerializer(JSONSerializer): <NEW_LINE> <INDENT> def __init__(self, context, schema_class=RecordMetadataOnlySchema, expanded=True, replace_refs=False): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self._expanded = expanded <NEW_LINE> super(JSONLDSerializer, self).__init__( schema_class=schema_class, replace_refs=replace_refs ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def expanded(self): <NEW_LINE> <INDENT> if request: <NEW_LINE> <INDENT> if 'expanded' in request.args: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif 'compacted' in request.args: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return self._expanded <NEW_LINE> <DEDENT> def dump(self, obj): <NEW_LINE> <INDENT> rec = copy.deepcopy(super(JSONLDSerializer, self).dump(obj)) <NEW_LINE> rec.update(self.context) <NEW_LINE> compacted = jsonld.compact(rec, self.context) <NEW_LINE> if not self.expanded: <NEW_LINE> <INDENT> return compacted <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return jsonld.expand(compacted)[0] | JSON-LD serializer for records.
Note: This serializer is not suitable for serializing large number of
records. | 62599079d486a94d0ba2d97a |
class ReleaseLog(Base): <NEW_LINE> <INDENT> __tablename__='releaselog' <NEW_LINE> id=Column(Integer,primary_key=True,index=True,nullable=False) <NEW_LINE> logdatetime=Column(DateTime(),index=True,nullable=False) <NEW_LINE> release_id=Column(Integer,ForeignKey('release.id'),index=True,nullable=False) <NEW_LINE> release=relationship('Release',backref='releaselog' ) | 发布日志表 | 6259907901c39578d7f14416 |
class Conv2dWithNorm(nn.Conv2d): <NEW_LINE> <INDENT> def __init__(self, *args, **kargs): <NEW_LINE> <INDENT> norm = kargs.pop('norm', None) <NEW_LINE> super().__init__(*args, **kargs) <NEW_LINE> self.norm = norm <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> h = super().forward(x) <NEW_LINE> if self.norm is not None: <NEW_LINE> <INDENT> h = self.norm(h) <NEW_LINE> <DEDENT> return h | Conv2d module that also applies given normalization module. | 625990793317a56b869bf227 |
class ConnectionBase: <NEW_LINE> <INDENT> def connect(self,host,port): <NEW_LINE> <INDENT> raise NotImplementedError("Not implemented by subclass") <NEW_LINE> <DEDENT> def handleSocket(self): <NEW_LINE> <INDENT> raise NotImplementedError("Not implemented by subclass") <NEW_LINE> <DEDENT> def prepareHeaders(self,request): <NEW_LINE> <INDENT> raise NotImplementedError("not implemented by subclass") <NEW_LINE> <DEDENT> def handleResponseHeaders(self,response): <NEW_LINE> <INDENT> raise NotImplementedError("not implemented by subclass") <NEW_LINE> <DEDENT> def sendRequest(self,req,method="POST"): <NEW_LINE> <INDENT> req = self.prepareHeaders(req) <NEW_LINE> self.conn.request(method, "/copernicus",req.msg,req.headers) <NEW_LINE> response=self.conn.getresponse() <NEW_LINE> if response.status!=200: <NEW_LINE> <INDENT> errorStr = "ERROR: %d: %s"%(response.status, response.reason) <NEW_LINE> resp_mmap = mmap.mmap(-1, int(len(errorStr)), mmap.ACCESS_WRITE) <NEW_LINE> resp_mmap.write(errorStr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.handleResponseHeaders(response) <NEW_LINE> headers=response.getheaders() <NEW_LINE> for (key,val) in headers: <NEW_LINE> <INDENT> log.log(cpc.util.log.TRACE,"Got header '%s'='%s'"%(key,val)) <NEW_LINE> <DEDENT> length=response.getheader('content-length', None) <NEW_LINE> if length is None: <NEW_LINE> <INDENT> length=response.getheader('Content-Length', None) <NEW_LINE> <DEDENT> if length is None: <NEW_LINE> <INDENT> raise ClientError("response has no length") <NEW_LINE> <DEDENT> log.log(cpc.util.log.TRACE,"Response length is %s"%(length)) <NEW_LINE> if int(length) == 0: <NEW_LINE> <INDENT> length = 1 <NEW_LINE> <DEDENT> resp_mmap = mmap.mmap(-1, int(length), access=mmap.ACCESS_WRITE) <NEW_LINE> resp_mmap.write(response.read(length)) <NEW_LINE> <DEDENT> resp_mmap.seek(0) <NEW_LINE> headerTuples = response.getheaders() <NEW_LINE> headers = dict() <NEW_LINE> for (header,value) in headerTuples: <NEW_LINE> <INDENT> headers[header] = value <NEW_LINE> <DEDENT> self.handleSocket() <NEW_LINE> return ClientResponse(resp_mmap,headers) | Abstract class
Responsible for sending a request and receiving a response | 625990794c3428357761bc7b |
class TestV1EnvFromSource(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 testV1EnvFromSource(self): <NEW_LINE> <INDENT> pass | V1EnvFromSource unit test stubs | 625990793539df3088ecdc5b |
class Account: <NEW_LINE> <INDENT> def __init__(self, name, balance): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.balance = balance <NEW_LINE> print('Thank you' + self.name) <NEW_LINE> <DEDENT> def deposit(self, amount): <NEW_LINE> <INDENT> if self.balance > 0: <NEW_LINE> <INDENT> self.balance += amount <NEW_LINE> print(self.balance) <NEW_LINE> <DEDENT> <DEDENT> def withdraw(self, amount): <NEW_LINE> <INDENT> if amount <= self.balance: <NEW_LINE> <INDENT> self.balance -= amount <NEW_LINE> print(self.balance) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Withdraw cash that is less or equal to the money in your bank account') <NEW_LINE> <DEDENT> <DEDENT> def check_balance(self): <NEW_LINE> <INDENT> print('your balance is {}'.format(self.balance)) | create a simple bank account that you can withdraw and check balance | 625990793346ee7daa338342 |
class RedisTemporaryInstance(EduidTemporaryInstance): <NEW_LINE> <INDENT> @property <NEW_LINE> def command(self) -> Sequence[str]: <NEW_LINE> <INDENT> return [ 'docker', 'run', '--rm', '-p', '{!s}:6379'.format(self.port), '-v', '{!s}:/data'.format(self.tmpdir), '-e', 'extra_args=--daemonize no --bind 0.0.0.0', 'docker.sunet.se/eduid/redis:latest', ] <NEW_LINE> <DEDENT> def setup_conn(self) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> host, port, db = self.get_params() <NEW_LINE> _conn = redis.Redis(host, port, db) <NEW_LINE> _conn.set('dummy', 'dummy') <NEW_LINE> self._conn = _conn <NEW_LINE> <DEDENT> except redis.exceptions.ConnectionError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def conn(self) -> redis.Redis: <NEW_LINE> <INDENT> if self._conn is None: <NEW_LINE> <INDENT> raise RuntimeError('Missing temporary Redis instance') <NEW_LINE> <DEDENT> return self._conn <NEW_LINE> <DEDENT> def get_params(self): <NEW_LINE> <INDENT> return 'localhost', self.port, 0 | Singleton to manage a temporary Redis instance
Use this for testing purpose only. The instance is automatically destroyed
at the end of the program. | 62599079dc8b845886d54f7e |
class TestState(unittest.TestCase): <NEW_LINE> <INDENT> def test_can_create(self): <NEW_LINE> <INDENT> self.assertIsNotNone(State("")) <NEW_LINE> self.assertIsNotNone(State(1)) <NEW_LINE> <DEDENT> def test_repr(self): <NEW_LINE> <INDENT> state1 = State("ABC") <NEW_LINE> self.assertEqual(str(state1), "ABC") <NEW_LINE> state2 = State(1) <NEW_LINE> self.assertEqual(str(state2), "1") <NEW_LINE> <DEDENT> def test_eq(self): <NEW_LINE> <INDENT> state1 = State("ABC") <NEW_LINE> state2 = State(1) <NEW_LINE> state3 = State("ABC") <NEW_LINE> self.assertEqual(state1, state3) <NEW_LINE> self.assertTrue(state2 == 1) <NEW_LINE> self.assertNotEqual(state2, state3) <NEW_LINE> self.assertEqual(state2, 1) <NEW_LINE> self.assertNotEqual(state1, state2) <NEW_LINE> <DEDENT> def test_hash(self): <NEW_LINE> <INDENT> state1 = hash(State("ABC")) <NEW_LINE> state2 = hash(State(1)) <NEW_LINE> state3 = hash(State("ABC")) <NEW_LINE> self.assertIsInstance(state1, int) <NEW_LINE> self.assertEqual(state1, state3) <NEW_LINE> self.assertNotEqual(state2, state3) <NEW_LINE> self.assertNotEqual(state1, state2) | Test the states
| 62599079283ffb24f3cf5265 |
class Command(BaseCommand): <NEW_LINE> <INDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> sites = FederalSite.objects.filter(slug__isnull=True) <NEW_LINE> slug = '' <NEW_LINE> for site in sites: <NEW_LINE> <INDENT> print(site.name) <NEW_LINE> if site.site_type == 'NPS': <NEW_LINE> <INDENT> slug = nps_slug(site.website) <NEW_LINE> <DEDENT> elif site.site_type == 'NF': <NEW_LINE> <INDENT> slug = nf_slug(site.name) <NEW_LINE> <DEDENT> elif site.site_type == 'NWR': <NEW_LINE> <INDENT> slug = nwr_slug(site.name) <NEW_LINE> <DEDENT> elif site.site_type == 'BLM': <NEW_LINE> <INDENT> slug = blm_slug(site.name) <NEW_LINE> <DEDENT> elif site.site_type == 'NRA': <NEW_LINE> <INDENT> slug = nra_slug(site.name) <NEW_LINE> <DEDENT> elif site.site_type == 'OTH': <NEW_LINE> <INDENT> slug = oth_slug(site.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slug = other_slug(site.name) <NEW_LINE> <DEDENT> site.slug = slug <NEW_LINE> print(slug) <NEW_LINE> print(site.site_type) <NEW_LINE> try: <NEW_LINE> <INDENT> site.save() <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> slug = slugify("%s %s" % (slug, site.city)) <NEW_LINE> site.slug = slug <NEW_LINE> try: <NEW_LINE> <INDENT> site.save() <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> if site.site_type == 'NPS': <NEW_LINE> <INDENT> slug = nps_name_slug(site.name) <NEW_LINE> site.slug = slug <NEW_LINE> site.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise | Assign a slug to each FederalSite in the database. | 62599079a17c0f6771d5d890 |
@python_2_unicode_compatible <NEW_LINE> class ContentItemOutput(SafeData): <NEW_LINE> <INDENT> def __init__(self, html, media=None, cacheable=True, cache_timeout=DEFAULT_TIMEOUT): <NEW_LINE> <INDENT> self.html = conditional_escape(html) <NEW_LINE> self.media = media or ImmutableMedia.empty_instance <NEW_LINE> self.cacheable = cacheable <NEW_LINE> self.cache_timeout = cache_timeout or DEFAULT_TIMEOUT <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.html) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(str(self.html)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<PluginOutput '{0}'>".format(repr(self.html)) <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> return getattr(self.html, item) <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return str(self).__getitem__(item) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return (str(self.html), self.media._css, self.media._js) <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> html_str, css, js = state <NEW_LINE> self.html = mark_safe(html_str) <NEW_LINE> self.cacheable = True <NEW_LINE> self.cache_timeout = DEFAULT_TIMEOUT <NEW_LINE> if not css and not js: <NEW_LINE> <INDENT> self.media = ImmutableMedia.empty_instance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.media = ImmutableMedia() <NEW_LINE> self.media._css = css <NEW_LINE> self.media._js = js <NEW_LINE> <DEDENT> <DEDENT> def _insert_media(self, media): <NEW_LINE> <INDENT> if self.media is ImmutableMedia.empty_instance: <NEW_LINE> <INDENT> self.media = Media() + media <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.media = media + self.media | A wrapper with holds the rendered output of a plugin,
This object is returned by the :func:`~fluent_contents.rendering.render_placeholder`
and :func:`ContentPlugin.render() <fluent_contents.extensions.ContentPlugin.render>` method.
Instances can be treated like a string object,
but also allows reading the :attr:`html` and :attr:`media` attributes. | 625990797c178a314d78e8cd |
class PurchaseFilter(django_filters.FilterSet): <NEW_LINE> <INDENT> number_purchase = CharFilter( field_name='number_purchase', lookup_expr='exact', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Número interno'}), ) <NEW_LINE> invoice_num = CharFilter( field_name='invoice_num', lookup_expr='exact', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Número factura'}), ) <NEW_LINE> start_date = DateFilter( label='Fecha de compra desde', field_name='date_purchase', lookup_expr='gte', widget=forms.DateInput( attrs={'class': 'form-control', 'type': 'date'}), ) <NEW_LINE> end_date = DateFilter( label='Fecha de compra hasta', field_name='date_purchase', lookup_expr='lte', widget=forms.DateInput( attrs={'class': 'form-control', 'type': 'date'}), ) <NEW_LINE> supplier = CharFilter( label='Proveedor', field_name='supplier__last_name', lookup_expr='icontains', widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Proveedor'}), ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Purchase <NEW_LINE> fields = ('number_purchase', 'invoice_num', 'start_date', 'end_date', 'is_fiscal') <NEW_LINE> localized_fields = ('date_purchase',) | Purchase filter. | 625990798a349b6b43687c1f |
class RandomSelectionStrategy(SelectionStrategy): <NEW_LINE> <INDENT> def select_round_workers(self, workers, poisoned_workers, kwargs): <NEW_LINE> <INDENT> return random.sample(workers, kwargs["NUM_WORKERS_PER_ROUND"]) | Randomly selects workers out of the list of all workers | 6259907999cbb53fe68328aa |
class memoize(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> <DEDENT> def __get__(self, obj, objtype=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self.func <NEW_LINE> <DEDENT> return partial(self, obj) <NEW_LINE> <DEDENT> def __call__(self, *args, **kw): <NEW_LINE> <INDENT> obj = args[0] <NEW_LINE> try: <NEW_LINE> <INDENT> cache = obj.__cache <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> cache = obj.__cache = {} <NEW_LINE> <DEDENT> key = (self.func, args[1:], frozenset(kw.items())) <NEW_LINE> try: <NEW_LINE> <INDENT> res = cache[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> res = cache[key] = self.func(*args, **kw) <NEW_LINE> <DEDENT> return res | cache the return value of a method
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method:
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached | 62599079ad47b63b2c5a9213 |
class XYPlotLine(Line): <NEW_LINE> <INDENT> def __init__(self, name, **args): <NEW_LINE> <INDENT> Line.__init__(self, name, **args) <NEW_LINE> self.add( setting.Choice('steps', ['off', 'left', 'centre', 'right'], 'off', descr='Plot horizontal steps ' 'instead of a line', usertext='Steps'), 0 ) <NEW_LINE> self.add( setting.Bool('bezierJoin', False, descr='Connect points with a cubic Bezier curve', usertext='Bezier join'), 1 ) | A plot line for plotting data, allowing histogram-steps
to be plotted. | 625990795fc7496912d48f4c |
class MultipleFile(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> managed = False | Dummy model to enable us of having an admin options in the
Files section to add multiple files | 62599079a8370b77170f1d92 |
class ModifyVpcEndPointAttributeResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId") | ModifyVpcEndPointAttribute返回参数结构体
| 62599079bf627c535bcb2e93 |
class IotHubNameAvailabilityInfo(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name_available': {'readonly': True}, 'reason': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, 'reason': {'key': 'reason', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, message: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(IotHubNameAvailabilityInfo, self).__init__(**kwargs) <NEW_LINE> self.name_available = None <NEW_LINE> self.reason = None <NEW_LINE> self.message = message | The properties indicating whether a given IoT hub name is available.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name_available: The value which indicates whether the provided name is available.
:vartype name_available: bool
:ivar reason: The reason for unavailability. Possible values include: "Invalid",
"AlreadyExists".
:vartype reason: str or
~azure.mgmt.iothub.v2021_03_03_preview.models.IotHubNameUnavailabilityReason
:ivar message: The detailed reason message.
:vartype message: str | 6259907916aa5153ce401e9e |
class OperatorAssignmentStmt(Node): <NEW_LINE> <INDENT> op = '' <NEW_LINE> lvalue = None <NEW_LINE> rvalue = None <NEW_LINE> def __init__(self, op: str, lvalue: Node, rvalue: Node) -> None: <NEW_LINE> <INDENT> self.op = op <NEW_LINE> self.lvalue = lvalue <NEW_LINE> self.rvalue = rvalue <NEW_LINE> <DEDENT> def accept(self, visitor: NodeVisitor[T]) -> T: <NEW_LINE> <INDENT> return visitor.visit_operator_assignment_stmt(self) | Operator assignment statement such as x += 1 | 62599079442bda511e95da3a |
class SELayer2d(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_features: int, reduction: int = 16) -> None: <NEW_LINE> <INDENT> super(SELayer2d, self).__init__() <NEW_LINE> reduction_size = max(1, in_features // reduction) <NEW_LINE> self.avg_pool = nn.AdaptiveAvgPool2d(1) <NEW_LINE> self.fc = nn.Sequential( nn.Linear(in_features, reduction_size, bias=False), nn.ReLU(inplace=True), nn.Linear(reduction_size, in_features, bias=False), nn.Sigmoid(), ) <NEW_LINE> <DEDENT> def forward(self, x: Tensor) -> Tensor: <NEW_LINE> <INDENT> b, c, _, _ = x.shape <NEW_LINE> y = self.avg_pool(x).view(b, c) <NEW_LINE> y = self.fc(y).view(b, c, 1, 1) <NEW_LINE> scaling = x * y.expand_as(x) <NEW_LINE> return scaling | Squeeze and Excitation block for image data.
Paper: `Squeeze-and-Excitation Networks <https://arxiv.org/abs/1709.01507>`_ | 625990791b99ca4002290218 |
class Rule(object): <NEW_LINE> <INDENT> def __init__(self, name=None, ts=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.ts = [] <NEW_LINE> if ts is not None: <NEW_LINE> <INDENT> if type(ts) is list: <NEW_LINE> <INDENT> self.ts.extend(ts) <NEW_LINE> idx = 0 <NEW_LINE> for t in self.ts: <NEW_LINE> <INDENT> t.setRule(self, idx) <NEW_LINE> idx += 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.ts = [ts] <NEW_LINE> ts.setRule(self, 0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> mystr = "Rule-Name: " <NEW_LINE> if self.name: <NEW_LINE> <INDENT> mystr += self.name + "\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mystr += "None\n" <NEW_LINE> <DEDENT> for t in self.ts: <NEW_LINE> <INDENT> mystr += str(t) <NEW_LINE> <DEDENT> return mystr <NEW_LINE> <DEDENT> def addTS(self, stream=None): <NEW_LINE> <INDENT> if stream: <NEW_LINE> <INDENT> self.ts.append(stream) <NEW_LINE> stream.setRule(self, len(self.ts) - 1) <NEW_LINE> <DEDENT> <DEDENT> def getRuleName(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def getTS(self): <NEW_LINE> <INDENT> return self.ts <NEW_LINE> <DEDENT> def setRuleName(self, name): <NEW_LINE> <INDENT> self.name = name | The Rule class marks the base class for any rule.
If a rule is to have added features, then this class must
be extended. Currently, the rule traffic generator depends
heavily on this class for generating content. The rule
is the cornerstone of generation. It acts as the ultimate
keeper of all the defined traffic streams. Further, each
TrafficStreamRule may be set to synchronize which means
that other TrafficStreamRules will not take affect unitl
after the TrafficStreamRule set to synchronize (and any
before it) are finished.
The primary API:
addTS(TrafficStreamRule ts): This function adds a new
TrafficStreamRule instance to this particular rule.
A particular rule may have an arbitrary number of
TrafficStreamRules attached to it.
getRuleName(): Return the name for this rule. Usually just
a string signifying the type of rule like: Snor Rule.
getTS(): get a list of the TrafficStreamRules for this
Rule intance.
setRuleName(name): self-explanatory | 6259907901c39578d7f14417 |
class BilinearInterpolation: <NEW_LINE> <INDENT> def __init__(self,a,xgrid=None,ygrid=None): <NEW_LINE> <INDENT> raise AssertionError('Use the same function from helper-module, not box; this function is somehow broken.') <NEW_LINE> self.a=a <NEW_LINE> self.nx=a.shape[0] <NEW_LINE> self.ny=a.shape[1] <NEW_LINE> self.xgrid=xgrid <NEW_LINE> self.ygrid=ygrid <NEW_LINE> if self.xgrid==None: <NEW_LINE> <INDENT> self.xgrid=np.arange(self.nx) <NEW_LINE> <DEDENT> if self.ygrid==None: <NEW_LINE> <INDENT> self.ygrid=np.arange(self.ny) <NEW_LINE> <DEDENT> self.dx=self.xgrid[1]-self.xgrid[0] <NEW_LINE> self.dy=self.ygrid[1]-self.ygrid[0] <NEW_LINE> <DEDENT> def __call__(self,x,y): <NEW_LINE> <INDENT> assert self.xgrid[0]<=x<=self.xgrid[-1] <NEW_LINE> assert self.ygrid[0]<=y<=self.ygrid[-1] <NEW_LINE> i,j=(np.floor(x/self.dx),np.floor(y/self.dx)) <NEW_LINE> i,j=(min(i,self.nx-2),min(j,self.ny-2)) <NEW_LINE> dx,dy=((x%self.dx)/self.dx,(y%self.dy)/self.dy) <NEW_LINE> raise NotImplementedError('Check that dx=0...1 and not something else.') <NEW_LINE> a=self.a <NEW_LINE> return a[i,j] *(1-dx)*(1-dy)+a[i+1,j]*dx*(1-dy)+ a[i,j+1]*(1-dx)*dy +a[i+1,j+1]*dx*dy <NEW_LINE> <DEDENT> def plot(self,nx=100,ny=100,out='screen'): <NEW_LINE> <INDENT> b=np.empty((nx,ny)) <NEW_LINE> X=np.linspace(self.xgrid[0],self.xgrid[1],nx) <NEW_LINE> Y=np.linspace(self.ygrid[0],self.ygrid[1],ny) <NEW_LINE> for i,x in enumerate(X): <NEW_LINE> <INDENT> for j,y in enumerate(Y): <NEW_LINE> <INDENT> b[i,j]=self(x,y) <NEW_LINE> <DEDENT> <DEDENT> pl.contourf(b,100) <NEW_LINE> pl.hot() <NEW_LINE> pl.colorbar() <NEW_LINE> if out=='screen': <NEW_LINE> <INDENT> pl.show() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pl.savefig('linter.png') | Perform bilinear interpolation for 2D (xy)-data
For bilinear interpolation, see e.g. Wikipedia. | 6259907992d797404e38983e |
class ExaileMpris(object): <NEW_LINE> <INDENT> def __init__(self, exaile=None): <NEW_LINE> <INDENT> self.exaile = exaile <NEW_LINE> self.mpris_root = None <NEW_LINE> self.mpris_tracklist = None <NEW_LINE> self.mpris_player = None <NEW_LINE> self.bus = None <NEW_LINE> <DEDENT> def release(self): <NEW_LINE> <INDENT> for obj in (self.mpris_root, self.mpris_tracklist, self.mpris_player): <NEW_LINE> <INDENT> if obj is not None: <NEW_LINE> <INDENT> obj.remove_from_connection() <NEW_LINE> <DEDENT> <DEDENT> self.mpris_root = None <NEW_LINE> self.mpris_tracklist = None <NEW_LINE> self.mpris_player = None <NEW_LINE> if self.bus is not None: <NEW_LINE> <INDENT> self.bus.get_bus().release_name(self.bus.get_name()) <NEW_LINE> <DEDENT> <DEDENT> def acquire(self): <NEW_LINE> <INDENT> self._acquire_bus() <NEW_LINE> self._add_interfaces() <NEW_LINE> <DEDENT> def _acquire_bus(self): <NEW_LINE> <INDENT> if self.bus is not None: <NEW_LINE> <INDENT> self.bus.get_bus().request_name(OBJECT_NAME) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bus = dbus.service.BusName(OBJECT_NAME, bus=dbus.SessionBus()) <NEW_LINE> <DEDENT> <DEDENT> def _add_interfaces(self): <NEW_LINE> <INDENT> self.mpris_root = mpris_root.ExaileMprisRoot(self.exaile, self.bus) <NEW_LINE> self.mpris_tracklist = mpris_tracklist.ExaileMprisTrackList( self.exaile, self.bus) <NEW_LINE> self.mpris_player = mpris_player.ExaileMprisPlayer( self.exaile, self.bus) | Controller for various MPRIS objects. | 625990793539df3088ecdc5d |
class AsynchronousSuccessTests(SuccessMixin, unittest.TestCase): <NEW_LINE> <INDENT> pass | Tests for the reporting of successful tests in the synchronous case. | 62599079dc8b845886d54f80 |
class Aggregate(object): <NEW_LINE> <INDENT> def __init__(self, elem, strict=True): <NEW_LINE> <INDENT> assert strict in (True, False) <NEW_LINE> self.strict = strict <NEW_LINE> assert elem.tag == self.__class__.__name__ <NEW_LINE> attributes = elem._flatten() <NEW_LINE> for name, element in self.elements.items(): <NEW_LINE> <INDENT> value = attributes.pop(name, None) <NEW_LINE> if element.required and value is None: <NEW_LINE> <INDENT> raise ValueError("'%s' attribute is required for %s" % (name, self.__class__.__name__)) <NEW_LINE> <DEDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> if attributes: <NEW_LINE> <INDENT> raise ValueError("Undefined element(s) for '%s': %s" % (self.__class__.__name__, attributes.keys())) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def elements(self): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for m in self.__class__.__mro__: <NEW_LINE> <INDENT> d.update({k: v for k,v in m.__dict__.items() if isinstance(v, Element)}) <NEW_LINE> <DEDENT> return d <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_etree(elem, strict=True): <NEW_LINE> <INDENT> SubClass = globals()[elem.tag] <NEW_LINE> instance = SubClass(elem, strict=strict) <NEW_LINE> return instance <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s %s>' % (self.__class__.__name__, ' '.join(['%s=%r' % (attr, str(getattr(self, attr))) for attr in self.elements.viewkeys() if getattr(self, attr) is not None])) | Base class for Python representation of OFX 'aggregate', i.e. SGML parent
node that contains no data.
Initialize with an instance of ofx.Parser.Element.
This class represents fundamental data aggregates such as transactions,
balances, and securities. Subaggregates have been flattened so that
data-bearing Elements are directly accessed as attributes of the
containing Aggregate.
Aggregates are grouped into higher-order containers such as lists
and statements. Although such higher-order containers are 'aggregates'
per the OFX specification, they are represented here by their own Python
classes other than Aggregate. | 6259907963b5f9789fe86b2c |
class SonosTmpSkill(MycroftSkill): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SonosTmpSkill, self).__init__(name="SonosTmpSkill") <NEW_LINE> self.zone_list = list(soco.discover()) <NEW_LINE> LOG.info("Sonos devices found: ") <NEW_LINE> LOG.info(self.zone_list) <NEW_LINE> <DEDENT> @intent_handler_intent(IntentBuilder("PlaySonos").require("Play").require("Sonos")) <NEW_LINE> def handle_play_sonos(self, message): <NEW_LINE> <INDENT> LOG.debug("Starting play sonos action.") <NEW_LINE> self.zone_list[0].play() <NEW_LINE> self.speak_dialog('play.sonos') <NEW_LINE> <DEDENT> @intent_handler(IntentBuilder("PauseSonos").require("Pause").require("Sonos")) <NEW_LINE> def handle_pause_sonos(self, message): <NEW_LINE> <INDENT> LOG.debug("Starting pause sonos action.") <NEW_LINE> self.zone_list[0].pause() <NEW_LINE> self.speak_dialog('pause.sonos') | Control Sonos speaker devices
Use play/pause to control sonos device. | 62599079f9cc0f698b1c5faf |
class SearchAll(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Zendesk/Search/SearchAll') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return SearchAllInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return SearchAllResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return SearchAllChoreographyExecution(session, exec_id, path) | Create a new instance of the SearchAll Choreography. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 62599079aad79263cf43017f |
class UrlDeleteView(DeleteView): <NEW_LINE> <INDENT> model = Url <NEW_LINE> template_name = 'pages/url_delete.html' <NEW_LINE> success_url = reverse_lazy('home') <NEW_LINE> success_message = "Url successfully deleted !" <NEW_LINE> def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super().delete(request, *args, **kwargs) | docstring for UrlDeleteView | 62599079be8e80087fbc0a5b |
class ScoreLessonListView(LoginRequiredMixin, TeacherLessonPermissionsMixin, ScoreJournalMixin, ListView): <NEW_LINE> <INDENT> template_name = 'journal/journal_lesson_list.html' <NEW_LINE> context_object_name = 'scores' <NEW_LINE> permission_denied_message = 'В доступе отказанно' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> group_student = GroupStudent.objects.select_related('grade') <NEW_LINE> self.group = get_object_or_404(group_student, id=self.kwargs['group_id']) <NEW_LINE> self.lesson = get_object_or_404(Lesson, id=self.kwargs['lesson_id']) <NEW_LINE> queryset = Score.objects.select_related('group', 'lesson') .filter(group_id=self.kwargs['group_id'], lesson_id=self.kwargs['lesson_id']) <NEW_LINE> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, *, object_list=None, **kwargs): <NEW_LINE> <INDENT> context = super(ScoreLessonListView, self).get_context_data(**kwargs) <NEW_LINE> date_period = self.create_date_period_list() <NEW_LINE> students = User.objects.select_related('student', 'student__group').filter(student__group=self.group) <NEW_LINE> scores = Score.objects.select_related('group', 'lesson') .filter(created__in=date_period, lesson_id=self.lesson, group_id=self.group) <NEW_LINE> context['date_period'] = date_period <NEW_LINE> context['students'] = students <NEW_LINE> context['scores_dict'] = self.create_scores_dict(date_period, scores.values('id', 'student', 'score', 'created'), students, 'student') <NEW_LINE> context['group'] = self.group <NEW_LINE> context['lesson'] = self.lesson <NEW_LINE> return context | Журнал оценок класса по предмету. | 625990798a349b6b43687c21 |
class TestUpgradeBundleFetchRequest(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 testUpgradeBundleFetchRequest(self): <NEW_LINE> <INDENT> pass | UpgradeBundleFetchRequest unit test stubs | 625990792c8b7c6e89bd51b1 |
class IPKeyDimmer(GenericDimmer, HelperWorking, HelperActionPress): <NEW_LINE> <INDENT> def __init__(self, device_description, proxy, resolveparamsets=False): <NEW_LINE> <INDENT> super().__init__(device_description, proxy, resolveparamsets) <NEW_LINE> self.EVENTNODE.update({"PRESS_SHORT": [1, 2], "PRESS_LONG_RELEASE": [1, 2]}) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ELEMENT(self): <NEW_LINE> <INDENT> return [4] | IP Dimmer switch that controls level of light brightness. | 62599079bf627c535bcb2e95 |
class ExportVideoByEditorTrackDataRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Platform = None <NEW_LINE> self.Definition = None <NEW_LINE> self.ExportDestination = None <NEW_LINE> self.TrackData = None <NEW_LINE> self.AspectRatio = None <NEW_LINE> self.CoverData = None <NEW_LINE> self.CMEExportInfo = None <NEW_LINE> self.VODExportInfo = None <NEW_LINE> self.Operator = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Platform = params.get("Platform") <NEW_LINE> self.Definition = params.get("Definition") <NEW_LINE> self.ExportDestination = params.get("ExportDestination") <NEW_LINE> self.TrackData = params.get("TrackData") <NEW_LINE> self.AspectRatio = params.get("AspectRatio") <NEW_LINE> self.CoverData = params.get("CoverData") <NEW_LINE> if params.get("CMEExportInfo") is not None: <NEW_LINE> <INDENT> self.CMEExportInfo = CMEExportInfo() <NEW_LINE> self.CMEExportInfo._deserialize(params.get("CMEExportInfo")) <NEW_LINE> <DEDENT> if params.get("VODExportInfo") is not None: <NEW_LINE> <INDENT> self.VODExportInfo = VODExportInfo() <NEW_LINE> self.VODExportInfo._deserialize(params.get("VODExportInfo")) <NEW_LINE> <DEDENT> self.Operator = params.get("Operator") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | ExportVideoByEditorTrackData请求参数结构体
| 625990793d592f4c4edbc841 |
class EventType(models.Model): <NEW_LINE> <INDENT> name = models.CharField(_('name'), db_index=True, unique=True, max_length=500) <NEW_LINE> description = models.CharField(_('description'), max_length=5000, null=True, blank=True) <NEW_LINE> last_update = models.DateTimeField(_('last update'), auto_now=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | A type of system event, to be logged | 625990797047854f46340d81 |
class SchemeHomsetFactory(UniqueFactory): <NEW_LINE> <INDENT> def create_key_and_extra_args(self, X, Y, category=None, base=ZZ, check=True, as_point_homset=False): <NEW_LINE> <INDENT> if is_CommutativeRing(X): <NEW_LINE> <INDENT> X = AffineScheme(X) <NEW_LINE> <DEDENT> if is_CommutativeRing(Y): <NEW_LINE> <INDENT> Y = AffineScheme(Y) <NEW_LINE> <DEDENT> if is_AffineScheme(base): <NEW_LINE> <INDENT> base_spec = base <NEW_LINE> base_ring = base.coordinate_ring() <NEW_LINE> <DEDENT> elif is_CommutativeRing(base): <NEW_LINE> <INDENT> base_spec = AffineScheme(base) <NEW_LINE> base_ring = base <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('base must be a commutative ring or its spectrum') <NEW_LINE> <DEDENT> if not category: <NEW_LINE> <INDENT> from sage.categories.schemes import Schemes <NEW_LINE> category = Schemes(base_spec) <NEW_LINE> <DEDENT> key = tuple([id(X), id(Y), category, as_point_homset]) <NEW_LINE> extra = {'X':X, 'Y':Y, 'base_ring':base_ring, 'check':check} <NEW_LINE> return key, extra <NEW_LINE> <DEDENT> def create_object(self, version, key, **extra_args): <NEW_LINE> <INDENT> category = key[2] <NEW_LINE> X = extra_args.pop('X') <NEW_LINE> Y = extra_args.pop('Y') <NEW_LINE> base_ring = extra_args.pop('base_ring') <NEW_LINE> if len(key) >= 4 and key[3]: <NEW_LINE> <INDENT> return Y._point_homset(X, Y, category=category, base=base_ring, **extra_args) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return X._homset(X, Y, category=category, base=base_ring, **extra_args) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return SchemeHomset_generic(X, Y, category=category, base=base_ring, **extra_args) | Factory for Hom-sets of schemes.
EXAMPLES::
sage: A2 = AffineSpace(QQ,2)
sage: A3 = AffineSpace(QQ,3)
sage: Hom = A3.Hom(A2)
The Hom-sets are uniquely determined by domain and codomain::
sage: Hom is copy(Hom)
True
sage: Hom is A3.Hom(A2)
True
Here is a tricky point. The Hom-sets are not identical if
domains/codomains are isomorphic but not identiacal. Affine spaces are not
unique, and hence, when pickling and unpickling the homset together with
domain and codomain, we obtain non-unique behaviour::
sage: loads(Hom.dumps()) is Hom
False
sage: loads(Hom.dumps()) == Hom
True
sage: A3_iso = AffineSpace(QQ,3)
sage: [ A3_iso is A3, A3_iso == A3 ]
[False, True]
sage: Hom_iso = A3_iso.Hom(A2)
sage: Hom_iso is Hom
False
sage: Hom_iso == Hom
True
TESTS::
sage: Hom.base()
Integer Ring
sage: Hom.base_ring()
Integer Ring | 625990793539df3088ecdc5e |
@attr.s(**config) <NEW_LINE> class UUID(Metadata): <NEW_LINE> <INDENT> value: uuid.UUID = attr.ib(converter=_uuid_convert, metadata={"jsonschema": { "type": "string", "format": "uuid", }}) | A 128-bit number used to identify information, also referred to as a GUID.
e.g.
UUID("654e5cff-817c-4e3d-8b01-47a6f45ae09a") | 625990797d43ff24874280f8 |
class VkMessApp(QtWidgets.QWidget, gui.Ui_VkMessenger): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.setupUi(self) <NEW_LINE> self.btn_start.clicked.connect(self.start_scan) <NEW_LINE> self.btn_stop.clicked.connect(self.stop_scan) <NEW_LINE> self.thread = msg_scan.MsgScan() <NEW_LINE> self.thread.started.connect(self.on_started) <NEW_LINE> self.thread.finished.connect(self.on_finished) <NEW_LINE> self.thread.result_signal.connect(self.show_result) <NEW_LINE> self.thread.success_signal.connect(self.success_alarm) <NEW_LINE> self.btn_login.clicked.connect(self.login) <NEW_LINE> <DEDENT> def start_scan(self): <NEW_LINE> <INDENT> self.thread.start() <NEW_LINE> <DEDENT> def stop_scan(self): <NEW_LINE> <INDENT> self.thread.terminate() <NEW_LINE> self.on_finished() <NEW_LINE> <DEDENT> def show_result(self, result): <NEW_LINE> <INDENT> self.log.textCursor().insertText(result) <NEW_LINE> self.log.ensureCursorVisible() <NEW_LINE> <DEDENT> def on_started(self): <NEW_LINE> <INDENT> self.btn_start.setDisabled(True) <NEW_LINE> self.btn_stop.setDisabled(False) <NEW_LINE> <DEDENT> def on_finished(self): <NEW_LINE> <INDENT> self.btn_start.setDisabled(False) <NEW_LINE> self.btn_stop.setDisabled(True) <NEW_LINE> <DEDENT> def success_alarm(self): <NEW_LINE> <INDENT> self.showNormal() <NEW_LINE> self.activateWindow() <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> credentials = self.authenticate_dialog() <NEW_LINE> self.login_thread = login.Login_Thread(credentials[0], credentials[1]) <NEW_LINE> self.login_thread.notification_string.connect( self.notification_window) <NEW_LINE> self.login_thread.start() <NEW_LINE> <DEDENT> def authenticate_dialog(self): <NEW_LINE> <INDENT> _login, ok = dialog.getText( None, 'VKMessenger Authorization', 'Type login', input_field.Normal ) <NEW_LINE> _password, ok = dialog.getText( None, 'VKMessenger Authorization', 'Type password', input_field.Password ) <NEW_LINE> return _login, _password <NEW_LINE> <DEDENT> def notification_window(self, text_arg): <NEW_LINE> <INDENT> self.display_msg = message_box() <NEW_LINE> self.display_msg.about(self, 'Notification', text_arg) | GUI и управление потоком запросов | 62599079fff4ab517ebcf1df |
class ExampleCatalogEntry(object): <NEW_LINE> <INDENT> def __init__(self, tenant_id, name, endpoint_count=2, idgen=lambda: 1): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = "compute" <NEW_LINE> self.path_prefix = "/v2/" <NEW_LINE> self.endpoints = [ExampleCatalogEndpoint(tenant_id, n + 1, idgen()) for n in range(endpoint_count)] | Example of a thing that a plugin produces at some phase of its lifecycle;
maybe you have to pass it a tenant ID to get one of these. (Services which
don't want to show up in the catalog won't produce these.) | 625990793317a56b869bf229 |
class SNMP(BaseCommand): <NEW_LINE> <INDENT> def is_enabled(self): <NEW_LINE> <INDENT> return self._gateway.get('/config/snmp/mode') == enum.Mode.Enabled <NEW_LINE> <DEDENT> def enable(self, port=161, community_str=None, username=None, password=None): <NEW_LINE> <INDENT> param = Object() <NEW_LINE> param.mode = enum.Mode.Enabled <NEW_LINE> param.port = port <NEW_LINE> param.readCommunity = community_str <NEW_LINE> if username is not None and password is not None: <NEW_LINE> <INDENT> param.snmpV3 = Object() <NEW_LINE> param.snmpV3.mode = enum.Mode.Enabled <NEW_LINE> param.snmpV3.username = username <NEW_LINE> param.snmpV3.password = password <NEW_LINE> <DEDENT> logging.getLogger().info("Enabling SNMP.") <NEW_LINE> self._gateway.put('/config/snmp', param) <NEW_LINE> logging.getLogger().info("Enabled SNMP.") <NEW_LINE> <DEDENT> def disable(self): <NEW_LINE> <INDENT> logging.getLogger().info("Disabling SNMP.") <NEW_LINE> self._gateway.put('/config/snmp/mode', enum.Mode.Disabled) <NEW_LINE> logging.getLogger().info("Disabled SNMP.") <NEW_LINE> <DEDENT> def get_configuration(self): <NEW_LINE> <INDENT> return self._gateway.get('/config/snmp') <NEW_LINE> <DEDENT> def modify(self, port=None, community_str=None, username=None, password=None): <NEW_LINE> <INDENT> current_config = self.get_configuration() <NEW_LINE> if current_config.mode == enum.Mode.Disabled: <NEW_LINE> <INDENT> raise CTERAException("SNMP configuration cannot be modified when disabled") <NEW_LINE> <DEDENT> if port: <NEW_LINE> <INDENT> current_config.port = port <NEW_LINE> <DEDENT> if community_str: <NEW_LINE> <INDENT> current_config.readCommunity = community_str <NEW_LINE> <DEDENT> if username is not None and password is not None: <NEW_LINE> <INDENT> current_config.snmpV3 = Object() <NEW_LINE> current_config.snmpV3.mode = enum.Mode.Enabled <NEW_LINE> current_config.snmpV3.username = username <NEW_LINE> current_config.snmpV3.password = password <NEW_LINE> <DEDENT> logging.getLogger().info("Updating SNMP configuration.") <NEW_LINE> self._gateway.put('/config/snmp', current_config) <NEW_LINE> logging.getLogger().info("SNMP configured.") | Edge Filer SNMP Configuration APIs | 62599079adb09d7d5dc0bf30 |
class UndefinedNeverFail(jinja2.Undefined): <NEW_LINE> <INDENT> __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __complex__ = __pow__ = __rpow__ = lambda *args, **kwargs: UndefinedNeverFail() <NEW_LINE> __str__ = __repr__ = lambda *args, **kwargs: u'' <NEW_LINE> __int__ = lambda _: 0 <NEW_LINE> __float__ = lambda _: 0.0 <NEW_LINE> def __getattr__(self, k): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return object.__getattr__(self, k) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return UndefinedNeverFail() <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, k, v): <NEW_LINE> <INDENT> pass | A class for Undefined jinja variables.
This is even less strict than the default jinja2.Undefined class,
because it permits things like {{ MY_UNDEFINED_VAR[:2] }} and {{ MY_UNDEFINED_VAR|int }}.
This can mask lots of errors in jinja templates, so it should only be used for a first-pass
parse, when you plan on running a 'strict' second pass later. | 625990794f88993c371f1205 |
class _PaddedFile: <NEW_LINE> <INDENT> def __init__(self, f, prepend=b''): <NEW_LINE> <INDENT> self._buffer = prepend <NEW_LINE> self._length = len(prepend) <NEW_LINE> self.file = f <NEW_LINE> self._read = 0 <NEW_LINE> <DEDENT> def read(self, size): <NEW_LINE> <INDENT> if self._read is None: <NEW_LINE> <INDENT> return self.file.read(size) <NEW_LINE> <DEDENT> if self._read + size <= self._length: <NEW_LINE> <INDENT> read = self._read <NEW_LINE> self._read += size <NEW_LINE> return self._buffer[read:self._read] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> read = self._read <NEW_LINE> self._read = None <NEW_LINE> return self._buffer[read:] + self.file.read(size-self._length+read) <NEW_LINE> <DEDENT> <DEDENT> def prepend(self, prepend=b'', readprevious=False): <NEW_LINE> <INDENT> if self._read is None: <NEW_LINE> <INDENT> self._buffer = prepend <NEW_LINE> <DEDENT> elif readprevious and len(prepend) <= self._read: <NEW_LINE> <INDENT> self._read -= len(prepend) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._buffer = self._buffer[read:] + prepend <NEW_LINE> <DEDENT> self._length = len(self._buffer) <NEW_LINE> self._read = 0 <NEW_LINE> <DEDENT> def unused(self): <NEW_LINE> <INDENT> if self._read is None: <NEW_LINE> <INDENT> return b'' <NEW_LINE> <DEDENT> return self._buffer[self._read:] <NEW_LINE> <DEDENT> def seek(self, offset, whence=0): <NEW_LINE> <INDENT> if whence == 1 and self._read is not None: <NEW_LINE> <INDENT> if 0 <= offset + self._read <= self._length: <NEW_LINE> <INDENT> self._read += offset <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> offset += self._length - self._read <NEW_LINE> <DEDENT> <DEDENT> self._read = None <NEW_LINE> self._buffer = None <NEW_LINE> return self.file.seek(offset, whence) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self.file, name) | Minimal read-only file object that prepends a string to the contents
of an actual file. Shouldn't be used outside of gzip.py, as it lacks
essential functionality. | 625990799c8ee82313040e6b |
class Temperature(Simulation): <NEW_LINE> <INDENT> def __init__(self, per_tick: float, current: float) -> None: <NEW_LINE> <INDENT> self._per_tick = per_tick <NEW_LINE> self._current = current <NEW_LINE> self._target: Optional[float] = None <NEW_LINE> <DEDENT> def tick(self) -> None: <NEW_LINE> <INDENT> if self._target is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> diff = self._target - self._current <NEW_LINE> if abs(diff) < self._per_tick: <NEW_LINE> <INDENT> self._current = self._target <NEW_LINE> <DEDENT> elif diff > 0: <NEW_LINE> <INDENT> self._current += self._per_tick <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._current -= self._per_tick <NEW_LINE> <DEDENT> <DEDENT> def deactivate(self, temperature: float) -> None: <NEW_LINE> <INDENT> self._target = None <NEW_LINE> self._current = temperature <NEW_LINE> <DEDENT> def set_target(self, target: float) -> None: <NEW_LINE> <INDENT> self._target = target <NEW_LINE> <DEDENT> @property <NEW_LINE> def current(self) -> float: <NEW_LINE> <INDENT> return self._current <NEW_LINE> <DEDENT> @property <NEW_LINE> def target(self) -> Optional[float]: <NEW_LINE> <INDENT> return self._target | A model with a current and target temperature. The current temperate is
always moving towards the target. | 6259907926068e7796d4e306 |
class PygrTestRunner(unittest.TextTestRunner): <NEW_LINE> <INDENT> def _makeResult(self): <NEW_LINE> <INDENT> return PygrTestResult(self.stream, self.descriptions, self.verbosity) | Support running tests that understand SkipTest. | 625990793d592f4c4edbc842 |
class Player(QObject): <NEW_LINE> <INDENT> def __init__(self, timeline): <NEW_LINE> <INDENT> super(Player, self).__init__() <NEW_LINE> self.timeline = timeline <NEW_LINE> self._publishing = set() <NEW_LINE> self._publishers = {} <NEW_LINE> self._publish_clock = False <NEW_LINE> <DEDENT> def is_publishing(self, topic): <NEW_LINE> <INDENT> return topic in self._publishing <NEW_LINE> <DEDENT> def start_publishing(self, topic): <NEW_LINE> <INDENT> if topic in self._publishing: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._publishing.add(topic) <NEW_LINE> self.timeline.add_listener(topic, self) <NEW_LINE> <DEDENT> def stop_publishing(self, topic): <NEW_LINE> <INDENT> if topic not in self._publishing: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.timeline.remove_listener(topic, self) <NEW_LINE> if topic in self._publishers: <NEW_LINE> <INDENT> self._publishers[topic].unregister() <NEW_LINE> del self._publishers[topic] <NEW_LINE> <DEDENT> self._publishing.remove(topic) <NEW_LINE> <DEDENT> def start_clock_publishing(self): <NEW_LINE> <INDENT> if CLOCK_TOPIC not in self._publishers: <NEW_LINE> <INDENT> self._publish_clock = self.create_publisher(CLOCK_TOPIC, rosgraph_msgs.msg.Clock()) <NEW_LINE> <DEDENT> <DEDENT> def stop_clock_publishing(self): <NEW_LINE> <INDENT> self._publish_clock = False <NEW_LINE> if CLOCK_TOPIC in self._publishers: <NEW_LINE> <INDENT> self._publishers[CLOCK_TOPIC].unregister() <NEW_LINE> del self._publishers[CLOCK_TOPIC] <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> for topic in list(self._publishing): <NEW_LINE> <INDENT> self.stop_publishing(topic) <NEW_LINE> <DEDENT> self.stop_clock_publishing() <NEW_LINE> <DEDENT> def create_publisher(self, topic, msg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._publishers[topic] = rospy.Publisher(topic, type(msg), queue_size=100) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> rospy.logerr('Error creating publisher on topic %s for type %s. \nError text: %s' % (topic, str(type(msg)), str(ex))) <NEW_LINE> if topic != CLOCK_TOPIC: <NEW_LINE> <INDENT> self.stop_publishing(topic) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def message_viewed(self, bag, msg_data): <NEW_LINE> <INDENT> if self.timeline.play_speed <= 0.0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> topic, msg, clock = msg_data <NEW_LINE> if topic not in self._publishers: <NEW_LINE> <INDENT> self.create_publisher(topic, msg) <NEW_LINE> <DEDENT> if self._publish_clock: <NEW_LINE> <INDENT> time_msg = rosgraph_msgs.msg.Clock() <NEW_LINE> time_msg.clock = clock <NEW_LINE> self._publishers[CLOCK_TOPIC].publish(time_msg) <NEW_LINE> <DEDENT> self._publishers[topic].publish(msg) <NEW_LINE> <DEDENT> def message_cleared(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def event(self, event): <NEW_LINE> <INDENT> bag, msg_data = event.data <NEW_LINE> if msg_data: <NEW_LINE> <INDENT> self.message_viewed(bag, msg_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.message_cleared() <NEW_LINE> <DEDENT> return True | This object handles publishing messages as the playhead passes over their position | 62599079091ae35668706605 |
class BrokerError(exceptions.Error): <NEW_LINE> <INDENT> pass | All errors raised by this module subclass BrokerError. | 6259907966673b3332c31dc8 |
@dataclass <NEW_LINE> class Graph: <NEW_LINE> <INDENT> nodes: Dict[str, Node] = field(default_factory=dict) <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> self._update_contained_by_relations() <NEW_LINE> <DEDENT> def _update_contained_by_relations(self): <NEW_LINE> <INDENT> for color, node in self.nodes.items(): <NEW_LINE> <INDENT> if node.contained_colors: <NEW_LINE> <INDENT> for contained_color in node.contained_colors: <NEW_LINE> <INDENT> self.nodes[contained_color].contained_by_colors.add(color) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_colors_containing_color(self, color: str) -> Set[str]: <NEW_LINE> <INDENT> node = self.nodes[color] <NEW_LINE> containing_colors = set(node.contained_by_colors) <NEW_LINE> for color in node.contained_by_colors: <NEW_LINE> <INDENT> containing_colors.update(self.get_colors_containing_color(color)) <NEW_LINE> <DEDENT> return containing_colors <NEW_LINE> <DEDENT> def get_total_bag_count_for_color(self, color: str) -> int: <NEW_LINE> <INDENT> node = self.nodes[color] <NEW_LINE> if not node.contained_colors: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> total_bags_required = node.total_contained_bags <NEW_LINE> for color, count in node.contained_colors.items(): <NEW_LINE> <INDENT> total_bags_required += self.get_total_bag_count_for_color(color) * count <NEW_LINE> <DEDENT> return total_bags_required <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_rules(rules: Iterable[str]) -> 'Graph': <NEW_LINE> <INDENT> nodes = [Node.from_rule_str(rule_str) for rule_str in rules] <NEW_LINE> return Graph({node.color_name: node for node in nodes}) | A directed graph representing bag colors containment rules. Each node in the graph represents
a bag-color and it has 2 sets of directed edges connecting it to other bag-colors (nodes).
1. Contained colors - Set of outgoing edges connecting the node to bag-colors that are
contained by the bag-color the node represents. These edges are weighted, the edge weight
represents the number of bags of the specified color contained by the node's bag color.
2. Contained by colors - Set of incoming edges connecting the nodes to bag-colors that
contain at least one bag of the color the node represents. | 625990794f88993c371f1206 |
class Game: <NEW_LINE> <INDENT> def __init__(self, max_levels): <NEW_LINE> <INDENT> self.over = False <NEW_LINE> self.simon = Simon() <NEW_LINE> self.player = Player() <NEW_LINE> self.level = self.simon.get_level_number() <NEW_LINE> self.max_levels = max_levels <NEW_LINE> self.regular_mode = False <NEW_LINE> self.timeout = 2 <NEW_LINE> <DEDENT> def next_level(self): <NEW_LINE> <INDENT> print("next level") <NEW_LINE> self.simon.add_color() <NEW_LINE> self.player.increase_score() <NEW_LINE> self.print_level() <NEW_LINE> self.test_player() <NEW_LINE> self.timeout = self.timeout - (self.timeout * 0.1) <NEW_LINE> <DEDENT> def print_level(self): <NEW_LINE> <INDENT> for x in self.simon.history: <NEW_LINE> <INDENT> self.clear_screen() <NEW_LINE> print(self.get_color(x) if self.regular_mode else self.get_random_color()+str(x)) <NEW_LINE> print(colorama.Fore.WHITE) <NEW_LINE> time.sleep(self.timeout) <NEW_LINE> self.clear_screen() <NEW_LINE> time.sleep(0.499995) <NEW_LINE> <DEDENT> <DEDENT> def get_color(self, tuple): <NEW_LINE> <INDENT> if tuple[1] is "BLUE": <NEW_LINE> <INDENT> return colorama.Fore.BLUE <NEW_LINE> <DEDENT> if tuple[1] is "GREEN": <NEW_LINE> <INDENT> return colorama.Fore.GREEN <NEW_LINE> <DEDENT> if tuple[1] is "RED": <NEW_LINE> <INDENT> return colorama.Fore.RED <NEW_LINE> <DEDENT> if tuple[1] is "YELLOW": <NEW_LINE> <INDENT> return colorama.Fore.YELLOW <NEW_LINE> <DEDENT> if tuple[1] is "CYAN": <NEW_LINE> <INDENT> return colorama.Fore.CYAN <NEW_LINE> <DEDENT> if tuple[1] is "MAGENTA": <NEW_LINE> <INDENT> return colorama.Fore.MAGENTA <NEW_LINE> <DEDENT> <DEDENT> def get_random_color(self): <NEW_LINE> <INDENT> random_color_tuple = random.choice(self.simon.colors) <NEW_LINE> random_color = self.get_color(random_color_tuple) <NEW_LINE> return random_color <NEW_LINE> <DEDENT> def test_player(self): <NEW_LINE> <INDENT> for x in self.simon.history: <NEW_LINE> <INDENT> test_result = input("What is the next color?") <NEW_LINE> if test_result is x[0]: <NEW_LINE> <INDENT> print("You have passed this test. On to the next.") <NEW_LINE> self.player.increase_score() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("You lose.") <NEW_LINE> self.over = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clear_screen(self): <NEW_LINE> <INDENT> print("\033[H\033[J") | game controller | 6259907956ac1b37e63039c7 |
class QueueHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self, queue): <NEW_LINE> <INDENT> logging.Handler.__init__(self) <NEW_LINE> self.queue = queue <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> self.queue.put_nowait(record) | This is a logging handler which sends events to a multiprocessing queue. | 62599079dc8b845886d54f84 |
class FetchNewWorkIds(luigi.Task): <NEW_LINE> <INDENT> site = luigi.Parameter() <NEW_LINE> n_work = luigi.IntParameter() <NEW_LINE> harvest_dts = luigi.DateMinuteParameter() <NEW_LINE> def output(self): <NEW_LINE> <INDENT> wids_filepath = '/tmp/reviewids_%s_%s.txt' % (self.site, self.harvest_dts.strftime(luigi.DateMinuteParameter.date_format)) <NEW_LINE> return luigi.LocalTarget(wids_filepath) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> f = self.output().open('w') <NEW_LINE> lang = 'eng' <NEW_LINE> if self.site in ('babelio'): <NEW_LINE> <INDENT> lang = 'fre' <NEW_LINE> <DEDENT> res_dic = service.fetch_workIds_not_harvested(self.site, nb_work=self.n_work, lang_code=lang, orderby_pop=False) <NEW_LINE> if len(res_dic) == 0: <NEW_LINE> <INDENT> raise brd.WorkflowError("No more work available to harvest for site %s, STOP PROCESSING!" % self.site) <NEW_LINE> <DEDENT> elif len(res_dic) < self.n_work: <NEW_LINE> <INDENT> logger.warning("Requested %d work but only %d are available for site %s" % (self.n_work, len(res_dic), self.site)) <NEW_LINE> <DEDENT> json.dump(res_dic, f, indent=2) <NEW_LINE> f.close() | Fetch n_work NOT yet harvested for site and their associated isbns
Used before harvesting sites where the work-uid is unknown. | 625990792c8b7c6e89bd51b4 |
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = os.environ.get('CONDUIT_SECRET', 'something') <NEW_LINE> APP_DIR = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir)) <NEW_LINE> BCRYPT_LOG_ROUNDS = 13 <NEW_LINE> DEBUG_TB_INTERCEPT_REDIRECTS = False <NEW_LINE> CACHE_TYPE = 'simple' <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> JWT_AUTH_USERNAME_KEY = 'email' <NEW_LINE> JWT_AUTH_HEADER_PREFIX = 'Token' <NEW_LINE> CORS_ORIGIN_WHITELIST = [ 'http://0.0.0.0:4100', 'http://localhost:4100', 'http://0.0.0.0:8000', 'http://localhost:8000', 'http://0.0.0.0:4200', 'http://localhost:4200', 'http://0.0.0.0:4000', 'http://localhost:4000', 'https://devops-front.netlify.app', 'http://devops-front.netlify.app', 'http://0.0.0.0:8080', 'https://0.0.0.0:8080', 'https://damp-taiga-40793.herokuapp.com/api/articles', 'https://damp-taiga-40793.herokuapp.com/', ] <NEW_LINE> JWT_HEADER_TYPE = 'Token' | Base configuration. | 62599079baa26c4b54d50c7b |
class Estimate(EmbeddedDocument): <NEW_LINE> <INDENT> cpu = IntField() <NEW_LINE> memory = StringField() | Estimator function output goes here | 625990791f5feb6acb1645c1 |
class LateTag(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'omeškanie' <NEW_LINE> verbose_name_plural = 'omeškanie' <NEW_LINE> <DEDENT> name = models.CharField( verbose_name='označenie štítku pre riešiteľa', max_length=50) <NEW_LINE> slug = models.CharField( verbose_name='označenie priečinku pri stiahnutí', max_length=50, validators=[validate_slug]) <NEW_LINE> upper_bound = models.DurationField( verbose_name='maximálna dĺžka omeškania') <NEW_LINE> comment = models.TextField(verbose_name='komentár pre opravovateľa') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | Slúži na označenie riešenia po termíne.
Každý LateTag vyjadruje druh omeškania (napríklad do 24 hodín) | 62599079aad79263cf430183 |
class SemaphorePool(object): <NEW_LINE> <INDENT> __shared_state = {} <NEW_LINE> def __init__(self, num_sems=5, count=1): <NEW_LINE> <INDENT> self.__dict__ = self.__shared_state <NEW_LINE> if len(self.__shared_state.keys()) == 0: <NEW_LINE> <INDENT> self.sem_dict = {} <NEW_LINE> self.sem_owner = [] <NEW_LINE> for i in range(num_sems): <NEW_LINE> <INDENT> self.sem_dict[i] = Semaphore(count) <NEW_LINE> self.sem_owner.append(None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def acquire(self, obj_id=None): <NEW_LINE> <INDENT> if obj_id is None: <NEW_LINE> <INDENT> raise Exception("Need object id to acquire semaphore.") <NEW_LINE> <DEDENT> for i in self.sem_dict: <NEW_LINE> <INDENT> if not self.sem_dict[i].available() is None: <NEW_LINE> <INDENT> self.sem_dict[i].acquire(obj_id) <NEW_LINE> self.sem_owner[i] = obj_id <NEW_LINE> return i <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def release(self, obj_id=None): <NEW_LINE> <INDENT> if obj_id is None: <NEW_LINE> <INDENT> raise Exception("Need object id to acquire semaphore.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> i = self.sem_owner.index(obj_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.sem_dict[i].release(obj_id) <NEW_LINE> self.sem_owner[i] = None <NEW_LINE> return i <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> for i, sem in self.sem_dict.items(): <NEW_LINE> <INDENT> string += "%s: %s\n" % (i,str(sem)) <NEW_LINE> <DEDENT> return string | A class to simulate a semaphore .
- **Methods**:
- acquire(obj_id) -> (int,None) : Attempt to acquire semaphore, success = value that is not None.
- release(obj_id) -> (int,None) : Attempt to release semaphore, success = value that is not None.
- **Attributes**:
- sem_dict : List of fake semaphores | 62599079097d151d1a2c2a41 |
class ReportedFundamentalsCache: <NEW_LINE> <INDENT> query_values = {} <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _query_key(identifier, statement, period_type, page_number): <NEW_LINE> <INDENT> return identifier + "_" + statement + "_" + str(period_type) + "_" + str(page_number) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_query_value_cached(cls, identifier, statement, period_type, page_number): <NEW_LINE> <INDENT> key = cls._query_key(identifier, statement, period_type, page_number) <NEW_LINE> return key in cls.query_values <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_query_value(cls, identifier, statement, period_type, page_number): <NEW_LINE> <INDENT> key = cls._query_key(identifier, statement, period_type, page_number) <NEW_LINE> return cls.query_values[key] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_query_value(cls, query_value, identifier, statement, period_type, page_number): <NEW_LINE> <INDENT> key = cls._query_key(identifier, statement, period_type, page_number) <NEW_LINE> cls.query_values[key] = query_value | Used to track reported fundamental data queries | 62599079ad47b63b2c5a9219 |
class PythonRun(PythonExecutionTaskBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def register_options(cls, register): <NEW_LINE> <INDENT> super(PythonRun, cls).register_options(register) <NEW_LINE> register('--args', type=list, help='Run with these extra args to main().') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def supports_passthru_args(cls): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> binary = self.require_single_root_target() <NEW_LINE> if isinstance(binary, PythonBinary): <NEW_LINE> <INDENT> pex = self.create_pex(binary.pexinfo) <NEW_LINE> self.context.release_lock() <NEW_LINE> with self.context.new_workunit(name='run', labels=[WorkUnitLabel.RUN]): <NEW_LINE> <INDENT> args = [] <NEW_LINE> for arg in self.get_options().args: <NEW_LINE> <INDENT> args.extend(safe_shlex_split(arg)) <NEW_LINE> <DEDENT> args += self.get_passthru_args() <NEW_LINE> po = pex.run(blocking=False, args=args) <NEW_LINE> try: <NEW_LINE> <INDENT> result = po.wait() <NEW_LINE> if result != 0: <NEW_LINE> <INDENT> msg = '{interpreter} {entry_point} {args} ... exited non-zero ({code})'.format( interpreter=pex.interpreter.binary, entry_point=binary.entry_point, args=' '.join(args), code=result) <NEW_LINE> raise TaskError(msg, exit_code=result) <NEW_LINE> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> po.send_signal(signal.SIGINT) <NEW_LINE> raise | Run a Python executable. | 625990797b180e01f3e49d4a |
class Comic: <NEW_LINE> <INDENT> def __init__(self, name, stock, average): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.stock = stock <NEW_LINE> self.average = average <NEW_LINE> comic_list.append(self) <NEW_LINE> <DEDENT> def restock(self, amount): <NEW_LINE> <INDENT> if amount > 0: <NEW_LINE> <INDENT> self.stock += amount <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def sell(self, amount): <NEW_LINE> <INDENT> if amount > 0 and amount <= self.stock: <NEW_LINE> <INDENT> self.stock -= amount <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get_progress(self): <NEW_LINE> <INDENT> progress = (self.stock / self.average) * 100 <NEW_LINE> return progress | The Comic class stores the details of each comic and has methods to restock, sell and calculate progress towards the daily average sold | 62599079091ae35668706607 |
class Config(object): <NEW_LINE> <INDENT> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> DEBUG = False <NEW_LINE> CSRF_ENABLED = True <NEW_LINE> SECRET_KEY = 'p9Bv<3Eid9%$i01' <NEW_LINE> SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://testuser:abc123@localhost:5432/testdb') <NEW_LINE> UPLOAD_FOLDER = 'designs/UI/uploads/' | Parent configuration class. | 62599079d486a94d0ba2d982 |
class XmlResult: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.logger = logging.getLogger("xml") <NEW_LINE> self.logger.setLevel("INFO") <NEW_LINE> self.xmlparser = xml.parsers.expat.ParserCreate() <NEW_LINE> self.xmlparser.StartElementHandler = self._start_element <NEW_LINE> self.xmlparser.EndElementHandler = self._end_element <NEW_LINE> self.xmlparser.CharacterDataHandler = self._char_data <NEW_LINE> self.rows = None <NEW_LINE> self.current_row = None <NEW_LINE> self.current_field = None <NEW_LINE> self.current_elements = list() <NEW_LINE> self.statement = None <NEW_LINE> <DEDENT> def parse(self, data): <NEW_LINE> <INDENT> if self.rows is not None: <NEW_LINE> <INDENT> raise ValueError("XmlResult objects can only be used once") <NEW_LINE> <DEDENT> self.rows = list() <NEW_LINE> self.xmlparser.Parse(data) <NEW_LINE> if self.current_elements: <NEW_LINE> <INDENT> raise partitionmanager.types.TruncatedDatabaseResultException( f"These XML tags are unclosed: {self.current_elements}" ) <NEW_LINE> <DEDENT> return self.rows <NEW_LINE> <DEDENT> def _start_element(self, name, attrs): <NEW_LINE> <INDENT> self.logger.debug( f"Element start: {name} {attrs} (Current elements: {self.current_elements}" ) <NEW_LINE> self.current_elements.append(name) <NEW_LINE> if name == "resultset": <NEW_LINE> <INDENT> self.statement = attrs["statement"] <NEW_LINE> <DEDENT> elif name == "row": <NEW_LINE> <INDENT> assert self.current_row is None <NEW_LINE> self.current_row = defaultdict(str) <NEW_LINE> <DEDENT> elif name == "field": <NEW_LINE> <INDENT> assert self.current_field is None <NEW_LINE> self.current_field = attrs["name"] <NEW_LINE> if "xsi:nil" in attrs and attrs["xsi:nil"] == "true": <NEW_LINE> <INDENT> self.current_row[attrs["name"]] = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _end_element(self, name): <NEW_LINE> <INDENT> self.logger.debug( f"Element end: {name} (Current elements: {self.current_elements}" ) <NEW_LINE> assert name == self.current_elements.pop() <NEW_LINE> if name == "row": <NEW_LINE> <INDENT> self.rows.append(self.current_row) <NEW_LINE> self.current_row = None <NEW_LINE> <DEDENT> elif name == "field": <NEW_LINE> <INDENT> assert self.current_field is not None <NEW_LINE> value = self.current_row[self.current_field] <NEW_LINE> if value: <NEW_LINE> <INDENT> self.current_row[self.current_field] = _destring(value) <NEW_LINE> <DEDENT> self.current_field = None <NEW_LINE> <DEDENT> <DEDENT> def _char_data(self, data): <NEW_LINE> <INDENT> if self.current_elements[-1] == "field": <NEW_LINE> <INDENT> assert self.current_field is not None <NEW_LINE> assert self.current_row is not None <NEW_LINE> self.current_row[self.current_field] += data | Parses XML results from the mariadb CLI client.
The general schema is:
<resultset statement="sql query">
<row>
<field name="name" xsi:nil="true/false">data if any</field>
</row>
</resultset>
The major hangups are that field can be nil, and field can also be
of arbitrary size. | 6259907932920d7e50bc7a12 |
class UnsupportedCutoffMethodError(BaseException): <NEW_LINE> <INDENT> pass | Exception for a cutoff method that is invalid or not supported by an engine. | 6259907971ff763f4b5e9176 |
class SteamMatchDataFeature(LastNMatchesFeature): <NEW_LINE> <INDENT> def _construct(self, last_date, team_name, n_matches, trait, conn=None,): <NEW_LINE> <INDENT> super(SteamMatchDataFeature, self)._construct(last_date, team_name, n_matches, conn=conn) <NEW_LINE> for match in self.matches: <NEW_LINE> <INDENT> friendly_players, enemy_players = self._get_friendly_and_enemy_players(team_name, match) <NEW_LINE> match['friendly_average'] = self._get_team_wide_average(friendly_players, trait) <NEW_LINE> match['enemy_average'] = self._get_team_wide_average(enemy_players, trait) <NEW_LINE> <DEDENT> <DEDENT> def _get_player_side_from_int(self, player_slot_int): <NEW_LINE> <INDENT> assert([player_slot_int < 256]) <NEW_LINE> if player_slot_int < 128: <NEW_LINE> <INDENT> return "RADIANT" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "DIRE" <NEW_LINE> <DEDENT> <DEDENT> def _get_players_by_sides(self, match_data): <NEW_LINE> <INDENT> radiant_players = [] <NEW_LINE> dire_players = [] <NEW_LINE> for player in match_data["players"]: <NEW_LINE> <INDENT> if self._get_player_side_from_int(player["player_slot"]) == "DIRE": <NEW_LINE> <INDENT> radiant_players.append(player) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dire_players.append(player) <NEW_LINE> <DEDENT> <DEDENT> return radiant_players, dire_players <NEW_LINE> <DEDENT> def _get_friendly_and_enemy_players(self, team_name, match): <NEW_LINE> <INDENT> dire_players, radiant_players = self._get_players_by_sides(match["match_data"]) <NEW_LINE> radiant_name = match["radiant_name"] <NEW_LINE> dire_name = match["dire_name"] <NEW_LINE> if team_name == radiant_name: <NEW_LINE> <INDENT> friendly_players = radiant_players <NEW_LINE> enemy_players = dire_players <NEW_LINE> <DEDENT> elif team_name == dire_name: <NEW_LINE> <INDENT> friendly_players = dire_players <NEW_LINE> enemy_players = radiant_players <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise(ValueError( "team_name: {} didn't match dire_name: {} or radiant_name: {} for match_id: {}".format( team_name, dire_name, radiant_name, match["match_id"] ) )) <NEW_LINE> <DEDENT> return friendly_players, enemy_players <NEW_LINE> <DEDENT> def _get_team_wide_average(self, players, trait): <NEW_LINE> <INDENT> values = [] <NEW_LINE> for player in players: <NEW_LINE> <INDENT> if trait == "leaver_status": <NEW_LINE> <INDENT> if player[trait] in (0, 1): <NEW_LINE> <INDENT> status = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status = 1 <NEW_LINE> <DEDENT> values.append(status) <NEW_LINE> continue <NEW_LINE> <DEDENT> values.append(player[trait]) <NEW_LINE> <DEDENT> average = sum(values)/5.0 <NEW_LINE> return average | Class provides a DRY way of parsing sides on steam API match data. | 6259907901c39578d7f1441a |
class Company(Base): <NEW_LINE> <INDENT> __tablename__ = 'company' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(32)) <NEW_LINE> country = Column(String(32)) <NEW_LINE> image_id = Column(Integer, ForeignKey('image.id')) <NEW_LINE> image = relationship(Image) <NEW_LINE> owner_id = Column(Integer, ForeignKey('user.id')) <NEW_LINE> user = relationship(User) <NEW_LINE> company_type = Column(String(32), nullable=False) <NEW_LINE> __mapper_args__ = {'polymorphic_on': company_type} <NEW_LINE> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'name': self.name, 'country': self.country, 'company_type': self.company_type, 'image_id': self.image_id } | Base class for companies of developers, publishers and manufacturers. | 625990793346ee7daa338346 |
class GroundStation(object): <NEW_LINE> <INDENT> GROUND_STATION_STATUS_MESSAGE = 1 <NEW_LINE> SERVICE_STATUS_MESSAGE = 2 <NEW_LINE> SERVICE_STATISTICS_MESSAGE = 3 <NEW_LINE> def __init__(self, sic, sac=232): <NEW_LINE> <INDENT> self.sic = sic <NEW_LINE> self.sac = sac <NEW_LINE> <DEDENT> def to_asterix_record(self, message_type, time_of_day): <NEW_LINE> <INDENT> record = {} <NEW_LINE> if self.SERVICE_STATUS_MESSAGE == message_type: <NEW_LINE> <INDENT> record = {0: {'message_type': message_type}, 10: {'SAC': self.sac, 'SIC': self.sic}, 15: {'SID': 2 }, 70: {'ToD': time_of_day}, 110: {'STAT': 8}} <NEW_LINE> <DEDENT> elif self.GROUND_STATION_STATUS_MESSAGE == message_type: <NEW_LINE> <INDENT> record = {0: {'message_type': message_type}, 10: {'SAC': self.sac, 'SIC': self.sic}, 70: {'ToD': time_of_day}, 100: {'OP': 0, 'ODP': 0, 'OXT': 0, 'MSC': 1, 'TSV': 0}} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> asterix_record = {23: [record]} <NEW_LINE> return asterix_record | This class provide service messages from a CNS/ATM Ground Station. | 62599079dc8b845886d54f86 |
class History(models.Model): <NEW_LINE> <INDENT> device = models.ForeignKey(Device) <NEW_LINE> date = models.DateField(auto_now=True, db_index=True) <NEW_LINE> timestamp = models.DateTimeField(auto_now=True, db_index=True) <NEW_LINE> action = models.IntegerField(choices=ACTION_TYPES_CHOICES) <NEW_LINE> user = models.TextField(max_length=20) <NEW_LINE> result = models.IntegerField(choices=RESULTS_CODE, blank=True) <NEW_LINE> comment = models.TextField(blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.device.name + ' ' + str(self.timestamp) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ["-timestamp"] <NEW_LINE> get_latest_by = "timestamp" <NEW_LINE> verbose_name_plural = "History" | History of a device | 625990792c8b7c6e89bd51b6 |
class AdminUserCourseAddressViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = UserCourse.objects.filter(user__role='STUDENT') <NEW_LINE> serializer_class = AdminUserCourseAddressSerializer <NEW_LINE> pagination_class = None <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_id = self.request.query_params.get('user') <NEW_LINE> queryset = self.queryset.filter(user_id=user_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise exceptions.ValidationError('请传入正确的user参数') <NEW_LINE> <DEDENT> return queryset | 学生成绩单寄送地址 | 625990794f6381625f19a192 |
class CsvData: <NEW_LINE> <INDENT> _month_names = cal.month_name[:7] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._filenames = {} <NEW_LINE> self._csv_files_available = None <NEW_LINE> self.get_filenames() <NEW_LINE> <DEDENT> def get_filenames(self): <NEW_LINE> <INDENT> for f in os.listdir("."): <NEW_LINE> <INDENT> if f.endswith(".csv"): <NEW_LINE> <INDENT> key = f[:-4].replace("_", " ").title() <NEW_LINE> self._filenames[key] = f <NEW_LINE> <DEDENT> <DEDENT> if len(self._filenames) == 0: <NEW_LINE> <INDENT> self._csv_files_available = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._csv_files_available = True <NEW_LINE> <DEDENT> <DEDENT> def csv_files_available(self): <NEW_LINE> <INDENT> return self._csv_files_available <NEW_LINE> <DEDENT> def get_city_names(self): <NEW_LINE> <INDENT> return list(self._filenames.keys()) <NEW_LINE> <DEDENT> def _convert_to_dataframe(self, csv_file): <NEW_LINE> <INDENT> headers = [] <NEW_LINE> for col in pd.read_csv(csv_file, nrows=1).columns: <NEW_LINE> <INDENT> if 'unnamed' not in col.lower() and col != 'End Time': <NEW_LINE> <INDENT> headers.append(col) <NEW_LINE> <DEDENT> <DEDENT> city_data = pd.read_csv(csv_file, usecols=headers, parse_dates=['Start Time'], infer_datetime_format=True) <NEW_LINE> city_data['Month'] = city_data['Start Time'].dt.month.apply( lambda x: self._month_names[x]) <NEW_LINE> city_data['Weekday'] = city_data['Start Time'].dt.weekday_name <NEW_LINE> city_data['Hour'] = city_data['Start Time'].dt.hour <NEW_LINE> city_data['Trip'] = city_data['Start Station'] + '_' + city_data['End Station'] <NEW_LINE> city_data.drop('Start Time', axis=1, inplace=True) <NEW_LINE> return city_data <NEW_LINE> <DEDENT> def get_data(self, city=None): <NEW_LINE> <INDENT> if city: <NEW_LINE> <INDENT> city_file = self._filenames[city] <NEW_LINE> return self._convert_to_dataframe(city_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all_city_data = {} <NEW_LINE> for city_name, city_file in self._filenames.items(): <NEW_LINE> <INDENT> all_city_data[city_name] = self._convert_to_dataframe(city_file) <NEW_LINE> <DEDENT> return all_city_data | A class for obtaining and filtering raw data from csv files. | 62599079627d3e7fe0e08853 |
class PaymentMethodData(Model): <NEW_LINE> <INDENT> _attribute_map = { 'supported_methods': {'key': 'supportedMethods', 'type': '[str]'}, 'data': {'key': 'data', 'type': 'object'}, } <NEW_LINE> def __init__(self, supported_methods=None, data=None): <NEW_LINE> <INDENT> super(PaymentMethodData, self).__init__() <NEW_LINE> self.supported_methods = supported_methods <NEW_LINE> self.data = data | Indicates a set of supported payment methods and any associated payment
method specific data for those methods.
:param supported_methods: Required sequence of strings containing payment
method identifiers for payment methods that the merchant web site accepts
:type supported_methods: list[str]
:param data: A JSON-serializable object that provides optional information
that might be needed by the supported payment methods
:type data: object | 625990791f5feb6acb1645c3 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.