code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ProtoTest(): <NEW_LINE> <INDENT> def __init__(self, test=None): <NEW_LINE> <INDENT> self.module = '' <NEW_LINE> self.class_name = '' <NEW_LINE> self.method_name = '' <NEW_LINE> self.docstr_part = '' <NEW_LINE> self.subtest_part = '' <NEW_LINE> self.is_subtest = False <NEW_LINE> if getattr(test, '_subDescription', None): <NEW_LINE> <INDENT> self.is_subtest = True <NEW_LINE> self.subtest_part = ' ' + test._subDescription() <NEW_LINE> test = test.test_case <NEW_LINE> <DEDENT> if test: <NEW_LINE> <INDENT> self.module = test.__module__ <NEW_LINE> self.class_name = test.__class__.__name__ <NEW_LINE> self.method_name = str(test).split()[0] <NEW_LINE> doc_segments = [] <NEW_LINE> if getattr(test, "_testMethodDoc", None): <NEW_LINE> <INDENT> for line in test._testMethodDoc.lstrip().split('\n'): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> doc_segments.append(line) <NEW_LINE> <DEDENT> <DEDENT> self.docstr_part = ' '.join(doc_segments) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__hash__() == other.__hash__() <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.dotted_name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.dotted_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def dotted_name(self, ignored=None): <NEW_LINE> <INDENT> return self.module + '.' + self.class_name + '.' + self.method_name + self.subtest_part <NEW_LINE> <DEDENT> def getDescription(self, verbose): <NEW_LINE> <INDENT> if verbose == 2: <NEW_LINE> <INDENT> return self.method_name + self.subtest_part <NEW_LINE> <DEDENT> elif verbose > 2: <NEW_LINE> <INDENT> return (self.docstr_part + self.subtest_part) or (self.method_name + self.subtest_part) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ''
I take a full-fledged TestCase and preserve just the information we need and can pass between processes.
62599062379a373c97d9a713
class Member(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, null=True, blank=True) <NEW_LINE> name = models.CharField(max_length=200) <NEW_LINE> slug = models.SlugField(unique=True) <NEW_LINE> site_url = models.CharField(max_length=200) <NEW_LINE> tags = TagField() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def feed_for_service(self, service): <NEW_LINE> <INDENT> entry = self.service_entries.get(service_slug=service) <NEW_LINE> if service == 'personal-blog': <NEW_LINE> <INDENT> return entry.feed_url <NEW_LINE> <DEDENT> return entry.service.userfeed_template % entry.username <NEW_LINE> <DEDENT> def username_for_service(self, service): <NEW_LINE> <INDENT> return self.service_entries.get(service_slug=service).username <NEW_LINE> <DEDENT> def save(self, force_insert=False, force_update=False): <NEW_LINE> <INDENT> self.slug = slugify(self.name) <NEW_LINE> super(Member, self).save(force_insert, force_update)
Class representing a member that has a feed being pulled in May or may not represent a User Service Entries allow us to point to any arbitrary Service Entry
62599062009cb60464d02c28
class DVdt_system(object): <NEW_LINE> <INDENT> def __init__(self, arguments): <NEW_LINE> <INDENT> self.arguments = arguments <NEW_LINE> <DEDENT> def dVdt(self): <NEW_LINE> <INDENT> flowrate = Flows(self.arguments) <NEW_LINE> q_AO = flowrate.flowrate_AO() <NEW_LINE> q_sa = flowrate.flowrate_sa() <NEW_LINE> q_sv = flowrate.flowrate_sv() <NEW_LINE> q_tr = flowrate.flowrate_tr() <NEW_LINE> q_pv = flowrate.flowrate_pv() <NEW_LINE> q_pc = flowrate.flowrate_pc() <NEW_LINE> q_cp = flowrate.flowrate_cp() <NEW_LINE> q_cv = flowrate.flowrate_cv() <NEW_LINE> q_mv = flowrate.flowrate_mv() <NEW_LINE> q_av = flowrate.flowrate_av() <NEW_LINE> dVdt_sa = q_AO - q_sa <NEW_LINE> dVdt_sv = q_sa - q_sv <NEW_LINE> dVdt_RA = q_sv - q_tr <NEW_LINE> dVdt_RV = q_tr - q_pv <NEW_LINE> dVdt_PA = q_pv - q_pc <NEW_LINE> dVdt_pc = q_pc - q_cp <NEW_LINE> dVdt_pv = q_cp - q_cv <NEW_LINE> dVdt_LA = q_cv - q_mv <NEW_LINE> dVdt_LV = q_mv - q_av <NEW_LINE> dVdt_AO = q_av - q_AO <NEW_LINE> dVdt_total = dVdt_sa + dVdt_sv + dVdt_RA + dVdt_RV + dVdt_PA + dVdt_pc + dVdt_pv + dVdt_LA + dVdt_LV + dVdt_AO <NEW_LINE> dVdt = { "dVdt_sa" : dVdt_sa, "dVdt_sv" : dVdt_sv, "dVdt_RA" : dVdt_RA, "dVdt_RV" : dVdt_RV, "dVdt_PA" : dVdt_PA, "dVdt_pc" : dVdt_pc, "dVdt_pv" : dVdt_pv, "dVdt_LA" : dVdt_LA, "dVdt_LV" : dVdt_LV, "dVdt_AO" : dVdt_AO } <NEW_LINE> return dVdt
docstring for DVdt_system.
6259906299cbb53fe68325d3
class HomeKit(): <NEW_LINE> <INDENT> def __init__(self, hass, port, ip_address, entity_filter, entity_config): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self._port = port <NEW_LINE> self._ip_address = ip_address <NEW_LINE> self._filter = entity_filter <NEW_LINE> self._config = entity_config <NEW_LINE> self.status = STATUS_READY <NEW_LINE> self.bridge = None <NEW_LINE> self.driver = None <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> from .accessories import HomeBridge, HomeDriver <NEW_LINE> self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, self.stop) <NEW_LINE> ip_addr = self._ip_address or get_local_ip() <NEW_LINE> path = self.hass.config.path(HOMEKIT_FILE) <NEW_LINE> self.driver = HomeDriver(self.hass, address=ip_addr, port=self._port, persist_file=path) <NEW_LINE> self.bridge = HomeBridge(self.hass, self.driver) <NEW_LINE> <DEDENT> def add_bridge_accessory(self, state): <NEW_LINE> <INDENT> if not state or not self._filter(state.entity_id): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> aid = generate_aid(state.entity_id) <NEW_LINE> conf = self._config.pop(state.entity_id, {}) <NEW_LINE> acc = get_accessory(self.hass, self.driver, state, aid, conf) <NEW_LINE> if acc is not None: <NEW_LINE> <INDENT> self.bridge.add_accessory(acc) <NEW_LINE> <DEDENT> <DEDENT> def start(self, *args): <NEW_LINE> <INDENT> if self.status != STATUS_READY: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.status = STATUS_WAIT <NEW_LINE> from . import ( type_covers, type_fans, type_lights, type_locks, type_media_players, type_security_systems, type_sensors, type_switches, type_thermostats) <NEW_LINE> for state in self.hass.states.all(): <NEW_LINE> <INDENT> self.add_bridge_accessory(state) <NEW_LINE> <DEDENT> self.driver.add_accessory(self.bridge) <NEW_LINE> if not self.driver.state.paired: <NEW_LINE> <INDENT> show_setup_message(self.hass, self.driver.state.pincode) <NEW_LINE> <DEDENT> _LOGGER.debug('Driver start') <NEW_LINE> self.hass.add_job(self.driver.start) <NEW_LINE> self.status = STATUS_RUNNING <NEW_LINE> <DEDENT> def stop(self, *args): <NEW_LINE> <INDENT> if self.status != STATUS_RUNNING: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.status = STATUS_STOPPED <NEW_LINE> _LOGGER.debug('Driver stop') <NEW_LINE> self.hass.add_job(self.driver.stop)
Class to handle all actions between HomeKit and Home Assistant.
6259906297e22403b383c5fd
class CPubKey(bytes): <NEW_LINE> <INDENT> def __new__(cls, buf, _cec_key=None): <NEW_LINE> <INDENT> self = super(CPubKey, cls).__new__(cls, buf) <NEW_LINE> if _cec_key is None: <NEW_LINE> <INDENT> _cec_key = CECKey() <NEW_LINE> <DEDENT> self._cec_key = _cec_key <NEW_LINE> self.is_fullyvalid = _cec_key.set_pubkey(self) != 0 <NEW_LINE> return self <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_valid(self): <NEW_LINE> <INDENT> return len(self) > 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_compressed(self): <NEW_LINE> <INDENT> return len(self) == 33 <NEW_LINE> <DEDENT> def verify(self, hash_in, sig): <NEW_LINE> <INDENT> return self._cec_key.verify(hash_in, sig) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if sys.version > '3': <NEW_LINE> <INDENT> return '%s(%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '%s(b%s)' % (self.__class__.__name__, super(CPubKey, self).__repr__())
An encapsulated public key Attributes: is_valid - Corresponds to CPubKey.IsValid() is_fullyvalid - Corresponds to CPubKey.IsFullyValid() is_compressed - Corresponds to CPubKey.IsCompressed()
625990628da39b475be048d9
class HTTPReadCredentialDTO(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, HTTPReadCredentialDTO): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62599062796e427e5384fe66
class ChosenInlineResultTest(BaseTest, unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> user = telegram.User(1, 'First name') <NEW_LINE> self.result_id = 'result id' <NEW_LINE> self.from_user = user <NEW_LINE> self.query = 'query text' <NEW_LINE> self.json_dict = { 'result_id': self.result_id, 'from': self.from_user.to_dict(), 'query': self.query } <NEW_LINE> <DEDENT> def test_choseninlineresult_de_json(self): <NEW_LINE> <INDENT> result = telegram.ChosenInlineResult.de_json(self.json_dict) <NEW_LINE> self.assertEqual(result.result_id, self.result_id) <NEW_LINE> self.assertDictEqual(result.from_user.to_dict(), self.from_user.to_dict()) <NEW_LINE> self.assertEqual(result.query, self.query) <NEW_LINE> <DEDENT> def test_choseninlineresult_to_json(self): <NEW_LINE> <INDENT> result = telegram.ChosenInlineResult.de_json(self.json_dict) <NEW_LINE> self.assertTrue(self.is_json(result.to_json())) <NEW_LINE> <DEDENT> def test_choseninlineresult_to_dict(self): <NEW_LINE> <INDENT> result = telegram.ChosenInlineResult.de_json(self.json_dict).to_dict() <NEW_LINE> self.assertTrue(self.is_dict(result)) <NEW_LINE> self.assertEqual(result['result_id'], self.result_id) <NEW_LINE> self.assertEqual(result['from'], self.from_user.to_dict()) <NEW_LINE> self.assertEqual(result['query'], self.query)
This object represents Tests for Telegram ChosenInlineResult.
62599062d6c5a102081e3816
class TestTutorialThread(JNTTThreadRun, JNTTThreadRunCommon): <NEW_LINE> <INDENT> thread_name = "tutorial2" <NEW_LINE> conf_file = "tests/data/helloworldv2.conf" <NEW_LINE> def test_102_check_values(self): <NEW_LINE> <INDENT> self.wait_for_nodeman() <NEW_LINE> time.sleep(5) <NEW_LINE> self.assertValueOnBus('cpu','temperature') <NEW_LINE> self.assertValueOnBus('temperature','temperature') <NEW_LINE> self.assertValueOnBus('ambiance','temperature') <NEW_LINE> self.assertValueOnBus('ambiance','humidity')
Test the thread
62599062baa26c4b54d50994
class Diagnosis2(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Diagnosis2, self).__init__() <NEW_LINE> self.conv1 = nn.Sequential( nn.Conv2d(12, 32, (30, 1), 1, 0), nn.ReLU(), nn.MaxPool2d(kernel_size=(3, 1)) ) <NEW_LINE> self.conv2 = nn.Sequential( nn.Conv2d(32, 64, (10, 1), 1, 0), nn.ReLU(), nn.MaxPool2d((3, 1)) ) <NEW_LINE> self.conv3 = nn.Sequential( nn.Conv2d(64, 64, (10, 1), 1, 0), nn.ReLU(), nn.MaxPool2d((3, 1)) ) <NEW_LINE> self.conv4 = nn.Sequential( nn.Conv2d(64, 64, (5, 1), 1, 0), nn.ReLU(), nn.MaxPool2d((3, 1)) ) <NEW_LINE> self.conv5 = nn.Sequential( nn.Conv2d(64, 128, (5, 1), 1, 0), nn.ReLU(), nn.MaxPool2d((3, 1)) ) <NEW_LINE> self.conv6 = nn.Sequential( nn.Conv2d(128, 128, (3, 1), 1, 0), nn.ReLU(), nn.MaxPool2d((3, 1)) ) <NEW_LINE> self.conv7 = nn.Sequential( nn.Conv2d(128, 128, (2, 1), 1, 0), nn.ReLU(), nn.MaxPool2d((1, 1)) ) <NEW_LINE> self.bilstm = nn.LSTM(128, 256, batch_first=True, bidirectional=True) <NEW_LINE> self.network = nn.Sequential( nn.Linear(512 * 1, 100), nn.Dropout(0.4), nn.Linear(100, 60), nn.Dropout(0.4), nn.Linear(60, 9), ) <NEW_LINE> self.dropout = nn.Dropout(0.5) <NEW_LINE> self.batchnorm = nn.BatchNorm1d(512) <NEW_LINE> self.relu = nn.ReLU() <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = self.conv3(x) <NEW_LINE> x = self.conv4(x) <NEW_LINE> x = self.conv5(x) <NEW_LINE> x = self.conv6(x) <NEW_LINE> x = x.reshape(x.size(0), 128, -1) <NEW_LINE> x = x.permute(0, 2, 1) <NEW_LINE> x = self.dropout(x) <NEW_LINE> x = self.relu(x) <NEW_LINE> r_out, (h_n, c_n) = self.bilstm(x, None) <NEW_LINE> x = r_out[:, -1, :] <NEW_LINE> x = self.dropout(x) <NEW_LINE> x = self.batchnorm(x) <NEW_LINE> x = self.network(x) <NEW_LINE> return x
CNN + LSTM
62599062fff4ab517ebcef18
class Vertex: <NEW_LINE> <INDENT> __slots__ = '_element' <NEW_LINE> def __init__(self, x): <NEW_LINE> <INDENT> self._element = x <NEW_LINE> <DEDENT> def element(self): <NEW_LINE> <INDENT> return self._element <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.element()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._element <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return ( self.__class__ == other.__class__ and self.element() == other.element() ) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other)
'Lightweight vertex structure for a graph
625990623d592f4c4edbc5ce
class LdpNsrPeerSyncStNoneIdentity(NsrPeerSyncStateIdentity): <NEW_LINE> <INDENT> _prefix = 'mpls-ldp-ios-xe-oper' <NEW_LINE> _revision = '2017-02-07' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> NsrPeerSyncStateIdentity.__init__(self) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xe._meta import _Cisco_IOS_XE_mpls_ldp as meta <NEW_LINE> return meta._meta_table['LdpNsrPeerSyncStNoneIdentity']['meta_info']
LDP NSR peer synchronization none.
62599062a8370b77170f1abf
class Vectorization_Layer(LayerInterface): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.input_shape = None <NEW_LINE> self.output_shape = None <NEW_LINE> <DEDENT> def forward_pass(self, input_data): <NEW_LINE> <INDENT> self.input_shape = input_data.shape <NEW_LINE> return np.array([input_data.flatten()]) <NEW_LINE> <DEDENT> def backward_prop(self, error): <NEW_LINE> <INDENT> self.output_shape = error.shape <NEW_LINE> return np.reshape(error,self.input_shape) <NEW_LINE> <DEDENT> def update_weight(self,learn_rate): <NEW_LINE> <INDENT> pass
Neural Layer to flatten all the values in the data to a single array Attributes ---------- input_shape : Tuple[int] shape of the image_data output_shape : Tuple[int] shape of the image_data Methods ------- __init__(self): initialization of the layer forward_pass(self, input_data): forward pass function for this neural layer backward_prop(self, error): backward propagation for this neural layer update_weight(self, learn_rate): updates the weights of this layer (if needed)
62599062f7d966606f749432
class GoodEndScreen(game.GameState): <NEW_LINE> <INDENT> tile_resolution = (0, 0) <NEW_LINE> h_center = 0 <NEW_LINE> timeout = 0 <NEW_LINE> def wake_up(self): <NEW_LINE> <INDENT> self.timeout = 300 <NEW_LINE> self.tile_resolution = game.pyxeltools.load_png_to_image_bank( game.assets.search('tile.png'), _TILE_SCR_ ) <NEW_LINE> self.h_center = int((pyxel.width / 2) - (self.tile_resolution[0] / 2)) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if (pyxel.btnr(pyxel.KEY_ENTER)) or (self.timeout <= 0): <NEW_LINE> <INDENT> self.go_to_state(INITIAL_SCREEN) <NEW_LINE> <DEDENT> self.timeout -= 1 <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> pyxel.rect(0, 0, pyxel.width, pyxel.height, pyxel.COLOR_BLACK) <NEW_LINE> pyxel.blt(self.h_center, 10, _TILE_SCR_, 0, 0, *self.tile_resolution) <NEW_LINE> pyxel.text(80, 220, "GOOD END", pyxel.COLOR_WHITE)
A very basic good end screen
62599062498bea3a75a59178
class NumVotesFilter(admin.SimpleListFilter): <NEW_LINE> <INDENT> title = 'number of votes' <NEW_LINE> parameter_name = 'num_votes' <NEW_LINE> def lookups(self, request, model_admin): <NEW_LINE> <INDENT> return ( ('0', 'No votes'), ('1', 'At least 1'), ('5', 'At least 5'), ('10', 'At least 10'), ('20', '20 or more'), ) <NEW_LINE> <DEDENT> def queryset(self, request, queryset): <NEW_LINE> <INDENT> if self.value() == '0': <NEW_LINE> <INDENT> return queryset.filter(num_votes=0) <NEW_LINE> <DEDENT> elif self.value(): <NEW_LINE> <INDENT> minimum = int(self.value()) <NEW_LINE> return queryset.filter(num_votes__gte=minimum)
Allows filtering on the `num_votes` attribute.
625990624f6381625f19a01c
class EntitiesEntityPresentationInfo(Model): <NEW_LINE> <INDENT> _validation = { 'entity_scenario': {'required': True}, 'entity_type_hints': {'readonly': True}, 'entity_type_display_hint': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'entity_scenario': {'key': 'entityScenario', 'type': 'str'}, 'entity_type_hints': {'key': 'entityTypeHints', 'type': '[str]'}, 'entity_type_display_hint': {'key': 'entityTypeDisplayHint', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(EntitiesEntityPresentationInfo, self).__init__(**kwargs) <NEW_LINE> self.entity_scenario = kwargs.get('entity_scenario', "DominantEntity") <NEW_LINE> self.entity_type_hints = None <NEW_LINE> self.entity_type_display_hint = None
Defines additional information about an entity such as type hints. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param entity_scenario: Required. The supported scenario. Possible values include: 'DominantEntity', 'DisambiguationItem', 'ListItem'. Default value: "DominantEntity" . :type entity_scenario: str or ~azure.cognitiveservices.search.entitysearch.models.EntityScenario :ivar entity_type_hints: A list of hints that indicate the entity's type. The list could contain a single hint such as Movie or a list of hints such as Place, LocalBusiness, Restaurant. Each successive hint in the array narrows the entity's type. :vartype entity_type_hints: list[str or ~azure.cognitiveservices.search.entitysearch.models.EntityType] :ivar entity_type_display_hint: A display version of the entity hint. For example, if entityTypeHints is Artist, this field may be set to American Singer. :vartype entity_type_display_hint: str
625990623617ad0b5ee07840
class ActivationsProcessor(Processor): <NEW_LINE> <INDENT> def __init__(self, mode, fps=None, sep=None, **kwargs): <NEW_LINE> <INDENT> self.mode = mode <NEW_LINE> self.fps = fps <NEW_LINE> self.sep = sep <NEW_LINE> <DEDENT> def process(self, data, output=None, **kwargs): <NEW_LINE> <INDENT> if self.mode in ('r', 'in', 'load'): <NEW_LINE> <INDENT> return Activations.load(data, fps=self.fps, sep=self.sep) <NEW_LINE> <DEDENT> if self.mode in ('w', 'out', 'save'): <NEW_LINE> <INDENT> Activations(data, fps=self.fps).save(output, sep=self.sep) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("wrong mode %s; choose {'r', 'w', 'in', 'out', " "'load', 'save'}") <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def add_arguments(parser): <NEW_LINE> <INDENT> g = parser.add_argument_group('save/load the activations') <NEW_LINE> g.add_argument('--save', action='store_true', default=False, help='save the activations to file') <NEW_LINE> g.add_argument('--load', action='store_true', default=False, help='load the activations from file') <NEW_LINE> g.add_argument('--sep', action='store', default=None, help='separator for saving/loading the activations ' '[default: None, i.e. numpy binary format]') <NEW_LINE> return g
ActivationsProcessor processes a file and returns an Activations instance. Parameters ---------- mode : {'r', 'w', 'in', 'out', 'load', 'save'} Mode of the Processor: read/write. fps : float, optional Frame rate of the activations (if set, it overwrites the saved frame rate). sep : str, optional Separator between activation values if saved as text file. Notes ----- An undefined or empty (“”) separator means that the file should be treated as a numpy binary file. Only binary files can store the frame rate of the activations.
625990624e4d562566373af9
class MAVLink_home_position_message(MAVLink_message): <NEW_LINE> <INDENT> id = MAVLINK_MSG_ID_HOME_POSITION <NEW_LINE> name = 'HOME_POSITION' <NEW_LINE> fieldnames = ['latitude', 'longitude', 'altitude', 'x', 'y', 'z', 'q', 'approach_x', 'approach_y', 'approach_z', 'time_usec'] <NEW_LINE> ordered_fieldnames = [ 'latitude', 'longitude', 'altitude', 'x', 'y', 'z', 'q', 'approach_x', 'approach_y', 'approach_z', 'time_usec' ] <NEW_LINE> format = '<iiifff4ffffQ' <NEW_LINE> native_format = bytearray('<iiifffffffQ', 'ascii') <NEW_LINE> orders = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <NEW_LINE> lengths = [1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1] <NEW_LINE> array_lengths = [0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0] <NEW_LINE> crc_extra = 104 <NEW_LINE> def __init__(self, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, time_usec=0): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLink_home_position_message.id, MAVLink_home_position_message.name) <NEW_LINE> self._fieldnames = MAVLink_home_position_message.fieldnames <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.altitude = altitude <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.z = z <NEW_LINE> self.q = q <NEW_LINE> self.approach_x = approach_x <NEW_LINE> self.approach_y = approach_y <NEW_LINE> self.approach_z = approach_z <NEW_LINE> self.time_usec = time_usec <NEW_LINE> <DEDENT> def pack(self, mav, force_mavlink1=False): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 104, struct.pack('<iiifff4ffffQ', self.latitude, self.longitude, self.altitude, self.x, self.y, self.z, self.q[0], self.q[1], self.q[2], self.q[3], self.approach_x, self.approach_y, self.approach_z, self.time_usec), force_mavlink1=force_mavlink1)
This message can be requested by sending the MAV_CMD_GET_HOME_POSITION command. The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitely set by the operator before or after. The position the system will return to and land on. The global and local positions encode the position in the respective coordinate frames, while the q parameter encodes the orientation of the surface. Under normal conditions it describes the heading and terrain slope, which can be used by the aircraft to adjust the approach. The approach 3D vector describes the point to which the system should fly in normal flight mode and then perform a landing sequence along the vector.
6259906291af0d3eaad3b51a
class itkImageMomentsCalculatorIF3(ITKCommonBasePython.itkObject): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> ImageDimension = _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_ImageDimension <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetImage(self, *args): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_SetImage(self, *args) <NEW_LINE> <DEDENT> def SetSpatialObjectMask(self, *args): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_SetSpatialObjectMask(self, *args) <NEW_LINE> <DEDENT> def Compute(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_Compute(self) <NEW_LINE> <DEDENT> def GetTotalMass(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetTotalMass(self) <NEW_LINE> <DEDENT> def GetFirstMoments(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetFirstMoments(self) <NEW_LINE> <DEDENT> def GetSecondMoments(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetSecondMoments(self) <NEW_LINE> <DEDENT> def GetCenterOfGravity(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetCenterOfGravity(self) <NEW_LINE> <DEDENT> def GetCentralMoments(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetCentralMoments(self) <NEW_LINE> <DEDENT> def GetPrincipalMoments(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetPrincipalMoments(self) <NEW_LINE> <DEDENT> def GetPrincipalAxes(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetPrincipalAxes(self) <NEW_LINE> <DEDENT> def GetPrincipalAxesToPhysicalAxesTransform(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetPrincipalAxesToPhysicalAxesTransform(self) <NEW_LINE> <DEDENT> def GetPhysicalAxesToPrincipalAxesTransform(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetPhysicalAxesToPrincipalAxesTransform(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkImageMomentsCalculatorPython.delete_itkImageMomentsCalculatorIF3 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkImageMomentsCalculatorPython.itkImageMomentsCalculatorIF3_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkImageMomentsCalculatorIF3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkImageMomentsCalculatorIF3 class
62599062009cb60464d02c2a
class WienerProcess(CountingProcess): <NEW_LINE> <INDENT> def __new__(cls, sym): <NEW_LINE> <INDENT> sym = _symbol_converter(sym) <NEW_LINE> return Basic.__new__(cls, sym) <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_space(self): <NEW_LINE> <INDENT> return S.Reals <NEW_LINE> <DEDENT> def distribution(self, rv): <NEW_LINE> <INDENT> return NormalDistribution(0, sqrt(rv.key)) <NEW_LINE> <DEDENT> def density(self, x): <NEW_LINE> <INDENT> return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key)) <NEW_LINE> <DEDENT> def simple_rv(self, rv): <NEW_LINE> <INDENT> return Normal(rv.name, 0, sqrt(rv.key))
The Wiener process is a real valued continuous-time stochastic process. In physics it is used to study Brownian motion and therefore also known as Brownian Motion. Parameters ========== sym: Symbol/str Examples ======== >>> from sympy.stats import WienerProcess, P, E >>> from sympy import symbols, Contains, Interval >>> X = WienerProcess("X") >>> X.state_space Reals >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 7).simplify() erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2 >>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify() -erf(1)/2 + erf(2)/2 + 1 >>> E(X(t1)) 0 >>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 0 References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php .. [2] https://en.wikipedia.org/wiki/Wiener_process
6259906276e4537e8c3f0c76
class Student: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.gpa = 0.0 <NEW_LINE> self.stress = 50 <NEW_LINE> self.knowledge = 50 <NEW_LINE> self.dexterity = 50 <NEW_LINE> self.strength = 50 <NEW_LINE> self.speed = 50 <NEW_LINE> self.courses = [] <NEW_LINE> self.name = "Bob" <NEW_LINE> <DEDENT> def liftWeights(self, weightOfWeights): <NEW_LINE> <INDENT> self.strength += weightOfWeights/20 <NEW_LINE> <DEDENT> def runOnTreadmill(self, speedOfRun): <NEW_LINE> <INDENT> if speedOfRun >= 3.5: <NEW_LINE> <INDENT> self.speed += speedOfRun <NEW_LINE> <DEDENT> <DEDENT> def addToStress(self, amt): <NEW_LINE> <INDENT> self.setStress(amt + self.getStress()) <NEW_LINE> <DEDENT> def getStress(self): <NEW_LINE> <INDENT> return self.stress <NEW_LINE> <DEDENT> def setStress(self, stress): <NEW_LINE> <INDENT> if 0 <= stress <= 100: <NEW_LINE> <INDENT> self.stress = stress <NEW_LINE> <DEDENT> elif stress < 0: <NEW_LINE> <INDENT> self.stress = 0 <NEW_LINE> <DEDENT> elif stress > 100: <NEW_LINE> <INDENT> self.stress = 100 <NEW_LINE> <DEDENT> <DEDENT> def getGPA(self): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> for course in self.courses: <NEW_LINE> <INDENT> sum += course.grade <NEW_LINE> <DEDENT> return sum / len(self.courses) <NEW_LINE> <DEDENT> def registerForCource(self, course): <NEW_LINE> <INDENT> self.courses += course <NEW_LINE> <DEDENT> def dropCourse(self, course): <NEW_LINE> <INDENT> self.courses.remove(course) <NEW_LINE> <DEDENT> def getGrades(self): <NEW_LINE> <INDENT> grades = [] <NEW_LINE> for course in self.courses: <NEW_LINE> <INDENT> grades.append(course.grade) <NEW_LINE> <DEDENT> return grades <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def setName(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def getKnowledge(self): <NEW_LINE> <INDENT> return self.knowledge <NEW_LINE> <DEDENT> def setKnowledge(self, know): <NEW_LINE> <INDENT> if 0 <= know <= 100: <NEW_LINE> <INDENT> self.knowledge = know <NEW_LINE> <DEDENT> elif know < 0: <NEW_LINE> <INDENT> self.knowledge = 0 <NEW_LINE> <DEDENT> elif know > 100: <NEW_LINE> <INDENT> self.knowledge = 100 <NEW_LINE> <DEDENT> <DEDENT> def addKnowledge(self, know): <NEW_LINE> <INDENT> self.setKnowledge(know + self.getKnowledge())
Default Student Constructor
6259906256b00c62f0fb3fbe
class TokenEndpointError(Exception): <NEW_LINE> <INDENT> def __init__(self, error, error_description): <NEW_LINE> <INDENT> self.error = error <NEW_LINE> self.error_description = error_description <NEW_LINE> super(TokenEndpointError, self).__init__( "[%s] %s" % (self.error, self.error_description))
Error communicating with the token endpoint.
62599062097d151d1a2c275d
class SinusoidalTaskSet(TaskSet): <NEW_LINE> <INDENT> def __init__( self, num_train_points=50, num_test_points=30, num_tasks=10, ): <NEW_LINE> <INDENT> num_points = num_train_points + num_test_points <NEW_LINE> X, Y = random_sinusoid_set(num_tasks, num_points) <NEW_LINE> self.X_train = X[:, :num_train_points] <NEW_LINE> self.Y_train = Y[:, :num_train_points] <NEW_LINE> self.X_test = X[:, num_train_points:] <NEW_LINE> self.Y_test = Y[:, num_train_points:]
Each task consists of training points and test points Detailed description coming soon.
62599062442bda511e95d8d3
class SmsGateway(object): <NEW_LINE> <INDENT> BASE_URL = "https://smsgateway.me" <NEW_LINE> def loginDetails(self, email, password): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def getMessages(self, page=1): <NEW_LINE> <INDENT> return self.makeRequest('/api/v3/messages', 'GET', dict(page=page)) <NEW_LINE> <DEDENT> def sendMessageToNumber(self, to, message, device, options={}): <NEW_LINE> <INDENT> options.update({'number': to, 'message': message, 'device': device}) <NEW_LINE> return self.makeRequest('/api/v3/messages/send', 'POST', options) <NEW_LINE> <DEDENT> def sendMessageToManyNumbers(self, to, message, device, options={}): <NEW_LINE> <INDENT> options.update({'number': to, 'message': message, 'device': device}) <NEW_LINE> return self.makeRequest('/api/v3/messages/send', 'POST', options) <NEW_LINE> <DEDENT> def makeRequest(self, url, method, fields): <NEW_LINE> <INDENT> fields['email'] = self.email <NEW_LINE> fields['password'] = self.password <NEW_LINE> url = self.BASE_URL + url <NEW_LINE> ret_dict = {} <NEW_LINE> if method == "POST": <NEW_LINE> <INDENT> resp = requests.post(url, data=fields, verify=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resp = requests.get(url, params=fields, verify=False) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ret_dict['response'] = resp.json() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret_dict['response'] = json.loads(resp.text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> ret_dict['response'] = resp.text <NEW_LINE> <DEDENT> <DEDENT> ret_dict['status'] = resp.status_code <NEW_LINE> return ret_dict
Python equivalent class of the php sample given by smsgateway.me.
62599062be8e80087fbc077a
class Backend: <NEW_LINE> <INDENT> def __init__(self, **zoo_kwargs): <NEW_LINE> <INDENT> self._client = zoo.Client(**zoo_kwargs) <NEW_LINE> self.jobs_control = ifaces.JobsControl(self._client) <NEW_LINE> self.jobs_process = ifaces.JobsProcess(self._client) <NEW_LINE> self.jobs_gc = ifaces.JobsGc(self._client) <NEW_LINE> self.scripts = ifaces.Scripts(self._client) <NEW_LINE> self.system_apps_state = ifaces.AppsState(self._client) <NEW_LINE> self.cas_storage = ifaces.CasStorage(self._client) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_options(cls): <NEW_LINE> <INDENT> return zoo.Client.get_options() <NEW_LINE> <DEDENT> @contextlib.contextmanager <NEW_LINE> def connected(self): <NEW_LINE> <INDENT> self.open() <NEW_LINE> try: <NEW_LINE> <INDENT> yield self <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def open(self): <NEW_LINE> <INDENT> self._client.open() <NEW_LINE> ifaces.init(self._client) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._client.close() <NEW_LINE> <DEDENT> def is_opened(self): <NEW_LINE> <INDENT> return self._client.is_opened() <NEW_LINE> <DEDENT> def is_alive(self): <NEW_LINE> <INDENT> return self._client.is_alive() <NEW_LINE> <DEDENT> def get_info(self): <NEW_LINE> <INDENT> return self._client.get_server_info()
ZooKeeper backend provides some interfaces for working with jobs and other operations. Each instance of this class contains an own connection to ZooKeeper and can be used for any operation.
62599062fff4ab517ebcef1a
class RatingOutOfRangeException(SparkException): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(RatingOutOfRangeException, self).__init__(message)
CF generated rating is out of range i.e. rating > 1 or rating < -1
62599062498bea3a75a59179
class DecisionTreeClassifier(DecisionTree): <NEW_LINE> <INDENT> def __init__(self, method="gini", max_depth=2, max_points=None): <NEW_LINE> <INDENT> self.PredictionNode = nodes.PredNodeClassify <NEW_LINE> super().__init__(method, max_depth, max_points)
Instantiate this class for a Decision Tree for classification tasks.
6259906221bff66bcd724359
class NodeInstallationTasksSequenceCreator(object): <NEW_LINE> <INDENT> def create(self, instance, graph, installation_tasks): <NEW_LINE> <INDENT> sequence = graph.sequence() <NEW_LINE> sequence.add( instance.set_state('initializing'), forkjoin( installation_tasks.set_state_creating[instance.id], installation_tasks.send_event_creating[instance.id] ), instance.execute_operation('cloudify.interfaces.lifecycle.create'), instance.set_state('created'), forkjoin(*_relationship_operations( instance, 'cloudify.interfaces.relationship_lifecycle.preconfigure' )), forkjoin( instance.set_state('configuring'), instance.send_event('Configuring node') ), instance.execute_operation( 'cloudify.interfaces.lifecycle.configure'), instance.set_state('configured'), forkjoin(*_relationship_operations( instance, 'cloudify.interfaces.relationship_lifecycle.postconfigure' )), forkjoin( instance.set_state('starting'), instance.send_event('Starting node') ), instance.execute_operation('cloudify.interfaces.lifecycle.start')) <NEW_LINE> if _is_host_node(instance): <NEW_LINE> <INDENT> sequence.add(*_host_post_start(instance)) <NEW_LINE> <DEDENT> sequence.add( forkjoin( instance.execute_operation( 'cloudify.interfaces.monitoring.start'), *_relationship_operations( instance, 'cloudify.interfaces.relationship_lifecycle.establish' )), installation_tasks.set_state_started[instance.id])
This class is used to create a tasks sequence installing one node instance. Considering the order of tasks executions, it enforces the proper dependencies only in context of this particular node instance.
625990623617ad0b5ee07842
class FieldSet(formalchemy.FieldSet): <NEW_LINE> <INDENT> def __init__(self, model, **kwargs): <NEW_LINE> <INDENT> super(FieldSet, self).__init__(model, **kwargs) <NEW_LINE> self.request = kwargs["request"] <NEW_LINE> assert kwargs["request"] <NEW_LINE> <DEDENT> def render(self, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault("_", self.request.translate) <NEW_LINE> kwargs.setdefault("ungettext", self.request.ungettext) <NEW_LINE> kwargs.setdefault("request", self.request) <NEW_LINE> kwargs.setdefault("lang", self.request.locale_name) <NEW_LINE> return super(FieldSet, self).render(**kwargs)
A base Grid, makes sure that request is passed, sets the context for localization in templates.
625990624a966d76dd5f05e9
class ZoteroRecord(dict): <NEW_LINE> <INDENT> __getattr__ = dict.__getitem__ <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> dict.__init__(self, **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> f = '{}({{}}): "{{}}"'.format( str(type(self)).split("'")[1].split('.')[-1]) <NEW_LINE> s = '' <NEW_LINE> for k in ['ShortTitle', 'Title']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = self[k] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if s != '': <NEW_LINE> <INDENT> return f.format(self['Key'], s) <NEW_LINE> <DEDENT> return repr(self) <NEW_LINE> <DEDENT> def suggest_short_title(self): <NEW_LINE> <INDENT> authors = self['Author'].strip() <NEW_LINE> if authors == '': <NEW_LINE> <INDENT> return self._make_short_title_acronym() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> date_published = parse_date(self['Date']) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return self._make_short_title_acronym() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> first_author = [a.strip() for a in authors.split(';')][0] <NEW_LINE> if ',' in first_author: <NEW_LINE> <INDENT> last_name = first_author.split(',')[0].strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> last_name = first_author.split()[-1].strip() <NEW_LINE> <DEDENT> return '{} {}'.format(last_name, date_published.year) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _make_short_title_acronym(self): <NEW_LINE> <INDENT> title = self['Title'].strip() <NEW_LINE> if ' ' not in title: <NEW_LINE> <INDENT> return title <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ''.join(list(filter(str.isupper, title.title())))
Store and manipulate data from a single Zotero record.
62599062a8ecb0332587290c
class NewlineNormalizer(object): <NEW_LINE> <INDENT> def __init__(self, wrapped_file): <NEW_LINE> <INDENT> self._wrapped_file = wrapped_file <NEW_LINE> self.name = getattr(wrapped_file, 'name', None) <NEW_LINE> <DEDENT> def read(self, *args): <NEW_LINE> <INDENT> return self._wrapped_file.read(*args).replace(b'\r\n', b'\n') <NEW_LINE> <DEDENT> def readline(self, *args): <NEW_LINE> <INDENT> return self._wrapped_file.readline(*args).replace(b'\r\n', b'\n') <NEW_LINE> <DEDENT> def readlines(self, *args): <NEW_LINE> <INDENT> return [line.rstrip(b'\r') for line in self._wrapped_file.readlines(*args)] <NEW_LINE> <DEDENT> def seek(self, *args): <NEW_LINE> <INDENT> return self._wrapped_file.seek(*args) <NEW_LINE> <DEDENT> def tell(self, *args): <NEW_LINE> <INDENT> return self._wrapped_file.tell(*args)
File wrapper that normalizes CRLF line endings.
625990623eb6a72ae038bd54
class MyList(list): <NEW_LINE> <INDENT> pass <NEW_LINE> def __init__(self, l=list(), call_tabs=True): <NEW_LINE> <INDENT> self.call_tabs = call_tabs <NEW_LINE> super().__init__(l)
list class which accepts all dynamic attributes: >>> l = MyList((1, 3, 4)) >>> l [1, 3, 4] >>> l.foo = 5 >>> l.foo 5
6259906299cbb53fe68325d7
class ProyectosTable(tables.Table): <NEW_LINE> <INDENT> def render_titulo(self, record): <NEW_LINE> <INDENT> enlace = reverse('proyecto_detail', args=[record.id]) <NEW_LINE> return mark_safe(f'<a href="{enlace}">{record.titulo}</a>') <NEW_LINE> <DEDENT> coordinadores = tables.Column( empty_values=(), orderable=False, verbose_name=_('Coordinador(es)') ) <NEW_LINE> def render_coordinadores(self, record): <NEW_LINE> <INDENT> coordinadores = record.get_coordinadores() <NEW_LINE> enlaces = [f'<a href="mailto:{c.email}">{c.full_name}</a>' for c in coordinadores] <NEW_LINE> return mark_safe(', '.join(enlaces)) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> attrs = {'class': 'table table-striped table-hover cabecera-azul'} <NEW_LINE> model = Proyecto <NEW_LINE> fields = ('programa', 'linea', 'id', 'titulo', 'coordinadores', 'estado') <NEW_LINE> empty_text = _('Por el momento no se ha introducido ninguna solicitud de proyecto.') <NEW_LINE> template_name = 'django_tables2/bootstrap4.html' <NEW_LINE> per_page = 20
Muestra las solicitudes de proyecto introducidas.
62599062796e427e5384fe6a
@functools.total_ordering <NEW_LINE> class AccountMeta: <NEW_LINE> <INDENT> def __init__( self, public_key: PublicKey, is_signer: Optional[bool] = False, is_writable: Optional[bool] = False, is_payer: Optional[bool] = False, is_program: Optional[bool] = False, ): <NEW_LINE> <INDENT> self.public_key = public_key <NEW_LINE> self.is_signer = is_signer <NEW_LINE> self.is_writable = is_writable <NEW_LINE> self.is_payer = is_payer <NEW_LINE> self.is_program = is_program <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AccountMeta): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return (self.public_key == other.public_key and self.is_signer == other.is_signer and self.is_writable == other.is_writable and self.is_payer == other.is_payer and self.is_program and other.is_program) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new(cls, pub: PublicKey, is_signer: bool) -> 'AccountMeta': <NEW_LINE> <INDENT> return cls(pub, is_signer=is_signer, is_writable=True) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new_read_only(cls, pub: PublicKey, is_signer: bool) -> 'AccountMeta': <NEW_LINE> <INDENT> return cls(pub, is_signer=is_signer, is_writable=False) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AccountMeta): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> if self.is_payer is not other.is_payer: <NEW_LINE> <INDENT> return self.is_payer <NEW_LINE> <DEDENT> if self.is_program != other.is_program: <NEW_LINE> <INDENT> return not self.is_program <NEW_LINE> <DEDENT> if self.is_signer != other.is_signer: <NEW_LINE> <INDENT> return self.is_signer <NEW_LINE> <DEDENT> if self.is_writable != other.is_writable: <NEW_LINE> <INDENT> return self.is_writable <NEW_LINE> <DEDENT> return False
Represents the account information required for building transactions.
62599062460517430c432bce
class Manipulations: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def replaceRule(oldRule: Rule, newRule: Rule) -> Rule: <NEW_LINE> <INDENT> for par in oldRule.from_symbols: <NEW_LINE> <INDENT> par._set_to_rule(newRule) <NEW_LINE> newRule._from_symbols.append(par) <NEW_LINE> <DEDENT> for ch in oldRule.to_symbols: <NEW_LINE> <INDENT> ch._set_from_rule(newRule) <NEW_LINE> newRule._to_symbols.append(ch) <NEW_LINE> <DEDENT> return newRule <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def replaceNode(oldNode: Nonterminal, newNode: Nonterminal): <NEW_LINE> <INDENT> if oldNode.from_rule is not None and len(oldNode.from_rule.to_symbols) > 0: <NEW_LINE> <INDENT> indexParent = oldNode.from_rule.to_symbols.index(oldNode) <NEW_LINE> oldNode.from_rule.to_symbols[indexParent] = newNode <NEW_LINE> newNode._set_from_rule(oldNode.from_rule) <NEW_LINE> <DEDENT> if oldNode.to_rule is not None and len(oldNode.to_rule.from_symbols) > 0: <NEW_LINE> <INDENT> indexChild = oldNode.to_rule.from_symbols.index(oldNode) <NEW_LINE> oldNode.to_rule._from_symbols[indexChild] = newNode <NEW_LINE> newNode._set_to_rule(oldNode.to_rule) <NEW_LINE> <DEDENT> return newNode <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def replace(oldEl, newEl): <NEW_LINE> <INDENT> if isinstance(oldEl, Rule): <NEW_LINE> <INDENT> return Manipulations.replaceRule(oldEl, newEl) <NEW_LINE> <DEDENT> if isinstance(oldEl, (Nonterminal, Terminal)): <NEW_LINE> <INDENT> return Manipulations.replaceNode(oldEl, newEl)
Class that associate function modifying AST
625990622c8b7c6e89bd4ee4
class Hsts_base: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._input_dict = {} <NEW_LINE> self._arguments = [] <NEW_LINE> self._instance = Https() <NEW_LINE> self._output_dict = {} <NEW_LINE> self._mitigations = {} <NEW_LINE> self._set_arguments() <NEW_LINE> self.__logging = self._get_logger() <NEW_LINE> <DEDENT> def _get_logger(self): <NEW_LINE> <INDENT> raise NotImplementedError("This method should be reimplemented!") <NEW_LINE> <DEDENT> def input(self, **kwargs): <NEW_LINE> <INDENT> self._input_dict = kwargs <NEW_LINE> <DEDENT> def _set_mitigations(self, result: dict, key: str, condition: bool) -> dict: <NEW_LINE> <INDENT> if condition: <NEW_LINE> <INDENT> result["mitigation"] = load_mitigation( key, raise_error=False ) <NEW_LINE> <DEDENT> return result if condition else {} <NEW_LINE> <DEDENT> def _set_arguments(self): <NEW_LINE> <INDENT> raise NotImplementedError("This method should be reimplemented!") <NEW_LINE> <DEDENT> def _worker(self, results): <NEW_LINE> <INDENT> raise NotImplementedError("This method should be reimplemented!") <NEW_LINE> <DEDENT> def _get_var_name(self): <NEW_LINE> <INDENT> if self._arguments == self._instance.HTTPS: <NEW_LINE> <INDENT> key = "HTTPS_NOT_ENFORCED" <NEW_LINE> <DEDENT> elif self._arguments == self._instance.HSTSSET: <NEW_LINE> <INDENT> key = "HSTS_NOT_SET" <NEW_LINE> <DEDENT> elif self._arguments == self._instance.HSTSPRELOAD: <NEW_LINE> <INDENT> key = "HSTS_NOT_PRELOADED" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key = "SERVERINFO" <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> def _obtain_results(self, results: bool or str): <NEW_LINE> <INDENT> Validator( [ (results, (bool, str)), ] ) <NEW_LINE> results = not results <NEW_LINE> conditioned_result = {self._input_dict["hostname"]: results} <NEW_LINE> key = self._get_var_name() <NEW_LINE> if self._arguments != self._instance.SERVERINFO and isinstance(results, bool): <NEW_LINE> <INDENT> conditioned_result = self._set_mitigations(conditioned_result, key, results) <NEW_LINE> <DEDENT> out = {key: conditioned_result} <NEW_LINE> return out <NEW_LINE> <DEDENT> def run(self, **kwargs): <NEW_LINE> <INDENT> self.input(**kwargs) <NEW_LINE> if "hostname" not in kwargs: <NEW_LINE> <INDENT> raise AssertionError("Hostname is missing!") <NEW_LINE> <DEDENT> Validator([(self._input_dict["hostname"], str)]) <NEW_LINE> self._input_dict["hostname"] = url_domain(self._input_dict["hostname"]) <NEW_LINE> self.__logging.debug( f"Executing analysis in {self._input_dict['hostname']} with args {self._arguments}" ) <NEW_LINE> self._output_dict = self._worker( self._instance.run( hostname=self._input_dict["hostname"], port=self._input_dict["port"], type=self._arguments, force=self._input_dict.get("force", True), ) ) <NEW_LINE> return self.output() <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return self._output_dict
Hsts_base is the base class for all HSTS analysis. It is used to obtain the results of the analysis.
62599062d268445f2663a6d7
class IsRAuthenticated(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return bool(request.user and request.user.is_active)
Allows access only to authenticated users.
6259906363d6d428bbee3e03
class Start(object): <NEW_LINE> <INDENT> def index(self): <NEW_LINE> <INDENT> product_id = Config.get_config(Config.FIELD_PRODUCT_ID) <NEW_LINE> client_id = Config.get_config(Config.FIELD_CLIENT_ID) <NEW_LINE> scope_data = json.dumps( {"alexa:all": { "productID": product_id, "productInstanceAttributes": { "deviceSerialNumber": "001"} }} ) <NEW_LINE> callback = cherrypy.url() + "code" <NEW_LINE> payload = { "client_id": client_id, "scope": "alexa:all", "scope_data": scope_data, "response_type": "code", "redirect_uri": callback } <NEW_LINE> req = requests.Request( 'GET', AlexaService.AMAZON_BASE_URL, params=payload ) <NEW_LINE> raise cherrypy.HTTPRedirect(req.prepare().url) <NEW_LINE> <DEDENT> def code(self, var=None, **params): <NEW_LINE> <INDENT> client_id = Config.get_config(Config.FIELD_CLIENT_ID) <NEW_LINE> client_secret = Config.get_config(Config.FIELD_CLIENT_SECRET) <NEW_LINE> code = urllib.quote(cherrypy.request.params['code']) <NEW_LINE> callback = cherrypy.url() <NEW_LINE> payload = { "client_id" : client_id, "client_secret" : client_secret, "code" : code, "grant_type" : "authorization_code", "redirect_uri" : callback } <NEW_LINE> result = requests.post(AlexaService.AMAZON_TOKEN_URL, data=payload) <NEW_LINE> result = result.json() <NEW_LINE> Config.save_config( Config.FIELD_REFRESH_TOKEN, format(result['refresh_token']) ) <NEW_LINE> Config.save_config(Config.FIELD_ACCESS_TOKEN, "") <NEW_LINE> html = "<b>Success!</b><br/>" <NEW_LINE> html += "Refresh token has been added to your credentials file.<br/>" <NEW_LINE> html += "You may now reboot the Pi or restart the service.<br/>" <NEW_LINE> html += "Your token: %s" % result['refresh_token'] <NEW_LINE> return html <NEW_LINE> <DEDENT> index.exposed = True <NEW_LINE> code.exposed = True
The Web object
62599063009cb60464d02c2d
class TestModuleTools(unittest.TestCase): <NEW_LINE> <INDENT> def test_map(self): <NEW_LINE> <INDENT> self.assertEqual(map(1, 0, 2, 0, 10), 5.0) <NEW_LINE> self.assertEqual(map(30, 0, 180, 0, math.pi), 0.5235987755982988) <NEW_LINE> with self.assertRaises(ValueError): map(1, 1, 1, 0, 10)
Unit test for the ``tools`` module.
625990634428ac0f6e659c29
class Block(_messages.Message): <NEW_LINE> <INDENT> class BlockTypeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> UNKNOWN = 0 <NEW_LINE> TEXT = 1 <NEW_LINE> TABLE = 2 <NEW_LINE> PICTURE = 3 <NEW_LINE> RULER = 4 <NEW_LINE> BARCODE = 5 <NEW_LINE> <DEDENT> blockType = _messages.EnumField('BlockTypeValueValuesEnum', 1) <NEW_LINE> boundingBox = _messages.MessageField('BoundingPoly', 2) <NEW_LINE> confidence = _messages.FloatField(3, variant=_messages.Variant.FLOAT) <NEW_LINE> paragraphs = _messages.MessageField('Paragraph', 4, repeated=True) <NEW_LINE> property = _messages.MessageField('TextProperty', 5)
Logical element on the page. Enums: BlockTypeValueValuesEnum: Detected block type (text, image etc) for this block. Fields: blockType: Detected block type (text, image etc) for this block. boundingBox: The bounding box for the block. The vertices are in the order of top-left, top-right, bottom-right, bottom-left. When a rotation of the bounding box is detected the rotation is represented as around the top-left corner as defined when the text is read in the 'natural' orientation. For example: * when the text is horizontal it might look like: 0----1 | | 3----2 * when it's rotated 180 degrees around the top-left corner it becomes: 2----3 | | 1----0 and the vertex order will still be (0, 1, 2, 3). confidence: Confidence of the OCR results on the block. Range [0, 1]. paragraphs: List of paragraphs in this block (if this blocks is of type text). property: Additional information detected for the block.
62599063cc0a2c111447c64a
class NetsBoot(object): <NEW_LINE> <INDENT> def __init__(self, io, filename): <NEW_LINE> <INDENT> self.io = io <NEW_LINE> self.filename = filename <NEW_LINE> self._clear() <NEW_LINE> self._open() <NEW_LINE> <DEDENT> def _clear(self): <NEW_LINE> <INDENT> self.lines = [] <NEW_LINE> <DEDENT> def _open(self): <NEW_LINE> <INDENT> self._clear() <NEW_LINE> if self.io.exists(self.filename): <NEW_LINE> <INDENT> with self.io.open(self.filename, 'r') as f: <NEW_LINE> <INDENT> for line in f.readlines(): <NEW_LINE> <INDENT> self.lines.append(line.strip()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _generate(self): <NEW_LINE> <INDENT> return '\n'.join(self.lines) <NEW_LINE> <DEDENT> def add(self, net): <NEW_LINE> <INDENT> if net not in self.lines: <NEW_LINE> <INDENT> self.lines.append(net) <NEW_LINE> <DEDENT> <DEDENT> def remove(self, net): <NEW_LINE> <INDENT> self.lines.remove(net) <NEW_LINE> <DEDENT> @property <NEW_LINE> def nets(self): <NEW_LINE> <INDENT> return [line for line in self.lines if line and not line.startswith('#')] <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> with self.io.open(self.filename, 'w') as f: <NEW_LINE> <INDENT> f.write(self._generate()) <NEW_LINE> f.write('\n')
Extremely simple parser for /etc/tinc/nets.boot This simply reads all lines into a list (this also includes comments). Adding a network via ``add`` avoids duplicate entries.
62599063e76e3b2f99fda0f6
@implementer(IRequestLogger) <NEW_LINE> class ResolvingLogger(object): <NEW_LINE> <INDENT> def __init__(self, resolver, logger): <NEW_LINE> <INDENT> self.resolver = resolver <NEW_LINE> self.logger = logger <NEW_LINE> <DEDENT> class logger_thunk(object): <NEW_LINE> <INDENT> def __init__(self, message, logger): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.logger = logger <NEW_LINE> <DEDENT> def __call__(self, host, ttl, answer): <NEW_LINE> <INDENT> if not answer: <NEW_LINE> <INDENT> answer = host <NEW_LINE> <DEDENT> self.logger.logMessage('%s%s' % (answer, self.message)) <NEW_LINE> <DEDENT> <DEDENT> def logRequest(self, ip, message): <NEW_LINE> <INDENT> self.resolver.resolve_ptr( ip, self.logger_thunk( message, self.logger ) )
Feed (ip, message) combinations into this logger to get a resolved hostname in front of the message. The message will not be logged until the PTR request finishes (or fails).
625990637047854f46340ab4
class ForumExample(object): <NEW_LINE> <INDENT> def __init__(self, qas_id, question_text, doc_tokens, orig_answer_text=None, start_position=None, end_position=None, is_impossible=False): <NEW_LINE> <INDENT> self.qas_id = qas_id <NEW_LINE> self.question_text = question_text <NEW_LINE> self.doc_tokens = doc_tokens <NEW_LINE> self.orig_answer_text = orig_answer_text <NEW_LINE> self.start_position = start_position <NEW_LINE> self.end_position = end_position <NEW_LINE> self.is_impossible = is_impossible <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = "" <NEW_LINE> s += "qas_id: %s" % (tokenization.printable_text(self.qas_id)) <NEW_LINE> s += ", question_text: %s" % ( tokenization.printable_text(self.question_text)) <NEW_LINE> if self.start_position: <NEW_LINE> <INDENT> s += ", start_position: %d" % (self.start_position) <NEW_LINE> <DEDENT> if self.start_position: <NEW_LINE> <INDENT> s += ", end_position: %d" % (self.end_position) <NEW_LINE> <DEDENT> if self.start_position: <NEW_LINE> <INDENT> s += ", is_impossible: %r" % (self.is_impossible) <NEW_LINE> <DEDENT> return s
A single training/test example for simple sequence classification. For examples without an answer, the start and end position are -1.
625990639c8ee82313040d03
class RegressionTrainer(SupervisedTrainer, Proxy): <NEW_LINE> <INDENT> def __init__(self, proxy, multiple_labels=False, accepts_matrix=False): <NEW_LINE> <INDENT> self.multiple_labels = multiple_labels <NEW_LINE> self.accepts_matrix = accepts_matrix <NEW_LINE> Proxy.__init__(self, proxy) <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> if isinstance(X, Cache): <NEW_LINE> <INDENT> if y is not None: <NEW_LINE> <INDENT> raise Exception("Second argument (y) is unexpected in case the first parameters is cache.") <NEW_LINE> <DEDENT> return self.fit_on_cache(X) <NEW_LINE> <DEDENT> X = np.array(X) <NEW_LINE> y = np.array(y) <NEW_LINE> if X.ndim == 1: <NEW_LINE> <INDENT> X = X.reshape(X.shape[0], 1) <NEW_LINE> <DEDENT> elif X.ndim > 2: <NEW_LINE> <INDENT> raise Exception("X has unexpected dimension [dim=%d]" % X.ndim) <NEW_LINE> <DEDENT> if y.ndim == 1: <NEW_LINE> <INDENT> y = y.reshape(y.shape[0], 1) <NEW_LINE> <DEDENT> elif y.ndim > 2: <NEW_LINE> <INDENT> raise Exception("y has unexpected dimension [dim=%d]" % y.ndim) <NEW_LINE> <DEDENT> X_java = Utils.to_java_double_array(X) <NEW_LINE> if self.multiple_labels: <NEW_LINE> <INDENT> y_java = Utils.to_java_double_array(y) <NEW_LINE> java_model = self.proxy.fit(X_java, y_java, None) <NEW_LINE> return Model(java_model, self.accepts_matrix) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> java_models = [] <NEW_LINE> for i in range(y.shape[1]): <NEW_LINE> <INDENT> y_java = Utils.to_java_double_array(y[:,i]) <NEW_LINE> java_model = self.proxy.fit(X_java, y_java, None) <NEW_LINE> java_models.append(java_model) <NEW_LINE> <DEDENT> return Model(java_models, self.accepts_matrix) <NEW_LINE> <DEDENT> <DEDENT> def fit_on_cache(self, cache): <NEW_LINE> <INDENT> if not isinstance(cache, Cache): <NEW_LINE> <INDENT> raise Exception("Unexpected type of cache (%s)." % type(cache)) <NEW_LINE> <DEDENT> java_model = self.proxy.fitOnCache(cache.proxy, cache.cache_filter, Proxy.proxy_or_none(cache.preprocessor)) <NEW_LINE> return Model(java_model, self.accepts_matrix)
Regression.
62599063435de62698e9d4fe
class Solution: <NEW_LINE> <INDENT> def deduplication(self, nums): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> if n == 0 : <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> nums.sort() <NEW_LINE> res = 1 <NEW_LINE> for i in range(1, n) : <NEW_LINE> <INDENT> if nums[i-1] != nums[i] : <NEW_LINE> <INDENT> nums[res] = nums[i] <NEW_LINE> res += 1 <NEW_LINE> <DEDENT> <DEDENT> return res
@param nums: an array of integers @return: the number of unique integers
62599063d486a94d0ba2d6bf
class unitTests(unittest.TestCase): <NEW_LINE> <INDENT> def testSearch(self): <NEW_LINE> <INDENT> root = Node(5) <NEW_LINE> node2 = Node(2) <NEW_LINE> node21 = Node(21) <NEW_LINE> nodeNeg4 = Node(-4) <NEW_LINE> node3 = Node(3) <NEW_LINE> node19 = Node(19) <NEW_LINE> node25 = Node(25) <NEW_LINE> root.setLeft(node2) <NEW_LINE> root.setRight(node21) <NEW_LINE> node2.setLeft(nodeNeg4) <NEW_LINE> node2.setRight(node3) <NEW_LINE> node21.setLeft(node19) <NEW_LINE> node21.setRight(node25) <NEW_LINE> print("setup complete.") <NEW_LINE> out = StringIO() <NEW_LINE> sys.stdout = out <NEW_LINE> root.search(3) <NEW_LINE> output = out.getvalue().strip() <NEW_LINE> self.assertEqual(output, 'left 3 right 3 node = to 3') <NEW_LINE> <DEDENT> def testNodeRef2(self): <NEW_LINE> <INDENT> root = Node(5) <NEW_LINE> node2 = Node(2) <NEW_LINE> node21 = Node(21) <NEW_LINE> nodeNeg4 = Node(-4) <NEW_LINE> node3 = Node(3) <NEW_LINE> node19 = Node(19) <NEW_LINE> node25 = Node(25) <NEW_LINE> root.setLeft(node2) <NEW_LINE> root.setRight(node21) <NEW_LINE> node2.setLeft(nodeNeg4) <NEW_LINE> node2.setRight(node3) <NEW_LINE> node21.setLeft(node19) <NEW_LINE> node21.setRight(node25) <NEW_LINE> print("setup complete.") <NEW_LINE> out = StringIO() <NEW_LINE> sys.stdout = out <NEW_LINE> root.search(15) <NEW_LINE> output = out.getvalue().strip() <NEW_LINE> self.assertEqual(output, 'right 15 left 15 left 15 NONE LEFT')
docstring for ClassName
6259906355399d3f05627c16
class User(AbstractEmailUser, BaseModel): <NEW_LINE> <INDENT> roll_no = models.IntegerField( blank=True, null=True ) <NEW_LINE> middle_name = models.CharField( max_length=100, blank = True, null=True ) <NEW_LINE> address = models.TextField( max_length=500, blank = True ) <NEW_LINE> description = models.TextField( max_length=500, blank = True ) <NEW_LINE> batch_year = models.IntegerField( blank=True, null=True ) <NEW_LINE> contact = models.CharField( validators=[RegexValidator( regex='^[0-9]{10}$', message='Length has to be 10', code='nomatch')], null=True, blank=True, max_length=12, ) <NEW_LINE> placed_in = models.CharField( default=None, max_length=100, null=True )
This model User holds the information about the registering User
625990634f88993c371f109a
class Eclipse(Makefile): <NEW_LINE> <INDENT> def generate(self): <NEW_LINE> <INDENT> super(Eclipse, self).generate() <NEW_LINE> ctx = { 'name': self.project_name, 'elf_location': join('BUILD',self.project_name)+'.elf', 'c_symbols': self.toolchain.get_symbols(), 'asm_symbols': self.toolchain.get_symbols(True), 'target': self.target, 'include_paths': self.resources.inc_dirs, 'load_exe': str(self.LOAD_EXE).lower() } <NEW_LINE> if not exists(join(self.export_dir,'eclipse-extras')): <NEW_LINE> <INDENT> makedirs(join(self.export_dir,'eclipse-extras')) <NEW_LINE> <DEDENT> self.gen_file('cdt/pyocd_settings.tmpl', ctx, join('eclipse-extras',self.target+'_pyocd_settings.launch')) <NEW_LINE> self.gen_file('cdt/necessary_software.tmpl', ctx, join('eclipse-extras','necessary_software.p2f')) <NEW_LINE> self.gen_file('cdt/.cproject.tmpl', ctx, '.cproject') <NEW_LINE> self.gen_file('cdt/.project.tmpl', ctx, '.project')
Generic Eclipse project. Intended to be subclassed by classes that specify a type of Makefile.
62599063009cb60464d02c2e
class DbVersion(BaseApp): <NEW_LINE> <INDENT> name = 'db_version' <NEW_LINE> @classmethod <NEW_LINE> def add_argument_parser(cls, subparsers): <NEW_LINE> <INDENT> parser = super(DbVersion, cls).add_argument_parser(subparsers) <NEW_LINE> parser.add_argument('--extension', default=None, help=('Migrate the database for the specified ' 'extension. If not provided, db_sync will ' 'migrate the common repository.')) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def main(): <NEW_LINE> <INDENT> extension = CONF.command.extension <NEW_LINE> if extension: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> package_name = ("%s.%s.migrate_repo" % (contrib.__name__, extension)) <NEW_LINE> package = importutils.import_module(package_name) <NEW_LINE> repo_path = os.path.abspath(os.path.dirname(package.__file__)) <NEW_LINE> print(migration.db_version(repo_path)) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> print(_("This extension does not provide migrations.")) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print(migration.db_version())
Print the current migration version of the database.
62599063a8ecb0332587290e
class JSONB(TYPECAST): <NEW_LINE> <INDENT> cast = "::jsonb"
Cast to JSONB
6259906332920d7e50bc773d
class AlwaysTrue(Dependency): <NEW_LINE> <INDENT> def should_build(self): <NEW_LINE> <INDENT> return True
Always rebuild the task.
625990630c0af96317c578da
class Playlist(object): <NEW_LINE> <INDENT> def __init__(self, username, spotify_instance, playlist_details): <NEW_LINE> <INDENT> self._logger = logging.getLogger('{base}.{suffix}' .format(base=LOGGER_BASENAME, suffix=self.__class__.__name__) ) <NEW_LINE> self._username = username <NEW_LINE> self._spotify = spotify_instance <NEW_LINE> self._playlist_details = playlist_details <NEW_LINE> <DEDENT> @property <NEW_LINE> def tracks(self): <NEW_LINE> <INDENT> songs_playlist = self._spotify.user_playlist_tracks(user=self._username, playlist_id=self.playlist_id) <NEW_LINE> return [Track(track.get('track')) for track in songs_playlist.get('items')] <NEW_LINE> <DEDENT> def delete_all_tracks(self): <NEW_LINE> <INDENT> track_ids = [track.track_id for track in self.tracks] <NEW_LINE> return self._spotify.user_playlist_remove_all_occurrences_of_tracks(self._username, self.playlist_id, track_ids) <NEW_LINE> <DEDENT> def add_track(self, track_id): <NEW_LINE> <INDENT> self._logger.info("Adding song %s", track_id) <NEW_LINE> self._spotify.user_playlist_add_tracks(user=self._username, playlist_id=self.uri, tracks=[track_id]) <NEW_LINE> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def href(self): <NEW_LINE> <INDENT> return self._playlist_details.get('href', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def collaborative(self): <NEW_LINE> <INDENT> return self._playlist_details.get('collaborative', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def playlist_id(self): <NEW_LINE> <INDENT> return self._playlist_details.get('id', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._playlist_details.get('name', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def public(self): <NEW_LINE> <INDENT> return self._playlist_details.get('public', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def uri(self): <NEW_LINE> <INDENT> return self._playlist_details.get('uri', None)
Playlist model
625990638da39b475be048df
class PostPost(View): <NEW_LINE> <INDENT> def post(self, request, username): <NEW_LINE> <INDENT> form = PostForm(self.request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> user = User.objects.get(username=username) <NEW_LINE> post = Post(text = form.cleaned_data['text'], user = user) <NEW_LINE> post.save() <NEW_LINE> words = form.cleaned_data['text'].split(" ") <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if word.startswith('#'): <NEW_LINE> <INDENT> hash_tag, created = HashTag.objects.get_or_create(name=word) <NEW_LINE> hash_tag.post.add(post) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return HttpResponseRedirect('/user/'+username)
Create Post View
62599063442bda511e95d8d5
class GhArtifactList(MetadataMap): <NEW_LINE> <INDENT> def __init__(self, metadata): <NEW_LINE> <INDENT> super().__init__(metadata) <NEW_LINE> self._artifact_item_list = [] <NEW_LINE> for artifact in self._metadata['artifacts']: <NEW_LINE> <INDENT> self._artifact_item_list.append(GhArtifactItem(artifact)) <NEW_LINE> <DEDENT> <DEDENT> def artifact_item_list(self): <NEW_LINE> <INDENT> return self._artifact_item_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def hdr(): <NEW_LINE> <INDENT> return '{:>10} {:>12} {:>20} {:<25}'.format('id', 'size', 'create date/time', 'name') <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._artifact_item_list.__iter__() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._artifact_item_list) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'GhArtifactList(num_artifacts={})'.format(len(self._artifact_item_list))
List of GitHub artifacts associated with a workflow
6259906366673b3332c31af3
class BasePage(BaseContentType): <NEW_LINE> <INDENT> def __init__(self, page, *args, **kwargs): <NEW_LINE> <INDENT> super(BasePage, self).__init__(*args, **kwargs) <NEW_LINE> self._data_model = page <NEW_LINE> self._template = 'page.html' <NEW_LINE> <DEDENT> def _get_html_data(self): <NEW_LINE> <INDENT> data = {C.HTML_DATA_TAG_KEY_URL : self.get_absolute_url(), C.HTML_DATA_TAG_KEY_NAME : self._data_model.name} <NEW_LINE> return data <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return self._data_model.get_absolute_url() <NEW_LINE> <DEDENT> def breadcrumbs(self): <NEW_LINE> <INDENT> breadcrumbs = pagelets.BreadCrumbPaglet(request=self.request, request_kwargs=self.request_kwargs) <NEW_LINE> breadcrumbs.append(self._data_model.module.title, self._data_model.module.get_absolute_url()) <NEW_LINE> breadcrumbs.append(self._data_model.title, self._data_model.get_absolute_url()) <NEW_LINE> return breadcrumbs.markup()
Base Page object to extend when creating different types of pages
625990632ae34c7f260ac7de
@p.toolkit.blanket.config_declarations <NEW_LINE> class TextView(p.SingletonPlugin): <NEW_LINE> <INDENT> p.implements(p.IConfigurer, inherit=True) <NEW_LINE> p.implements(p.IConfigurable, inherit=True) <NEW_LINE> p.implements(p.IResourceView, inherit=True) <NEW_LINE> proxy_is_enabled = False <NEW_LINE> text_formats = [] <NEW_LINE> xml_formats = [] <NEW_LINE> json_formats = [] <NEW_LINE> jsonp_formats = [] <NEW_LINE> no_jsonp_formats = [] <NEW_LINE> def update_config(self, config: CKANConfig): <NEW_LINE> <INDENT> formats = get_formats(config) <NEW_LINE> for key, value in formats.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> self.no_jsonp_formats = (self.text_formats + self.xml_formats + self.json_formats) <NEW_LINE> p.toolkit.add_public_directory(config, 'theme/public') <NEW_LINE> p.toolkit.add_template_directory(config, 'theme/templates') <NEW_LINE> p.toolkit.add_resource('theme/public', 'ckanext-textview') <NEW_LINE> <DEDENT> def info(self): <NEW_LINE> <INDENT> return {'name': 'text_view', 'title': p.toolkit._('Text'), 'icon': 'file-text-o', 'default_title': p.toolkit._('Text'), } <NEW_LINE> <DEDENT> def can_view(self, data_dict: dict[str, Any]): <NEW_LINE> <INDENT> resource = data_dict['resource'] <NEW_LINE> format_lower = resource.get('format', '').lower() <NEW_LINE> proxy_enabled = p.plugin_loaded('resource_proxy') <NEW_LINE> same_domain = datapreview.on_same_domain(data_dict) <NEW_LINE> if format_lower in self.jsonp_formats: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if format_lower in self.no_jsonp_formats: <NEW_LINE> <INDENT> return proxy_enabled or same_domain <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def setup_template_variables(self, context: Context, data_dict: dict[str, Any]): <NEW_LINE> <INDENT> metadata = {'text_formats': self.text_formats, 'json_formats': self.json_formats, 'jsonp_formats': self.jsonp_formats, 'xml_formats': self.xml_formats} <NEW_LINE> url = proxy.get_proxified_resource_url(data_dict) <NEW_LINE> format_lower = data_dict['resource']['format'].lower() <NEW_LINE> if format_lower in self.jsonp_formats: <NEW_LINE> <INDENT> url = data_dict['resource']['url'] <NEW_LINE> <DEDENT> return {'preview_metadata': json.dumps(metadata), 'resource_json': json.dumps(data_dict['resource']), 'resource_url': json.dumps(url)} <NEW_LINE> <DEDENT> def view_template(self, context: Context, data_dict: dict[str, Any]): <NEW_LINE> <INDENT> return 'text_view.html' <NEW_LINE> <DEDENT> def form_template(self, context: Context, data_dict: dict[str, Any]): <NEW_LINE> <INDENT> return 'text_form.html'
This extension previews JSON(P).
62599063a79ad1619776b638
class TestFillHandlebarFormField(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 testFillHandlebarFormField(self): <NEW_LINE> <INDENT> pass
FillHandlebarFormField unit test stubs
62599063be8e80087fbc077e
class InternalError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, original_exception=None, *args): <NEW_LINE> <INDENT> self.args = (msg, original_exception) + args <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s\nOriginal message:\n%s" % self.args[:2]
I am raised whenever a backend encounters an internal error. I wrap the original exception, if any, as my second argument.
625990638e7ae83300eea785
class Port(model_base.BASEV2, HasId, HasTenant): <NEW_LINE> <INDENT> name = sa.Column(sa.String(255)) <NEW_LINE> network_id = sa.Column(sa.String(36), sa.ForeignKey("networks.id"), nullable=False) <NEW_LINE> fixed_ips = orm.relationship(IPAllocation, backref='ports', lazy='joined') <NEW_LINE> mac_address = sa.Column(sa.String(32), nullable=False) <NEW_LINE> admin_state_up = sa.Column(sa.Boolean(), nullable=False) <NEW_LINE> status = sa.Column(sa.String(16), nullable=False) <NEW_LINE> device_id = sa.Column(sa.String(255), nullable=False) <NEW_LINE> device_owner = sa.Column(sa.String(255), nullable=False) <NEW_LINE> def __init__(self, id=None, tenant_id=None, name=None, network_id=None, mac_address=None, admin_state_up=None, status=None, device_id=None, device_owner=None, fixed_ips=None): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.tenant_id = tenant_id <NEW_LINE> self.name = name <NEW_LINE> self.network_id = network_id <NEW_LINE> self.mac_address = mac_address <NEW_LINE> self.admin_state_up = admin_state_up <NEW_LINE> self.device_owner = device_owner <NEW_LINE> self.device_id = device_id <NEW_LINE> if fixed_ips: <NEW_LINE> <INDENT> self.fixed_ips = fixed_ips <NEW_LINE> <DEDENT> self.status = status
Represents a port on a Neutron v2 network.
62599063a8370b77170f1ac5
class UpsampleSkeletonsBase(luigi.Task): <NEW_LINE> <INDENT> task_name = 'upsample_skeletons' <NEW_LINE> src_file = os.path.abspath(__file__) <NEW_LINE> allow_retry = False <NEW_LINE> input_path = luigi.Parameter() <NEW_LINE> input_key = luigi.Parameter() <NEW_LINE> skeleton_path = luigi.Parameter() <NEW_LINE> skeleton_key = luigi.Parameter() <NEW_LINE> output_path = luigi.Parameter() <NEW_LINE> output_key = luigi.Parameter() <NEW_LINE> dependency = luigi.TaskParameter() <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return self.dependency <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def default_task_config(): <NEW_LINE> <INDENT> config = LocalTask.default_task_config() <NEW_LINE> config.update({'halo': None, 'pixel_pitch': None}) <NEW_LINE> return config <NEW_LINE> <DEDENT> def run_impl(self): <NEW_LINE> <INDENT> shebang, block_shape, roi_begin, roi_end = self.global_config_values() <NEW_LINE> self.init(shebang) <NEW_LINE> with vu.file_reader(self.input_path, 'r') as f: <NEW_LINE> <INDENT> shape = f[self.input_key].shape <NEW_LINE> <DEDENT> task_config = self.get_task_config() <NEW_LINE> chunks = (25, 256, 256) <NEW_LINE> with vu.file_reader(self.output_path) as f: <NEW_LINE> <INDENT> f.require_dataset(self.output_key, shape=shape, chunks=chunks, compression='gzip', dtype='uint64') <NEW_LINE> <DEDENT> task_config.update({'input_path': self.input_path, 'input_key': self.input_key, 'skeleton_path': self.skeleton_path, 'skeleton_key': self.skeleton_key, 'output_path': self.output_path, 'output_key': self.output_key}) <NEW_LINE> if self.n_retries == 0: <NEW_LINE> <INDENT> block_list = vu.blocks_in_volume(shape, block_shape, roi_begin, roi_end) <NEW_LINE> self._write_log("scheduled %i blocks to run" % len(block_list)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> block_list = self.block_list <NEW_LINE> self.clean_up_for_retry(block_list) <NEW_LINE> <DEDENT> n_jobs = min(len(block_list), self.max_jobs) <NEW_LINE> self.prepare_jobs(n_jobs, block_list, task_config) <NEW_LINE> self.submit_jobs(n_jobs) <NEW_LINE> self.wait_for_jobs() <NEW_LINE> self.check_jobs(n_jobs)
UpsampleSkeletons base class
62599063498bea3a75a5917b
class LRFinder(Callback): <NEW_LINE> <INDENT> def __init__(self, lr_bounds:Tuple[float,float]=[1e-7, 10], nb:Optional[int]=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.lr_bounds,self.nb = lr_bounds,nb <NEW_LINE> if self.nb is not None: self.lr_mult = (self.lr_bounds[1]/self.lr_bounds[0])**(1/self.nb) <NEW_LINE> <DEDENT> def on_train_begin(self) -> None: <NEW_LINE> <INDENT> super().on_train_begin() <NEW_LINE> self.best,self.iter = math.inf,0 <NEW_LINE> self.model.set_lr(self.lr_bounds[0]) <NEW_LINE> self.history = {'loss': [], 'lr': []} <NEW_LINE> <DEDENT> def on_epoch_begin(self) -> None: <NEW_LINE> <INDENT> if self.model.fit_params.state != 'train': return <NEW_LINE> if self.nb is None: <NEW_LINE> <INDENT> self.nb = self.model.fit_params.n_epochs*np.sum([self.model.fit_params.fy.get_data_count(i)//self.model.fit_params.bs for i in self.model.fit_params.trn_idxs]) <NEW_LINE> self.lr_mult = (self.lr_bounds[1]/self.lr_bounds[0])**(1/self.nb) <NEW_LINE> <DEDENT> <DEDENT> def _calc_lr(self): return self.lr_bounds[0]*(self.lr_mult**self.iter) <NEW_LINE> def plot(self) -> None: <NEW_LINE> <INDENT> plot_lr_finders([self], loss_range='auto', settings=self.plot_settings, log_y='auto' if 'regress' in self.model.objective.lower() else False) <NEW_LINE> <DEDENT> def plot_lr(self) -> None: <NEW_LINE> <INDENT> with sns.axes_style(self.plot_settings.style), sns.color_palette(self.plot_settings.cat_palette): <NEW_LINE> <INDENT> plt.figure(figsize=(self.plot_settings.h_small, self.plot_settings.h_small)) <NEW_LINE> plt.plot(range(len(self.history['lr'])), self.history['lr']) <NEW_LINE> plt.xticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col) <NEW_LINE> plt.yticks(fontsize=self.plot_settings.tk_sz, color=self.plot_settings.tk_col) <NEW_LINE> plt.ylabel("Learning rate", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col) <NEW_LINE> plt.xlabel("Iterations", fontsize=self.plot_settings.lbl_sz, color=self.plot_settings.lbl_col) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> <DEDENT> def get_df(self) -> pd.DataFrame: <NEW_LINE> <INDENT> return pd.DataFrame({'LR': self.history['lr'], 'Loss': self.history['loss']}) <NEW_LINE> <DEDENT> def on_batch_end(self) -> None: <NEW_LINE> <INDENT> if self.model.fit_params.state != 'train': return <NEW_LINE> loss = self.model.fit_params.loss_val.data.item() <NEW_LINE> self.history['loss'].append(loss) <NEW_LINE> self.history['lr'].append(self.model.opt.param_groups[0]['lr']) <NEW_LINE> self.iter += 1 <NEW_LINE> lr = self._calc_lr() <NEW_LINE> self.model.opt.param_groups[0]['lr'] = lr <NEW_LINE> if math.isnan(loss) or loss > self.best*100 or lr > self.lr_bounds[1]: self.model.stop_train = True <NEW_LINE> if loss < self.best and self.iter > 10: self.best = loss
Callback class for Smith learning-rate range test (https://arxiv.org/abs/1803.09820) Arguments: nb: number of batches in a epoch lr_bounds: tuple of initial and final LR
62599063cc0a2c111447c64b
class AbortHandshake(InvalidHandshake): <NEW_LINE> <INDENT> def __init__(self, status, headers, body=None): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.headers = headers <NEW_LINE> self.body = body
Exception raised to abort a handshake and return a HTTP response.
6259906344b2445a339b74dc
class ImageProcessingTagEntity(ImageProcessingEntity): <NEW_LINE> <INDENT> def __init__(self, ip, port, camera_entity, name, confidence): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._url_check = "http://{}:{}/{}/check".format(ip, port, CLASSIFIER) <NEW_LINE> self._camera = camera_entity <NEW_LINE> if name: <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> camera_name = split_entity_id(camera_entity)[1] <NEW_LINE> self._name = "{} {}".format( CLASSIFIER, camera_name) <NEW_LINE> <DEDENT> self._confidence = confidence <NEW_LINE> self.tags = [] <NEW_LINE> self._matched = {} <NEW_LINE> <DEDENT> def process_image(self, image): <NEW_LINE> <INDENT> response = post_image(self._url_check, image) <NEW_LINE> if response is not None: <NEW_LINE> <INDENT> response_json = response.json() <NEW_LINE> if response_json['success']: <NEW_LINE> <INDENT> api_tags = response_json['tags'] + response_json['custom_tags'] <NEW_LINE> tags = parse_tags(api_tags) <NEW_LINE> self.process_tags(tags) <NEW_LINE> self._matched = get_matched_tags(tags, self.confidence) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.tags = [] <NEW_LINE> self._matched = {} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def confidence(self): <NEW_LINE> <INDENT> return self._confidence <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> state = None <NEW_LINE> if len(self._matched) > 0: <NEW_LINE> <INDENT> return self.tags[0][ATTR_NAME] <NEW_LINE> <DEDENT> return state <NEW_LINE> <DEDENT> def process_tags(self, tags): <NEW_LINE> <INDENT> run_callback_threadsafe( self.hass.loop, self.async_process_tags, tags).result() <NEW_LINE> <DEDENT> @callback <NEW_LINE> def async_process_tags(self, tags): <NEW_LINE> <INDENT> for tag in tags: <NEW_LINE> <INDENT> tag.update({ATTR_ENTITY_ID: self.entity_id}) <NEW_LINE> if tag[ATTR_CONFIDENCE] > self.confidence: <NEW_LINE> <INDENT> self.hass.async_add_job( self.hass.bus.async_fire, EVENT_DETECT_TAG, tag ) <NEW_LINE> <DEDENT> <DEDENT> self.tags = tags <NEW_LINE> <DEDENT> @property <NEW_LINE> def camera_entity(self): <NEW_LINE> <INDENT> return self._camera <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> return { 'tags': self.tags, 'total_tags': len(self.tags), 'matched_tags': self._matched, 'total_matched_tags': len(self._matched), }
Perform a tag search via a Tagbox.
625990638a43f66fc4bf3887
class ErrorsInFile: <NEW_LINE> <INDENT> def __init__(self, regionsLeftBoundaries=None, messages=None): <NEW_LINE> <INDENT> self.regionsLeftBoundaries = regionsLeftBoundaries <NEW_LINE> self.messages = messages
Holder of all errors/warnings in particular file.
62599063a219f33f346c7efe
class RowError(TableError): <NEW_LINE> <INDENT> code = "row-error" <NEW_LINE> name = "Row Error" <NEW_LINE> tags = ["#table", "#row"] <NEW_LINE> template = "Row Error" <NEW_LINE> description = "Row Error" <NEW_LINE> def __init__(self, descriptor=None, *, note, cells, row_number, row_position): <NEW_LINE> <INDENT> self.setinitial("cells", cells) <NEW_LINE> self.setinitial("rowNumber", row_number) <NEW_LINE> self.setinitial("rowPosition", row_position) <NEW_LINE> super().__init__(descriptor, note=note) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_row(cls, row, *, note): <NEW_LINE> <INDENT> to_str = lambda v: str(v) if v is not None else "" <NEW_LINE> return cls( note=note, cells=list(map(to_str, row.cells)), row_number=row.row_number, row_position=row.row_position, )
Row error representation Parameters: descriptor? (str|dict): error descriptor note (str): an error note row_number (int): row number row_position (int): row position Raises: FrictionlessException: raise any error that occurs during the process
62599063adb09d7d5dc0bc62
class Watchdog(object): <NEW_LINE> <INDENT> _RESTART_TIMEFRAME = 60 <NEW_LINE> def __init__(self, duration, max_mem_mb=None, max_resets=None): <NEW_LINE> <INDENT> import resource <NEW_LINE> self._duration = int(duration) <NEW_LINE> signal.signal(signal.SIGALRM, Watchdog.self_destruct) <NEW_LINE> if max_mem_mb is not None: <NEW_LINE> <INDENT> self._max_mem_kb = 1024 * max_mem_mb <NEW_LINE> max_mem_bytes = 1024 * self._max_mem_kb <NEW_LINE> resource.setrlimit(resource.RLIMIT_AS, (max_mem_bytes, max_mem_bytes)) <NEW_LINE> self.memory_limit_enabled = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.memory_limit_enabled = False <NEW_LINE> <DEDENT> self._restarts = deque([]) <NEW_LINE> self._max_resets = max_resets <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def self_destruct(signum, frame): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import traceback <NEW_LINE> log.error("Self-destructing...") <NEW_LINE> log.error(traceback.format_exc()) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.kill(os.getpid(), signal.SIGKILL) <NEW_LINE> <DEDENT> <DEDENT> def _is_frenetic(self): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> while(self._restarts and self._restarts[0] < now - self._RESTART_TIMEFRAME): <NEW_LINE> <INDENT> self._restarts.popleft() <NEW_LINE> <DEDENT> return len(self._restarts) > self._max_resets <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> if self.memory_limit_enabled: <NEW_LINE> <INDENT> mem_usage_kb = int(os.popen('ps -p %d -o %s | tail -1' % (os.getpid(), 'rss')).read()) <NEW_LINE> if mem_usage_kb > (0.95 * self._max_mem_kb): <NEW_LINE> <INDENT> Watchdog.self_destruct(signal.SIGKILL, sys._getframe(0)) <NEW_LINE> <DEDENT> <DEDENT> if self._max_resets: <NEW_LINE> <INDENT> self._restarts.append(time.time()) <NEW_LINE> if self._is_frenetic(): <NEW_LINE> <INDENT> Watchdog.self_destruct(signal.SIGKILL, sys._getframe(0)) <NEW_LINE> <DEDENT> <DEDENT> log.debug("Resetting watchdog for %d" % self._duration) <NEW_LINE> signal.alarm(self._duration)
Simple signal-based watchdog. Restarts the process when: * no reset was made for more than a specified duration * (optional) a specified memory threshold is exceeded * (optional) a suspicious high activity is detected, i.e. too many resets for a given timeframe. **Warning**: Not thread-safe. Can only be invoked once per process, so don't use with multiple threads. If you instantiate more than one, you're also asking for trouble.
625990634a966d76dd5f05ed
class IO: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def print_menu(): <NEW_LINE> <INDENT> print('Menu\n\n[l] load Inventory from file\n[a] Add CD\n[i] Display Current Inventory') <NEW_LINE> print('[d] delete CD from Inventory\n[s] Save Inventory to file\n[x] exit\n') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def menu_choice(): <NEW_LINE> <INDENT> choice = ' ' <NEW_LINE> while choice not in ['l', 'a', 'i', 'd', 's', 'x']: <NEW_LINE> <INDENT> choice = input('Which operation would you like to perform? [l, a, i, d, s or x]: ').lower().strip() <NEW_LINE> <DEDENT> print() <NEW_LINE> return choice <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def show_inventory(table): <NEW_LINE> <INDENT> print('======= The Current Inventory: =======') <NEW_LINE> print('ID\tCD Title (by: Artist)\n') <NEW_LINE> for row in table: <NEW_LINE> <INDENT> print('{}\t{} (by:{})'.format(*row.values())) <NEW_LINE> <DEDENT> print('======================================') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def user_cd_input(): <NEW_LINE> <INDENT> strID = input('Enter ID: ').strip() <NEW_LINE> strTitle = input('What is the CD\'s title? ').strip() <NEW_LINE> strArtist = input('What is the Artist\'s name? ').strip() <NEW_LINE> return strID, strTitle, strArtist
Handling Input / Output
62599063d486a94d0ba2d6c1
class RomVerScheme(SemVerScheme): <NEW_LINE> <INDENT> pass
http://dafoster.net/articles/2015/03/14/semantic-versioning-vs-romantic-versioning/
6259906391f36d47f2231a0b
class ManagementCommandMixin(BaseTestCase): <NEW_LINE> <INDENT> def get_command(self, cmd_module): <NEW_LINE> <INDENT> cmd = cmd_module.Command() <NEW_LINE> self.assertIn('help', dir(cmd)) <NEW_LINE> self.assertIsInstance(cmd.help, basestring) <NEW_LINE> self.assertTrue(len(cmd.help)) <NEW_LINE> return cmd
Class mixin for TestCase sub-classes that test Django management commands.
62599063379a373c97d9a718
class OpenStorageCloudBackupServicer(object): <NEW_LINE> <INDENT> def Create(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Restore(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Delete(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def DeleteAll(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Enumerate(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Status(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Catalog(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def History(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def StateChange(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def SchedCreate(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def SchedDelete(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def SchedEnumerate(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
OpenStorageCloudBackup service manages backing up volumes to a cloud location like Amazon, Google, or Azure. #### Backup To create a backup, you must first call the Create() call for a specified volume. To see the status of this request, use Status() which returns a map where the keys are the source volume id. #### Restore To restore, you would pass a `backup_id` of a successful backup. `backup_id` can be retreived by calling Enumerate() for a specified volume. Pass this `backup_id` and a new volume name to Restore() to start restoring a new volume from an existing backup. To see the status of this restore, pass volume id returned by Restore() to input to Status()
625990633539df3088ecd996
class AllOfDomainsListDomainsItems(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(AllOfDomainsListDomainsItems, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AllOfDomainsListDomainsItems): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
625990630c0af96317c578db
class CommentForm(forms.Form): <NEW_LINE> <INDENT> comment = forms.CharField(required=True, max_length=100, error_messages={ "required": "内容不能为空" })
用户评论表单
6259906332920d7e50bc773f
class IntentMessageImage(_messages.Message): <NEW_LINE> <INDENT> accessibilityText = _messages.StringField(1) <NEW_LINE> imageUri = _messages.StringField(2)
The image response message. Fields: accessibilityText: A text description of the image to be used for accessibility, e.g., screen readers. Required if image_uri is set for CarouselSelect. imageUri: Optional. The public URI to an image file.
625990635fdd1c0f98e5f67c
class ConversionError(Exception): <NEW_LINE> <INDENT> def __init__(self, key_type, attr, value): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.key_type = key_type <NEW_LINE> self.value = value <NEW_LINE> self.attr = attr <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Could not convert %s = %s to %s\n' % (self.attr, self.value, self.key_type) + 'This means you either tried to set a value of the wrong\n' + 'type or this keyword needs some special care. Please feel\n' + 'to add it to the corresponding __setattr__ method and send\n' + 'the patch to %s, so we can all benefit.' % (contact_email)
Print customized error for options that are not converted correctly and point out that they are maybe not implemented, yet
6259906338b623060ffaa3cd
class EnemyBullet: <NEW_LINE> <INDENT> def __init__(self, var_x, var_y, var_image): <NEW_LINE> <INDENT> self.x = var_x <NEW_LINE> self.y = var_y <NEW_LINE> self.image = var_image <NEW_LINE> <DEDENT> def draw(self, var_screen): <NEW_LINE> <INDENT> var_screen.blit(pygame.image.load(self.image), (self.x, self.y)) <NEW_LINE> <DEDENT> def move(self): <NEW_LINE> <INDENT> self.y += 10 <NEW_LINE> if self.y >= 800: <NEW_LINE> <INDENT> del self
敌军飞机发射的子弹类
62599063442bda511e95d8d6
class ToonGasMeterDeviceSensor(ToonSensor, ToonGasMeterDeviceEntity): <NEW_LINE> <INDENT> pass
Defines a Gas Meter sensor.
625990631f037a2d8b9e53e7
class TemplateTest(unittest.TestCase): <NEW_LINE> <INDENT> def testA(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> template = Template() <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> msg = "Failed to instantiate Template object:\n" <NEW_LINE> msg += str(ex) <NEW_LINE> self.fail(msg) <NEW_LINE> <DEDENT> <DEDENT> def testB(self): <NEW_LINE> <INDENT> step = WMStep("TestStep") <NEW_LINE> template = Template() <NEW_LINE> try: <NEW_LINE> <INDENT> template.coreInstall(step) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> msg = "Error calling Template.coreInstall(step)\n" <NEW_LINE> msg += str(ex) <NEW_LINE> self.fail(msg) <NEW_LINE> <DEDENT> self.failUnless(getattr(step, "environment", None) != None) <NEW_LINE> env = getattr(step, "environment") <NEW_LINE> self.failUnless(getattr(env, "paths", None) != None) <NEW_LINE> self.failUnless(getattr(env, "variables", None) != None) <NEW_LINE> self.failUnless(getattr(step, "build", None) != None) <NEW_LINE> build = getattr(step, "build") <NEW_LINE> self.failUnless(getattr(build, "directories", None) != None) <NEW_LINE> <DEDENT> def testC(self): <NEW_LINE> <INDENT> template = Template() <NEW_LINE> step = WMStep("TestStep") <NEW_LINE> self.assertRaises(NotImplementedError, template.install, step) <NEW_LINE> self.assertRaises(NotImplementedError, template.helper, step)
TestCase for Template base object
62599063d6c5a102081e381d
class InaccessibleGroupError(ESDLSyntaxErrorBase): <NEW_LINE> <INDENT> code = "W2006" <NEW_LINE> default_message = "Group '%s' specified after an unbounded group"
Returned when a group appears after an unbounded group and will never be selected into.
625990638e71fb1e983bd1c4
class ServiceOutputParser(LineOnlyReceiver): <NEW_LINE> <INDENT> delimiter = b"\n" <NEW_LINE> substitutions = { "Y": "(?P<Y>\d{4})", "m": "(?P<m>\d{2})", "d": "(?P<d>\d{2})", "H": "(?P<H>\d{2})", "M": "(?P<M>\d{2})", "S": "(?P<S>\d{2})", "msecs": "(?P<msecs>\d{3})", "levelname": "(?P<levelname>[a-zA-Z]+)", "name": "(?P<name>.+)", "message": "(?P<message>.+)", } <NEW_LINE> service = "" <NEW_LINE> def __init__(self, logger=None, pattern=None): <NEW_LINE> <INDENT> self.pattern = pattern or "{message}" <NEW_LINE> self.logger = logger or logging.getLogger("") <NEW_LINE> self._callbacks = {} <NEW_LINE> <DEDENT> def setServiceName(self, name): <NEW_LINE> <INDENT> self.service = name <NEW_LINE> <DEDENT> def whenLineContains(self, text, callback): <NEW_LINE> <INDENT> self._callbacks[text] = callback <NEW_LINE> <DEDENT> def lineReceived(self, line): <NEW_LINE> <INDENT> message = line.decode("utf-8") <NEW_LINE> params = { "levelname": "NOTSET", "levelno": 0, "msg": message, "processName": self.service, } <NEW_LINE> match = re.match(self.pattern.format(**self.substitutions), message) <NEW_LINE> if match: <NEW_LINE> <INDENT> params.update(self._getLogRecordParamsForMatch(match)) <NEW_LINE> <DEDENT> record = logging.makeLogRecord(params) <NEW_LINE> self.logger.handle(record) <NEW_LINE> for text in list(self._callbacks.keys()): <NEW_LINE> <INDENT> if text in record.msg: <NEW_LINE> <INDENT> self._callbacks.pop(text)() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def lineLengthExceeded(self, line): <NEW_LINE> <INDENT> self.lineReceived(line[:self.MAX_LENGTH]) <NEW_LINE> <DEDENT> def _getLogRecordParamsForMatch(self, match): <NEW_LINE> <INDENT> groups = _filterNoneValues(match.groupdict()) <NEW_LINE> params = { "name": groups.get("name"), "msg": groups.get("message"), } <NEW_LINE> if "levelname" in groups: <NEW_LINE> <INDENT> levelname = groups["levelname"].upper() <NEW_LINE> if len(levelname) == 1: <NEW_LINE> <INDENT> levelname = SHORT_LEVELS.get(levelname, "INFO") <NEW_LINE> <DEDENT> params["levelname"] = levelname <NEW_LINE> params["levelno"] = logging.getLevelName(params["levelname"]) <NEW_LINE> <DEDENT> if set(groups.keys()).issuperset({"Y", "m", "d", "H", "M", "S"}): <NEW_LINE> <INDENT> params["created"] = float(datetime( int(groups["Y"]), int(groups["m"]), int(groups["d"]), int(groups["H"]), int(groups["M"]), int(groups["S"]), ).strftime("%s")) <NEW_LINE> <DEDENT> if "msecs" in groups: <NEW_LINE> <INDENT> params["msecs"] = float(groups["msecs"]) <NEW_LINE> <DEDENT> return params
Parse the standard output stream of a service and forward it to the Python logging system. The stream is assumed to be a UTF-8 sequence of lines each delimited by a (configurable) delimiter character. Each received line is tested against the RegEx pattern provided in the constructor. If a match is found, a :class:`~logging.LogRecord` is built using the information from the groups of the match object, otherwise default values will be used. The record is then passed to the :class:`~logging.Logger` provided in the constructor. Match objects that result from the RegEx pattern are supposed to provide groups named after the substitutions below.
62599063f548e778e596cc82
class portal_menu(osv.osv): <NEW_LINE> <INDENT> _name = 'ir.ui.menu' <NEW_LINE> _inherit = 'ir.ui.menu' <NEW_LINE> def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> if not context.get('ir.ui.menu.full_list') and uid != 1 and args == [('parent_id', '=', False)]: <NEW_LINE> <INDENT> portal_obj = self.pool.get('res.portal') <NEW_LINE> portal_ids = portal_obj.search(cr, uid, [('users', 'in', uid)]) <NEW_LINE> if portal_ids: <NEW_LINE> <INDENT> if len(portal_ids) > 1: <NEW_LINE> <INDENT> log = logging.getLogger('ir.ui.menu') <NEW_LINE> log.warning('User %s belongs to several portals', str(uid)) <NEW_LINE> <DEDENT> p = portal_obj.browse(cr, uid, portal_ids[0]) <NEW_LINE> if p.menu_action_id: <NEW_LINE> <INDENT> args = safe_eval(p.menu_action_id.domain) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return super(portal_menu, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count)
Fix menu class to customize the login search for menus, as web client 6.0 does not support the menu action properly yet
625990634e4d562566373b00
class PhraseMatch(object): <NEW_LINE> <INDENT> def __init__(self, extracted_value, match_start, match_end, phrase): <NEW_LINE> <INDENT> self.extracted_value = extracted_value <NEW_LINE> self.match_start = match_start <NEW_LINE> self.match_end = match_end <NEW_LINE> self.phrase = phrase
Describes a single phrase match to a single RPDR Note for a phrase.
62599063cc0a2c111447c64c
class Mood(models.Model): <NEW_LINE> <INDENT> mood_title = models.CharField(max_length=20) <NEW_LINE> mood_time = models.CharField(max_length=20) <NEW_LINE> mood_content = models.CharField(max_length=128, default='开心的很,没有要讲的') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.mood_title
记录心情内容
625990638a43f66fc4bf3889
class Wallet: <NEW_LINE> <INDENT> def __init__(self, amount=100): <NEW_LINE> <INDENT> self.amount = amount <NEW_LINE> self.bet_amount = 0 <NEW_LINE> <DEDENT> def add_to_wallet(self, amount): <NEW_LINE> <INDENT> self.amount += amount <NEW_LINE> print("Your wallet now contains: ", self.amount) <NEW_LINE> <DEDENT> def check_bet(self, bet_amount, win = False): <NEW_LINE> <INDENT> if win: <NEW_LINE> <INDENT> self.amount += bet_amount <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.amount -= bet_amount <NEW_LINE> <DEDENT> <DEDENT> def show_wallet(self): <NEW_LINE> <INDENT> print(f"Your wallet contains {self.amount} ")
A wallet to store and make the bets
625990633d592f4c4edbc5d6
class ProductRetrieveView(generics.RetrieveAPIView): <NEW_LINE> <INDENT> renderer_classes = (CMSPageRenderer, JSONRenderer, BrowsableAPIRenderer) <NEW_LINE> lookup_field = lookup_url_kwarg = 'slug' <NEW_LINE> product_model = ProductModel <NEW_LINE> serializer_class = None <NEW_LINE> limit_choices_to = Q() <NEW_LINE> def get_template_names(self): <NEW_LINE> <INDENT> product = self.get_object() <NEW_LINE> app_label = product._meta.app_label.lower() <NEW_LINE> basename = '{}-detail.html'.format(product.__class__.__name__.lower()) <NEW_LINE> return [ os.path.join(app_label, 'catalog', basename), os.path.join(app_label, 'catalog/product-detail.html'), 'shop/catalog/product-detail.html', ] <NEW_LINE> <DEDENT> def get_renderer_context(self): <NEW_LINE> <INDENT> renderer_context = super(ProductRetrieveView, self).get_renderer_context() <NEW_LINE> if renderer_context['request'].accepted_renderer.format == 'html': <NEW_LINE> <INDENT> renderer_context['product'] = self.get_object() <NEW_LINE> renderer_context['ng_model_options'] = shop_settings.ADD2CART_NG_MODEL_OPTIONS <NEW_LINE> <DEDENT> return renderer_context <NEW_LINE> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> if not hasattr(self, '_product'): <NEW_LINE> <INDENT> assert self.lookup_url_kwarg in self.kwargs <NEW_LINE> filter_kwargs = {self.lookup_field: self.kwargs[self.lookup_url_kwarg]} <NEW_LINE> if hasattr(self.product_model, 'translations'): <NEW_LINE> <INDENT> filter_kwargs.update(translations__language_code=get_language_from_request(self.request)) <NEW_LINE> <DEDENT> queryset = self.product_model.objects.filter(self.limit_choices_to, **filter_kwargs) <NEW_LINE> product = get_object_or_404(queryset) <NEW_LINE> self._product = product <NEW_LINE> <DEDENT> return self._product
View responsible for rendering the products details. Additionally an extra method as shown in products lists, cart lists and order item lists.
6259906392d797404e3896da
class FtWarning(Warning): <NEW_LINE> <INDENT> pass
Base class for all 4Suite-specific warnings.
6259906376e4537e8c3f0c7c
class PersistentCache(object): <NEW_LINE> <INDENT> def set(self, key, value): <NEW_LINE> <INDENT> raise NotImplementedError('abstract method') <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> raise NotImplementedError('abstract method')
The base caching backend. This backend should be subclassed by concrete implementations.
6259906332920d7e50bc7740
class propfile(base.TranslationStore): <NEW_LINE> <INDENT> UnitClass = propunit <NEW_LINE> def __init__(self, inputfile=None, personality="java", encoding=None): <NEW_LINE> <INDENT> super(propfile, self).__init__(unitclass=self.UnitClass) <NEW_LINE> self.personality = get_dialect(personality) <NEW_LINE> self.encoding = encoding or self.personality.default_encoding <NEW_LINE> self.filename = getattr(inputfile, 'name', '') <NEW_LINE> if inputfile is not None: <NEW_LINE> <INDENT> propsrc = inputfile.read() <NEW_LINE> inputfile.close() <NEW_LINE> self.parse(propsrc) <NEW_LINE> <DEDENT> <DEDENT> def parse(self, propsrc): <NEW_LINE> <INDENT> text, encoding = self.detect_encoding(propsrc, default_encodings=[self.personality.default_encoding, 'utf-8', 'utf-16']) <NEW_LINE> self.encoding = encoding <NEW_LINE> propsrc = text <NEW_LINE> newunit = propunit("", self.personality.name) <NEW_LINE> inmultilinevalue = False <NEW_LINE> for line in propsrc.split(u"\n"): <NEW_LINE> <INDENT> line = quote.rstripeol(line) <NEW_LINE> if inmultilinevalue: <NEW_LINE> <INDENT> newunit.value += line.lstrip() <NEW_LINE> inmultilinevalue = is_line_continuation(newunit.value) <NEW_LINE> if inmultilinevalue: <NEW_LINE> <INDENT> newunit.value = newunit.value[:-1] <NEW_LINE> <DEDENT> if not inmultilinevalue: <NEW_LINE> <INDENT> self.addunit(newunit) <NEW_LINE> newunit = propunit("", self.personality.name) <NEW_LINE> <DEDENT> <DEDENT> elif (line.strip()[:1] in (u'#', u'!') or line.strip()[:2] in (u"/*", u"//") or line.strip()[:-2] == "*/"): <NEW_LINE> <INDENT> if line not in self.personality.drop_comments: <NEW_LINE> <INDENT> newunit.comments.append(line) <NEW_LINE> <DEDENT> <DEDENT> elif not line.strip(): <NEW_LINE> <INDENT> if str(newunit).strip(): <NEW_LINE> <INDENT> self.addunit(newunit) <NEW_LINE> newunit = propunit("", self.personality.name) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> newunit.delimiter, delimiter_pos = self.personality.find_delimiter(line) <NEW_LINE> if delimiter_pos == -1: <NEW_LINE> <INDENT> newunit.name = self.personality.key_strip(line) <NEW_LINE> newunit.value = u"" <NEW_LINE> self.addunit(newunit) <NEW_LINE> newunit = propunit("", self.personality.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newunit.name = self.personality.key_strip(line[:delimiter_pos]) <NEW_LINE> if is_line_continuation(line[delimiter_pos+1:].lstrip()): <NEW_LINE> <INDENT> inmultilinevalue = True <NEW_LINE> newunit.value = line[delimiter_pos+1:].lstrip()[:-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newunit.value = self.personality.value_strip(line[delimiter_pos+1:]) <NEW_LINE> self.addunit(newunit) <NEW_LINE> newunit = propunit("", self.personality.name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if inmultilinevalue or len(newunit.comments) > 0: <NEW_LINE> <INDENT> self.addunit(newunit) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> for unit in self.units: <NEW_LINE> <INDENT> lines.append(str(unit)) <NEW_LINE> <DEDENT> return "".join(lines)
this class represents a .properties file, made up of propunits
6259906376e4537e8c3f0c7d
class CustomLocations(object): <NEW_LINE> <INDENT> def __init__( self, credential, subscription_id, base_url=None, **kwargs ): <NEW_LINE> <INDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'https://management.azure.com' <NEW_LINE> <DEDENT> self._config = CustomLocationsConfiguration(credential, subscription_id, **kwargs) <NEW_LINE> self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._serialize.client_side_validation = False <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.custom_locations = CustomLocationsOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> <DEDENT> def _send_request(self, http_request, **kwargs): <NEW_LINE> <INDENT> path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), } <NEW_LINE> http_request.url = self._client.format_url(http_request.url, **path_format_arguments) <NEW_LINE> stream = kwargs.pop("stream", True) <NEW_LINE> pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) <NEW_LINE> return pipeline_response.http_response <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._client.close() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._client.__enter__() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, *exc_details): <NEW_LINE> <INDENT> self._client.__exit__(*exc_details)
The customLocations Rest API spec. :ivar custom_locations: CustomLocationsOperations operations :vartype custom_locations: azure.mgmt.extendedlocation.v2021_03_15_preview.operations.CustomLocationsOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The ID of the target subscription. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
62599063a8ecb03325872912
class InternalAwsInstanceEventViewSet( InternalViewSetMixin, viewsets.ReadOnlyModelViewSet ): <NEW_LINE> <INDENT> queryset = aws_models.AwsInstanceEvent.objects.all() <NEW_LINE> serializer_class = serializers.InternalAwsInstanceEventSerializer <NEW_LINE> filterset_fields = { "subnet": ["exact"], "instance_type": ["exact"], "created_at": ["lt", "exact", "gt"], "updated_at": ["lt", "exact", "gt"], }
Retrieve or list AwsInstanceEvents for internal use.
625990632ae34c7f260ac7e1
class MainWindow(wx.Frame): <NEW_LINE> <INDENT> def __init__(self,parent,id,title): <NEW_LINE> <INDENT> wx.Frame.__init__(self,parent, wx.ID_ANY, title, size = (800,900), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE) <NEW_LINE> self.SetBackgroundColour(wx.WHITE) <NEW_LINE> wx.StaticText(self, -1, "Drag and Drop Image File 1", (10, 15)) <NEW_LINE> wx.StaticText(self, -1, "Drag and Drop Image File 2", (410, 15)) <NEW_LINE> self.text1 = wx.TextCtrl(self, -1, "", pos=(10,35), size=(360,20), style = wx.TE_READONLY) <NEW_LINE> self.text2 = wx.TextCtrl(self, -1, "", pos=(410,35), size=(360,20), style = wx.TE_READONLY) <NEW_LINE> self.text1.WriteText(NoFileSelected) <NEW_LINE> self.text2.WriteText(NoFileSelected) <NEW_LINE> self.alignStatus = wx.StaticText(self, -1, "Aligning...Please Wait", (520,485)) <NEW_LINE> self.alignStatus.Hide() <NEW_LINE> img1 = wx.Image(ThumbMaxSize,ThumbMaxSize) <NEW_LINE> img2 = wx.Image(ThumbMaxSize,ThumbMaxSize) <NEW_LINE> img3 = wx.Image(OutputMaxSize, OutputMaxSize) <NEW_LINE> self.imageCtrl1 = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(img1), pos=(10,65)) <NEW_LINE> self.imageCtrl2 = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(img2), pos=(410,65)) <NEW_LINE> self.imageCtrl3 = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(img3), pos=(10,450)) <NEW_LINE> dt1 = FileDropTarget(self.text1, self.imageCtrl1, self) <NEW_LINE> dt2 = FileDropTarget(self.text2, self.imageCtrl2, self) <NEW_LINE> self.detectEdges = wx.CheckBox(self, -1, "Detect Edges", pos = (410,450)) <NEW_LINE> buttonAlign = wx.Button(self, -1, "Align", pos=(410,480)) <NEW_LINE> buttonAlign.Bind(wx.EVT_BUTTON, self.onAlign) <NEW_LINE> buttonCopyToClipboard = wx.Button(self, -1, "Copy Image To Clipboard", pos=(410,510)) <NEW_LINE> buttonCopyToClipboard.Bind(wx.EVT_BUTTON, self.onCopyToClipboard) <NEW_LINE> self.imageCtrl1.SetDropTarget(dt1) <NEW_LINE> self.imageCtrl2.SetDropTarget(dt2) <NEW_LINE> self.Show(True) <NEW_LINE> <DEDENT> def onAlign(self, button): <NEW_LINE> <INDENT> path1 = self.text1.GetValue() <NEW_LINE> path2 = self.text2.GetValue() <NEW_LINE> if(path1 != NoFileSelected and path2 != NoFileSelected): <NEW_LINE> <INDENT> detectEdges = self.detectEdges.GetValue() <NEW_LINE> worker = AlignWorkerThread(self, path1, path2, detectEdges) <NEW_LINE> <DEDENT> <DEDENT> def onCopyToClipboard(self, button): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.img3 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> app = QtWidgets.QApplication([]) <NEW_LINE> data = QtCore.QMimeData() <NEW_LINE> cwd = os.getcwd() <NEW_LINE> overlayFilePath = os.path.join(cwd, overlayFile) <NEW_LINE> url = QtCore.QUrl.fromLocalFile(overlayFilePath) <NEW_LINE> data.setUrls([url]) <NEW_LINE> app.clipboard().setMimeData(data)
This window displays the GUI Widgets.
6259906399cbb53fe68325dd
class ContentGenerator(object): <NEW_LINE> <INDENT> can_defer = True <NEW_LINE> @classmethod <NEW_LINE> def name(cls): <NEW_LINE> <INDENT> return cls.__name__ <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_resource_list(cls, post): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_etag(cls, post): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def generate_resource(cls, post, resource): <NEW_LINE> <INDENT> raise NotImplementedError()
A class that generates content and dependency list for blog posts
6259906356b00c62f0fb3fc6
class PostInline(admin.StackedInline): <NEW_LINE> <INDENT> model = Post <NEW_LINE> can_delete = False <NEW_LINE> verbose_name_plural = 'posts'
Post in-line
625990638e71fb1e983bd1c6
class NonMSAMortgageData(MortgageBase): <NEW_LINE> <INDENT> state = models.ForeignKey( State, null=True, on_delete=models.CASCADE) <NEW_LINE> @property <NEW_LINE> def county_list(self): <NEW_LINE> <INDENT> return self.state.non_msa_counties
Aggregate state data for counties that do not belong to an MSA.
625990632c8b7c6e89bd4eea
class IMediumFormat(Interface): <NEW_LINE> <INDENT> __uuid__ = '6238e1cf-a17d-4ec1-8172-418bfb22b93a' <NEW_LINE> __wsmap__ = 'managed' <NEW_LINE> @property <NEW_LINE> def id_p(self): <NEW_LINE> <INDENT> ret = self._get_attr("id") <NEW_LINE> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> ret = self._get_attr("name") <NEW_LINE> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def capabilities(self): <NEW_LINE> <INDENT> ret = self._get_attr("capabilities") <NEW_LINE> return [MediumFormatCapabilities(a) for a in ret] <NEW_LINE> <DEDENT> def describe_file_extensions(self): <NEW_LINE> <INDENT> (extensions, types) = self._call("describeFileExtensions") <NEW_LINE> types = [DeviceType(a) for a in types] <NEW_LINE> return (extensions, types) <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> (names, descriptions, types, flags, defaults) = self._call("describeProperties") <NEW_LINE> types = [DataType(a) for a in types] <NEW_LINE> return (names, descriptions, types, flags, defaults)
The IMediumFormat interface represents a medium format. Each medium format has an associated backend which is used to handle media stored in this format. This interface provides information about the properties of the associated backend. Each medium format is identified by a string represented by the :py:func:`id_p` attribute. This string is used in calls like :py:func:`IVirtualBox.create_hard_disk` to specify the desired format. The list of all supported medium formats can be obtained using :py:func:`ISystemProperties.medium_formats` . :py:class:`IMedium`
62599063cc0a2c111447c64d
class HistokatException(Exception): <NEW_LINE> <INDENT> pass
Raise if an exception within the histokat module occurred.
6259906344b2445a339b74de
class UnreliableMagicCarpet(Vehicle): <NEW_LINE> <INDENT> def __init__(self, new_fuel: int) -> None: <NEW_LINE> <INDENT> Vehicle.__init__(self, new_fuel, (random.randint(-10, 10), random.randint(-10, 10))) <NEW_LINE> <DEDENT> def move(self, new_x: int, new_y: int) -> None: <NEW_LINE> <INDENT> self.position = (new_x + random.randint(-2, 2), new_y + random.randint(-2, 2)) <NEW_LINE> <DEDENT> def fuel_needed(self, new_x: int, new_y: int) -> int: <NEW_LINE> <INDENT> return 0
An unreliable magic carpet. Does not need to use fuel to travel, but ends up in a random position within two horizontal and two vertical units from the target destination. >>> SDM = SuperDuperManager() >>> SDM.add_vehicle('UnreliableMagicCarpet', 'Silky', 0) >>> SDM.get_vehicle_position('Silky') (-4, 4) >>> SDM.move_vehicle('Silky', 50, 50) >>> SDM.get_vehicle_position('Silky') (49, 48)
62599063e76e3b2f99fda0fc
class Device(object): <NEW_LINE> <INDENT> def __init__(self, client, index): <NEW_LINE> <INDENT> super(Device, self).__init__() <NEW_LINE> self._client = client <NEW_LINE> self.index = index <NEW_LINE> self.device_type = self._request('name').decode('utf-8') <NEW_LINE> if self.device_type.endswith('Device'): <NEW_LINE> <INDENT> self.device_type = self.device_type[:-6] <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}Device(index={:d})'.format(self.device_type, self.index) <NEW_LINE> <DEDENT> def _request(self, cmd, *args): <NEW_LINE> <INDENT> return self._client._request('device.{}'.format(cmd), self.index, *args) <NEW_LINE> <DEDENT> def power_on(self): <NEW_LINE> <INDENT> self._request('power_on') <NEW_LINE> <DEDENT> def power_off(self): <NEW_LINE> <INDENT> self._request('power_off') <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._request('reset') <NEW_LINE> <DEDENT> def configure(self): <NEW_LINE> <INDENT> self._request('configure') <NEW_LINE> <DEDENT> def daq_start(self): <NEW_LINE> <INDENT> self._request('daq_start') <NEW_LINE> <DEDENT> def daq_stop(self): <NEW_LINE> <INDENT> self._request('daq_stop') <NEW_LINE> <DEDENT> def list_registers(self): <NEW_LINE> <INDENT> return self._request('list_registers').decode('utf-8').split() <NEW_LINE> <DEDENT> def get_register(self, name): <NEW_LINE> <INDENT> return int(self._request('get_register', name)) <NEW_LINE> <DEDENT> def set_register(self, name, value): <NEW_LINE> <INDENT> self._request('set_register', name, value) <NEW_LINE> <DEDENT> def get_current(self, name): <NEW_LINE> <INDENT> return float(self._request('get_current', name)) <NEW_LINE> <DEDENT> def set_current(self, name, value): <NEW_LINE> <INDENT> self._request('set_current', name, value) <NEW_LINE> <DEDENT> def get_voltage(self, name): <NEW_LINE> <INDENT> return float(self._request('get_voltage', name)) <NEW_LINE> <DEDENT> def set_voltage(self, name, value): <NEW_LINE> <INDENT> self._request('set_voltage', name, value) <NEW_LINE> <DEDENT> def switch_on(self, name): <NEW_LINE> <INDENT> self._request('switch_on', name) <NEW_LINE> <DEDENT> def switch_off(self, name): <NEW_LINE> <INDENT> self._request('switch_off', name) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> func = functools.partial(self._request, name) <NEW_LINE> self.__dict__[name] = func <NEW_LINE> return func
A Peary device. This object acts as a proxy that forwards all function calls to the device specified by the device index using the client object.
6259906376e4537e8c3f0c7e
class lookupByPhoneNumber_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = SpotPhoneNumberResponse() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = TalkException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('lookupByPhoneNumber_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - e
6259906391af0d3eaad3b524
class Lifetime(enum.Enum): <NEW_LINE> <INDENT> singleton = enum.auto() <NEW_LINE> transient = enum.auto() <NEW_LINE> scoped = enum.auto()
Marks lifetime of an instance.
625990634a966d76dd5f05f1
class StatusBar(tkinter.Frame): <NEW_LINE> <INDENT> def __init__(self, master, text=''): <NEW_LINE> <INDENT> tkinter.Frame.__init__(self, master) <NEW_LINE> self.text = tkinter.StringVar() <NEW_LINE> self.label = tkinter.Label(self, textvariable=self.text, font=('arial', 12, 'normal')) <NEW_LINE> self.text.set(text) <NEW_LINE> self.label.pack(fill=tkinter.X) <NEW_LINE> self.pack(side=tkinter.BOTTOM, anchor=tkinter.W) <NEW_LINE> <DEDENT> def set_text(self, text): <NEW_LINE> <INDENT> self.text.set(text) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.text.set('') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Status Bar with text '{}'".format(self.text.get())
StatusBar class
6259906324f1403a9268644c
class XmippProtMaskVolumes(ProtMaskVolumes, XmippProcessVolumes, XmippProtMask, XmippGeometricalMask3D): <NEW_LINE> <INDENT> _label = 'apply 3d mask' <NEW_LINE> MASK_FILE = 'mask.vol' <NEW_LINE> MASK_CLASSNAME = 'VolumeMask' <NEW_LINE> GEOMETRY_BASECLASS = XmippGeometricalMask3D <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> ProtMaskVolumes.__init__(self, **kwargs) <NEW_LINE> XmippProcessVolumes.__init__(self, **kwargs) <NEW_LINE> XmippProtMask.__init__(self, **kwargs) <NEW_LINE> self.allowMpi = False <NEW_LINE> self.allowThreads = False <NEW_LINE> <DEDENT> def _defineProcessParams(self, form): <NEW_LINE> <INDENT> XmippProtMask._defineProcessParams(self, form) <NEW_LINE> <DEDENT> def _getGeometryCommand(self): <NEW_LINE> <INDENT> if self._isSingleInput(): <NEW_LINE> <INDENT> Xdim = self.inputVolumes.get().getDim()[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Xdim = self.inputVolumes.get().getDimensions()[0] <NEW_LINE> <DEDENT> args = XmippGeometricalMask3D.argsForTransformMask(self, Xdim) <NEW_LINE> return args <NEW_LINE> <DEDENT> def _getExtraMaskArgs(self): <NEW_LINE> <INDENT> if self._isSingleInput(): <NEW_LINE> <INDENT> return " -o %s" % self.outputStk <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return XmippProtMask._getExtraMaskArgs(self) <NEW_LINE> <DEDENT> <DEDENT> def _summary(self): <NEW_LINE> <INDENT> messages = [] <NEW_LINE> messages += XmippProtMask._summary(self, XmippGeometricalMask3D) <NEW_LINE> return messages <NEW_LINE> <DEDENT> def _methods(self): <NEW_LINE> <INDENT> messages = [] <NEW_LINE> messages += XmippProtMask._methods(self, XmippGeometricalMask3D) <NEW_LINE> return messages <NEW_LINE> <DEDENT> def _validate(self): <NEW_LINE> <INDENT> return XmippProtMask._validateDimensions(self, 'inputVolumes', 'inputMask', 'Input volumes and mask should ' 'have same dimensions.')
Apply mask to a volume
62599063b7558d5895464aac