code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class MainHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.render("index.html") | starting point off the application | 6259905cd7e4931a7ef3d68f |
@dataclass <NEW_LINE> class LinkedTaskChannel(trio.abc.Channel): <NEW_LINE> <INDENT> _to_aio: asyncio.Queue <NEW_LINE> _from_aio: trio.MemoryReceiveChannel <NEW_LINE> _to_trio: trio.MemorySendChannel <NEW_LINE> _trio_cs: trio.CancelScope <NEW_LINE> _aio_task_complete: trio.Event <NEW_LINE> _aio_task: Optional[asyncio.Task] = None <NEW_LINE> _aio_err: Optional[BaseException] = None <NEW_LINE> async def aclose(self) -> None: <NEW_LINE> <INDENT> await self._from_aio.aclose() <NEW_LINE> <DEDENT> async def receive(self) -> Any: <NEW_LINE> <INDENT> async with translate_aio_errors(self): <NEW_LINE> <INDENT> return await self._from_aio.receive() <NEW_LINE> <DEDENT> <DEDENT> async def wait_ayncio_complete(self) -> None: <NEW_LINE> <INDENT> await self._aio_task_complete.wait() <NEW_LINE> <DEDENT> async def send(self, item: Any) -> None: <NEW_LINE> <INDENT> self._to_aio.put_nowait(item) | A "linked task channel" which allows for two-way synchronized msg
passing between a ``trio``-in-guest-mode task and an ``asyncio``
task scheduled in the host loop. | 6259905cf548e778e596cb9f |
class TestChatbotController(BaseTestCase): <NEW_LINE> <INDENT> def test_root_get(self): <NEW_LINE> <INDENT> response = self.client.open( '/nmf21/chatbotModel/1.0.0/', method='GET') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) | ChatbotController integration test stubs | 6259905c3539df3088ecd8b2 |
class OrkutAuth(BaseGoogleOAuth): <NEW_LINE> <INDENT> AUTH_BACKEND = OrkutBackend <NEW_LINE> SETTINGS_KEY_NAME = 'ORKUT_CONSUMER_KEY' <NEW_LINE> SETTINGS_SECRET_NAME = 'ORKUT_CONSUMER_SECRET' <NEW_LINE> def user_data(self, access_token): <NEW_LINE> <INDENT> fields = ORKUT_DEFAULT_DATA <NEW_LINE> if hasattr(settings, 'ORKUT_EXTRA_DATA'): <NEW_LINE> <INDENT> fields += ',' + settings.ORKUT_EXTRA_DATA <NEW_LINE> <DEDENT> scope = ORKUT_SCOPE + getattr(settings, 'ORKUT_EXTRA_SCOPE', []) <NEW_LINE> params = {'method': 'people.get', 'id': 'myself', 'userId': '@me', 'groupId': '@self', 'fields': fields, 'scope': ' '.join(scope)} <NEW_LINE> request = self.oauth_request(access_token, ORKUT_REST_ENDPOINT, params) <NEW_LINE> response = urllib.urlopen(request.to_url()).read() <NEW_LINE> try: <NEW_LINE> <INDENT> return simplejson.loads(response)['data'] <NEW_LINE> <DEDENT> except (ValueError, KeyError): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def oauth_request(self, token, url, extra_params=None): <NEW_LINE> <INDENT> extra_params = extra_params or {} <NEW_LINE> scope = ORKUT_SCOPE + getattr(settings, 'ORKUT_EXTRA_SCOPE', []) <NEW_LINE> extra_params['scope'] = ' '.join(scope) <NEW_LINE> return super(OrkutAuth, self).oauth_request(token, url, extra_params) | Orkut OAuth authentication mechanism | 6259905cdd821e528d6da48b |
class CliExtension(object): <NEW_LINE> <INDENT> COMMAND_NAME = None <NEW_LINE> COMMAND_DESCRIPTION = None <NEW_LINE> def __init__(self, parser: ArgumentParser, application): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.parser = parser <NEW_LINE> self.__application_manager = application <NEW_LINE> <DEDENT> def get_application_manager(self): <NEW_LINE> <INDENT> return self.__application_manager <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def setup_parser(cls, parser: ArgumentParser): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handle(self, args): <NEW_LINE> <INDENT> raise NotImplementedError() | Allows Module to extend CLI interface | 6259905cf548e778e596cba0 |
class ExpenseUnpacker(Unpacker): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Unpacker.__init__( self, scalars=('currency', 'description', 'expense_date', 'payer', 'value'), vectors=('travelers', ) ) | Specialized unpacker for Expense data | 6259905c2ae34c7f260ac6fd |
class IEeaPrivacyscreenLayer(IDefaultBrowserLayer): <NEW_LINE> <INDENT> pass | Marker interface that defines a browser layer. | 6259905c0fa83653e46f64fc |
class Attachment: <NEW_LINE> <INDENT> __slots__ = ('id', 'size', 'height', 'width', 'filename', 'url', 'proxy_url', '_http') <NEW_LINE> def __init__(self, *, data, state): <NEW_LINE> <INDENT> self.id = int(data['id']) <NEW_LINE> self.size = data['size'] <NEW_LINE> self.height = data.get('height') <NEW_LINE> self.width = data.get('width') <NEW_LINE> self.filename = data['filename'] <NEW_LINE> self.url = data.get('url') <NEW_LINE> self.proxy_url = data.get('proxy_url') <NEW_LINE> self._http = state.http <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def save(self, fp): <NEW_LINE> <INDENT> data = yield from self._http.get_attachment(self.url) <NEW_LINE> if isinstance(fp, str): <NEW_LINE> <INDENT> with open(fp, 'wb') as f: <NEW_LINE> <INDENT> return f.write(data) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return fp.write(data) | Represents an attachment from Discord.
Attributes
------------
id: int
The attachment ID.
size: int
The attachment size in bytes.
height: Optional[int]
The attachment's height, in pixels. Only applicable to images.
width: Optional[int]
The attachment's width, in pixels. Only applicable to images.
filename: str
The attachment's filename.
url: str
The attachment URL. If the message this attachment was attached
to is deleted, then this will 404.
proxy_url: str
The proxy URL. This is a cached version of the :attr:`~Attachment.url` in the
case of images. When the message is deleted, this URL might be valid for a few
minutes or not valid at all. | 6259905c097d151d1a2c2683 |
class Job(object): <NEW_LINE> <INDENT> def __init__(self, page): <NEW_LINE> <INDENT> self.document = weakref.ref(page.document()) <NEW_LINE> self.pageNumber = page.pageNumber() <NEW_LINE> self.rotation = page.rotation() <NEW_LINE> self.width = page.physWidth() <NEW_LINE> self.height = page.physHeight() | Simply contains data needed to create an image later. | 6259905c8da39b475be047fd |
class Game: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.player = Player("Phixyn") <NEW_LINE> self._woodcutting = Woodcutting() <NEW_LINE> self.player.add_skill(self._woodcutting) <NEW_LINE> self._wood = Wood() <NEW_LINE> self.player.add_item_to_inventory(self._wood) <NEW_LINE> self._chat = Chat(max_messages=10) <NEW_LINE> self._chat.add_message("Welcome to {textColorMagenta}IdlePhix{textFormatReset}.". format(textColorMagenta=terminal.TEXT_COLOR_MAGENTA, textFormatReset=terminal.TEXT_FORMATTING_RESET)) <NEW_LINE> <DEDENT> def _increment_resources_and_exp(self): <NEW_LINE> <INDENT> self._wood.chop() <NEW_LINE> self._chat.add_message(self._wood.gatherMessage) <NEW_LINE> if self._woodcutting.add_exp(self._wood.woodcuttingExpMultiplier): <NEW_LINE> <INDENT> self._chat.add_message(self._woodcutting.get_level_up_message()) <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self._increment_resources_and_exp() <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> terminal.clear_screen() <NEW_LINE> print("Wood: {0} | Woodcutting exp: {1} | Woodcutting level: {2}".format(self._wood.amount, self._woodcutting.totalExperience, self._woodcutting.level)) <NEW_LINE> self._chat.print() | The Game class. | 6259905c91af0d3eaad3b43f |
class DeliverCallbackUseCase: <NEW_LINE> <INDENT> MAX_ATTEMPTS = 3 <NEW_LINE> def __init__(self, delivery_outbox_repo: repos.DeliveryOutboxRepo, hub_url): <NEW_LINE> <INDENT> self.delivery_outbox = delivery_outbox_repo <NEW_LINE> self.hub_url = hub_url <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> deliverable = self.delivery_outbox.get_job() <NEW_LINE> if not deliverable: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> queue_msg_id, payload = deliverable <NEW_LINE> return self.process(queue_msg_id, payload) <NEW_LINE> <DEDENT> def process(self, queue_msg_id, job): <NEW_LINE> <INDENT> subscribe_url = job['s'] <NEW_LINE> payload = job['payload'] <NEW_LINE> attempt = int(job.get('retry', 1)) <NEW_LINE> try: <NEW_LINE> <INDENT> logger.debug('[%s] deliver notification to %s with payload: %s (attempt %s)', queue_msg_id, subscribe_url, payload, attempt) <NEW_LINE> self._deliver_notification(subscribe_url, payload) <NEW_LINE> <DEDENT> except InvalidCallbackResponse as e: <NEW_LINE> <INDENT> logger.info("[%s] delivery failed", queue_msg_id) <NEW_LINE> logger.exception(e) <NEW_LINE> if attempt < self.MAX_ATTEMPTS: <NEW_LINE> <INDENT> logger.info("[%s] re-schedule delivery", queue_msg_id) <NEW_LINE> self._retry(subscribe_url, payload, attempt) <NEW_LINE> <DEDENT> <DEDENT> self.delivery_outbox.delete(queue_msg_id) <NEW_LINE> <DEDENT> def _retry(self, subscribe_url, payload, attempt): <NEW_LINE> <INDENT> logger.info("Delivery failed, re-schedule it") <NEW_LINE> job = {'s': subscribe_url, 'payload': payload, 'retry': attempt + 1} <NEW_LINE> self.delivery_outbox.post_job(job, delay_seconds=get_retry_time(attempt)) <NEW_LINE> <DEDENT> def _deliver_notification(self, url, payload): <NEW_LINE> <INDENT> logger.info("Sending WebSub payload \n %s to callback URL \n %s", payload, url) <NEW_LINE> header = { 'Link': f'<{self.hub_url}>; rel="hub"' } <NEW_LINE> try: <NEW_LINE> <INDENT> resp = requests.post(url, json=payload, headers=header) <NEW_LINE> if str(resp.status_code).startswith('2'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> except ConnectionError: <NEW_LINE> <INDENT> raise InvalidCallbackResponse("Connection error, url: %s", url) <NEW_LINE> <DEDENT> raise InvalidCallbackResponse("Subscription url %s seems to be invalid, " "returns %s", url, resp.status_code) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_retry_time(attempt): <NEW_LINE> <INDENT> base = 8 <NEW_LINE> max_retry = 100 <NEW_LINE> delay = min(base * 2 ** attempt, max_retry) <NEW_LINE> jitter = random.uniform(0, delay / 2) <NEW_LINE> return int(delay / 2 + jitter) | Is used by a callback deliverer worker
Reads queue delivery_outbox_repo consisting of tasks in format:
(url, message)
Then such message should be either sent to this URL and the task is deleted
or, in case of any error, not to be re-scheduled again
(up to MAX_ATTEMPTS times) | 6259905c097d151d1a2c2684 |
class ActionShortcut(object): <NEW_LINE> <INDENT> def __init__(self, ckan): <NEW_LINE> <INDENT> self._ckan = ckan <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> def action(**kwargs): <NEW_LINE> <INDENT> files = {} <NEW_LINE> for k, v in kwargs.items(): <NEW_LINE> <INDENT> if is_file_like(v): <NEW_LINE> <INDENT> files[k] = v <NEW_LINE> <DEDENT> <DEDENT> if files: <NEW_LINE> <INDENT> nonfiles = dict((k, v) for k, v in kwargs.items() if k not in files) <NEW_LINE> return self._ckan.call_action(name, data_dict=nonfiles, files=files) <NEW_LINE> <DEDENT> return self._ckan.call_action(name, data_dict=kwargs) <NEW_LINE> <DEDENT> return action | ActionShortcut(foo).bar(baz=2) <=> foo.call_action('bar', {'baz':2})
An instance of this class is used as the .action attribute of
LocalCKAN and RemoteCKAN instances to provide a short way to call
actions, e.g::
pkg = demo.action.package_show(id='adur_district_spending')
instead of::
pkg = demo.call_action('package_show', {'id':'adur_district_spending'})
File-like values (objects with a 'read' attribute) are
sent as file-uploads::
pkg = demo.action.resource_update(package_id='foo', upload=open(..))
becomes::
pkg = demo.call_action('resource_update',
{'package_id': 'foo'}, files={'upload': open(..)}) | 6259905ca219f33f346c7e1c |
class ANscanTest(RunStopMacroTestCase): <NEW_LINE> <INDENT> pass | Not yet implemented. Once implemented it will test anscan.
See :class:`.RunStopMacroTestCase` for requirements. | 6259905c498bea3a75a59108 |
class InboundNATRules(_BaseHNVModel): <NEW_LINE> <INDENT> _endpoint = ("/networking/v1/loadBalancers/{parent_id}" "/inboundNatRules/{resource_id}") <NEW_LINE> parent_id = model.Field( name="parent_id", key="parentResourceID", is_property=False, is_required=True, is_read_only=True) <NEW_LINE> backend_ip_configuration = model.Field( name="backend_ip_configuration", key="backendIPConfiguration", is_required=False, is_read_only=False) <NEW_LINE> backend_port = model.Field(name="backend_port", key="backendPort", is_required=False, is_read_only=False) <NEW_LINE> frontend_ip_configurations = model.Field( name="frontend_ip_configurations", key="frontendIPConfigurations", is_required=True, is_read_only=False) <NEW_LINE> frontend_port = model.Field(name="frontend_port", key="frontendPort", is_required=False, is_read_only=False) <NEW_LINE> protocol = model.Field(name="protocol", key="protocol", is_required=True, is_read_only=False) <NEW_LINE> idle_timeout = model.Field(name="idle_timeout", key="idleTimeoutInMinutes", is_required=False, is_read_only=False) <NEW_LINE> floating_ip = model.Field(name="floating_ip", key="enableFloatingIP", is_required=False, is_read_only=False) <NEW_LINE> @classmethod <NEW_LINE> def process_raw_data(cls, raw_data): <NEW_LINE> <INDENT> properties = raw_data.get("properties", {}) <NEW_LINE> raw_ip_configuration = properties.get("backendIPConfiguration", []) <NEW_LINE> if isinstance(raw_ip_configuration, dict): <NEW_LINE> <INDENT> raw_ip_configuration = [raw_ip_configuration] <NEW_LINE> <DEDENT> for raw_content in raw_ip_configuration: <NEW_LINE> <INDENT> backend_ip_configuration = Resource.from_raw_data(raw_content) <NEW_LINE> properties["backendIPConfiguration"] = backend_ip_configuration <NEW_LINE> <DEDENT> frontend_ip_configurations = [] <NEW_LINE> for raw_content in properties.get("frontendIPConfigurations", []): <NEW_LINE> <INDENT> resource = Resource.from_raw_data(raw_content) <NEW_LINE> frontend_ip_configurations.append(resource) <NEW_LINE> <DEDENT> properties["frontendIPConfigurations"] = frontend_ip_configurations <NEW_LINE> return super(InboundNATRules, cls).process_raw_data(raw_data) | Model for inbound nat rules.
This resource is used to configure the load balancer to apply
Network Address Translation of inbound traffic. | 6259905c32920d7e50bc765d |
class OutputCheckerFix(doctest.OutputChecker): <NEW_LINE> <INDENT> _literal_re = re.compile( r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE) <NEW_LINE> _remove_byteorder = re.compile( r"([\'\"])[|<>]([biufcSaUV][0-9]+)([\'\"])", re.UNICODE) <NEW_LINE> _original_output_checker = doctest.OutputChecker <NEW_LINE> def do_fixes(self, want, got): <NEW_LINE> <INDENT> want = re.sub(self._literal_re, r'\1\2', want) <NEW_LINE> want = re.sub(self._remove_byteorder, r'\1\2\3', want) <NEW_LINE> got = re.sub(self._literal_re, r'\1\2', got) <NEW_LINE> got = re.sub(self._remove_byteorder, r'\1\2\3', got) <NEW_LINE> return want, got <NEW_LINE> <DEDENT> def check_output(self, want, got, flags): <NEW_LINE> <INDENT> if flags & FIX: <NEW_LINE> <INDENT> want, got = self.do_fixes(want, got) <NEW_LINE> <DEDENT> return self._original_output_checker.check_output( self, want, got, flags) <NEW_LINE> <DEDENT> def output_difference(self, want, got, flags): <NEW_LINE> <INDENT> if flags & FIX: <NEW_LINE> <INDENT> want, got = self.do_fixes(want, got) <NEW_LINE> <DEDENT> return self._original_output_checker.output_difference( self, want, got, flags) | A special doctest OutputChecker that normalizes a number of things common
to astropy doctests.
- Removes u'' prefixes on string literals
- In Numpy dtype strings, removes the leading pipe, i.e. '|S9' ->
'S9'. Numpy 1.7 no longer includes it in display. | 6259905c460517430c432b5e |
class Show(ImageElement): <NEW_LINE> <INDENT> xmlns = namespaces.image <NEW_LINE> class Help: <NEW_LINE> <INDENT> synopsis = "show an image" <NEW_LINE> <DEDENT> image = Attribute( "Image to show", type="expression", default="image", evaldefault=True ) <NEW_LINE> def logic(self, context): <NEW_LINE> <INDENT> if context[".debug"]: <NEW_LINE> <INDENT> self.image(context)._img.show() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.warn("<show> can be used in debug mode only") | Show an image (for debugging purposes). Imagemagick is required for this operation. | 6259905c07f4c71912bb0a52 |
class About(QtGui.QDialog, about_dialog_layout.Ui_Dialog): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(About, self).__init__() <NEW_LINE> self.setupUi(self) | This class is a dialog which contains information about the program.
The information shown here is on where to go for help, and on the lisence. | 6259905cd6c5a102081e3738 |
class HolderListSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = { "City": fields.Str(required=False, load_from="City"), "CreateTime": fields.Int(required=False, load_from="CreateTime"), "DockerCount": fields.Int(required=False, load_from="DockerCount"), "DockerInfo": fields.List(DockerInfoSchema()), "ExpireTime": fields.Int(required=False, load_from="ExpireTime"), "FirewallId": fields.Str(required=False, load_from="FirewallId"), "HolderName": fields.Str(required=False, load_from="HolderName"), "IdcId": fields.Str(required=False, load_from="IdcId"), "ImageList": fields.List(ImageListSchema()), "InnerIp": fields.Str(required=False, load_from="InnerIp"), "IpList": fields.List(IpListSchema()), "NetLimit": fields.Int(required=False, load_from="NetLimit"), "OcName": fields.Str(required=False, load_from="OcName"), "ProductType": fields.Str(required=False, load_from="ProductType"), "Province": fields.Str(required=False, load_from="Province"), "ResourceId": fields.Str(required=False, load_from="ResourceId"), "RestartStrategy": fields.Int( required=False, load_from="RestartStrategy" ), "State": fields.Int(required=False, load_from="State"), "StorVolumeCount": fields.Int( required=False, load_from="StorVolumeCount" ), "StorVolumeInfo": fields.List(StorVolumeInfoSchema()), "SubnetId": fields.Str(required=False, load_from="SubnetId"), "Type": fields.Int(required=False, load_from="Type"), } | HolderList - 容器组信息 | 6259905c3c8af77a43b68a4c |
class ComparisonTestFramework(SupernodeCoinTestFramework): <NEW_LINE> <INDENT> def set_test_params(self): <NEW_LINE> <INDENT> self.num_nodes = 2 <NEW_LINE> self.setup_clean_chain = True <NEW_LINE> <DEDENT> def add_options(self, parser): <NEW_LINE> <INDENT> parser.add_option("--testbinary", dest="testbinary", default=os.getenv("BITCOIND", "supernodecoind"), help="supernodecoind binary to test") <NEW_LINE> parser.add_option("--refbinary", dest="refbinary", default=os.getenv("BITCOIND", "supernodecoind"), help="supernodecoind binary to use for reference nodes (if any)") <NEW_LINE> <DEDENT> def setup_network(self): <NEW_LINE> <INDENT> extra_args = [['-whitelist=127.0.0.1']] * self.num_nodes <NEW_LINE> if hasattr(self, "extra_args"): <NEW_LINE> <INDENT> extra_args = self.extra_args <NEW_LINE> <DEDENT> self.add_nodes(self.num_nodes, extra_args, binary=[self.options.testbinary] + [self.options.refbinary] * (self.num_nodes - 1)) <NEW_LINE> self.start_nodes() | Test framework for doing p2p comparison testing
Sets up some supernodecoind binaries:
- 1 binary: test binary
- 2 binaries: 1 test binary, 1 ref binary
- n>2 binaries: 1 test binary, n-1 ref binaries | 6259905c7b25080760ed87eb |
class DeleteForm(FlaskForm): <NEW_LINE> <INDENT> pass | Delete form – intentionally left blank. | 6259905c0a50d4780f7068ca |
class GroupsV2GroupPotentialMembership(object): <NEW_LINE> <INDENT> swagger_types = { 'member': 'GroupsV2GroupPotentialMember', 'group': 'GroupsV2GroupV2' } <NEW_LINE> attribute_map = { 'member': 'member', 'group': 'group' } <NEW_LINE> def __init__(self, member=None, group=None): <NEW_LINE> <INDENT> self._member = None <NEW_LINE> self._group = None <NEW_LINE> self.discriminator = None <NEW_LINE> if member is not None: <NEW_LINE> <INDENT> self.member = member <NEW_LINE> <DEDENT> if group is not None: <NEW_LINE> <INDENT> self.group = group <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def member(self): <NEW_LINE> <INDENT> return self._member <NEW_LINE> <DEDENT> @member.setter <NEW_LINE> def member(self, member): <NEW_LINE> <INDENT> self._member = member <NEW_LINE> <DEDENT> @property <NEW_LINE> def group(self): <NEW_LINE> <INDENT> return self._group <NEW_LINE> <DEDENT> @group.setter <NEW_LINE> def group(self, group): <NEW_LINE> <INDENT> self._group = group <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GroupsV2GroupPotentialMembership): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259905c2c8b7c6e89bd4e05 |
class TestPlotMultiFunctions(unittest.TestCase): <NEW_LINE> <INDENT> def test_plot_multi_functions(self): <NEW_LINE> <INDENT> functions = { "Gamma 2.2": lambda x: x ** (1 / 2.2), "Gamma 2.4": lambda x: x ** (1 / 2.4), "Gamma 2.6": lambda x: x ** (1 / 2.6), } <NEW_LINE> plot_kwargs = {"c": "r"} <NEW_LINE> figure, axes = plot_multi_functions(functions, plot_kwargs=plot_kwargs) <NEW_LINE> self.assertIsInstance(figure, Figure) <NEW_LINE> self.assertIsInstance(axes, Axes) <NEW_LINE> plot_kwargs = [{"c": "r"}, {"c": "g"}, {"c": "b"}] <NEW_LINE> figure, axes = plot_multi_functions( functions, log_x=10, log_y=10, plot_kwargs=plot_kwargs ) <NEW_LINE> self.assertIsInstance(figure, Figure) <NEW_LINE> self.assertIsInstance(axes, Axes) <NEW_LINE> figure, axes = plot_multi_functions(functions, log_x=10) <NEW_LINE> self.assertIsInstance(figure, Figure) <NEW_LINE> self.assertIsInstance(axes, Axes) <NEW_LINE> figure, axes = plot_multi_functions(functions, log_y=10) <NEW_LINE> self.assertIsInstance(figure, Figure) <NEW_LINE> self.assertIsInstance(axes, Axes) | Define :func:`colour.plotting.common.plot_multi_functions` definition unit
tests methods. | 6259905c3539df3088ecd8b3 |
class MyRobot(wpilib.TimedRobot): <NEW_LINE> <INDENT> def robotInit(self): <NEW_LINE> <INDENT> self.drive = wpilib.drive.DifferentialDrive(wpilib.Talon(0), wpilib.Talon(1)) <NEW_LINE> self.components = {"drive": self.drive} <NEW_LINE> self.automodes = AutonomousModeSelector("autonomous", self.components) <NEW_LINE> <DEDENT> def autonomousInit(self): <NEW_LINE> <INDENT> self.drive.setSafetyEnabled(True) <NEW_LINE> self.automodes.start() <NEW_LINE> <DEDENT> def autonomousPeriodic(self): <NEW_LINE> <INDENT> self.automodes.periodic() <NEW_LINE> <DEDENT> def disabledInit(self): <NEW_LINE> <INDENT> self.automodes.disable() <NEW_LINE> <DEDENT> def teleopInit(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def teleopPeriodic(self): <NEW_LINE> <INDENT> pass | This shows using the AutonomousModeSelector to automatically choose
autonomous modes.
If you find this useful, you may want to consider using the Magicbot
framework, as it already has this integrated into it. | 6259905ce76e3b2f99fda016 |
class Handler: <NEW_LINE> <INDENT> def callback(self, prefix, name, *args): <NEW_LINE> <INDENT> method = getattr(self, prefix+name, None) <NEW_LINE> if isinstance(method, collections.Callable): return method(*args) <NEW_LINE> <DEDENT> def start(self, name): <NEW_LINE> <INDENT> self.callback('start_', name) <NEW_LINE> <DEDENT> def end(self, name): <NEW_LINE> <INDENT> self.callback('end_', name) <NEW_LINE> <DEDENT> def sub(self, name): <NEW_LINE> <INDENT> def substitution(match): <NEW_LINE> <INDENT> result = self.callback('sub_', name, match) <NEW_LINE> if result is None: match.group(0) <NEW_LINE> return result <NEW_LINE> <DEDENT> return substitution | An object that handles method calls from the Parser.
The Parser will call the start() and end() methods at the
beginning of each block, with the proper block name as a
parameter. The sub() method will be used in regular expression
substitution. When called with a name such as 'emphasis', it will
return a proper substitution function. | 6259905c16aa5153ce401afb |
class Annotator(object): <NEW_LINE> <INDENT> def __init__(self, remove_types): <NEW_LINE> <INDENT> self.remove_list = remove_types <NEW_LINE> <DEDENT> def extract(self, i, doc, tags): <NEW_LINE> <INDENT> tag = [] <NEW_LINE> while doc[i] != '>': <NEW_LINE> <INDENT> tag.append(doc[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> tags.append(''.join(tag[1:])) <NEW_LINE> if doc[i] == '<': <NEW_LINE> <INDENT> return self.extract(i, doc, tags) <NEW_LINE> <DEDENT> return i, tags <NEW_LINE> <DEDENT> def extract2(self, i, doc, tags): <NEW_LINE> <INDENT> tag = [] <NEW_LINE> while doc[i] != '>': <NEW_LINE> <INDENT> tag.append(doc[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> tags.append(''.join(tag[1:])) <NEW_LINE> if doc[i:].startswith('</'): <NEW_LINE> <INDENT> return self.extract2(i, doc, tags) <NEW_LINE> <DEDENT> return i, tags <NEW_LINE> <DEDENT> def annotate(self, doc): <NEW_LINE> <INDENT> i, j = 0, 0 <NEW_LINE> text = [] <NEW_LINE> spans = [] <NEW_LINE> entities = [] <NEW_LINE> while i < len(doc): <NEW_LINE> <INDENT> if doc[i] == '<' and not doc[i:].startswith('</'): <NEW_LINE> <INDENT> i, tags = self.extract(i, doc, []) <NEW_LINE> j = i <NEW_LINE> <DEDENT> if doc[i:].startswith('</'): <NEW_LINE> <INDENT> entities.append(tags) <NEW_LINE> spans.append((len(text) - len(doc[j:i]), len(text))) <NEW_LINE> i, _ = self.extract2(i, doc, []) <NEW_LINE> continue <NEW_LINE> <DEDENT> text.append(doc[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> res = self._build_response(''.join(text), spans, entities) <NEW_LINE> return res <NEW_LINE> <DEDENT> def to_bio(self, html): <NEW_LINE> <INDENT> res = self.annotate(html) <NEW_LINE> text = res['text'] <NEW_LINE> entities = res['entities'] <NEW_LINE> tags = self._get_bio_tags(text, entities) <NEW_LINE> return text, tags <NEW_LINE> <DEDENT> def _get_bio_tags(self, text, entities): <NEW_LINE> <INDENT> tags = ['O'] * len(text) <NEW_LINE> for entity in entities: <NEW_LINE> <INDENT> begin_offset, end_offset = entity['beginOffset'], entity['endOffset'] <NEW_LINE> entity_type = entity['type'] <NEW_LINE> if entity_type in self.remove_list: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for i in range(begin_offset, end_offset): <NEW_LINE> <INDENT> tags[i] = 'I-{}'.format(entity_type) <NEW_LINE> <DEDENT> tags[begin_offset] = 'B-{}'.format(entity_type) <NEW_LINE> <DEDENT> return tags <NEW_LINE> <DEDENT> def _build_response(self, clean_text, spans, entity_types): <NEW_LINE> <INDENT> res = { 'text': clean_text, 'entities': [ ] } <NEW_LINE> for (begin_offset, end_offset), entity_type in zip(spans, entity_types): <NEW_LINE> <INDENT> entity = { 'entity': clean_text[begin_offset: end_offset], 'type': entity_type[0], 'beginOffset': begin_offset, 'endOffset': end_offset } <NEW_LINE> res['entities'].append(entity) <NEW_LINE> <DEDENT> return res | Annotates named-entity tag with Wikipedia text. | 6259905c7047854f463409d7 |
class MPUException(Exception): <NEW_LINE> <INDENT> def __init__(self, errString): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.errString = errString <NEW_LINE> <DEDENT> def ShowAndExit(self): <NEW_LINE> <INDENT> sys.stderr.write("mpu: Error: " + self.errString) <NEW_LINE> sys.exit(1) | Simple exception class for fatal errors. | 6259905c8e7ae83300eea6a5 |
class FileRequestError(GeneralFileRequestsError): <NEW_LINE> <INDENT> not_found = None <NEW_LINE> not_a_folder = None <NEW_LINE> app_lacks_access = None <NEW_LINE> no_permission = None <NEW_LINE> email_unverified = None <NEW_LINE> validation_error = None <NEW_LINE> def is_not_found(self): <NEW_LINE> <INDENT> return self._tag == 'not_found' <NEW_LINE> <DEDENT> def is_not_a_folder(self): <NEW_LINE> <INDENT> return self._tag == 'not_a_folder' <NEW_LINE> <DEDENT> def is_app_lacks_access(self): <NEW_LINE> <INDENT> return self._tag == 'app_lacks_access' <NEW_LINE> <DEDENT> def is_no_permission(self): <NEW_LINE> <INDENT> return self._tag == 'no_permission' <NEW_LINE> <DEDENT> def is_email_unverified(self): <NEW_LINE> <INDENT> return self._tag == 'email_unverified' <NEW_LINE> <DEDENT> def is_validation_error(self): <NEW_LINE> <INDENT> return self._tag == 'validation_error' <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(FileRequestError, self)._process_custom_annotations(annotation_type, field_path, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'FileRequestError(%r, %r)' % (self._tag, self._value) | There is an error with the file request.
This class acts as a tagged union. Only one of the ``is_*`` methods will
return true. To get the associated value of a tag (if one exists), use the
corresponding ``get_*`` method.
:ivar file_requests.FileRequestError.not_found: This file request ID was not
found.
:ivar file_requests.FileRequestError.not_a_folder: The specified path is not
a folder.
:ivar file_requests.FileRequestError.app_lacks_access: This file request is
not accessible to this app. Apps with the app folder permission can only
access file requests in their app folder.
:ivar file_requests.FileRequestError.no_permission: This user doesn't have
permission to access or modify this file request.
:ivar file_requests.FileRequestError.email_unverified: This user's email
address is not verified. File requests are only available on accounts
with a verified email address. Users can verify their email address
`here <https://www.dropbox.com/help/317>`_.
:ivar file_requests.FileRequestError.validation_error: There was an error
validating the request. For example, the title was invalid, or there
were disallowed characters in the destination path. | 6259905c55399d3f05627b37 |
class NBVAE(nn.Module): <NEW_LINE> <INDENT> NAME = "nbvae" <NEW_LINE> def __init__( self, *, n_input: int, n_latent: int, encoder_layers: Sequence[int], decoder_layers: Sequence[int] = None, lib_loc: float, lib_scale: float, scale_factor: float = 1.0, weight_scaling: bool = False, ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.encoder = Encoder(n_input, n_latent, encoder_layers, weight_scaling) <NEW_LINE> if decoder_layers is not None: <NEW_LINE> <INDENT> self.decoder = NBDecoder(n_latent, n_input, decoder_layers, weight_scaling) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.decoder = NBDecoder( n_latent, n_input, encoder_layers[::-1], weight_scaling ) <NEW_LINE> <DEDENT> self.register_buffer("lib_loc", torch.as_tensor(lib_loc)) <NEW_LINE> self.register_buffer("lib_scale", torch.full((1,), lib_scale)) <NEW_LINE> self.n_latent = n_latent <NEW_LINE> self.scale_factor = scale_factor <NEW_LINE> <DEDENT> def model(self, x: torch.Tensor): <NEW_LINE> <INDENT> pyro.module(self.NAME, self) <NEW_LINE> with pyro.plate("data", len(x)), poutine.scale(scale=self.scale_factor): <NEW_LINE> <INDENT> z = pyro.sample( "latent", dist.Normal(0, x.new_ones(self.n_latent)).to_event(1) ) <NEW_LINE> lib = pyro.sample( "library", dist.Normal(self.lib_loc, self.lib_scale).to_event(1) ) <NEW_LINE> log_r, logit = self.decoder(z, lib) <NEW_LINE> pyro.sample( "obs", dist.NegativeBinomial( total_count=torch.exp(log_r), logits=logit ).to_event(1), obs=x, ) <NEW_LINE> <DEDENT> return z <NEW_LINE> <DEDENT> def guide(self, x: torch.Tensor): <NEW_LINE> <INDENT> pyro.module(self.NAME, self) <NEW_LINE> with pyro.plate("data", len(x)), poutine.scale(scale=self.scale_factor): <NEW_LINE> <INDENT> z_loc, z_scale, l_loc, l_scale = self.encoder(x) <NEW_LINE> pyro.sample("latent", dist.Normal(z_loc, z_scale).to_event(1)) <NEW_LINE> pyro.sample("library", dist.Normal(l_loc, l_scale).to_event(1)) | Variational auto-encoder model with negative binomial loss.
:param n_input: Number of input genes
:param n_latent: Dimensionality of the latent space
:param encoder_layers: Number and size of hidden layers used for encoder NN
:param decoder_layers: Number of size of hidden layers for decoder NN.
If None, uses encoder_layers in reverse order
:param lib_loc: Mean for prior distribution on library scaling factor
:param lib_scale: Scale for prior distribution on library scaling factor
:param scale_factor: For adjusting the ELBO loss
:param weight_scaling: use Gamma ReLU and weight scaling for linear layers | 6259905c435de62698e9d41c |
class TestBuildUrlShowHide(unittest.TestCase): <NEW_LINE> <INDENT> def makeManageable(self, component='', delete=True, checkPermission=True): <NEW_LINE> <INDENT> from raptus.article.core.manageable import Manageable <NEW_LINE> context = mock.Mock(spec='absolute_url portal_membership'.split()) <NEW_LINE> context.absolute_url.return_value = 'http://test' <NEW_LINE> context.portal_membership.checkPermission.return_value = checkPermission <NEW_LINE> manageable = Manageable(context) <NEW_LINE> manageable.component = component <NEW_LINE> manageable.delete = delete <NEW_LINE> return manageable <NEW_LINE> <DEDENT> def test_component_not_set(self): <NEW_LINE> <INDENT> manageable = self.makeManageable() <NEW_LINE> self.assertEquals(None, manageable.build_url_show_hide(None, None, None)) <NEW_LINE> <DEDENT> def test_not_allowed(self): <NEW_LINE> <INDENT> manageable = self.makeManageable(component='foo', checkPermission=False) <NEW_LINE> brain = mock.Mock(spec='getObject'.split()) <NEW_LINE> self.assertEquals(None, manageable.build_url_show_hide(None, brain, None)) <NEW_LINE> <DEDENT> def test_already_shown(self): <NEW_LINE> <INDENT> manageable = self.makeManageable(component='foo') <NEW_LINE> brain = mock.Mock(spec='getObject'.split()) <NEW_LINE> self.assertEquals(None, manageable.build_url_show_hide(['foo', ], brain, 'show')) <NEW_LINE> <DEDENT> def test_already_hidden(self): <NEW_LINE> <INDENT> manageable = self.makeManageable(component='foo') <NEW_LINE> brain = mock.Mock(spec='getObject'.split()) <NEW_LINE> self.assertEquals(None, manageable.build_url_show_hide([], brain, 'hide')) | Test edge cases of Manageable.build_url_show_hide(). | 6259905c009cb60464d02b4e |
class UserSearchResultList(SearchResultList): <NEW_LINE> <INDENT> model = User <NEW_LINE> serializer_class = UserPublicOnlySerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> key = self.request.GET.get('q', '') <NEW_LINE> return User.objects.filter(Q(username__contains=key) | Q(moment__contains=key) | Q(name__contains=key)).all() <NEW_LINE> <DEDENT> def get_paginate_by(self): <NEW_LINE> <INDENT> count = self.get_queryset().count() <NEW_LINE> return count if (count > 0) else self.paginate_by | List results of search on users
## Reading
### Permissions
* Anyone can read this endpoint.
### Fields
Parameter | Description | Type
------------ | ----------------------------------- | ----------
`q` | A UTF-8, URL-encoded search query | _string_
### Response
Reading this endpoint returns an array of user objects containing only
public data.
## Publishing
You can't write using this endpoint
## Deleting
You can't delete using this endpoint
## Updating
You can't update using this endpoint | 6259905cfff4ab517ebcee3d |
class WSignalSource(WSignalSourceProto): <NEW_LINE> <INDENT> @verify_type('strict', signal_names=str) <NEW_LINE> def __init__(self, *signal_names): <NEW_LINE> <INDENT> WSignalSourceProto.__init__(self) <NEW_LINE> self.__signal_names = signal_names <NEW_LINE> self.__callbacks = {x: weakref.WeakSet() for x in signal_names} <NEW_LINE> <DEDENT> @verify_type('strict', signal_name=str) <NEW_LINE> def send_signal(self, signal_name, signal_args=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for callback in self.__callbacks[signal_name]: <NEW_LINE> <INDENT> if callback is not None: <NEW_LINE> <INDENT> callback(self, signal_name, signal_args) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise WUnknownSignalException('Unknown signal "%s"' % signal_name) <NEW_LINE> <DEDENT> <DEDENT> def signals(self): <NEW_LINE> <INDENT> return self.__signal_names <NEW_LINE> <DEDENT> @verify_type('strict', signal_name=str) <NEW_LINE> @verify_value('strict', callback=lambda x: callable(x)) <NEW_LINE> def callback(self, signal_name, callback): <NEW_LINE> <INDENT> self.__callbacks[signal_name].add(callback) <NEW_LINE> <DEDENT> @verify_type('strict', signal_name=str) <NEW_LINE> @verify_value('strict', callback=lambda x: callable(x)) <NEW_LINE> def remove_callback(self, signal_name, callback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__callbacks[signal_name].remove(callback) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError('Signal "%s" does not have the specified callback' % signal_name) | :class:`.WSignalSourceProto` implementation
| 6259905ce5267d203ee6cecc |
class RegisterUser(MethodView): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> if request.content_type == 'application/json': <NEW_LINE> <INDENT> post_data = request.get_json() <NEW_LINE> email = post_data.get('email') <NEW_LINE> password = post_data.get('password') <NEW_LINE> username = post_data.get('username') <NEW_LINE> if re.match(r"[^@]+@[^@]+\.[^@]+", email) and len(password) > 4 and len(username) > 3: <NEW_LINE> <INDENT> user = User.get_by_email(email) <NEW_LINE> if not user: <NEW_LINE> <INDENT> token = User(email=email, password=password, username=username).save() <NEW_LINE> return response_auth('success', 'Successfully registered', token, 201) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response('failed', 'Failed, User already exists, Please sign In', 400) <NEW_LINE> <DEDENT> <DEDENT> return response('failed', 'Missing or wrong email format or password is less than four characters', 400) <NEW_LINE> <DEDENT> return response('failed', 'Content-type must be json', 400) | View function to register a user via the api | 6259905c2ae34c7f260ac6ff |
class OpenAction (BaseAction): <NEW_LINE> <INDENT> stringId = u"OpenTree" <NEW_LINE> def __init__ (self, application): <NEW_LINE> <INDENT> self._application = application <NEW_LINE> <DEDENT> @property <NEW_LINE> def title (self): <NEW_LINE> <INDENT> return _(u"Open…") <NEW_LINE> <DEDENT> @property <NEW_LINE> def description (self): <NEW_LINE> <INDENT> return _(u"Open tree notes") <NEW_LINE> <DEDENT> def run (self, params): <NEW_LINE> <INDENT> openWikiWithDialog (self._application.mainWindow, False) | Открытие дерева заметок | 6259905c91af0d3eaad3b441 |
class ViewTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> self.job_data = { 'id': 1, 'name': 'Mock Job (1)', 'type': 'test', 'status': 'unknown', 'meta': {} } <NEW_LINE> self.response = self.client.post( reverse('create'), self.job_data, format="json") <NEW_LINE> <DEDENT> def test_api_can_create_a_job(self): <NEW_LINE> <INDENT> self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> def test_api_can_get_a_job(self): <NEW_LINE> <INDENT> job = Job.objects.get() <NEW_LINE> response = self.client.get( reverse('details', kwargs={'pk': job.id}), format="json") <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertContains(response, job) <NEW_LINE> <DEDENT> def test_api_can_update_job(self): <NEW_LINE> <INDENT> job = Job.objects.get() <NEW_LINE> change_job = { 'name': 'Mock Job (1)', 'type': 'test', 'status': 'unknown', 'meta': {} } <NEW_LINE> res = self.client.put( reverse('details', kwargs={'pk': job.id}), change_job, format='json' ) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_api_can_delete_job(self): <NEW_LINE> <INDENT> job = Job.objects.get() <NEW_LINE> response = self.client.delete( reverse('details', kwargs={'pk': job.id}), format='json', follow=True) <NEW_LINE> self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT) | Test suite for the api views. | 6259905c8a43f66fc4bf37a5 |
class DoctorModel(BaseModel): <NEW_LINE> <INDENT> email = CharField(max_length=100, unique=True) <NEW_LINE> first_name = CharField(max_length=100) <NEW_LINE> last_name = CharField(max_length=100) <NEW_LINE> qualification = CharField(max_length=100) <NEW_LINE> profession = CharField(max_length=100) <NEW_LINE> birth = CharField(max_length=100) <NEW_LINE> experience = IntegerField() <NEW_LINE> gender = CharField(max_length=10) <NEW_LINE> patients = TextField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> order_by = ('last_name',) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_by_dict(cls, post_data): <NEW_LINE> <INDENT> return DoctorModel.create( first_name=post_data.get('first_name'), last_name=post_data.get('last_name'), email=post_data.get('email', '{}@doctor.hms.com'.format( post_data.get('first_name')+post_data.get('last_name'))), qualification=post_data.get('qualification', 'q'), profession=post_data.get('profession', 'p'), birth=post_data.get('birth', ''), experience=int(post_data.get('experience', '0')), gender=post_data.get('gender', 'm'), patients=post_data.get('patients', '') ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_dict(cls, email): <NEW_LINE> <INDENT> logger.debug('in DoctorModel.get_dict ') <NEW_LINE> user_dict = {} <NEW_LINE> try: <NEW_LINE> <INDENT> user = DoctorModel.get(DoctorModel.email==email) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> logger.debug('in DoctorModel.get_dict exception, ', ex) <NEW_LINE> raise UserNotExistException() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user_dict['first_name'] = user.first_name <NEW_LINE> user_dict['last_name'] = user.last_name <NEW_LINE> user_dict['email'] = user.email <NEW_LINE> user_dict['qualification'] = user.qualification <NEW_LINE> user_dict['profession'] = user.profession <NEW_LINE> user_dict['birth'] = user.birth <NEW_LINE> user_dict['experience'] = str(user.experience) <NEW_LINE> user_dict['gender'] = user.gender <NEW_LINE> user_dict['patients'] = user.patients <NEW_LINE> logger.debug('after ger user: %s' % email) <NEW_LINE> return user_dict <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def update_by_dict(cls, email, post_data): <NEW_LINE> <INDENT> user = DoctorModel.get(DoctorModel.email==email) <NEW_LINE> with database.atomic(): <NEW_LINE> <INDENT> q = DoctorModel.update( first_name=post_data.get('first_name', user.first_name), last_name=post_data.get('last_name', user.last_name), qualification=post_data.get('qualification', user.qualification), profession=post_data.get('profession', user.profession), birth=post_data.get('birth', user.birth), experience=int(post_data.get('experience', user.experience)), gender=post_data.get('gender', user.gender), patients=post_data.get('patients', user.patients), ).where(DoctorModel.email==email) <NEW_LINE> q.execute() | {
'first_name':'',
'last_name':'',
'qualification':'',
'profession': 'xxx',
'experience':'',
'gender':'',
'schedule':'',
} | 6259905ca219f33f346c7e1e |
class RequestList(Resource): <NEW_LINE> <INDENT> @admin_required <NEW_LINE> def get(self): <NEW_LINE> <INDENT> result = models.Request.get_all_requests() <NEW_LINE> return result | Contains GET method to get all requests | 6259905c8e7ae83300eea6a6 |
class TestData75(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 testData75(self): <NEW_LINE> <INDENT> pass | Data75 unit test stubs | 6259905c01c39578d7f14243 |
class Hello(command.Command): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def command(self, message): <NEW_LINE> <INDENT> if message['type'] != 'message' or 'subtype' in message: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pieces = message['text'].split() <NEW_LINE> if not pieces or pieces[0] != "<@{0}>".format(UTILS['slack'].user['id']): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if pieces[1].lower() in ['hi', 'hello', 'heya', 'hihi']: <NEW_LINE> <INDENT> await UTILS['slack'].say(message['channel'], "{0}, <@{1}>!".format(pieces[1], message['user'])) | Simple command to showcase command structure/responses | 6259905c442bda511e95d866 |
class DammitLogger(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.log_dir = os.path.join(get_dammit_dir(), 'log') <NEW_LINE> try: <NEW_LINE> <INDENT> os.makedirs(self.log_dir) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.log_file = os.path.join(self.log_dir, 'dammit-all.log') <NEW_LINE> self.config = { 'format': '%(asctime)s %(name)s:%(funcName)s:%(lineno)d ' '[%(levelname)s] \n%(message)s\n-----', 'datefmt': '%m-%d %H:%M:%S', 'filename':self.log_file, 'filemode': 'a' } <NEW_LINE> self.logger = logging.getLogger(__name__) <NEW_LINE> noop = logging.NullHandler() <NEW_LINE> self.logger.addHandler(noop) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> logging.basicConfig(level=logging.DEBUG, **self.config) <NEW_LINE> self.console = logging.StreamHandler(sys.stderr) <NEW_LINE> self.console.setLevel(logging.INFO) <NEW_LINE> self.formatter = LogFormatter() <NEW_LINE> self.console.setFormatter(self.formatter) <NEW_LINE> logging.getLogger('').addHandler(self.console) <NEW_LINE> logging.getLogger('').debug('*** dammit! begin ***') | Set up logging for the dammit application. We insulate it
in a class to let us choose to only activate it when the program itself
is run, effectively keeping the tests and any use of the API from
being noisy. | 6259905c460517430c432b5f |
class MachineData: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'name', None, None, ), (2, TType.I32, 'port', None, None, ), ) <NEW_LINE> def __init__(self, name=None, port=None,): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.name = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.port = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('MachineData') <NEW_LINE> if self.name is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('name', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.name) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.port is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('port', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.port) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.name) <NEW_LINE> value = (value * 31) ^ hash(self.port) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- name
- port | 6259905c07f4c71912bb0a54 |
class _StructUnion(DeclNode): <NEW_LINE> <INDENT> def __init__(self, tag, members, r): <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> self.members = members <NEW_LINE> self.r = r <NEW_LINE> super().__init__() | Base class to represent a struct or a union C type.
tag (Token) - Token containing the tag of this struct
members (List(Node)) - List of decl_nodes nodes of members, or None
r (Range) - range that the specifier covers | 6259905c56b00c62f0fb3ee4 |
class Table(tablib.Dataset): <NEW_LINE> <INDENT> def __init__(self, fields, process_data, *args, **kwargs): <NEW_LINE> <INDENT> super(Table, self).__init__(*args, **kwargs) <NEW_LINE> self.fields = fields <NEW_LINE> self._process_data = types.MethodType(process_data, self, Table) <NEW_LINE> self.headers = [f.header for f in self.fields] <NEW_LINE> <DEDENT> def process_data(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._process_data(*args, **kwargs) | A extension of `tablib.Dataset` that has fields' slugs and HTML classes,
and processes data that it is fed through a function provided at
initialization. | 6259905c63b5f9789fe8678b |
class TokenAuthMiddleware: <NEW_LINE> <INDENT> def __init__(self, inner): <NEW_LINE> <INDENT> self.inner = inner <NEW_LINE> <DEDENT> def __call__(self, scope): <NEW_LINE> <INDENT> user = None <NEW_LINE> database_sync_to_async(close_old_connections)() <NEW_LINE> parsed_qs = parse_qs(scope["query_string"].decode("utf8")) <NEW_LINE> if parsed_qs: <NEW_LINE> <INDENT> token = parsed_qs["token"][0] <NEW_LINE> try: <NEW_LINE> <INDENT> UntypedToken(token) <NEW_LINE> <DEDENT> except (InvalidToken, TokenError) as e: <NEW_LINE> <INDENT> return self.inner(dict(scope, user=user)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"]) <NEW_LINE> user = database_sync_to_async(User.objects.get)( id=decoded_data["user_id"] ) <NEW_LINE> <DEDENT> <DEDENT> return self.inner(dict(scope, user=user)) | Custom token auth middleware | 6259905c3617ad0b5ee07764 |
class UserRegisterSchema(ResponsesSchema): <NEW_LINE> <INDENT> status_descriptions_create = { '201': _('Пользователь создан'), } <NEW_LINE> def get_status_descriptions(self, has_body=False, *args, **kwargs): <NEW_LINE> <INDENT> results = super().get_status_descriptions(has_body, *args, **kwargs) <NEW_LINE> if self.view.action == 'create': <NEW_LINE> <INDENT> results.update(self.status_descriptions_create) <NEW_LINE> <DEDENT> return results | Класс документирует user-register и partner-register
(добавляет статус коды в openapi документацию) | 6259905c7047854f463409d9 |
class IBrowserView(IView): <NEW_LINE> <INDENT> pass | Views which are specialized for requests from a browser
o Such views are distinct from those geerated via WebDAV, FTP, XML-RPC,
etc.. | 6259905c99cbb53fe68324f9 |
class SceneOperation(HookClass): <NEW_LINE> <INDENT> def execute(self, operation, file_path, context, parent_action, file_version, read_only, **kwargs): <NEW_LINE> <INDENT> if operation == "current_path": <NEW_LINE> <INDENT> file_path = MaxPlus.FileManager.GetFileNameAndPath() <NEW_LINE> if not file_path: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return file_path <NEW_LINE> <DEDENT> elif operation == "open": <NEW_LINE> <INDENT> MaxPlus.FileManager.Open(file_path) <NEW_LINE> <DEDENT> elif operation == "save": <NEW_LINE> <INDENT> MaxPlus.FileManager.Save() <NEW_LINE> <DEDENT> elif operation == "save_as": <NEW_LINE> <INDENT> MaxPlus.FileManager.Save(file_path) <NEW_LINE> <DEDENT> elif operation == "reset": <NEW_LINE> <INDENT> MaxPlus.FileManager.Reset(True) <NEW_LINE> return True | Hook called to perform an operation with the current scene | 6259905c67a9b606de5475ae |
class Z2UnicodeEncodingConflictResolver: <NEW_LINE> <INDENT> implements(IUnicodeEncodingConflictResolver) <NEW_LINE> def __init__(self, mode='strict'): <NEW_LINE> <INDENT> self.mode = mode <NEW_LINE> <DEDENT> def resolve(self, context, text, expression): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return unicode(text) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> encoding = getattr(context, 'management_page_charset', default_encoding) <NEW_LINE> try: <NEW_LINE> <INDENT> return unicode(text, encoding, self.mode) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> return unicode(text, 'iso-8859-15', self.mode) | This resolver tries to lookup the encoding from the
'management_page_charset' property and defaults to
sys.getdefaultencoding(). | 6259905cd53ae8145f919a7c |
class Update(models.Model): <NEW_LINE> <INDENT> UPDATE_STATUS = ( (Status.PENDING, "Pending"), (Status.STARTED, "Started"), (Status.RUNNING, "Running"), (Status.ABORTED, "Aborted"), (Status.SUCCESS, "Success"), (Status.FAILED, "Failed"), (Status.WAITING, "Waiting"), (Status.REJECTED, "Rejected"), ) <NEW_LINE> upd_vehicle = models.ForeignKey(Vehicle, verbose_name='Vehicle') <NEW_LINE> upd_package = models.ForeignKey(Package, verbose_name='Package') <NEW_LINE> upd_status = models.CharField('Update Status', max_length=2, choices=UPDATE_STATUS, default=Status.PENDING) <NEW_LINE> upd_timeout = models.DateTimeField('Valid Until') <NEW_LINE> upd_retries = models.IntegerField('Maximum Retries', validators=[validate_upd_retries], default="0") <NEW_LINE> @property <NEW_LINE> def upd_status_text(self): <NEW_LINE> <INDENT> return dict(self.UPDATE_STATUS)[self.upd_status] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.update_name() <NEW_LINE> <DEDENT> def update_name(self): <NEW_LINE> <INDENT> return ("'" + self.upd_package.get_name() + "' on '" + self.upd_vehicle.get_name() + "'" ) <NEW_LINE> <DEDENT> def not_expired(self): <NEW_LINE> <INDENT> return (timezone.now() <= self.upd_timeout) <NEW_LINE> <DEDENT> not_expired.short_description = 'Not Expired' <NEW_LINE> not_expired.admin_order_field = 'udp_timeout' <NEW_LINE> not_expired.boolean = True <NEW_LINE> def retry_count(self): <NEW_LINE> <INDENT> return Retry.objects.filter(ret_update=self).count() <NEW_LINE> <DEDENT> retry_count.short_description = "Retry Count" <NEW_LINE> def active_retries(self): <NEW_LINE> <INDENT> return Retry.objects.filter(ret_update=self, ret_status=(Status.PENDING or Status.STARTED or Status.RUNNING or Status.WAITING) ) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.upd_status in [Status.PENDING, Status.ABORTED, Status.FAILED]: <NEW_LINE> <INDENT> retry = Retry(ret_update=self, ret_start=timezone.now(), ret_timeout=self.upd_timeout, ret_status=Status.PENDING ) <NEW_LINE> retry.save() <NEW_LINE> self.upd_status = Status.STARTED <NEW_LINE> self.save() <NEW_LINE> notify_update(retry) <NEW_LINE> return retry <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def abort(self): <NEW_LINE> <INDENT> if self.upd_status in [Status.STARTED, Status.RUNNING, Status.WAITING]: <NEW_LINE> <INDENT> retries = self.active_retries() <NEW_LINE> retry = None <NEW_LINE> if retries: <NEW_LINE> <INDENT> retry = retries[0] <NEW_LINE> retry.set_status(Status.ABORTED) <NEW_LINE> <DEDENT> self.set_status(Status.ABORTED) <NEW_LINE> return retry <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def delete(self): <NEW_LINE> <INDENT> if not self.upd_status in [Status.STARTED, Status.RUNNING, Status.WAITING]: <NEW_LINE> <INDENT> super(Update, self).delete() <NEW_LINE> <DEDENT> <DEDENT> def set_status(self, status): <NEW_LINE> <INDENT> self.upd_status = status <NEW_LINE> self.save() | Update description
An Update is defined by a vehicle and a software package that to
be sent to that vehicle. | 6259905cb5575c28eb7137d9 |
class ProgressBar: <NEW_LINE> <INDENT> BAR = '${GREEN}[${BOLD}%s%s${NORMAL}${GREEN}]${NORMAL} %3d%%\n' <NEW_LINE> HEADER = '${BOLD}${CYAN}%s${NORMAL}\n\n' <NEW_LINE> simple = False <NEW_LINE> def __init__(self, term, header): <NEW_LINE> <INDENT> self.term = term <NEW_LINE> if not (self.term.CLEAR_EOL and self.term.UP and self.term.BOL): <NEW_LINE> <INDENT> self.simple = True <NEW_LINE> print(header, end='') <NEW_LINE> return <NEW_LINE> <DEDENT> self.width = self.term.COLS or 75 <NEW_LINE> self.bar = term.render(self.BAR) <NEW_LINE> self.header = self.term.render(self.HEADER % header.center(self.width)) <NEW_LINE> self.cleared = 1 <NEW_LINE> self.update(0, '') <NEW_LINE> <DEDENT> def update(self, percent, message): <NEW_LINE> <INDENT> if self.simple: <NEW_LINE> <INDENT> print('.', end='') <NEW_LINE> return <NEW_LINE> <DEDENT> self.width = self.term.COLS <NEW_LINE> if self.cleared: <NEW_LINE> <INDENT> sys.stdout.write(self.header) <NEW_LINE> self.cleared = 0 <NEW_LINE> <DEDENT> n = int((self.width-10)*percent) <NEW_LINE> sys.stdout.write( self.term.BOL + self.term.UP + self.term.CLEAR_EOL + (self.bar % ('='*n, '-'*(self.width-10-n), 100*percent)) + self.term.CLEAR_EOL + message.center(self.width)) <NEW_LINE> def clear(self): <NEW_LINE> <INDENT> if not self.cleared: <NEW_LINE> <INDENT> sys.stdout.write(self.term.BOL + self.term.CLEAR_EOL + self.term.UP + self.term.CLEAR_EOL + self.term.UP + self.term.CLEAR_EOL) <NEW_LINE> self.cleared = 1 | A 3-line progress bar, which looks like::
Header
20% [===========----------------------------------]
progress message
The progress bar is colored, if the terminal supports color
output; and adjusts to the width of the terminal. | 6259905c32920d7e50bc7660 |
class ConvertFiguresTransformer(Transformer): <NEW_LINE> <INDENT> from_format = Unicode(config=True, help='Format the converter accepts') <NEW_LINE> to_format = Unicode(config=True, help='Format the converter writes') <NEW_LINE> def __init__(self, **kw): <NEW_LINE> <INDENT> super(ConvertFiguresTransformer, self).__init__(**kw) <NEW_LINE> <DEDENT> def convert_figure(self, data_format, data): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def transform_cell(self, cell, resources, cell_index): <NEW_LINE> <INDENT> for index, cell_out in enumerate(cell.get('outputs', [])): <NEW_LINE> <INDENT> for data_type, data in list(cell_out.items()): <NEW_LINE> <INDENT> self._convert_figure(cell_out, resources, data_type, data) <NEW_LINE> <DEDENT> <DEDENT> return cell, resources <NEW_LINE> <DEDENT> def _convert_figure(self, cell_out, resources, data_type, data): <NEW_LINE> <INDENT> if not self.to_format in cell_out and data_type == self.from_format: <NEW_LINE> <INDENT> data = self.convert_figure(data_type, data) <NEW_LINE> cell_out[self.to_format] = data | Converts all of the outputs in a notebook from one format to another. | 6259905cb57a9660fecd3095 |
class PacketCaptureListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[PacketCaptureResult]'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["PacketCaptureResult"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(PacketCaptureListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value | List of packet capture sessions.
:param value: Information about packet capture sessions.
:type value: list[~azure.mgmt.network.v2020_06_01.models.PacketCaptureResult] | 6259905c2ae34c7f260ac701 |
class AbstractClient(Producer): <NEW_LINE> <INDENT> ONE_TIME_EVENTS = ('finish',) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> __str__ = __repr__ <NEW_LINE> def connect(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return self.fire_event('finish') <NEW_LINE> <DEDENT> abort = close <NEW_LINE> def create_connection(self, address, protocol_factory=None, **kw): <NEW_LINE> <INDENT> protocol_factory = protocol_factory or self.create_protocol <NEW_LINE> if isinstance(address, tuple): <NEW_LINE> <INDENT> host, port = address <NEW_LINE> _, protocol = yield self._loop.create_connection( protocol_factory, host, port, **kw) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError('Could not connect to %s' % str(address)) <NEW_LINE> <DEDENT> coroutine_return(protocol) | A :class:`.Producer` for a client connections.
| 6259905c91af0d3eaad3b442 |
class ThemePlan(AttestationModel): <NEW_LINE> <INDENT> __tablename__ = 'theme_plan' <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> period_id = Column(ForeignKey(f'period.id')) <NEW_LINE> start_date = Column(DateTime(True), nullable=False) <NEW_LINE> end_date = Column(DateTime(True), nullable=False) <NEW_LINE> order_number = Column(String(100), nullable=False) <NEW_LINE> order_date = Column(DateTime(True), nullable=False) <NEW_LINE> small_division = Column(Boolean, nullable=False) | Тематический план
task: https://jira.it2g.ru/browse/KISUSS-913
subtask: https://jira.it2g.ru/browse/KISUSS-1047 | 6259905c23e79379d538db16 |
class case_01(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.driver = webdriver.Chrome() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls.driver.quit() <NEW_LINE> <DEDENT> def add_img(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.imgs = [] <NEW_LINE> self.addCleanup(self.cleanup) <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_case1(self): <NEW_LINE> <INDENT> print("本次校验没过?") <NEW_LINE> self.driver.get("https://www.baidu.com") <NEW_LINE> self.add_img() <NEW_LINE> self.driver.find_element_by_id('kw').send_keys(u'CSDN') <NEW_LINE> self.add_img() <NEW_LINE> self.driver.find_element_by_id('su').click() <NEW_LINE> time.sleep(1) <NEW_LINE> self.add_img() <NEW_LINE> <DEDENT> def test_case2(self): <NEW_LINE> <INDENT> self.driver.get("https://www.csdn.net") <NEW_LINE> print("本次校验没过?") <NEW_LINE> self.assertTrue(False,"这是相当的OK") <NEW_LINE> <DEDENT> def test_case3(self): <NEW_LINE> <INDENT> self.driver.get("https://www.runoob.com/python/python-tutorial.html") <NEW_LINE> print("没法打印?") <NEW_LINE> self.assertIn(u"中文", u'菜鸟','WYZ') <NEW_LINE> <DEDENT> def test_case4(self): <NEW_LINE> <INDENT> self.driver.get("https://www.runoob.com") <NEW_LINE> raise Exception <NEW_LINE> self.add_img() <NEW_LINE> self.assertTrue(True) | def setUp(cls):
cls.driver = webdriver.Chrome()
def tearDown(cls):
cls.driver.quit()
| 6259905c3d592f4c4edbc4f7 |
@admin.register(UserProfile) <NEW_LINE> class UserProfileAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = 'user', <NEW_LINE> def get_queryset(self, request): <NEW_LINE> <INDENT> return super().get_queryset(request).select_related('user') | UserProfile admin. | 6259905c8e71fb1e983bd0e5 |
class GenericTable(AppendableFrameTable): <NEW_LINE> <INDENT> pandas_kind = "frame_table" <NEW_LINE> table_type = "generic_table" <NEW_LINE> ndim = 2 <NEW_LINE> obj_type = DataFrame <NEW_LINE> levels: list[Hashable] <NEW_LINE> @property <NEW_LINE> def pandas_type(self) -> str: <NEW_LINE> <INDENT> return self.pandas_kind <NEW_LINE> <DEDENT> @property <NEW_LINE> def storable(self): <NEW_LINE> <INDENT> return getattr(self.group, "table", None) or self.group <NEW_LINE> <DEDENT> def get_attrs(self): <NEW_LINE> <INDENT> self.non_index_axes = [] <NEW_LINE> self.nan_rep = None <NEW_LINE> self.levels = [] <NEW_LINE> self.index_axes = [a for a in self.indexables if a.is_an_indexable] <NEW_LINE> self.values_axes = [a for a in self.indexables if not a.is_an_indexable] <NEW_LINE> self.data_columns = [a.name for a in self.values_axes] <NEW_LINE> <DEDENT> @cache_readonly <NEW_LINE> def indexables(self): <NEW_LINE> <INDENT> d = self.description <NEW_LINE> md = self.read_metadata("index") <NEW_LINE> meta = "category" if md is not None else None <NEW_LINE> index_col = GenericIndexCol( name="index", axis=0, table=self.table, meta=meta, metadata=md ) <NEW_LINE> _indexables: list[GenericIndexCol | GenericDataIndexableCol] = [index_col] <NEW_LINE> for i, n in enumerate(d._v_names): <NEW_LINE> <INDENT> assert isinstance(n, str) <NEW_LINE> atom = getattr(d, n) <NEW_LINE> md = self.read_metadata(n) <NEW_LINE> meta = "category" if md is not None else None <NEW_LINE> dc = GenericDataIndexableCol( name=n, pos=i, values=[n], typ=atom, table=self.table, meta=meta, metadata=md, ) <NEW_LINE> _indexables.append(dc) <NEW_LINE> <DEDENT> return _indexables <NEW_LINE> <DEDENT> def write(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError("cannot write on an generic table") | a table that read/writes the generic pytables table format | 6259905c4f6381625f199faf |
class Slice(Delegate): <NEW_LINE> <INDENT> defaults = manager.Defaults( ("width", 256, "Slice width"), ("side", "left", "Side of the slice (left, right, top, bottom)"), ("name", "max", "Name of this layout."), ) <NEW_LINE> def __init__(self, side, width, wname=None, wmclass=None, role=None, fallback=Max(), **config): <NEW_LINE> <INDENT> self.match = { 'wname': wname, 'wmclass': wmclass, 'role': role, } <NEW_LINE> Delegate.__init__(self, width=width, side=side, **config) <NEW_LINE> self._slice = Single() <NEW_LINE> self._fallback = fallback <NEW_LINE> <DEDENT> def clone(self, group): <NEW_LINE> <INDENT> res = Layout.clone(self, group) <NEW_LINE> res._slice = self._slice.clone(group) <NEW_LINE> res._fallback = self._fallback.clone(group) <NEW_LINE> res._window = None <NEW_LINE> return res <NEW_LINE> <DEDENT> def layout(self, windows, screen): <NEW_LINE> <INDENT> if self.side == 'left': <NEW_LINE> <INDENT> win, sub = screen.hsplit(self.width) <NEW_LINE> <DEDENT> elif self.side == 'right': <NEW_LINE> <INDENT> sub, win = screen.hsplit(screen.width - self.width) <NEW_LINE> <DEDENT> elif self.side == 'top': <NEW_LINE> <INDENT> win, sub = screen.vsplit(self.width) <NEW_LINE> <DEDENT> elif self.side == 'bottom': <NEW_LINE> <INDENT> sub, win = screen.vsplit(screen.height - self.width) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError(self.side) <NEW_LINE> <DEDENT> self.delegate_layout(windows, { self._slice: win, self._fallback: sub, }) <NEW_LINE> <DEDENT> def configure(self, win, screen): <NEW_LINE> <INDENT> raise NotImplementedError("Should not be called") <NEW_LINE> <DEDENT> def _get_layouts(self): <NEW_LINE> <INDENT> return self._slice, self._fallback <NEW_LINE> <DEDENT> def _get_active_layout(self): <NEW_LINE> <INDENT> return self._fallback <NEW_LINE> <DEDENT> def add(self, win): <NEW_LINE> <INDENT> if self._slice.empty() and win.match(**self.match): <NEW_LINE> <INDENT> self._slice.add(win) <NEW_LINE> self.layouts[win] = self._slice <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fallback.add(win) <NEW_LINE> self.layouts[win] = self._fallback | Slice layout
This layout cuts piece of screen and places a single window on that piece,
and delegates other window placement to other layout | 6259905c8e7ae83300eea6a8 |
class GoogleFinanceSource(): <NEW_LINE> <INDENT> _DATA_SOURCE = 'google' <NEW_LINE> def __init__(self, ticker): <NEW_LINE> <INDENT> self.ticker = ticker <NEW_LINE> <DEDENT> def get_stock_historical_prices(self, start_date, end_date): <NEW_LINE> <INDENT> return web.DataReader(self.ticker, self._DATA_SOURCE, start_date, end_date) | Google Finance source | 6259905c627d3e7fe0e084a6 |
class Access_Id(Base): <NEW_LINE> <INDENT> subclass_names = ['Use_Name', 'Generic_Spec'] | :F03R:`519`::
<access-id> = <use-name>
| <generic-spec>
| 6259905c01c39578d7f14244 |
class AttributeDescriptor(Descriptor): <NEW_LINE> <INDENT> __slots__ = ("_name", "_doc") <NEW_LINE> def __init__(self, name, doc=None): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._doc = doc <NEW_LINE> <DEDENT> def key(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def doc(self, obj): <NEW_LINE> <INDENT> return self._doc <NEW_LINE> <DEDENT> def attrtype(self, obj): <NEW_LINE> <INDENT> return "attr" <NEW_LINE> <DEDENT> def valuetype(self, obj): <NEW_LINE> <INDENT> return type(getattr(obj, self._name)) <NEW_LINE> <DEDENT> def value(self, obj): <NEW_LINE> <INDENT> return getattr(obj, self._name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self._doc is None: <NEW_LINE> <INDENT> return "Attribute(%r)" % self._name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Attribute(%r, %r)" % (self._name, self._doc) | An ``AttributeDescriptor`` describes a simple attribute of an object. | 6259905c460517430c432b60 |
class SomaFlowPlugin(GraphPluginBase): <NEW_LINE> <INDENT> def __init__(self, plugin_args=None): <NEW_LINE> <INDENT> if soma_not_loaded: <NEW_LINE> <INDENT> raise ImportError('SomaFlow could not be imported') <NEW_LINE> <DEDENT> super(SomaFlowPlugin, self).__init__(plugin_args=plugin_args) <NEW_LINE> <DEDENT> def _submit_graph(self, pyfiles, dependencies, nodes): <NEW_LINE> <INDENT> jobs = [] <NEW_LINE> soma_deps = [] <NEW_LINE> for idx, fname in enumerate(pyfiles): <NEW_LINE> <INDENT> name = os.path.splitext(os.path.split(fname)[1])[0] <NEW_LINE> jobs.append(Job(command=[sys.executable, fname], name=name)) <NEW_LINE> <DEDENT> for key, values in dependencies.items(): <NEW_LINE> <INDENT> for val in values: <NEW_LINE> <INDENT> soma_deps.append((jobs[val], jobs[key])) <NEW_LINE> <DEDENT> <DEDENT> wf = Workflow(jobs, soma_deps) <NEW_LINE> logger.info('serializing workflow') <NEW_LINE> Helper.serialize('workflow', wf) <NEW_LINE> controller = WorkflowController() <NEW_LINE> logger.info('submitting workflow') <NEW_LINE> wf_id = controller.submit_workflow(wf) <NEW_LINE> Helper.wait_workflow(wf_id, controller) | Execute using Soma workflow
| 6259905c07f4c71912bb0a56 |
class Test(unittest.TestCase): <NEW_LINE> <INDENT> def test_run_all(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> work_dir = os.getcwd() <NEW_LINE> os.chdir(EXAMPLES_DIR) <NEW_LINE> self._run_all_examples() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.chdir(work_dir) <NEW_LINE> <DEDENT> <DEDENT> def _run_all_examples(self): <NEW_LINE> <INDENT> for name in os.listdir('.'): <NEW_LINE> <INDENT> if name.endswith(".rml"): <NEW_LINE> <INDENT> path = name <NEW_LINE> print('running: {}'.format(path)) <NEW_LINE> output = trml2pdf.parseString(text_type(open(path, "r").read())) <NEW_LINE> self.assertIsNotNone(output) | run pdf genration using all files in examples. | 6259905c3617ad0b5ee07766 |
class RedisCacheStore(BaseCacheStore): <NEW_LINE> <INDENT> def __init__(self, redis_connection=None, **kwargs): <NEW_LINE> <INDENT> super(RedisCacheStore, self).__init__(**kwargs) <NEW_LINE> self._cache_store = redis_connection <NEW_LINE> <DEDENT> def save(self, key, data, expire=None): <NEW_LINE> <INDENT> pipe = self._cache_store.pipeline() <NEW_LINE> pipe.set(key, data) <NEW_LINE> if expire: <NEW_LINE> <INDENT> expire_seconds = expire - time.time() <NEW_LINE> assert(expire_seconds > 0) <NEW_LINE> pipe.expire(key, int(expire_seconds)) <NEW_LINE> <DEDENT> pipe.execute() <NEW_LINE> <DEDENT> def load(self, key): <NEW_LINE> <INDENT> return self._cache_store.get(key) <NEW_LINE> <DEDENT> def delete(self, key): <NEW_LINE> <INDENT> self._cache_store.delete(key) <NEW_LINE> <DEDENT> def delete_expired(self): <NEW_LINE> <INDENT> raise NotImplementedError | Redis cache using Redis' EXPIRE command to set
expiration time. `delete_expired` raises NotImplementedError.
Pass the Redis connection instance as `db_conn`.
##################
IMPORTANT NOTE:
This caching store uses a flat namespace for storing keys since
we cannot set an EXPIRE for a hash `field`. Use different
Redis databases to keep applications from overwriting
keys of other applications.
##################
The Redis connection uses the redis-py api located here:
https://github.com/andymccurdy/redis-py | 6259905cd486a94d0ba2d5e3 |
class SilentLogger(): <NEW_LINE> <INDENT> def debug(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def warning(self, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def error(self, msg): <NEW_LINE> <INDENT> pass | A logger for YouTube-DL that doesn't actually log anything. | 6259905cbaa26c4b54d508c1 |
class SimContext(InstanceContext): <NEW_LINE> <INDENT> def __init__(self, version, sid): <NEW_LINE> <INDENT> super(SimContext, self).__init__(version) <NEW_LINE> self._solution = {'sid': sid, } <NEW_LINE> self._uri = '/Sims/{sid}'.format(**self._solution) <NEW_LINE> self._billing_periods = None <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> payload = self._version.fetch(method='GET', uri=self._uri, ) <NEW_LINE> return SimInstance(self._version, payload, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> def update(self, unique_name=values.unset, status=values.unset, fleet=values.unset, callback_url=values.unset, callback_method=values.unset, account_sid=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'UniqueName': unique_name, 'Status': status, 'Fleet': fleet, 'CallbackUrl': callback_url, 'CallbackMethod': callback_method, 'AccountSid': account_sid, }) <NEW_LINE> payload = self._version.update(method='POST', uri=self._uri, data=data, ) <NEW_LINE> return SimInstance(self._version, payload, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def billing_periods(self): <NEW_LINE> <INDENT> if self._billing_periods is None: <NEW_LINE> <INDENT> self._billing_periods = BillingPeriodList(self._version, sim_sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._billing_periods <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Supersim.V1.SimContext {}>'.format(context) | PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. | 6259905c99cbb53fe68324fc |
class LoggerDependency: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.logger: Optional[BoundLogger] = None <NEW_LINE> <DEDENT> async def __call__(self, request: Request) -> BoundLogger: <NEW_LINE> <INDENT> if not self.logger: <NEW_LINE> <INDENT> self.logger = structlog.get_logger(logging.logger_name) <NEW_LINE> <DEDENT> assert self.logger <NEW_LINE> request_data = { "requestMethod": request.method, "requestUrl": str(request.url), "remoteIp": request.client.host, } <NEW_LINE> user_agent = request.headers.get("User-Agent") <NEW_LINE> if user_agent: <NEW_LINE> <INDENT> request_data["userAgent"] = user_agent <NEW_LINE> <DEDENT> logger = self.logger.new( httpRequest=request_data, request_id=str(uuid.uuid4()), ) <NEW_LINE> return logger | Provides a structlog logger configured with request information.
The following additional information will be included:
* A UUID for the request
* The method and URL of the request
* The IP address of the client
* The ``User-Agent`` header of the request, if any.
The last three pieces of information will be added using naming consistent
with the expectations of Google Log Explorer so that the request
information will be liftedn into the appropriate JSON fields for complex
log queries. | 6259905c7047854f463409dc |
class TrackerAlleles( VariantsTracker ): <NEW_LINE> <INDENT> pattern = "(.*)_alleles_genes$" | default tracker for allele analysis. | 6259905c435de62698e9d420 |
class LOE_076: <NEW_LINE> <INDENT> play = GenericChoice(CONTROLLER, RandomBasicHeroPower() * 3) | Sir Finley Mrrgglton | 6259905c1f037a2d8b9e5379 |
class LstsqL2nz(_LstsqL2Solver): <NEW_LINE> <INDENT> def __call__(self, A, Y, rng=None, E=None): <NEW_LINE> <INDENT> sigma = (self.reg * A.max()) * np.sqrt((A > 0).mean(axis=0)) <NEW_LINE> sigma[sigma == 0] = sigma.max() <NEW_LINE> X, info = self.solver(A, Y, sigma, **self.kwargs) <NEW_LINE> return self.mul_encoders(X, E), info | Least-squares with L2 regularization on non-zero components. | 6259905c30dc7b76659a0d8e |
class DNNClassifier(estimator.Estimator): <NEW_LINE> <INDENT> def __init__(self, hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None, label_vocabulary=None, optimizer='Adagrad', activation_fn=nn.relu, dropout=None, input_layer_partitioner=None, config=None): <NEW_LINE> <INDENT> if n_classes == 2: <NEW_LINE> <INDENT> head = head_lib._binary_logistic_head_with_sigmoid_cross_entropy_loss( weight_column=weight_column, label_vocabulary=label_vocabulary) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> head = head_lib._multi_class_head_with_softmax_cross_entropy_loss( n_classes, weight_column=weight_column, label_vocabulary=label_vocabulary) <NEW_LINE> <DEDENT> def _model_fn(features, labels, mode, config): <NEW_LINE> <INDENT> return _dnn_model_fn( features=features, labels=labels, mode=mode, head=head, hidden_units=hidden_units, feature_columns=tuple(feature_columns or []), optimizer=optimizer, activation_fn=activation_fn, dropout=dropout, input_layer_partitioner=input_layer_partitioner, config=config) <NEW_LINE> <DEDENT> super(DNNClassifier, self).__init__( model_fn=_model_fn, model_dir=model_dir, config=config) | A classifier for TensorFlow DNN models.
Example:
```python
sparse_feature_a = sparse_column_with_hash_bucket(...)
sparse_feature_b = sparse_column_with_hash_bucket(...)
sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a,
...)
sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b,
...)
estimator = DNNClassifier(
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = DNNClassifier(
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Input builders
def input_fn_train: # returns x, y
pass
estimator.train(input_fn=input_fn_train, steps=100)
def input_fn_eval: # returns x, y
pass
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
def input_fn_predict: # returns x, None
pass
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features,
otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with
`key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
- if `column` is a `_CategoricalColumn`, a feature with `key=column.name`
whose `value` is a `SparseTensor`.
- if `column` is a `_WeightedCategoricalColumn`, two features: the first
with `key` the id column name, the second with `key` the weight column
name. Both features' `value` must be a `SparseTensor`.
- if `column` is a `_DenseColumn`, a feature with `key=column.name`
whose `value` is a `Tensor`.
Loss is calculated by using softmax cross entropy. | 6259905ca8ecb03325872833 |
class AlexaInterfaceEnum(str, Enum): <NEW_LINE> <INDENT> BrightnessController = "Alexa.BrightnessController" <NEW_LINE> ColorController = "Alexa.ColorController" <NEW_LINE> ColorTemperatureController = "Alexa.ColorTemperatureController" <NEW_LINE> Cooking = "Alexa.Cooking" <NEW_LINE> EndpointHealth = "Alexa.EndpointHealth" <NEW_LINE> FoodTemperatureController = "Alexa.FoodTemperatureController" <NEW_LINE> FoodTemperatureSensor = "Alexa.FoodTemperatureSensor" <NEW_LINE> InventoryLevelSensor = "Alexa.InventoryLevelSensor" <NEW_LINE> InventoryUsageSensor = "Alexa.InventoryUsageSensor" <NEW_LINE> ModeController = "Alexa.ModeController" <NEW_LINE> PercentageController = "Alexa.PercentageController" <NEW_LINE> PowerController = "Alexa.PowerController" <NEW_LINE> PowerLevelController = "Alexa.PowerLevelController" <NEW_LINE> PresetController = "Alexa.PresetController" <NEW_LINE> RangeController = "Alexa.RangeController" <NEW_LINE> SceneController = "Alexa.SceneController" <NEW_LINE> TemperatureController = "Alexa.TemperatureController" <NEW_LINE> TemperatureSensor = "Alexa.TemperatureSensor" <NEW_LINE> ThermostatController = "Alexa.ThermostatController" <NEW_LINE> TimeController = "Alexa.TimeController" <NEW_LINE> TimeHoldController = "Alexa.TimeHoldController" <NEW_LINE> ToggleController = "Alexa.ToggleController" | Alexa interfaces.
Reference: https://developer.amazon.com/en-US/docs/alexa/device-apis/list-of-interfaces.html | 6259905cf7d966606f7493c6 |
class Detail(object): <NEW_LINE> <INDENT> def __init__(self, tag=None, value=None): <NEW_LINE> <INDENT> self.swagger_types = { 'tag': 'str', 'value': 'str' } <NEW_LINE> self.attribute_map = { 'tag': 'tag', 'value': 'value' } <NEW_LINE> self._tag = tag <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def tag(self): <NEW_LINE> <INDENT> return self._tag <NEW_LINE> <DEDENT> @tag.setter <NEW_LINE> def tag(self, tag): <NEW_LINE> <INDENT> self._tag = tag <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return 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, Detail): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259905cf548e778e596cba5 |
class Bounds(BaseAPIObject): <NEW_LINE> <INDENT> def __init__(self, d): <NEW_LINE> <INDENT> self.__dict__ = d <NEW_LINE> self.southwest = Coordinates(self.southwest) <NEW_LINE> self.northeast = Coordinates(self.northeast) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'(%s, %s)' % (self.southwest, self.northeast) | A bounding box that contains the `southwest` and `northeast` corners
as lnt/lng pairs. | 6259905c3539df3088ecd8b8 |
class IPConfigurationProfile(SubResource): <NEW_LINE> <INDENT> _validation = { 'type': {'readonly': True}, 'etag': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'subnet': {'key': 'properties.subnet', 'type': 'Subnet'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(IPConfigurationProfile, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.type = None <NEW_LINE> self.etag = None <NEW_LINE> self.subnet = kwargs.get('subnet', None) <NEW_LINE> self.provisioning_state = None | IP configuration profile child resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:param name: The name of the resource. This name can be used to access the resource.
:type name: str
:ivar type: Sub Resource type.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param subnet: The reference of the subnet resource to create a container network interface ip
configuration.
:type subnet: ~azure.mgmt.network.v2019_09_01.models.Subnet
:ivar provisioning_state: The provisioning state of the IP configuration profile resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_09_01.models.ProvisioningState | 6259905cf548e778e596cba6 |
class TextLogger(logging.Logger): <NEW_LINE> <INDENT> def __init__(self, name = "text_logger", level = logging.DEBUG, rootdir = None, filename = "testlog.txt", mode = 'w'): <NEW_LINE> <INDENT> super(TextLogger, self).__init__(name=name, level=level) <NEW_LINE> self.rootdir = rootdir <NEW_LINE> report_dir = self.get_report_dir() <NEW_LINE> if report_dir: <NEW_LINE> <INDENT> if not os.path.exists(report_dir): <NEW_LINE> <INDENT> os.makedirs(report_dir) <NEW_LINE> <DEDENT> """ write to file """ <NEW_LINE> formater = TextFormater() <NEW_LINE> file_handler = TextFileHandler(report_dir+"/"+filename, mode) <NEW_LINE> file_handler.setFormatter(formater) <NEW_LINE> self.addHandler(file_handler) <NEW_LINE> """ write to console """ <NEW_LINE> stream_handler = logging.StreamHandler(sys.stdout) <NEW_LINE> stream_handler.setFormatter(formater) <NEW_LINE> self.addHandler(stream_handler) <NEW_LINE> <DEDENT> <DEDENT> def get_current_dir(self): <NEW_LINE> <INDENT> return os.path.dirname(os.path.abspath(sys.argv[0])) <NEW_LINE> <DEDENT> def get_report_dir(self): <NEW_LINE> <INDENT> base_dir = "reports" <NEW_LINE> if self.rootdir: <NEW_LINE> <INDENT> return '{}/{}'.format(self.rootdir, base_dir) <NEW_LINE> <DEDENT> return None | Print logs to text file.
Args:
name (str): logger name
level (logging): logging.DEBUG, etc... refer to logging docs
filename (str): report file name
mode (str): refer to logging docs
| 6259905c7d847024c075d9f0 |
class ResourceviewsZoneViewsDeleteResponse(_messages.Message): <NEW_LINE> <INDENT> pass | An empty ResourceviewsZoneViewsDelete response. | 6259905cac7a0e7691f73afe |
class RetryDB(RetryOperationalError, MySQLDatabase): <NEW_LINE> <INDENT> pass | 封装数据库重试类 | 6259905ca79ad1619776b5cb |
class DoMysql: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> host=config.get("db","host") <NEW_LINE> user = config.get("db", "user") <NEW_LINE> password = config.get("db", "password") <NEW_LINE> port = config.get("db", "port") <NEW_LINE> self.mysql = pymysql.connect(host=host,user=user,password=password,port=int(port)) <NEW_LINE> self.cursor = self.mysql.cursor() <NEW_LINE> <DEDENT> def fetch_one(self,sql): <NEW_LINE> <INDENT> self.cursor.execute(sql) <NEW_LINE> self.mysql.commit() <NEW_LINE> return self.cursor.fetchone() <NEW_LINE> <DEDENT> def fetch_all(self,sql): <NEW_LINE> <INDENT> self.cursor.execute(sql) <NEW_LINE> return self.cursor.fetchall() <NEW_LINE> <DEDENT> def fetch_many(self,sql): <NEW_LINE> <INDENT> self.cursor.execute(sql) <NEW_LINE> return self.cursor.fetchmany() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.mysql.close() | 完成与mysql数据库的交互 | 6259905c2ae34c7f260ac703 |
class BlobjectAsync(Object): <NEW_LINE> <INDENT> def ice_invoke(self, bytes, current): <NEW_LINE> <INDENT> pass | Special-purpose servant base class that allows a subclass to
handle asynchronous Ice invocations as "blobs" of bytes. | 6259905c91af0d3eaad3b444 |
class Stack: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.stack = [] <NEW_LINE> <DEDENT> def stack_empty(self): <NEW_LINE> <INDENT> return self.stack == [] <NEW_LINE> <DEDENT> def push(self, x): <NEW_LINE> <INDENT> self.stack.append(x) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> return self.stack.pop() | Стек на списках | 6259905c498bea3a75a5910b |
class ObjectTypeClient(ObjectTypeClientOperationsMixin): <NEW_LINE> <INDENT> def __init__( self, base_url=None, **kwargs ): <NEW_LINE> <INDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'http://localhost:3000' <NEW_LINE> <DEDENT> self._config = ObjectTypeClientConfiguration(**kwargs) <NEW_LINE> self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) <NEW_LINE> client_models = {} <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._client.close() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._client.__enter__() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, *exc_details): <NEW_LINE> <INDENT> self._client.__exit__(*exc_details) | Service client for testing basic type: object swaggers.
:param str base_url: Service URL
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. | 6259905c91f36d47f223199d |
class Forafricconfig(Config): <NEW_LINE> <INDENT> NAME = "ForafricPro" <NEW_LINE> IMAGES_PER_GPU = 5 <NEW_LINE> GPU_COUNT = 1 <NEW_LINE> NUM_CLASSES = 1 + 1 <NEW_LINE> STEPS_PER_EPOCH = 500 <NEW_LINE> VALIDATION_STEPS = 50 <NEW_LINE> IMAGE_MAX_DIM=128 <NEW_LINE> IMAGE_MIN_DIM=128 | Configuration for training on data in MS COCO format.
Derives from the base Config class and overrides values specific
to the COCO dataset. | 6259905c4f6381625f199fb0 |
class UnidentifiedUser(ValueError): <NEW_LINE> <INDENT> pass | Raised when a specified account does not exist within a bank. | 6259905c16aa5153ce401b00 |
class BuildConfigTestsBase(test_lib.GRRBaseTest): <NEW_LINE> <INDENT> exceptions = [ "Client.private_key", "PrivateKeys.ca_key", "PrivateKeys.executable_signing_private_key", "PrivateKeys.server_key", ] <NEW_LINE> disabled_filters = ["resource", "file"] <NEW_LINE> def ValidateConfig(self, config_file=None): <NEW_LINE> <INDENT> logging.debug("Processing %s", config_file) <NEW_LINE> if isinstance(config_file, config_lib.GrrConfigManager): <NEW_LINE> <INDENT> conf_obj = config_file <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conf_obj = config.CONFIG.MakeNewConfig() <NEW_LINE> conf_obj.Initialize(filename=config_file, reset=True) <NEW_LINE> <DEDENT> with utils.MultiStubber((config, "CONFIG", conf_obj), (config_lib, "_CONFIG", conf_obj)): <NEW_LINE> <INDENT> all_sections = conf_obj.GetSections() <NEW_LINE> errors = conf_obj.Validate(sections=all_sections) <NEW_LINE> <DEDENT> return errors <NEW_LINE> <DEDENT> def ValidateConfigs(self, configs): <NEW_LINE> <INDENT> test_filter_map = config_lib.ConfigFilter.classes_by_name <NEW_LINE> for filter_name in self.disabled_filters: <NEW_LINE> <INDENT> test_filter_map[filter_name] = config_lib.ConfigFilter <NEW_LINE> <DEDENT> with utils.Stubber(config_lib.ConfigFilter, "classes_by_name", test_filter_map): <NEW_LINE> <INDENT> for config_file in configs: <NEW_LINE> <INDENT> errors = self.ValidateConfig(config_file) <NEW_LINE> for exception in self.exceptions: <NEW_LINE> <INDENT> errors.pop(exception, None) <NEW_LINE> <DEDENT> if errors: <NEW_LINE> <INDENT> logging.info("Validation of %s returned errors:", config_file) <NEW_LINE> for config_entry, error in errors.iteritems(): <NEW_LINE> <INDENT> logging.info("%s:", config_entry) <NEW_LINE> logging.info("%s", error) <NEW_LINE> <DEDENT> self.fail("Validation of %s returned errors: %s" % (config_file, errors)) | Base for config functionality tests. | 6259905c63b5f9789fe8678f |
class RetrieveArticleAPIView(APIView): <NEW_LINE> <INDENT> def get(self, request, slug): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> article = Article.objects.get(slug=slug) <NEW_LINE> article.tag_list = list(article.tag_list.names()) <NEW_LINE> serializer = ArticleSerializer( article, many=False, context={'request': self.request}) <NEW_LINE> return Response({'article': serializer.data}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> except Article.DoesNotExist: <NEW_LINE> <INDENT> return Response( {"message": "The article requested does not exist"}, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> <DEDENT> def put(self, request, slug): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> article = Article.objects.get(slug=slug) <NEW_LINE> <DEDENT> except Article.DoesNotExist: <NEW_LINE> <INDENT> return Response({"error": "the article was not found"}, status=status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> serializer = ArticleSerializer( article, data=request.data, context={'request': self.request}) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> if article.author.id == request.user.id: <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = {"message": "unauthorised to perform the action"} <NEW_LINE> return Response(response, status=status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> <DEDENT> def delete(self, request, slug): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> article = Article.objects.get(slug=slug) <NEW_LINE> <DEDENT> except Article.DoesNotExist: <NEW_LINE> <INDENT> raise APIException('Sorry, the article was not found') <NEW_LINE> <DEDENT> if article.author.id == request.user.id: <NEW_LINE> <INDENT> article.delete() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = {"message": "unauthorised to perform the action"} <NEW_LINE> return Response(response, status=status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> response = {"message": "article deleted"} <NEW_LINE> return Response(response, status=status.HTTP_202_ACCEPTED) | this class that handles the get request with slug | 6259905ce76e3b2f99fda01c |
class TimestampField(Field): <NEW_LINE> <INDENT> base_type = "float" <NEW_LINE> validators = [FloatValidator()] <NEW_LINE> example = 34.8 | A unix timestamp | 6259905c2ae34c7f260ac704 |
@magento <NEW_LINE> class StoreImporter(MagentoImporter): <NEW_LINE> <INDENT> _model_name = ['magento.store', ] <NEW_LINE> def _create(self, data): <NEW_LINE> <INDENT> binding = super(StoreImporter, self)._create(data) <NEW_LINE> checkpoint = self.unit_for(StoreAddCheckpoint) <NEW_LINE> checkpoint.run(binding.id) <NEW_LINE> return binding | Import one Magento Store (create a sale.shop via _inherits) | 6259905c10dbd63aa1c72189 |
@zope.interface.implementer_only(interfaces.IRadioWidget) <NEW_LINE> class RadioWidget(widget.HTMLInputWidget, SequenceWidget): <NEW_LINE> <INDENT> klass = u'radio-widget' <NEW_LINE> css = u'radio' <NEW_LINE> items = () <NEW_LINE> def isChecked(self, term): <NEW_LINE> <INDENT> return term.token in self.value <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> super(RadioWidget, self).update() <NEW_LINE> widget.addFieldClass(self) <NEW_LINE> self.items = [] <NEW_LINE> for count, term in enumerate(self.terms): <NEW_LINE> <INDENT> checked = self.isChecked(term) <NEW_LINE> id = '%s-%i' % (self.id, count) <NEW_LINE> label = util.toUnicode(term.value) <NEW_LINE> if zope.schema.interfaces.ITitledTokenizedTerm.providedBy(term): <NEW_LINE> <INDENT> label = translate(term.title, context=self.request, default=term.title) <NEW_LINE> <DEDENT> self.items.append( {'id':id, 'name':self.name, 'value':term.token, 'label':label, 'checked':checked}) | Input type radio widget implementation. | 6259905c097d151d1a2c268c |
class ListItem(FloatLayout): <NEW_LINE> <INDENT> data = ObjectProperty() <NEW_LINE> item_id = NumericProperty() <NEW_LINE> item_link = NumericProperty() <NEW_LINE> rv_key = NumericProperty(0) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ListItem, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def on_active(self, *args): <NEW_LINE> <INDENT> app = args[0] <NEW_LINE> active = self.ids.active_box.active <NEW_LINE> if active and self.rv_key not in app.item_selection: <NEW_LINE> <INDENT> result = Items.update_active(item_id=self.item_id, active=self.ids.active_box.active) <NEW_LINE> if result == 'revert': <NEW_LINE> <INDENT> self.ids.active_box.active = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> itemsmaint_obj.refresh_list() <NEW_LINE> <DEDENT> <DEDENT> elif not active and self.rv_key in app.item_selection: <NEW_LINE> <INDENT> result = Items.update_active(item_id=self.item_id, active=self.ids.active_box.active) <NEW_LINE> itemsmaint_obj.refresh_list() <NEW_LINE> <DEDENT> <DEDENT> def on_data(self, *args): <NEW_LINE> <INDENT> self.ids.itemname.text = self.data["text"] <NEW_LINE> self.item_id = self.data["item_id"] <NEW_LINE> self.item_link = self.data["item_link"] | Class to create a list item on the item maintenance screen | 6259905c435de62698e9d423 |
class _DragState(object): <NEW_LINE> <INDENT> def __init__(self, root, tab_bar, tab, start_pos): <NEW_LINE> <INDENT> self.dragging = False <NEW_LINE> self._root = root <NEW_LINE> self._tab_bar = tab_bar <NEW_LINE> self._tab = tab <NEW_LINE> self._start_pos = QtCore.QPoint(start_pos) <NEW_LINE> self._clone = None <NEW_LINE> <DEDENT> def start_dragging(self, pos): <NEW_LINE> <INDENT> if (pos - self._start_pos).manhattanLength() <= QtWidgets.QApplication.startDragDistance(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.dragging = True <NEW_LINE> otb = self._tab_bar <NEW_LINE> tab = self._tab <NEW_LINE> ctb = self._clone = QtWidgets.QTabBar() <NEW_LINE> if sys.platform == 'darwin' and QtCore.QT_VERSION >= 0x40500: <NEW_LINE> <INDENT> ctb.setDocumentMode(True) <NEW_LINE> <DEDENT> ctb.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents) <NEW_LINE> ctb.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.Tool | QtCore.Qt.X11BypassWindowManagerHint) <NEW_LINE> ctb.setWindowOpacity(0.5) <NEW_LINE> ctb.setElideMode(otb.elideMode()) <NEW_LINE> ctb.setShape(otb.shape()) <NEW_LINE> ctb.addTab(otb.tabText(tab)) <NEW_LINE> ctb.setTabTextColor(0, otb.tabTextColor(tab)) <NEW_LINE> trect = otb.tabRect(tab) <NEW_LINE> self._clone_offset = trect.topLeft() - pos <NEW_LINE> self._centre_offset = trect.center() - pos <NEW_LINE> self.drag(pos) <NEW_LINE> ctb.show() <NEW_LINE> <DEDENT> def drag(self, pos): <NEW_LINE> <INDENT> self._clone.move(self._tab_bar.mapToGlobal(pos) + self._clone_offset) <NEW_LINE> self._root._select(self._tab_bar.mapTo(self._root, pos + self._centre_offset)) <NEW_LINE> <DEDENT> def drop(self, pos): <NEW_LINE> <INDENT> self.drag(pos) <NEW_LINE> self._clone = None <NEW_LINE> global_pos = self._tab_bar.mapToGlobal(pos) <NEW_LINE> self._root._drop(global_pos, self._tab_bar.parent(), self._tab) <NEW_LINE> self.dragging = False | The _DragState class handles most of the work when dragging a tab. | 6259905cbe8e80087fbc06a2 |
class DogsCatsDataset(ImageFolder): <NEW_LINE> <INDENT> url = "http://files.fast.ai/data/dogscats.zip" <NEW_LINE> filename = "dogscats.zip" <NEW_LINE> checksum = "aef22ec7d472dd60e8ee79eecc19f131" <NEW_LINE> def __init__(self, root: str, suffix: str, transform=None, target_transform=None, loader=default_loader, download=False): <NEW_LINE> <INDENT> self.root = os.path.expanduser(root) <NEW_LINE> if download: <NEW_LINE> <INDENT> self._download() <NEW_LINE> self._extract() <NEW_LINE> <DEDENT> if not self._check_integrity(): <NEW_LINE> <INDENT> raise RuntimeError("Dataset not found or corrupted. " "You can use download=True to download it") <NEW_LINE> <DEDENT> path = os.path.join(self.root, "dogscats", suffix) <NEW_LINE> print(f"Loading data from {path}.") <NEW_LINE> assert os.path.isdir(path), f"'{suffix}' is not valid." <NEW_LINE> super().__init__(path, transform, target_transform, loader) <NEW_LINE> <DEDENT> def _download(self): <NEW_LINE> <INDENT> if self._check_integrity(): <NEW_LINE> <INDENT> print("Dataset already downloaded and verified.") <NEW_LINE> return <NEW_LINE> <DEDENT> root = self.root <NEW_LINE> print("Downloading dataset... (this might take a while)") <NEW_LINE> download_url(self.url, root, self.filename, self.checksum) <NEW_LINE> <DEDENT> def _extract(self): <NEW_LINE> <INDENT> import zipfile <NEW_LINE> path_to_zip = os.path.join(self.root, self.filename) <NEW_LINE> with zipfile.ZipFile(path_to_zip, 'r') as zip_ref: <NEW_LINE> <INDENT> zip_ref.extractall(self.root) <NEW_LINE> <DEDENT> <DEDENT> def _check_integrity(self): <NEW_LINE> <INDENT> path_to_zip = os.path.join(self.root, self.filename) <NEW_LINE> return check_integrity(path_to_zip, self.checksum) | The 'Dogs and Cats' dataset from kaggle.
https://www.kaggle.com/c/dogs-vs-cats-redux-kernels-edition/
Args:
root: the location where to store the dataset
suffix: path to the train/valid/sample dataset. See folder structure.
transform (callable, optional): A function/transform that takes in
an PIL image and returns a transformed version.
E.g, ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that
takes in the target and transforms it.
loader: A function to load an image given its path.
download: if ``True``, download the data.
The folder structure of the dataset is as follows::
└── dogscats
├── sample
│ ├── train
│ │ ├── cats
│ │ └── dogs
│ └── valid
│ ├── cats
│ └── dogs
├── train
│ ├── cats
│ └── dogs
└── valid
├── cats
└── dogs | 6259905c91f36d47f223199e |
class TestSetup(unittest.TestCase): <NEW_LINE> <INDENT> layer = COLLECTIVE_SMARTLINK_INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer['portal'] <NEW_LINE> self.installer = api.portal.get_tool('portal_quickinstaller') <NEW_LINE> <DEDENT> def test_product_installed(self): <NEW_LINE> <INDENT> self.assertTrue(self.installer.isProductInstalled( 'collective.smartlink')) <NEW_LINE> <DEDENT> def test_browserlayer(self): <NEW_LINE> <INDENT> from collective.smartlink.interfaces import ( ICollectiveSmartlinkLayer) <NEW_LINE> from plone.browserlayer import utils <NEW_LINE> self.assertIn(ICollectiveSmartlinkLayer, utils.registered_layers()) | Test that collective.smartlink is properly installed. | 6259905c8e71fb1e983bd0e8 |
class AMTH_SCREEN_OT_frame_jump(Operator): <NEW_LINE> <INDENT> bl_idname = "screen.amaranth_frame_jump" <NEW_LINE> bl_label = "Jump Frames" <NEW_LINE> forward = BoolProperty(default=True) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> preferences = context.user_preferences.addons[__name__].preferences <NEW_LINE> if preferences.use_framerate: <NEW_LINE> <INDENT> framedelta = scene.render.fps <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> framedelta = preferences.frames_jump <NEW_LINE> <DEDENT> if self.forward: <NEW_LINE> <INDENT> scene.frame_current = scene.frame_current + framedelta <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scene.frame_current = scene.frame_current - framedelta <NEW_LINE> <DEDENT> return{'FINISHED'} | Jump a number of frames forward/backwards | 6259905cbaa26c4b54d508c4 |
class VertexPosition(Enum): <NEW_LINE> <INDENT> LEFT_OF_SOURCE = -1 <NEW_LINE> RIGHT_OF_SOURCE = 1 <NEW_LINE> SOURCE = 0 | Enumeration class used to define position of a vertex w.r.t source in
modular decomposition.
For computing modular decomposition of connected graphs a source vertex is
chosen. The position of vertex is w.r.t this source vertex. The various
positions defined are
- ``LEFT_OF_SOURCE`` -- indicates vertex is to left of source and is a
neighbour of source vertex
- ``RIGHT_OF_SOURCE`` -- indicates vertex is to right of source and is
connected to but not a neighbour of source vertex
- ``SOURCE`` -- indicates vertex is source vertex | 6259905c4f6381625f199fb1 |
class TestTeamMembershipPolicyChoiceRestrcted( TestTeamMembershipPolicyChoiceModerated): <NEW_LINE> <INDENT> POLICY = TeamMembershipPolicy.RESTRICTED | Test `TeamMembershipPolicyChoice` Restricted constraints. | 6259905ce64d504609df9ede |
class RiakLinkPhase(object): <NEW_LINE> <INDENT> def __init__(self, bucket, tag, keep): <NEW_LINE> <INDENT> self._bucket = bucket <NEW_LINE> self._tag = tag <NEW_LINE> self._keep = keep <NEW_LINE> <DEDENT> def to_array(self): <NEW_LINE> <INDENT> stepdef = {'bucket': self._bucket, 'tag': self._tag, 'keep': self._keep} <NEW_LINE> return {'link': stepdef} | The RiakLinkPhase object holds information about a Link phase in a
map/reduce operation.
Normally you won't need to use this object directly, but instead
call :meth:`RiakMapReduce.link` on RiakMapReduce objects to add
instances to the query. | 6259905ccc0a2c111447c5de |
class Squad(): <NEW_LINE> <INDENT> def __init__(self, units_number: int, unit_type: str, color: str, attack_mode: int): <NEW_LINE> <INDENT> self.units_number = units_number <NEW_LINE> self.unit_type = unit_type <NEW_LINE> self.color = color <NEW_LINE> self.attack_mode = attack_mode <NEW_LINE> self.units = [] <NEW_LINE> self.att_succ_prob = None <NEW_LINE> <DEDENT> def create_squad(self): <NEW_LINE> <INDENT> number = 0 <NEW_LINE> for i in range(0, self.units_number): <NEW_LINE> <INDENT> self.units.append(self.choice_unit_type(number, self.color,self.unit_type)) <NEW_LINE> <DEDENT> <DEDENT> def choice_unit_type(self, number: int, color: str, attack_mode: int, unit_type: str): <NEW_LINE> <INDENT> if self.unit_type == 'soldier': <NEW_LINE> <INDENT> return Soldier(number, color, attack_mode) <NEW_LINE> <DEDENT> if self.unit_type == 'tank': <NEW_LINE> <INDENT> return Tank(number, color, attack_mode) <NEW_LINE> <DEDENT> if self.unit_type == 'buggy': <NEW_LINE> <INDENT> return Buggy(number, color, attack_mode) <NEW_LINE> <DEDENT> <DEDENT> def attack(self): <NEW_LINE> <INDENT> multiple_att_prob = 1 <NEW_LINE> for unit in self.units: <NEW_LINE> <INDENT> multiple_att_prob *= unit.attack_success_prob <NEW_LINE> <DEDENT> self.att_succ_prob = multiple_att_prob ** 1/len(self.units) <NEW_LINE> <DEDENT> def is_active(self): <NEW_LINE> <INDENT> temp = None <NEW_LINE> for unit in self.units: <NEW_LINE> <INDENT> if unit.is_active(): <NEW_LINE> <INDENT> temp = True <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp = False <NEW_LINE> <DEDENT> <DEDENT> return temp | Represents units squad | 6259905c0a50d4780f7068ce |
class PostResource(Resource): <NEW_LINE> <INDENT> method_decorators = [jwt_required] <NEW_LINE> def get(self, post_id): <NEW_LINE> <INDENT> schema = PostSchema() <NEW_LINE> post = Post.query.get_or_404(post_id) <NEW_LINE> return {"post": schema.dump(post).data} | Single object resource
| 6259905cd53ae8145f919a82 |
class LogSliceView(viewsets.ViewSet): <NEW_LINE> <INDENT> def get_log_handle(self, url): <NEW_LINE> <INDENT> return urllib2.urlopen( url, timeout=settings.TREEHERDER_REQUESTS_TIMEOUT ) <NEW_LINE> <DEDENT> @with_jobs <NEW_LINE> def list(self, request, project, jm): <NEW_LINE> <INDENT> job_id = request.query_params.get("job_id") <NEW_LINE> log_name = request.query_params.get("name", "buildbot_text") <NEW_LINE> format = 'json' if log_name == 'mozlog_json' else 'text' <NEW_LINE> handle = None <NEW_LINE> gz_file = None <NEW_LINE> start_line = request.query_params.get("start_line") <NEW_LINE> end_line = request.query_params.get("end_line") <NEW_LINE> if not start_line or not end_line: <NEW_LINE> <INDENT> return Response("``start_line`` and ``end_line`` parameters are both required", 400) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> start_line = abs(int(start_line)) <NEW_LINE> end_line = abs(int(end_line)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return Response("parameters could not be converted to integers", 400) <NEW_LINE> <DEDENT> if start_line >= end_line: <NEW_LINE> <INDENT> return Response("``end_line`` must be larger than ``start_line``", 400) <NEW_LINE> <DEDENT> logs = jm.get_log_references(job_id) <NEW_LINE> exp_log_names = [log_name, 'builds-4h'] <NEW_LINE> try: <NEW_LINE> <INDENT> log = next(log for log in logs if log["name"] in exp_log_names) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> act_log_names = [x["name"] for x in logs] <NEW_LINE> raise ResourceNotFoundException( "Expected log names of {} not found in {} for job_id {}".format( exp_log_names, act_log_names, job_id, )) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> url = log.get("url") <NEW_LINE> gz_file = filesystem.get(url) <NEW_LINE> if not gz_file: <NEW_LINE> <INDENT> handle = self.get_log_handle(url) <NEW_LINE> gz_file = gzip.GzipFile(fileobj=BytesIO(handle.read())) <NEW_LINE> filesystem.set(url, gz_file.fileobj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gz_file = gzip.GzipFile(fileobj=gz_file) <NEW_LINE> <DEDENT> lines = [] <NEW_LINE> for i, line in enumerate(gz_file): <NEW_LINE> <INDENT> if i < start_line: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif i >= end_line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if format == 'json': <NEW_LINE> <INDENT> lines.append({"data": json.loads(line), "index": i}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lines.append({"text": line, "index": i}) <NEW_LINE> <DEDENT> <DEDENT> return Response(lines) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if handle: <NEW_LINE> <INDENT> handle.close() <NEW_LINE> <DEDENT> if gz_file: <NEW_LINE> <INDENT> gz_file.close() | This view serves slices of the log | 6259905c45492302aabfdaf8 |
class MDDLinked_WithPreviousAndNext( MDDLinked_WithPrevious, MDDLinked_WithNext): <NEW_LINE> <INDENT> security = ClassSecurityInfo() <NEW_LINE> def __init__( self): <NEW_LINE> <INDENT> MDDLinked_WithPrevious.__init__( self) <NEW_LINE> MDDLinked_WithNext.__init__( self) | Abstract cache entry class fully able to participate in the linked list, integrating the capabilities to relate to both previous and next cache entries.
| 6259905cd268445f2663a66c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.