code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CapacityPool(Model): <NEW_LINE> <INDENT> _validation = { 'location': {'required': True}, 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'pool_id': {'readonly': True, 'max_length': 36, 'min_length': 36, 'pattern': r'^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$'}, 'size': {'maximum': 549755813888000, 'minimum': 4398046511104}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'location': {'key': 'location', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': 'object'}, 'pool_id': {'key': 'properties.poolId', 'type': 'str'}, 'size': {'key': 'properties.size', 'type': 'long'}, 'service_level': {'key': 'properties.serviceLevel', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, location: str, tags=None, size: int=4398046511104, service_level="Premium", **kwargs) -> None: <NEW_LINE> <INDENT> super(CapacityPool, self).__init__(**kwargs) <NEW_LINE> self.location = location <NEW_LINE> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.tags = tags <NEW_LINE> self.pool_id = None <NEW_LINE> self.size = size <NEW_LINE> self.service_level = service_level <NEW_LINE> self.provisioning_state = None
Capacity pool resource. 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 location: Required. Resource location :type location: str :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar type: Resource type :vartype type: str :param tags: Resource tags :type tags: object :ivar pool_id: poolId. UUID v4 used to identify the Pool :vartype pool_id: str :param size: size. Provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104). Default value: 4398046511104 . :type size: long :param service_level: serviceLevel. The service level of the file system. Possible values include: 'Standard', 'Premium', 'Extreme'. Default value: "Premium" . :type service_level: str or ~azure.mgmt.netapp.models.ServiceLevel :ivar provisioning_state: Azure lifecycle management :vartype provisioning_state: str
6259903fbe383301e0254a8d
class Node: <NEW_LINE> <INDENT> def __init__(self, i, N, f, p, d): <NEW_LINE> <INDENT> self.i = i <NEW_LINE> self.x = normal(0, 1, [N, 1]) <NEW_LINE> self.f = f <NEW_LINE> self.Neighbours = [] <NEW_LINE> self.M = {} <NEW_LINE> self.d_T = d <NEW_LINE> self.p = p <NEW_LINE> self.N_max = 5000 <NEW_LINE> <DEDENT> def finalise(self): <NEW_LINE> <INDENT> for neighbour in self.Neighbours: <NEW_LINE> <INDENT> neighbour.m_ij = neighbour.new_m_ij <NEW_LINE> <DEDENT> <DEDENT> def get_message(self, j): <NEW_LINE> <INDENT> for neighbour in self.Neighbours: <NEW_LINE> <INDENT> if neighbour.j == j: <NEW_LINE> <INDENT> return neighbour.m_ij <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def update_messages(self): <NEW_LINE> <INDENT> for neighbour in self.Neighbours: <NEW_LINE> <INDENT> m_ji = neighbour.node.get_message(self.i) <NEW_LINE> neighbour.new_m_ij = m_ji + (neighbour.c_ij - 2 * dot(neighbour.A_ij, self.x)) <NEW_LINE> <DEDENT> <DEDENT> def objective(self, x): <NEW_LINE> <INDENT> obj = self.f(x) <NEW_LINE> for neighbour in self.Neighbours: <NEW_LINE> <INDENT> m_ji = neighbour.node.get_message(self.i) <NEW_LINE> A_ij = neighbour.A_ij <NEW_LINE> P_ij = neighbour.P_ij <NEW_LINE> obj_int = dot(A_ij, x) - m_ji <NEW_LINE> obj = obj + 0.5 * dot(obj_int.T, dot(P_ij, obj_int)) <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def find_minimum(self): <NEW_LINE> <INDENT> obj_grad = grad(self.objective) <NEW_LINE> d = 1 <NEW_LINE> i = 0 <NEW_LINE> while d > self.d_T and i < self.N_max: <NEW_LINE> <INDENT> g = self.p * obj_grad(self.x) <NEW_LINE> self.x = self.x - g <NEW_LINE> d = norm(g) <NEW_LINE> i = i + 1 <NEW_LINE> <DEDENT> print(i, d) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.find_minimum() <NEW_LINE> self.update_messages()
This class is the implementation of a single node in a Kalman Filter chain for PDMM It can calculate it's local loss and propogate messages to adjacent nodes
6259903f23e79379d538d774
class ResultOutOfRange(object): <NEW_LINE> <INDENT> implements(IFieldIcons) <NEW_LINE> adapts(IAnalysisRequest) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> <DEDENT> def __call__(self, result=None, specification="lab", **kwargs): <NEW_LINE> <INDENT> workflow = getToolByName(self.context, 'portal_workflow') <NEW_LINE> items = self.context.getAnalyses() <NEW_LINE> field_icons = {} <NEW_LINE> for obj in items: <NEW_LINE> <INDENT> obj = obj.getObject() if hasattr(obj, 'getObject') else obj <NEW_LINE> uid = obj.UID() <NEW_LINE> astate = workflow.getInfoFor(obj, 'review_state') <NEW_LINE> if astate == 'retracted': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> adapters = getAdapters((obj, ), IFieldIcons) <NEW_LINE> for name, adapter in adapters: <NEW_LINE> <INDENT> alerts = adapter(obj) <NEW_LINE> if alerts: <NEW_LINE> <INDENT> if uid in field_icons: <NEW_LINE> <INDENT> field_icons[uid].extend(alerts[uid]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> field_icons[uid] = alerts[uid] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return field_icons
Return alerts for any analyses inside the context ar
6259903fdc8b845886d5482c
class PairLocalAccessBase(_GroupLocalAccess): <NEW_LINE> <INDENT> _cpp_get_data_method_name = "getPairData"
Class for directly accessing HOOMD-blue special pair data. Attributes: typeid ((N_pairs) `hoomd.data.array` object of ``float``): The type of special pair. members ((N_pairs, 3) `hoomd.data.array` object of ``int``): the tags of particles in a special pair. tag ((N_special_pairs) `hoomd.data.array` object of ``int``): The tag of the special pair. HOOMD-blue uses spacial sorting to improve cache efficiency in special pair look-ups. This means the ordering of the array changes. However, special pair tags remain constant. This means that if ``special pair.tag[0]`` is 1, then later whatever special pair has a tag of 1 later in the simulation is the same special pair. rtag ((N_special_pairs_global) `hoomd.data.array` object of ``int``): The reverse tag of a special pair. This means that the value ``special pair.rtag[0]`` represents the current index for accessing data for the special pair with tag 0.
6259903fd6c5a102081e339b
class sfp_whois(SpiderFootPlugin): <NEW_LINE> <INDENT> opts = { } <NEW_LINE> optdescs = { } <NEW_LINE> results = list() <NEW_LINE> def setup(self, sfc, userOpts=dict()): <NEW_LINE> <INDENT> self.sf = sfc <NEW_LINE> self.results = list() <NEW_LINE> for opt in userOpts.keys(): <NEW_LINE> <INDENT> self.opts[opt] = userOpts[opt] <NEW_LINE> <DEDENT> <DEDENT> def watchedEvents(self): <NEW_LINE> <INDENT> return ["DOMAIN_NAME", "OWNED_NETBLOCK"] <NEW_LINE> <DEDENT> def producedEvents(self): <NEW_LINE> <INDENT> return ["DOMAIN_WHOIS", "NETBLOCK_WHOIS", "DOMAIN_REGISTRAR"] <NEW_LINE> <DEDENT> def handleEvent(self, event): <NEW_LINE> <INDENT> eventName = event.eventType <NEW_LINE> srcModuleName = event.module <NEW_LINE> eventData = event.data <NEW_LINE> parentEvent = event.sourceEvent <NEW_LINE> if eventData in self.results: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.results.append(eventData) <NEW_LINE> <DEDENT> self.sf.debug("Received event, " + eventName + ", from " + srcModuleName) <NEW_LINE> try: <NEW_LINE> <INDENT> data = pythonwhois.net.get_whois_raw(eventData) <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> self.sf.error("Unable to perform WHOIS on " + eventData + ": " + str(e), False) <NEW_LINE> return None <NEW_LINE> <DEDENT> if eventName == "DOMAIN_NAME": <NEW_LINE> <INDENT> typ = "DOMAIN_WHOIS" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> typ = "NETBLOCK_WHOIS" <NEW_LINE> <DEDENT> evt = SpiderFootEvent(typ, '\n'.join(data), self.__name__, event) <NEW_LINE> self.notifyListeners(evt) <NEW_LINE> try: <NEW_LINE> <INDENT> info = pythonwhois.parse.parse_raw_whois(data, True) <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> self.sf.debug("Error parsing whois data for " + eventData) <NEW_LINE> return None <NEW_LINE> <DEDENT> if info.has_key('registrar'): <NEW_LINE> <INDENT> if eventName == "DOMAIN_NAME" and info['registrar'] is not None: <NEW_LINE> <INDENT> evt = SpiderFootEvent("DOMAIN_REGISTRAR", info['registrar'][0], self.__name__, event) <NEW_LINE> self.notifyListeners(evt)
Whois:Footprint,Investigate:Perform a WHOIS look-up on domain names and owned netblocks.
6259903f50485f2cf55dc1f9
class Action(GObject.Object, Loggable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> GObject.Object.__init__(self) <NEW_LINE> Loggable.__init__(self) <NEW_LINE> <DEDENT> def asScenarioAction(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Something which might worth logging in a scenario.
6259903f596a897236128ee9
class TestRandomPartSeven(unittest.TestCase): <NEW_LINE> <INDENT> @mock.patch('os.urandom', return_value='pumpkins') <NEW_LINE> def test_abc_urandom(self, urandom_function): <NEW_LINE> <INDENT> assert not urandom_function.called <NEW_LINE> assert os.urandom(5) == 'pumpkins' <NEW_LINE> assert os.urandom(5) == 'pumpkins' <NEW_LINE> assert urandom_function.called <NEW_LINE> assert urandom_function.call_count == 2 <NEW_LINE> urandom_function.reset_mock() <NEW_LINE> assert not urandom_function.called <NEW_LINE> assert urandom_function.call_count == 0
사실 가장 필요한 방법은 이 방법 인 것 같습니다. 그냥 리턴값 따로 명시를 해놓고...
6259903fbaa26c4b54d5051f
class Topic(TimestampMixin): <NEW_LINE> <INDENT> title = models.CharField(max_length=250) <NEW_LINE> slug = models.SlugField(max_length=100, default='', unique=True) <NEW_LINE> content = models.TextField() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('forums:view', kwargs=dict(bid=int_to_base36(self.id))) <NEW_LINE> <DEDENT> @property <NEW_LINE> def latest(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.reply_set.filter(status='posted').order_by('created_at')[0].entry <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def reply_length(self): <NEW_LINE> <INDENT> return len(self.reply_set.filter(status='posted')) <NEW_LINE> <DEDENT> @property <NEW_LINE> def bid(self): <NEW_LINE> <INDENT> return int_to_base36(self.id)
A topic heads off each forum thread only admins can create a topic
6259903f26068e7796d4dbbd
class ExampleEnvironment(Environment): <NEW_LINE> <INDENT> _latex_name = 'exampleEnvironment' <NEW_LINE> packages = [Package('mdframed')]
A class representing a custom LaTeX environment. This class represents a custom LaTeX environment named ``exampleEnvironment``.
6259903f3c8af77a43b68877
class Cursor: <NEW_LINE> <INDENT> def __init__(self, model, spec=None, *args, **kwargs): <NEW_LINE> <INDENT> from .model import Model <NEW_LINE> self._order_entries = [] <NEW_LINE> self._query = spec <NEW_LINE> self._model = model <NEW_LINE> self._pycur = PyCursor(model._get_collection(), spec, *args, **kwargs) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> value = self._pycur.next() <NEW_LINE> return self._model(**value) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> return self.__next__() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._pycur.count() <NEW_LINE> <DEDENT> def count(self): <NEW_LINE> <INDENT> return self._pycur.count() <NEW_LINE> <DEDENT> def __getitem__(self, *args, **kwargs): <NEW_LINE> <INDENT> value = self._pycur.__getitem__(*args, **kwargs) <NEW_LINE> if type(value) == self.__class__: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return self._model(**value) <NEW_LINE> <DEDENT> def first(self): <NEW_LINE> <INDENT> if self.__len__() == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self[0] <NEW_LINE> <DEDENT> def order(self, **kwargs): <NEW_LINE> <INDENT> if len(kwargs) < 1: <NEW_LINE> <INDENT> raise ValueError("order() requires one field = ASC or DESC.") <NEW_LINE> <DEDENT> for key, value in kwargs.items(): <NEW_LINE> <INDENT> if value not in (ASC, DESC): <NEW_LINE> <INDENT> raise TypeError("Order value must be mogo.ASC or mogo.DESC.") <NEW_LINE> <DEDENT> self._order_entries.append((key, value)) <NEW_LINE> self._pycur.sort(self._order_entries) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def limit(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._pycur.limit(*args, **kwargs) <NEW_LINE> <DEDENT> def skip(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._pycur.skip(*args, **kwargs) <NEW_LINE> <DEDENT> def sort(self, key, direction=ASC): <NEW_LINE> <INDENT> return self.order(**{key:direction}) <NEW_LINE> <DEDENT> def rawsort(self, sort_args): <NEW_LINE> <INDENT> self._pycur.sort(sort_args) <NEW_LINE> return self <NEW_LINE> <DEDENT> def update(self, modifier): <NEW_LINE> <INDENT> if self._query is None: <NEW_LINE> <INDENT> raise ValueError( "Cannot update on a cursor without a query. If you " "actually want to modify all values on a model, pass " "in an explicit {} to find().") <NEW_LINE> <DEDENT> self._model.update(self._query, modifier, multi=True) <NEW_LINE> return self <NEW_LINE> <DEDENT> def change(self, **kwargs): <NEW_LINE> <INDENT> modifier = {"$set": kwargs} <NEW_LINE> return self.update(modifier)
A simple proxy to pymongo's Cursor class.
6259903fd99f1b3c44d06913
class SheetMeta(PyexcelObject): <NEW_LINE> <INDENT> @append_doc(docs.SAVE_AS_OPTIONS) <NEW_LINE> def save_as(self, filename, **keywords): <NEW_LINE> <INDENT> return save_sheet(self, file_name=filename, **keywords) <NEW_LINE> <DEDENT> def save_to_memory(self, file_type, stream=None, **keywords): <NEW_LINE> <INDENT> stream = save_sheet(self, file_type=file_type, file_stream=stream, **keywords) <NEW_LINE> return stream <NEW_LINE> <DEDENT> def save_to_django_model(self, model, initializer=None, mapdict=None, batch_size=None): <NEW_LINE> <INDENT> save_sheet(self, model=model, initializer=initializer, mapdict=mapdict, batch_size=batch_size) <NEW_LINE> <DEDENT> def save_to_database(self, session, table, initializer=None, mapdict=None, auto_commit=True): <NEW_LINE> <INDENT> save_sheet(self, session=session, table=table, initializer=initializer, mapdict=mapdict, auto_commit=auto_commit)
Annotate sheet attributes
6259903f287bf620b6272e61
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = "iECgbYWReMNxkRprrzMo5KAQYnb2UeZ3bwvReTSt+VSESW0OB8zbglT+6rEcDW9X" <NEW_LINE> SQLALCHEMY_DATABASE_URI = "mysql://root:[email protected]:3306/information" <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> SQLALCHEMY_COMMIT_ON_TEARDOWN = True <NEW_LINE> REDIS_HOST = "127.0.0.1" <NEW_LINE> REDIS_PORT = 6379 <NEW_LINE> SESSION_TYPE = "redis" <NEW_LINE> SESSION_USE_SIGNER = True <NEW_LINE> SESSION_REDIS = StrictRedis(host=REDIS_HOST, port=REDIS_PORT) <NEW_LINE> SESSION_PERMANENT = False <NEW_LINE> PERMANENT_SESSION_LIFETIME = 86400 * 2 <NEW_LINE> LOG_LEVEL = logging.DEBUG
项目的配置
6259903f507cdc57c63a6012
class DecodeError(Exception): <NEW_LINE> <INDENT> pass
The file could not be decoded by any backend. Either no backends are available or each available backedn failed to decode the file.
6259903f8da39b475be04466
@directory.register <NEW_LINE> class Icom746Radio(IcomCIVRadio): <NEW_LINE> <INDENT> MODEL = "746" <NEW_LINE> BAUD_RATE = 9600 <NEW_LINE> _model = "\x56" <NEW_LINE> _template = 102 <NEW_LINE> _num_banks = 1 <NEW_LINE> def _initialize(self): <NEW_LINE> <INDENT> self._classes["mem"] = DupToneMemFrame <NEW_LINE> self._rf.has_bank = False <NEW_LINE> self._rf.has_dtcs_polarity = False <NEW_LINE> self._rf.has_dtcs = False <NEW_LINE> self._rf.has_ctone = True <NEW_LINE> self._rf.has_offset = False <NEW_LINE> self._rf.has_name = True <NEW_LINE> self._rf.has_tuning_step = False <NEW_LINE> self._rf.valid_modes = ["LSB", "USB", "AM", "CW", "RTTY", "FM"] <NEW_LINE> self._rf.valid_tmodes = ["", "Tone", "TSQL"] <NEW_LINE> self._rf.valid_duplexes = ["", "-", "+"] <NEW_LINE> self._rf.valid_bands = [(30000, 199999999)] <NEW_LINE> self._rf.valid_tuning_steps = [] <NEW_LINE> self._rf.valid_skips = [] <NEW_LINE> self._rf.valid_name_length = 9 <NEW_LINE> self._rf.valid_characters = chirp_common.CHARSET_ASCII <NEW_LINE> self._rf.memory_bounds = (1, 99)
Icom IC-746
6259903f711fe17d825e15d8
class InvalidCapsuleError(CapsuleLoadError): <NEW_LINE> <INDENT> pass
This is thrown when a capsule has the correct API compatibility version, but it still doesn't have the correct information on it.
6259903f15baa72349463209
class HostUserBind(models.Model): <NEW_LINE> <INDENT> host = models.ForeignKey("Host",on_delete=models.DO_NOTHING) <NEW_LINE> host_user = models.ForeignKey("HostUser",on_delete=models.DO_NOTHING) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "%s-%s-%s"%(self.id,self.host,self.host_user) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ("host","host_user")
绑定主机和用户
6259903fd99f1b3c44d06914
class PIDController(AbstractController): <NEW_LINE> <INDENT> def __init__(self, actuator_limits, ref_state, frequency, p_gain=None, i_gain=None, d_gain=None): <NEW_LINE> <INDENT> super(PIDController, self).__init__(actuator_limits) <NEW_LINE> self._ref_state = ref_state <NEW_LINE> self._acc_error = np.zeros_like(ref_state) <NEW_LINE> self._last_error = self._acc_error.copy() <NEW_LINE> self._dt = 1. / frequency <NEW_LINE> self._p_gain, self._i_gain, self._d_gain = self._assert_gains(p_gain, i_gain, d_gain) <NEW_LINE> <DEDENT> def _key(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _assert_gains(self, *gains): <NEW_LINE> <INDENT> out_gains = [gain if gain is not None else np.zeros( (self._actuator_limits.shape[0], self._ref_state.shape[0]) ) for gain in gains] <NEW_LINE> if len(out_gains) != 1: <NEW_LINE> <INDENT> for gain in out_gains[1:]: <NEW_LINE> <INDENT> assert_shape_like(gain, out_gains[0]) <NEW_LINE> <DEDENT> <DEDENT> return out_gains <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._acc_error = np.zeros_like(self._ref_state) <NEW_LINE> self._last_error = np.zeros_like(self._ref_state) <NEW_LINE> <DEDENT> def get_action(self, state): <NEW_LINE> <INDENT> state_error = self.compute_error_signal(state) <NEW_LINE> error_diff = (state_error - self._last_error) / self._dt <NEW_LINE> sat_action = saturate( self._p_gain.dot(state_error) + self._i_gain.dot(self._acc_error) + self._d_gain.dot(error_diff), self._actuator_limits ) <NEW_LINE> self.logger.debug("Action is {:s}".format(sat_action.flatten())) <NEW_LINE> self._accumulate_error(state_error) <NEW_LINE> self._set_last_error(state_error) <NEW_LINE> return sat_action <NEW_LINE> <DEDENT> def compute_error_signal(self, state): <NEW_LINE> <INDENT> assert_shape_like(state, self._ref_state) <NEW_LINE> err = self._ref_state - state <NEW_LINE> self.logger.debug("Error is {}".format(err.flatten())) <NEW_LINE> return err <NEW_LINE> <DEDENT> def _set_last_error(self, error): <NEW_LINE> <INDENT> self._last_error = error.copy() <NEW_LINE> self.logger.debug("Set last error to {}".format(self._last_error.flatten())) <NEW_LINE> <DEDENT> def _accumulate_error(self, error): <NEW_LINE> <INDENT> self._acc_error += error <NEW_LINE> self.logger.debug("Set accumulated error to {}".format(self._acc_error.flatten()))
Simple implementation of a PID controller.
6259903fd53ae8145f9196d4
class SubmissionProcess(Base): <NEW_LINE> <INDENT> _page_title = 'Submit an App | Developer Hub | Mozilla Marketplace' <NEW_LINE> _continue_locator = (By.CSS_SELECTOR, '.continue.prominent') <NEW_LINE> _current_step_locator = (By.CSS_SELECTOR, '#submission-progress > li.current') <NEW_LINE> @property <NEW_LINE> def current_step(self): <NEW_LINE> <INDENT> return self.selenium.find_element(*self._current_step_locator).text <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_the_current_submission_stage(self): <NEW_LINE> <INDENT> return self.is_element_visible(*self._precise_current_step_locator) <NEW_LINE> <DEDENT> def click_continue(self): <NEW_LINE> <INDENT> current_step = self.current_step <NEW_LINE> if current_step == 'Agreement' or not self.is_element_present(*self._continue_locator): <NEW_LINE> <INDENT> if self.is_dev_agreement_present: <NEW_LINE> <INDENT> self.selenium.find_element(*self._continue_locator).click() <NEW_LINE> <DEDENT> return Validation(self.testsetup) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.selenium.find_element(*self._continue_locator).click() <NEW_LINE> if current_step == 'Submit': <NEW_LINE> <INDENT> return Details(self.testsetup) <NEW_LINE> <DEDENT> elif current_step == 'Details': <NEW_LINE> <INDENT> return Finished(self.testsetup)
Base class that is available at every submission step
6259903f1d351010ab8f4d95
class XView: <NEW_LINE> <INDENT> def xview(self, *args): <NEW_LINE> <INDENT> res = self.tk.call(self._w, 'xview', *args) <NEW_LINE> if not args: <NEW_LINE> <INDENT> return self._getdoubles(res) <NEW_LINE> <DEDENT> <DEDENT> def xview_moveto(self, fraction): <NEW_LINE> <INDENT> self.tk.call(self._w, 'xview', 'moveto', fraction) <NEW_LINE> <DEDENT> def xview_scroll(self, number, what): <NEW_LINE> <INDENT> self.tk.call(self._w, 'xview', 'scroll', number, what)
Mix-in class for querying and changing the horizontal position of a widget's window.
6259903fd4950a0f3b11177c
class ReplyKeyboardMarkup(ReplyMarkup): <NEW_LINE> <INDENT> def __init__(self, keyboard, **kwargs): <NEW_LINE> <INDENT> self.keyboard = keyboard <NEW_LINE> self.resize_keyboard = bool(kwargs.get('resize_keyboard', False)) <NEW_LINE> self.one_time_keyboard = bool(kwargs.get('one_time_keyboard', False)) <NEW_LINE> self.selective = bool(kwargs.get('selective', False)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def de_json(data): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> data['keyboard'] = [KeyboardButton.de_list(keyboard) for keyboard in data['keyboard']] <NEW_LINE> return ReplyKeyboardMarkup(**data) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> data = super(ReplyKeyboardMarkup, self).to_dict() <NEW_LINE> data['keyboard'] = [] <NEW_LINE> for keyboard in self.keyboard: <NEW_LINE> <INDENT> data['keyboard'].append([x.to_dict() for x in keyboard]) <NEW_LINE> <DEDENT> return data
This object represents a Telegram ReplyKeyboardMarkup. Attributes: keyboard (List[List[:class:`telegram.KeyboardButton`]]): resize_keyboard (bool): one_time_keyboard (bool): selective (bool): Args: keyboard (List[List[str]]): **kwargs: Arbitrary keyword arguments. Keyword Args: resize_keyboard (Optional[bool]): one_time_keyboard (Optional[bool]): selective (Optional[bool]):
6259903f07f4c71912bb06aa
class Inventory(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.contents = {} <NEW_LINE> <DEDENT> def add(self, item, qty=1): <NEW_LINE> <INDENT> self.contents[item] = ItemEntry(item, qty) <NEW_LINE> <DEDENT> def contains_enough(self, item): <NEW_LINE> <INDENT> if item in self.contents: <NEW_LINE> <INDENT> return self.contents[item].qty <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def quantity_of(self, item): <NEW_LINE> <INDENT> if self.contains_enough(item, 1): <NEW_LINE> <INDENT> return self.contents[item].qty <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def remove(self, item, qty): <NEW_LINE> <INDENT> if self.contains_enough(item, qty): <NEW_LINE> <INDENT> remaining_qty = self.quantity_of(item) - qty <NEW_LINE> self.contents[item] = ItemEntry(item, remaining_qty) <NEW_LINE> <DEDENT> if remaining_qty == 0: <NEW_LINE> <INDENT> del self.contents[item] <NEW_LINE> <DEDENT> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return len(self.contents) == 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> title = 'Your inventory contains:\n' <NEW_LINE> if self.is_empty(): <NEW_LINE> <INDENT> contents = 'Nothing' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> contents = '\n'.join(str(item_entry) for item_entry in self.contents.values()) <NEW_LINE> <DEDENT> return title + contents
Inventories are a set of item entries.
6259903f26068e7796d4dbbf
class TwoWayDict(dict): <NEW_LINE> <INDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> del self[key] <NEW_LINE> <DEDENT> if value in self: <NEW_LINE> <INDENT> del self[value] <NEW_LINE> <DEDENT> dict.__setitem__(self, key, value) <NEW_LINE> dict.__setitem__(self, value, key) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> dict.__delitem__(self, self[key]) <NEW_LINE> dict.__delitem__(self, key) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return dict.__len__(self) // 2
dictionary which can be read as key: val or val: key.
6259903f73bcbd0ca4bcb503
@admin.register(models.TrackingEvent) <NEW_LINE> class TrackingEventAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> fields = ( "event_id", "package", "status", "carrier_code", "description", "timestamp", "location", ) <NEW_LINE> list_display = ( "event_id", "package", "status", "carrier_code", "description", "timestamp", "location", ) <NEW_LINE> search_fields = ("event_id", "package__scurri_id") <NEW_LINE> date_hierarchy = "timestamp" <NEW_LINE> list_filter = ("package__carrier",)
Admin for the tracking.TrackingEvent model.
6259903f6e29344779b018ca
class HtmlCalendarWeek(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def multi_day_bands(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def single_day_bands(self): <NEW_LINE> <INDENT> raise NotImplementedError()
A single week of the calendar to be rendered
6259903f287bf620b6272e62
class ExportJobsOperationResultInfo(OperationResultInfoBase): <NEW_LINE> <INDENT> _validation = { 'object_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'object_type': {'key': 'objectType', 'type': 'str'}, 'blob_url': {'key': 'blobUrl', 'type': 'str'}, 'blob_sas_key': {'key': 'blobSasKey', 'type': 'str'}, 'excel_file_blob_url': {'key': 'excelFileBlobUrl', 'type': 'str'}, 'excel_file_blob_sas_key': {'key': 'excelFileBlobSasKey', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, blob_url: Optional[str] = None, blob_sas_key: Optional[str] = None, excel_file_blob_url: Optional[str] = None, excel_file_blob_sas_key: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ExportJobsOperationResultInfo, self).__init__(**kwargs) <NEW_LINE> self.object_type = 'ExportJobsOperationResultInfo' <NEW_LINE> self.blob_url = blob_url <NEW_LINE> self.blob_sas_key = blob_sas_key <NEW_LINE> self.excel_file_blob_url = excel_file_blob_url <NEW_LINE> self.excel_file_blob_sas_key = excel_file_blob_sas_key
This class is used to send blob details after exporting jobs. All required parameters must be populated in order to send to Azure. :ivar object_type: Required. This property will be used as the discriminator for deciding the specific types in the polymorphic chain of types.Constant filled by server. :vartype object_type: str :ivar blob_url: URL of the blob into which the serialized string of list of jobs is exported. :vartype blob_url: str :ivar blob_sas_key: SAS key to access the blob. It expires in 15 mins. :vartype blob_sas_key: str :ivar excel_file_blob_url: URL of the blob into which the ExcelFile is uploaded. :vartype excel_file_blob_url: str :ivar excel_file_blob_sas_key: SAS key to access the blob. It expires in 15 mins. :vartype excel_file_blob_sas_key: str
6259903fd53ae8145f9196d5
class Game(GameABC): <NEW_LINE> <INDENT> class GameNotStartedException(TypeError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, starting_player=GameBoard.Players.UNKNOWN): <NEW_LINE> <INDENT> self.game_board = None <NEW_LINE> self.current_players_turn = None <NEW_LINE> self.starting_player = starting_player <NEW_LINE> <DEDENT> def make_move(self, move_coords): <NEW_LINE> <INDENT> if self.current_players_turn is None: <NEW_LINE> <INDENT> raise TypeError("Method make_move from checkers was run before game " "was initialized") <NEW_LINE> <DEDENT> self.game_board.make_move(self.current_players_turn, move_coords) <NEW_LINE> next_player_dict = { GameBoard.Players.PLAYER1: GameBoard.Players.PLAYER2, GameBoard.Players.PLAYER2: GameBoard.Players.PLAYER1 } <NEW_LINE> self.current_players_turn = next_player_dict[self.current_players_turn] <NEW_LINE> <DEDENT> def get_game_state(self): <NEW_LINE> <INDENT> if self.current_players_turn is None: <NEW_LINE> <INDENT> raise TypeError("Method get_game_state from checkers was run before game " "was initialized") <NEW_LINE> <DEDENT> return self.game_board.check_game_state(self.current_players_turn) <NEW_LINE> <DEDENT> def get_board(self): <NEW_LINE> <INDENT> return self.game_board.get_board_view() <NEW_LINE> <DEDENT> def tell_whose_turn_it_is(self): <NEW_LINE> <INDENT> if self.current_players_turn is None: <NEW_LINE> <INDENT> raise Game.GameNotStartedException("Can`t tell whose turn it is when game has not " "started yet") <NEW_LINE> <DEDENT> return self.current_players_turn <NEW_LINE> <DEDENT> def start_game(self): <NEW_LINE> <INDENT> self.game_board = GameBoard() <NEW_LINE> if self.starting_player == GameBoard.Players.UNKNOWN: <NEW_LINE> <INDENT> self.current_players_turn = random.choice([ GameBoard.Players.PLAYER1, GameBoard.Players.PLAYER2]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.current_players_turn = self.starting_player
Provides games interface for player
6259903f8e71fb1e983bcd46
class Result(object): <NEW_LINE> <INDENT> def __init__(self, L, E, m, m2, corr): <NEW_LINE> <INDENT> self.L = L <NEW_LINE> self.energy_density = E <NEW_LINE> self.magnetisation = m <NEW_LINE> self.magnetisation_squared = m2 <NEW_LINE> self.correlation = corr
A place to store results of an experiment
6259903f07f4c71912bb06ab
class Order(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, related_name='order', on_delete=models.CASCADE) <NEW_LINE> dish = models.ForeignKey(Dish, related_name='order', on_delete=models.CASCADE) <NEW_LINE> amount = models.IntegerField() <NEW_LINE> paid = models.BooleanField(default=False) <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "order: " + self.dish.name + ", by " + self.user.name
User: point to the user object made this order Dish: point to the dish object of this order Amount: specify how many serves ordered Paid: whether this order has been paid
6259903f16aa5153ce401766
class BasicStem(CNNBlockBase): <NEW_LINE> <INDENT> def __init__(self, in_channels=3, out_channels=64, norm="BN"): <NEW_LINE> <INDENT> super().__init__(in_channels, out_channels, 4) <NEW_LINE> self.in_channels = in_channels <NEW_LINE> self.conv1 = Conv2d( in_channels, out_channels, kernel_size=3, stride=2, padding=1, bias=False, norm=get_norm(norm, out_channels), ) <NEW_LINE> weight_init.c2_msra_fill(self.conv1) <NEW_LINE> self.conv2 = Conv2d( out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False, norm=get_norm(norm, out_channels), ) <NEW_LINE> weight_init.c2_msra_fill(self.conv2) <NEW_LINE> self.conv3 = Conv2d( out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False, norm=get_norm(norm, out_channels), ) <NEW_LINE> weight_init.c2_msra_fill(self.conv3) <NEW_LINE> self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = F.relu_(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = F.relu_(x) <NEW_LINE> x = self.conv3(x) <NEW_LINE> x = F.relu_(x) <NEW_LINE> x = self.pool(x) <NEW_LINE> return x
The standard ResNet stem (layers before the first residual block).
6259903f21a7993f00c671e6
class MplData(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.img = None <NEW_LINE> self.WD = 12 <NEW_LINE> self.HG = 18 <NEW_LINE> <DEDENT> def read_img(self, name): <NEW_LINE> <INDENT> self.filename = name <NEW_LINE> self.img = cv2.imread(name) <NEW_LINE> <DEDENT> def save_img(self, name): <NEW_LINE> <INDENT> cv2.imwrite(name, self.img) <NEW_LINE> <DEDENT> def set(self,para): <NEW_LINE> <INDENT> self.WD, self.HG = para <NEW_LINE> <DEDENT> def process_img(self): <NEW_LINE> <INDENT> self.img, self.cha, self.features = recfunc.process(self.img, self.WD, self.HG) <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> self.inputLayerSize = self.WD * self.HG <NEW_LINE> self.hiddenLayerSize = 15 <NEW_LINE> self.outLayersize = 10 <NEW_LINE> self.featuresResult = np.array(4*[0,1,2,3,4,5,6,7,8,9]) <NEW_LINE> self.w1, self.b1, self.w2, self.b2 = recfunc.creat_net(self.inputLayerSize, self.hiddenLayerSize, self.outLayersize) <NEW_LINE> self.w1, self.b1, self.w2, self.b2 = recfunc.SGD(self.features, self.featuresResult, self.inputLayerSize, self.outLayersize, self.w1, self.b1, self.w2, self.b2) <NEW_LINE> <DEDENT> def recognize(self): <NEW_LINE> <INDENT> self.result = recfunc.rec(self.features,self.w1, self.b1, self.w2, self.b2)
存放和处理图片数据的类
6259903f66673b3332c31672
class Quadric(SpatialFilter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> SpatialFilter.__init__(self, radius=1.5) <NEW_LINE> <DEDENT> def weight(self, x): <NEW_LINE> <INDENT> if x < 0.75: <NEW_LINE> <INDENT> return 0.75 - x * x <NEW_LINE> <DEDENT> elif x < 1.5: <NEW_LINE> <INDENT> t = x - 1.5 <NEW_LINE> return 0.5 * t * t <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0.0
Quadric filter (radius = 1.5). Weight function:: | 0.0 ≤ x < 0.5: 0.75 - x*x w(x) = | 0.5 ≤ x < 1.5: 0.5 - (x-1.5)^2 | 1.5 ≤ x : 0
6259903f96565a6dacd2d8c7
class Edit(generic.edit.UpdateView): <NEW_LINE> <INDENT> template_name = 'identity/edit.html' <NEW_LINE> form_class = UserEditForm <NEW_LINE> success_url = reverse_lazy('homepage') <NEW_LINE> model = Identity <NEW_LINE> @method_decorator(never_cache) <NEW_LINE> @method_decorator(login_required) <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(Edit, self).dispatch(request, *args, **kwargs) <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.password_form = SetPasswordForm(user=request.user) <NEW_LINE> return super(Edit, self).get(request, *args, **kwargs) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.object = self.get_object() <NEW_LINE> forms_valid = True <NEW_LINE> change_password = False <NEW_LINE> form = self.get_form(self.get_form_class()) <NEW_LINE> if not form.is_valid(): <NEW_LINE> <INDENT> forms_valid = False <NEW_LINE> <DEDENT> if self.request.POST.get('new_password1'): <NEW_LINE> <INDENT> change_password = True <NEW_LINE> self.password_form = SetPasswordForm( data=request.POST, user=request.user) <NEW_LINE> if not self.password_form.is_valid(): <NEW_LINE> <INDENT> forms_valid = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.password_form = SetPasswordForm(user=request.user) <NEW_LINE> <DEDENT> if forms_valid: <NEW_LINE> <INDENT> form.save() <NEW_LINE> if change_password: <NEW_LINE> <INDENT> self.password_form.save() <NEW_LINE> <DEDENT> self.notifications_form.save() <NEW_LINE> return HttpResponseRedirect(self.get_success_url()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.render_to_response( self.get_context_data(form=form)) <NEW_LINE> <DEDENT> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> return self.request.user <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> return super(Edit, self).get_context_data( password_form=self.password_form, notifications_form=self.notifications_form, **kwargs )
User profile editing
6259903f8da39b475be04468
class AnnotatorDelete(BaseModel): <NEW_LINE> <INDENT> id: str
Fields information needed for Delete
6259903fb830903b9686edb6
class ShutdownClusters(mortartask.MortarClusterShutdownTask): <NEW_LINE> <INDENT> output_base_path = luigi.Parameter() <NEW_LINE> mongodb_output_collection_name = luigi.Parameter() <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return [SanityTestUICollection(output_base_path=self.output_base_path, mongodb_output_collection_name=self.mongodb_output_collection_name)] <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return [S3Target(create_full_path(self.output_base_path, self.__class__.__name__))]
When the pipeline is completed, shut down all active clusters not currently running jobs
6259903f6fece00bbacccc2a
class QueueStorage: <NEW_LINE> <INDENT> def __init__(self, loop, pool): <NEW_LINE> <INDENT> self.loop = loop <NEW_LINE> self.pool = pool <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return self.loop.run_until_complete(size(self.pool))
A mixin class to preserve compatability with asyncio.Queue which calls len(self._queue)
6259903f26238365f5faddd2
class CallInfo(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.call_info = {} <NEW_LINE> self.patched_func_names = [ 'setRange', 'setValue', 'setLabelText', 'show', 'close', 'labelText', 'setLabelText' ] <NEW_LINE> self.register_functions() <NEW_LINE> <DEDENT> def function_generator(self, name): <NEW_LINE> <INDENT> def call_recorder(*args, **kwargs): <NEW_LINE> <INDENT> self.call_info[name] = [args, kwargs] <NEW_LINE> <DEDENT> return call_recorder <NEW_LINE> <DEDENT> def register_functions(self): <NEW_LINE> <INDENT> for f_name in self.patched_func_names: <NEW_LINE> <INDENT> setattr(self, f_name, self.function_generator(f_name))
A class for completely patching other classes. CallInfo classes or derived classes will not function correctly but it will store the call info, that is it will store which function or method is called and what was the arguments.
6259903fd10714528d69efc9
class TableExtension(markdown.Extension): <NEW_LINE> <INDENT> def extendMarkdown(self, md, md_globals): <NEW_LINE> <INDENT> md.parser.blockprocessors.add('table', TableProcessor(md.parser), '<hashheader')
Add tables to Markdown.
6259903f1d351010ab8f4d98
class Message(Resource): <NEW_LINE> <INDENT> name = 'message' <NEW_LINE> version = 1 <NEW_LINE> class schema: <NEW_LINE> <INDENT> id = UUID(operators='equal') <NEW_LINE> request_id = UUID(nonempty=True, operators='equal') <NEW_LINE> author = UUID(nonnull=True, operators='equal') <NEW_LINE> occurrence = DateTime(utc=True, readonly=True, sortable=True) <NEW_LINE> message = Text()
A request message.
6259903f6e29344779b018cc
class ConnectionMonitorResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'id': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'source': {'key': 'properties.source', 'type': 'ConnectionMonitorSource'}, 'destination': {'key': 'properties.destination', 'type': 'ConnectionMonitorDestination'}, 'auto_start': {'key': 'properties.autoStart', 'type': 'bool'}, 'monitoring_interval_in_seconds': {'key': 'properties.monitoringIntervalInSeconds', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'monitoring_status': {'key': 'properties.monitoringStatus', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ConnectionMonitorResult, self).__init__(**kwargs) <NEW_LINE> self.name = None <NEW_LINE> self.id = None <NEW_LINE> self.etag = kwargs.get('etag', "A unique read-only string that changes whenever the resource is updated.") <NEW_LINE> self.type = None <NEW_LINE> self.location = kwargs.get('location', None) <NEW_LINE> self.tags = kwargs.get('tags', None) <NEW_LINE> self.source = kwargs.get('source', None) <NEW_LINE> self.destination = kwargs.get('destination', None) <NEW_LINE> self.auto_start = kwargs.get('auto_start', True) <NEW_LINE> self.monitoring_interval_in_seconds = kwargs.get('monitoring_interval_in_seconds', 60) <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.start_time = kwargs.get('start_time', None) <NEW_LINE> self.monitoring_status = kwargs.get('monitoring_status', None)
Information about the connection monitor. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: Name of the connection monitor. :vartype name: str :ivar id: ID of the connection monitor. :vartype id: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :ivar type: Connection monitor type. :vartype type: str :param location: Connection monitor location. :type location: str :param tags: A set of tags. Connection monitor tags. :type tags: dict[str, str] :param source: Describes the source of connection monitor. :type source: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorSource :param destination: Describes the destination of connection monitor. :type destination: ~azure.mgmt.network.v2019_04_01.models.ConnectionMonitorDestination :param auto_start: Determines if the connection monitor will start automatically once created. :type auto_start: bool :param monitoring_interval_in_seconds: Monitoring interval in seconds. :type monitoring_interval_in_seconds: int :ivar provisioning_state: The provisioning state of the connection monitor. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2019_04_01.models.ProvisioningState :param start_time: The date and time when the connection monitor was started. :type start_time: ~datetime.datetime :param monitoring_status: The monitoring status of the connection monitor. :type monitoring_status: str
6259903f8e05c05ec3f6f798
class GroupList(APIView): <NEW_LINE> <INDENT> permission_classes = (ApiAuthRequired,) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> params = request.DATA <NEW_LINE> groupname = params['name'] <NEW_LINE> group = CoreGroup.objects.create(name=groupname) <NEW_LINE> for user in params['user[]']: <NEW_LINE> <INDENT> group.user_set.add(user) <NEW_LINE> <DEDENT> serialized_data = GroupSerializer(group).data <NEW_LINE> response = Response(serialized_data) <NEW_LINE> return response <NEW_LINE> <DEDENT> def get(self, request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> all_groups = user.group_set.order_by('name') <NEW_LINE> serialized_data = GroupSerializer(all_groups).data <NEW_LINE> response = Response(serialized_data) <NEW_LINE> return response
Every User is assigned to a Group of their own name initially. This 'usergroup' is then in charge of all the identities, providers, instances, and applications which can be shared among other, larger groups, but can still be tracked back to the original user who made the API request.
6259903f21bff66bcd723ee5
class Choice(Setting): <NEW_LINE> <INDENT> typename = 'choice' <NEW_LINE> def __init__(self, name, vallist, val, descriptions=None, uilist=None, **args): <NEW_LINE> <INDENT> assert type(vallist) in (list, tuple) <NEW_LINE> self.vallist = vallist <NEW_LINE> self.descriptions = descriptions <NEW_LINE> self.uilist = uilist <NEW_LINE> Setting.__init__(self, name, val, **args) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return self._copyHelper( (self.vallist,), (), { 'descriptions': self.descriptions, 'uilist': self.uilist, } ) <NEW_LINE> <DEDENT> def normalize(self, val): <NEW_LINE> <INDENT> if val in self.vallist: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise utils.InvalidType <NEW_LINE> <DEDENT> <DEDENT> def toUIText(self): <NEW_LINE> <INDENT> return self.val <NEW_LINE> <DEDENT> def fromUIText(self, text): <NEW_LINE> <INDENT> if text in self.vallist: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise utils.InvalidType <NEW_LINE> <DEDENT> <DEDENT> def makeControl(self, *args): <NEW_LINE> <INDENT> return controls.Choice( self, False, self.vallist, descriptions=self.descriptions, uilist=self.uilist, *args )
One out of a list of strings.
6259903fbe383301e0254a93
class GraphBar(ur.Widget): <NEW_LINE> <INDENT> _sizing = frozenset([ur.FLOW]) <NEW_LINE> ignore_focus = True <NEW_LINE> def __init__(self, minimum=None, maximum=None, format=' {min}-{max}', delta=timedelta(minutes=1), chars=' ▁▂▃▄▅▆▇█', bar_align='<'): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.minimum = minimum <NEW_LINE> self.maximum = maximum <NEW_LINE> self.delta = delta <NEW_LINE> self.chars = chars <NEW_LINE> self.bar_align = bar_align <NEW_LINE> self._format = format <NEW_LINE> self._minimum = None <NEW_LINE> self._maximum = None <NEW_LINE> self._history = None <NEW_LINE> <DEDENT> def rows(self, size, focus=False): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def update(self, stats): <NEW_LINE> <INDENT> if stats: <NEW_LINE> <INDENT> timestamps, readings = zip(*stats) <NEW_LINE> values = sorted(readings) <NEW_LINE> self._minimum = values[0] if self.minimum is None else self.minimum <NEW_LINE> self._maximum = values[-1] if self.maximum is None else self.maximum <NEW_LINE> assert self._maximum >= self._minimum <NEW_LINE> finish = len(timestamps) - 1 <NEW_LINE> value = readings[finish] <NEW_LINE> history = [] <NEW_LINE> for i in range(ceil((timestamps[-1] - timestamps[0]) / self.delta)): <NEW_LINE> <INDENT> start = bisect_left(timestamps, timestamps[-1] - i * self.delta) <NEW_LINE> values = sorted(readings[start:finish]) <NEW_LINE> if values: <NEW_LINE> <INDENT> value = values[len(values) // 2] <NEW_LINE> <DEDENT> history.append(value) <NEW_LINE> finish = start <NEW_LINE> <DEDENT> self._history = history <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._minimum = self._maximum = self._history = None <NEW_LINE> <DEDENT> self._invalidate() <NEW_LINE> <DEDENT> def render(self, size, focus=False): <NEW_LINE> <INDENT> (maxcol,) = size <NEW_LINE> if self._history is None: <NEW_LINE> <INDENT> return ur.SolidCanvas('╌', maxcol, 1) <NEW_LINE> <DEDENT> if self._minimum == self._maximum: <NEW_LINE> <INDENT> return ur.SolidCanvas('╌', maxcol, 1) <NEW_LINE> <DEDENT> if isinstance(self._format, str): <NEW_LINE> <INDENT> label = self._format.format(min=self._minimum, max=self._maximum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = self._format(self._minimum, self._maximum) <NEW_LINE> <DEDENT> bar_len = maxcol - len(label) <NEW_LINE> if bar_len < 4: <NEW_LINE> <INDENT> return ur.SolidCanvas('▸', maxcol, 1) <NEW_LINE> <DEDENT> step = (self._maximum - self._minimum) / len(self.chars) <NEW_LINE> bar_ranges = [ self._minimum + (i * step) for i in range(len(self.chars)) ] <NEW_LINE> bar = ''.join( self.chars[min(len(self.chars) - 1, bisect_left(bar_ranges, value))] for value in reversed(self._history[:bar_len]) ) <NEW_LINE> s = '{bar:{bar_align}{bar_len}s}{label}'.format( bar=bar, bar_align=self.bar_align, bar_len=bar_len, label=label) <NEW_LINE> text, cs = ur.apply_target_encoding(s) <NEW_LINE> return ur.TextCanvas([text], [cs], maxcol=maxcol)
A right-to-left scrolling historical bar-chart plotting the median of each minute of a metric using unicode chars.
6259903fdc8b845886d54832
class ExtentionsManager(object): <NEW_LINE> <INDENT> EXTENTIONS = { "update-profile": UpdateProfile } <NEW_LINE> POST_RUN = set([ "update-profile" ]) <NEW_LINE> def __init__(self, options): <NEW_LINE> <INDENT> self._loaded_extentions = {} <NEW_LINE> self._options = options <NEW_LINE> <DEDENT> def _get_extention(self, name): <NEW_LINE> <INDENT> if name not in self._loaded_extentions: <NEW_LINE> <INDENT> constructor = ExtentionsManager.EXTENTIONS[name] <NEW_LINE> self._loaded_extentions[name] = constructor(self._options) <NEW_LINE> <DEDENT> return self._loaded_extentions[name] <NEW_LINE> <DEDENT> def post_run(self, command, executor): <NEW_LINE> <INDENT> sys.stderr.write(executor.stderr()) <NEW_LINE> sys.stdout.write(executor.stdout()) <NEW_LINE> configured = set(command.extentions.keys()) <NEW_LINE> extentions = configured & ExtentionsManager.POST_RUN <NEW_LINE> reload_conf = False <NEW_LINE> for extention in extentions: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ext = self._get_extention(extention) <NEW_LINE> reload_conf = ext.post_run(command, executor) or reload_conf <NEW_LINE> <DEDENT> except SkipException as ex: <NEW_LINE> <INDENT> sys.stderr.write( "[ERROR] Profile update failed: {0}. Moving on.\n".format(str(ex)) ) <NEW_LINE> <DEDENT> <DEDENT> return reload_conf
Manages the execution of extentions.
6259903f30c21e258be99a88
class TokenizerOverride(Model): <NEW_LINE> <INDENT> def __init__(self, character, tokenizer_class): <NEW_LINE> <INDENT> self._config = { "character": character, "tokenizer-class": tokenizer_class } <NEW_LINE> <DEDENT> def character(self): <NEW_LINE> <INDENT> return self._get_config_property('character') <NEW_LINE> <DEDENT> def set_character(self, character): <NEW_LINE> <INDENT> self._config['character'] = character <NEW_LINE> return self <NEW_LINE> <DEDENT> def tokenizer_override(self): <NEW_LINE> <INDENT> return self._get_config_property('tokenizer-override') <NEW_LINE> <DEDENT> def set_tokenizer_override(self, override): <NEW_LINE> <INDENT> self._config['tokenizer-override'] = override <NEW_LINE> return self
A tokenizer override.
6259903f4e696a045264e75f
class AttenMlpFinal(Module): <NEW_LINE> <INDENT> def __init__(self, in_features, hop, hidden=512, temperature=0.07, phi='atten', bias=False): <NEW_LINE> <INDENT> super(AttenMlpFinal, self).__init__() <NEW_LINE> self.in_features = in_features <NEW_LINE> self.hidden = hidden <NEW_LINE> self.temperature = temperature <NEW_LINE> self.act = nn.ReLU() <NEW_LINE> self.hop = hop <NEW_LINE> self.phi = phi <NEW_LINE> if self.phi == 'atten': <NEW_LINE> <INDENT> self.linear1 = nn.Linear(self.in_features * 2, self.hidden, bias=False) <NEW_LINE> self.linear2 = nn.Linear(self.hidden, 1, bias=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.linear3 = nn.Linear(self.in_features * (self.hop + 1), self.in_features, bias=False) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, q_vec, k_vec, v_vec): <NEW_LINE> <INDENT> if self.phi == 'atten': <NEW_LINE> <INDENT> bsz, m, d = k_vec.shape <NEW_LINE> q_vec = q_vec.view(-1, 1, self.in_features).repeat(1, m, 1) <NEW_LINE> xx = torch.cat((q_vec, k_vec), dim=-1) <NEW_LINE> xx = self.linear1(xx) <NEW_LINE> xx = self.act(xx) <NEW_LINE> xx = self.linear2(xx) <NEW_LINE> xx = torch.softmax(xx, dim=1) <NEW_LINE> v_vec = torch.mul(v_vec, xx) <NEW_LINE> v_vec = torch.sum(v_vec, dim=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> m, seq_len, d = k_vec.shape <NEW_LINE> v_vec = self.linear3(k_vec.view(m, -1)) <NEW_LINE> v_vec = torch.nn.functional.relu(v_vec) <NEW_LINE> <DEDENT> return v_vec <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
6259903fd6c5a102081e33a1
class Date(datetime): <NEW_LINE> <INDENT> format = DEFAULT_DATE_FORMAT <NEW_LINE> @property <NEW_LINE> def minutes(self): <NEW_LINE> <INDENT> return self.minute <NEW_LINE> <DEDENT> @property <NEW_LINE> def seconds(self): <NEW_LINE> <INDENT> return self.second <NEW_LINE> <DEDENT> @property <NEW_LINE> def microseconds(self): <NEW_LINE> <INDENT> return self.microsecond <NEW_LINE> <DEDENT> @property <NEW_LINE> def week(self): <NEW_LINE> <INDENT> return self.isocalendar()[1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def weekday(self): <NEW_LINE> <INDENT> return self.isocalendar()[2] <NEW_LINE> <DEDENT> @property <NEW_LINE> def timestamp(self): <NEW_LINE> <INDENT> return int(mktime(self.timetuple())) <NEW_LINE> <DEDENT> def strftime(self, format): <NEW_LINE> <INDENT> if self.year < 1900: <NEW_LINE> <INDENT> return strftime(format, (1900,) + self.timetuple()[1:]).replace("1900", str(self.year), 1) <NEW_LINE> <DEDENT> return datetime.strftime(self, format) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return date(self.timestamp) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.strftime(self.format) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Date(%s)" % repr(self.__str__()) <NEW_LINE> <DEDENT> def __iadd__(self, time): <NEW_LINE> <INDENT> return self.__add__(time) <NEW_LINE> <DEDENT> def __isub__(self, time): <NEW_LINE> <INDENT> return self.__sub__(time) <NEW_LINE> <DEDENT> def __add__(self, time): <NEW_LINE> <INDENT> d = datetime.__add__(self, time) <NEW_LINE> return date(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, self.format) <NEW_LINE> <DEDENT> def __sub__(self, time): <NEW_LINE> <INDENT> d = datetime.__sub__(self, time) <NEW_LINE> if isinstance(d, timedelta): <NEW_LINE> <INDENT> return d <NEW_LINE> <DEDENT> return date(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, self.format)
A convenience wrapper for datetime.datetime with a default string format.
6259903f8a349b6b436874c2
class TimerRef: <NEW_LINE> <INDENT> def current_timing_method(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = livesplit_core_native.Timer_current_timing_method(self.ptr) <NEW_LINE> return result <NEW_LINE> <DEDENT> def current_comparison(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = livesplit_core_native.Timer_current_comparison(self.ptr).decode() <NEW_LINE> return result <NEW_LINE> <DEDENT> def is_game_time_initialized(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = livesplit_core_native.Timer_is_game_time_initialized(self.ptr) <NEW_LINE> return result <NEW_LINE> <DEDENT> def is_game_time_paused(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = livesplit_core_native.Timer_is_game_time_paused(self.ptr) <NEW_LINE> return result <NEW_LINE> <DEDENT> def loading_times(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = TimeSpanRef(livesplit_core_native.Timer_loading_times(self.ptr)) <NEW_LINE> return result <NEW_LINE> <DEDENT> def current_phase(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = livesplit_core_native.Timer_current_phase(self.ptr) <NEW_LINE> return result <NEW_LINE> <DEDENT> def get_run(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = RunRef(livesplit_core_native.Timer_get_run(self.ptr)) <NEW_LINE> return result <NEW_LINE> <DEDENT> def save_as_lss(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = livesplit_core_native.Timer_save_as_lss(self.ptr).decode() <NEW_LINE> return result <NEW_LINE> <DEDENT> def print_debug(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> livesplit_core_native.Timer_print_debug(self.ptr) <NEW_LINE> <DEDENT> def current_time(self): <NEW_LINE> <INDENT> if self.ptr == None: <NEW_LINE> <INDENT> raise Exception("self is disposed") <NEW_LINE> <DEDENT> result = TimeRef(livesplit_core_native.Timer_current_time(self.ptr)) <NEW_LINE> return result <NEW_LINE> <DEDENT> def __init__(self, ptr): <NEW_LINE> <INDENT> self.ptr = ptr
A Timer provides all the capabilities necessary for doing speedrun attempts.
6259903fb57a9660fecd2cf7
class Solution: <NEW_LINE> <INDENT> def singleNumber(self, A): <NEW_LINE> <INDENT> result = A[0] <NEW_LINE> for a in A[1:]: <NEW_LINE> <INDENT> result ^= a <NEW_LINE> <DEDENT> return result
@param A: An integer array @return: An integer
6259903f097d151d1a2c22e2
class LinkManField(Base): <NEW_LINE> <INDENT> _fields_ = [ ('BrokerID', ctypes.c_char * 11), ('InvestorID', ctypes.c_char * 13), ('PersonType', ctypes.c_char), ('IdentifiedCardType', ctypes.c_char), ('IdentifiedCardNo', ctypes.c_char * 51), ('PersonName', ctypes.c_char * 81), ('Telephone', ctypes.c_char * 41), ('Address', ctypes.c_char * 101), ('ZipCode', ctypes.c_char * 7), ('Priority', ctypes.c_int), ('UOAZipCode', ctypes.c_char * 11), ('PersonFullName', ctypes.c_char * 101), ] <NEW_LINE> def __init__(self, BrokerID='', InvestorID='', PersonType='', IdentifiedCardType='', IdentifiedCardNo='', PersonName='', Telephone='', Address='', ZipCode='', Priority=0, UOAZipCode='', PersonFullName=''): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.BrokerID = self._to_bytes(BrokerID) <NEW_LINE> self.InvestorID = self._to_bytes(InvestorID) <NEW_LINE> self.PersonType = self._to_bytes(PersonType) <NEW_LINE> self.IdentifiedCardType = self._to_bytes(IdentifiedCardType) <NEW_LINE> self.IdentifiedCardNo = self._to_bytes(IdentifiedCardNo) <NEW_LINE> self.PersonName = self._to_bytes(PersonName) <NEW_LINE> self.Telephone = self._to_bytes(Telephone) <NEW_LINE> self.Address = self._to_bytes(Address) <NEW_LINE> self.ZipCode = self._to_bytes(ZipCode) <NEW_LINE> self.Priority = int(Priority) <NEW_LINE> self.UOAZipCode = self._to_bytes(UOAZipCode) <NEW_LINE> self.PersonFullName = self._to_bytes(PersonFullName)
联系人
6259903fe76e3b2f99fd9c88
class IpAddress(Model): <NEW_LINE> <INDENT> _attribute_map = { 'ip_address': {'key': 'ipAddress', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, ip_address: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(IpAddress, self).__init__(**kwargs) <NEW_LINE> self.ip_address = ip_address
Specifies the IP address of the network interface. :param ip_address: Specifies the IP address of the network interface. :type ip_address: str
6259903fd99f1b3c44d06919
class RGit2r(RPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/ropensci/git2r" <NEW_LINE> url = "https://cran.r-project.org/src/contrib/git2r_0.18.0.tar.gz" <NEW_LINE> list_url = "https://cran.r-project.org/src/contrib/Archive/git2r" <NEW_LINE> version('0.18.0', 'fb5741eb490c3d6e23a751a72336f24d') <NEW_LINE> version('0.15.0', '57658b3298f9b9aadc0dd77b4ef6a1e1') <NEW_LINE> depends_on('[email protected]:') <NEW_LINE> depends_on('zlib') <NEW_LINE> depends_on('openssl')
Interface to the 'libgit2' library, which is a pure C implementation of the 'Git' core methods. Provides access to 'Git' repositories to extract data and running some basic 'Git' commands.
6259903fdc8b845886d54834
class nurbbank_zero_TestOutput(TestOutput): <NEW_LINE> <INDENT> __test__ = True <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(self): <NEW_LINE> <INDENT> super(nurbbank_zero_TestOutput, self).setUpClass('huc12__60099.gms', 'huc12__60099.json')
Tests model generated output versus known static output.
6259903f30c21e258be99a8a
class CreateCourseHandler(Handler): <NEW_LINE> <INDENT> def render_create(self, name="", instructor="", description="", error=""): <NEW_LINE> <INDENT> self.render("create.html", name=name, instructor=instructor, description=description, error=error) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> self.render_create() <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> name = self.request.get("course_name") <NEW_LINE> instructor = self.request.get("instructor_name") <NEW_LINE> description = self.request.get("description") <NEW_LINE> if name and instructor and description: <NEW_LINE> <INDENT> b = Course(name=name, instructor=instructor, description=description) <NEW_LINE> b.put() <NEW_LINE> self.redirect('/browse') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error = "Please enter a Course Name, Instructor, and Description!" <NEW_LINE> self.render_create(name, instructor, description, error)
Renders course creation template and adds course to db
6259903f66673b3332c31676
class NorGate(_SimpleCombinatorial): <NEW_LINE> <INDENT> def evaluate(self, a, b): <NEW_LINE> <INDENT> if (a == "1") or (b == "1"): <NEW_LINE> <INDENT> return "0" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "1"
A Nor gate.
6259903f8da39b475be0446c
class plugin(object): <NEW_LINE> <INDENT> hooks = {} <NEW_LINE> name = "Feed parser" <NEW_LINE> commands = { } <NEW_LINE> def __init__(self, irc): <NEW_LINE> <INDENT> self.irc = irc <NEW_LINE> self.help = { } <NEW_LINE> self.settings_handler = yaml_loader(True, "feeds") <NEW_LINE> self.load() <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> self.settings = self.settings_handler.load("settings") <NEW_LINE> self.feeds = self.settings_handler.load("feeds")
Feed parser plugin. Used to notify channels of changes to feeds
6259903f1f5feb6acb163e71
class Parser: <NEW_LINE> <INDENT> host_url = 'http://coursefinder.utoronto.ca/course-search/search/' <NEW_LINE> course_codes = [] <NEW_LINE> def load_course_codes(self): <NEW_LINE> <INDENT> scraper = Scraper.Scraper() <NEW_LINE> url = Parser.host_url + 'courseSearch/course/search' <NEW_LINE> params = { 'requirements': '', 'queryText': '', 'campusParam': 'St. George,Scarborough,Mississauga'} <NEW_LINE> json_ = scraper.get_data(url, params=params, write=False, json=True) <NEW_LINE> if json_: <NEW_LINE> <INDENT> for course_data in json_["aaData"]: <NEW_LINE> <INDENT> Parser.course_codes.append( re.search('offImg(.*)', course_data[0]).group(1).split('"')[0] ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def create_json(self, location=''): <NEW_LINE> <INDENT> t1 = time.time() <NEW_LINE> parsing_source = 'http://coursefinder.utoronto.ca/course-search/search/courseInquiry/' <NEW_LINE> course_info = {'UofT-Courses' : []} <NEW_LINE> self.load_course_codes() <NEW_LINE> if self.course_codes: <NEW_LINE> <INDENT> print('Source: {}'.format(parsing_source)) <NEW_LINE> for code in self.course_codes: <NEW_LINE> <INDENT> courseParser = CourseParser.CourseParser(code) <NEW_LINE> course_info['UofT-Courses'].append(courseParser.parse_html()) <NEW_LINE> sys.stdout.write('\r') <NEW_LINE> sys.stdout.write('Parsing course with code %s ' % (code[:-5])) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> if course_info['UofT-Courses']: <NEW_LINE> <INDENT> f = open(location + 'courses.json', 'w') <NEW_LINE> json.dump(course_info, f, indent=4, sort_keys=True, separators=(',', ':')) <NEW_LINE> <DEDENT> t2 = time.time() <NEW_LINE> print('\n-- Summary --') <NEW_LINE> print('Took {} minutes to parse {} courses'.format((t2 - t1)/60, len(self.course_codes)))
A parser to parse information of every course -- reference -- :see: https://docs.python.org/3/library/sys.html
6259903f6fece00bbacccc2e
class GitCommit(Command): <NEW_LINE> <INDENT> def invoked(self, ctx): <NEW_LINE> <INDENT> print("fake git commit") <NEW_LINE> <DEDENT> def register_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument( '-m', '--message', metavar='<msg>', help="Use given <msg> as the commit message")
The 'git commit' command.
6259903f50485f2cf55dc202
class DbusWeakCallback (WeakCallback): <NEW_LINE> <INDENT> def object_deleted(self, wref): <NEW_LINE> <INDENT> if self.token: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.token.remove() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.token = None
Will use @token if set as follows: token.remove()
6259903f30dc7b76659a0ab0
class MemoryKVPRecord(KVPRecord): <NEW_LINE> <INDENT> def __init__(self, kvpid, d): <NEW_LINE> <INDENT> self._kvpid = kvpid <NEW_LINE> self._d = d <NEW_LINE> <DEDENT> @property <NEW_LINE> def key(self): <NEW_LINE> <INDENT> return self._kvpid.key <NEW_LINE> <DEDENT> @property <NEW_LINE> def index(self): <NEW_LINE> <INDENT> return self._kvpid.index <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return len(self._d['value']) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._d['value'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def timestamp(self): <NEW_LINE> <INDENT> return self._d.get('timestamp') <NEW_LINE> <DEDENT> @timestamp.setter <NEW_LINE> def timestamp(self, seconds): <NEW_LINE> <INDENT> self._d['timestamp'] = seconds <NEW_LINE> <DEDENT> @property <NEW_LINE> def time_to_live(self): <NEW_LINE> <INDENT> return self._d.get('time_to_live') <NEW_LINE> <DEDENT> @time_to_live.setter <NEW_LINE> def time_to_live(self, seconds): <NEW_LINE> <INDENT> self._d['time_to_live'] = seconds <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_original(self): <NEW_LINE> <INDENT> return self._d.get('is_original') <NEW_LINE> <DEDENT> @is_original.setter <NEW_LINE> def is_original(self, b): <NEW_LINE> <INDENT> self._d['is_original'] = b <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_update(self): <NEW_LINE> <INDENT> return self._d.get('last_update') <NEW_LINE> <DEDENT> @last_update.setter <NEW_LINE> def last_update(self, seconds): <NEW_LINE> <INDENT> self._d['last_update'] = seconds
The record associated with :class:`MemoryKVPTable`
6259903fc432627299fa4240
class Mod(VBA_Object): <NEW_LINE> <INDENT> def __init__(self, original_str, location, tokens): <NEW_LINE> <INDENT> super(Mod, self).__init__(original_str, location, tokens) <NEW_LINE> self.arg = tokens[0][::2] <NEW_LINE> <DEDENT> def eval(self, context, params=None): <NEW_LINE> <INDENT> evaluated_args = eval_args(self.arg, context) <NEW_LINE> if ((isinstance(evaluated_args, Iterable)) and ("**MATCH ANY**" in evaluated_args)): <NEW_LINE> <INDENT> return "**MATCH ANY**" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if (log.getEffectiveLevel() == logging.DEBUG): <NEW_LINE> <INDENT> log.debug("Compute mod " + str(self.arg)) <NEW_LINE> <DEDENT> return reduce(lambda x, y: int(x) % int(y), coerce_args(evaluated_args, preferred_type="int")) <NEW_LINE> <DEDENT> except (TypeError, ValueError) as e: <NEW_LINE> <INDENT> log.error('Impossible to mod arguments of different types. ' + str(e)) <NEW_LINE> return '' <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> log.error('Mod division by zero error.') <NEW_LINE> return '' <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return debug_repr("mod", self.arg) <NEW_LINE> return ' mod '.join(map(repr, self.arg)) <NEW_LINE> <DEDENT> def to_python(self, context, params=None, indent=0): <NEW_LINE> <INDENT> r = "" <NEW_LINE> first = True <NEW_LINE> for arg in self.arg: <NEW_LINE> <INDENT> if (not first): <NEW_LINE> <INDENT> r += " % " <NEW_LINE> <DEDENT> first = False <NEW_LINE> r += "coerce_to_num(" + to_python(arg, context, params=params) + ")" <NEW_LINE> <DEDENT> return "(" + r + ")"
VBA Modulo using the operator 'Mod'
6259903fb57a9660fecd2cf9
class ConvergenceStarterTests(SynchronousTestCase): <NEW_LINE> <INDENT> def test_start_convergence(self): <NEW_LINE> <INDENT> svc = ConvergenceStarter('my-dispatcher') <NEW_LINE> log = mock_log() <NEW_LINE> def perform(dispatcher, eff): <NEW_LINE> <INDENT> return succeed((dispatcher, eff)) <NEW_LINE> <DEDENT> d = svc.start_convergence(log, 'tenant', 'group', perform=perform) <NEW_LINE> self.assertEqual( self.successResultOf(d), ('my-dispatcher', Effect(CreateOrSet(path='/groups/divergent/tenant_group', content='dirty')))) <NEW_LINE> log.msg.assert_called_once_with( 'mark-dirty-success', tenant_id='tenant', scaling_group_id='group') <NEW_LINE> <DEDENT> def test_error_marking_dirty(self): <NEW_LINE> <INDENT> svc = ConvergenceStarter('my-dispatcher') <NEW_LINE> log = mock_log() <NEW_LINE> def perform(dispatcher, eff): <NEW_LINE> <INDENT> return fail(RuntimeError('oh no')) <NEW_LINE> <DEDENT> d = svc.start_convergence(log, 'tenant', 'group', perform=perform) <NEW_LINE> self.assertEqual(self.successResultOf(d), None) <NEW_LINE> log.err.assert_called_once_with( CheckFailureValue(RuntimeError('oh no')), 'mark-dirty-failure', tenant_id='tenant', scaling_group_id='group')
Tests for :obj:`ConvergenceStarter`.
6259903f73bcbd0ca4bcb509
class ThreadedGenerator(GenericIterator): <NEW_LINE> <INDENT> def __init__(self, dps, classes, dim, batch_size=8, image_generator=None, extra_aug=False, shuffle=True, seed=173, data_mean=0.0, verbose=0, variable_shape=False, input_n=1, keep=False): <NEW_LINE> <INDENT> self.variable_shape = variable_shape <NEW_LINE> self._aug = None <NEW_LINE> super(ThreadedGenerator, self).__init__(data=dps, classes=classes, dim=dim, batch_size=batch_size, image_generator=image_generator, extra_aug=extra_aug, shuffle=shuffle, seed=seed, data_mean=data_mean, verbose=verbose, input_n=input_n, keep=keep) <NEW_LINE> workers = round((self.batch_size/3 + (self.batch_size % 3 > 0) + 0.5)) <NEW_LINE> self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=workers) <NEW_LINE> <DEDENT> def _get_batches_of_transformed_samples(self, index_array): <NEW_LINE> <INDENT> if self.extra_aug and self._aug is None: <NEW_LINE> <INDENT> self._aug = iaa.Sometimes(0.5, iaa.ContrastNormalization((0.75, 1.5))) <NEW_LINE> <DEDENT> if self.shape is not None: <NEW_LINE> <INDENT> batch_x = np.zeros(tuple([len(index_array)] + list(self.shape)), dtype=np.float32) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> batch_x = None <NEW_LINE> <DEDENT> y = np.zeros(tuple([len(index_array)]), dtype=int) <NEW_LINE> X = self.data[0] <NEW_LINE> Y = self.data[1] <NEW_LINE> futures = {} <NEW_LINE> for i, j in enumerate(index_array): <NEW_LINE> <INDENT> futures[self._executor.submit(self._thread_run_images, X[j], Y[j], self.keep)] = i <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> for f in concurrent.futures.as_completed(futures): <NEW_LINE> <INDENT> example, t_y = f.result() <NEW_LINE> i = futures[f] <NEW_LINE> if batch_x is None: <NEW_LINE> <INDENT> self.shape = example.shape <NEW_LINE> print("Image batch shape: {}".format(self.shape)) <NEW_LINE> batch_x = np.zeros(tuple([len(index_array)] + list(self.shape)), dtype=np.float32) <NEW_LINE> <DEDENT> batch_x[i] = example <NEW_LINE> y[i] = t_y <NEW_LINE> <DEDENT> batch_x = self.image_generator.standardize(batch_x) <NEW_LINE> if self.extra_aug: <NEW_LINE> <INDENT> batch_x = self._aug(images=batch_x) <NEW_LINE> <DEDENT> del futures <NEW_LINE> if self.variable_shape: <NEW_LINE> <INDENT> self.shape = None <NEW_LINE> <DEDENT> if self.input_n > 1: <NEW_LINE> <INDENT> batch_x = [batch_x for _ in range(self.input_n)] <NEW_LINE> <DEDENT> output = (batch_x, keras.utils.to_categorical(y, self.classes)) <NEW_LINE> return output <NEW_LINE> <DEDENT> def _thread_run_images(self, t_x, t_y, keep): <NEW_LINE> <INDENT> example = t_x.read_image(keep_img=keep, size=self.dim, verbose=self.verbose) <NEW_LINE> if self.image_generator is not None: <NEW_LINE> <INDENT> example = self.image_generator.random_transform(example, self.seed) <NEW_LINE> <DEDENT> return example, t_y
Generates batches of images, applies augmentation, resizing, centering...the whole shebang.
6259903f82261d6c52730803
@inside_glslc_testsuite('SpirvAssembly') <NEW_LINE> class TestHybridInputFiles(expect.ValidObjectFile): <NEW_LINE> <INDENT> shader1 = FileShader(empty_main_assembly(), '.spvasm') <NEW_LINE> shader2 = FileShader(empty_main(), '.vert') <NEW_LINE> shader3 = FileShader(empty_main(), '.frag') <NEW_LINE> glslc_args = ['-c', shader1, shader2, shader3]
Tests that glslc accepts a mix of SPIR-V assembly files and GLSL source files.
6259903f287bf620b6272e65
class WADLResolvableDefinition(WADLBase): <NEW_LINE> <INDENT> def __init__(self, application): <NEW_LINE> <INDENT> self._definition = None <NEW_LINE> self.application = application <NEW_LINE> <DEDENT> def resolve_definition(self): <NEW_LINE> <INDENT> if self._definition is not None: <NEW_LINE> <INDENT> return self._definition <NEW_LINE> <DEDENT> object_url = self._get_definition_url() <NEW_LINE> if object_url is None: <NEW_LINE> <INDENT> self._definition = self <NEW_LINE> return self <NEW_LINE> <DEDENT> xml_id = self.application.lookup_xml_id(object_url) <NEW_LINE> definition = self._definition_factory(xml_id) <NEW_LINE> if definition is None: <NEW_LINE> <INDENT> raise KeyError('No such XML ID: "%s"' % object_url) <NEW_LINE> <DEDENT> self._definition = definition <NEW_LINE> return definition <NEW_LINE> <DEDENT> def _definition_factory(self, id): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _get_definition_url(self): <NEW_LINE> <INDENT> raise NotImplementedError()
A base class for objects whose definitions may be references.
6259903f50485f2cf55dc203
class QueryGenerator(object): <NEW_LINE> <INDENT> def __init__(self, user_limit=10000): <NEW_LINE> <INDENT> self._user_limit = user_limit <NEW_LINE> self._words_generator = RandomWords() <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self.next() <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> return (randint(0, self._user_limit), ' '.join( self._words_generator.random_words(count=randint(1, 5)))) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self
Query rnadom generator to generate tuples (user_id, query_terms)
6259903f1f5feb6acb163e73
class GlozzDocument(Document): <NEW_LINE> <INDENT> def __init__(self, hashcode, unit, rels, schemas, text): <NEW_LINE> <INDENT> Document.__init__(self, unit, rels, schemas, text) <NEW_LINE> self.hashcode = hashcode <NEW_LINE> <DEDENT> def to_xml(self, settings=DEFAULT_OUTPUT_SETTINGS): <NEW_LINE> <INDENT> elm = ET.Element('annotations') <NEW_LINE> if self.hashcode is not None: <NEW_LINE> <INDENT> elm.append(ET.Element('metadata', corpusHashcode=self.hashcode)) <NEW_LINE> <DEDENT> elm.extend([glozz_annotation_to_xml(x, 'unit', settings) for x in self.units]) <NEW_LINE> elm.extend([glozz_annotation_to_xml(x, 'relation', settings) for x in self.relations]) <NEW_LINE> elm.extend([glozz_annotation_to_xml(x, 'schema', settings) for x in self.schemas]) <NEW_LINE> return elm <NEW_LINE> <DEDENT> def set_origin(self, origin): <NEW_LINE> <INDENT> Document.set_origin(self, origin) <NEW_LINE> for x in self.schemas: <NEW_LINE> <INDENT> x.origin = origin
Representation of a glozz document
6259903f711fe17d825e15dc
class SensorReading(object): <NEW_LINE> <INDENT> def __init__(self, reading, suffix): <NEW_LINE> <INDENT> self.broken_sensor_ids = {} <NEW_LINE> self.health = const.Health.Ok <NEW_LINE> self.type = reading['type'] <NEW_LINE> self.value = None <NEW_LINE> self.imprecision = None <NEW_LINE> self.states = [] <NEW_LINE> self.state_ids = [] <NEW_LINE> self.unavailable = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> self.health = reading['health'] <NEW_LINE> self.states = reading['states'] <NEW_LINE> self.state_ids = reading['state_ids'] <NEW_LINE> self.value = reading['value'] <NEW_LINE> self.imprecision = reading['imprecision'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if 'unavailable' in reading: <NEW_LINE> <INDENT> self.unavailable = 1 <NEW_LINE> <DEDENT> self.units = suffix <NEW_LINE> self.name = reading['name'] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr({ 'value': self.value, 'states': self.states, 'state_ids': self.state_ids, 'units': self.units, 'imprecision': self.imprecision, 'name': self.name, 'type': self.type, 'unavailable': self.unavailable, 'health': self.health }) <NEW_LINE> <DEDENT> def simplestring(self): <NEW_LINE> <INDENT> repr = self.name + ": " <NEW_LINE> if self.value is not None: <NEW_LINE> <INDENT> repr += str(self.value) <NEW_LINE> repr += " ± " + str(self.imprecision) <NEW_LINE> repr += self.units <NEW_LINE> <DEDENT> for state in self.states: <NEW_LINE> <INDENT> repr += state + "," <NEW_LINE> <DEDENT> if self.health >= const.Health.Failed: <NEW_LINE> <INDENT> repr += '(Failed)' <NEW_LINE> <DEDENT> elif self.health >= const.Health.Critical: <NEW_LINE> <INDENT> repr += '(Critical)' <NEW_LINE> <DEDENT> elif self.health >= const.Health.Warning: <NEW_LINE> <INDENT> repr += '(Warning)' <NEW_LINE> <DEDENT> return repr
Representation of the state of a sensor. It is initialized by pyghmi internally, it does not make sense for a developer to create one of these objects directly. It provides the following properties: name: UTF-8 string describing the sensor units: UTF-8 string describing the units of the sensor (if numeric) value: Value of the sensor if numeric imprecision: The amount by which the actual measured value may deviate from 'value' due to limitations in the resolution of the given sensor.
6259903f379a373c97d9a2a9
class PrintCommandFailed(ValueError): <NEW_LINE> <INDENT> pass
Raised if copy command was successful, but printing file via ssh gave us an error (check 'lpquota' output on remote host to see if there isn't enough money to print)
6259903fbaa26c4b54d50529
class WhitePort: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.session=DBSession <NEW_LINE> <DEDENT> def select_white_port(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> white_port_res = self.session.query(Whiteport.dst_port).all() <NEW_LINE> return white_port_res <NEW_LINE> <DEDENT> except InvalidRequestError: <NEW_LINE> <INDENT> self.session.rollback() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.session.close() <NEW_LINE> <DEDENT> <DEDENT> def insert_white_port(self, dst_port): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> wip_insert = Whiteport(dst_port=dst_port) <NEW_LINE> self.session.merge(wip_insert) <NEW_LINE> self.session.commit() <NEW_LINE> <DEDENT> except InvalidRequestError: <NEW_LINE> <INDENT> self.session.rollback() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.session.close() <NEW_LINE> <DEDENT> <DEDENT> def delete_white_port(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.session.query(Whiteport).delete() <NEW_LINE> self.session.commit() <NEW_LINE> <DEDENT> except InvalidRequestError: <NEW_LINE> <INDENT> self.session.rollback() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.session.close()
增删改查
6259903fd10714528d69efcc
class FireTVDevice(MediaPlayerDevice): <NEW_LINE> <INDENT> def __init__(self, proto, host, port, device, name): <NEW_LINE> <INDENT> self._firetv = FireTV(proto, host, port, device) <NEW_LINE> self._name = name <NEW_LINE> self._state = STATE_UNKNOWN <NEW_LINE> self._running_apps = None <NEW_LINE> self._current_app = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> return SUPPORT_FIRETV <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self._current_app <NEW_LINE> <DEDENT> @property <NEW_LINE> def source_list(self): <NEW_LINE> <INDENT> return self._running_apps <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self._state = { 'idle': STATE_IDLE, 'off': STATE_OFF, 'play': STATE_PLAYING, 'pause': STATE_PAUSED, 'standby': STATE_STANDBY, 'disconnected': STATE_UNKNOWN, }.get(self._firetv.state, STATE_UNKNOWN) <NEW_LINE> if self._state not in [STATE_OFF, STATE_UNKNOWN]: <NEW_LINE> <INDENT> self._running_apps = self._firetv.running_apps <NEW_LINE> self._current_app = self._firetv.current_app <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._running_apps = None <NEW_LINE> self._current_app = None <NEW_LINE> <DEDENT> <DEDENT> def turn_on(self): <NEW_LINE> <INDENT> self._firetv.action('turn_on') <NEW_LINE> <DEDENT> def turn_off(self): <NEW_LINE> <INDENT> self._firetv.action('turn_off') <NEW_LINE> <DEDENT> def media_play(self): <NEW_LINE> <INDENT> self._firetv.action('media_play') <NEW_LINE> <DEDENT> def media_pause(self): <NEW_LINE> <INDENT> self._firetv.action('media_pause') <NEW_LINE> <DEDENT> def media_play_pause(self): <NEW_LINE> <INDENT> self._firetv.action('media_play_pause') <NEW_LINE> <DEDENT> def volume_up(self): <NEW_LINE> <INDENT> self._firetv.action('volume_up') <NEW_LINE> <DEDENT> def volume_down(self): <NEW_LINE> <INDENT> self._firetv.action('volume_down') <NEW_LINE> <DEDENT> def media_previous_track(self): <NEW_LINE> <INDENT> self._firetv.action('media_previous') <NEW_LINE> <DEDENT> def media_next_track(self): <NEW_LINE> <INDENT> self._firetv.action('media_next') <NEW_LINE> <DEDENT> def select_source(self, source): <NEW_LINE> <INDENT> self._firetv.start_app(source)
Representation of an Amazon Fire TV device on the network.
6259903f1d351010ab8f4d9d
class ParseError(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = "Parse Error: " + value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value)
Class for parse-error exceptions
6259903f30dc7b76659a0ab2
class NoFullPacketError(Exception): <NEW_LINE> <INDENT> pass
Exception thrown when no full packet is available
6259903f097d151d1a2c22e6
class Communicator(object): <NEW_LINE> <INDENT> def __init__(self, afm_url): <NEW_LINE> <INDENT> self.logger = logging.getLogger("Communicator") <NEW_LINE> self.afm_url = afm_url <NEW_LINE> <DEDENT> def _post(self, path, json): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = post( self.afm_url + path, json=json ) <NEW_LINE> if 400 <= r.status_code < 500: <NEW_LINE> <INDENT> raise FatalError('AFM responded with client error status: {0}'.format(r.status_code)) <NEW_LINE> <DEDENT> elif 500 <= r.status_code < 600: <NEW_LINE> <INDENT> raise TemporaryError('AFM responded with server error status: {0}'.format(r.status_code)) <NEW_LINE> <DEDENT> return r <NEW_LINE> <DEDENT> except RequestException as e: <NEW_LINE> <INDENT> raise TemporaryError(e) <NEW_LINE> <DEDENT> <DEDENT> def request_tasks(self, **kwargs): <NEW_LINE> <INDENT> request_data = { "protocol": 1 } <NEW_LINE> request_data.update(kwargs) <NEW_LINE> logging.getLogger('HTTP').info("Requesting for tasks: %s", request_data) <NEW_LINE> r = self._post('/tasks', json=request_data) <NEW_LINE> try: <NEW_LINE> <INDENT> response_data = r.json() <NEW_LINE> return response_data <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise FatalError('Failed to parse response JSON: {0}'.format(e)) <NEW_LINE> <DEDENT> <DEDENT> def post_result(self, task_id, task_data=None, task_error=None): <NEW_LINE> <INDENT> request_data = { "protocol": 1, "task_id": task_id } <NEW_LINE> if task_data: <NEW_LINE> <INDENT> request_data["task_data"] = task_data <NEW_LINE> <DEDENT> elif task_error: <NEW_LINE> <INDENT> request_data["task_error"] = task_error <NEW_LINE> <DEDENT> logging.getLogger('HTTP').info("Posting results for task '%s'", task_id) <NEW_LINE> uploaded = False <NEW_LINE> while not uploaded: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> uploaded = self._post('/tasks/response', json=request_data).status_code == 200 <NEW_LINE> <DEDENT> except TemporaryError as e: <NEW_LINE> <INDENT> self.logger.warning("Temporary error while posting results: %s", e)
Class to handle afm communication and to provide simple error handling interface for the agent application.
6259903f8e05c05ec3f6f79b
class StockAttribute(enum.Enum): <NEW_LINE> <INDENT> DEBT_TO_EQUITY = 'Total Debt/Equity (mrq)' <NEW_LINE> DIVIDEND_YIELD = '5 Year Average Dividend Yield 4' <NEW_LINE> EPS = 'Revenue Per Share (ttm)' <NEW_LINE> PE = 'Trailing P/E' <NEW_LINE> PROFIT_MARGIN = 'Profit Margin' <NEW_LINE> RETURN_ON_EQUITY = 'Return on Equity (ttm)' <NEW_LINE> REVENUE_GROWTH = 'Quarterly Revenue Growth (yoy)' <NEW_LINE> VALUE_OVER_EBITDA = 'Enterprise Value/EBITDA 6'
Yahoo Finance attribute names for stocks.
6259903f21bff66bcd723eeb
class Search(AbstractActionBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def subparser(cls, parent): <NEW_LINE> <INDENT> parser = parent.add_parser('search', help='search for images') <NEW_LINE> super().subparser(parser) <NEW_LINE> parser.add_argument( '--filter', '-f', action=FilterAction, help='Filter output based on conditions provided.') <NEW_LINE> parser.add_argument( '--limit', action=PositiveIntAction, default=25, help='Limit the number of results.' ' (default: %(default)s)') <NEW_LINE> parser.add_argument('term', nargs=1, help='search term for image') <NEW_LINE> parser.set_defaults(class_=cls, method='search') <NEW_LINE> <DEDENT> def __init__(self, args): <NEW_LINE> <INDENT> super().__init__(args) <NEW_LINE> self.columns = OrderedDict({ 'name': ReportColumn('name', 'NAME', 44), 'description': ReportColumn('description', 'DESCRIPTION', 44), 'star_count': ReportColumn('star_count', 'STARS', 5), 'is_official': ReportColumn('is_official', 'OFFICIAL', 8), 'is_automated': ReportColumn('is_automated', 'AUTOMATED', 9), }) <NEW_LINE> <DEDENT> def search(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rows = list() <NEW_LINE> for entry in self.client.images.search( self._args.term[0], limit=self._args.limit): <NEW_LINE> <INDENT> if self._args.filter == 'is-official': <NEW_LINE> <INDENT> if self._args.filter_value != entry.is_official: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> elif self._args.filter == 'is-automated': <NEW_LINE> <INDENT> if self._args.filter_value != entry.is_automated: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> elif self._args.filter == 'stars': <NEW_LINE> <INDENT> if self._args.filter_value > entry.star_count: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> fields = dict(entry._asdict()) <NEW_LINE> status = '[OK]' if entry.is_official else '' <NEW_LINE> fields['is_official'] = status <NEW_LINE> status = '[OK]' if entry.is_automated else '' <NEW_LINE> fields['is_automated'] = status <NEW_LINE> if self._args.truncate: <NEW_LINE> <INDENT> fields.update({'name': entry.name[-44:]}) <NEW_LINE> <DEDENT> rows.append(fields) <NEW_LINE> <DEDENT> with Report(self.columns, heading=self._args.heading) as report: <NEW_LINE> <INDENT> report.layout( rows, self.columns.keys(), truncate=self._args.truncate) <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> report.row(**row) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except podman.ErrorOccurred as e: <NEW_LINE> <INDENT> sys.stdout.flush() <NEW_LINE> print( '{}'.format(e.reason).capitalize(), file=sys.stderr, flush=True)
Class for searching registries for an image.
6259903f63f4b57ef00866b5
class TestHistoricalTTController(BaseTestCase): <NEW_LINE> <INDENT> def test_historical_get(self): <NEW_LINE> <INDENT> query_string = [('start_point', 'start_point_example'), ('end_point', 'end_point_example'), ('start_datetime', '2013-10-20'), ('end_datetime', '2013-10-20')] <NEW_LINE> response = self.client.open('/v0/historical', method='GET', query_string=query_string) <NEW_LINE> self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
HistoricalTTController integration test stubs
6259903fd6c5a102081e33a7
class Visualizer(object): <NEW_LINE> <INDENT> def __init__(self, env='default', **kwargs): <NEW_LINE> <INDENT> self.vis = visdom.Visdom(env=env, **kwargs) <NEW_LINE> self.index = {} <NEW_LINE> self.log_text = '' <NEW_LINE> <DEDENT> def reinit(self, env='default', **kwargs): <NEW_LINE> <INDENT> self.vis = visdom.Visdom(env=env, **kwargs) <NEW_LINE> return self <NEW_LINE> <DEDENT> def plot_many(self, d): <NEW_LINE> <INDENT> for k, v in d.items(): <NEW_LINE> <INDENT> self.plot(k, v) <NEW_LINE> <DEDENT> <DEDENT> def img_many(self, d): <NEW_LINE> <INDENT> for k, v in d.items(): <NEW_LINE> <INDENT> self.img(k, v) <NEW_LINE> <DEDENT> <DEDENT> def plot(self, name, y, **kwargs): <NEW_LINE> <INDENT> x = self.index.get(name, 0) <NEW_LINE> self.vis.line(Y=np.array([y]), X=np.array([x]), win=name, opts=dict(title=name), update=None if x == 0 else 'append', **kwargs ) <NEW_LINE> self.index[name] = x + 1 <NEW_LINE> <DEDENT> def img(self, name, img_, **kwargs): <NEW_LINE> <INDENT> self.vis.images(img_.cpu().numpy(), win=name, opts=dict(title=name), **kwargs ) <NEW_LINE> <DEDENT> def log(self, info, win='log_text'): <NEW_LINE> <INDENT> self.log_text += ('[{time}] {info} <br>'.format( time=time.strftime('%m%d_%H%M%S'), info=info)) <NEW_LINE> self.vis.text(self.log_text, win) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self.vis, name)
封装了visdom基本操作
6259903f3eb6a72ae038b8ec
class IndexHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def get(self, *args, **kwargs): <NEW_LINE> <INDENT> imgs = get_images('uploads') <NEW_LINE> self.render('index.html',imgs=imgs)
Homepage for users,photo feeds of follow
6259903f8a43f66fc4bf3412
class Client(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User, blank=True, null=True, on_delete=models.SET_NULL) <NEW_LINE> online = models.BooleanField(default=False) <NEW_LINE> last_update = models.DateTimeField(auto_now=True, null=True, blank=True) <NEW_LINE> created_on = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{} {}".format(self.user, self.online) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.last_update = datetime.datetime.now()
In this model we are tracking desktop client status. Is it online or is it in offline. So we can give user notifications.
6259903fd53ae8145f9196de
class DatasetEntry(urwid.WidgetWrap): <NEW_LINE> <INDENT> __metaclass__ = urwid.signals.MetaSignals <NEW_LINE> signals = ['selected'] <NEW_LINE> def __init__(self, dataset, path): <NEW_LINE> <INDENT> self.dataset = dataset <NEW_LINE> self.path = path <NEW_LINE> self.item = [ ('fixed', 15, urwid.Padding(urwid.AttrWrap(urwid.Text('%s' % str(dataset)), 'body', 'focus'), left=2)), urwid.AttrWrap(urwid.Text('%s' % path), 'body', 'focus'), ] <NEW_LINE> w = urwid.Columns(self.item) <NEW_LINE> super(DatasetEntry, self).__init__(w) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.path <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<DatasetEntry: '+str(self)+'>' <NEW_LINE> <DEDENT> def send_signal(self): <NEW_LINE> <INDENT> urwid.emit_signal(self, 'selected') <NEW_LINE> <DEDENT> def selectable (self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def keypress (self, size, key): <NEW_LINE> <INDENT> if key is 'enter': <NEW_LINE> <INDENT> self.send_signal() <NEW_LINE> <DEDENT> elif key is 'right': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> <DEDENT> def matchesCriteria(self, posList, negList): <NEW_LINE> <INDENT> for pos in posList: <NEW_LINE> <INDENT> if pos not in self.path: return False <NEW_LINE> <DEDENT> for neg in negList: <NEW_LINE> <INDENT> if neg in self.path: return False <NEW_LINE> <DEDENT> return True
Single dataset entry in the list
6259903fbaa26c4b54d5052b
class seisan_M(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.year = None <NEW_LINE> self.month = None <NEW_LINE> self.day = None <NEW_LINE> self.hour = None <NEW_LINE> self.minutes = None <NEW_LINE> self.seconds = None <NEW_LINE> self.latitude = None <NEW_LINE> self.longitude = None <NEW_LINE> self.depth = None <NEW_LINE> self.reporting_agency = ' ' <NEW_LINE> self.megnitude = None <NEW_LINE> self.magnitude_type = ' ' <NEW_LINE> self.magnitude_reporting_agency = ' ' <NEW_LINE> self.method_used = ' ' <NEW_LINE> self.quality = ' ' <NEW_LINE> self.mt = ' ' <NEW_LINE> self.mrr_mzz = None <NEW_LINE> self.mtt_mxx = None <NEW_LINE> self.mpp_myy = None <NEW_LINE> self.mrt_mzx = None <NEW_LINE> self.mrp_mzy = None <NEW_LINE> self.mtp_mxy = None <NEW_LINE> self.reporting_agency2 = ' ' <NEW_LINE> self.mt_coordinate_system = ' ' <NEW_LINE> self.exponential = None <NEW_LINE> self.scalar_moment = None <NEW_LINE> self.method_used_2 = ' ' <NEW_LINE> self.quality_2 = ' ' <NEW_LINE> self.dataid = ''
Type M Line (Optional): Moment tensor solution. Note: the type M lines are pairs of lines with one line that gives the hypocenter time, and one line that gives the moment tensor values: The first moment tensor line: Columns Format Description 1:1 Free 2:5 I4 Year 7:8 I2 Month 9:10 I2 Day of Month 12:13 I2 Hour 14:15 I2 Minutes 17:20 F4.1 Seconds 24:30 F7.3 Latitude Degrees (+ N) 31:38 F8.3 Longitude Degrees (+ E) 39:43 F5.1 Depth Km 46:48 A3 Reporting Agency 56:59 F4.1 Magnitude 60 A1 Type of Magnitude L=ML, b=mb, B=mB, s=Ms, S=MS, W=MW, 61:63 A3 Magnitude Reporting Agency 71:77 A7 Method used 78:78 A1 Quality of solution, A (best), B C or D (worst), added - manually 79:79 A1 Blank, can be used by user 80:80 A1 M The second moment tensor line: Columns Format Description 1:1 Free 2:3 A2 MT 4:9 F6.3 Mrr or Mzz [Nm] 11:16 F6.3 Mtt or Mxx [Nm] 18:23 F6.3 Mpp or Myy [Nm] 25:30 F6.3 Mrt or Mzx [Nm] 32:37 F6.3 Mrp or Mzy [Nm] 39:44 F6.3 Mtp or Mxy [Nm] 46:48 A3 Reporting Agency 49:49 A1 MT coordinate system (S=spherical, C=Cartesian) 50:51 i2 Exponential 53:62 G6.3 Scalar Moment [Nm] 71:77 A7 Method used 78:78 A1 Quality of solution, A (best), B C or D (worst), added - manually 79:79 A1 Blank, can be used by user 80:80 A1 M
6259903f29b78933be26aa04
class IOpenlayers(Interface): <NEW_LINE> <INDENT> pass
A layer specific to my product
62599040b57a9660fecd2cfd
class Person: <NEW_LINE> <INDENT> count = 1 <NEW_LINE> def run(self, distance, step): <NEW_LINE> <INDENT> print("人在跑") <NEW_LINE> return distance / step <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.__name = "sz"
关于这个类的描述, 类的作用, 类的构造函数等等; 类属性的描述 Attributes: count: int 代表是人的个数
6259904071ff763f4b5e8a21
class ExitException(Exception): <NEW_LINE> <INDENT> pass
Exception thrown when we wish to exit, but no real errors occured
6259904082261d6c52730805
class MKServiceCommand(MKService): <NEW_LINE> <INDENT> def __init__(self, context, name, properties): <NEW_LINE> <INDENT> MKService.__init__(self, name, properties) <NEW_LINE> self.identity = uuid.uuid1() <NEW_LINE> self.socket = context.socket(zmq.DEALER) <NEW_LINE> self.socket.identity = str(self.identity).encode() <NEW_LINE> self.socket.connect(self.dsn) <NEW_LINE> self.commandID = itertools.count() <NEW_LINE> self.locked = threading.Lock() <NEW_LINE> self.outstandingMsgs = {} <NEW_LINE> self.compounds = [] <NEW_LINE> <DEDENT> def topicName(self): <NEW_LINE> <INDENT> return 'command' <NEW_LINE> <DEDENT> def newTicket(self): <NEW_LINE> <INDENT> with self.locked: <NEW_LINE> <INDENT> return next(self.commandID) <NEW_LINE> <DEDENT> <DEDENT> def msgChanged(self, msg): <NEW_LINE> <INDENT> for compound in self.compounds: <NEW_LINE> <INDENT> compound.processCommand(msg) <NEW_LINE> <DEDENT> self.compounds = [compound for compound in self.compounds if compound.isActive()] <NEW_LINE> self.notifyObservers(msg) <NEW_LINE> if msg.isCompleted() and self.outstandingMsgs.get(msg.msg.ticket): <NEW_LINE> <INDENT> del self.outstandingMsgs[msg.msg.ticket] <NEW_LINE> <DEDENT> <DEDENT> def process(self, container): <NEW_LINE> <INDENT> if container.type == TYPES.MT_ERROR: <NEW_LINE> <INDENT> for msg in container.note: <NEW_LINE> <INDENT> print(" ERROR: %s" % msg) <NEW_LINE> <DEDENT> print('') <NEW_LINE> self.setTermination() <NEW_LINE> return <NEW_LINE> <DEDENT> if container.HasField('reply_ticket'): <NEW_LINE> <INDENT> msg = self.outstandingMsgs.get(container.reply_ticket) <NEW_LINE> if msg: <NEW_LINE> <INDENT> msg = self.outstandingMsgs[container.reply_ticket] <NEW_LINE> if container.type == TYPES.MT_EMCCMD_EXECUTED: <NEW_LINE> <INDENT> msg.msgExecuted() <NEW_LINE> <DEDENT> if container.type == TYPES.MT_EMCCMD_COMPLETED: <NEW_LINE> <INDENT> msg.msgCompleted() <NEW_LINE> <DEDENT> self.msgChanged(msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("process(%s) - unknown ticket" % container) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("process(%s)" % container) <NEW_LINE> <DEDENT> <DEDENT> def sendCommand(self, msg): <NEW_LINE> <INDENT> ticket = self.newTicket() <NEW_LINE> msg.msg.ticket = ticket <NEW_LINE> buf = msg.serializeToString() <NEW_LINE> self.outstandingMsgs[ticket] = msg <NEW_LINE> msg.msgSent() <NEW_LINE> self.socket.send(buf) <NEW_LINE> if not msg.expectsResponses(): <NEW_LINE> <INDENT> msg.msgCompleted() <NEW_LINE> self.msgChanged(msg) <NEW_LINE> <DEDENT> <DEDENT> def sendCommands(self, commands): <NEW_LINE> <INDENT> if 1 == len(commands): <NEW_LINE> <INDENT> self.sendCommand(commands[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sendCommandSequence([[command] for command in commands]) <NEW_LINE> <DEDENT> <DEDENT> def sendCommandSequence(self, sequence): <NEW_LINE> <INDENT> command = CommandSequence(self, sequence) <NEW_LINE> self.compounds.append(command) <NEW_LINE> command.start() <NEW_LINE> <DEDENT> def abortCommandSequence(self): <NEW_LINE> <INDENT> self.compounds = [] <NEW_LINE> <DEDENT> def ping(self): <NEW_LINE> <INDENT> for compound in self.compounds: <NEW_LINE> <INDENT> compound.ping() <NEW_LINE> <DEDENT> self.compounds = [compound for compound in self.compounds if compound.isActive()]
Class to interact with the MK service 'command'. The receiver keeps track of the service's state and the completion status of any commands that have been sent to MK.
62599040507cdc57c63a601e
@ddt <NEW_LINE> class Test_Goods(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self) : <NEW_LINE> <INDENT> self.host = 'https://pbsapi.aikenong.com.cn/boss/' <NEW_LINE> self.token = base.get_token_akn() <NEW_LINE> self.header = {'Authorization': "JWT " + self.token} <NEW_LINE> <DEDENT> def test01_goods(self): <NEW_LINE> <INDENT> doc = "goods/105710052/" <NEW_LINE> url = ''.join([self.host,doc]) <NEW_LINE> print(url) <NEW_LINE> resp = requests.get(url, headers=self.header) <NEW_LINE> json_str = resp.json() <NEW_LINE> print(resp) <NEW_LINE> print(json_str) <NEW_LINE> code = resp.status_code <NEW_LINE> self.assertEqual(code,200,msg= '返回值错误') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass
农资总览
62599040dc8b845886d54839
class UserList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> users = User.objects.all() <NEW_LINE> serializer = UserSerializer(users, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = UserSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
List all users, or create a new user.
62599040b57a9660fecd2cfe
class PastEventsManager(models.Manager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return super(PastEventsManager, self).get_query_set().filter( start__lte=datetime.datetime.now()-datetime.timedelta(hours=1) ).order_by('-start')
Return all events in the past, starting with most recent
625990400fa83653e46f615d
class ConfigParser(PythonConfigParser): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> PythonConfigParser.__init__(self) <NEW_LINE> self._sections = OrderedDict() <NEW_LINE> self.filename = None <NEW_LINE> self._callbacks = [] <NEW_LINE> <DEDENT> def add_callback(self, callback, section=None, key=None): <NEW_LINE> <INDENT> if section is None and key is not None: <NEW_LINE> <INDENT> raise Exception('You cannot specify a key without a section') <NEW_LINE> <DEDENT> self._callbacks.append((callback, section, key)) <NEW_LINE> <DEDENT> def _do_callbacks(self, section, key, value): <NEW_LINE> <INDENT> for callback, csection, ckey in self._callbacks: <NEW_LINE> <INDENT> if csection is not None and csection != section: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif ckey is not None and ckey != key: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> callback(section, key, value) <NEW_LINE> <DEDENT> <DEDENT> def read(self, filename): <NEW_LINE> <INDENT> if not isinstance(filename, string_types): <NEW_LINE> <INDENT> raise Exception('Only one filename is accepted ({})'.format( string_types.__name__)) <NEW_LINE> <DEDENT> self.filename = filename <NEW_LINE> PythonConfigParser.read(self, filename) <NEW_LINE> <DEDENT> def set(self, section, option, value): <NEW_LINE> <INDENT> e_value = value <NEW_LINE> if PY2: <NEW_LINE> <INDENT> if not isinstance(value, string_types): <NEW_LINE> <INDENT> e_value = str(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(value, unicode): <NEW_LINE> <INDENT> e_value = value.encode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ret = PythonConfigParser.set(self, section, option, e_value) <NEW_LINE> self._do_callbacks(section, option, value) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def get(self, section, option, **kwargs): <NEW_LINE> <INDENT> value = PythonConfigParser.get(self, section, option, **kwargs) <NEW_LINE> if PY2: <NEW_LINE> <INDENT> if type(value) is str: <NEW_LINE> <INDENT> return value.decode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def setdefaults(self, section, keyvalues): <NEW_LINE> <INDENT> self.adddefaultsection(section) <NEW_LINE> for key, value in keyvalues.items(): <NEW_LINE> <INDENT> self.setdefault(section, key, value) <NEW_LINE> <DEDENT> <DEDENT> def setdefault(self, section, option, value): <NEW_LINE> <INDENT> if self.has_option(section, option): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.set(section, option, value) <NEW_LINE> <DEDENT> def getdefault(self, section, option, defaultvalue): <NEW_LINE> <INDENT> if not self.has_section(section): <NEW_LINE> <INDENT> return defaultvalue <NEW_LINE> <DEDENT> if not self.has_option(section, option): <NEW_LINE> <INDENT> return defaultvalue <NEW_LINE> <DEDENT> return self.get(section, option) <NEW_LINE> <DEDENT> def getdefaultint(self, section, option, defaultvalue): <NEW_LINE> <INDENT> return int(self.getdefault(section, option, defaultvalue)) <NEW_LINE> <DEDENT> def adddefaultsection(self, section): <NEW_LINE> <INDENT> if self.has_section(section): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.add_section(section) <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> if self.filename is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(self.filename, 'w') as fd: <NEW_LINE> <INDENT> PythonConfigParser.write(self, fd) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> Logger.exception('Unable to write the config <%s>' % self.filename) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True
Enhanced ConfigParser class, that supports addition of default sections and default values. .. versionadded:: 1.0.7
6259904024f1403a9268620e
class BrowserLikeRedirectAgent(RedirectAgent): <NEW_LINE> <INDENT> _redirectResponses = [http.TEMPORARY_REDIRECT] <NEW_LINE> _seeOtherResponses = [ http.MOVED_PERMANENTLY, http.FOUND, http.SEE_OTHER, http.PERMANENT_REDIRECT, ]
An L{Agent} wrapper which handles HTTP redirects in the same fashion as web browsers. Unlike L{RedirectAgent}, the implementation is more relaxed: 301 and 302 behave like 303, redirecting automatically on any method and altering the redirect request to a I{GET}. @see: L{RedirectAgent} @since: 13.1
62599040a4f1c619b294f7c9
class SignatureAlgorithm(TLSEnum): <NEW_LINE> <INDENT> anonymous = 0 <NEW_LINE> rsa = 1 <NEW_LINE> dsa = 2 <NEW_LINE> ecdsa = 3
Signing algorithms used in TLSv1.2
62599040711fe17d825e15de
class Fase(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'Fase' <NEW_LINE> idFase = db.Column(db.Integer, primary_key=True, nullable=False) <NEW_LINE> nombre = db.Column(db.String(45), unique=True, nullable=False) <NEW_LINE> descripcion = db.Column(db.String(150)) <NEW_LINE> estado = db.Column(db.String(20), default ='Pendiente', nullable=False) <NEW_LINE> orden = db.Column(db.Integer, nullable=False) <NEW_LINE> fechaDeCreacion = db.Column(db.DateTime, default = datetime.now(), nullable=False) <NEW_LINE> proyectoId = db.Column(db.Integer, db.ForeignKey('Proyecto.idProyecto')) <NEW_LINE> listaTipoDeItem = db.relationship('TipoDeItem', backref='Fase', lazy = 'dynamic') <NEW_LINE> listaItem = db.relationship('Item', backref='Fase', lazy = 'dynamic') <NEW_LINE> tipoDeAtributos = db.relationship('TipoDeAtributo', uselist=False, backref= 'Fase') <NEW_LINE> def __init__(self, nombre=None, descripcion=None, orden=None): <NEW_LINE> <INDENT> self.nombre = nombre <NEW_LINE> self.descripcion = descripcion <NEW_LINE> self.orden = orden
Modelo de Fase
625990408a349b6b436874ca
class FavoriteProductDeleteAjaxView(View): <NEW_LINE> <INDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> body = request.body.decode('utf-8') <NEW_LINE> bjson = json.loads(body) <NEW_LINE> login_user = bjson['login_user'] <NEW_LINE> target = bjson['target'] <NEW_LINE> try: <NEW_LINE> <INDENT> delete_obj = models.FavoriteProduct.objects.filter(user__username=login_user).filter(product__uuid_url=target) <NEW_LINE> delete_obj.delete() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error(e) <NEW_LINE> data = { 'success': False, 'message': 'Can not Create favorite product' } <NEW_LINE> data_json = json.dumps(data) <NEW_LINE> return HttpResponse(data_json, content_type='application/json') <NEW_LINE> <DEDENT> data = { 'success': True, 'message': 'test delete', } <NEW_LINE> data_json = json.dumps(data) <NEW_LINE> return HttpResponse(data_json, content_type='application/json')
お気に入りのユーザーを削除
62599040097d151d1a2c22ea
class BinaryFileTestCase(BaseTestCase): <NEW_LINE> <INDENT> def testOneObject(self): <NEW_LINE> <INDENT> _, path = tempfile.mkstemp() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(path, "wb") as out: <NEW_LINE> <INDENT> out.write(ints2octs((2, 1, 12))) <NEW_LINE> <DEDENT> with open(path, "rb") as source: <NEW_LINE> <INDENT> values = list(decoder.StreamingDecoder(source)) <NEW_LINE> <DEDENT> assert values == [12] <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.remove(path) <NEW_LINE> <DEDENT> <DEDENT> def testMoreObjects(self): <NEW_LINE> <INDENT> _, path = tempfile.mkstemp() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(path, "wb") as out: <NEW_LINE> <INDENT> out.write(ints2octs((2, 1, 12, 35, 128, 3, 2, 0, 169, 3, 2, 1, 138, 0, 0))) <NEW_LINE> <DEDENT> with open(path, "rb") as source: <NEW_LINE> <INDENT> values = list(decoder.StreamingDecoder(source)) <NEW_LINE> <DEDENT> assert values == [12, (1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1)] <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.remove(path) <NEW_LINE> <DEDENT> <DEDENT> def testInvalidFileContent(self): <NEW_LINE> <INDENT> _, path = tempfile.mkstemp() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(path, "wb") as out: <NEW_LINE> <INDENT> out.write(ints2octs((2, 1, 12, 35, 128, 3, 2, 0, 169, 3, 2, 1, 138, 0, 0, 7))) <NEW_LINE> <DEDENT> with open(path, "rb") as source: <NEW_LINE> <INDENT> list(decoder.StreamingDecoder(source)) <NEW_LINE> <DEDENT> <DEDENT> except error.EndOfStreamError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.remove(path)
Assure that decode works on open binary files.
62599040d4950a0f3b111782
class DescribeProjectSecurityGroupsResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Groups = None <NEW_LINE> self.Total = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Groups") is not None: <NEW_LINE> <INDENT> self.Groups = [] <NEW_LINE> for item in params.get("Groups"): <NEW_LINE> <INDENT> obj = SecurityGroup() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Groups.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.Total = params.get("Total") <NEW_LINE> self.RequestId = params.get("RequestId")
DescribeProjectSecurityGroups response structure.
6259904026068e7796d4dbcb
class TimedOperation(Operation): <NEW_LINE> <INDENT> __slots__ = ('timeout', 'coro', 'weak_timeout', 'delta', 'last_checkpoint') <NEW_LINE> def set_timeout(self, val): <NEW_LINE> <INDENT> if val and val != -1 and not isinstance(val, datetime.datetime): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> if isinstance(val, datetime.timedelta): <NEW_LINE> <INDENT> val = now+val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = now+datetime.timedelta(seconds=val) <NEW_LINE> <DEDENT> <DEDENT> self.timeout = val <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> return cmp(self.timeout, other.timeout) <NEW_LINE> <DEDENT> def __init__(self, timeout=None, weak_timeout=True, **kws): <NEW_LINE> <INDENT> super(TimedOperation, self).__init__(**kws) <NEW_LINE> self.set_timeout(timeout) <NEW_LINE> self.weak_timeout = weak_timeout <NEW_LINE> <DEDENT> def process(self, sched, coro): <NEW_LINE> <INDENT> super(TimedOperation, self).process(sched, coro) <NEW_LINE> if sched.default_timeout and not self.timeout: <NEW_LINE> <INDENT> self.set_timeout(sched.default_timeout) <NEW_LINE> <DEDENT> if self.timeout and self.timeout != -1: <NEW_LINE> <INDENT> self.coro = coro <NEW_LINE> if self.weak_timeout: <NEW_LINE> <INDENT> self.last_checkpoint = getnow() <NEW_LINE> self.delta = self.timeout - self.last_checkpoint <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.last_checkpoint = self.delta = None <NEW_LINE> <DEDENT> heapq.heappush(sched.timeouts, self) <NEW_LINE> <DEDENT> <DEDENT> def cleanup(self, sched, coro): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def finalize(self, sched): <NEW_LINE> <INDENT> if self.timeout and self.timeout != -1: <NEW_LINE> <INDENT> heapremove(sched.timeouts, self) <NEW_LINE> <DEDENT> return super(TimedOperation, self).finalize(sched)
Operations that have a timeout derive from this. Eg: .. sourcecode:: python yield TimedOperation( timeout=None, weak_timeout=True, prio=priority.DEFAULT ) * timeout - can be a float/int (number of seconds) or a timedelta or a datetime value if it's a datetime the timeout will occur on that moment * weak_timeout - strong timeouts just happen when specified, weak_timeouts get delayed if some action happens (eg: new but not enough data recieved) See: :class:`Operation`. Note: you don't really use this, this is for subclassing for other operations.
6259904071ff763f4b5e8a23
class ArtistViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.Artist.objects.all() <NEW_LINE> serializer_class = serializers.ArtistSerializer <NEW_LINE> permission_classes = [permissions.IsAuthenticated]
ViewSet for the Artist class
62599040cad5886f8bdc59bf
class ExamsDeleteView(ExamsMixin, DeleteView): <NEW_LINE> <INDENT> template_name = 'dj_diabetes/confirm_delete.html'
to Delete Examination Details
625990408c3a8732951f77dd
class HPHMembershipSettingsEditForm(RegistryEditForm): <NEW_LINE> <INDENT> schema = IHPHMembershipSettings <NEW_LINE> label = u"HPH membership tool settings"
Define form logic
6259904045492302aabfd75f
class ReportDir(object): <NEW_LINE> <INDENT> _current_dir = '' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, progress, data): <NEW_LINE> <INDENT> return self._current_dir <NEW_LINE> <DEDENT> def set_directory_name(self, arg): <NEW_LINE> <INDENT> self._current_dir = arg <NEW_LINE> <DEDENT> def get_directory_name(self): <NEW_LINE> <INDENT> return self._current_dir
Class to provide progressbar widget with current directory name.
6259904007f4c71912bb06b7