code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Messenger: <NEW_LINE> <INDENT> def __init__(self, token='{}'): <NEW_LINE> <INDENT> self._token = token <NEW_LINE> self.post_url = FB_URL.format(self._token) <NEW_LINE> self.user_url = FB_USER_URL.format(self._token) <NEW_LINE> <DEDENT> @property <NEW_LINE> def token(self): <NEW_LINE> <INDENT> return self._token <NEW_LINE> <DEDENT> @token.setter <NEW_LINE> def token(self, value): <NEW_LINE> <INDENT> self._token = value <NEW_LINE> <DEDENT> def send(self, obj): <NEW_LINE> <INDENT> payload = serialize_(obj) <NEW_LINE> payload = dumps(payload) <NEW_LINE> print('Sending Message with payload: ') <NEW_LINE> print(payload) <NEW_LINE> try: <NEW_LINE> <INDENT> status = requests.post(self.post_url, data=payload, headers=HEADERS_JSON) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as e: <NEW_LINE> <INDENT> raise CourierRequestError(str(e)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return (status.status_code, status.text) <NEW_LINE> <DEDENT> <DEDENT> def get_user_profile(self, fbid): <NEW_LINE> <INDENT> url = self.user_url % fbid <NEW_LINE> try: <NEW_LINE> <INDENT> status = requests.get(url) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as e: <NEW_LINE> <INDENT> raise CourierRequestError(str(e)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> return (status.status_code, status.json()) | Class that represents a singleton used to send messages to the Facebook API | 6259905e3c8af77a43b68a6c |
class VerifyUpdateVMName(pending_action.PendingServerAction): <NEW_LINE> <INDENT> def retry(self): <NEW_LINE> <INDENT> if (not self._target['id'] in self._state.get_instances().keys() or self._state.get_instances()[self._target['id']][1] == 'TERMINATING'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> response, body = self._manager.serverse_client.get_server(self._target['id']) <NEW_LINE> if (response.status != 200): <NEW_LINE> <INDENT> self._logger.error("response: %s " % response) <NEW_LINE> self._logger.error("body: %s " % body) <NEW_LINE> raise Exception <NEW_LINE> <DEDENT> if self._target['name'] != body['name']: <NEW_LINE> <INDENT> self._logger.error(self._target['name'] + ' vs. ' + body['name']) <NEW_LINE> raise Exception <NEW_LINE> <DEDENT> self._logger.info('machine %s: UPDATING_NAME -> ACTIVE' % self._target['id']) <NEW_LINE> self._state.set_instance_state(self._target['id'], (body, 'ACTIVE')) <NEW_LINE> return True | Check that VM has new name | 6259905ef7d966606f7493e4 |
class Node(object): <NEW_LINE> <INDENT> __slots__ = 'row','column','left', 'right', 'up', 'down' <NEW_LINE> def __init__ ( self, row=0, column=0, left = None, right = None, up = None, down = None ): <NEW_LINE> <INDENT> self.row = row <NEW_LINE> self.column = column <NEW_LINE> self.left = left <NEW_LINE> self.right = right <NEW_LINE> self.up = up <NEW_LINE> self.down = down <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "(" + str(self.column) + ", " + str(self.row) + ")" | This class is used to represent a position of a
frozen pond puzzle in a graph representation of that
puzzle. | 6259905e21a7993f00c675c4 |
class MonitoringStation: <NEW_LINE> <INDENT> def __init__(self, station_id, measure_id, label, coord, typical_range, river, town): <NEW_LINE> <INDENT> self.station_id = station_id <NEW_LINE> self.measure_id = measure_id <NEW_LINE> self.name = label <NEW_LINE> if isinstance(label, list): <NEW_LINE> <INDENT> self.name = label[0] <NEW_LINE> <DEDENT> self.coord = coord <NEW_LINE> self.typical_range = typical_range <NEW_LINE> self.river = river <NEW_LINE> self.town = town <NEW_LINE> self.latest_level = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> d = "Station name: {}\n".format(self.name) <NEW_LINE> d += " id: {}\n".format(self.station_id) <NEW_LINE> d += " measure id: {}\n".format(self.measure_id) <NEW_LINE> d += " coordinate: {}\n".format(self.coord) <NEW_LINE> d += " town: {}\n".format(self.town) <NEW_LINE> d += " river: {}\n".format(self.river) <NEW_LINE> d += " typical range: {}".format(self.typical_range) <NEW_LINE> return d <NEW_LINE> <DEDENT> def typical_range_consistent(self): <NEW_LINE> <INDENT> if type(self.typical_range) == type((0,1)) and self.typical_range[1] > self.typical_range[0]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def relative_water_level(self): <NEW_LINE> <INDENT> if type(self) == MonitoringStation and self.latest_level != None and self.typical_range != None: <NEW_LINE> <INDENT> return (float(self.latest_level - self.typical_range[0])/(self.typical_range[1] - self.typical_range[0])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | This class represents a river level monitoring station | 6259905e0a50d4780f7068ea |
class Namespace(object): <NEW_LINE> <INDENT> __slots__ = ("scope", "parent") <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> self.scope = {} <NEW_LINE> self.parent = parent <NEW_LINE> <DEDENT> def _eval_passdown(self, passdown:bool): <NEW_LINE> <INDENT> if self.parent is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return passdown <NEW_LINE> <DEDENT> def _get(self, name: str, d: typing.Any=_DUMMY, *, passdown: bool=True): <NEW_LINE> <INDENT> passdown = self._eval_passdown(passdown) <NEW_LINE> if name not in self.scope: <NEW_LINE> <INDENT> if passdown: <NEW_LINE> <INDENT> return self.parent._get(name, d) <NEW_LINE> <DEDENT> if d is _DUMMY: <NEW_LINE> <INDENT> raise KeyError(name) <NEW_LINE> <DEDENT> return d <NEW_LINE> <DEDENT> return self.scope.get(name) <NEW_LINE> <DEDENT> def _set(self, name:str, value: typing.Any, *, passdown: bool=True): <NEW_LINE> <INDENT> passdown = self._eval_passdown(passdown) <NEW_LINE> if passdown and name in self.parent: <NEW_LINE> <INDENT> self.parent._set(name, value) <NEW_LINE> return <NEW_LINE> <DEDENT> self.scope[name] = value <NEW_LINE> <DEDENT> def _del(self, name:str, *, passdown: bool=True): <NEW_LINE> <INDENT> passdown = self._eval_passdown(passdown) <NEW_LINE> if self._has(name, passdown=False): <NEW_LINE> <INDENT> del self.scope[name] <NEW_LINE> <DEDENT> if passdown: <NEW_LINE> <INDENT> self.parent._del(name, passdown=True) <NEW_LINE> <DEDENT> <DEDENT> def _has(self, name: str, *, passdown: bool = True): <NEW_LINE> <INDENT> passdown = self._eval_passdown(passdown) <NEW_LINE> if name in self.scope: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if passdown and self.parent._has(name, passdown=True): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def get(self, name: str, d: typing.Any=_DUMMY): <NEW_LINE> <INDENT> return self._get(name, d, passdown=True) <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self._get(item, passdown=False) <NEW_LINE> <DEDENT> def __setitem__(self, item, value): <NEW_LINE> <INDENT> self._set(item, value, passdown=False) <NEW_LINE> <DEDENT> def __delitem__(self, item): <NEW_LINE> <INDENT> self._del(item, passdown=False) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return self._get(attr, passdown=True) <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return self._has(item, passdown=True) <NEW_LINE> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> if attr in Namespace.__slots__: <NEW_LINE> <INDENT> super(Namespace, self).__setattr__(attr, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._set(attr, value, passdown=True) <NEW_LINE> <DEDENT> <DEDENT> def __delattr__(self, attr): <NEW_LINE> <INDENT> if attr in Namespace.__slots__: <NEW_LINE> <INDENT> raise AttributeError("Read Only attribute.") <NEW_LINE> <DEDENT> self._del(attr) | A namespace for the function calls. | 6259905eb7558d5895464a58 |
class PassAvatarIdTerminalRealm(TerminalRealm): <NEW_LINE> <INDENT> noisy = False <NEW_LINE> def _getAvatar(self, avatarId): <NEW_LINE> <INDENT> comp = components.Componentized() <NEW_LINE> user = self.userFactory(comp, avatarId) <NEW_LINE> sess = self.sessionFactory(comp) <NEW_LINE> sess.transportFactory = self.transportFactory <NEW_LINE> sess.chainedProtocolFactory = lambda: self.chainedProtocolFactory(avatarId) <NEW_LINE> comp.setComponent(iconch.IConchUser, user) <NEW_LINE> comp.setComponent(iconch.ISession, sess) <NEW_LINE> return user | Returns an avatar that passes the avatarId through to the
protocol. This is probably not the best way to do it. | 6259905e01c39578d7f14262 |
class Request(object): <NEW_LINE> <INDENT> def __init__( self, method: str, path: str, params: dict, data: Union[dict, str, bytes], headers: dict, callback: Callable = None, on_failed: Callable = None, on_error: Callable = None, extra: Any = None, ): <NEW_LINE> <INDENT> self.method = method <NEW_LINE> self.path = path <NEW_LINE> self.callback = callback <NEW_LINE> self.params = params <NEW_LINE> self.data = data <NEW_LINE> self.headers = headers <NEW_LINE> self.on_failed = on_failed <NEW_LINE> self.on_error = on_error <NEW_LINE> self.extra = extra <NEW_LINE> self.response: Optional[aiohttp.ClientResponse] = None <NEW_LINE> self.status = RequestStatus.ready <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.response is None: <NEW_LINE> <INDENT> status_code = "terminated" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status_code = self.response.status <NEW_LINE> <DEDENT> return ( "request : {} {} {} because {}: \n" "headers: {}\n" "params: {}\n" "data: {}\n" "response:" "{}\n".format( self.method, self.path, self.status.name, status_code, self.headers, self.params, self.data, "" if self.response is None else self.response.text, ) ) | Request object for status check. | 6259905e460517430c432b7e |
class Settings(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (0, 0, 0) <NEW_LINE> self.ship_limit = 3 <NEW_LINE> self.bullet_speed_factor = 5 <NEW_LINE> self.bullet_width = 8 <NEW_LINE> self.bullet_height = 17 <NEW_LINE> self.bullet_color = 255, 0, 0 <NEW_LINE> self.bullets_allowed = 10 <NEW_LINE> self.fleet_drop_speed = 10 <NEW_LINE> self.speedup_scale = 1.1 <NEW_LINE> self.score_scale = 1.5 <NEW_LINE> self.initialize_dynamic_settings() <NEW_LINE> <DEDENT> def initialize_dynamic_settings(self): <NEW_LINE> <INDENT> self.ship_speed_factor = 2.0 <NEW_LINE> self.bullet_speed_factor = 3 <NEW_LINE> self.alien_speed_factor = 1 <NEW_LINE> self.alien_points = 50 <NEW_LINE> self.fleet_direction = 1 <NEW_LINE> <DEDENT> def increase_speed(self): <NEW_LINE> <INDENT> self.ship_speed_factor *= self.speedup_scale <NEW_LINE> self.bullet_speed_factor *= self.speedup_scale <NEW_LINE> self.alien_speed_factor *= self.speedup_scale <NEW_LINE> self.alien_points = int(self.alien_points * self.score_scale) | A class to store all settings for Alien Invasion. | 6259905e7d847024c075da2a |
class RoomDoesNotExists(Exception): <NEW_LINE> <INDENT> pass | Exception for Room | 6259905e55399d3f05627b77 |
class TestConfigurationParameterCondition(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 testConfigurationParameterCondition(self): <NEW_LINE> <INDENT> pass | ConfigurationParameterCondition unit test stubs | 6259905ea219f33f346c7e5d |
@registry.bind(TestCaseReport) <NEW_LINE> class TestCaseRowBuilder(TestRowRenderer): <NEW_LINE> <INDENT> def get_header_linestyle(self): <NEW_LINE> <INDENT> return 0.5, colors.lightgrey <NEW_LINE> <DEDENT> def should_display(self, source): <NEW_LINE> <INDENT> return self.get_style(source).display_testcase | Row builder for TestCaseReport, this mainly corresponds
to a testcase method / function. | 6259905e29b78933be26abf0 |
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) <NEW_LINE> class AdminCustomUrlsTest(TestCase): <NEW_LINE> <INDENT> fixtures = ['users.json', 'actions.json'] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.client.login(username='super', password='secret') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.client.logout() <NEW_LINE> <DEDENT> def testBasicAddGet(self): <NEW_LINE> <INDENT> response = self.client.get('/custom_urls/admin/admin_custom_urls/action/!add/') <NEW_LINE> self.assertIsInstance(response, TemplateResponse) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def testAddWithGETArgs(self): <NEW_LINE> <INDENT> response = self.client.get('/custom_urls/admin/admin_custom_urls/action/!add/', {'name': 'My Action'}) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, 'value="My Action"') <NEW_LINE> <DEDENT> def testBasicAddPost(self): <NEW_LINE> <INDENT> post_data = { '_popup': '1', "name": 'Action added through a popup', "description": "Description of added action", } <NEW_LINE> response = self.client.post('/custom_urls/admin/admin_custom_urls/action/!add/', post_data) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, 'dismissAddAnotherPopup') <NEW_LINE> self.assertContains(response, 'Action added through a popup') <NEW_LINE> <DEDENT> def testAdminUrlsNoClash(self): <NEW_LINE> <INDENT> response = self.client.get('/custom_urls/admin/admin_custom_urls/action/add/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, 'Change action') <NEW_LINE> url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote('add'),)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, 'Change action') <NEW_LINE> url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote("path/to/html/document.html"),)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, 'Change action') <NEW_LINE> self.assertContains(response, 'value="path/to/html/document.html"') | Remember that:
* The Action model has a CharField PK.
* The ModelAdmin for Action customizes the add_view URL, it's
'<app name>/<model name>/!add/' | 6259905e32920d7e50bc769e |
class TestSAMLProviderRulesApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = SAMLProviderRulesApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_create_saml_provider_rule(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_delete_saml_provider_rule(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_list_saml_provider_rules(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_saml_provider_rule(self): <NEW_LINE> <INDENT> pass | SAMLProviderRulesApi unit test stubs | 6259905e379a373c97d9a67d |
class AddDofEmpty(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "add.dof_empty" <NEW_LINE> bl_label = "Add DOF Empty" <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.active_object is not None <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> add_DOF_Empty() <NEW_LINE> return {'FINISHED'} | Create empty and add as DOF Object | 6259905e97e22403b383c565 |
class AttachmentPreprocessor(markdown.preprocessors.Preprocessor): <NEW_LINE> <INDENT> def run(self, lines): <NEW_LINE> <INDENT> new_text = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> m = ATTACHMENT_RE.match(line) <NEW_LINE> if m: <NEW_LINE> <INDENT> attachment_id = m.group('id').strip() <NEW_LINE> before = m.group('before') <NEW_LINE> after = m.group('after') <NEW_LINE> try: <NEW_LINE> <INDENT> attachment = models.Attachment.objects.get(articles=self.markdown.article, id=attachment_id, current_revision__deleted=False) <NEW_LINE> url = reverse('wiki:attachments_download', kwargs={'article_id': self.markdown.article.id, 'attachment_id':attachment.id,}) <NEW_LINE> html = render_to_string("wiki/plugins/attachments/render.html", Context({'url': url, 'filename': attachment.original_filename,})) <NEW_LINE> line = self.markdown.htmlStash.store(html, safe=True) <NEW_LINE> <DEDENT> except models.Attachment.DoesNotExist: <NEW_LINE> <INDENT> line = line.replace(m.group(1), """<span class="attachment attachment-deleted">Attachment with ID #%s is deleted.</span>""" % attachment_id) <NEW_LINE> <DEDENT> line = before + line + after <NEW_LINE> <DEDENT> new_text.append(line) <NEW_LINE> <DEDENT> return new_text | django-wiki attachment preprocessor - parse text for [attachment:id] references. | 6259905ea17c0f6771d5d6cf |
class NutritionOrderEnteralFormulaAdministration(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_name = "NutritionOrderEnteralFormulaAdministration" <NEW_LINE> def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.quantity = None <NEW_LINE> self.rateQuantity = None <NEW_LINE> self.rateRatio = None <NEW_LINE> self.schedule = None <NEW_LINE> super(NutritionOrderEnteralFormulaAdministration, self).__init__(jsondict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(NutritionOrderEnteralFormulaAdministration, self).elementProperties() <NEW_LINE> js.extend([ ("quantity", "quantity", quantity.Quantity, False, None, False), ("rateQuantity", "rateQuantity", quantity.Quantity, False, "rate", False), ("rateRatio", "rateRatio", ratio.Ratio, False, "rate", False), ("schedule", "schedule", timing.Timing, False, None, False), ]) <NEW_LINE> return js | Formula feeding instruction as structured data.
Formula administration instructions as structured data. This repeating
structure allows for changing the administration rate or volume over time
for both bolus and continuous feeding. An example of this would be an
instruction to increase the rate of continuous feeding every 2 hours. | 6259905e99cbb53fe6832539 |
class Group(models.Model): <NEW_LINE> <INDENT> name = models.SlugField(_("name"), max_length=64, blank=False) <NEW_LINE> display_name = models.CharField(_("display name"), max_length=64) <NEW_LINE> mailing_list = models.EmailField(_("mailing list"), blank=True, help_text=_("The mailing list review requests and discussions " "are sent to.")) <NEW_LINE> users = models.ManyToManyField(User, blank=True, related_name="review_groups", verbose_name=_("users")) <NEW_LINE> local_site = models.ForeignKey(LocalSite, blank=True, null=True) <NEW_LINE> incoming_request_count = CounterField( _('incoming review request count'), initializer=lambda g: ReviewRequest.objects.to_group( g, local_site=g.local_site).count()) <NEW_LINE> invite_only = models.BooleanField(_('invite only'), default=False) <NEW_LINE> visible = models.BooleanField(default=True) <NEW_LINE> objects = ReviewGroupManager() <NEW_LINE> def is_accessible_by(self, user): <NEW_LINE> <INDENT> "" <NEW_LINE> if self.local_site and not self.local_site.is_accessible_by(user): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return (not self.invite_only or user.is_superuser or (user.is_authenticated() and self.users.filter(pk=user.pk).count() > 0)) <NEW_LINE> <DEDENT> def is_mutable_by(self, user): <NEW_LINE> <INDENT> return (user.has_perm('reviews.change_group') or (self.local_site and self.local_site.is_mutable_by(user))) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> if self.local_site_id: <NEW_LINE> <INDENT> local_site_name = self.local_site.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> local_site_name = None <NEW_LINE> <DEDENT> return local_site_reverse('group', local_site_name=local_site_name, kwargs={'name': self.name}) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = (('name', 'local_site'),) <NEW_LINE> verbose_name = _("review group") <NEW_LINE> ordering = ['name'] | A group of reviewers identified by a name. This is usually used to
separate teams at a company or components of a project.
Each group can have an e-mail address associated with it, sending
all review requests and replies to that address. If that e-mail address is
blank, e-mails are sent individually to each member of that group. | 6259905e7047854f46340a19 |
@inside_glslc_testsuite('PragmaShaderStage') <NEW_LINE> class TestConflictingPSSfromIncludingAndIncludedFile(expect.ErrorMessage): <NEW_LINE> <INDENT> environment = Directory('.', [ File('a.vert', '#pragma shader_stage(fragment)\n' 'void main() { gl_Position = vec4(1.); }\n' '#include "b.glsl"\n'), File('b.glsl', '#pragma shader_stage(vertex)')]) <NEW_LINE> glslc_args = ['-c', 'a.vert'] <NEW_LINE> expected_error = [ "b.glsl:1: error: '#pragma': conflicting stages for 'shader_stage' " "#pragma: 'vertex' (was 'fragment' at a.vert:1)\n"] | Tests that conflicting #pragma shader_stage() from including and
included files results in an error with the correct location spec. | 6259905e004d5f362081fb1b |
class ShippingMethod(models.Model, Criteria): <NEW_LINE> <INDENT> active = models.BooleanField(_(u"Active"), default=False) <NEW_LINE> priority = models.IntegerField(_(u"Priority"), default=0) <NEW_LINE> name = models.CharField(_(u"Name"), max_length=50) <NEW_LINE> description = models.TextField(_(u"Description"), blank=True) <NEW_LINE> note = models.TextField(_(u"Note"), blank=True) <NEW_LINE> image = models.ImageField(_(u"Image"), upload_to="images", blank=True, null=True) <NEW_LINE> tax = models.ForeignKey(Tax, verbose_name=_(u"Tax"), blank=True, null=True) <NEW_LINE> price = models.FloatField(_(u"Price"), default=0.0) <NEW_LINE> delivery_time = models.ForeignKey(DeliveryTime, verbose_name=_(u"Delivery time"), blank=True, null=True) <NEW_LINE> price_calculator = models.CharField(_(u"Price Calculator"), max_length=200, choices=settings.LFS_SHIPPING_METHOD_PRICE_CALCULATORS, default=settings.LFS_SHIPPING_METHOD_PRICE_CALCULATORS[0][0]) <NEW_LINE> objects = ActiveShippingMethodManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ("priority", ) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_price(self, request): <NEW_LINE> <INDENT> if self.price_calculator: <NEW_LINE> <INDENT> price_class = import_symbol(self.price_calculator) <NEW_LINE> return price_class(request, self).get_price() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.price <NEW_LINE> <DEDENT> <DEDENT> def get_price_gross(self, request): <NEW_LINE> <INDENT> if self.price_calculator: <NEW_LINE> <INDENT> price_class = import_symbol(self.price_calculator) <NEW_LINE> return price_class(request, self).get_price_gross() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.price <NEW_LINE> <DEDENT> <DEDENT> def get_price_net(self, request): <NEW_LINE> <INDENT> if self.price_calculator: <NEW_LINE> <INDENT> price_class = import_symbol(self.price_calculator) <NEW_LINE> return price_class(request, self).get_price_net() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.price <NEW_LINE> <DEDENT> <DEDENT> def get_tax(self, request): <NEW_LINE> <INDENT> if self.price_calculator: <NEW_LINE> <INDENT> price_class = import_symbol(self.price_calculator) <NEW_LINE> return price_class(request, self).get_tax() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.tax.rate | Decides how bought products are delivered to the customer.
name
The name of the shipping method. This is displayed to the customer to
choose the shipping method.
description
A longer description of the shipping method. This could be displayed to
the customer to describe the shipping method in detail.
note
This is displayed to the customer within the checkout process and should
contain a short note about the shipping method.
priority
The order in which the shipping methods are displayed to the customer.
image
An image of the shipping method, which is displayed to customer within
the checkout process.
active
A flag which decides whether a shipping method is displayed to the
customer or not.
tax
The tax of the shipping method.
price
The default price of the shipping method. This is taken if the shipping
method either has no additional prices or if none of he additional prices
is valid.
criteria
A shipping method may have several criteria which decide whether the
shipping method is valid. It is valid if all criteria are true. Only
active and valid shipping methods are provided to the shop customer.
delivery_time
Reference to a delivery_time | 6259905e435de62698e9d45e |
class ContextMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, request): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.extrahead = request.PYLUCID.extrahead <NEW_LINE> <DEDENT> def _add_pagetree_headfiles(self): <NEW_LINE> <INDENT> pagetree = self.request.PYLUCID.pagetree <NEW_LINE> design = pagetree.design <NEW_LINE> self.extrahead.append(design.get_headfile_data()) <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> self._add_pagetree_headfiles() <NEW_LINE> return "\n".join(self.extrahead) | replace <!-- ContextMiddleware extrahead --> in the global page template | 6259905e76e4537e8c3f0be5 |
class RuleFilter: <NEW_LINE> <INDENT> def to_query(self) -> Q: <NEW_LINE> <INDENT> raise NotImplementedError('You must override the method in successors') <NEW_LINE> <DEDENT> def __ne__(self, o: object) -> bool: <NEW_LINE> <INDENT> return not self == o | Abstract class shows the idea of rules query filtering invariants. | 6259905e8e7ae83300eea6e7 |
class ExchangeValidator(Validator): <NEW_LINE> <INDENT> def __init__(self, provider: BaseProvider, contract_address: str): <NEW_LINE> <INDENT> super().__init__(provider, contract_address) <NEW_LINE> self.contract_address = contract_address <NEW_LINE> <DEDENT> def assert_valid( self, method_name: str, parameter_name: str, argument_value: Any ) -> None: <NEW_LINE> <INDENT> if parameter_name == "order": <NEW_LINE> <INDENT> json_schemas.assert_valid( order_to_jsdict(argument_value, self.contract_address), "/orderSchema", ) <NEW_LINE> <DEDENT> if parameter_name == "orders": <NEW_LINE> <INDENT> for order in argument_value: <NEW_LINE> <INDENT> json_schemas.assert_valid( order_to_jsdict(order, self.contract_address), "/orderSchema", ) | Validate inputs to Exchange methods. | 6259905e097d151d1a2c26c7 |
class TwitterStreamer(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.twitter_authenticator=TwitterAuthenticator() <NEW_LINE> <DEDENT> def stream_tweets(self,fetched_tweets_filename,hash_tag_list): <NEW_LINE> <INDENT> Listener = TwitterListener() <NEW_LINE> auth = OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET) <NEW_LINE> auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET) <NEW_LINE> stream = Stream(auth, Listener) <NEW_LINE> stream.filter(track=hash_tag_list) | class for streaming and processing live tweets | 6259905ee64d504609df9efb |
class ResetButton(Input): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> type = "reset" | A button that resets the contents of the form to default values. Not
recommended. | 6259905ed6c5a102081e377c |
class ClosingIterator(object): <NEW_LINE> <INDENT> def __init__(self, iterable, callbacks=None): <NEW_LINE> <INDENT> iterator = iter(iterable) <NEW_LINE> self._next = iterator.next <NEW_LINE> if callbacks is None: <NEW_LINE> <INDENT> callbacks = [] <NEW_LINE> <DEDENT> elif callable(callbacks): <NEW_LINE> <INDENT> callbacks = [callbacks] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> callbacks = list(callbacks) <NEW_LINE> <DEDENT> iterable_close = getattr(iterator, 'close', None) <NEW_LINE> if iterable_close: <NEW_LINE> <INDENT> callbacks.insert(0, iterable_close) <NEW_LINE> <DEDENT> self._callbacks = callbacks <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> return self._next() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> for callback in self._callbacks: <NEW_LINE> <INDENT> callback() | The WSGI specification requires that all middlewares and gateways
respect the `close` callback of an iterator. Because it is useful to add
another close action to a returned iterator and adding a custom iterator
is a boring task this class can be used for that::
return ClosingIterator(app(environ, start_response), [cleanup_session,
cleanup_locals])
If there is just one close function it can be passed instead of the list.
A closing iterator is not needed if the application uses response objects
and finishes the processing if the response is started::
try:
return response(environ, start_response)
finally:
cleanup_session()
cleanup_locals() | 6259905e3539df3088ecd8f5 |
class DBSaver: <NEW_LINE> <INDENT> conn = None <NEW_LINE> def __init__(self, db_name): <NEW_LINE> <INDENT> self.db_name = db_name <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.conn = sqlite3.connect(self.db_name) <NEW_LINE> <DEDENT> def return_cursor(self): <NEW_LINE> <INDENT> if self.conn is not None: <NEW_LINE> <INDENT> cursor = self.conn.cursor() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.connect() <NEW_LINE> cursor = self.conn.cursor() <NEW_LINE> <DEDENT> return cursor <NEW_LINE> <DEDENT> def select_query(self, query): <NEW_LINE> <INDENT> cursor = self.return_cursor() <NEW_LINE> cursor.execute(query) <NEW_LINE> result = cursor.fetchall() <NEW_LINE> result = np.array(result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def other_query(self, query): <NEW_LINE> <INDENT> cursor = self.return_cursor() <NEW_LINE> cursor.execute(query) <NEW_LINE> self.conn.commit() | Saves pandas dataframe into sqlite table.
Parameters:
----------
db_name string,
name of database to interact with | 6259905e55399d3f05627b79 |
class DeblendedParent: <NEW_LINE> <INDENT> def __init__(self, filterName, footprint, maskedImage, psf, psffwhm, avgNoise, maxNumberOfPeaks, debResult): <NEW_LINE> <INDENT> self.filter = filterName <NEW_LINE> self.fp = footprint <NEW_LINE> self.maskedImage = maskedImage <NEW_LINE> self.psf = psf <NEW_LINE> self.psffwhm = psffwhm <NEW_LINE> self.img = maskedImage.getImage() <NEW_LINE> self.imbb = self.img.getBBox() <NEW_LINE> self.varimg = maskedImage.getVariance() <NEW_LINE> self.mask = maskedImage.getMask() <NEW_LINE> self.avgNoise = avgNoise <NEW_LINE> self.updateFootprintBbox() <NEW_LINE> self.debResult = debResult <NEW_LINE> self.peakCount = debResult.peakCount <NEW_LINE> self.templateSum = None <NEW_LINE> if avgNoise is None: <NEW_LINE> <INDENT> stats = afwMath.makeStatistics(self.varimg, self.mask, afwMath.MEDIAN) <NEW_LINE> avgNoise = np.sqrt(stats.getValue(afwMath.MEDIAN)) <NEW_LINE> debResult.log.trace('Estimated avgNoise for filter %s = %f', self.filter, avgNoise) <NEW_LINE> <DEDENT> self.avgNoise = avgNoise <NEW_LINE> self.peaks = [] <NEW_LINE> peaks = self.fp.getPeaks() <NEW_LINE> for idx in range(self.peakCount): <NEW_LINE> <INDENT> deblendedPeak = DeblendedPeak(peaks[idx], idx, self) <NEW_LINE> self.peaks.append(deblendedPeak) <NEW_LINE> <DEDENT> <DEDENT> def updateFootprintBbox(self): <NEW_LINE> <INDENT> self.bb = self.fp.getBBox() <NEW_LINE> if not self.imbb.contains(self.bb): <NEW_LINE> <INDENT> raise ValueError(('Footprint bounding-box %s extends outside image bounding-box %s') % (str(self.bb), str(self.imbb))) <NEW_LINE> <DEDENT> self.W, self.H = self.bb.getWidth(), self.bb.getHeight() <NEW_LINE> self.x0, self.y0 = self.bb.getMinX(), self.bb.getMinY() <NEW_LINE> self.x1, self.y1 = self.bb.getMaxX(), self.bb.getMaxY() | Deblender result of a single parent footprint, in a single band
Convenience class to store useful objects used by the deblender for a single band,
such as the maskedImage, psf, etc as well as the results from the deblender.
Parameters
----------
filterName: `str`
Name of the filter used for `maskedImage`
footprint: list of `afw.detection.Footprint`s
Parent footprint to deblend in each band.
maskedImages: list of `afw.image.MaskedImageF`s
Masked image containing the ``footprint`` in each band.
psf: list of `afw.detection.Psf`s
Psf of the ``maskedImage`` for each band.
psffwhm: list of `float`s
FWHM of the ``maskedImage``'s ``psf`` in each band.
avgNoise: `float`or list of `float`s, optional
Average noise level in each ``maskedImage``.
The default is ``None``, which estimates the noise from the median value of the
variance plane of ``maskedImage`` for each filter.
maxNumberOfPeaks: `int`, optional
If positive, the maximum number of peaks to deblend.
If the total number of peaks is greater than ``maxNumberOfPeaks``,
then only the first ``maxNumberOfPeaks`` sources are deblended.
The default is 0, which deblends all of the peaks.
debResult: `DeblenderResult`
The ``DeblenderResult`` that contains this ``DeblendedParent``. | 6259905ea219f33f346c7e5f |
class TestUrlWithStoragesAndOverrides(TankTestBase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestUrlWithStoragesAndOverrides, self).setUp() <NEW_LINE> self.setup_fixtures() <NEW_LINE> self.storage = { "type": "LocalStorage", "id": 1, "code": "storage_1", "windows_path": r"\\storage_win", } <NEW_LINE> self.add_to_sg_mock_db([self.storage]) <NEW_LINE> <DEDENT> def test_augument_local_storage(self): <NEW_LINE> <INDENT> sg_dict = { "id": 123, "type": "PublishedFile", "code": "foo", "path": { "url": "file://storage_win/path/to/file", "type": "Attachment", "name": "bar.baz", "link_type": "web", "content_type": None, }, } <NEW_LINE> os.environ["SHOTGUN_PATH_MAC_STORAGE_1"] = "/storage_mac" <NEW_LINE> os.environ["SHOTGUN_PATH_LINUX_STORAGE_1"] = "/storage_linux" <NEW_LINE> expected_path = { "win32": r"\\storage_win\path\to\file", "linux2": "/storage_linux/path/to/file", "darwin": "/storage_mac/path/to/file", }[sgsix.platform] <NEW_LINE> evaluated_path = sgtk.util.resolve_publish_path(self.tk, sg_dict) <NEW_LINE> self.assertEqual(evaluated_path, expected_path) | Tests file:// url resolution with local storages and environment overrides | 6259905e29b78933be26abf1 |
class FeatResults(object): <NEW_LINE> <INDENT> def __init__(self, results, json_file): <NEW_LINE> <INDENT> with open(json_file) as data: <NEW_LINE> <INDENT> feature_data = json.load(data) <NEW_LINE> <DEDENT> self.feat_fractions = {} <NEW_LINE> self.feat_status = {} <NEW_LINE> self.features = set() <NEW_LINE> self.results = results <NEW_LINE> profiles = {} <NEW_LINE> profile_orig = profile.load_test_profile(results[0].options['profile'][0]) <NEW_LINE> for feature in feature_data: <NEW_LINE> <INDENT> self.features.add(feature) <NEW_LINE> incl_str = feature_data[feature]["include_tests"] <NEW_LINE> excl_str = feature_data[feature]["exclude_tests"] <NEW_LINE> include_filter = [incl_str] if incl_str and not incl_str.isspace() else [] <NEW_LINE> exclude_filter = [excl_str] if excl_str and not excl_str.isspace() else [] <NEW_LINE> opts = core.Options(include_filter=include_filter, exclude_filter=exclude_filter) <NEW_LINE> profiles[feature] = copy.deepcopy(profile_orig) <NEW_LINE> try: <NEW_LINE> <INDENT> profiles[feature]._prepare_test_list(opts) <NEW_LINE> <DEDENT> except exceptions.PiglitFatalError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> for results in self.results: <NEW_LINE> <INDENT> self.feat_fractions[results.name] = {} <NEW_LINE> self.feat_status[results.name] = {} <NEW_LINE> for feature in feature_data: <NEW_LINE> <INDENT> result_set = set(results.tests) <NEW_LINE> profile_set = set(profiles[feature].test_list) <NEW_LINE> common_set = profile_set & result_set <NEW_LINE> passed_list = [x for x in common_set if results.tests[x].result == status.PASS] <NEW_LINE> total = len(common_set) <NEW_LINE> passed = len(passed_list) <NEW_LINE> self.feat_fractions[results.name][feature] = (passed, total) <NEW_LINE> if total == 0: <NEW_LINE> <INDENT> self.feat_status[results.name][feature] = status.NOTRUN <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if 100 * passed // total >= feature_data[feature]["target_rate"]: <NEW_LINE> <INDENT> self.feat_status[results.name][feature] = status.PASS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.feat_status[results.name][feature] = status.FAIL | Container object for results.
Has the results, feature profiles and feature computed results. | 6259905e45492302aabfdb33 |
class CanineModelBuilder(GenericModelBuilder): <NEW_LINE> <INDENT> def __init__(self, model_config: canine_modeling.CanineModelConfig): <NEW_LINE> <INDENT> self.model_config = model_config <NEW_LINE> <DEDENT> def create_encoder_model(self, is_training, input_ids, input_mask, segment_ids): <NEW_LINE> <INDENT> return canine_modeling.CanineModel( config=self.model_config, atom_input_ids=input_ids, atom_input_mask=input_mask, atom_segment_ids=segment_ids, is_training=is_training) | Class for constructing a TyDi QA model based on CANINE. | 6259905e4e4d562566373a61 |
class SCENE_OT_close_report_error(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "{}.close_report_error".format(makeBashSafe(addon_name.lower(), replace_with="_")) <NEW_LINE> bl_label = "Close Report Error" <NEW_LINE> bl_options = {"REGISTER", "UNDO"} <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> txt = bpy.data.texts[addon_name + " log"] <NEW_LINE> bpy.data.texts.remove(txt, do_unlink=True) <NEW_LINE> return{"FINISHED"} | Deletes error report from blender's memory (still exists in file system) | 6259905ebaa26c4b54d50900 |
class MarketAPITestCase(APITestCase): <NEW_LINE> <INDENT> client_class = MarketAPIClient <NEW_LINE> def assertFieldEqual(self, response, field, value): <NEW_LINE> <INDENT> self.assertEqual(response.data.get(field), value) <NEW_LINE> <DEDENT> def assert200(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_200_OK, response.status_code, response.data) <NEW_LINE> <DEDENT> def assert201(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.data) <NEW_LINE> <DEDENT> def assert204(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code, response.data) <NEW_LINE> <DEDENT> def assert400(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.data) <NEW_LINE> <DEDENT> def assert403(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_403_FORBIDDEN, response.status_code, response.data) <NEW_LINE> <DEDENT> def assert404(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code, response.data) <NEW_LINE> <DEDENT> def assert405(self, response): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> self.assertEqual(status.HTTP_405_METHOD_NOT_ALLOWED, response.status_code, response.data) <NEW_LINE> <DEDENT> def assertResultsLen(self, response, length): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> assert isinstance(length, int) <NEW_LINE> self.assertEqual(len(response.data.get('results')), length) <NEW_LINE> <DEDENT> def assertRequiredFields(self, response, required_fields, status_code=400): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> for field in required_fields: <NEW_LINE> <INDENT> self.assertContains(response, field, status_code=status_code) <NEW_LINE> <DEDENT> <DEDENT> def assertNonVisibleFields(self, response, fields, status_code=200): <NEW_LINE> <INDENT> check_response_type(response) <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> self.assertNotContains(response, field, status_code=status_code) <NEW_LINE> <DEDENT> <DEDENT> def assertLogin(self, username, password): <NEW_LINE> <INDENT> data = {'email': username, 'password': password} <NEW_LINE> response = self.client.post('/api-token-auth/', data) <NEW_LINE> self.assert200(response) <NEW_LINE> self.assertContains(response, 'token', status_code=200) <NEW_LINE> <DEDENT> def assertCannotLogin(self, username, password): <NEW_LINE> <INDENT> data = {'email': username, 'password': password} <NEW_LINE> response = self.client.post('/api-token-auth/', data) <NEW_LINE> self.assert400(response) <NEW_LINE> self.assertNonFieldErrors(response, 'Unable to login with provided credentials.') <NEW_LINE> <DEDENT> def assertObjFieldEqual(self, obj, field, value): <NEW_LINE> <INDENT> self.assertEqual(getattr(obj, field), value) | Custom APITestCase that provides a APIClient with
some nice methods and some extra assert methods
for common use cases | 6259905e0c0af96317c5788c |
class RatingStar(models.Model): <NEW_LINE> <INDENT> value = models.SmallIntegerField('Currency', default=0) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'{self.value}' <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Rating Star' <NEW_LINE> verbose_name_plural = 'Rating Stars' <NEW_LINE> ordering = ['-value'] | Rating stars | 6259905e7d43ff2487427f3d |
class APIBase(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__connect_timeout = 5.0 <NEW_LINE> self.__socket_timeout = 5.0 <NEW_LINE> self.__proxies = {} <NEW_LINE> <DEDENT> def set_connection_timeout(self, second): <NEW_LINE> <INDENT> self.__connect_timeout = second <NEW_LINE> <DEDENT> def set_socket_timeout(self, second): <NEW_LINE> <INDENT> self.__socket_timeout = second <NEW_LINE> <DEDENT> def set_proxies(self, proxies): <NEW_LINE> <INDENT> self.__proxies = proxies <NEW_LINE> <DEDENT> def _request(self, method, url, params=None, data=None, json=None, **kw): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resp = requests.request( method.upper().strip(), url, params=params, data=data, json=json, timeout=(self.__connect_timeout, self.__socket_timeout), proxies=self.__proxies, **kw ) <NEW_LINE> data = resp.json() <NEW_LINE> <DEDENT> except (ReadTimeout, ConnectTimeout): <NEW_LINE> <INDENT> return { "ret_code": "sdk001", "message": "connection or read data timeout", } <NEW_LINE> <DEDENT> except JSONDecodeError: <NEW_LINE> <INDENT> return { "ret_code": "sdk002", "message": "invalid json data", } <NEW_LINE> <DEDENT> except RequestException as e: <NEW_LINE> <INDENT> return { "ret_code": "sdk003", "message": str(e), } <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> _get = partialmethod(_request, "GET") <NEW_LINE> _post = partialmethod(_request, "POST") <NEW_LINE> _put = partialmethod(_request, "PUT") <NEW_LINE> _delete = partialmethod(_request, "DELETE") | 自定义web请求类,封装requests | 6259905e435de62698e9d460 |
class DefaultMeta(object): <NEW_LINE> <INDENT> pass | Default Meta for a Djid | 6259905e8e7ae83300eea6e8 |
class Solver: <NEW_LINE> <INDENT> def __init__(self, cube): <NEW_LINE> <INDENT> self.cube = cube <NEW_LINE> self.result = None <NEW_LINE> self.expanded = 0 <NEW_LINE> self.ops = ['F', 'B', 'R', 'L', 'U', 'D', 'rF', 'rB', 'rR', 'rL', 'rU', 'rD'] <NEW_LINE> self.rops = ['rF', 'rB', 'rR', 'rL', 'rU', 'rD', 'F', 'B', 'R', 'L', 'U', 'D'] <NEW_LINE> <DEDENT> def solve(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getResult(self): <NEW_LINE> <INDENT> return self.__parseInstructions(self.result) <NEW_LINE> <DEDENT> def __parseInstructions(self, instructions): <NEW_LINE> <INDENT> res, i = [], 0 <NEW_LINE> while i < len(instructions): <NEW_LINE> <INDENT> if instructions[i] == 'r': <NEW_LINE> <INDENT> res.append(instructions[i]+instructions[i+1]) <NEW_LINE> i += 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res.append(instructions[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> def getNodeExpanded(self): <NEW_LINE> <INDENT> return self.expanded | Abstract class solver.
Define helper properties and functions for other solvers. | 6259905ed99f1b3c44d06cfd |
class TemplateState(State): <NEW_LINE> <INDENT> def __init__(self, hass, state): <NEW_LINE> <INDENT> self._hass = hass <NEW_LINE> self._state = state <NEW_LINE> <DEDENT> def _access_state(self): <NEW_LINE> <INDENT> state = object.__getattribute__(self, '_state') <NEW_LINE> hass = object.__getattribute__(self, '_hass') <NEW_LINE> _collect_state(hass, state.entity_id) <NEW_LINE> return state <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_with_unit(self): <NEW_LINE> <INDENT> state = object.__getattribute__(self, '_access_state')() <NEW_LINE> unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) <NEW_LINE> if unit is None: <NEW_LINE> <INDENT> return state.state <NEW_LINE> <DEDENT> return "{} {}".format(state.state, unit) <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> if name == 'entity_id' or name in object.__dict__: <NEW_LINE> <INDENT> state = object.__getattribute__(self, '_state') <NEW_LINE> return getattr(state, name) <NEW_LINE> <DEDENT> if name in TemplateState.__dict__: <NEW_LINE> <INDENT> return object.__getattribute__(self, name) <NEW_LINE> <DEDENT> state = object.__getattribute__(self, '_access_state')() <NEW_LINE> return getattr(state, name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> state = object.__getattribute__(self, '_access_state')() <NEW_LINE> rep = state.__repr__() <NEW_LINE> return '<template ' + rep[1:] | Class to represent a state object in a template. | 6259905e01c39578d7f14264 |
class _UnreadVariable(ResourceVariable): <NEW_LINE> <INDENT> def __init__(self, handle, dtype, shape, in_graph_mode, deleter, parent_op, unique_id): <NEW_LINE> <INDENT> self._trainable = False <NEW_LINE> self._synchronization = None <NEW_LINE> self._aggregation = None <NEW_LINE> self._save_slice_info = None <NEW_LINE> self._graph_key = ops.get_default_graph()._graph_key <NEW_LINE> self._in_graph_mode = in_graph_mode <NEW_LINE> self._handle = handle <NEW_LINE> self._shape = shape <NEW_LINE> self._initial_value = None <NEW_LINE> if isinstance(self._handle, ops.EagerTensor): <NEW_LINE> <INDENT> self._handle_name = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._handle_name = self._handle.name <NEW_LINE> <DEDENT> self._unique_id = unique_id <NEW_LINE> self._dtype = dtype <NEW_LINE> self._constraint = None <NEW_LINE> self._cached_value = None <NEW_LINE> self._is_initialized_op = None <NEW_LINE> self._initializer_op = None <NEW_LINE> self._parent_op = parent_op <NEW_LINE> if (context.executing_eagerly() or ops.get_default_graph()._building_function): <NEW_LINE> <INDENT> self._graph_element = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._graph_element = self.read_value() <NEW_LINE> <DEDENT> self._handle_deleter = deleter <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> if self._in_graph_mode: <NEW_LINE> <INDENT> return self._parent_op.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "UnreadVariable" <NEW_LINE> <DEDENT> <DEDENT> def value(self): <NEW_LINE> <INDENT> return self._read_variable_op() <NEW_LINE> <DEDENT> def read_value(self): <NEW_LINE> <INDENT> return self._read_variable_op() <NEW_LINE> <DEDENT> def _read_variable_op(self): <NEW_LINE> <INDENT> with ops.control_dependencies([self._parent_op]): <NEW_LINE> <INDENT> result = gen_resource_variable_ops.read_variable_op(self._handle, self._dtype) <NEW_LINE> _maybe_set_handle_data(self._dtype, self._handle, result) <NEW_LINE> return result <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def op(self): <NEW_LINE> <INDENT> return self._parent_op | Represents a future for a read of a variable.
Pretends to be the tensor if anyone looks. | 6259905e097d151d1a2c26ca |
class Tokenizer(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.token_to_str = {} <NEW_LINE> self.str_to_token = {} <NEW_LINE> self.counter = 0 <NEW_LINE> <DEDENT> def Normalize(self, s): <NEW_LINE> <INDENT> black_words = ['spp'] <NEW_LINE> parts = re.split(r'\W+', s.strip()) <NEW_LINE> parts = [part.lower() for part in parts] <NEW_LINE> parts = [part for part in parts if part not in black_words] <NEW_LINE> is_color = np.asarray([part in _COLORS for part in parts]) <NEW_LINE> if np.any(is_color): <NEW_LINE> <INDENT> parts = tuple(parts[np.flatnonzero(is_color)[0]]) <NEW_LINE> <DEDENT> return tuple(parts) <NEW_LINE> <DEDENT> def TokenForStr(self, s, similarity_thres=None): <NEW_LINE> <INDENT> blacklist = ['perennial', 'bergenia'] <NEW_LINE> aliases = _ALIASES <NEW_LINE> s_norm = self.Normalize(s) <NEW_LINE> s_norm_joined = ' '.join(s_norm) <NEW_LINE> if s_norm_joined in aliases: <NEW_LINE> <INDENT> s_norm = aliases[s_norm_joined] <NEW_LINE> <DEDENT> if s_norm not in self.str_to_token: <NEW_LINE> <INDENT> if similarity_thres is not None: <NEW_LINE> <INDENT> for token in self.token_to_str: <NEW_LINE> <INDENT> s_token = self.StrForToken(token) <NEW_LINE> sim = util.StringSim(s_token, s_norm_joined) <NEW_LINE> if sim > similarity_thres and (s_norm_joined not in blacklist): <NEW_LINE> <INDENT> self.str_to_token[s_norm] = token <NEW_LINE> return token <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.str_to_token[s_norm] = self.counter <NEW_LINE> self.counter += 1 <NEW_LINE> <DEDENT> token = self.str_to_token[s_norm] <NEW_LINE> self.token_to_str[token] = s_norm <NEW_LINE> return token <NEW_LINE> <DEDENT> def StrForToken(self, token): <NEW_LINE> <INDENT> if token in self.token_to_str: <NEW_LINE> <INDENT> s = ' '.join(self.token_to_str[token]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = 'Token %d' % token <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def StringList(self, n_tokens=None): <NEW_LINE> <INDENT> if n_tokens is None: <NEW_LINE> <INDENT> n_tokens = self.TokenCount() <NEW_LINE> <DEDENT> strings = [self.StrForToken(token) for token in range(n_tokens)] <NEW_LINE> strings = pandas.Series(strings, name='str') <NEW_LINE> return strings <NEW_LINE> <DEDENT> def TokenCount(self): <NEW_LINE> <INDENT> return len(self.token_to_str) | Assigns a unique token to each string in a corpus.
Attributes:
token_to_str: A dictionary mapping integer tokens to normalized strings
str_to_token: A dictionary mapping normalized strings to token IDs | 6259905ed6c5a102081e377e |
class IndexTestCase(NodeAPITestCase): <NEW_LINE> <INDENT> def test_status_code(self): <NEW_LINE> <INDENT> rv = self.app.get('/') <NEW_LINE> assert rv.status_code == 200 <NEW_LINE> <DEDENT> def test_service_type(self): <NEW_LINE> <INDENT> rv = self.app.get('/') <NEW_LINE> data = json.loads(rv.data) <NEW_LINE> assert data.has_key('service') <NEW_LINE> assert data['service'] == 'node' <NEW_LINE> <DEDENT> def test_versions(self): <NEW_LINE> <INDENT> rv = self.app.get('/') <NEW_LINE> data = json.loads(rv.data) <NEW_LINE> assert data.has_key('version') <NEW_LINE> assert data.has_key('api_version') | Test the node API root endpoint for correct infos | 6259905e38b623060ffaa37d |
class SmoothingFunction: <NEW_LINE> <INDENT> def __init__(self, epsilon=0.1, alpha=5, k=5): <NEW_LINE> <INDENT> self.epsilon = epsilon <NEW_LINE> self.alpha = alpha <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def method0(self, p_n, *args, **kwargs): <NEW_LINE> <INDENT> return p_n <NEW_LINE> <DEDENT> def method1(self, p_n, *args, **kwargs): <NEW_LINE> <INDENT> return [(p_i.numerator + self.epsilon)/ p_i.denominator if p_i.numerator == 0 else p_i for p_i in p_n] <NEW_LINE> <DEDENT> def method2(self, p_n, *args, **kwargs): <NEW_LINE> <INDENT> return [Fraction(p_i.numerator + 1, p_i.denominator + 1) for p_i in p_n] <NEW_LINE> <DEDENT> def method3(self, p_n, *args, **kwargs): <NEW_LINE> <INDENT> incvnt = 1 <NEW_LINE> for i, p_i in enumerate(p_n): <NEW_LINE> <INDENT> if p_i == 0: <NEW_LINE> <INDENT> p_n[i] = 1 / (2**incvnt * p_i.denominator) <NEW_LINE> incvnt+=1 <NEW_LINE> <DEDENT> <DEDENT> return p_n <NEW_LINE> <DEDENT> def method4(self, p_n, references, hypothesis, hyp_len): <NEW_LINE> <INDENT> incvnt = 1 <NEW_LINE> for i, p_i in enumerate(p_n): <NEW_LINE> <INDENT> if p_i == 0 and hyp_len != 0: <NEW_LINE> <INDENT> p_n[i] = incvnt * self.k / math.log(hyp_len) <NEW_LINE> incvnt+=1 <NEW_LINE> <DEDENT> <DEDENT> return p_n <NEW_LINE> <DEDENT> def method5(self, p_n, references, hypothesis, hyp_len): <NEW_LINE> <INDENT> m = {} <NEW_LINE> p_n_plus1 = p_n + [_modified_precision(references, hypothesis, 5)] <NEW_LINE> m[-1] = p_n[0] + 1 <NEW_LINE> for i, p_i in enumerate(p_n): <NEW_LINE> <INDENT> p_n[i] = (m[i-1] + p_i + p_n_plus1[i+1]) / 3 <NEW_LINE> m[i] = p_n[i] <NEW_LINE> <DEDENT> return p_n <NEW_LINE> <DEDENT> def method6(self, p_n, references, hypothesis, hyp_len): <NEW_LINE> <INDENT> for i, p_i in enumerate(p_n): <NEW_LINE> <INDENT> if i in [1,2]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pi0 = 0 if p_n[i-2] == 0 else p_n[i-1]**2 / p_n[i-2] <NEW_LINE> l = sum(1 for _ in ngrams(hypothesis, i+1)) <NEW_LINE> p_n[i] = (p_i + self.alpha * pi0) / (l + self.alpha) <NEW_LINE> <DEDENT> <DEDENT> return p_n <NEW_LINE> <DEDENT> def method7(self, p_n, references, hypothesis, hyp_len): <NEW_LINE> <INDENT> p_n = self.method4(p_n, references, hypothesis, hyp_len) <NEW_LINE> p_n = self.method5(p_n, references, hypothesis, hyp_len) <NEW_LINE> return p_n | This is an implementation of the smoothing techniques
for segment-level BLEU scores that was presented in
Boxing Chen and Collin Cherry (2014) A Systematic Comparison of
Smoothing Techniques for Sentence-Level BLEU. In WMT14.
http://acl2014.org/acl2014/W14-33/pdf/W14-3346.pdf | 6259905ea8ecb03325872873 |
class SimpleRegistrationBackendTests(TestCase): <NEW_LINE> <INDENT> backend = SimpleBackend() <NEW_LINE> def test_registration(self): <NEW_LINE> <INDENT> new_user = self.backend.register(_mock_request(), username='bob', email='[email protected]', password1='secret') <NEW_LINE> self.assertEqual(new_user.username, 'bob') <NEW_LINE> self.failUnless(new_user.check_password('secret')) <NEW_LINE> self.assertEqual(new_user.email, '[email protected]') <NEW_LINE> self.failUnless(new_user.is_active) <NEW_LINE> <DEDENT> def test_allow(self): <NEW_LINE> <INDENT> old_allowed = getattr(settings, 'REGISTRATION_OPEN', True) <NEW_LINE> settings.REGISTRATION_OPEN = True <NEW_LINE> self.failUnless(self.backend.registration_allowed(_mock_request())) <NEW_LINE> settings.REGISTRATION_OPEN = False <NEW_LINE> self.failIf(self.backend.registration_allowed(_mock_request())) <NEW_LINE> settings.REGISTRATION_OPEN = old_allowed <NEW_LINE> <DEDENT> def test_form_class(self): <NEW_LINE> <INDENT> self.failUnless(self.backend.get_form_class(_mock_request()) is forms.RegistrationForm) <NEW_LINE> <DEDENT> def test_post_registration_redirect(self): <NEW_LINE> <INDENT> new_user = self.backend.register(_mock_request(), username='bob', email='[email protected]', password1='secret') <NEW_LINE> self.assertEqual(self.backend.post_registration_redirect(_mock_request(), new_user), (new_user.get_absolute_url(), (), {})) <NEW_LINE> <DEDENT> def test_registration_signal(self): <NEW_LINE> <INDENT> def receiver(sender, **kwargs): <NEW_LINE> <INDENT> self.failUnless('user' in kwargs) <NEW_LINE> self.assertEqual(kwargs['user'].username, 'bob') <NEW_LINE> self.failUnless('request' in kwargs) <NEW_LINE> self.failUnless(isinstance(kwargs['request'], WSGIRequest)) <NEW_LINE> received_signals.append(kwargs.get('signal')) <NEW_LINE> <DEDENT> received_signals = [] <NEW_LINE> signals.user_registered.connect(receiver, sender=self.backend.__class__) <NEW_LINE> self.backend.register(_mock_request(), username='bob', email='[email protected]', password1='secret') <NEW_LINE> self.assertEqual(len(received_signals), 1) <NEW_LINE> self.assertEqual(received_signals, [signals.user_registered]) <NEW_LINE> <DEDENT> def test_activation(self): <NEW_LINE> <INDENT> self.assertRaises(NotImplementedError, self.backend.activate, request=_mock_request()) <NEW_LINE> <DEDENT> def test_post_activation_redirect(self): <NEW_LINE> <INDENT> self.assertRaises(NotImplementedError, self.backend.post_activation_redirect, request=_mock_request(), user=User()) | Test the simple registration backend, which does signup and
immediate activation. | 6259905efff4ab517ebcee81 |
class LocationSerializerWithStoryImages(LocationSerializerWithStoryTitle): <NEW_LINE> <INDENT> stories = StoryImageSerializer(many=True) | Serializes a Location and the attached stories using the StoryImageSerializer | 6259905ee5267d203ee6ceed |
class Cleaner(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__files = [] <NEW_LINE> <DEDENT> def Add(self, filename): <NEW_LINE> <INDENT> self.__files.append(filename) <NEW_LINE> <DEDENT> def HasFiles(self): <NEW_LINE> <INDENT> return self.__files <NEW_LINE> <DEDENT> def GetFiles(self): <NEW_LINE> <INDENT> return self.__files <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> for filename in self.__files: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(filename) <NEW_LINE> <DEDENT> except (OSError, IOError) as ex: <NEW_LINE> <INDENT> log.error('Error deleting [%s]: %s', filename, ex) | Class to manage cleanup of a set of files.
Instances of this class are callable, when called they delete all of the
files. | 6259905ea8370b77170f1a2a |
class MeanSquaredError(Cost_ABC) : <NEW_LINE> <INDENT> def run(self, targets, outputs, stream) : <NEW_LINE> <INDENT> cost = tt.mean((outputs - targets) ** 2) <NEW_LINE> return cost | The all time classic | 6259905e3eb6a72ae038bcbc |
class ModelStrategyExecuter(models.Model): <NEW_LINE> <INDENT> code = models.CharField(u'代码', max_length=50) <NEW_LINE> name = models.CharField(u'名称', max_length=100) <NEW_LINE> account = models.ForeignKey('ModelAccount', verbose_name=u'账号', blank=True, null=True) <NEW_LINE> dataGenerator = models.ForeignKey('ModelDataGenerator', verbose_name=u'数据生成') <NEW_LINE> strategyDir = models.CharField(u'策略程序所在目录', max_length=500) <NEW_LINE> strategyProgram = models.CharField(u'策略程序名称', max_length=100) <NEW_LINE> strategyConfig = models.CharField(u'策略配置文件', max_length=100) <NEW_LINE> instrumentIdList = models.CharField(u'品种列表', max_length=500) <NEW_LINE> volume = models.FloatField(u'默认头寸大小', default=1) <NEW_LINE> maxBuyPosition = models.IntegerField(u'最大做多头寸数量', default=1) <NEW_LINE> maxSellPosition = models.IntegerField(u'最大做多头寸数量', default=1) <NEW_LINE> traderClass = models.CharField(u'交易接口类型', max_length=30, choices=TRADER_CLASS) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = u'策略执行器' <NEW_LINE> verbose_name_plural = u'[07].策略执行器' | 策略执行器 | 6259905e7b25080760ed880e |
class JistBrainMp2rageSkullStripping(SEMLikeCommandLine): <NEW_LINE> <INDENT> input_spec = JistBrainMp2rageSkullStrippingInputSpec <NEW_LINE> output_spec = JistBrainMp2rageSkullStrippingOutputSpec <NEW_LINE> _cmd = "java edu.jhu.ece.iacl.jist.cli.run de.mpg.cbs.jist.brain.JistBrainMp2rageSkullStripping " <NEW_LINE> _outputs_filenames = {'outBrain': 'outBrain.nii', 'outMasked3': 'outMasked3.nii', 'outMasked2': 'outMasked2.nii', 'outMasked': 'outMasked.nii'} <NEW_LINE> _redirect_x = True | title: MP2RAGE Skull Stripping
category: Developer Tools
description: Estimate a brain mask for a MP2RAGE dataset. At least a T1-weighted or a T1 map image is required.
version: 3.0.RC | 6259905e7cff6e4e811b70a1 |
class CommandFailedError(BaseError): <NEW_LINE> <INDENT> def __init__(self, cmd, msg, device=None): <NEW_LINE> <INDENT> super(CommandFailedError, self).__init__( (('device %s: ' % device) if device else '') + 'adb command \'%s\' failed with message: \'%s\'' % (' '.join(cmd), msg)) | Exception for command failures. | 6259905e7d847024c075da2f |
class DefaultEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, datetime.datetime): <NEW_LINE> <INDENT> return int(mktime(obj.timetuple())) <NEW_LINE> <DEDENT> return json.JSONEncoder.default(self, obj) | Encode for the json. | 6259905e45492302aabfdb36 |
class TestCreateDateRangeFilter(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.repo_config = { constants.PUBLISH_HTTPS_KEYWORD: True, constants.PUBLISH_HTTP_KEYWORD: False, } <NEW_LINE> self.start_date = '2010-01-01 12:00:00' <NEW_LINE> self.end_date = '2010-01-02 12:00:00' <NEW_LINE> <DEDENT> def test_no_filter(self): <NEW_LINE> <INDENT> date = export_utils.create_date_range_filter(PluginCallConfiguration({}, self.repo_config)) <NEW_LINE> self.assertTrue(date is None) <NEW_LINE> <DEDENT> def test_start_date_only(self): <NEW_LINE> <INDENT> self.repo_config[constants.START_DATE_KEYWORD] = self.start_date <NEW_LINE> config = PluginCallConfiguration({}, self.repo_config) <NEW_LINE> expected = mongoengine.Q(created__gte=self.start_date) <NEW_LINE> date_filter = export_utils.create_date_range_filter(config) <NEW_LINE> self.assertDictEqual(expected.query, date_filter.query) <NEW_LINE> <DEDENT> def test_end_date_only(self): <NEW_LINE> <INDENT> self.repo_config[constants.END_DATE_KEYWORD] = self.end_date <NEW_LINE> config = PluginCallConfiguration({}, self.repo_config) <NEW_LINE> expected = mongoengine.Q(created__lte=self.end_date) <NEW_LINE> date_filter = export_utils.create_date_range_filter(config) <NEW_LINE> self.assertDictEqual(expected.query, date_filter.query) <NEW_LINE> <DEDENT> def test_start_and_end_date(self): <NEW_LINE> <INDENT> self.repo_config[constants.START_DATE_KEYWORD] = self.start_date <NEW_LINE> self.repo_config[constants.END_DATE_KEYWORD] = self.end_date <NEW_LINE> config = PluginCallConfiguration({}, self.repo_config) <NEW_LINE> expected = mongoengine.Q(created__gte=self.start_date, created__lte=self.end_date) <NEW_LINE> date_filter = export_utils.create_date_range_filter(config) <NEW_LINE> self.assertDictEqual(expected.query, date_filter.query) | Tests for the create_date_range_filter method in export_utils | 6259905e56ac1b37e6303815 |
class TileListagemHorizontal(BaseTile): <NEW_LINE> <INDENT> security = ClassSecurityInfo() <NEW_LINE> implements(ITileListagemHorizontal) <NEW_LINE> portal_type = 'TileListagemHorizontal' <NEW_LINE> _at_rename_after_creation = True <NEW_LINE> schema = TileListagemHorizontal_schema <NEW_LINE> def voc_list_types(self): <NEW_LINE> <INDENT> types = [] <NEW_LINE> for item in LIST_PLONETYPES: <NEW_LINE> <INDENT> obj = self.portal_types[item] <NEW_LINE> types.append( (item,obj.title) ) <NEW_LINE> <DEDENT> return types <NEW_LINE> <DEDENT> columns = 12 <NEW_LINE> scripts_js = ['/++resource++vindula.tile/js/ajax_boll_batch.js'] | Reserve Content for TileListagemHorizontal | 6259905ee76e3b2f99fda05c |
class FilesAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Files <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> user = super(FilesAdmin, self).save(commit=False) <NEW_LINE> if commit: <NEW_LINE> <INDENT> user.save() <NEW_LINE> <DEDENT> return user | A form for creating new users. Includes all the required
fields, plus a repeated password. | 6259905e3cc13d1c6d466d9e |
class TestAuthManager(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_class(cls): <NEW_LINE> <INDENT> ckan.plugins.load('configpermission') <NEW_LINE> <DEDENT> def teardown(self): <NEW_LINE> <INDENT> ckan.model.repo.rebuild_db() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def teardown_class(cls): <NEW_LINE> <INDENT> ckan.plugins.unload('configpermission') <NEW_LINE> <DEDENT> def test_member_role(self): <NEW_LINE> <INDENT> roles = get.member_roles_list({}, {}) <NEW_LINE> assert set([x['value'] for x in roles]) == {u'test_role', u'sysadmin', u'editor', u'member', u'admin', u'reg_user', u'anon_user'} | Tests for the ckanext.configpermission.logic.action.get module.
Specifically tests that overriding parent auth functions will cause
child auth functions to use the overridden version. | 6259905e4a966d76dd5f0550 |
class TestDjango: <NEW_LINE> <INDENT> def django_version(self): <NEW_LINE> <INDENT> output = check_output(['python', '-c', 'import django; print(django.get_version())']) <NEW_LINE> return output.decode(getpreferredencoding()).strip() <NEW_LINE> <DEDENT> def test_django_version(self): <NEW_LINE> <INDENT> assert self.django_version() == '1.9.6' | Test if Django and its libraries are properly installed inside venv | 6259905ecb5e8a47e493ccb4 |
class VRFTenantSerializer(object): <NEW_LINE> <INDENT> def __init__(self, id=None, name=None, rd=None, tenant=None): <NEW_LINE> <INDENT> self.swagger_types = { 'id': 'int', 'name': 'str', 'rd': 'str', 'tenant': 'TenantNestedSerializer' } <NEW_LINE> self.attribute_map = { 'id': 'id', 'name': 'name', 'rd': 'rd', 'tenant': 'tenant' } <NEW_LINE> self._id = id <NEW_LINE> self._name = name <NEW_LINE> self._rd = rd <NEW_LINE> self._tenant = tenant <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def rd(self): <NEW_LINE> <INDENT> return self._rd <NEW_LINE> <DEDENT> @rd.setter <NEW_LINE> def rd(self, rd): <NEW_LINE> <INDENT> self._rd = rd <NEW_LINE> <DEDENT> @property <NEW_LINE> def tenant(self): <NEW_LINE> <INDENT> return self._tenant <NEW_LINE> <DEDENT> @tenant.setter <NEW_LINE> def tenant(self, tenant): <NEW_LINE> <INDENT> self._tenant = tenant <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> 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. | 6259905e15baa723494635f0 |
class Customer: <NEW_LINE> <INDENT> def view_menu(self): <NEW_LINE> <INDENT> menu = FoodDetails.objects.select_related('category_id').all() <NEW_LINE> return menu <NEW_LINE> <DEDENT> def customer_signup(self, cust_name, cust_phone, cust_email): <NEW_LINE> <INDENT> signup = CustomerDetails( cust_name=cust_name, cust_phone=cust_phone, cust_email=cust_email ) <NEW_LINE> signup.save() <NEW_LINE> return signup <NEW_LINE> <DEDENT> def customer_login(self, cust_id): <NEW_LINE> <INDENT> login = CustomerDetails.objects.get(pk=cust_id) <NEW_LINE> return login <NEW_LINE> <DEDENT> def create_order_id(self, cust_id): <NEW_LINE> <INDENT> order_id = CustOrderStatus(cust_id_id=cust_id) <NEW_LINE> order_id.save() <NEW_LINE> return order_id <NEW_LINE> <DEDENT> def add_food_to_order(self, order_id, food_id, food_qty): <NEW_LINE> <INDENT> add_food = CustOrderSelection(order_id_id=order_id, food_id_id=food_id, food_qty=food_qty) <NEW_LINE> add_food.save() <NEW_LINE> return add_food | Customer's end operation | 6259905e8e71fb1e983bd128 |
class PandasDelegate(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _make_accessor(cls, data): <NEW_LINE> <INDENT> raise AbstractMethodError("_make_accessor should be implemented" "by subclass and return an instance" "of `cls`.") <NEW_LINE> <DEDENT> def _delegate_property_get(self, name, *args, **kwargs): <NEW_LINE> <INDENT> raise TypeError("You cannot access the " "property {name}".format(name=name)) <NEW_LINE> <DEDENT> def _delegate_property_set(self, name, value, *args, **kwargs): <NEW_LINE> <INDENT> raise TypeError("The property {name} cannot be set".format(name=name)) <NEW_LINE> <DEDENT> def _delegate_method(self, name, *args, **kwargs): <NEW_LINE> <INDENT> raise TypeError("You cannot call method {name}".format(name=name)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _add_delegate_accessors(cls, delegate, accessors, typ, overwrite=False): <NEW_LINE> <INDENT> def _create_delegator_property(name): <NEW_LINE> <INDENT> def _getter(self): <NEW_LINE> <INDENT> return self._delegate_property_get(name) <NEW_LINE> <DEDENT> def _setter(self, new_values): <NEW_LINE> <INDENT> return self._delegate_property_set(name, new_values) <NEW_LINE> <DEDENT> _getter.__name__ = name <NEW_LINE> _setter.__name__ = name <NEW_LINE> return property(fget=_getter, fset=_setter, doc=getattr(delegate, name).__doc__) <NEW_LINE> <DEDENT> def _create_delegator_method(name): <NEW_LINE> <INDENT> def f(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._delegate_method(name, *args, **kwargs) <NEW_LINE> <DEDENT> f.__name__ = name <NEW_LINE> f.__doc__ = getattr(delegate, name).__doc__ <NEW_LINE> return f <NEW_LINE> <DEDENT> for name in accessors: <NEW_LINE> <INDENT> if typ == 'property': <NEW_LINE> <INDENT> f = _create_delegator_property(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f = _create_delegator_method(name) <NEW_LINE> <DEDENT> if overwrite or not hasattr(cls, name): <NEW_LINE> <INDENT> setattr(cls, name, f) | an abstract base class for delegating methods/properties | 6259905e56b00c62f0fb3f29 |
class Event(Base): <NEW_LINE> <INDENT> def __init__(my, event_name): <NEW_LINE> <INDENT> my.event_name = event_name <NEW_LINE> my.event_container = WebContainer.get_event_container() <NEW_LINE> <DEDENT> def add_listener(my, script_text, replace=False): <NEW_LINE> <INDENT> my.event_container.add_listener(my.event_name, script_text, replace) <NEW_LINE> <DEDENT> def add_listener_func(my, function_name, replace=False): <NEW_LINE> <INDENT> my.event_container.add_listener_func(my.event_name, function_name, replace) <NEW_LINE> <DEDENT> def get_caller(my): <NEW_LINE> <INDENT> return my.event_container.get_event_caller(my.event_name) | This class is a wrapper around a simple event architecture in javascript
General usage:
To add an event caller:
span = SpanWdg()
span.add("push me")
event_container = WebContainer.get_event_container()
caller = event_container.get_event_caller('event_name')
span.add_event("onclick", caller)
To add a listener:
event_container = WebContainer.get_event_container()
event_contaner.add_listener('event_name', 'alert("cow") )
When an event is called, all of the registered listeners will be executed | 6259905e435de62698e9d463 |
class ManagementGroup(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'server_count': {'key': 'properties.serverCount', 'type': 'int'}, 'is_gateway': {'key': 'properties.isGateway', 'type': 'bool'}, 'name': {'key': 'properties.name', 'type': 'str'}, 'id': {'key': 'properties.id', 'type': 'str'}, 'created': {'key': 'properties.created', 'type': 'iso-8601'}, 'data_received': {'key': 'properties.dataReceived', 'type': 'iso-8601'}, 'version': {'key': 'properties.version', 'type': 'str'}, 'sku': {'key': 'properties.sku', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, server_count: Optional[int] = None, is_gateway: Optional[bool] = None, name: Optional[str] = None, id: Optional[str] = None, created: Optional[datetime.datetime] = None, data_received: Optional[datetime.datetime] = None, version: Optional[str] = None, sku: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagementGroup, self).__init__(**kwargs) <NEW_LINE> self.server_count = server_count <NEW_LINE> self.is_gateway = is_gateway <NEW_LINE> self.name = name <NEW_LINE> self.id = id <NEW_LINE> self.created = created <NEW_LINE> self.data_received = data_received <NEW_LINE> self.version = version <NEW_LINE> self.sku = sku | A management group that is connected to a workspace.
:ivar server_count: The number of servers connected to the management group.
:vartype server_count: int
:ivar is_gateway: Gets or sets a value indicating whether the management group is a gateway.
:vartype is_gateway: bool
:ivar name: The name of the management group.
:vartype name: str
:ivar id: The unique ID of the management group.
:vartype id: str
:ivar created: The datetime that the management group was created.
:vartype created: ~datetime.datetime
:ivar data_received: The last datetime that the management group received data.
:vartype data_received: ~datetime.datetime
:ivar version: The version of System Center that is managing the management group.
:vartype version: str
:ivar sku: The SKU of System Center that is managing the management group.
:vartype sku: str | 6259905e29b78933be26abf3 |
class pesan(object): <NEW_LINE> <INDENT> def __init__(self, sebuahString): <NEW_LINE> <INDENT> self.teks = sebuahString <NEW_LINE> <DEDENT> def cetakIni(self): <NEW_LINE> <INDENT> print(self.teks) <NEW_LINE> <DEDENT> def cetakHurufkapital(self): <NEW_LINE> <INDENT> print(str.upper(self.teks)) <NEW_LINE> <DEDENT> def cetakHurufkecil(self): <NEW_LINE> <INDENT> print(str.lower(self.teks)) <NEW_LINE> <DEDENT> def jamKar(self): <NEW_LINE> <INDENT> return len(self.teks) <NEW_LINE> <DEDENT> def cetakJumlahKarakterku(self): <NEW_LINE> <INDENT> print('kalimatku mempunyai' ,len(self.teks),'karakter.') <NEW_LINE> <DEDENT> def perbarui(self,stringBaru): <NEW_LINE> <INDENT> self.teks = stringBaru <NEW_LINE> <DEDENT> def apakahterkandung(self, string): <NEW_LINE> <INDENT> return string in self.teks <NEW_LINE> <DEDENT> def hitungvokal(self): <NEW_LINE> <INDENT> vok = 0 <NEW_LINE> x = "aiueoAIUEO" <NEW_LINE> for car in self.teks: <NEW_LINE> <INDENT> if car in x: <NEW_LINE> <INDENT> vok += 1 <NEW_LINE> <DEDENT> <DEDENT> return(vok) <NEW_LINE> <DEDENT> def hitungkonsonan(self): <NEW_LINE> <INDENT> vok = 0 <NEW_LINE> x = "aiueoAIUEO" <NEW_LINE> for car in self.teks: <NEW_LINE> <INDENT> if car not in x: <NEW_LINE> <INDENT> vok += 1 <NEW_LINE> <DEDENT> <DEDENT> return(vok) | sebuah class bernama pesan.
untuk memahami konsep class dan object. | 6259905ee5267d203ee6ceee |
class UserProfileFeedViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> authentication_classes = (TokenAuthentication, ) <NEW_LINE> serializer_class = serializers.ProfileFeedItemSerializer <NEW_LINE> queryset = models.ProfileFeedItem.objects.all() <NEW_LINE> permission_classes = ( permissions.updateOwnStatus, IsAuthenticated ) <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user_profile=self.request.user) | Handles creating, reading and updating profile feed items | 6259905e379a373c97d9a683 |
class NSNitroNserrCaconfCnflAbsexpHeurexp(NSNitroCaconfErrors): <NEW_LINE> <INDENT> pass | Nitro error code 483
Conflicting arguments, absExpiry and heurExpiryParam | 6259905e3539df3088ecd8fa |
class ProtectedResourceView(ProtectedResourceMixin, View): <NEW_LINE> <INDENT> server_class = Server <NEW_LINE> validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS <NEW_LINE> oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS | Generic view protecting resources by providing OAuth2 authentication out of the box | 6259905e3617ad0b5ee077ab |
class CategorySerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> notes = serializers.HyperlinkedRelatedField(view_name='main:note-detail', many=True, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Category <NEW_LINE> fields = ('id', 'date_modified','date_created', 'category', 'notes') | Serializer for Category model | 6259905e2ae34c7f260ac746 |
class Solution: <NEW_LINE> <INDENT> def woodCut(self, L, k): <NEW_LINE> <INDENT> if sum(L) < k: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> start,end = 1,max(L) <NEW_LINE> while start + 1 < end: <NEW_LINE> <INDENT> mid = (start+end) //2 <NEW_LINE> pieces_num = sum(len_i / mid for len_i in L) <NEW_LINE> if pieces+sum < k: <NEW_LINE> <INDENT> end = mid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start = mid <NEW_LINE> <DEDENT> <DEDENT> if sum(len_i / end for len_i in L) >= k: <NEW_LINE> <INDENT> return end <NEW_LINE> <DEDENT> return start | @param: L: Given n pieces of wood with length L[i]
@param: k: An integer
@return: The maximum length of the small pieces | 6259905e3cc13d1c6d466da0 |
class BetaTransactionApiServicer(object): <NEW_LINE> <INDENT> def CreateTransaction(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) <NEW_LINE> <DEDENT> def GetTransaction(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) | The Beta API is deprecated for 0.15.0 and later.
It is recommended to use the GA API (classes and functions in this
file not marked beta) for all further purposes. This class was generated
only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0. | 6259905e442bda511e95d889 |
@dataclass(frozen=True) <NEW_LINE> class PlayerCharacter(Character): <NEW_LINE> <INDENT> player: Optional[str] = None | Record for a Player Character. | 6259905ecc0a2c111447c5fe |
class EtcdInvalidActiveSize(EtcdException): <NEW_LINE> <INDENT> pass | Error ecodeInvalidActiveSize (http code 403) | 6259905e7d847024c075da32 |
@dochelper <NEW_LINE> class XicsrtSourceFocused(XicsrtSourceGeneric): <NEW_LINE> <INDENT> def default_config(self): <NEW_LINE> <INDENT> config = super().default_config() <NEW_LINE> config['target'] = None <NEW_LINE> return config <NEW_LINE> <DEDENT> def generate_direction(self, origin): <NEW_LINE> <INDENT> normal = self.make_normal_focused(origin) <NEW_LINE> D = super().random_direction(normal) <NEW_LINE> return D <NEW_LINE> <DEDENT> def make_normal_focused(self, origin): <NEW_LINE> <INDENT> normal = self.param['target'] - origin <NEW_LINE> normal = normal / np.linalg.norm(normal, axis=1)[:, np.newaxis] <NEW_LINE> return normal | An extended rectangular ray source that allows focusing towards a target.
This is different to a SourceDirected in that the emission cone is aimed
at the target for every location in the source. The SourceDirected instead
uses a fixed direction for emission. | 6259905e8da39b475be04846 |
class MyApplication(web.application): <NEW_LINE> <INDENT> def run(self, port=int(SERVER_OPTS['port']), *middleware): <NEW_LINE> <INDENT> func = self.wsgifunc(*middleware) <NEW_LINE> return web.httpserver.runsimple(func, ('0.0.0.0', port)) | Can change port or other stuff | 6259905e0fa83653e46f6546 |
class FuturesCommission(BaseCommission): <NEW_LINE> <INDENT> BROKER_COMMISSION_PER_CONTRACT = 0 <NEW_LINE> EXCHANGE_FEE_PER_CONTRACT = 0 <NEW_LINE> CARRYING_FEE_PER_CONTRACT = 0 <NEW_LINE> @classmethod <NEW_LINE> def get_commissions(cls, contract_values, turnover, **kwargs): <NEW_LINE> <INDENT> cost_per_contract = cls.BROKER_COMMISSION_PER_CONTRACT + cls.EXCHANGE_FEE_PER_CONTRACT + cls.CARRYING_FEE_PER_CONTRACT <NEW_LINE> commission_rates = float(cost_per_contract)/contract_values <NEW_LINE> commissions = commission_rates * turnover <NEW_LINE> return commissions | Base class for futures commissions.
Parameters
----------
BROKER_COMMISSION_PER_CONTRACT : float
the commission per contract
EXCHANGE_FEE_PER_CONTRACT : float
the exchange and regulatory fees per contract
CARRYING_FEE_PER_CONTRACT : float
the overnight carrying fee per contract (depends on equity in excess of
margin requirement)
Examples
--------
Example subclass for Globex E-Mini commissions:
>>> class GlobexEquityEMiniFixedCommission(FuturesCommission):
>>> BROKER_COMMISSION_PER_CONTRACT = 0.85
>>> EXCHANGE_FEE_PER_CONTRACT = 1.18
>>> CARRYING_FEE_PER_CONTRACT = 0 # Depends on equity in excess of margin requirement
>>>
>>> # then, use this on your strategy:
>>> class MyEminiStrategy(Moonshot):
>>> COMMISSION_CLASS = GlobexEquityEMiniFixedCommission | 6259905e23e79379d538db5b |
class PartieCollectivite(models.Model): <NEW_LINE> <INDENT> id = models.IntegerField(primary_key=True) <NEW_LINE> partie = models.ForeignKey(Partie) <NEW_LINE> collectivite = models.ForeignKey(Collectivite) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = u'partie_collectivite' | PartieCollectivite model
* datamodel review by sam
* 0 inconsistant/unused fields
* MD : OK | 6259905e07f4c71912bb0a9c |
class MyAccountView(ConfigPagesView): <NEW_LINE> <INDENT> title = _('My Account') <NEW_LINE> css_bundle_names = [ 'account-page', ] <NEW_LINE> js_bundle_names = [ '3rdparty-jsonlint', 'config-forms', 'account-page', ] <NEW_LINE> @method_decorator(login_required) <NEW_LINE> @augment_method_from(ConfigPagesView) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def nav_title(self): <NEW_LINE> <INDENT> return self.request.user.username <NEW_LINE> <DEDENT> @property <NEW_LINE> def page_classes(self): <NEW_LINE> <INDENT> return get_page_classes() <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def ordered_user_local_sites(self): <NEW_LINE> <INDENT> return self.request.user.local_site.order_by('name') | Displays the My Account page containing user preferences.
The page will be built based on registered pages and forms. This makes
it easy to plug in new bits of UI for the page, which is handy for
extensions that want to offer customization for users. | 6259905e99cbb53fe6832540 |
class Env: <NEW_LINE> <INDENT> def __init__(self, modpath_var='MODM_MODULES_PATH', modloaded_var='MODM_LOADED_MODULES'): <NEW_LINE> <INDENT> self.modpath_var = modpath_var <NEW_LINE> self.modloaded_var = modloaded_var <NEW_LINE> self.modpath = self.load_path(modpath_var) <NEW_LINE> self.modloaded = self.load_path(modloaded_var) <NEW_LINE> self.variables = dict() <NEW_LINE> <DEDENT> def load_path(self, variable): <NEW_LINE> <INDENT> path = self.load_string(variable) <NEW_LINE> return path.split(os.path.pathsep) if path else [] <NEW_LINE> <DEDENT> def load_string(self, variable): <NEW_LINE> <INDENT> return os.environ[variable] if variable in os.environ else None <NEW_LINE> <DEDENT> def get_modloaded_str(self): <NEW_LINE> <INDENT> return os.path.pathsep.join(self.modloaded) <NEW_LINE> <DEDENT> def add_loaded_module(self, module): <NEW_LINE> <INDENT> self.modloaded.append(module) <NEW_LINE> <DEDENT> def remove_loaded_module(self, module): <NEW_LINE> <INDENT> if module in self.modloaded: <NEW_LINE> <INDENT> self.modloaded.remove(module) | Class to handle environment variables in an easy way. | 6259905eac7a0e7691f73b43 |
class getEulaIDL_result(object): <NEW_LINE> <INDENT> thrift_spec = ((0, TType.STRUCT, 'success', (LicenseEulaIDL, LicenseEulaIDL.thrift_spec), None), (1, TType.STRUCT, 'e', (Shared.ttypes.ExceptionIDL, Shared.ttypes.ExceptionIDL.thrift_spec), None)) <NEW_LINE> def __init__(self, success = None, e = None): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__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 == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = LicenseEulaIDL() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = Shared.ttypes.ExceptionIDL() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__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('getEulaIDL_result') <NEW_LINE> if self.success != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <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:
- success
- e | 6259905e2ae34c7f260ac747 |
class Expert(ExperChatBaseModel): <NEW_LINE> <INDENT> userbase = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, primary_key=True, verbose_name=_('user base'), ) <NEW_LINE> expert_uid = models.CharField(max_length=5, unique=True, null=True) <NEW_LINE> account_id = models.IntegerField(default=0) <NEW_LINE> avg_rating = models.DecimalField(max_digits=3, decimal_places=2, default=0.00) <NEW_LINE> num_rating = models.PositiveIntegerField(default=0) <NEW_LINE> display_name = models.CharField(_('display name'), max_length=100, unique=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "users_expert" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{id}: {userbase}'.format( id=self.id if self.id else "", userbase=self.userbase, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self.userbase_id | Store expert's information. | 6259905e0c0af96317c5788f |
class Douban: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'en,zh-CN;q=0.8,zh;q=0.6,zh-TW;q=0.4' } <NEW_LINE> self.session = requests.session() <NEW_LINE> open('cookies', 'a').close() <NEW_LINE> self.session.cookies = cookielib.LWPCookieJar(filename='cookies') <NEW_LINE> try: <NEW_LINE> <INDENT> self.session.cookies.load(ignore_discard=True) <NEW_LINE> <DEDENT> except LoadError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.url = 'https://www.douban.com/login' <NEW_LINE> self.response = self.session.get(self.url, headers=self.headers) <NEW_LINE> try: <NEW_LINE> <INDENT> self.soup = BeautifulSoup(self.response.text, "lxml") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.soup = BeautifulSoup(self.response.text, "html.parser") <NEW_LINE> <DEDENT> <DEDENT> def _get_captcha_id(self): <NEW_LINE> <INDENT> return self.soup.find("input", {"name": "captcha-id"}).get('value') <NEW_LINE> <DEDENT> def get_captcha(self): <NEW_LINE> <INDENT> captcha_id = self._get_captcha_id() <NEW_LINE> captcha_url = 'https://www.douban.com/misc/captcha?id={0}&size=s'.format(captcha_id) <NEW_LINE> r = self.session.get(captcha_url) <NEW_LINE> with open('captcha', 'wb') as f: <NEW_LINE> <INDENT> f.write(r.content) <NEW_LINE> <DEDENT> print("请到当前目录找到captcha文件, 并输入验证码") <NEW_LINE> captcha = input() <NEW_LINE> return captcha, captcha_id <NEW_LINE> <DEDENT> def login(self, username, password=None): <NEW_LINE> <INDENT> if not password: <NEW_LINE> <INDENT> password = getpass(prompt='密码:') <NEW_LINE> <DEDENT> captcha, captcha_id = self.get_captcha() <NEW_LINE> form_data = { 'source': None, 'redir': 'https://www.douban.com', 'form_email': username, 'form_password': password, 'captcha-solution': captcha, 'captcha-id': captcha_id, 'login': '登录' } <NEW_LINE> response = self.session.post(self.url, data=form_data, headers=self.headers) <NEW_LINE> self.session.cookies.save() <NEW_LINE> <DEDENT> def scrape_doumail(self): <NEW_LINE> <INDENT> url = 'https://www.douban.com/doumail/' <NEW_LINE> response = self.session.get(url, headers=self.headers) <NEW_LINE> soup = BeautifulSoup(response.text, "lxml") <NEW_LINE> print([s.text for s in soup.select('.from')]) <NEW_LINE> <DEDENT> def do_other_stuff(self): <NEW_LINE> <INDENT> pass | 使用:
1. 命令行
$ python douban.py
密码: *******
请到当前目录找到captcha文件, 并输入验证码
captcha
$ douban.scrape_doumail()
$ douban.do_other_stuff()
2. from douban import Douban
douban = Douban()
douban.login('<yourusername>', '<yourpassword>')
douban.scrape_doumail()
douban.do_other_stuff() | 6259905ee76e3b2f99fda060 |
class UserForm(forms.ModelForm): <NEW_LINE> <INDENT> password = forms.CharField(widget=forms.PasswordInput) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ['username', 'email', 'password'] | ModelForm for Users.
This is the general form for creating Users.
Attributes
----------
username = Username
Username for the user to login into the system.
email = Email
Email required for the user, has format validation.
password = Password
Password for the user, the widget PasswordInput hides the characters in the field | 6259905e76e4537e8c3f0bed |
class ProjectsLocationsClustersWellKnownService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'projects_locations_clusters_well_known' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(ContainerV1.ProjectsLocationsClustersWellKnownService, self).__init__(client) <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def GetOpenid_configuration(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('GetOpenid_configuration') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> GetOpenid_configuration.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1/projects/{projectsId}/locations/{locationsId}/clusters/{clustersId}/.well-known/openid-configuration', http_method=u'GET', method_id=u'container.projects.locations.clusters.well-known.getOpenid-configuration', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[], relative_path=u'v1/{+parent}/.well-known/openid-configuration', request_field='', request_type_name=u'ContainerProjectsLocationsClustersWellKnownGetOpenidConfigurationRequest', response_type_name=u'GetOpenIDConfigResponse', supports_download=False, ) | Service class for the projects_locations_clusters_well_known resource. | 6259905e8e7ae83300eea6ef |
class ItemOperation(FlaskForm): <NEW_LINE> <INDENT> iid = HiddenField("iid") <NEW_LINE> remove = SubmitField("Smazat") <NEW_LINE> edit = SubmitField("Editovat") | smazání položky | 6259905e097d151d1a2c26cf |
class IFCurrDualExp(AbstractPopulationVertex): <NEW_LINE> <INDENT> _model_based_max_atoms_per_core = 255 <NEW_LINE> default_parameters = { 'tau_m': 20.0, 'cm': 1.0, 'v_rest': -65.0, 'v_reset': -65.0, 'v_thresh': -50.0, 'tau_syn_E': 5.0, 'tau_syn_E2': 5.0, 'tau_syn_I': 5.0, 'tau_refrac': 0.1, 'i_offset': 0} <NEW_LINE> def __init__( self, n_neurons, spikes_per_second=None, ring_buffer_sigma=None, incoming_spike_buffer_size=None, constraints=None, label=None, tau_m=default_parameters['tau_m'], cm=default_parameters['cm'], v_rest=default_parameters['v_rest'], v_reset=default_parameters['v_reset'], v_thresh=default_parameters['v_thresh'], tau_syn_E=default_parameters['tau_syn_E'], tau_syn_E2=default_parameters['tau_syn_E2'], tau_syn_I=default_parameters['tau_syn_I'], tau_refrac=default_parameters['tau_refrac'], i_offset=default_parameters['i_offset'], v_init=None): <NEW_LINE> <INDENT> neuron_model = NeuronModelLeakyIntegrateAndFire( n_neurons, v_init, v_rest, tau_m, cm, i_offset, v_reset, tau_refrac) <NEW_LINE> synapse_type = SynapseTypeDualExponential( n_neurons, tau_syn_E, tau_syn_E2, tau_syn_I) <NEW_LINE> input_type = InputTypeCurrent() <NEW_LINE> threshold_type = ThresholdTypeStatic(n_neurons, v_thresh) <NEW_LINE> AbstractPopulationVertex.__init__( self, n_neurons=n_neurons, binary="IF_curr_exp_dual.aplx", label=label, max_atoms_per_core=IFCurrDualExp._model_based_max_atoms_per_core, spikes_per_second=spikes_per_second, ring_buffer_sigma=ring_buffer_sigma, incoming_spike_buffer_size=incoming_spike_buffer_size, model_name="IF_curr_dual_exp", neuron_model=neuron_model, input_type=input_type, synapse_type=synapse_type, threshold_type=threshold_type, constraints=constraints) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def set_model_max_atoms_per_core(new_value): <NEW_LINE> <INDENT> IFCurrDualExp._model_based_max_atoms_per_core = new_value <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_max_atoms_per_core(): <NEW_LINE> <INDENT> return IFCurrDualExp._model_based_max_atoms_per_core | Leaky integrate and fire neuron with two exponentially decaying excitatory current inputs, and one exponentially decaying inhibitory current input
| 6259905e627d3e7fe0e084ec |
class PrivateTopicNew(CreateView): <NEW_LINE> <INDENT> form_class = PrivateTopicForm <NEW_LINE> template_name = 'mp/topic/new.html' <NEW_LINE> @method_decorator(login_required) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(PrivateTopicNew, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> title = request.GET.get('title') if 'title' in request.GET else None <NEW_LINE> participants = None <NEW_LINE> if 'username' in request.GET: <NEW_LINE> <INDENT> dest_list = [] <NEW_LINE> for username in request.GET.getlist('username'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dest_list.append(User.objects.get(username=username).username) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if len(dest_list) > 0: <NEW_LINE> <INDENT> participants = ', '.join(dest_list) <NEW_LINE> <DEDENT> <DEDENT> form = self.form_class(username=request.user.username, initial={ 'participants': participants, 'title': title }) <NEW_LINE> return render(request, self.template_name, {'form': form}) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> form = self.get_form(self.form_class) <NEW_LINE> if 'preview' in request.POST: <NEW_LINE> <INDENT> if request.is_ajax(): <NEW_LINE> <INDENT> content = render_to_response('misc/previsualization.part.html', {'text': request.POST['text']}) <NEW_LINE> return StreamingHttpResponse(content) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = self.form_class(request.user.username, initial={ 'participants': request.POST['participants'], 'title': request.POST['title'], 'subtitle': request.POST['subtitle'], 'text': request.POST['text'], }) <NEW_LINE> <DEDENT> <DEDENT> elif form.is_valid(): <NEW_LINE> <INDENT> return self.form_valid(form) <NEW_LINE> <DEDENT> return render(request, self.template_name, {'form': form}) <NEW_LINE> <DEDENT> def get_form(self, form_class=PrivateTopicForm): <NEW_LINE> <INDENT> return form_class(self.request.user.username, self.request.POST) <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> participants = [] <NEW_LINE> for participant in form.data['participants'].split(','): <NEW_LINE> <INDENT> current = participant.strip() <NEW_LINE> if not current: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> participants.append(get_object_or_404(User, username=current)) <NEW_LINE> <DEDENT> p_topic = send_mp(self.request.user, participants, form.data['title'], form.data['subtitle'], form.data['text'], True, False) <NEW_LINE> return redirect(p_topic.get_absolute_url()) | Creates a new MP. | 6259905e435de62698e9d467 |
class Menu(QtGui.QMenu): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> QtGui.QMenu.__init__(self, parent) <NEW_LINE> self.parent = parent <NEW_LINE> <DEDENT> def newAction(self, label, icon, slot): <NEW_LINE> <INDENT> action = self.addAction(icon, label) <NEW_LINE> self.parent.connect(action, QtCore.SIGNAL("triggered(bool)"), slot); <NEW_LINE> return action | QMenu wrapper for creating popups without pain.
Usage:
menu = Menu()
menu.newAction("Item 1", "green_led", self.slotItem1Clicked) | 6259905ea17c0f6771d5d6d4 |
class MainWindow(QMainWindow): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.item_cnt = 0 <NEW_LINE> self.list_widget = QListWidget(self) <NEW_LINE> self.list_widget.setMinimumWidth(200) <NEW_LINE> self.scene = QGraphicsScene(self) <NEW_LINE> self.scene.setSceneRect(0, 0, 600, 600) <NEW_LINE> self.canvas_widget = MyCanvas(self.scene, self) <NEW_LINE> self.canvas_widget.setFixedSize(600, 600) <NEW_LINE> self.canvas_widget.main_window = self <NEW_LINE> self.canvas_widget.list_widget = self.list_widget <NEW_LINE> menubar = self.menuBar() <NEW_LINE> file_menu = menubar.addMenu('文件') <NEW_LINE> set_pen_act = file_menu.addAction('设置画笔') <NEW_LINE> reset_canvas_act = file_menu.addAction('重置画布') <NEW_LINE> exit_act = file_menu.addAction('退出') <NEW_LINE> draw_menu = menubar.addMenu('绘制') <NEW_LINE> line_menu = draw_menu.addMenu('线段') <NEW_LINE> line_naive_act = line_menu.addAction('Naive') <NEW_LINE> line_dda_act = line_menu.addAction('DDA') <NEW_LINE> line_bresenham_act = line_menu.addAction('Bresenham') <NEW_LINE> polygon_menu = draw_menu.addMenu('多边形') <NEW_LINE> polygon_dda_act = polygon_menu.addAction('DDA') <NEW_LINE> polygon_bresenham_act = polygon_menu.addAction('Bresenham') <NEW_LINE> ellipse_act = draw_menu.addAction('椭圆') <NEW_LINE> curve_menu = draw_menu.addMenu('曲线') <NEW_LINE> curve_bezier_act = curve_menu.addAction('Bezier') <NEW_LINE> curve_b_spline_act = curve_menu.addAction('B-spline') <NEW_LINE> edit_menu = menubar.addMenu('编辑') <NEW_LINE> translate_act = edit_menu.addAction('平移') <NEW_LINE> rotate_act = edit_menu.addAction('旋转') <NEW_LINE> scale_act = edit_menu.addAction('缩放') <NEW_LINE> clip_menu = edit_menu.addMenu('裁剪') <NEW_LINE> clip_cohen_sutherland_act = clip_menu.addAction('Cohen-Sutherland') <NEW_LINE> clip_liang_barsky_act = clip_menu.addAction('Liang-Barsky') <NEW_LINE> exit_act.triggered.connect(qApp.quit) <NEW_LINE> line_naive_act.triggered.connect(self.line_naive_action) <NEW_LINE> self.list_widget.currentTextChanged.connect(self.canvas_widget.selection_changed) <NEW_LINE> self.hbox_layout = QHBoxLayout() <NEW_LINE> self.hbox_layout.addWidget(self.canvas_widget) <NEW_LINE> self.hbox_layout.addWidget(self.list_widget, stretch=1) <NEW_LINE> self.central_widget = QWidget() <NEW_LINE> self.central_widget.setLayout(self.hbox_layout) <NEW_LINE> self.setCentralWidget(self.central_widget) <NEW_LINE> self.statusBar().showMessage('空闲') <NEW_LINE> self.resize(600, 600) <NEW_LINE> self.setWindowTitle('CG Demo') <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> _id = str(self.item_cnt) <NEW_LINE> self.item_cnt += 1 <NEW_LINE> return _id <NEW_LINE> <DEDENT> def line_naive_action(self): <NEW_LINE> <INDENT> self.canvas_widget.start_draw_line('Naive', self.get_id()) <NEW_LINE> self.statusBar().showMessage('Naive算法绘制线段') <NEW_LINE> self.list_widget.clearSelection() <NEW_LINE> self.canvas_widget.clear_selection() | 主窗口类 | 6259905e3617ad0b5ee077af |
class Solution: <NEW_LINE> <INDENT> def permute(self, nums): <NEW_LINE> <INDENT> temp = nums[:] <NEW_LINE> n = len(nums) <NEW_LINE> path, result = [], [] <NEW_LINE> if len(nums) == 0: <NEW_LINE> <INDENT> result.append(path) <NEW_LINE> return result <NEW_LINE> <DEDENT> self.helper(temp, path, n, result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def helper(self, temp, path, n, result): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> while index < len(temp): <NEW_LINE> <INDENT> cur = temp[index] <NEW_LINE> path.append(cur) <NEW_LINE> if len(path) == n: <NEW_LINE> <INDENT> result.append(path[:]) <NEW_LINE> path.pop() <NEW_LINE> return <NEW_LINE> <DEDENT> temp.remove(cur) <NEW_LINE> self.helper(temp, path, n, result) <NEW_LINE> temp.insert(index, cur) <NEW_LINE> path.pop() <NEW_LINE> index += 1 | @param: nums: A list of integers.
@return: A list of permutations. | 6259905e2ae34c7f260ac74a |
class BasePrior(object): <NEW_LINE> <INDENT> def __init__(self, adaptive=False, sort=False, nfunc_min=1): <NEW_LINE> <INDENT> self.adaptive = adaptive <NEW_LINE> self.sort = sort <NEW_LINE> self.nfunc_min = nfunc_min <NEW_LINE> <DEDENT> def cube_to_physical(self, cube): <NEW_LINE> <INDENT> return cube <NEW_LINE> <DEDENT> def __call__(self, cube): <NEW_LINE> <INDENT> if self.adaptive: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> theta = adaptive_transform( cube, sort=self.sort, nfunc_min=self.nfunc_min) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if np.isnan(cube[0]): <NEW_LINE> <INDENT> return np.full(cube.shape, np.nan) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> theta[1:] = self.cube_to_physical(theta[1:]) <NEW_LINE> return theta <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.sort: <NEW_LINE> <INDENT> return self.cube_to_physical(forced_identifiability(cube)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.cube_to_physical(cube) | Base class for Priors. | 6259905e3cc13d1c6d466da4 |
class Webserver: <NEW_LINE> <INDENT> def __init__(self, root=None, port=None, wait=5, handler=None, ssl_opts=None): <NEW_LINE> <INDENT> if port is not None and not isinstance(port, int): <NEW_LINE> <INDENT> raise ValueError("port must be an integer") <NEW_LINE> <DEDENT> if root is None: <NEW_LINE> <INDENT> root = RUNTIME_VARS.BASE_FILES <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.root = os.path.realpath(root) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError("root must be a string") <NEW_LINE> <DEDENT> self.port = port <NEW_LINE> self.wait = wait <NEW_LINE> self.handler = ( handler if handler is not None else salt.ext.tornado.web.StaticFileHandler ) <NEW_LINE> self.web_root = None <NEW_LINE> self.ssl_opts = ssl_opts <NEW_LINE> <DEDENT> def target(self): <NEW_LINE> <INDENT> self.ioloop = salt.ext.tornado.ioloop.IOLoop() <NEW_LINE> self.ioloop.make_current() <NEW_LINE> if self.handler == salt.ext.tornado.web.StaticFileHandler: <NEW_LINE> <INDENT> self.application = salt.ext.tornado.web.Application( [(r"/(.*)", self.handler, {"path": self.root})] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.application = salt.ext.tornado.web.Application( [(r"/(.*)", self.handler)] ) <NEW_LINE> <DEDENT> self.application.listen(self.port, ssl_options=self.ssl_opts) <NEW_LINE> self.ioloop.start() <NEW_LINE> <DEDENT> @property <NEW_LINE> def listening(self): <NEW_LINE> <INDENT> if self.port is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> return sock.connect_ex(("127.0.0.1", self.port)) == 0 <NEW_LINE> <DEDENT> def url(self, path): <NEW_LINE> <INDENT> if self.web_root is None: <NEW_LINE> <INDENT> raise RuntimeError("Webserver instance has not been started") <NEW_LINE> <DEDENT> err_msg = ( "invalid path, must be either a relative path or a path " "within {}".format(self.root) ) <NEW_LINE> try: <NEW_LINE> <INDENT> relpath = ( path if not os.path.isabs(path) else os.path.relpath(path, self.root) ) <NEW_LINE> if relpath.startswith(".." + os.sep): <NEW_LINE> <INDENT> raise ValueError(err_msg) <NEW_LINE> <DEDENT> return "/".join((self.web_root, relpath)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError(err_msg) <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.port is None: <NEW_LINE> <INDENT> self.port = get_unused_localhost_port() <NEW_LINE> <DEDENT> self.web_root = "http{}://127.0.0.1:{}".format( "s" if self.ssl_opts else "", self.port ) <NEW_LINE> self.server_thread = threading.Thread(target=self.target) <NEW_LINE> self.server_thread.daemon = True <NEW_LINE> self.server_thread.start() <NEW_LINE> for idx in range(self.wait + 1): <NEW_LINE> <INDENT> if self.listening: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if idx != self.wait: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Failed to start tornado webserver on 127.0.0.1:{} within " "{} seconds".format(self.port, self.wait) ) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.ioloop.add_callback(self.ioloop.stop) <NEW_LINE> self.server_thread.join() | Starts a tornado webserver on 127.0.0.1 on a random available port
USAGE:
.. code-block:: python
from tests.support.helpers import Webserver
webserver = Webserver('/path/to/web/root')
webserver.start()
webserver.stop() | 6259905e0a50d4780f7068f0 |
class Concrete(Spec, t.NamedTuple): <NEW_LINE> <INDENT> typ: type | str, int, float, null | 6259905e56ac1b37e6303818 |
@util.export <NEW_LINE> class Plugin(plugin.PluginBase): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super(Plugin, self).__init__(context=context) <NEW_LINE> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_INIT, ) <NEW_LINE> def _init(self): <NEW_LINE> <INDENT> self.environment.setdefault( osetupcons.CoreEnv.ANSWER_FILE, None ) <NEW_LINE> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_CLEANUP, priority=plugin.Stages.PRIORITY_LAST, ) <NEW_LINE> def _cleanup(self): <NEW_LINE> <INDENT> answers = [] <NEW_LINE> answers.append( os.path.join( osetupcons.FileLocations.OVIRT_SETUP_ANSWERS_DIR, '%s-%s.conf' % ( datetime.datetime.now().strftime('%Y%m%d%H%M%S'), self.environment[osetupcons.CoreEnv.ACTION], ), ) ) <NEW_LINE> if self.environment[osetupcons.CoreEnv.ANSWER_FILE] is not None: <NEW_LINE> <INDENT> answers.append( self.environment[osetupcons.CoreEnv.ANSWER_FILE] ) <NEW_LINE> <DEDENT> for answer in answers: <NEW_LINE> <INDENT> self.logger.info( _("Generating answer file '{name}'").format( name=answer, ) ) <NEW_LINE> with open(self.resolveFile(answer), 'w') as f: <NEW_LINE> <INDENT> os.fchmod(f.fileno(), 0o600) <NEW_LINE> f.write( ( '# action=%s\n' '[environment:default]\n' ) % ( self.environment[ osetupcons.CoreEnv.ACTION ], ) ) <NEW_LINE> consts = [] <NEW_LINE> for constobj in self.environment[ osetupcons.CoreEnv.SETUP_ATTRS_MODULES ]: <NEW_LINE> <INDENT> consts.extend(constobj.__dict__['__osetup_attrs__']) <NEW_LINE> <DEDENT> for c in consts: <NEW_LINE> <INDENT> for k in c.__dict__.values(): <NEW_LINE> <INDENT> if hasattr(k, '__osetup_attrs__'): <NEW_LINE> <INDENT> if k.__osetup_attrs__['answerfile']: <NEW_LINE> <INDENT> k = k.fget(None) <NEW_LINE> if k in self.environment: <NEW_LINE> <INDENT> v = self.environment[k] <NEW_LINE> f.write( '%s=%s:%s\n' % ( k, common.typeName(v), '\n'.join(v) if isinstance(v, list) else v, ) ) | Answer file plugin. | 6259905e01c39578d7f14268 |
class Sky2Pix_TAN(Sky2PixProjection, Zenithal): <NEW_LINE> <INDENT> @property <NEW_LINE> def inverse(self): <NEW_LINE> <INDENT> return Pix2Sky_TAN() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def evaluate(cls, phi, theta): <NEW_LINE> <INDENT> phi = np.deg2rad(phi) <NEW_LINE> theta = np.deg2rad(theta) <NEW_LINE> r_theta = cls._compute_r_theta(theta) <NEW_LINE> x = np.rad2deg(r_theta * np.sin(phi)) <NEW_LINE> y = -np.rad2deg(r_theta * np.cos(phi)) <NEW_LINE> return x, y <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _compute_r_theta(theta): <NEW_LINE> <INDENT> return 1 / np.tan(theta) | TAN : Gnomonic Projection - sky to pixel.
See `Zenithal` for a definition of the full transformation.
.. math::
R_\theta = \frac{180^{\circ}}{\pi}\cot \theta | 6259905e21bff66bcd7242c8 |
@StreamFeatures.as_feature_class <NEW_LINE> class StartTLSFeature(StartTLSXSO): <NEW_LINE> <INDENT> TAG = (namespaces.starttls, "starttls") <NEW_LINE> class Required(xso.XSO): <NEW_LINE> <INDENT> TAG = (namespaces.starttls, "required") <NEW_LINE> <DEDENT> required = xso.Child([Required], required=False) | Start TLS capability stream feature | 6259905e15baa723494635f6 |
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA) <NEW_LINE> class GetValue(base.Command): <NEW_LINE> <INDENT> detailed_help = {'properties': properties.VALUES.GetHelpString()} <NEW_LINE> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.add_argument( 'property', metavar='SECTION/PROPERTY', completer=completers.PropertiesCompleter, help='The property to be fetched. Note that `SECTION/` is optional' ' while referring to properties in the core section.') <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> config_name = named_configs.ConfigurationStore.ActiveConfig().name <NEW_LINE> if config_name != 'default': <NEW_LINE> <INDENT> log.status.write('Your active configuration is: [{0}]\n'.format( config_name)) <NEW_LINE> <DEDENT> section, prop = properties.ParsePropertyString(args.property) <NEW_LINE> if not prop: <NEW_LINE> <INDENT> if section: <NEW_LINE> <INDENT> err_msg = ('You cannot call get-value on a SECTION/. ' 'Did you mean `gcloud config list SECTION`?') <NEW_LINE> raise c_exc.InvalidArgumentException('property', err_msg) <NEW_LINE> <DEDENT> raise c_exc.InvalidArgumentException( 'property', 'Must be in the form: [SECTION/]PROPERTY') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> value = properties.VALUES.Section(section).Property(prop).Get( validate=True) <NEW_LINE> if not value: <NEW_LINE> <INDENT> log.err.Print('(unset)') <NEW_LINE> <DEDENT> <DEDENT> except properties.InvalidValueError as e: <NEW_LINE> <INDENT> log.warn(str(e)) <NEW_LINE> value = properties.VALUES.Section(section).Property(prop).Get( validate=False) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def DeprecatedFormat(self, args): <NEW_LINE> <INDENT> return 'value(.)' | Print the value of a Cloud SDK property.
{command} prints the property value from your active configuration only.
## AVAILABLE PROPERTIES
{properties}
## EXAMPLES
To print the project property in the core section, run:
$ {command} project
To print the zone property in the compute section, run:
$ {command} compute/zone | 6259905ee64d504609df9f00 |
class ManageUserFormSchema(interface.Interface): <NEW_LINE> <INDENT> user_id = schema.ASCIILine(title=_(u"Users uuid")) | Form used by user to register. | 6259905ea8ecb0332587287b |
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = '=!=!=!= PLEASE,CHANGE THIS SECRET KEY, OK?... =!=!=!=' <NEW_LINE> TOKEN_SALT = '=!=!=!= TOKEN-SALT-KEY (do not forget to change it) =!=!=!=' <NEW_LINE> APP_DIR = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir)) <NEW_LINE> THEME_NAME = 'classic' <NEW_LINE> FULL_DATETIME_FORMAT = 'MMM DD YYYY, HH:mm:ss ZZZ' <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> TIME_ZONE = 'UTC' <NEW_LINE> MAIL_DEFAULT_SENDER = '[email protected]' <NEW_LINE> ACTIVE_WIDGETS = ( 'flibia_aac.widgets.widgets.TopExperienceWidget', 'flibia_aac.widgets.widgets.PlayersOnlineWidget', ) | Base configuration. | 6259905e67a9b606de5475d3 |
class TestOption(TestCase): <NEW_LINE> <INDENT> pass | def _test_option(self, options):
self._test("", options=options)
def _test_threshold(self, threshold):
self._test_option(["--threshold=%(threshold)s" % { "threshold": threshold }])
def test_threshold1(self):
self._test_threshold("42")
def test_threshold2(self):
self._test_threshold("42k")
def test_threshold3(self):
self._test_threshold("42K")
def test_threshold4(self):
self._test_threshold("42m")
def test_threshold5(self):
self._test_threshold("42M")
def test_threshold6(self):
self._test_threshold("42M43k44") | 6259905eac7a0e7691f73b47 |
class Element(Enum): <NEW_LINE> <INDENT> DATE_FROM_XPATH = '//*[@id="ctl00_PlaceHolderMain_generalSearchForm_txtGSStartDate"]' <NEW_LINE> SEARCH_BUTTON_XPATH = '//*[@id="ctl00_PlaceHolderMain_btnNewSearch"]' <NEW_LINE> TABLE_ID = 'ctl00_PlaceHolderMain_dgvPermitList_gdvPermitList' <NEW_LINE> PAGE_NAV_CLASS = 'aca_pagination' <NEW_LINE> UNFOLD_BUTTON_XPATH = '//h1/a[@class="NotShowLoading"]' <NEW_LINE> NEXT_BUTTON_XPATH = '//*[contains(text(), "Next >")]' | The class contains variables that describe different attributes of web elements to be located | 6259905e45492302aabfdb3d |
class TestNormalization(ParametricTestCase): <NEW_LINE> <INDENT> def _testCodec(self, normalization, rtol=1e-5): <NEW_LINE> <INDENT> test_data = (numpy.arange(1, 10, dtype=numpy.int32), numpy.linspace(1., 100., 1000, dtype=numpy.float32), numpy.linspace(-1., 1., 100, dtype=numpy.float32), 1., 1) <NEW_LINE> for index in range(len(test_data)): <NEW_LINE> <INDENT> with self.subTest(normalization=normalization, data_index=index): <NEW_LINE> <INDENT> data = test_data[index] <NEW_LINE> normalized = normalization.apply(data, 1., 100.) <NEW_LINE> result = normalization.revert(normalized, 1., 100.) <NEW_LINE> self.assertTrue(numpy.array_equal( numpy.isnan(normalized), numpy.isnan(result))) <NEW_LINE> if isinstance(data, numpy.ndarray): <NEW_LINE> <INDENT> notNaN = numpy.logical_not(numpy.isnan(result)) <NEW_LINE> data = data[notNaN] <NEW_LINE> result = result[notNaN] <NEW_LINE> <DEDENT> self.assertTrue(numpy.allclose(data, result, rtol=rtol)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def testLinearNormalization(self): <NEW_LINE> <INDENT> normalization = colormap.LinearNormalization() <NEW_LINE> self._testCodec(normalization) <NEW_LINE> <DEDENT> def testLogarithmicNormalization(self): <NEW_LINE> <INDENT> normalization = colormap.LogarithmicNormalization() <NEW_LINE> self._testCodec(normalization, rtol=1e-3) <NEW_LINE> self.assertTrue(numpy.isnan(normalization.apply(-1., 1., 100.))) <NEW_LINE> self.assertTrue(numpy.isnan(normalization.apply(numpy.nan, 1., 100.))) <NEW_LINE> self.assertEqual(normalization.apply(numpy.inf, 1., 100.), numpy.inf) <NEW_LINE> self.assertEqual(normalization.apply(0, 1., 100.), - numpy.inf) <NEW_LINE> <DEDENT> def testArcsinhNormalization(self): <NEW_LINE> <INDENT> self._testCodec(colormap.ArcsinhNormalization()) <NEW_LINE> <DEDENT> def testSqrtNormalization(self): <NEW_LINE> <INDENT> normalization = colormap.SqrtNormalization() <NEW_LINE> self._testCodec(normalization) <NEW_LINE> self.assertTrue(numpy.isnan(normalization.apply(-1., 0., 100.))) <NEW_LINE> self.assertTrue(numpy.isnan(normalization.apply(numpy.nan, 0., 100.))) <NEW_LINE> self.assertEqual(normalization.apply(numpy.inf, 0., 100.), numpy.inf) <NEW_LINE> self.assertEqual(normalization.apply(0, 0., 100.), 0.) | Test silx.math.colormap.Normalization sub classes | 6259905ea8370b77170f1a32 |
class SkodaServiceUnavailable(Exception): <NEW_LINE> <INDENT> def __init__(self, status): <NEW_LINE> <INDENT> super(SkodaServiceUnavailable, self).__init__(status) <NEW_LINE> self.status = status | Raised when a API is unavailable | 6259905e3539df3088ecd900 |
class config: <NEW_LINE> <INDENT> interval = float(getenv('THRASH_PROTECT_INTERVAL', '0.5')) <NEW_LINE> max_acceptable_time_delta = interval/16.0 <NEW_LINE> swap_page_threshold = int(getenv('THRASH_PROTECT_SWAP_PAGE_THRESHOLD', '512')) <NEW_LINE> pgmajfault_scan_threshold = int(getenv('THRASH_PROTECT_PGMAJFAULT_SCAN_THRESHOLD', swap_page_threshold*4)) <NEW_LINE> cmd_whitelist = getenv('THRASH_PROTECT_CMD_WHITELIST', '') <NEW_LINE> cmd_whitelist = cmd_whitelist.split(' ') if cmd_whitelist else ['sshd', 'bash', 'xinit', 'X', 'spectrwm', 'screen', 'SCREEN', 'mutt', 'ssh', 'xterm', 'rxvt', 'urxvt', 'Xorg.bin', 'systemd-journal'] <NEW_LINE> cmd_blacklist = getenv('THRASH_PROTECT_CMD_BLACKLIST', '').split(' ') <NEW_LINE> cmd_jobctrllist = getenv('THRASH_PROTECT_CMD_JOBCTRLLIST', 'bash').split(' ') <NEW_LINE> blacklist_score_multiplier = int(getenv('THRASH_PROTECT_BLACKLIST_SCORE_MULTIPLIER', '16')) <NEW_LINE> whitelist_score_divider = int(getenv('THRASH_PROTECT_BLACKLIST_SCORE_MULTIPLIER', str(blacklist_score_multiplier*4))) <NEW_LINE> unfreeze_pop_ratio = int(getenv('THRASH_PROTECT_UNFREEZE_POP_RATIO', '5')) <NEW_LINE> test_mode = int(getenv('THRASH_PROTECT_TEST_MODE', '0')) <NEW_LINE> log_user_data = int(getenv('THRASH_PROTECT_LOG_USER_DATA', '0')) <NEW_LINE> date_human_readable = int(getenv('THRASH_PROTECT_DATE_HUMAN_READABLE', '1')) | Collection of configuration variables. (Those are still really
global variables, but looks a bit neater to access
config.bits_per_byte than bits_per_byte. Perhaps we'll parse some
a config file and initiate some object with the name config in
some future version) | 6259905ea79ad1619776b5ef |
class CreateTokenView(ObtainAuthToken): <NEW_LINE> <INDENT> serializer_class = AuthTokenSerializer <NEW_LINE> renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES | Create a new auth tolen for user | 6259905e379a373c97d9a689 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.