code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class AuthRequestMixin(object): <NEW_LINE> <INDENT> def __init__(self, client_authenticator, scope_handler, token_generator, **kwargs): <NEW_LINE> <INDENT> self.client = None <NEW_LINE> self.state = None <NEW_LINE> self.client_authenticator = client_authenticator <NEW_LINE> self.scope_handler = scope_handler <NEW_LINE> self.token_generator = token_generator <NEW_LINE> super(AuthRequestMixin, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def read_validate_params(self, request): <NEW_LINE> <INDENT> self.client = self.client_authenticator.by_identifier(request) <NEW_LINE> print(self.client) <NEW_LINE> response_type = request.get_param("response_type") <NEW_LINE> print(response_type) <NEW_LINE> if self.client.response_type_supported(response_type) is False: <NEW_LINE> <INDENT> raise OAuthInvalidError(error="unauthorized_client") <NEW_LINE> <DEDENT> self.state = request.get_param("state") <NEW_LINE> self.scope_handler.parse(request, "query") <NEW_LINE> return True
|
Generalization of reading and validating an incoming request used by
`oauth2.grant.AuthorizationCodeAuthHandler` and
`oauth2.grant.ImplicitGrantHandler`.
|
6259902c8a349b6b4368723a
|
class TestPlatzbegrenzungen(TestCase): <NEW_LINE> <INDENT> fixtures = [ 'testdata/verwaltungszeitraum_testdata', 'testdata/block_testdata', 'testdata/zeitraum_testdata', 'testdata/praxis_testdata', 'testdata/student_testdata', ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> Platz.objects.all().delete() <NEW_LINE> self.st1 = Student.objects.get(pk=1) <NEW_LINE> self.st2 = Student.objects.get(pk=2) <NEW_LINE> self.verwzr = Verwaltungszeitraum.objects.first() <NEW_LINE> for praxis in Praxis.objects.all(): <NEW_LINE> <INDENT> if praxis.maximale_kapazitaet(): <NEW_LINE> <INDENT> self.pr1 = praxis <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_keine_plaetze_vergeben(self): <NEW_LINE> <INDENT> Platzbegrenzung.objects.create( verwaltungszeitraum=self.verwzr, praxis=self.pr1, anzahl=0, ) <NEW_LINE> with self.assertRaisesRegex(ValidationError, 'Maximale Platzgrenze ist erreicht.'): <NEW_LINE> <INDENT> Platz.vergib_platz(self.st1.id, self.pr1.id) <NEW_LINE> <DEDENT> <DEDENT> def test_einen_platz_vergeben(self): <NEW_LINE> <INDENT> Platzbegrenzung.objects.create( verwaltungszeitraum=self.verwzr, praxis=self.pr1, anzahl=1, ) <NEW_LINE> Platz.vergib_platz(self.st1.id, self.pr1.id) <NEW_LINE> with self.assertRaisesRegex(ValidationError, 'Maximale Platzgrenze ist erreicht.'): <NEW_LINE> <INDENT> Platz.vergib_platz(self.st2.id, self.pr1.id) <NEW_LINE> <DEDENT> <DEDENT> def test_negative_anzahl(self): <NEW_LINE> <INDENT> platzgrenze = Platzbegrenzung.objects.create( verwaltungszeitraum=self.verwzr, praxis=self.pr1, anzahl=-1, ) <NEW_LINE> with self.assertRaisesRegex(ValidationError, 'Anzahl darf nicht negativ sein.'): <NEW_LINE> <INDENT> platzgrenze.full_clean()
|
Testet die Platzbegrenzungen.
|
6259902cac7a0e7691f734ea
|
class DraggableTabBar(TabBar): <NEW_LINE> <INDENT> tab_move_request = QtCore.Signal(QtWidgets.QWidget, int) <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> super(DraggableTabBar, self).__init__(parent) <NEW_LINE> self._pos = QtCore.QPoint() <NEW_LINE> self.setAcceptDrops(True) <NEW_LINE> self.setMouseTracking(True) <NEW_LINE> self.setElideMode(QtCore.Qt.ElideNone) <NEW_LINE> <DEDENT> def mousePressEvent(self, event): <NEW_LINE> <INDENT> if event.button() == QtCore.Qt.LeftButton: <NEW_LINE> <INDENT> self._pos = event.pos() <NEW_LINE> <DEDENT> super(DraggableTabBar, self).mousePressEvent(event) <NEW_LINE> <DEDENT> def widget_under_mouse(self, event): <NEW_LINE> <INDENT> index = self.tabAt(event.pos()) <NEW_LINE> tab = self.parent().widget(index) <NEW_LINE> return tab <NEW_LINE> <DEDENT> def mouseMoveEvent(self, event): <NEW_LINE> <INDENT> tab = self.widget_under_mouse(event) <NEW_LINE> if tab is not None: <NEW_LINE> <INDENT> tooltip = tab.toolTip() <NEW_LINE> if not tooltip: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tooltip = tab.file.path <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.setToolTip(tooltip) <NEW_LINE> <DEDENT> if (event.pos() - self._pos).manhattanLength() < QtWidgets.QApplication.startDragDistance(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not event.buttons() & QtCore.Qt.LeftButton: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> drag = QtWidgets.QDrag(self) <NEW_LINE> data = QtCore.QMimeData() <NEW_LINE> data.tab = tab <NEW_LINE> data.widget = self <NEW_LINE> data.setData("action", b"tab-reordering") <NEW_LINE> drag.setMimeData(data) <NEW_LINE> drag.setPixmap(self.tabIcon(self.tabAt(event.pos())).pixmap(32, 32)) <NEW_LINE> drag.exec_() <NEW_LINE> <DEDENT> def dragEnterEvent(self, event): <NEW_LINE> <INDENT> m = event.mimeData() <NEW_LINE> formats = m.formats() <NEW_LINE> if "action" in formats and m.data("action") == "tab-reordering": <NEW_LINE> <INDENT> event.acceptProposedAction() <NEW_LINE> <DEDENT> <DEDENT> def dropEvent(self, event): <NEW_LINE> <INDENT> m = event.mimeData() <NEW_LINE> index = self.tabAt(event.pos()) <NEW_LINE> if m.tab != self.parent().widget(index): <NEW_LINE> <INDENT> self.tab_move_request.emit(m.tab, index) <NEW_LINE> <DEDENT> event.acceptProposedAction()
|
A draggable tab bar that allow to drag & drop tabs.
Implementation is based on this qt article:
http://www.qtcentre.org/wiki/index.php?title=Movable_Tabs
|
6259902c30c21e258be9980d
|
class ProdConfig(Config): <NEW_LINE> <INDENT> DEBUG = False
|
Production configurations
|
6259902c507cdc57c63a5da9
|
class Cashier(Visitor): <NEW_LINE> <INDENT> def visit_book(self, book): <NEW_LINE> <INDENT> return book.get_price() <NEW_LINE> <DEDENT> def visit_fruit(self, fruit): <NEW_LINE> <INDENT> return fruit.get_price()
|
具体访问者 - 收银员
|
6259902cb57a9660fecd2a84
|
class PID: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.kp = 0 <NEW_LINE> self.ki = 0 <NEW_LINE> self.kd = 0 <NEW_LINE> self.p = 0 <NEW_LINE> self.i = 0 <NEW_LINE> self.d = 0 <NEW_LINE> self.previous_error = 0 <NEW_LINE> <DEDENT> def set_params(self, kp, ki, kd): <NEW_LINE> <INDENT> self.kp = kp <NEW_LINE> self.ki = ki <NEW_LINE> self.kd = kd <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.previous_error = 0 <NEW_LINE> self.i = 0 <NEW_LINE> <DEDENT> def calculate(self, error): <NEW_LINE> <INDENT> self.p = error * self.kp <NEW_LINE> self.i += error * self.ki <NEW_LINE> self.d = (error - self.previous_error) * self.kd <NEW_LINE> self.previous_error = error <NEW_LINE> return self.p + self.i + self.d
|
implements a standard PID controller
|
6259902c5166f23b2e2443d8
|
class OutputCore(Contractable): <NEW_LINE> <INDENT> def __init__(self, tensor): <NEW_LINE> <INDENT> if len(tensor.shape) not in [3, 4]: <NEW_LINE> <INDENT> raise ValueError( "OutputCore tensors must have shape [batch_size, " "output_dim, D_l, D_r], or else [output_dim, D_l," " D_r] if batch size has already been set" ) <NEW_LINE> <DEDENT> super().__init__(tensor, bond_str="bolr")
|
A single MPS core with a single output index
|
6259902c6fece00bbaccc9b2
|
class TakeComment(models.Model): <NEW_LINE> <INDENT> take = models.ForeignKey(Take, on_delete=models.CASCADE) <NEW_LINE> created_by = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True) <NEW_LINE> body = models.TextField()
|
Represents user discussion around a take
|
6259902c30c21e258be9980f
|
class SaveIO(object): <NEW_LINE> <INDENT> def __init__(self, io): <NEW_LINE> <INDENT> self.name = io.name <NEW_LINE> self.io_type = io.io_type <NEW_LINE> self.loaded_item = None <NEW_LINE> <DEDENT> def update(self, io): <NEW_LINE> <INDENT> self.__init__(io)
|
Container for UIIO state without Qt bindings. Used for saving.
|
6259902c50485f2cf55dbf7f
|
class ListLogPayloadResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Context = None <NEW_LINE> self.Listover = None <NEW_LINE> self.Results = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Context = params.get("Context") <NEW_LINE> self.Listover = params.get("Listover") <NEW_LINE> if params.get("Results") is not None: <NEW_LINE> <INDENT> self.Results = [] <NEW_LINE> for item in params.get("Results"): <NEW_LINE> <INDENT> obj = PayloadLogItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Results.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId")
|
ListLogPayload返回参数结构体
|
6259902cc432627299fa3ff8
|
class Task(TaskDetails, AbstractTask, Item): <NEW_LINE> <INDENT> path = '/tasks/' <NEW_LINE> @classmethod <NEW_LINE> def wait_for_response(cls, pulp, response, timeout=120): <NEW_LINE> <INDENT> ret = cls.from_response(response) <NEW_LINE> if isinstance(ret, list): <NEW_LINE> <INDENT> for task in ret: <NEW_LINE> <INDENT> task.wait(pulp, timeout=timeout) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ret.wait(pulp, timeout=timeout) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def wait_for_report(cls, pulp, response, timeout=300): <NEW_LINE> <INDENT> ret = cls.from_report(response)['spawned_tasks'] <NEW_LINE> if isinstance(ret, list): <NEW_LINE> <INDENT> for task in ret: <NEW_LINE> <INDENT> task_resp = pulp.send(Request('GET', strip_url(task['_href']))) <NEW_LINE> Task.wait_for_response(pulp, task_resp, timeout=timeout) <NEW_LINE> task_resp = pulp.send(Request('GET', strip_url(task['_href']))) <NEW_LINE> if 'spawned_tasks' in Task.from_response(task_resp).data: <NEW_LINE> <INDENT> Task.wait_for_report(pulp, task_resp, timeout=timeout) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def wait_for_reports(cls, pulp, responses, timeout=300): <NEW_LINE> <INDENT> for response in responses: <NEW_LINE> <INDENT> cls.wait_for_report(pulp, response, timeout)
|
an item-view task
|
6259902c21bff66bcd723c67
|
@register_axis('bqplot.Axis') <NEW_LINE> class Axis(BaseAxis): <NEW_LINE> <INDENT> icon = 'fa-arrows' <NEW_LINE> orientation = Enum(['horizontal', 'vertical'], default_value='horizontal', sync=True) <NEW_LINE> side = Enum(['bottom', 'top', 'left', 'right'], allow_none=True, default_value=None, sync=True) <NEW_LINE> label = Unicode(sync=True) <NEW_LINE> grid_lines = Enum(['none', 'solid', 'dashed'], default_value='none', sync=True) <NEW_LINE> tick_format = Unicode(None, allow_none=True, sync=True) <NEW_LINE> scale = Instance(Scale, sync=True, **widget_serialization) <NEW_LINE> num_ticks = Int(default_value=None, sync=True, allow_none=True) <NEW_LINE> tick_values = NdArray(sync=True) <NEW_LINE> offset = Dict(sync=True, **widget_serialization) <NEW_LINE> label_location = Enum(['middle', 'start', 'end'], default_value='middle', sync=True) <NEW_LINE> label_color = Color(None, sync=True, allow_none=True) <NEW_LINE> grid_color = Color(None, sync=True, allow_none=True) <NEW_LINE> color = Color(None, sync=True, allow_none=True) <NEW_LINE> label_offset = Unicode(default_value=None, sync=True, allow_none=True) <NEW_LINE> visible = Bool(True, sync=True) <NEW_LINE> _view_name = Unicode('Axis', sync=True) <NEW_LINE> _view_module = Unicode('nbextensions/bqplot/Axis', sync=True) <NEW_LINE> _model_name = Unicode('AxisModel', sync=True) <NEW_LINE> _model_module = Unicode('nbextensions/bqplot/AxisModel', sync=True) <NEW_LINE> _ipython_display_ = None
|
A line axis.
A line axis is the visual representation of a numerical or date scale.
Attributes
----------
icon: string (class-level attribute)
The font-awesome icon name for this object.
axis_types: dict (class-level attribute)
A registry of existing axis types.
orientation: {'horizontal', 'vertical'}
The orientation of the axis, either vertical or horizontal
side: {'bottom', 'top', 'left', 'right'} or None (default: None)
The side of the axis, either bottom, top, left or right.
label: string (default: '')
The axis label
tick_format: string or None (default: '')
The tick format for the axis.
scale: Scale
The scale represented by the axis
num_ticks: int or None (default: None)
If tick_values is None, number of ticks
tick_values: numpy.ndarray or None (default: [])
Tick values for the axis
offset: dict (default: {})
Containing a scale and a value {'scale': scale or None,
'value': value of the offset}
If offset['scale'] is None, the corresponding figure scale is used
instead.
label_location: {'middle', 'start', 'end'}
The location of the label along the axis, one of 'start', 'end' or
'middle'
label_color: Color or None (default: None)
The color of the axis label
grid_lines: {'none', 'solid', 'dashed'}
The display of the grid lines
grid_color: Color or None (default: None)
The color of the grid lines
color: Color or None (default: None)
The color of the line
label_offset: string or None (default: None)
Label displacement from the axis line. Units allowed are 'em', 'px'
and 'ex'. Positive values are away from the figure and negative
values are towards the figure with resepect to the axis line.
visible: bool (default: True)
A visibility toggle for the axis
|
6259902cd4950a0f3b11163f
|
class Yaw(EventState): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> smach.State.__init__(self, outcomes=['Success', 'Failure'], input_keys=['args']) <NEW_LINE> self.topic = "go_to_yaw" <NEW_LINE> self.client = ProxyActionClient({ self.topic, riptide_controllers.msg.GoToYawAction}) <NEW_LINE> <DEDENT> def on_enter(self, userdata): <NEW_LINE> <INDENT> Logger.loginfo('Yawing with angle %f'%userdata.args['angle']) <NEW_LINE> self.client.send_goal(self.topic, riptide_controllers.msg.GoToYawGoal(userdata.args['angle'])) <NEW_LINE> <DEDENT> def execute(self, userdata): <NEW_LINE> <INDENT> if self.client.has_result(self.topic): <NEW_LINE> <INDENT> result = self.client.get_result(self.topic) <NEW_LINE> status = 'Success' <NEW_LINE> return status
|
Handles rotating the robot's yaw by a given angle.
Yaw is like left/right movement.
@param angle => float
the angle to rotate by
|
6259902cd10714528d69ee8f
|
class DeepTask(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.testDir = tempfile.mkdtemp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> CRABClient.Emulator.clearEmulators() <NEW_LINE> if os.path.exists(self.testDir): <NEW_LINE> <INDENT> shutil.rmtree(self.testDir) <NEW_LINE> <DEDENT> <DEDENT> def test_Submit(self): <NEW_LINE> <INDENT> class dummyRest: <NEW_LINE> <INDENT> def __init__(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get(self, url, req): <NEW_LINE> <INDENT> if url == '/crabserver/prod/info': <NEW_LINE> <INDENT> if req == {'subresource': 'version'}: <NEW_LINE> <INDENT> return {'result':["unittest"]},200,"" <NEW_LINE> <DEDENT> if req == {'subresource': 'backendurls'}: <NEW_LINE> <INDENT> return {'result':["unittest.host"]},200,"" <NEW_LINE> <DEDENT> <DEDENT> print("%s -> %s" % (url, req)) <NEW_LINE> <DEDENT> def put(self, url, data): <NEW_LINE> <INDENT> if url == '/crabserver/prod/workflow': <NEW_LINE> <INDENT> res = {'result':[{"RequestName" : "UnittestRequest"}]} <NEW_LINE> return res, 200, "" <NEW_LINE> <DEDENT> print("%s -> %s" % (url, data)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getCACertPath(): <NEW_LINE> <INDENT> return "/tmp" <NEW_LINE> <DEDENT> <DEDENT> class dummyUFC: <NEW_LINE> <INDENT> def __init__(self, req): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def upload(self, name): <NEW_LINE> <INDENT> return {'hashkey':'unittest-dummy-tarball'} <NEW_LINE> <DEDENT> <DEDENT> CRABClient.Emulator.setEmulator('rest', dummyRest) <NEW_LINE> CRABClient.Emulator.setEmulator('ufc', dummyUFC) <NEW_LINE> myTask = CRABAPI.Abstractions.Task() <NEW_LINE> myTask.config.section_("General") <NEW_LINE> myTask.config.General.requestName = 'test1' <NEW_LINE> myTask.config.General.transferLogs = True <NEW_LINE> myTask.config.General.workArea = os.path.join(self.testDir, "unit") <NEW_LINE> myTask.config.section_("JobType") <NEW_LINE> myTask.config.JobType.pluginName = 'PrivateMC' <NEW_LINE> myTask.config.JobType.psetName = 'test_pset.py' <NEW_LINE> myTask.config.section_("Data") <NEW_LINE> myTask.config.Data.inputDataset = '/CrabTestSingleMu' <NEW_LINE> myTask.config.Data.splitting = 'EventBased' <NEW_LINE> myTask.config.Data.unitsPerJob = 100 <NEW_LINE> myTask.config.Data.totalUnits = 1000 <NEW_LINE> myTask.config.Data.publication = True <NEW_LINE> myTask.config.Data.outputDatasetTag = 'CRABAPI-Unittest' <NEW_LINE> myTask.config.section_("Site") <NEW_LINE> myTask.config.Site.storageSite = 'T2_US_Nowhere' <NEW_LINE> val = myTask.submit() <NEW_LINE> print(val) <NEW_LINE> self.assertEqual(val, 'UnittestRequest')
|
Test that we actually get back what we want from CRABClient. Don't
require too much from the internals, just inject enough fake
dependecies to convince the client it's talking to something real
|
6259902c925a0f43d25e904d
|
class TextMatchStrategy(object): <NEW_LINE> <INDENT> def __init__(self, name: str, matcher: Callable[[str, str], bool]): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.matcher = matcher <NEW_LINE> <DEDENT> def __call__(self, text: str, pattern: str) -> bool: <NEW_LINE> <INDENT> return self.matcher(text, pattern) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _prefixes_of(text: str) -> Sequence[str]: <NEW_LINE> <INDENT> for i in range(len(text)): <NEW_LINE> <INDENT> yield text[i:] <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _matches_words(text: str, words: Sequence[str]) -> bool: <NEW_LINE> <INDENT> if not text: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for word in words: <NEW_LINE> <INDENT> common_prefix = os.path.commonprefix([text, word]) <NEW_LINE> if not common_prefix: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif common_prefix == text: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for prefix in TextMatchStrategy._prefixes_of(common_prefix): <NEW_LINE> <INDENT> if TextMatchStrategy._matches_words(text[len(prefix):], words[1:]): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def snake_case_matches(short: str, full: str) -> bool: <NEW_LINE> <INDENT> return TextMatchStrategy._matches_words(short, full.split('_')) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def fuzzy_matches(short: str, full: str) -> bool: <NEW_LINE> <INDENT> short_at = 0 <NEW_LINE> for char in full: <NEW_LINE> <INDENT> if char == short[short_at]: <NEW_LINE> <INDENT> short_at += 1 <NEW_LINE> if short_at == len(short): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
|
Represents a method of checking if given text matches a pattern.
|
6259902cb57a9660fecd2a88
|
class Command(RunServerCommand): <NEW_LINE> <INDENT> option_list = RunServerCommand.option_list + ( make_option('--pdb', action='store_true', dest='pdb', default=False, help='Drop into pdb shell on at the start of any view.'), make_option('--ipdb', action='store_true', dest='ipdb', default=False, help='Drop into ipdb shell on at the start of any view.'), ) <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> from django.conf import settings <NEW_LINE> pdb_option = options.pop('pdb') <NEW_LINE> ipdb_option = options.pop('ipdb') <NEW_LINE> if pdb_option or settings.DEBUG: <NEW_LINE> <INDENT> settings.MIDDLEWARE_CLASSES += ('django_pdb.middleware.PdbMiddleware',) <NEW_LINE> <DEDENT> if pdb_option: <NEW_LINE> <INDENT> PdbMiddleware.always_break = 'pdb' <NEW_LINE> <DEDENT> elif ipdb_option: <NEW_LINE> <INDENT> PdbMiddleware.always_break = 'ipdb' <NEW_LINE> <DEDENT> super(Command, self).handle(*args, **options)
|
Identical to Django's standard 'runserver' management command,
except that it also adds support for a '--pdb' option.
|
6259902cd99f1b3c44d066a9
|
class ServiceTagsOperations: <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer) -> None: <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> async def list( self, location: str, **kwargs: Any ) -> "_models.ServiceTagsListResult": <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2020-11-01" <NEW_LINE> accept = "application/json" <NEW_LINE> url = self.list.metadata['url'] <NEW_LINE> path_format_arguments = { 'location': self._serialize.url("location", location, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = self._deserialize('ServiceTagsListResult', pipeline_response) <NEW_LINE> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized <NEW_LINE> <DEDENT> list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTags'}
|
ServiceTagsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_11_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
|
6259902cd4950a0f3b111640
|
class product_specification(osv.osv): <NEW_LINE> <INDENT> _name = 'product.specification' <NEW_LINE> _rec_name = 'description' <NEW_LINE> def onchange_product_det_id(self, cr, uid, ids, product_id, determination_id, context=None): <NEW_LINE> <INDENT> description='' <NEW_LINE> productname='' <NEW_LINE> determinationname='' <NEW_LINE> if determination_id: <NEW_LINE> <INDENT> deter = self.pool.get('certificate.determination').browse(cr, uid, lot_id, context=context) <NEW_LINE> determinationname=deter.name <NEW_LINE> <DEDENT> if product_id: <NEW_LINE> <INDENT> prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context) <NEW_LINE> productname=prod.name <NEW_LINE> <DEDENT> description=productname + ' - ' + determinationname <NEW_LINE> return {'value': {'description': description }} <NEW_LINE> <DEDENT> _columns = { 'description': fields.char('Description', size=50, required=False), 'product_id': fields.many2one('product.product', 'Product', required=True, help="Product."), 'determination_id': fields.many2one('certificate.determination', 'Determination', required=True, help="Determination."), 'limits': fields.char('Limits', size=50, required=False), }
|
Open ERP Model Product Specification
|
6259902c0a366e3fb87dd9ee
|
class ProjectsGetXpnResources(_messages.Message): <NEW_LINE> <INDENT> kind = _messages.StringField(1, default=u'compute#projectsGetXpnResources') <NEW_LINE> nextPageToken = _messages.StringField(2) <NEW_LINE> resources = _messages.MessageField('XpnResourceId', 3, repeated=True)
|
A ProjectsGetXpnResources object.
Fields:
kind: [Output Only] Type of resource. Always
compute#projectsGetXpnResources for lists of service resources (a.k.a
service projects)
nextPageToken: [Output Only] This token allows you to get the next page of
results for list requests. If the number of results is larger than
maxResults, use the nextPageToken as a value for the query parameter
pageToken in the next list request. Subsequent list requests will have
their own nextPageToken to continue paging through the results.
resources: Service resources (a.k.a service projects) attached to this
project as their shared VPC host.
|
6259902c8a349b6b43687241
|
class WebhookNotifier(NotifierUtils): <NEW_LINE> <INDENT> def __init__(self, url, username, password): <NEW_LINE> <INDENT> self.logger = structlog.get_logger() <NEW_LINE> self.url = url <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def notify(self, messages, chart_file): <NEW_LINE> <INDENT> data = {'messages': json.dumps(messages)} <NEW_LINE> if chart_file and os.path.exists(chart_file): <NEW_LINE> <INDENT> files = {'chart': open(chart_file, 'rb')} <NEW_LINE> if self.username and self.password: <NEW_LINE> <INDENT> request = requests.post( self.url, files=files, data=data, auth=(self.username, self.password)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(f'url is {self.url}') <NEW_LINE> print(f'data is {data}') <NEW_LINE> request = requests.post(self.url, files=files, data=data) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.username and self.password: <NEW_LINE> <INDENT> request = requests.post( self.url, data=data, auth=(self.username, self.password)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request = requests.post(self.url, data=data) <NEW_LINE> <DEDENT> <DEDENT> if not request.status_code == requests.codes.ok: <NEW_LINE> <INDENT> self.logger.error("Request failed: %s - %s", request.status_code, request.content)
|
Class for handling webhook notifications
|
6259902c15baa72349462f9f
|
class Question(models.Model): <NEW_LINE> <INDENT> objects = QuestionManager() <NEW_LINE> title = models.CharField(max_length=255) <NEW_LINE> text = models.TextField() <NEW_LINE> added_at = models.DateField(auto_now_add=True) <NEW_LINE> rating = models.IntegerField(default=0) <NEW_LINE> author = models.OneToOneField(User) <NEW_LINE> likes = models.ManyToManyField(User, related_name="likes_set") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "%s %s" % (self.author, self.title) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('rating', 'added_at')
|
Question - вопрос
title - заголовок вопроса
text - полный текст вопроса
added_at - дата добавления вопроса
rating - рейтинг вопроса (число)
author - автор вопроса
likes - список пользователей, поставивших "лайк"
|
6259902c30c21e258be99812
|
class Chip(Base): <NEW_LINE> <INDENT> __tablename__ = "chips" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> boards = relationship("Board", secondary = "board_chip_links") <NEW_LINE> board_links = relationship("BoardChipLink", back_populates = "chip") <NEW_LINE> channels = relationship("Channel", secondary = "chip_channel_links") <NEW_LINE> channel_links = relationship("ChipChannelLink", order_by = 'ChipChannelLink.address', back_populates = "chip") <NEW_LINE> def add_channel(self, channel, address): <NEW_LINE> <INDENT> return ChipChannelLink(chip=self, channel=channel, address=address) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Chip: %s>" % self.id
|
A chip is a pair of FE/ADC asics with 16 channels
|
6259902c5e10d32532ce4107
|
class Constant(NonNode): <NEW_LINE> <INDENT> def __init__(self, constant: float): <NEW_LINE> <INDENT> self.constant = constant <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"{self.__class__.__name__}({self.constant})" <NEW_LINE> <DEDENT> @property <NEW_LINE> def dependencies(self) -> Iterable["Expression"]: <NEW_LINE> <INDENT> yield from () <NEW_LINE> <DEDENT> def evaluate(self, context: Mapping["Node", float]) -> float: <NEW_LINE> <INDENT> return self.constant
|
Constant value over time.
|
6259902cd164cc6175821f79
|
class DepSolver (object): <NEW_LINE> <INDENT> def __init__(self, arch=None): <NEW_LINE> <INDENT> self.deps = set() <NEW_LINE> <DEDENT> def get_deps(self, path): <NEW_LINE> <INDENT> LOG.info('getting dependencies for %s', path) <NEW_LINE> try: <NEW_LINE> <INDENT> ef = ELFFile(path) <NEW_LINE> interp = ef.interpreter() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> LOG.debug('%s is not a dynamically linked ELF binary (ignoring)', path) <NEW_LINE> return <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> LOG.debug('%s does not have a .interp section', path) <NEW_LINE> return <NEW_LINE> <DEDENT> self.deps.add(interp) <NEW_LINE> out = subprocess.check_output([interp, '--list', path]) <NEW_LINE> for line in out.splitlines(): <NEW_LINE> <INDENT> for exp in RE_DEPS: <NEW_LINE> <INDENT> match = exp.match(line) <NEW_LINE> if not match: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> dep = match.group('path') <NEW_LINE> LOG.debug('%s requires %s', path, dep) <NEW_LINE> self.deps.add(dep) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add(self, path): <NEW_LINE> <INDENT> self.get_deps(path) <NEW_LINE> <DEDENT> def prefixes(self): <NEW_LINE> <INDENT> return set(os.path.dirname(path) for path in self.deps)
|
Finds shared library dependencies of ELF binaries.
|
6259902c507cdc57c63a5daf
|
class AutoReset(object): <NEW_LINE> <INDENT> def __init__(self, env): <NEW_LINE> <INDENT> self._env = env <NEW_LINE> self._done = True <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self._env, name) <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> if self._done: <NEW_LINE> <INDENT> observ, reward, done, info = self._env.reset(), 0.0, False, {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> observ, reward, done, info = self._env.step(action) <NEW_LINE> <DEDENT> self._done = done <NEW_LINE> return observ, reward, done, info <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._done = False <NEW_LINE> return self._env.reset()
|
Automatically reset environment when the episode is done.
|
6259902cec188e330fdf989b
|
@register_command <NEW_LINE> class GlibcHeapSmallBinsCommand(GenericCommand): <NEW_LINE> <INDENT> _cmdline_ = "heap bins small" <NEW_LINE> _syntax_ = "{:s} [ARENA_ADDRESS]".format(_cmdline_) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(GlibcHeapSmallBinsCommand, self).__init__(complete=gdb.COMPLETE_LOCATION) <NEW_LINE> return <NEW_LINE> <DEDENT> @only_if_gdb_running <NEW_LINE> def do_invoke(self, argv): <NEW_LINE> <INDENT> if get_main_arena() is None: <NEW_LINE> <INDENT> err("Incorrect Glibc arenas") <NEW_LINE> return <NEW_LINE> <DEDENT> arena_addr = "*{:s}".format(argv[0]) if len(argv) == 1 else "main_arena" <NEW_LINE> print(titlify("Small Bins for arena '{:s}'".format(arena_addr))) <NEW_LINE> bins = {} <NEW_LINE> for i in range(1, 63): <NEW_LINE> <INDENT> nb_chunk = GlibcHeapBinsCommand.pprint_bin(arena_addr, i, "small_") <NEW_LINE> if nb_chunk < 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if nb_chunk > 0: <NEW_LINE> <INDENT> bins[i] = nb_chunk <NEW_LINE> <DEDENT> <DEDENT> info("Found {:d} chunks in {:d} small non-empty bins.".format(sum(bins.values()), len(bins))) <NEW_LINE> return
|
Convenience command for viewing small bins.
|
6259902c711fe17d825e149e
|
class SetSubpictureClut(PipelineCmd): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> methodName = 'setSubpictureClut'
|
When constructed with parameter list `(clut)`, set the
subpicture color lookup table to 'clut''clut' is a 16-position
array.
|
6259902cbe8e80087fbc0083
|
class Halo(object): <NEW_LINE> <INDENT> def __init__(self, dm): <NEW_LINE> <INDENT> lsec = dm.getDefaultSection() <NEW_LINE> gsec = dm.getDefaultGlobalSection() <NEW_LINE> dm.createDefaultSF(lsec, gsec) <NEW_LINE> sf = dm.getDefaultSF() <NEW_LINE> self.sf = dmplex.prune_sf(sf) <NEW_LINE> self.comm = self.sf.comm.tompi4py() <NEW_LINE> self.sf.setFromOptions() <NEW_LINE> if self.sf.getType() != self.sf.Type.BASIC: <NEW_LINE> <INDENT> raise RuntimeError("Windowed SFs expose bugs in OpenMPI (use -sf_type basic)") <NEW_LINE> <DEDENT> if self.comm.size == 1: <NEW_LINE> <INDENT> self._gnn2unn = None <NEW_LINE> <DEDENT> self._gnn2unn = dmplex.make_global_numbering(lsec, gsec) <NEW_LINE> <DEDENT> def begin(self, dat, reverse=False): <NEW_LINE> <INDENT> if self.comm.size == 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mtype = _get_mtype(dat) <NEW_LINE> dmplex.halo_begin(self.sf, dat, mtype, reverse) <NEW_LINE> <DEDENT> def end(self, dat, reverse=False): <NEW_LINE> <INDENT> if self.comm.size == 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mtype = _get_mtype(dat) <NEW_LINE> maybe_setflags(dat._data, write=True) <NEW_LINE> dmplex.halo_end(self.sf, dat, mtype, reverse) <NEW_LINE> maybe_setflags(dat._data, write=False) <NEW_LINE> <DEDENT> def verify(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def global_to_petsc_numbering(self): <NEW_LINE> <INDENT> return self._gnn2unn
|
Build a Halo for a function space.
:arg dm: The DM describing the data layout (has a Section attached).
The halo is implemented using a PETSc SF (star forest) object and
is usable as a PyOP2 :class:`pyop2.Halo`.
|
6259902cd10714528d69ee91
|
class GlibTranslations(gettext.GNUTranslations): <NEW_LINE> <INDENT> def __init__(self, fp=None): <NEW_LINE> <INDENT> self.path = (fp and fp.name) or "" <NEW_LINE> self._catalog = {} <NEW_LINE> self.plural = lambda n: n != 1 <NEW_LINE> gettext.GNUTranslations.__init__(self, fp) <NEW_LINE> <DEDENT> def qgettext(self, msgid): <NEW_LINE> <INDENT> msgstr = self.gettext(msgid) <NEW_LINE> if msgstr == msgid: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return msgstr.split("|", 1)[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return msgstr <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return msgstr <NEW_LINE> <DEDENT> <DEDENT> def ugettext(self, message): <NEW_LINE> <INDENT> message = unicode(message) <NEW_LINE> return gettext.GNUTranslations.ugettext(self, message) <NEW_LINE> <DEDENT> def ungettext(self, msgid1, msgid2, n): <NEW_LINE> <INDENT> msgid1 = unicode(msgid1) <NEW_LINE> msgid2 = unicode(msgid2) <NEW_LINE> return gettext.GNUTranslations.ungettext(self, msgid1, msgid2, n) <NEW_LINE> <DEDENT> def uqgettext(self, msgid): <NEW_LINE> <INDENT> msgid = unicode(msgid) <NEW_LINE> msgstr = self.ugettext(msgid) <NEW_LINE> if msgstr == msgid: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return msgstr.split(u"|", 1)[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return msgstr <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return msgstr <NEW_LINE> <DEDENT> <DEDENT> def install(self, unicode=False): <NEW_LINE> <INDENT> if "QUODLIBET_NO_TRANS" in os.environ: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if unicode: <NEW_LINE> <INDENT> _ = self.ugettext <NEW_LINE> _Q = self.uqgettext <NEW_LINE> ngettext = self.ungettext <NEW_LINE> _N = unicode <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _ = self.gettext <NEW_LINE> _Q = self.qgettext <NEW_LINE> ngettext = self.ngettext <NEW_LINE> _N = lambda s: s <NEW_LINE> <DEDENT> test_key = "QUODLIBET_TEST_TRANS" <NEW_LINE> if test_key in os.environ: <NEW_LINE> <INDENT> text = os.environ[test_key] <NEW_LINE> def wrap(f): <NEW_LINE> <INDENT> def g(*args): <NEW_LINE> <INDENT> return text + f(*args) + text <NEW_LINE> <DEDENT> return g <NEW_LINE> <DEDENT> _ = wrap(_) <NEW_LINE> _Q = wrap(_Q) <NEW_LINE> _N = wrap(_N) <NEW_LINE> ngettext = wrap(ngettext) <NEW_LINE> <DEDENT> __builtin__.__dict__["_"] = _ <NEW_LINE> __builtin__.__dict__["Q_"] = _Q <NEW_LINE> __builtin__.__dict__["N_"] = _N <NEW_LINE> __builtin__.__dict__["ngettext"] = ngettext
|
Provide a glib-like translation API for Python.
This class adds support for qgettext (and uqgettext) mirroring
glib's Q_ macro, which allows for disambiguation of identical
source strings. It also installs N_, Q_, and ngettext into the
__builtin__ namespace.
It can also be instantiated and used with any valid MO files
(though it won't be able to translate anything, of course).
|
6259902c507cdc57c63a5db1
|
class MatrixUtils: <NEW_LINE> <INDENT> def circle(pos, radius, imgsize): <NEW_LINE> <INDENT> xx, yy = np.mgrid[:imgsize[0], :imgsize[1]] <NEW_LINE> distances = (xx - pos[0]) ** 2 + (yy - pos[1]) ** 2 <NEW_LINE> radius2 = radius**2 <NEW_LINE> result = distances.clip(0, radius2)/radius2 * -1 + 1 <NEW_LINE> return result <NEW_LINE> <DEDENT> def ellipse(pos, size, imgsize): <NEW_LINE> <INDENT> xx, yy = np.mgrid[:imgsize[0], :imgsize[1]] <NEW_LINE> ratio = size[0]/size[1] <NEW_LINE> distances = (xx - pos[0]) ** 2 + ((yy - pos[1]) * ratio) ** 2 <NEW_LINE> ceiling = size[0]**2 <NEW_LINE> result = distances.clip(0, ceiling)/ceiling * -1 + 1 <NEW_LINE> return result <NEW_LINE> <DEDENT> def color(mat, color): <NEW_LINE> <INDENT> mat.shape = mat.shape + (1,) <NEW_LINE> result = mat.repeat(4, axis=-1) <NEW_LINE> mat.shape = mat.shape[:-1] <NEW_LINE> result *= color <NEW_LINE> return result.flatten()
|
Useful for drawing and colouring simple shapes.
|
6259902c50485f2cf55dbf85
|
class EditForm(base.EditForm): <NEW_LINE> <INDENT> form_fields = form.fields(IPeoplePage) <NEW_LINE> label = _(u"Edit People Page") <NEW_LINE> form_name = _(u"People Page Details")
|
Edit form
|
6259902cec188e330fdf989d
|
class HiddenContent(Base): <NEW_LINE> <INDENT> __tablename__ = 'hidden_content' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> content_type = Column(String(32)) <NEW_LINE> content_identifier = Column(String(128)) <NEW_LINE> content_description = Column(String) <NEW_LINE> def __init__(self, content_type, content_identifier, content_description=''): <NEW_LINE> <INDENT> self.content_type = content_type <NEW_LINE> self.content_identifier = content_identifier <NEW_LINE> self.content_description = content_description <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_hidden_content(rein, content_type): <NEW_LINE> <INDENT> hidden_content_db = rein.session.query(HiddenContent).filter(HiddenContent.content_type == content_type).all() <NEW_LINE> hidden_content = [] <NEW_LINE> for content in hidden_content_db: <NEW_LINE> <INDENT> hidden_content.append({'content_identifier': content.content_identifier, 'content_description': content.content_description}) <NEW_LINE> <DEDENT> return hidden_content <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def hide_button(content_type, content_identifier, content_description=''): <NEW_LINE> <INDENT> button_id = random.getrandbits(32) <NEW_LINE> content_description = content_description.replace('"', '"').replace("'", """) <NEW_LINE> return '<button type="button" onclick="hide(\'{}\', \'{}\', \'{}\', \'{}\')" id="{}">Hide {}</button>'.format(content_type, content_identifier, content_description, button_id, button_id, content_type) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def unhide_button(content_type, content_identifier): <NEW_LINE> <INDENT> button_id = random.getrandbits(32) <NEW_LINE> return '<button type="button" onclick="unhide(\'{}\', \'{}\', \'{}\')" id="{}">Unhide {}</button>'.format(content_type, content_identifier, button_id, button_id, content_type)
|
Model to hold settings regarding what content is hidden.
|
6259902cc432627299fa3ffe
|
class AnnotationTypesEnum(str, enum.Enum): <NEW_LINE> <INDENT> Anatomy = "Anatomy" <NEW_LINE> Cell = "Cell" <NEW_LINE> CellLine = "CellLine" <NEW_LINE> CellStructure = "CellStructure" <NEW_LINE> Disease = "Disease" <NEW_LINE> Species = "Species" <NEW_LINE> All = "All"
|
Namespace entity annotation types
|
6259902c73bcbd0ca4bcb29c
|
class TrapaggCollector(object): <NEW_LINE> <INDENT> def __init__(self, args=None): <NEW_LINE> <INDENT> self.args = None <NEW_LINE> if not args: <NEW_LINE> <INDENT> args = sys.argv[1:] <NEW_LINE> <DEDENT> self._parse_args(args) <NEW_LINE> <DEDENT> def _parse_args(self, args): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> group = parser.add_mutually_exclusive_group(required=True) <NEW_LINE> group.add_argument( '-f', '--textfile-name', dest='textfile_name', help=('Full file path where to store data for node ' 'collector to pick up') ) <NEW_LINE> group.add_argument( '-l', '--listen', dest='listen', help='Listen host:port, i.e. 0.0.0.0:9417' ) <NEW_LINE> parser.add_argument( '-i', '--interval', dest='interval', type=int, help=('Number of seconds between updates of the textfile. ' 'Default is 5 seconds') ) <NEW_LINE> parser.add_argument( '-1', '--oneshot', dest='oneshot', action='store_true', default=False, help='Run only once and exit. Useful for running in a cronjob' ) <NEW_LINE> arguments = parser.parse_args(args) <NEW_LINE> if arguments.oneshot and not arguments.textfile_name: <NEW_LINE> <INDENT> logging.error('Oneshot has to be used with textfile mode') <NEW_LINE> parser.print_help() <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> if arguments.interval and not arguments.textfile_name: <NEW_LINE> <INDENT> logging.error('Interval has to be used with textfile mode') <NEW_LINE> parser.print_help() <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> if not arguments.interval: <NEW_LINE> <INDENT> arguments.interval = 5 <NEW_LINE> <DEDENT> self.args = vars(arguments) <NEW_LINE> <DEDENT> def trapagg_output_get(self, command): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> proc = subprocess.Popen(command, stdout=subprocess.PIPE) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> logging.critical(e.strerror) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return proc.stdout.readlines() <NEW_LINE> <DEDENT> def update_trapagg_stats(self, counter): <NEW_LINE> <INDENT> command = ['./trapagg', '-s'] <NEW_LINE> output = self.trapagg_output_get(command) <NEW_LINE> for line in output[2:]: <NEW_LINE> <INDENT> columns = line.decode('utf-8').split() <NEW_LINE> counter.add_metric(columns[:-1], columns[-1]) <NEW_LINE> <DEDENT> <DEDENT> def collect(self): <NEW_LINE> <INDENT> output = self.trapagg_output_get(['./trapagg', '-s']) <NEW_LINE> labels = [l.lower() for l in output[1].decode('utf-8').split()] <NEW_LINE> counter = CounterMetricFamily('node_net_trapagg', 'Aggregated trap data', labels=labels) <NEW_LINE> for line in output[2:]: <NEW_LINE> <INDENT> columns = line.decode('utf-8').split() <NEW_LINE> counter.add_metric(columns[:-1], columns[-1]) <NEW_LINE> <DEDENT> yield counter
|
Collect aggregated per-{trap, flow} metrics and publish them via http
or save them to a file.
|
6259902c8a43f66fc4bf318e
|
class ExtendedCode(AbstractLinearCode): <NEW_LINE> <INDENT> _registered_encoders = {} <NEW_LINE> _registered_decoders = {} <NEW_LINE> def __init__(self, C): <NEW_LINE> <INDENT> if not isinstance(C, AbstractLinearCode): <NEW_LINE> <INDENT> raise ValueError("Provided code must be a linear code") <NEW_LINE> <DEDENT> super(ExtendedCode, self).__init__(C.base_ring(), C.length() + 1, "ExtendedMatrix", "OriginalDecoder") <NEW_LINE> self._original_code = C <NEW_LINE> self._dimension = C.dimension() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, ExtendedCode) and self.original_code() == other.original_code() <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Extension of %s" % self.original_code() <NEW_LINE> <DEDENT> def _latex_(self): <NEW_LINE> <INDENT> return "\\textnormal{Extension of %s}" % self.original_code() <NEW_LINE> <DEDENT> def original_code(self): <NEW_LINE> <INDENT> return self._original_code <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def parity_check_matrix(self): <NEW_LINE> <INDENT> F = self.base_ring() <NEW_LINE> zero = F.zero() <NEW_LINE> one = F.one() <NEW_LINE> H = self.original_code().parity_check_matrix() <NEW_LINE> nr, nc = H.nrows(), H.ncols() <NEW_LINE> Hlist = H.list() <NEW_LINE> v = matrix(F, nr + 1, 1, [one] + [zero] * nr) <NEW_LINE> M = matrix(F, nr + 1, nc, [one] * nc + Hlist).augment(v) <NEW_LINE> M.set_immutable() <NEW_LINE> return M <NEW_LINE> <DEDENT> def random_element(self): <NEW_LINE> <INDENT> c = self.original_code().random_element() <NEW_LINE> c_list = c.list() <NEW_LINE> F = self.base_ring() <NEW_LINE> last_element = F.zero() <NEW_LINE> for i in c_list: <NEW_LINE> <INDENT> last_element += i <NEW_LINE> <DEDENT> c_list.append(-last_element) <NEW_LINE> return vector(F, c_list)
|
Representation of an extended code.
INPUT:
- ``C`` -- A linear code
EXAMPLES::
sage: C = codes.random_linear_code(GF(7), 11, 5)
sage: Ce = codes.ExtendedCode(C)
sage: Ce
Extension of [11, 5] linear code over GF(7)
|
6259902c6fece00bbaccc9b9
|
class TestODataQueryOptionsAccount(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testODataQueryOptionsAccount(self): <NEW_LINE> <INDENT> pass
|
ODataQueryOptionsAccount unit test stubs
|
6259902cbe8e80087fbc0085
|
class WindowsClient(_BaseClient): <NEW_LINE> <INDENT> def __init__(self, origin, verify=verify_rp_id, handle=None): <NEW_LINE> <INDENT> super(WindowsClient, self).__init__(origin, verify) <NEW_LINE> self.api = WinAPI(handle) <NEW_LINE> <DEDENT> @property <NEW_LINE> def info(self): <NEW_LINE> <INDENT> return _WIN_INFO <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_available(): <NEW_LINE> <INDENT> return platform.system().lower() == "windows" and WinAPI.version > 0 <NEW_LINE> <DEDENT> def make_credential(self, options, **kwargs): <NEW_LINE> <INDENT> options = PublicKeyCredentialCreationOptions._wrap(options) <NEW_LINE> self._verify_rp_id(options.rp.id) <NEW_LINE> client_data = self._build_client_data( WEBAUTHN_TYPE.MAKE_CREDENTIAL, options.challenge ) <NEW_LINE> selection = options.authenticator_selection or AuthenticatorSelectionCriteria() <NEW_LINE> try: <NEW_LINE> <INDENT> result = self.api.make_credential( options.rp, options.user, options.pub_key_cred_params, client_data, options.timeout or 0, selection.require_resident_key or False, WebAuthNAuthenticatorAttachment.from_string( selection.authenticator_attachment or "any" ), WebAuthNUserVerificationRequirement.from_string( selection.user_verification or "discouraged" ), WebAuthNAttestationConvoyancePreference.from_string( options.attestation or "none" ), options.exclude_credentials, options.extensions, kwargs.get("event"), ) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> raise ClientError.ERR.OTHER_ERROR(e) <NEW_LINE> <DEDENT> return AttestationObject(result), client_data <NEW_LINE> <DEDENT> def get_assertion(self, options, **kwargs): <NEW_LINE> <INDENT> options = PublicKeyCredentialRequestOptions._wrap(options) <NEW_LINE> self._verify_rp_id(options.rp_id) <NEW_LINE> client_data = self._build_client_data( WEBAUTHN_TYPE.GET_ASSERTION, options.challenge ) <NEW_LINE> try: <NEW_LINE> <INDENT> (credential, auth_data, signature, user_id) = self.api.get_assertion( options.rp_id, client_data, options.timeout or 0, WebAuthNAuthenticatorAttachment.ANY, WebAuthNUserVerificationRequirement.from_string( options.user_verification or "discouraged" ), options.allow_credentials, options.extensions, kwargs.get("event"), ) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> raise ClientError.ERR.OTHER_ERROR(e) <NEW_LINE> <DEDENT> user = {"id": user_id} if user_id else None <NEW_LINE> return ( [AssertionResponse.create(credential, auth_data, signature, user)], client_data, )
|
Fido2Client-like class using the Windows WebAuthn API.
Note: This class only works on Windows 10 19H1 or later. This is also when Windows
started restricting access to FIDO devices, causing the standard client classes to
require admin priveleges to run (unlike this one).
The make_credential and get_assertion methods are intended to work as a drop-in
replacement for the Fido2Client methods of the same name.
:param str origin: The origin to use.
:param verify: Function to verify an RP ID for a given origin.
:param ctypes.wintypes.HWND handle: (optional) Window reference to use.
|
6259902c1d351010ab8f4b22
|
class PhonebookTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.phonebook = Phonebook() <NEW_LINE> <DEDENT> def test_lookup_entry_by_name(self): <NEW_LINE> <INDENT> self.phonebook.add("Bob", "12345") <NEW_LINE> self.assertEqual("12345", self.phonebook.lookup("Bob")) <NEW_LINE> <DEDENT> def test_missing_entry_raises_KeyError(self): <NEW_LINE> <INDENT> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> self.phonebook.lookup("missing") <NEW_LINE> <DEDENT> <DEDENT> def test_empty_phonebook_is_consistent(self): <NEW_LINE> <INDENT> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> <DEDENT> @unittest.skip("poor example") <NEW_LINE> def test_is_consistent(self): <NEW_LINE> <INDENT> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> self.phonebook.add("Bob", "12345") <NEW_LINE> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> self.phonebook.add("Mary", "012345") <NEW_LINE> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> self.phonebook.add("Sue", "12345") <NEW_LINE> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> self.phonebook.add("Sue", "123") <NEW_LINE> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> <DEDENT> def test_phonebook_with_normal_entries_is_consistent(self): <NEW_LINE> <INDENT> self.phonebook.add("Bob", "12345") <NEW_LINE> self.phonebook.add("Mary", "012345") <NEW_LINE> self.assertTrue(self.phonebook.is_consistent()) <NEW_LINE> <DEDENT> def test_phonebook_with_duplicate_entries_is_inconsostent(self): <NEW_LINE> <INDENT> self.phonebook.add("Bob", "12345") <NEW_LINE> self.phonebook.add("Mary", "12345") <NEW_LINE> self.assertFalse(self.phonebook.is_consistent()) <NEW_LINE> <DEDENT> def test_phonebook_with_numbers_that_prefix_one_another_is_inconsistent(self): <NEW_LINE> <INDENT> self.phonebook.add("Bob", "12345") <NEW_LINE> self.phonebook.add("Mary", "123") <NEW_LINE> self.assertFalse(self.phonebook.is_consistent()) <NEW_LINE> <DEDENT> def test_phonebook_add_names_and_numbers(self): <NEW_LINE> <INDENT> self.phonebook.add("Sue", "12345") <NEW_LINE> self.assertIn("Sue", self.phonebook.get_names()) <NEW_LINE> self.assertIn("12345", self.phonebook.get_numbers())
|
Class that contains the test cases.
|
6259902cd164cc6175821f7d
|
class ComputeTargetInstancesAggregatedListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> pageToken = _messages.StringField(3) <NEW_LINE> project = _messages.StringField(4, required=True)
|
A ComputeTargetInstancesAggregatedListRequest object.
Fields:
filter: Sets a filter expression for filtering listed resources, in the
form filter={expression}. Your {expression} must be in the format:
FIELD_NAME COMPARISON_STRING LITERAL_STRING. The FIELD_NAME is the name
of the field you want to compare. Only atomic field types are supported
(string, number, boolean). The COMPARISON_STRING must be either eq
(equals) or ne (not equals). The LITERAL_STRING is the string value to
filter to. The literal value must be valid for the type of field
(string, number, boolean). For string fields, the literal value is
interpreted as a regular expression using RE2 syntax. The literal value
must match the entire field. For example, filter=name ne example-
instance.
maxResults: Maximum count of results to be returned.
pageToken: Specifies a page token to use. Use this parameter if you want
to list the next page of results. Set pageToken to the nextPageToken
returned by a previous list request.
project: Name of the project scoping this request.
|
6259902ca4f1c619b294f600
|
class VectorUDT(UserDefinedType): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def sqlType(cls): <NEW_LINE> <INDENT> return StructType([ StructField("type", ByteType(), False), StructField("size", IntegerType(), True), StructField("indices", ArrayType(IntegerType(), False), True), StructField("values", ArrayType(DoubleType(), False), True)]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def module(cls): <NEW_LINE> <INDENT> return "pyspark.mllib.linalg" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def scalaUDT(cls): <NEW_LINE> <INDENT> return "org.apache.spark.mllib.linalg.VectorUDT" <NEW_LINE> <DEDENT> def serialize(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, SparseVector): <NEW_LINE> <INDENT> indices = [int(i) for i in obj.indices] <NEW_LINE> values = [float(v) for v in obj.values] <NEW_LINE> return (0, obj.size, indices, values) <NEW_LINE> <DEDENT> elif isinstance(obj, DenseVector): <NEW_LINE> <INDENT> values = [float(v) for v in obj] <NEW_LINE> return (1, None, None, values) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("cannot serialize %r of type %r" % (obj, type(obj))) <NEW_LINE> <DEDENT> <DEDENT> def deserialize(self, datum): <NEW_LINE> <INDENT> assert len(datum) == 4, "VectorUDT.deserialize given row with length %d but requires 4" % len(datum) <NEW_LINE> tpe = datum[0] <NEW_LINE> if tpe == 0: <NEW_LINE> <INDENT> return SparseVector(datum[1], datum[2], datum[3]) <NEW_LINE> <DEDENT> elif tpe == 1: <NEW_LINE> <INDENT> return DenseVector(datum[3]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("do not recognize type %r" % tpe) <NEW_LINE> <DEDENT> <DEDENT> def simpleString(self): <NEW_LINE> <INDENT> return "vector"
|
SQL user-defined type (UDT) for Vector.
|
6259902cd10714528d69ee92
|
class EntryNotInDatabaseError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message
|
Entry not in the db. Obvs
|
6259902c1f5feb6acb163bfc
|
class CensorRealtime(): <NEW_LINE> <INDENT> def __init__(self, args, explicits): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.explicits = explicits <NEW_LINE> self.args = args <NEW_LINE> create_env_var('CLEANSIO_REALTIME', 'true') <NEW_LINE> <DEDENT> def censor(self): <NEW_LINE> <INDENT> system = platform.system() <NEW_LINE> if system == 'Darwin': <NEW_LINE> <INDENT> CensorRealtimeMac(self.args, self.explicits).censor() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(Fore.RED + 'Real-time does not support your OS' + Fore.RESET)
|
Filters audio stream in real-time
|
6259902c5166f23b2e2443e2
|
@provides(IWindow) <NEW_LINE> class Window(MWindow, Widget): <NEW_LINE> <INDENT> position = Property(Tuple) <NEW_LINE> size = Property(Tuple) <NEW_LINE> size_state = Enum('normal', 'maximized') <NEW_LINE> title = Unicode <NEW_LINE> opened = Event <NEW_LINE> opening = VetoableEvent <NEW_LINE> activated = Event <NEW_LINE> closed = Event <NEW_LINE> closing = VetoableEvent <NEW_LINE> deactivated = Event <NEW_LINE> _position = Tuple((-1, -1)) <NEW_LINE> _size = Tuple((-1, -1)) <NEW_LINE> def activate(self): <NEW_LINE> <INDENT> self.control.activateWindow() <NEW_LINE> self.control.raise_() <NEW_LINE> self.activated = self <NEW_LINE> <DEDENT> def _create_control(self, parent): <NEW_LINE> <INDENT> control = QtGui.QMainWindow(parent) <NEW_LINE> if self.size != (-1, -1): <NEW_LINE> <INDENT> control.resize(*self.size) <NEW_LINE> <DEDENT> if self.position != (-1, -1): <NEW_LINE> <INDENT> control.move(*self.position) <NEW_LINE> <DEDENT> if self.size_state != 'normal': <NEW_LINE> <INDENT> self._size_state_changed(self.size_state) <NEW_LINE> <DEDENT> control.setWindowTitle(self.title) <NEW_LINE> control.setEnabled(self.enabled) <NEW_LINE> control.setVisible(self.visible) <NEW_LINE> return control <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> self._remove_event_listeners() <NEW_LINE> if self.control is not None: <NEW_LINE> <INDENT> control = self.control <NEW_LINE> super(Window, self).destroy() <NEW_LINE> control.close() <NEW_LINE> <DEDENT> <DEDENT> def _get_position(self): <NEW_LINE> <INDENT> return self._position <NEW_LINE> <DEDENT> def _set_position(self, position): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self.control.move(*position) <NEW_LINE> <DEDENT> old = self._position <NEW_LINE> self._position = position <NEW_LINE> self.trait_property_changed('position', old, position) <NEW_LINE> <DEDENT> def _get_size(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def _set_size(self, size): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self.control.resize(*size) <NEW_LINE> <DEDENT> old = self._size <NEW_LINE> self._size = size <NEW_LINE> self.trait_property_changed('size', old, size) <NEW_LINE> <DEDENT> def _size_state_changed(self, state): <NEW_LINE> <INDENT> control = self.control <NEW_LINE> if control is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if state == 'maximized': <NEW_LINE> <INDENT> control.setWindowState( control.windowState() | QtCore.Qt.WindowMaximized ) <NEW_LINE> <DEDENT> elif state == 'normal': <NEW_LINE> <INDENT> control.setWindowState( control.windowState() & ~QtCore.Qt.WindowMaximized ) <NEW_LINE> <DEDENT> <DEDENT> def _title_changed(self, title): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self.control.setWindowTitle(title) <NEW_LINE> <DEDENT> <DEDENT> def __event_filter_default(self): <NEW_LINE> <INDENT> return WindowEventFilter(self)
|
The toolkit specific implementation of a Window. See the IWindow
interface for the API documentation.
|
6259902cec188e330fdf989f
|
class LoginViewSet(viewsets.ViewSet, generics.GenericAPIView): <NEW_LINE> <INDENT> serializer_class = AuthTokenSerializer <NEW_LINE> def create(self, request): <NEW_LINE> <INDENT> return ObtainAuthToken().post(request)
|
Log in using your username and password.
**returns:** Token.
|
6259902c711fe17d825e14a0
|
class SshClient(object): <NEW_LINE> <INDENT> def __init__(self, executable='ssh', socket=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.executable = find_executable(executable) <NEW_LINE> executables = ['ssh', 'dbclient'] <NEW_LINE> while self.executable is None: <NEW_LINE> <INDENT> self.executable = find_executable(executables.pop(0)) <NEW_LINE> <DEDENT> if self.executable is None: <NEW_LINE> <INDENT> raise ValueError('Could not find your SSH client.') <NEW_LINE> <DEDENT> self.__version = None <NEW_LINE> self.__project = None <NEW_LINE> self.client_data() <NEW_LINE> self.socket = socket <NEW_LINE> <DEDENT> SSH_PROJECTS = { 'OpenSSH': ['6.7', '6.8', '6.9', '7.'], 'Dropbear': None, } <NEW_LINE> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> return self.__version <NEW_LINE> <DEDENT> @property <NEW_LINE> def project(self): <NEW_LINE> <INDENT> return self.__project <NEW_LINE> <DEDENT> def client_data(self): <NEW_LINE> <INDENT> version_data = subprocess.getoutput(' '.join([self.executable, '-V'])) <NEW_LINE> if version_data.startswith('OpenSSH'): <NEW_LINE> <INDENT> self.__project = 'OpenSSH' <NEW_LINE> self.__version = version_data.split()[0].split('_')[1] <NEW_LINE> <DEDENT> elif version_data.startswith('Dropbear'): <NEW_LINE> <INDENT> self.__project = 'Dropbear' <NEW_LINE> self.__version = version_data.split()[1] <NEW_LINE> <DEDENT> return (self.executable, self.__project, self.__version) <NEW_LINE> <DEDENT> def is_valid(self): <NEW_LINE> <INDENT> if self.SSH_PROJECTS.get(self.project) is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for version in self.SSH_PROJECTS[self.project]: <NEW_LINE> <INDENT> if self.version.startswith(version): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def run(self, arguments): <NEW_LINE> <INDENT> os.execv( self.executable, [ os.path.basename(self.executable), '-R', ':'.join((self.socket, self.socket)), '-t', ] + arguments + [ 'SSHED_SOCK=%s ' % self.socket, os.environ.get('SHELL', 'bash'), ])
|
An SSH client.
|
6259902cd53ae8145f919470
|
class EpisodicLearnerMixin(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def value_function(self): <NEW_LINE> <INDENT> if hasattr(self, 'vfunction'): <NEW_LINE> <INDENT> return self.vfunction <NEW_LINE> <DEDENT> if hasattr(self, 'qfunction'): <NEW_LINE> <INDENT> return self.qfunction <NEW_LINE> <DEDENT> <DEDENT> def train(self, n_episodes, callbacks=None): <NEW_LINE> <INDENT> callbacks = CallbackList(callbacks) <NEW_LINE> callbacks.on_train_begin() <NEW_LINE> for episode in range(n_episodes): <NEW_LINE> <INDENT> callbacks.on_episode_begin(episode, self.value_function) <NEW_LINE> self.env.reset() <NEW_LINE> self.episode() <NEW_LINE> callbacks.on_episode_end(episode, self.value_function) <NEW_LINE> <DEDENT> callbacks.on_train_end(self.value_function)
|
Mixin for learning value functions by interacting with an
environment in an episodic setting.
|
6259902c6e29344779b0165c
|
class ResponseContinuation(Response): <NEW_LINE> <INDENT> def __init__(self, text: MaybeBytes) -> None: <NEW_LINE> <INDENT> super().__init__(b'+', text)
|
Class used for server responses that indicate a continuation
requirement. This is when the server needs more data from the client to
finish handling the command. The ``AUTHENTICATE`` command and any command
that uses a literal string argument will send this response as needed.
Args:
text: The continuation text.
|
6259902c66673b3332c313fd
|
class GalsimMoffatFitter(GalsimFitter): <NEW_LINE> <INDENT> def __init__(self, prior=None, fit_pars=None): <NEW_LINE> <INDENT> super().__init__(model="moffat", prior=prior, fit_pars=fit_pars) <NEW_LINE> <DEDENT> def _make_fit_model(self, obs, guess): <NEW_LINE> <INDENT> return GalsimMoffatFitModel( obs=obs, guess=guess, prior=self.prior, )
|
Fit a moffat model using galsim
Parameters
----------
model: string
e.g. 'exp', 'spergel'
prior: ngmix prior, optional
For example ngmix.priors.PriorSimpleSep can
be used as a separable prior on center, g, size, flux.
fit_pars: dict, optional
parameters for the lm fitter, e.g. maxfev, ftol, xtol
|
6259902c30c21e258be99818
|
class CauseEOFError(CauseExceptionMixin, Question): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.exception = EOFError <NEW_LINE> <DEDENT> def get_correct_answers(self): <NEW_LINE> <INDENT> return [( 'import StringIO\n' 'import sys\n' 'sys.stdin = StringIO.StringIO("")\n' 'input()\n' )]
|
Cause an EOFError.
https://docs.python.org/3.6/library/exceptions.html#EOFError
|
6259902ce76e3b2f99fd9a1a
|
class HealthStateCount(Model): <NEW_LINE> <INDENT> _validation = { 'ok_count': {'minimum': 0}, 'warning_count': {'minimum': 0}, 'error_count': {'minimum': 0}, } <NEW_LINE> _attribute_map = { 'ok_count': {'key': 'OkCount', 'type': 'long'}, 'warning_count': {'key': 'WarningCount', 'type': 'long'}, 'error_count': {'key': 'ErrorCount', 'type': 'long'}, } <NEW_LINE> def __init__(self, ok_count=None, warning_count=None, error_count=None): <NEW_LINE> <INDENT> self.ok_count = ok_count <NEW_LINE> self.warning_count = warning_count <NEW_LINE> self.error_count = error_count
|
Represents information about how many health entities are in Ok, Warning
and Error health state.
.
:param ok_count: The number of health entities with aggregated health
state Ok.
:type ok_count: long
:param warning_count: The number of health entities with aggregated health
state Warning.
:type warning_count: long
:param error_count: The number of health entities with aggregated health
state Error.
:type error_count: long
|
6259902c287bf620b6272bf5
|
class User_blog(db.Model): <NEW_LINE> <INDENT> __tablename__ = "user_blogs" <NEW_LINE> user_blog_id = db.Column(db.Integer, autoincrement=True, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'), nullable=False) <NEW_LINE> blog_id = db.Column(db.Integer, db.ForeignKey('blogs.blog_id'), nullable=False) <NEW_LINE> user = db.relationship("User", backref='user_blogs') <NEW_LINE> blog = db.relationship("Blog", backref='user_blogs') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<Blog_user User: {} Blog: {}>".format(self.user.name, self.blog.title)
|
Association table between users and blogs.
|
6259902c5166f23b2e2443e4
|
class InterfaceSymbol(ClassInterfaceSymbol): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super(InterfaceSymbol, self).__init__(name) <NEW_LINE> self._sub_interfaces = None <NEW_LINE> self._super_interface = '' <NEW_LINE> <DEDENT> def _get_super_interface(self): <NEW_LINE> <INDENT> return self._super_interface <NEW_LINE> <DEDENT> def _set_super_interface(self, super_interface): <NEW_LINE> <INDENT> self._super_interface = super_interface <NEW_LINE> <DEDENT> super_interface = property(_get_super_interface, _set_super_interface)
|
Represents interfaces.
|
6259902cd53ae8145f919472
|
@admin.register(models.CandidateContest) <NEW_LINE> class CandidateContestAdmin(base.ModelAdmin): <NEW_LINE> <INDENT> readonly_fields = ("id", "created_at", "updated_at") <NEW_LINE> raw_id_fields = ("division", "runoff_for_contest") <NEW_LINE> fields = ( ("name", "election", "party", "previous_term_unexpired", "number_elected") + raw_id_fields + readonly_fields ) <NEW_LINE> list_display = ("name", "election", "division_name", "id", "updated_at") <NEW_LINE> search_fields = ("name", "election__name") <NEW_LINE> list_filter = ("updated_at",) <NEW_LINE> date_hierarchy = "election__date" <NEW_LINE> inlines = [ CandidateContestPostInline, CandidateContestIdentifierInline, CandidateContestSourceInline, ] <NEW_LINE> def division_name(self, obj): <NEW_LINE> <INDENT> return obj.division.name
|
Custom administrative panel for the CandidateContest model.
|
6259902c73bcbd0ca4bcb2a0
|
class Parser(object): <NEW_LINE> <INDENT> def __init__(self, file_path): <NEW_LINE> <INDENT> self.file_path = file_path <NEW_LINE> <DEDENT> def _read_lines(self): <NEW_LINE> <INDENT> with open(self.file_path, 'rb') as json_file: <NEW_LINE> <INDENT> for line in json_file: <NEW_LINE> <INDENT> yield line <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_entries(self, num=10, unlimited=False, func=lambda x: x): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> for line in self._read_lines(): <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> yield func(json.loads(line)) <NEW_LINE> if unlimited is False and counter >= num: <NEW_LINE> <INDENT> break
|
Iterative Parser
Args:
file_path
Usage:
Users should call get_entries(num) where num
is the number of lines one needs.
|
6259902c66673b3332c313ff
|
class AddInstanceResult(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.FailedInstanceIds = None <NEW_LINE> self.SuccInstanceIds = None <NEW_LINE> self.TimeoutInstanceIds = None <NEW_LINE> self.FailedReasons = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.FailedInstanceIds = params.get("FailedInstanceIds") <NEW_LINE> self.SuccInstanceIds = params.get("SuccInstanceIds") <NEW_LINE> self.TimeoutInstanceIds = params.get("TimeoutInstanceIds") <NEW_LINE> self.FailedReasons = params.get("FailedReasons") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
|
添加实例到集群的结果
|
6259902c8a349b6b43687249
|
class ProjectScreenshot(models.Model): <NEW_LINE> <INDENT> project = models.ForeignKey( Project, related_name='screenshots', on_delete=models.CASCADE) <NEW_LINE> screenshot = models.ImageField( help_text=_('A project screenshot.'), upload_to=os.path.join(MEDIA_ROOT, 'images/projects/screenshots'), blank=True )
|
A model to store a screenshot linked to a project.
|
6259902c30c21e258be9981a
|
class ContentType(str, Enum): <NEW_LINE> <INDENT> APPLICATION_SRGS = 'application/srgs' <NEW_LINE> APPLICATION_SRGS_XML = 'application/srgs+xml'
|
The format (MIME type) of the grammar file:
* `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a
plain-text representation that is similar to traditional BNF grammars.
* `application/srgs+xml` for XML Form, which uses XML elements to represent the
grammar.
|
6259902c30c21e258be9981b
|
class TrackPipeline(object): <NEW_LINE> <INDENT> def process_item(self, item, spider): <NEW_LINE> <INDENT> track_item = item <NEW_LINE> user_url = track_item['sc_user_url'] <NEW_LINE> try: <NEW_LINE> <INDENT> db_artist = db.get_single('artist_page', user_url, 'url')['artist'] <NEW_LINE> new_artist_sample = { 'url': track_item['sc_track_url'], 'resource_id': track_item['sc_track_id'], 'name': track_item['sc_name'], 'genre_string': track_item['sc_genre'], 'artist_id': db_artist['id'], 'third_party_id': sc['id']} <NEW_LINE> log.msg('Inserting:') <NEW_LINE> log.msg(str(new_artist_sample)) <NEW_LINE> log.msg('--') <NEW_LINE> db.insert_dict('artist_sample', new_artist_sample) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return item
|
track['sc_user_url']
track['sc_name']
track['sc_track_id']
track['sc_num_plays']
track['sc_description']
track['sc_genre']
track['sc_embeddable_by']
track['sc_streamable']
track['sc_license']
track['sc_lable_name']
|
6259902c8e05c05ec3f6f663
|
class PrincipalCalendarsExportResource(SimpleResource): <NEW_LINE> <INDENT> addSlash = False <NEW_LINE> def __init__(self, record, store, principalCollections): <NEW_LINE> <INDENT> super(PrincipalCalendarsExportResource, self).__init__(principalCollections, isdir=False) <NEW_LINE> self._record = record <NEW_LINE> self._store = store <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def calendarComponents(self): <NEW_LINE> <INDENT> uid = self._record.uid <NEW_LINE> calendarComponents = [] <NEW_LINE> txn = self._store.newTransaction() <NEW_LINE> try: <NEW_LINE> <INDENT> calendarHome = yield txn.calendarHomeWithUID(uid) <NEW_LINE> if calendarHome is None: <NEW_LINE> <INDENT> raise RuntimeError("No calendar home for UID: {}".format(uid)) <NEW_LINE> <DEDENT> for calendar in (yield calendarHome.calendars()): <NEW_LINE> <INDENT> name = calendar.displayName() <NEW_LINE> for calendarObject in (yield calendar.calendarObjects()): <NEW_LINE> <INDENT> perUser = yield calendarObject.filteredComponent(uid, True) <NEW_LINE> calendarComponents.add((name, perUser)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> txn.abort() <NEW_LINE> <DEDENT> returnValue(calendarComponents) <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def iCalendarZipArchiveData(self): <NEW_LINE> <INDENT> calendarComponents = yield self.calendarComponents() <NEW_LINE> fileHandle = StringIO() <NEW_LINE> try: <NEW_LINE> <INDENT> zipFile = ZipFile(fileHandle, "w", allowZip64=True) <NEW_LINE> try: <NEW_LINE> <INDENT> zipFile.comment = ( "Calendars for UID: {}".format(self._record.uid) ) <NEW_LINE> names = set() <NEW_LINE> for name, component in calendarComponents: <NEW_LINE> <INDENT> if name in names: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> nextName = "{} {:d}".format(name, i) <NEW_LINE> if nextName not in names: <NEW_LINE> <INDENT> name = nextName <NEW_LINE> break <NEW_LINE> <DEDENT> assert i < len(calendarComponents) <NEW_LINE> <DEDENT> <DEDENT> text = component.getText().encode("utf-8") <NEW_LINE> zipFile.writestr(name.encode("utf-8"), text) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> zipFile.close() <NEW_LINE> <DEDENT> data = fileHandle.getvalue() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> fileHandle.close() <NEW_LINE> <DEDENT> returnValue(data) <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def render(self, request): <NEW_LINE> <INDENT> response = Response() <NEW_LINE> response.stream = MemoryStream((yield self.iCalendarZipArchiveData())) <NEW_LINE> response.headers.setHeader( b"content-type", MimeType.fromString(b"application/zip") ) <NEW_LINE> returnValue(response)
|
Resource that vends a principal's calendars as iCalendar text.
|
6259902c91af0d3eaad3ae39
|
class TopicRemodeler(_BaseRemodeler): <NEW_LINE> <INDENT> TYPE = 'TOPIC' <NEW_LINE> @property <NEW_LINE> def _haros_model_instances(self): <NEW_LINE> <INDENT> return self._haros_configuration.topics <NEW_LINE> <DEDENT> @property <NEW_LINE> def _chris_model_banks(self): <NEW_LINE> <INDENT> return {BankType.TOPIC: self._chris_ros_model[BankType.TOPIC]} <NEW_LINE> <DEDENT> def _merge_haros_topic_links_with_chris_topic_nodes(self, haros_topic_model, chris_topic_model): <NEW_LINE> <INDENT> model_updated = False <NEW_LINE> for link in haros_topic_model.publishers: <NEW_LINE> <INDENT> haros_node_instance_name = link.node.id <NEW_LINE> if self._check_haros_name_is_complete(haros_node_instance_name, 'Check for Topic Nodes'): <NEW_LINE> <INDENT> if haros_node_instance_name not in chris_topic_model.publisher_node_names: <NEW_LINE> <INDENT> Logger.get_logger().log(LoggerLevel.INFO, '[{}] Adding HAROS Topic\'s Publisher Node "{}" to CHRIS Topic Instance.'.format( self.__class__.TYPE, haros_node_instance_name)) <NEW_LINE> chris_topic_model.publisher_node_names.add( haros_node_instance_name) <NEW_LINE> model_updated = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for link in haros_topic_model.subscribers: <NEW_LINE> <INDENT> haros_node_instance_name = link.node.id <NEW_LINE> if self._check_haros_name_is_complete(haros_node_instance_name, 'Check for Topic Nodes'): <NEW_LINE> <INDENT> if haros_node_instance_name not in chris_topic_model.subscriber_node_names: <NEW_LINE> <INDENT> Logger.get_logger().log(LoggerLevel.INFO, '[{}] Adding HAROS Topic\'s Subscriber Node "{}" to CHRIS Topic Instance.'.format( self.__class__.TYPE, haros_node_instance_name)) <NEW_LINE> chris_topic_model.subscriber_node_names.add( haros_node_instance_name) <NEW_LINE> model_updated = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return model_updated <NEW_LINE> <DEDENT> def _helper_merge_haros_model_with_chris_model(self, bank_type, haros_model, chris_model): <NEW_LINE> <INDENT> model_updated = False <NEW_LINE> haros_topic_type = haros_model.type <NEW_LINE> chris_topic_type = chris_model.construct_type <NEW_LINE> if haros_topic_type != chris_topic_type: <NEW_LINE> <INDENT> Logger.get_logger().log(LoggerLevel.ERROR, '[{}] HAROS Topic\'s Type "{}" does NOT Match CHRIS Topic\'s Type "{}".'.format( self.__class__.TYPE, haros_topic_type, chris_topic_type)) <NEW_LINE> <DEDENT> model_updated |= self._merge_haros_topic_links_with_chris_topic_nodes( haros_model, chris_model) <NEW_LINE> return model_updated <NEW_LINE> <DEDENT> def _helper_populate_new_chris_model(self, bank_type, instance_name, haros_model, new_chris_model_instance): <NEW_LINE> <INDENT> new_chris_model_instance.construct_type = haros_model.type <NEW_LINE> self._merge_haros_topic_links_with_chris_topic_nodes( haros_model, new_chris_model_instance)
|
The `TopicRemodeler` is a `_BaseRemodeler` that provides the
specific logic necessary to load the CHRIS and HAROS Topic Specification
models, determine which HAROS models are present in the CHRIS models and
merge them (if applicable), determine which HAROS models are not present
in the CHRIS models and create them (if applicable)
|
6259902cd164cc6175821f81
|
class Weapon(Stone): <NEW_LINE> <INDENT> def __init__(self, element, comp, wep_type): <NEW_LINE> <INDENT> Stone.__init__(self, comp) <NEW_LINE> self.type = wep_type <NEW_LINE> self.element = element <NEW_LINE> <DEDENT> def map_to_grid(self, origin, grid_size): <NEW_LINE> <INDENT> orix,oriy = origin <NEW_LINE> tiles = [] <NEW_LINE> if self.type != 'Wand': <NEW_LINE> <INDENT> if self.type == 'Bow': <NEW_LINE> <INDENT> no_hit = 4 <NEW_LINE> min = -(2 * no_hit) <NEW_LINE> max = -min + 1 <NEW_LINE> dist = range(min,max) <NEW_LINE> attack_pattern = [] <NEW_LINE> [[attack_pattern.append((x,y)) for y in dist if (no_hit < (abs(x) + abs(y)) < max) ] for x in dist] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attack_pattern = [(0,-1),(1,0),(0,1),(-1,0),(-1,-1),(-1,1),(1,1),(1,-1)] <NEW_LINE> <DEDENT> for i in attack_pattern: <NEW_LINE> <INDENT> x,y = (i[0] + origin[0]),(i[1] + origin[1]) <NEW_LINE> if 0 <= x < grid_size[0]: <NEW_LINE> <INDENT> if 0 <= y < grid_size[1]: <NEW_LINE> <INDENT> tiles.append((x,y)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return tiles <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def make_pattern(self, origin, distance, pointing): <NEW_LINE> <INDENT> src = origin <NEW_LINE> sid = 2 * distance <NEW_LINE> pattern = [] <NEW_LINE> tiles = [] <NEW_LINE> for i in xrange(sid): <NEW_LINE> <INDENT> if i % 2: <NEW_LINE> <INDENT> in_range = xrange(-(i/2),((i/2)+1)) <NEW_LINE> for j in xrange(len(in_range)): <NEW_LINE> <INDENT> if pointing == 'North': <NEW_LINE> <INDENT> pattern.append((src[0] + in_range[j], (src[1] - (1 +(i/2))))) <NEW_LINE> <DEDENT> elif pointing =='South': <NEW_LINE> <INDENT> pattern.append((src[0] + in_range[j], (src[1] + (1 +(i/2))))) <NEW_LINE> <DEDENT> elif pointing =='East': <NEW_LINE> <INDENT> pattern.append((src[0] + (1 +(i/2)), (src[1] - in_range[j]))) <NEW_LINE> <DEDENT> elif pointing =='West': <NEW_LINE> <INDENT> pattern.append((src[0] - (1 +(i/2)), (src[1] - in_range[j]))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return pattern <NEW_LINE> <DEDENT> direction = {0:'West', 1:'North', 2:'East', 3:'South'} <NEW_LINE> maxes = (origin[0], origin[1], (grid_size[0] - 1 - origin[0]), (grid_size[1] - 1 - origin[1]),) <NEW_LINE> tiles = [] <NEW_LINE> for i in direction: <NEW_LINE> <INDENT> for j in self.make_pattern(origin, maxes[i], direction[i]): <NEW_LINE> <INDENT> if 0 <= j[0] < grid_size[0]: <NEW_LINE> <INDENT> if 0 <= j[1] < grid_size[1]: <NEW_LINE> <INDENT> tiles.append(j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return tiles
|
Scients Equip weapons to do damage
|
6259902ca4f1c619b294f605
|
class SVNSync(NewBase): <NEW_LINE> <INDENT> short_desc = "Perform sync operations on SVN repositories" <NEW_LINE> @staticmethod <NEW_LINE> def name(): <NEW_LINE> <INDENT> return "SVNSync" <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> NewBase.__init__(self, "svn", "dev-vcs/subversion") <NEW_LINE> <DEDENT> def exists(self, **kwargs): <NEW_LINE> <INDENT> return os.path.exists(os.path.join(self.repo.location, ".svn")) <NEW_LINE> <DEDENT> def new(self, **kwargs): <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> self._kwargs(kwargs) <NEW_LINE> <DEDENT> svn_root = self.repo.sync_uri <NEW_LINE> exitcode = portage.process.spawn_bash( "cd %s; exec svn co %s ." % ( portage._shell_quote(self.repo.location), portage._shell_quote(svn_root), ), **self.spawn_kwargs ) <NEW_LINE> if exitcode != os.EX_OK: <NEW_LINE> <INDENT> msg = "!!! svn checkout error; exiting." <NEW_LINE> self.logger(self.xterm_titles, msg) <NEW_LINE> writemsg_level(msg + "\n", noiselevel=-1, level=logging.ERROR) <NEW_LINE> <DEDENT> return (exitcode, False) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> exitcode = self._svn_upgrade() <NEW_LINE> if exitcode != os.EX_OK: <NEW_LINE> <INDENT> return (exitcode, False) <NEW_LINE> <DEDENT> exitcode = portage.process.spawn_bash( "cd %s; exec svn update" % (portage._shell_quote(self.repo.location),), **self.spawn_kwargs ) <NEW_LINE> if exitcode != os.EX_OK: <NEW_LINE> <INDENT> msg = "!!! svn update error; exiting." <NEW_LINE> self.logger(self.xterm_titles, msg) <NEW_LINE> writemsg_level(msg + "\n", noiselevel=-1, level=logging.ERROR) <NEW_LINE> <DEDENT> return (exitcode, False) <NEW_LINE> <DEDENT> def _svn_upgrade(self): <NEW_LINE> <INDENT> exitcode = portage.process.spawn_bash( "cd %s; exec svn upgrade" % (portage._shell_quote(self.repo.location),), **self.spawn_kwargs ) <NEW_LINE> if exitcode != os.EX_OK: <NEW_LINE> <INDENT> msg = "!!! svn upgrade error; exiting." <NEW_LINE> self.logger(self.xterm_titles, msg) <NEW_LINE> writemsg_level(msg + "\n", noiselevel=-1, level=logging.ERROR) <NEW_LINE> <DEDENT> return exitcode
|
SVN sync module
|
6259902c63f4b57ef008657a
|
class FaultWrapper(wsgi.Middleware): <NEW_LINE> <INDENT> error_map = { 'AttributeError': webob.exc.HTTPBadRequest, 'ValueError': webob.exc.HTTPBadRequest, 'StackNotFound': webob.exc.HTTPNotFound, 'ResourceNotFound': webob.exc.HTTPNotFound, 'ResourceTypeNotFound': webob.exc.HTTPNotFound, 'ResourceNotAvailable': webob.exc.HTTPNotFound, 'PhysicalResourceNotFound': webob.exc.HTTPNotFound, 'InvalidTenant': webob.exc.HTTPForbidden, 'StackExists': webob.exc.HTTPConflict, 'StackValidationFailed': webob.exc.HTTPBadRequest, 'InvalidTemplateReference': webob.exc.HTTPBadRequest, 'UnknownUserParameter': webob.exc.HTTPBadRequest, 'RevertFailed': webob.exc.HTTPInternalServerError, 'ServerBuildFailed': webob.exc.HTTPInternalServerError, 'NotSupported': webob.exc.HTTPBadRequest, 'MissingCredentialError': webob.exc.HTTPBadRequest, 'UserParameterMissing': webob.exc.HTTPBadRequest, 'RequestLimitExceeded': webob.exc.HTTPBadRequest, 'InvalidTemplateParameter': webob.exc.HTTPBadRequest, } <NEW_LINE> def _error(self, ex): <NEW_LINE> <INDENT> trace = None <NEW_LINE> webob_exc = None <NEW_LINE> if isinstance(ex, exception.HTTPExceptionDisguise): <NEW_LINE> <INDENT> if cfg.CONF.debug: <NEW_LINE> <INDENT> trace = ''.join(traceback.format_tb(ex.tb)) <NEW_LINE> <DEDENT> ex = ex.exc <NEW_LINE> webob_exc = ex <NEW_LINE> <DEDENT> ex_type = ex.__class__.__name__ <NEW_LINE> if ex_type.endswith(rpc_common._REMOTE_POSTFIX): <NEW_LINE> <INDENT> ex_type = ex_type[:-len(rpc_common._REMOTE_POSTFIX)] <NEW_LINE> <DEDENT> message = unicode(ex.message) <NEW_LINE> if cfg.CONF.debug and not trace: <NEW_LINE> <INDENT> trace = unicode(ex) <NEW_LINE> if trace.find('\n') > -1: <NEW_LINE> <INDENT> unused, trace = trace.split('\n', 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trace = traceback.format_exc() <NEW_LINE> <DEDENT> <DEDENT> if not webob_exc: <NEW_LINE> <INDENT> webob_exc = self.error_map.get(ex_type, webob.exc.HTTPInternalServerError) <NEW_LINE> <DEDENT> error = { 'code': webob_exc.code, 'title': webob_exc.title, 'explanation': webob_exc.explanation, 'error': { 'message': message, 'type': ex_type, 'traceback': trace, } } <NEW_LINE> return error <NEW_LINE> <DEDENT> def process_request(self, req): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return req.get_response(self.application) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> return req.get_response(Fault(self._error(exc)))
|
Replace error body with something the client can parse.
|
6259902c8c3a8732951f7568
|
class DevConfig(Config): <NEW_LINE> <INDENT> DEBUG = True
|
Development configuration child class
Args:
Config: The parent configuration class with General
configuration settings
|
6259902c5166f23b2e2443e6
|
class AsyncCompletedEventHandler(MulticastDelegate,ICloneable,ISerializable): <NEW_LINE> <INDENT> def BeginInvoke(self,sender,e,callback,object): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CombineImpl(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def DynamicInvokeImpl(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def EndInvoke(self,result): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def GetMethodImpl(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Invoke(self,sender,e): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def RemoveImpl(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(self,object,method): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass
|
Represents the method that will handle the MethodNameCompleted event of an asynchronous operation.
AsyncCompletedEventHandler(object: object,method: IntPtr)
|
6259902cec188e330fdf98a3
|
class V1ResourceQuotaStatus(object): <NEW_LINE> <INDENT> openapi_types = { 'hard': 'dict(str, str)', 'used': 'dict(str, str)' } <NEW_LINE> attribute_map = { 'hard': 'hard', 'used': 'used' } <NEW_LINE> def __init__(self, hard=None, used=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._hard = None <NEW_LINE> self._used = None <NEW_LINE> self.discriminator = None <NEW_LINE> if hard is not None: <NEW_LINE> <INDENT> self.hard = hard <NEW_LINE> <DEDENT> if used is not None: <NEW_LINE> <INDENT> self.used = used <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def hard(self): <NEW_LINE> <INDENT> return self._hard <NEW_LINE> <DEDENT> @hard.setter <NEW_LINE> def hard(self, hard): <NEW_LINE> <INDENT> self._hard = hard <NEW_LINE> <DEDENT> @property <NEW_LINE> def used(self): <NEW_LINE> <INDENT> return self._used <NEW_LINE> <DEDENT> @used.setter <NEW_LINE> def used(self, used): <NEW_LINE> <INDENT> self._used = used <NEW_LINE> <DEDENT> def to_dict(self, serialize=False): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def convert(x): <NEW_LINE> <INDENT> if hasattr(x, "to_dict"): <NEW_LINE> <INDENT> args = getfullargspec(x.to_dict).args <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> return x.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.to_dict(serialize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> attr = self.attribute_map.get(attr, attr) if serialize else attr <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: convert(x), value )) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], convert(item[1])), value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = convert(value) <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1ResourceQuotaStatus): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1ResourceQuotaStatus): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
|
NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
|
6259902cd99f1b3c44d066b3
|
class IConfirmationDialog(IDialog): <NEW_LINE> <INDENT> cancel = Bool(False) <NEW_LINE> default = Enum(NO, YES, CANCEL) <NEW_LINE> image = Image() <NEW_LINE> message = Str() <NEW_LINE> informative = Str() <NEW_LINE> detail = Str() <NEW_LINE> no_label = Str() <NEW_LINE> yes_label = Str()
|
The interface for a dialog that prompts the user for confirmation.
|
6259902c6e29344779b01660
|
class ServiceNotFound(BalenaException): <NEW_LINE> <INDENT> def __init__(self, service_id): <NEW_LINE> <INDENT> super(ServiceNotFound, self).__init__() <NEW_LINE> self.message = Message.SERVICE_NOT_FOUND.format(id=service_id)
|
Args:
service_id (str): service id.
Attributes:
message (str): error message.
|
6259902ca8ecb0332587222e
|
class Humanoid(object): <NEW_LINE> <INDENT> def __init__(self, position, health, stamina): <NEW_LINE> <INDENT> self.position = position <NEW_LINE> self.health = health <NEW_LINE> self.stamina = stamina <NEW_LINE> self.wolf_position = None <NEW_LINE> self.food_position = None <NEW_LINE> <DEDENT> def get_wolf_proximity(self): <NEW_LINE> <INDENT> if self.wolf_position is None: <NEW_LINE> <INDENT> return DistanceObservation.UNKNOWN <NEW_LINE> <DEDENT> d = dist(self.wolf_position, self.position) <NEW_LINE> proximity = DistanceObservation.proximity_level(d) <NEW_LINE> logging.info( "Wolf Distance: {} - Proximity: {}".format(d, DistanceObservation.as_string(proximity)) ) <NEW_LINE> return proximity <NEW_LINE> <DEDENT> def get_health(self): <NEW_LINE> <INDENT> return HealthObservation.health_level(self.health) <NEW_LINE> <DEDENT> def get_hunger_level(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_dict(data): <NEW_LINE> <INDENT> x, y, z = data["position"] <NEW_LINE> humanoid = Humanoid((x, y, z), data["health"], data["stamina"]) <NEW_LINE> humanoid.wolf_position = tuple(data["lastWolfPosition"]) if data["lastWolfPosition"] else None <NEW_LINE> humanoid.food_position = tuple(data["lastFoodPosition"]) if data["lastFoodPosition"] else None <NEW_LINE> return humanoid <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(json_string): <NEW_LINE> <INDENT> data = loads(json_string) <NEW_LINE> if type(data) == dict: <NEW_LINE> <INDENT> return Humanoid.from_dict(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Error, unrecognised json parse type")
|
Humanoid is a python class that wraps around json data
that describes the current state of the agent in the QCOG test bed environment.
An example of the json data used to create this class.
{
"lastWolfPosition": [29.02450942993164,0.0,27.91568946838379],
"lastFoodPosition":[0.0,0.0,0.0],
"position":[29.140689849853516,0.0,26.8988094329834],
"entityId":0,
"stamina":100.0,
"health":7.0
}
|
6259902c73bcbd0ca4bcb2a2
|
class ZonesService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'zones' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(ComputeAlpha.ZonesService, self).__init__(client) <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def Get(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Get') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> Get.method_config = lambda: base_api.ApiMethodInfo( http_method=u'GET', method_id=u'compute.zones.get', ordered_params=[u'project', u'zone'], path_params=[u'project', u'zone'], query_params=[], relative_path=u'projects/{project}/zones/{zone}', request_field='', request_type_name=u'ComputeZonesGetRequest', response_type_name=u'Zone', supports_download=False, ) <NEW_LINE> def List(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('List') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> List.method_config = lambda: base_api.ApiMethodInfo( http_method=u'GET', method_id=u'compute.zones.list', ordered_params=[u'project'], path_params=[u'project'], query_params=[u'filter', u'maxResults', u'orderBy', u'pageToken'], relative_path=u'projects/{project}/zones', request_field='', request_type_name=u'ComputeZonesListRequest', response_type_name=u'ZoneList', supports_download=False, )
|
Service class for the zones resource.
|
6259902c6fece00bbaccc9bf
|
class Tuio2dCurMotionEvent(TuioMotionEvent): <NEW_LINE> <INDENT> def __init__(self, device, id, args): <NEW_LINE> <INDENT> super(Tuio2dCurMotionEvent, self).__init__(device, id, args) <NEW_LINE> <DEDENT> def depack(self, args): <NEW_LINE> <INDENT> if len(args) < 5: <NEW_LINE> <INDENT> self.sx, self.sy = map(float, args[0:2]) <NEW_LINE> self.profile = ('pos', ) <NEW_LINE> <DEDENT> elif len(args) == 5: <NEW_LINE> <INDENT> self.sx, self.sy, self.X, self.Y, self.m = map(float, args[0:5]) <NEW_LINE> self.Y = -self.Y <NEW_LINE> self.profile = ('pos', 'mov', 'motacc') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sx, self.sy, self.X, self.Y = map(float, args[0:4]) <NEW_LINE> self.m, width, height = map(float, args[4:7]) <NEW_LINE> self.Y = -self.Y <NEW_LINE> self.profile = ('pos', 'mov', 'motacc', 'shape') <NEW_LINE> if self.shape is None: <NEW_LINE> <INDENT> self.shape = ShapeRect() <NEW_LINE> <DEDENT> self.shape.width = width <NEW_LINE> self.shape.height = height <NEW_LINE> <DEDENT> self.sy = 1 - self.sy <NEW_LINE> super(Tuio2dCurMotionEvent, self).depack(args)
|
A 2dCur TUIO touch.
|
6259902cbe8e80087fbc008b
|
@op <NEW_LINE> class Dummy(Node): <NEW_LINE> <INDENT> ins = [] <NEW_LINE> flags = ["cfopcode", "start_block", "constlike", "dump_noblock"] <NEW_LINE> pinned = "yes"
|
A placeholder value. This is used when constructing cyclic graphs where
you have cases where not all predecessors of a phi-node are known. Dummy
nodes are used for the unknown predecessors and replaced later.
|
6259902c1d351010ab8f4b28
|
class SentEdgesToNodesAggregator(_EdgesToNodesAggregator): <NEW_LINE> <INDENT> def __init__(self, reducer, name="sent_edges_to_nodes_aggregator"): <NEW_LINE> <INDENT> super(SentEdgesToNodesAggregator, self).__init__( use_sent_edges=True, reducer=reducer, name=name)
|
Agregates sent edges into the corresponding sender nodes.
|
6259902c8c3a8732951f7569
|
class HDFreadRandom(HDFread): <NEW_LINE> <INDENT> Block.alias('hdfread_random') <NEW_LINE> Block.output_is_defined_at_runtime() <NEW_LINE> Block.config('file', 'HDF file to write') <NEW_LINE> Block.config('signals', 'Which signals to output (and in what order). ' 'Should be a comma-separated list. ' 'If you do not specify it will be all signal in the original order', default=None) <NEW_LINE> def init(self): <NEW_LINE> <INDENT> HDFread.init(self) <NEW_LINE> lengths = [len(table) for table in self.signal2table.values()] <NEW_LINE> if not len(numpy.unique(lengths)) == 1: <NEW_LINE> <INDENT> raise Exception('I want a log whose lengths are the same, not %r.' % lengths) <NEW_LINE> <DEDENT> self.sequence = numpy.random.permutation(lengths[0]) <NEW_LINE> self.sequence_index = 0 <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> index = self.sequence[self.sequence_index] <NEW_LINE> self.info('Index: %d corresponds to %d.' % (self.sequence_index, index)) <NEW_LINE> for signal, table in self.signal2table.items(): <NEW_LINE> <INDENT> value = table[index]['value'] <NEW_LINE> self.set_output(signal, value, self.sequence_index) <NEW_LINE> <DEDENT> self.sequence_index += 1 <NEW_LINE> <DEDENT> def next_data_status(self): <NEW_LINE> <INDENT> if self.sequence_index >= len(self.sequence): <NEW_LINE> <INDENT> return (False, None) <NEW_LINE> <DEDENT> ts = self.sequence_index <NEW_LINE> return (True, ts)
|
This block reads the long in a random fashion.
|
6259902c30c21e258be9981d
|
class MockTheory(ScatteringTheory): <NEW_LINE> <INDENT> def __init__(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _can_handle(self, scatterer): <NEW_LINE> <INDENT> return isinstance(scatterer, Sphere) <NEW_LINE> <DEDENT> def _raw_fields(self, positions, *args, **kwargs): <NEW_LINE> <INDENT> return np.ones(positions.shape, dtype='complex128')
|
Minimally-functional daughter of ScatteringTheory for fast tests.
|
6259902c287bf620b6272bf9
|
class ShowIpOspfDatabaseSummaryDetail(ShowIpOspfDatabaseSummaryDetailSchema, ShowIpOspfDatabaseDetailParser): <NEW_LINE> <INDENT> cli_command = ['show ip ospf database summary detail vrf {vrf}', 'show ip ospf database summary detail'] <NEW_LINE> exclude = [ 'age', 'checksum', 'seq_num', 'metric', 'lsas'] <NEW_LINE> def cli(self, vrf='', output=None): <NEW_LINE> <INDENT> if vrf: <NEW_LINE> <INDENT> cmd = self.cli_command[0].format(vrf=vrf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = self.cli_command[1] <NEW_LINE> <DEDENT> return super().cli(cmd=cmd, db_type='summary',output=output)
|
Parser for:
show ip ospf database summary detail
show ip ospf database summary detail vrf <vrf>
|
6259902c8c3a8732951f756a
|
class PathChooserWidget(QtGui.QWidget, ConstantWidgetMixin): <NEW_LINE> <INDENT> def __init__(self, param, parent=None): <NEW_LINE> <INDENT> QtGui.QWidget.__init__(self, parent) <NEW_LINE> ConstantWidgetMixin.__init__(self, param.strValue) <NEW_LINE> layout = QtGui.QHBoxLayout() <NEW_LINE> self.line_edit = StandardConstantWidget(param, self) <NEW_LINE> self.browse_button = self.create_browse_button() <NEW_LINE> layout.setMargin(5) <NEW_LINE> layout.setSpacing(5) <NEW_LINE> layout.addWidget(self.line_edit) <NEW_LINE> layout.addWidget(self.browse_button) <NEW_LINE> self.setLayout(layout) <NEW_LINE> <DEDENT> def create_browse_button(self): <NEW_LINE> <INDENT> return PathChooserToolButton(self, self.line_edit) <NEW_LINE> <DEDENT> def updateMethod(self): <NEW_LINE> <INDENT> if self.parent() and hasattr(self.parent(), 'updateMethod'): <NEW_LINE> <INDENT> self.parent().updateMethod() <NEW_LINE> <DEDENT> <DEDENT> def contents(self): <NEW_LINE> <INDENT> return self.line_edit.contents() <NEW_LINE> <DEDENT> def setContents(self, strValue, silent=True): <NEW_LINE> <INDENT> self.line_edit.setContents(strValue, silent) <NEW_LINE> if not silent: <NEW_LINE> <INDENT> self.update_parent() <NEW_LINE> <DEDENT> <DEDENT> def focusInEvent(self, event): <NEW_LINE> <INDENT> if self.parent(): <NEW_LINE> <INDENT> QtCore.QCoreApplication.sendEvent(self.parent(), event) <NEW_LINE> <DEDENT> QtGui.QWidget.focusInEvent(self, event) <NEW_LINE> <DEDENT> def focusOutEvent(self, event): <NEW_LINE> <INDENT> self.update_parent() <NEW_LINE> QtGui.QWidget.focusOutEvent(self, event) <NEW_LINE> if self.parent(): <NEW_LINE> <INDENT> QtCore.QCoreApplication.sendEvent(self.parent(), event)
|
PathChooserWidget is a widget containing a line edit and a button that
opens a browser for paths. The lineEdit is updated with the pathname that is
selected.
|
6259902cd53ae8145f919476
|
class GlobalContainer(object): <NEW_LINE> <INDENT> def put(key, value): <NEW_LINE> <INDENT> GLOBAL_CONTAINER[key] = value <NEW_LINE> <DEDENT> put = staticmethod(put) <NEW_LINE> def get(key): <NEW_LINE> <INDENT> return GLOBAL_CONTAINER.get(key) <NEW_LINE> <DEDENT> get = staticmethod(get) <NEW_LINE> def remove(key): <NEW_LINE> <INDENT> instance = GLOBAL_CONTAINER <NEW_LINE> if key in instance: <NEW_LINE> <INDENT> del(instance[key]) <NEW_LINE> <DEDENT> <DEDENT> remove = staticmethod(remove)
|
Global container that spans across all threads
|
6259902c6e29344779b01662
|
class ListTagCallMixin(Call): <NEW_LINE> <INDENT> def list_tags(self): <NEW_LINE> <INDENT> from highton.models.tag import Tag <NEW_LINE> return fields.ListField( name=self.ENDPOINT, init_class=Tag ).decode( self.element_from_string( self._get_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Tag.ENDPOINT, ).text ) )
|
A mixin to get all tags of inherited class
These could be: people || companies || kases || deals
|
6259902c50485f2cf55dbf8e
|
class StreamingLocatorContentKey(Model): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'id': {'required': True}, } <NEW_LINE> _attribute_map = { 'label': {'key': 'label', 'type': 'str'}, 'type': {'key': 'type', 'type': 'StreamingLocatorContentKeyType'}, 'id': {'key': 'id', 'type': 'str'}, 'value': {'key': 'value', 'type': 'str'}, 'policy_name': {'key': 'policyName', 'type': 'str'}, 'tracks': {'key': 'tracks', 'type': '[TrackSelection]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(StreamingLocatorContentKey, self).__init__(**kwargs) <NEW_LINE> self.label = kwargs.get('label', None) <NEW_LINE> self.type = kwargs.get('type', None) <NEW_LINE> self.id = kwargs.get('id', None) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.policy_name = kwargs.get('policy_name', None) <NEW_LINE> self.tracks = kwargs.get('tracks', None)
|
Class for content key in Streaming Locator.
All required parameters must be populated in order to send to Azure.
:param label: Label of Content Key
:type label: str
:param type: Required. Encryption type of Content Key. Possible values
include: 'CommonEncryptionCenc', 'CommonEncryptionCbcs',
'EnvelopeEncryption'
:type type: str or ~azure.mgmt.media.models.StreamingLocatorContentKeyType
:param id: Required. ID of Content Key
:type id: str
:param value: Value of of Content Key
:type value: str
:param policy_name: ContentKeyPolicy used by Content Key
:type policy_name: str
:param tracks: Tracks which use this Content Key
:type tracks: list[~azure.mgmt.media.models.TrackSelection]
|
6259902c1d351010ab8f4b2a
|
class C7200(Router): <NEW_LINE> <INDENT> def __init__(self, module, server, project, npe="npe-400"): <NEW_LINE> <INDENT> Router.__init__(self, module, server, project, platform="c7200") <NEW_LINE> c7200_settings = {"ram": 512, "nvram": 128, "disk0": 64, "disk1": 0, "npe": npe, "midplane": "vxr", "clock_divisor": 4, "sensors": [22, 22, 22, 22], "power_supplies": [1, 1]} <NEW_LINE> if npe == "npe-g2": <NEW_LINE> <INDENT> c7200_settings["slot0"] = "C7200-IO-GE-E" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c7200_settings["slot0"] = "C7200-IO-FE" <NEW_LINE> <DEDENT> self._settings.update(c7200_settings) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Router c7200" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def symbolName(): <NEW_LINE> <INDENT> return "Router c7200"
|
Dynamips c7200 router.
:param module: parent module for this node
:param server: GNS3 server instance
:param project: Project instance
|
6259902ce76e3b2f99fd9a20
|
class CourseSchedule_207(object): <NEW_LINE> <INDENT> def canFinish(self, numCourses, prerequisites): <NEW_LINE> <INDENT> def dfs(courses): <NEW_LINE> <INDENT> if visited[courses] == -1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if visited[courses] == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> visited[courses] = -1 <NEW_LINE> for j in graph[courses]: <NEW_LINE> <INDENT> if not dfs(j): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> visited[courses] = 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> if len(prerequisites) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> visited = [0 for _ in range(numCourses)] <NEW_LINE> graph = [[] for _ in range(numCourses)] <NEW_LINE> for x, y in prerequisites: <NEW_LINE> <INDENT> graph[x].append(y) <NEW_LINE> <DEDENT> for i in range(numCourses): <NEW_LINE> <INDENT> if not dfs(i): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
|
if node v has not been visited, then mark it as 0.
if node v is being visited, then mark it as -1. If we find a vertex marked as -1 in DFS, then their is a ring.
if node v has been visited, then mark it as 1. If a vertex was marked as 1, then no ring contains v or its successors.
|
6259902c1f5feb6acb163c04
|
class TemplateConfiguration(RuleSet): <NEW_LINE> <INDENT> template = None <NEW_LINE> def __init__(self, name, base=None, source=None, template=None, description=None, **options): <NEW_LINE> <INDENT> if template: <NEW_LINE> <INDENT> if isinstance(template, str): <NEW_LINE> <INDENT> template = DocumentTemplate.from_string(template) <NEW_LINE> <DEDENT> assert self.template in (None, template) <NEW_LINE> self.template = template <NEW_LINE> <DEDENT> if base: <NEW_LINE> <INDENT> if isinstance(base, str): <NEW_LINE> <INDENT> base = TemplateConfigurationFile(base, source=self) <NEW_LINE> <DEDENT> assert self.template in (None, base.template) <NEW_LINE> self.template = self.template or base.template <NEW_LINE> <DEDENT> for attr, val in options.items(): <NEW_LINE> <INDENT> options[attr] = self._validate_attribute(self.template, attr, val) <NEW_LINE> <DEDENT> base = base or self.template <NEW_LINE> super().__init__(name, base=base, source=source, **options) <NEW_LINE> self.description = description <NEW_LINE> <DEDENT> def get_entries(self, name, document): <NEW_LINE> <INDENT> if name in self: <NEW_LINE> <INDENT> yield self[name] <NEW_LINE> <DEDENT> if self.base: <NEW_LINE> <INDENT> yield from self.base.get_entries(name, document) <NEW_LINE> <DEDENT> raise KeyError(name) <NEW_LINE> <DEDENT> def get_attribute_value(self, name): <NEW_LINE> <INDENT> if name in self: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> return self.base.get_attribute_value(name) <NEW_LINE> <DEDENT> def get_entry_class(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> template = self.template.get_template(name) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError("'{}' is not a template used by {}" .format(name, self.template)) <NEW_LINE> <DEDENT> return type(template) <NEW_LINE> <DEDENT> def document(self, document_tree, backend=None): <NEW_LINE> <INDENT> return self.template(document_tree, configuration=self, backend=backend)
|
Stores a configuration for a :class:`DocumentTemplate`
Args:
name (str): a label for this template configuration
base (TemplateConfiguration): the template configuration to extend
template (DocumentTemplateMeta or str): the document template to
configure
description (str): a short string describing this style sheet
**options: configuration values for the configuration attributes
defined by the document :attr:`template`
|
6259902cd99f1b3c44d066b7
|
class RunningAverage(Metric): <NEW_LINE> <INDENT> def __init__(self, src=None, alpha=0.98, output_transform=None): <NEW_LINE> <INDENT> if not (isinstance(src, Metric) or src is None): <NEW_LINE> <INDENT> raise TypeError("Argument src should be a Metric or None") <NEW_LINE> <DEDENT> if not (0.0 < alpha <= 1.0): <NEW_LINE> <INDENT> raise ValueError("Argument alpha should be a float between 0.0 and 1.0") <NEW_LINE> <DEDENT> if isinstance(src, Metric): <NEW_LINE> <INDENT> if output_transform is not None: <NEW_LINE> <INDENT> raise ValueError("Argument output_transform should be None if src is a Metric") <NEW_LINE> <DEDENT> self.src = src <NEW_LINE> self._get_src_value = self._get_metric_value <NEW_LINE> self.iteration_completed = self._metric_iteration_completed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if output_transform is None: <NEW_LINE> <INDENT> raise ValueError("Argument output_transform should not be None if src corresponds " "to the output of process function.") <NEW_LINE> <DEDENT> self._get_src_value = self._get_output_value <NEW_LINE> self.update = self._output_update <NEW_LINE> <DEDENT> self.alpha = alpha <NEW_LINE> super(RunningAverage, self).__init__(output_transform=output_transform) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._value = None <NEW_LINE> <DEDENT> def update(self, output): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def compute(self): <NEW_LINE> <INDENT> if self._value is None: <NEW_LINE> <INDENT> self._value = self._get_src_value() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._value = self._value * self.alpha + (1.0 - self.alpha) * self._get_src_value() <NEW_LINE> <DEDENT> return self._value <NEW_LINE> <DEDENT> def attach(self, engine, name): <NEW_LINE> <INDENT> engine.add_event_handler(Events.EPOCH_STARTED, self.started) <NEW_LINE> engine.add_event_handler(Events.ITERATION_COMPLETED, self.iteration_completed) <NEW_LINE> engine.add_event_handler(Events.ITERATION_COMPLETED, self.completed, name) <NEW_LINE> <DEDENT> def _get_metric_value(self): <NEW_LINE> <INDENT> return self.src.compute() <NEW_LINE> <DEDENT> def _get_output_value(self): <NEW_LINE> <INDENT> return self.src <NEW_LINE> <DEDENT> def _metric_iteration_completed(self, engine): <NEW_LINE> <INDENT> self.src.started(engine) <NEW_LINE> self.src.iteration_completed(engine) <NEW_LINE> <DEDENT> def _output_update(self, output): <NEW_LINE> <INDENT> self.src = output
|
Compute running average of a metric or the output of process function.
Args:
src (Metric or None): input source: an instance of :class:`ignite.metrics.Metric` or None. The latter
corresponds to `engine.state.output` which holds the output of process function.
alpha (float, optional): running average decay factor, default 0.98
output_transform (Callable, optional): a function to use to transform the output if `src` is None and
corresponds the output of process function. Otherwise it should be None.
Examples:
.. code-block:: python
alpha = 0.98
acc_metric = RunningAverage(CategoricalAccuracy(output_transform=lambda x: [x[1], x[2]]), alpha=alpha)
acc_metric.attach(trainer, 'running_avg_accuracy')
avg_output = RunningAverage(output_transform=lambda x: x[0], alpha=alpha)
avg_output.attach(trainer, 'running_avg_loss')
@trainer.on(Events.ITERATION_COMPLETED)
def log_running_avg_metrics(engine):
print("running avg accuracy:", engine.state.metrics['running_avg_accuracy'])
print("running avg loss:", engine.state.metrics['running_avg_loss'])
|
6259902c26238365f5fadb65
|
class FillingCirclesBar(ChargingBar): <NEW_LINE> <INDENT> def __init__(self, max_value: float = 100, current_value: float = 0, increment_by: float = 1, cap_value: bool = True): <NEW_LINE> <INDENT> super().__init__(max_value, current_value, increment_by, cap_value) <NEW_LINE> self._empty_character = '◯' <NEW_LINE> self._fill_character = '◉'
|
Specialization of ChargingBar where the fill and empty characters are
circles.
|
6259902c8a43f66fc4bf3198
|
class LogzMonitorResourceListResponse(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[LogzMonitorResource]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(LogzMonitorResourceListResponse, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None)
|
Response of a list operation.
:param value: Results of a list operation.
:type value: list[~microsoft_logz.models.LogzMonitorResource]
:param next_link: Link to the next set of results, if any.
:type next_link: str
|
6259902c8a349b6b4368724e
|
class Baidu(Scraper): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Scraper.__init__(self) <NEW_LINE> self.url = 'https://www.baidu.com/s' <NEW_LINE> self.newsURL = 'http://news.baidu.com/ns' <NEW_LINE> self.defaultStart = 0 <NEW_LINE> self.queryKey = 'word' <NEW_LINE> self.startKey = 'pn' <NEW_LINE> self.name = 'baidu' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_response(soup): <NEW_LINE> <INDENT> urls = [] <NEW_LINE> for div in soup.findAll('div', {'class': 'result'}): <NEW_LINE> <INDENT> title = div.h3.a.getText() <NEW_LINE> url = div.h3.a['href'] <NEW_LINE> urls.append({'title': title, 'link': url}) <NEW_LINE> <DEDENT> print('Baidu parsed: ' + str(urls)) <NEW_LINE> return urls <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_news_response(soup): <NEW_LINE> <INDENT> urls = [] <NEW_LINE> for h3 in soup.findAll('h3', {'class': 'c-title'}): <NEW_LINE> <INDENT> title = h3.a.getText() <NEW_LINE> link = h3.a.get('href') <NEW_LINE> urls.append({'title': title, 'link': link}) <NEW_LINE> <DEDENT> print('Baidu parsed: ' + str(urls)) <NEW_LINE> return urls
|
Scrapper class for Baidu
|
6259902c3eb6a72ae038b67a
|
class IdxWORD10R(db.Model): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __tablename__ = 'idxWORD10R' <NEW_LINE> id_bibrec = db.Column(db.MediumInteger(8, unsigned=True), db.ForeignKey(Bibrec.id), primary_key=True) <NEW_LINE> termlist = db.Column(db.iLargeBinary, nullable=True) <NEW_LINE> type = db.Column(db.Enum('CURRENT', 'FUTURE', 'TEMPORARY', name=__tablename__+'_type'), nullable=False, server_default='CURRENT', primary_key=True)
|
Represents a IdxWORD10R record.
|
6259902c507cdc57c63a5dbd
|
class APISpecExt: <NEW_LINE> <INDENT> def __init__(self, app=None, **kwargs): <NEW_LINE> <INDENT> self.spec = None <NEW_LINE> if app is not None: <NEW_LINE> <INDENT> self.init_app(app, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def init_app(self, app, **kwargs): <NEW_LINE> <INDENT> app.config.setdefault("APISPEC_TITLE", "StockMarketSimulator") <NEW_LINE> app.config.setdefault("APISPEC_VERSION", "1.0.0") <NEW_LINE> app.config.setdefault("OPENAPI_VERSION", "3.0.2") <NEW_LINE> app.config.setdefault("SWAGGER_JSON_URL", "/swagger.json") <NEW_LINE> app.config.setdefault("SWAGGER_UI_URL", "/swagger-ui") <NEW_LINE> app.config.setdefault("SWAGGER_URL_PREFIX", None) <NEW_LINE> self.spec = APISpec( title=app.config["APISPEC_TITLE"], version=app.config["APISPEC_VERSION"], openapi_version=app.config["OPENAPI_VERSION"], plugins=[MarshmallowPlugin(), FlaskRestfulPlugin()], **kwargs ) <NEW_LINE> blueprint = Blueprint( "swagger", __name__, template_folder="./templates", url_prefix=app.config["SWAGGER_URL_PREFIX"], ) <NEW_LINE> blueprint.add_url_rule( app.config["SWAGGER_JSON_URL"], "swagger_json", self.swagger_json ) <NEW_LINE> blueprint.add_url_rule( app.config["SWAGGER_UI_URL"], "swagger_ui", self.swagger_ui ) <NEW_LINE> app.register_blueprint(blueprint) <NEW_LINE> <DEDENT> def swagger_json(self): <NEW_LINE> <INDENT> return jsonify(self.spec.to_dict()) <NEW_LINE> <DEDENT> def swagger_ui(self): <NEW_LINE> <INDENT> return render_template("swagger.j2")
|
Very simple and small extension to use apispec with this API as a flask extension
|
6259902c1f5feb6acb163c06
|
class Settings(PlexObject): <NEW_LINE> <INDENT> key = '/:/prefs' <NEW_LINE> def __init__(self, server, data, initpath=None): <NEW_LINE> <INDENT> self._settings = {} <NEW_LINE> super(Settings, self).__init__(server, data, initpath) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr.startswith('_'): <NEW_LINE> <INDENT> return self.__dict__[attr] <NEW_LINE> <DEDENT> return self.get(attr).value <NEW_LINE> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> if not attr.startswith('_'): <NEW_LINE> <INDENT> return self.get(attr).set(value) <NEW_LINE> <DEDENT> self.__dict__[attr] = value <NEW_LINE> <DEDENT> def _loadData(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> for elem in data: <NEW_LINE> <INDENT> id = utils.lowerFirst(elem.attrib['id']) <NEW_LINE> if id in self._settings: <NEW_LINE> <INDENT> self._settings[id]._loadData(elem) <NEW_LINE> continue <NEW_LINE> <DEDENT> self._settings[id] = Setting(self._server, elem, self._initpath) <NEW_LINE> <DEDENT> <DEDENT> def all(self): <NEW_LINE> <INDENT> return list(v for id, v in sorted(self._settings.items())) <NEW_LINE> <DEDENT> def get(self, id): <NEW_LINE> <INDENT> id = utils.lowerFirst(id) <NEW_LINE> if id in self._settings: <NEW_LINE> <INDENT> return self._settings[id] <NEW_LINE> <DEDENT> raise NotFound('Invalid setting id: %s' % id) <NEW_LINE> <DEDENT> def groups(self): <NEW_LINE> <INDENT> groups = defaultdict(list) <NEW_LINE> for setting in self.all(): <NEW_LINE> <INDENT> groups[setting.group].append(setting) <NEW_LINE> <DEDENT> return dict(groups) <NEW_LINE> <DEDENT> def group(self, group): <NEW_LINE> <INDENT> return self.groups().get(group, []) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> params = {} <NEW_LINE> for setting in self.all(): <NEW_LINE> <INDENT> if setting._setValue: <NEW_LINE> <INDENT> log.info('Saving PlexServer setting %s = %s' % (setting.id, setting._setValue)) <NEW_LINE> params[setting.id] = quote(setting._setValue) <NEW_LINE> <DEDENT> <DEDENT> if not params: <NEW_LINE> <INDENT> raise BadRequest('No setting have been modified.') <NEW_LINE> <DEDENT> querystr = '&'.join(['%s=%s' % (k, v) for k, v in params.items()]) <NEW_LINE> url = '%s?%s' % (self.key, querystr) <NEW_LINE> self._server.query(url, self._server._session.put) <NEW_LINE> self.reload()
|
Container class for all settings. Allows getting and setting PlexServer settings.
Attributes:
key (str): '/:/prefs'
|
6259902cd164cc6175821f87
|
class CourseSubCategory(models.Model): <NEW_LINE> <INDENT> category = models.ForeignKey("CourseCategory",on_delete=models.CASCADE) <NEW_LINE> name = models.CharField(max_length=64, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "%s" % self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "课程子类" <NEW_LINE> verbose_name_plural = "课程子类"
|
课程子类, e.g python linux
|
6259902c1d351010ab8f4b2d
|
class RequestGroupActionCondition(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_type = "RequestGroupActionCondition" <NEW_LINE> def __init__(self, jsondict=None, strict=True, **kwargs): <NEW_LINE> <INDENT> self.expression = None <NEW_LINE> self.kind = None <NEW_LINE> super(RequestGroupActionCondition, self).__init__(jsondict=jsondict, strict=strict, **kwargs) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(RequestGroupActionCondition, self).elementProperties() <NEW_LINE> js.extend([ ("expression", "expression", expression.Expression, False, None, False), ("kind", "kind", str, False, None, True), ]) <NEW_LINE> return js
|
Whether or not the action is applicable.
An expression that describes applicability criteria, or start/stop
conditions for the action.
|
6259902cd53ae8145f919479
|
class TransferProcessor(ZipProcessor): <NEW_LINE> <INDENT> pdf_fieldnames=[] <NEW_LINE> def transform(self): <NEW_LINE> <INDENT> with ZipFile(self.fn, 'r') as zf: <NEW_LINE> <INDENT> namelist = zf.namelist() <NEW_LINE> <DEDENT> with StringIO(newline='') as f: <NEW_LINE> <INDENT> writer = csv.DictWriter(f, fieldnames=self.pdf_fieldnames, delimiter='\t', extrasaction='ignore') <NEW_LINE> writer.writeheader() <NEW_LINE> for fn in namelist: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> writer.writerow(re.match(self.pdf_pattern, fn).groupdict()) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> print(f'Error parsing filename:\n' f' zipfile: {self.fn}\n' f' pdf: {fn}') <NEW_LINE> <DEDENT> <DEDENT> with ZipFile(self.fn, 'a') as zf: <NEW_LINE> <INDENT> zf.writestr('index.txt', f.getvalue())
|
Class for handling CommonApp transfer zip files, which all need
an index file to be generated for DIP.
|
6259902c50485f2cf55dbf91
|
class RobotDelocalized(object): <NEW_LINE> <INDENT> __slots__ = ( '_robotID', ) <NEW_LINE> @property <NEW_LINE> def robotID(self): <NEW_LINE> <INDENT> return self._robotID <NEW_LINE> <DEDENT> @robotID.setter <NEW_LINE> def robotID(self, value): <NEW_LINE> <INDENT> self._robotID = msgbuffers.validate_integer( 'RobotDelocalized.robotID', value, 0, 255) <NEW_LINE> <DEDENT> def __init__(self, robotID=0): <NEW_LINE> <INDENT> self.robotID = robotID <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def unpack(cls, buffer): <NEW_LINE> <INDENT> reader = msgbuffers.BinaryReader(buffer) <NEW_LINE> value = cls.unpack_from(reader) <NEW_LINE> if reader.tell() != len(reader): <NEW_LINE> <INDENT> raise msgbuffers.ReadError( ('RobotDelocalized.unpack received a buffer of length {length}, ' + 'but only {position} bytes were read.').format( length=len(reader), position=reader.tell())) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def unpack_from(cls, reader): <NEW_LINE> <INDENT> _robotID = reader.read('B') <NEW_LINE> return cls(_robotID) <NEW_LINE> <DEDENT> def pack(self): <NEW_LINE> <INDENT> writer = msgbuffers.BinaryWriter() <NEW_LINE> self.pack_to(writer) <NEW_LINE> return writer.dumps() <NEW_LINE> <DEDENT> def pack_to(self, writer): <NEW_LINE> <INDENT> writer.write(self._robotID, 'B') <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(self) is type(other): <NEW_LINE> <INDENT> return self._robotID == other._robotID <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if type(self) is type(other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return (msgbuffers.size(self._robotID, 'B')) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{type}(robotID={robotID})'.format( type=type(self).__name__, robotID=self._robotID) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{type}(robotID={robotID})'.format( type=type(self).__name__, robotID=repr(self._robotID))
|
Generated message-passing message.
|
6259902cd6c5a102081e313d
|
class InverseFeature(TransformerMixin, BaseEstimator): <NEW_LINE> <INDENT> def __init__(self, classes): <NEW_LINE> <INDENT> self.classes = classes <NEW_LINE> <DEDENT> def fit(self, *args): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X, y=None): <NEW_LINE> <INDENT> from copy import deepcopy <NEW_LINE> new_X = deepcopy(X) <NEW_LINE> new_X[self.classes] = -new_X[self.classes] <NEW_LINE> return new_X
|
Multiply one or more columns by -1.
Parameters
----------
classes : the list of classes to be transformed (by name)
|
6259902c6fece00bbaccc9c5
|
class Source_Interface(object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> @abstractmethod <NEW_LINE> def get_digest(self): raise NotImplementedError
|
Trying to make an interface for each source of digest
|
6259902c796e427e5384f793
|
class EventCounter: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.events_count = 0 <NEW_LINE> self.events_count_by_type = dict() <NEW_LINE> <DEDENT> def increment_counting(self, event): <NEW_LINE> <INDENT> assert isinstance(event, Event) <NEW_LINE> self.events_count += 1 <NEW_LINE> t = type(event.type) <NEW_LINE> if t in self.events_count_by_type: <NEW_LINE> <INDENT> self.events_count_by_type[t] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.events_count_by_type[t] = 1 <NEW_LINE> <DEDENT> <DEDENT> def count_all(self): <NEW_LINE> <INDENT> return self.events_count <NEW_LINE> <DEDENT> def count(self, eventtype): <NEW_LINE> <INDENT> return self.events_count_by_type.get(type(eventtype), 0)
|
A counter of events.
|
6259902c30c21e258be99823
|
class TestTrustedSystemParanoia(TestTrustedSystemBaseClass): <NEW_LINE> <INDENT> def testProjectsWithoutNextActions(self): <NEW_LINE> <INDENT> self.addAnonymousFile([ "# Ordered project.", " @ First task (DONE 2013-05-02 20:59)", "", "# Another ordered project", " @ First task (DONE 2013-05-02 20:59)", " @ Second task, which makes the parent Project not show up.", "", "- Empty super-project.", " * The super-project shouldn't show up; the sub-project will.", " - Empty project.", "", "# Project WITH next action", " @ Next action", "", "# Project which is (DONE)", ]) <NEW_LINE> projects = self.trusted_system.ProjectsWithoutNextActions() <NEW_LINE> self.assertEqual(2, len(projects)) <NEW_LINE> six.assertCountEqual( self, ['Ordered project.', 'Empty project.'], [x.text for x in projects]) <NEW_LINE> <DEDENT> def testNextActionsWithoutContexts(self): <NEW_LINE> <INDENT> self.addAnonymousFile([ "# Project with context @test", " @ Should not show up", "", "# Project without context.", " @ Should show up", "", "= Section with context @foo =", "", "# Project with implicit context.", " @ Also should not show up", ]) <NEW_LINE> next_actions = self.trusted_system.NextActionsWithoutContexts() <NEW_LINE> self.assertEqual(1, len(next_actions)) <NEW_LINE> six.assertCountEqual( self, ['Should show up'], [x.text for x in next_actions])
|
Test "paranoia" features.
All the little things that might cause you to lose trust in the system.
|
6259902ce76e3b2f99fd9a24
|
class Product: <NEW_LINE> <INDENT> def getProductId(self): <NEW_LINE> <INDENT> return self.__productId <NEW_LINE> <DEDENT> """metodo que setea el id de un product""" <NEW_LINE> def setProductId(self, productId): <NEW_LINE> <INDENT> self.__productId = productId <NEW_LINE> <DEDENT> """metodo que obtiene el nombre de un product""" <NEW_LINE> def getProductName(self): <NEW_LINE> <INDENT> return self.__productName <NEW_LINE> <DEDENT> """metodo que setea el nombre de un product""" <NEW_LINE> def setProductName(self, productName): <NEW_LINE> <INDENT> self.__productName = productName <NEW_LINE> <DEDENT> """metodo que obtiene la descripcion de un product""" <NEW_LINE> def getProductDescription(self): <NEW_LINE> <INDENT> return self.__productDescription <NEW_LINE> <DEDENT> """metodo que setea la descripcion de un product""" <NEW_LINE> def setProductDescription(self, productDescription): <NEW_LINE> <INDENT> self.__productDescription = productDescription <NEW_LINE> <DEDENT> """metodo que obtiene el precio de un product""" <NEW_LINE> def getProductPrice(self): <NEW_LINE> <INDENT> return self.__productPrice <NEW_LINE> <DEDENT> """metodo que setea el precio de un product""" <NEW_LINE> def setProductPrice(self, productPrice): <NEW_LINE> <INDENT> self.__productPrice = productPrice <NEW_LINE> <DEDENT> """metodo que obtiene el stock (cantidad en stock) de un product""" <NEW_LINE> def getProductStock(self): <NEW_LINE> <INDENT> return self.__productStock <NEW_LINE> <DEDENT> """metodo que setea el stock (cantidad en stock) de un product""" <NEW_LINE> def setProductStock(self, productStock): <NEW_LINE> <INDENT> self.__productStock = productStock <NEW_LINE> <DEDENT> """metodo que obtiene la categoria""" <NEW_LINE> def getProductCategory(self): <NEW_LINE> <INDENT> return self.__productCategory <NEW_LINE> <DEDENT> """metodo que setea una categoria""" <NEW_LINE> def setProductCategory(self, productCategory): <NEW_LINE> <INDENT> self.__productCategory = productCategory
|
metodo que obtiene el id de un product
|
6259902cac7a0e7691f73500
|
class GalleryImageVersionPublishingProfile(GalleryArtifactPublishingProfileBase): <NEW_LINE> <INDENT> _validation = { 'published_date': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'target_regions': {'key': 'targetRegions', 'type': '[TargetRegion]'}, 'replica_count': {'key': 'replicaCount', 'type': 'int'}, 'exclude_from_latest': {'key': 'excludeFromLatest', 'type': 'bool'}, 'published_date': {'key': 'publishedDate', 'type': 'iso-8601'}, 'end_of_life_date': {'key': 'endOfLifeDate', 'type': 'iso-8601'}, 'storage_account_type': {'key': 'storageAccountType', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, target_regions: Optional[List["TargetRegion"]] = None, replica_count: Optional[int] = None, exclude_from_latest: Optional[bool] = None, end_of_life_date: Optional[datetime.datetime] = None, storage_account_type: Optional[Union[str, "StorageAccountType"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(GalleryImageVersionPublishingProfile, self).__init__(target_regions=target_regions, replica_count=replica_count, exclude_from_latest=exclude_from_latest, end_of_life_date=end_of_life_date, storage_account_type=storage_account_type, **kwargs)
|
The publishing profile of a gallery Image Version.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar target_regions: The target regions where the Image Version is going to be replicated to.
This property is updatable.
:vartype target_regions: list[~azure.mgmt.compute.v2019_07_01.models.TargetRegion]
:ivar replica_count: The number of replicas of the Image Version to be created per region. This
property would take effect for a region when regionalReplicaCount is not specified. This
property is updatable.
:vartype replica_count: int
:ivar exclude_from_latest: If set to true, Virtual Machines deployed from the latest version of
the Image Definition won't use this Image Version.
:vartype exclude_from_latest: bool
:ivar published_date: The timestamp for when the gallery Image Version is published.
:vartype published_date: ~datetime.datetime
:ivar end_of_life_date: The end of life date of the gallery Image Version. This property can be
used for decommissioning purposes. This property is updatable.
:vartype end_of_life_date: ~datetime.datetime
:ivar storage_account_type: Specifies the storage account type to be used to store the image.
This property is not updatable. Possible values include: "Standard_LRS", "Standard_ZRS".
:vartype storage_account_type: str or ~azure.mgmt.compute.v2019_07_01.models.StorageAccountType
|
6259902c5e10d32532ce410f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.