code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Solution: <NEW_LINE> <INDENT> def NumberOf1(self, n): <NEW_LINE> <INDENT> number_of_1 = 0 <NEW_LINE> flag = 1 <NEW_LINE> while flag <= MAXINT: <NEW_LINE> <INDENT> if flag & n: <NEW_LINE> <INDENT> number_of_1 += 1 <NEW_LINE> <DEDENT> flag <<= 1 <NEW_LINE> <DEDENT> return number_of_1
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 算法2: 依次检查所有的 bit,Python2 最大是 64 bit,所以要检测 64 次。 检查第 k(0<=k<64) 位是否是1:将其与 0000...1(从右开始数第k个,k从0开始)...0 进行位与操作, 如果结果是 0,说明第 k 位是 0,否则第 k 位是 1。因为 0 与任何数位与都为 0,而另一个数除了第 k 位 都是0,所以只有当第 k 位为 1 时的位与结果才不会为 0.
62599080f9cc0f698b1c6020
class TheGuardianCredentials: <NEW_LINE> <INDENT> def __init__(self, key): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> <DEDENT> @property <NEW_LINE> def valid(self): <NEW_LINE> <INDENT> response = requests.get(BASE_URL, {'api-key': self.key}) <NEW_LINE> return response.status_code == 200 <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.key == other.key
The Guardian API credentials.
62599080099cdd3c6367614e
class LocationField(Field): <NEW_LINE> <INDENT> def check_type(self, value): <NEW_LINE> <INDENT> if not isinstance(value, (tuple, list)): <NEW_LINE> <INDENT> raise TypeError("Value '%s' should be tuple or list", value) <NEW_LINE> <DEDENT> if len(value) != 2: <NEW_LINE> <INDENT> raise ValidateError( "LocationField should be something like (x, y) or [x, y]") <NEW_LINE> <DEDENT> result = [] <NEW_LINE> for item in value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _ = float(item) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValidateError( "Can't translate %s to float in %s" % (item, value)) <NEW_LINE> <DEDENT> result.append(_) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> value = super(LocationField, self).validate(value) <NEW_LINE> return value
Location(longitude, latitude) field, the value should be something like (x, y) or [x, y], in which both x and y are float`.
625990805fc7496912d48fc0
class XFrameOptionsSameOrigin(generic.View): <NEW_LINE> <INDENT> xframe_options_same_origin = True <NEW_LINE> @classonlymethod <NEW_LINE> def as_view(cls, **kwargs): <NEW_LINE> <INDENT> view = super(XFrameOptionsSameOrigin, cls).as_view(**kwargs) <NEW_LINE> return ( clickjacking.xframe_options_sameorigin(view) if cls.xframe_options_same_origin else view)
A view behavior that adds a SAMEORIGIN X-Frame-Options header to the response at the top level of the dispatch. Set the xframe_options_same_origin attribute to a falsy value to disable the behavior. See the django.views.decorators.clickjacking.xframe_options_sameorigin() decorator for details.
62599080a8370b77170f1e7a
class Router: <NEW_LINE> <INDENT> def __init__(self, view_404=None, view_500=None): <NEW_LINE> <INDENT> self.routes = {} <NEW_LINE> self.handler404 = view_404 if view_404 else default404 <NEW_LINE> self.handler500 = view_500 if view_500 else default500 <NEW_LINE> <DEDENT> def add_route(self, route: str, view: FunctionType): <NEW_LINE> <INDENT> self.routes[route] = [re.compile(route), view] <NEW_LINE> <DEDENT> def route(self, route: str): <NEW_LINE> <INDENT> def decorator(view): <NEW_LINE> <INDENT> self.add_route(route, view) <NEW_LINE> return view <NEW_LINE> <DEDENT> return decorator <NEW_LINE> <DEDENT> def dispatch(self, path: str) -> FunctionType: <NEW_LINE> <INDENT> for route in self.routes: <NEW_LINE> <INDENT> regex = self.routes[route][0] <NEW_LINE> match = regex.search(path) <NEW_LINE> if match: <NEW_LINE> <INDENT> view = self.routes[route][1] <NEW_LINE> return view, match.groupdict() <NEW_LINE> <DEDENT> <DEDENT> return self.handler404, {"error": "Path {} Not Found".format(path)}
Route different matching string patterns to different urls.
6259908097e22403b383c9aa
class ProductTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_product_defines_properties_and_methods(self): <NEW_LINE> <INDENT> product = Product('some_value') <NEW_LINE> self.assertEqual(product.some_property, 'some_value') <NEW_LINE> self.assertTrue(hasattr(product, 'some_method')) <NEW_LINE> self.assertEqual(product.some_method(), 'some_value') <NEW_LINE> self.assertEqual(product.some_other_method(), 'some_value')
Unittest for the Product class
625990803d592f4c4edbc8b4
class MultiplePSIMITerms(MultipleItems): <NEW_LINE> <INDENT> _item_class = PSIMITerm
A list of PSI-MI Terms.
6259908076e4537e8c3f1029
class TestTotalsCommittee(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 testTotalsCommittee(self): <NEW_LINE> <INDENT> pass
TotalsCommittee unit test stubs
62599080a8370b77170f1e7b
class AllocateIp6AddressesBandwidthRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Ip6Addresses = None <NEW_LINE> self.InternetMaxBandwidthOut = None <NEW_LINE> self.InternetChargeType = None <NEW_LINE> self.BandwidthPackageId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Ip6Addresses = params.get("Ip6Addresses") <NEW_LINE> self.InternetMaxBandwidthOut = params.get("InternetMaxBandwidthOut") <NEW_LINE> self.InternetChargeType = params.get("InternetChargeType") <NEW_LINE> self.BandwidthPackageId = params.get("BandwidthPackageId") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
AllocateIp6AddressesBandwidth请求参数结构体
625990802c8b7c6e89bd5290
class AsyncTask(object): <NEW_LINE> <INDENT> def __init__(self, thread_function, callback=None, timeout=0): <NEW_LINE> <INDENT> self.event = Event() <NEW_LINE> wrapped_function = self.wrap_thread(thread_function) <NEW_LINE> self.thread = Thread(target=wrapped_function) <NEW_LINE> self.thread.daemon = True <NEW_LINE> self.timeout = timeout <NEW_LINE> self.callback = callback <NEW_LINE> <DEDENT> def timeout_test(self): <NEW_LINE> <INDENT> if self.timeout: <NEW_LINE> <INDENT> return DelayTimer(self.timeout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def wrap_thread(self, fn): <NEW_LINE> <INDENT> def signal_done(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fn() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.event.set() <NEW_LINE> <DEDENT> <DEDENT> return signal_done <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> self.thread.start() <NEW_LINE> not_expired = self.timeout_test() <NEW_LINE> while not self.event.isSet(): <NEW_LINE> <INDENT> if not_expired: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> task_logger.info("thread job timed out") <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> if self.callback: <NEW_LINE> <INDENT> self.callback() <NEW_LINE> <DEDENT> task_logger.info("thread job completed")
run <thread_function> in a new thread it until it ends or has run for longer than <timeout> seconds. If <callback> is provided, it will be executed when the task completes or times out. The return value, if any, will be the final state of the task.
6259908099fddb7c1ca63b2e
class Ritchie(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Ritchie(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): <NEW_LINE> <INDENT> return grpc.experimental.unary_unary(request, target, '/ritchie.Ritchie/Ritchie', ritchie__pb2.RitchieRequest.SerializeToString, ritchie__pb2.RitchieReply.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
The Formula service definition.
625990805fdd1c0f98e5fa2a
class MatchException(Exception): <NEW_LINE> <INDENT> pass
Exception raised when matching fails, for example if input dictionary contains keys with the wrong data type for the specified query.
62599080ad47b63b2c5a92fb
class AppBuildViewSet(BaseAppViewSet): <NEW_LINE> <INDENT> model = models.Build <NEW_LINE> serializer_class = serializers.BuildSerializer <NEW_LINE> def post_save(self, build, created=False): <NEW_LINE> <INDENT> if created: <NEW_LINE> <INDENT> release = build.app.release_set.latest() <NEW_LINE> self.release = release.new(self.request.user, build=build) <NEW_LINE> initial = True if build.app.structure == {} else False <NEW_LINE> build.app.deploy(self.release, initial=initial) <NEW_LINE> <DEDENT> <DEDENT> def get_success_headers(self, data): <NEW_LINE> <INDENT> headers = super(AppBuildViewSet, self).get_success_headers(data) <NEW_LINE> headers.update({'X-Deis-Release': self.release.version}) <NEW_LINE> return headers <NEW_LINE> <DEDENT> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> app = get_object_or_404(models.App, id=self.kwargs['id']) <NEW_LINE> request._data = request.DATA.copy() <NEW_LINE> request.DATA['app'] = app <NEW_LINE> return super(AppBuildViewSet, self).create(request, *args, **kwargs)
RESTful views for :class:`~api.models.Build`.
62599080f548e778e596d03d
class Grant(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(AUTH_USER_MODEL) <NEW_LINE> client = models.ForeignKey(Client) <NEW_LINE> code = models.CharField(max_length=255, default=long_token) <NEW_LINE> expires = models.DateTimeField(default=get_code_expiry) <NEW_LINE> redirect_uri = models.CharField(max_length=255, blank=True) <NEW_LINE> scope = models.IntegerField(default=0) <NEW_LINE> created = models.DateTimeField(auto_now_add=True, default=datetime.datetime.now, blank=True, null=True) <NEW_LINE> modified = models.DateTimeField(auto_now=True, default=datetime.datetime.now, blank=True, null=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.code
Default grant implementation. A grant is a code that can be swapped for an access token. Grants have a limited lifetime as defined by :attr:`provider.constants.EXPIRE_CODE_DELTA` and outlined in :rfc:`4.1.2` Expected fields: * :attr:`user` * :attr:`client` - :class:`Client` * :attr:`code` * :attr:`expires` - :attr:`datetime.datetime` * :attr:`redirect_uri` * :attr:`scope`
625990804f6381625f19a204
class Solution: <NEW_LINE> <INDENT> def intToRoman(self, num: int) -> str: <NEW_LINE> <INDENT> symbols = {1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"} <NEW_LINE> ans = "" <NEW_LINE> for val in [1000, 100, 10, 1]: <NEW_LINE> <INDENT> i = num // val <NEW_LINE> if i > 0: <NEW_LINE> <INDENT> if i == 4: <NEW_LINE> <INDENT> ans += symbols[val] + symbols[5*val] <NEW_LINE> <DEDENT> elif i == 9: <NEW_LINE> <INDENT> ans += symbols[val] + symbols[10*val] <NEW_LINE> <DEDENT> elif i in (5, 6, 7, 8): <NEW_LINE> <INDENT> ans += symbols[5*val] + symbols[val]*(i-5) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ans += symbols[val]*i <NEW_LINE> <DEDENT> num -= i* val <NEW_LINE> <DEDENT> <DEDENT> return ans
check through 1000, 100, 10, 1. if > 9, insert "I"+Roman(val*10); if > 4 but < 5, insert "I"+Roman(val*5) if >= 5 but < 9, insert Roman(val*5) + "I"/"II"/"III"
625990805fcc89381b266eb2
class UnnormalizedMeasure(UnnormalizedCutoffMeasure): <NEW_LINE> <INDENT> thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> _nsubjettiness.UnnormalizedMeasure_swiginit(self, _nsubjettiness.new_UnnormalizedMeasure(*args)) <NEW_LINE> <DEDENT> description = _swig_new_instance_method(_nsubjettiness.UnnormalizedMeasure_description) <NEW_LINE> create = _swig_new_instance_method(_nsubjettiness.UnnormalizedMeasure_create) <NEW_LINE> __swig_destroy__ = _nsubjettiness.delete_UnnormalizedMeasure
Proxy of C++ fastjet::contrib::UnnormalizedMeasure class.
62599080ec188e330fdfa356
class IDLE(Operation): <NEW_LINE> <INDENT> NAME = "IDLE" <NEW_LINE> def __init__(self, cycles): <NEW_LINE> <INDENT> self.cycles = cycles <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s %d cycles" % (self.NAME, self.cycles) <NEW_LINE> <DEDENT> def as_bytes(self): <NEW_LINE> <INDENT> if not (IDLE_MIN_CYCLES <= self.cycles <= IDLE_MAX_CYCLES): <NEW_LINE> <INDENT> raise ValueError( "IDLE num cycles must fit in {} bits".format( IDLE_NUM_BITS ) ) <NEW_LINE> <DEDENT> return littleEndian(self.cycles << 1, 2)
Idle operation Attributes: cycles (int): Number of FPGA cycles to idle.
6259908023849d37ff852b65
class ChartDelegate(CustomDelegate): <NEW_LINE> <INDENT> editor = ChartEditor <NEW_LINE> def __init__(self, parent=None, **kwargs): <NEW_LINE> <INDENT> super(ChartDelegate, self).__init__(parent) <NEW_LINE> <DEDENT> def setModelData(self, editor, model, index): <NEW_LINE> <INDENT> pass
Custom delegate for Matplotlib charts
62599080a05bb46b3848be7e
class Url: <NEW_LINE> <INDENT> def __init__(self , url , visitedTime = 1): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.visitedTime = visitedTime <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[Url:url=" + self.url + ",visitedTime=" + self.visitedTime + "]" <NEW_LINE> <DEDENT> __repr__ = __str__ <NEW_LINE> def __setUrl__(self , url): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> <DEDENT> def __getUrl__(self): <NEW_LINE> <INDENT> return self.url <NEW_LINE> <DEDENT> def __setVisitedTime__(self , visitedTime): <NEW_LINE> <INDENT> self.visitedTime = 1 <NEW_LINE> <DEDENT> def __getVisitedTime(self): <NEW_LINE> <INDENT> return self.visitedTime
A url class to describe a url
625990805166f23b2e244e84
class TimeStamped(models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> objects = managers.CustomModelManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True
TimeStamped Model Definition
625990803317a56b869bf29c
class PubsubProjectsSubscriptionsTestIamPermissionsRequest(_messages.Message): <NEW_LINE> <INDENT> resource = _messages.StringField(1, required=True) <NEW_LINE> testIamPermissionsRequest = _messages.MessageField('TestIamPermissionsRequest', 2)
A PubsubProjectsSubscriptionsTestIamPermissionsRequest object. Fields: resource: REQUIRED: The resource for which policy detail is being requested. Resource is usually specified as a path, such as, projects/{project}. testIamPermissionsRequest: A TestIamPermissionsRequest resource to be passed as the request body.
6259908076e4537e8c3f102b
class TcpipPluginMixin(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def args(cls, parser): <NEW_LINE> <INDENT> super(TcpipPluginMixin, cls).args(parser) <NEW_LINE> parser.add_argument("--tcpip_guid", default=None, help="Force this profile to be used for tcpip.") <NEW_LINE> <DEDENT> def __init__(self, tcpip_guid=None, **kwargs): <NEW_LINE> <INDENT> super(TcpipPluginMixin, self).__init__(**kwargs) <NEW_LINE> if tcpip_guid: <NEW_LINE> <INDENT> self.session.SetParameter("tcpip_guid", tcpip_guid) <NEW_LINE> <DEDENT> self.tcpip_profile = self.session.address_resolver.LoadProfileForName( "tcpip") <NEW_LINE> if not self.tcpip_profile: <NEW_LINE> <INDENT> raise RuntimeError("Unable to load the profile for tcpip.sys")
A mixin for plugins that want to use tcpip.sys profiles.
625990804527f215b58eb6f6
class MyGame(arcade.Window): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "Sprite Example") <NEW_LINE> self.player_list = None <NEW_LINE> self.coin_list = None <NEW_LINE> self.player_sprite = None <NEW_LINE> self.score = 0 <NEW_LINE> self.set_mouse_visible(False) <NEW_LINE> arcade.set_background_color(arcade.color.AMAZON) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.player_list = arcade.SpriteList() <NEW_LINE> self.coin_list = arcade.SpriteList() <NEW_LINE> self.score = 0 <NEW_LINE> self.player_sprite = arcade.Sprite("images/character.png", SPRITE_SCALING_PLAYER) <NEW_LINE> self.player_sprite.center_x = 50 <NEW_LINE> self.player_sprite.center_y = 50 <NEW_LINE> self.player_list.append(self.player_sprite) <NEW_LINE> for i in range(COIN_COUNT): <NEW_LINE> <INDENT> coin = Coin("images/coin_01.png", SPRITE_SCALING_COIN) <NEW_LINE> coin.center_x = random.randrange(SCREEN_WIDTH) <NEW_LINE> coin.center_y = random.randrange(SCREEN_HEIGHT) <NEW_LINE> self.coin_list.append(coin) <NEW_LINE> <DEDENT> <DEDENT> def on_draw(self): <NEW_LINE> <INDENT> arcade.start_render() <NEW_LINE> self.coin_list.draw() <NEW_LINE> self.player_list.draw() <NEW_LINE> output = "Score: {}".format(self.score) <NEW_LINE> arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14) <NEW_LINE> <DEDENT> def on_mouse_motion(self, x, y, dx, dy): <NEW_LINE> <INDENT> self.player_sprite.center_x = x <NEW_LINE> self.player_sprite.center_y = y <NEW_LINE> <DEDENT> def update(self, delta_time): <NEW_LINE> <INDENT> self.coin_list.update() <NEW_LINE> coins_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) <NEW_LINE> for coin in coins_hit_list: <NEW_LINE> <INDENT> self.score += 1 <NEW_LINE> coin.reset_pos()
Our custom Window Class
6259908044b2445a339b76b3
class JSONEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, Promise): <NEW_LINE> <INDENT> return force_text(obj) <NEW_LINE> <DEDENT> elif isinstance(obj, datetime.datetime): <NEW_LINE> <INDENT> representation = obj.isoformat() <NEW_LINE> if obj.microsecond: <NEW_LINE> <INDENT> representation = representation[:23] + representation[26:] <NEW_LINE> <DEDENT> if representation.endswith('+00:00'): <NEW_LINE> <INDENT> representation = representation[:-6] + 'Z' <NEW_LINE> <DEDENT> return representation <NEW_LINE> <DEDENT> elif isinstance(obj, datetime.date): <NEW_LINE> <INDENT> return obj.isoformat() <NEW_LINE> <DEDENT> elif isinstance(obj, datetime.time): <NEW_LINE> <INDENT> if timezone and timezone.is_aware(obj): <NEW_LINE> <INDENT> raise ValueError("JSON can't represent timezone-aware times.") <NEW_LINE> <DEDENT> representation = obj.isoformat() <NEW_LINE> if obj.microsecond: <NEW_LINE> <INDENT> representation = representation[:12] <NEW_LINE> <DEDENT> return representation <NEW_LINE> <DEDENT> elif isinstance(obj, datetime.timedelta): <NEW_LINE> <INDENT> return six.text_type(total_seconds(obj)) <NEW_LINE> <DEDENT> elif isinstance(obj, decimal.Decimal): <NEW_LINE> <INDENT> return float(obj) <NEW_LINE> <DEDENT> elif isinstance(obj, uuid.UUID): <NEW_LINE> <INDENT> return six.text_type(obj) <NEW_LINE> <DEDENT> elif isinstance(obj, QuerySet): <NEW_LINE> <INDENT> return tuple(obj) <NEW_LINE> <DEDENT> elif hasattr(obj, 'tolist'): <NEW_LINE> <INDENT> return obj.tolist() <NEW_LINE> <DEDENT> elif hasattr(obj, '__getitem__'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dict(obj) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> elif hasattr(obj, '__iter__'): <NEW_LINE> <INDENT> return tuple(item for item in obj) <NEW_LINE> <DEDENT> return super(JSONEncoder, self).default(obj)
JSONEncoder subclass that knows how to encode date/time/timedelta, decimal types, generators and other basic python objects. Taken from https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py
625990803346ee7daa3383b8
class OnesWeightInitializer(WeightInitializer): <NEW_LINE> <INDENT> def init(self, dimension: Tuple) -> Tensor: <NEW_LINE> <INDENT> return np.ones(dimension)
Initializes a Tensor with all ones. Example:: weight_init = OnesWeightInitializer() w = weight_init.init((10, 20))
62599080fff4ab517ebcf2c4
class ShowIpOspfDatabaseRouterSchema(MetaParser): <NEW_LINE> <INDENT> schema = { 'vrf': {Any(): {'address_family': {Any(): {'instance': {Any(): {Optional('areas'): {Any(): {'database': {'lsa_types': {Any(): {'lsa_type': int, 'lsas': {Any(): {'lsa_id': str, 'adv_router': str, 'ospfv2': {'header': {'option': str, 'option_desc': str, 'lsa_id': str, 'age': int, 'type': int, 'adv_router': str, 'seq_num': str, 'checksum': str, 'length': int, Optional('routing_bit_enable'): bool, Optional('as_boundary_router'): bool, Optional('area_border_router'): bool, }, 'body': {'router': {Optional('flags'): str, 'num_of_links': int, Optional('links'): {Any(): {'link_id': str, 'link_data': str, 'type': str, Optional('num_mtid_metrics'): int, Optional('num_tos_metrics'): int, 'topologies': {Any(): {'mt_id': int, Optional('metric'): int, Optional('tos'): int, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }, }
Schema for: * show ip ospf database router'
625990804428ac0f6e659fdc
class City(object): <NEW_LINE> <INDENT> def __init__(self, areaName=None, country=None, region=None, weatherUrl=None, latitude=None, longitude=None, population=None): <NEW_LINE> <INDENT> self.areaName = areaName <NEW_LINE> self.country = country <NEW_LINE> self.region = region <NEW_LINE> self.weatherUrl = weatherUrl <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.population = population <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<City({0}, {1}, {2})>".format(self.areaName, self.country, self.region)
Describe City object according to real city
62599080283ffb24f3cf534e
class Range(BaseMetadataObject): <NEW_LINE> <INDENT> _type = "sc:Range" <NEW_LINE> _uri_segment = "range/" <NEW_LINE> _required = ["@id", "label", "canvases"] <NEW_LINE> _warn = [] <NEW_LINE> canvases = [] <NEW_LINE> def __init__(self, factory, ident="", label="", mdhash={}): <NEW_LINE> <INDENT> super(Range, self).__init__(factory, ident, label, mdhash) <NEW_LINE> self.canvases = [] <NEW_LINE> <DEDENT> def add_canvas(self, cvs, frag=""): <NEW_LINE> <INDENT> cvsid = cvs.id <NEW_LINE> if frag: <NEW_LINE> <INDENT> cvsid += frag <NEW_LINE> <DEDENT> self.canvases.append(cvsid)
Range object in Presentation API.
62599080ec188e330fdfa358
class TestUpgrade(BaseTestCase): <NEW_LINE> <INDENT> def test_to1010_available(self): <NEW_LINE> <INDENT> upgradeSteps = listUpgradeSteps(self.st, self.profile, '1000') <NEW_LINE> step = [step for step in upgradeSteps if (step[0]['dest'] == ('1010',)) and (step[0]['source'] == ('1000',))] <NEW_LINE> self.assertEqual(len(step), 0)
Ensure product upgrades work.
62599080796e427e53850228
class NucleicAcidMethods(unittest.TestCase): <NEW_LINE> <INDENT> def test_complement(self): <NEW_LINE> <INDENT> foo = NucleicAcid('ACTG') <NEW_LINE> foo2 = 'TGAC' <NEW_LINE> self.assertEqual(foo.complement(), foo2) <NEW_LINE> <DEDENT> def test_codon(self): <NEW_LINE> <INDENT> foo = NucleicAcid('GGTGCG') <NEW_LINE> foo2 = ['GGT','GCG'] <NEW_LINE> self.assertEqual(foo.codon(), foo2) <NEW_LINE> <DEDENT> def test_translate(self): <NEW_LINE> <INDENT> foo = NucleicAcid('GGTGCG') <NEW_LINE> foo2 = 'GA' <NEW_LINE> self.assertEqual(foo.translate(), foo2)
Test NucleicAcid methods
62599080091ae356687066ed
@abstract <NEW_LINE> class DataRenderer(Renderer): <NEW_LINE> <INDENT> pass
An abstract base class for data renderer types (e.g. ``GlyphRenderer``, ``TileRenderer``).
625990807d847024c075de8b
class SocialServicesDetailsForm(NannyForm): <NEW_LINE> <INDENT> error_summary_title = "There was a problem" <NEW_LINE> error_summary_template_name = "standard-error-summary.html" <NEW_LINE> auto_replace_widgets = True <NEW_LINE> social_services_details = forms.CharField( widget=forms.Textarea(), label="Give details of all instances.", error_messages={ "required": "Details about your involvement with social services must be entered" }, ) <NEW_LINE> def clean_social_services_details(self): <NEW_LINE> <INDENT> social_services_details = self.cleaned_data['social_services_details'] <NEW_LINE> if len(social_services_details) > 1000: <NEW_LINE> <INDENT> raise forms.ValidationError( 'Details must be under 1000 characters long') <NEW_LINE> <DEDENT> return social_services_details
GOV.UK form for the social services details page
6259908092d797404e3898b3
@six.add_metaclass(ABCMeta) <NEW_LINE> class IconFontDownloader(object): <NEW_LINE> <INDENT> css_path = None <NEW_LINE> ttf_path = None <NEW_LINE> @property <NEW_LINE> def css_url(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def ttf_url(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __init__(self, directory=None): <NEW_LINE> <INDENT> self.directory = directory <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _download_file_from_url(url, directory=None): <NEW_LINE> <INDENT> if not directory: <NEW_LINE> <INDENT> return urlretrieve(url)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> css_filename = os.path.join(directory, url.split('/')[-1]) <NEW_LINE> return urlretrieve(url, filename=css_filename)[0] <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _get_latest_tag_from_github(repo_api_url): <NEW_LINE> <INDENT> url = '/'.join([repo_api_url, 'tags']) <NEW_LINE> r = requests.get(url) <NEW_LINE> latest = r.json()[0] <NEW_LINE> return latest['name'] <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def get_latest_version_number(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def download_css(self, directory): <NEW_LINE> <INDENT> return self._download_file_from_url(self.css_url, directory) <NEW_LINE> <DEDENT> def download_ttf(self, directory): <NEW_LINE> <INDENT> return self._download_file_from_url(self.ttf_url, directory) <NEW_LINE> <DEDENT> def download_files(self): <NEW_LINE> <INDENT> self.css_path = self.download_css(self.directory) <NEW_LINE> self.ttf_path = self.download_ttf(self.directory)
Abstract class for downloading icon font CSS and TTF files
6259908097e22403b383c9ae
class EmsRoutingGetIterKeyTd(NetAppObject): <NEW_LINE> <INDENT> _key_0 = None <NEW_LINE> @property <NEW_LINE> def key_0(self): <NEW_LINE> <INDENT> return self._key_0 <NEW_LINE> <DEDENT> @key_0.setter <NEW_LINE> def key_0(self, val): <NEW_LINE> <INDENT> if val != None: <NEW_LINE> <INDENT> self.validate('key_0', val) <NEW_LINE> <DEDENT> self._key_0 = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "ems-routing-get-iter-key-td" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_desired_attrs(): <NEW_LINE> <INDENT> return [ 'key-0', ] <NEW_LINE> <DEDENT> def describe_properties(self): <NEW_LINE> <INDENT> return { 'key_0': { 'class': basestring, 'is_list': False, 'required': 'optional' }, }
Key typedef for table ems_definition
62599080dc8b845886d55068
class ColossusApi(BasicAPIClient): <NEW_LINE> <INDENT> pagination_param_names = ("page",) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ColossusApi, self).__init__( os.environ.get("COLOSSUS_API_URL", COLOSSUS_API_URL), username=os.environ.get("COLOSSUS_API_USERNAME"), password=os.environ.get("COLOSSUS_API_PASSWORD"), ) <NEW_LINE> <DEDENT> def get_list_pagination_initial_params(self, params): <NEW_LINE> <INDENT> params["page"] = 1 <NEW_LINE> <DEDENT> def get_list_pagination_next_page_params(self, params): <NEW_LINE> <INDENT> params["page"] += 1 <NEW_LINE> <DEDENT> def get_colossus_sublibraries_from_library_id(self, library_id): <NEW_LINE> <INDENT> return list(self.list("sublibraries", library__pool_id=library_id)) <NEW_LINE> <DEDENT> def query_libraries_by_library_id(self, library_id): <NEW_LINE> <INDENT> return self.get("library", pool_id=library_id)
Colossus API class.
62599080656771135c48ad87
class BehanceOAuth2(BaseOAuth2): <NEW_LINE> <INDENT> name = 'behance' <NEW_LINE> AUTHORIZATION_URL = 'https://www.behance.net/v2/oauth/authenticate' <NEW_LINE> ACCESS_TOKEN_URL = 'https://www.behance.net/v2/oauth/token' <NEW_LINE> ACCESS_TOKEN_METHOD = 'POST' <NEW_LINE> SCOPE_SEPARATOR = '|' <NEW_LINE> EXTRA_DATA = [('username', 'username')] <NEW_LINE> REDIRECT_STATE = False <NEW_LINE> def get_user_id(self, details, response): <NEW_LINE> <INDENT> return response['user']['id'] <NEW_LINE> <DEDENT> def get_user_details(self, response): <NEW_LINE> <INDENT> user = response['user'] <NEW_LINE> fullname, first_name, last_name = self.get_user_names( user['display_name'], user['first_name'], user['last_name'] ) <NEW_LINE> return {'username': user['username'], 'fullname': fullname, 'first_name': first_name, 'last_name': last_name, 'email': ''} <NEW_LINE> <DEDENT> def extra_data(self, user, uid, response, details): <NEW_LINE> <INDENT> data = response.copy() <NEW_LINE> data.update(response['user']) <NEW_LINE> return super(BehanceOAuth2, self).extra_data(user, uid, data, details)
Behance OAuth authentication backend
62599080ad47b63b2c5a92ff
@final <NEW_LINE> class FadeoutMusicAction(EventAction[FadeoutMusicActionParameters]): <NEW_LINE> <INDENT> name = "fadeout_music" <NEW_LINE> param_class = FadeoutMusicActionParameters <NEW_LINE> def start(self) -> None: <NEW_LINE> <INDENT> time = self.parameters.duration <NEW_LINE> mixer.music.fadeout(time) <NEW_LINE> if self.session.client.current_music["song"]: <NEW_LINE> <INDENT> self.session.client.current_music["status"] = "stopped" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning("Music cannot be paused, none is playing.")
Fade out the music over a set amount of time in milliseconds. Script usage: .. code-block:: fadeout_music <duration> Script parameters: duration: Number of milliseconds to fade out the music over.
62599080099cdd3c63676151
class PhantomDataTransferServer(socketserver.ThreadingTCPServer, DataTransferServer): <NEW_LINE> <INDENT> def __init__(self, ip, port, fmt, handler_class=PhantomDataTransferHandler): <NEW_LINE> <INDENT> DataTransferServer.__init__(self, ip, port, fmt, handler_class) <NEW_LINE> socketserver.ThreadingTCPServer.__init__(self, self.address, self.handler_class) <NEW_LINE> self.create_thread() <NEW_LINE> <DEDENT> def receive_image(self): <NEW_LINE> <INDENT> while self.image_bytes is None: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> <DEDENT> image_bytes = self.image_bytes <NEW_LINE> self.image_bytes = None <NEW_LINE> self.logger.debug('Reset internal buffer to %s after image with %s bytes', self.image_bytes, len(image_bytes)) <NEW_LINE> return image_bytes <NEW_LINE> <DEDENT> def create_thread(self): <NEW_LINE> <INDENT> self.thread = threading.Thread(target=self.serve_forever) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.running = True <NEW_LINE> self.thread.daemon = True <NEW_LINE> self.thread.start() <NEW_LINE> self.logger.debug('main thread has started') <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> self.server_close() <NEW_LINE> self.shutdown() <NEW_LINE> self.thread.join() <NEW_LINE> self.logger.debug('Server shutting down...')
This is a threaded server, that is being started, by the main phantom control instance, the PhantomSocket. It listens for incoming connections FROM the phantom camera, because over these secondary channels the camera transmits the raw byte data. The way it works: The main program execution maintains a reference to this object. This object will work as the main access point for receiving images using the "receive_image" method. But the actual process of receiving the image is not handled in this object. Although this object listens for incoming data connections, but as soon as a camera makes a request for a new connection for transferring an image, this object automatically creates a handler object and passes the data connection to that handler, which is then in charge of receiving the data in a separate thread. The "receive_image" method just waits until the handler is finished, gets the image from the handler and then passes it along to the main program CHANGELOG Added 23.02.2019 Changed 19.03.2019 Moved most of the actual functions into a base class. This class now only inherits from that base class.
62599080fff4ab517ebcf2c7
class Meta(element.Element): <NEW_LINE> <INDENT> resource_type = "Meta" <NEW_LINE> def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.lastUpdated = None <NEW_LINE> self.profile = None <NEW_LINE> self.security = None <NEW_LINE> self.source = None <NEW_LINE> self.tag = None <NEW_LINE> self.versionId = None <NEW_LINE> super(Meta, self).__init__(jsondict=jsondict, strict=strict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(Meta, self).elementProperties() <NEW_LINE> js.extend([ ("lastUpdated", "lastUpdated", fhirdate.FHIRDate, False, None, False), ("profile", "profile", str, True, None, False), ("security", "security", coding.Coding, True, None, False), ("source", "source", str, False, None, False), ("tag", "tag", coding.Coding, True, None, False), ("versionId", "versionId", str, False, None, False), ]) <NEW_LINE> return js
Metadata about a resource. The metadata about a resource. This is content in the resource that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource.
6259908097e22403b383c9af
class ThreathunterJsonParser(BaseParser): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name or "" <NEW_LINE> <DEDENT> def parse(self, data): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = json.loads(data) <NEW_LINE> if result["status"] != 0: <NEW_LINE> <INDENT> LOGGER.error("config %s: the status is not good, status is %s", self.name, result["status"]) <NEW_LINE> return {} <NEW_LINE> <DEDENT> config = {} <NEW_LINE> for _ in result["values"]: <NEW_LINE> <INDENT> config[_["key"]] = _["value"] <NEW_LINE> <DEDENT> return config <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> LOGGER.error("config %s: fail to parse threathunter json config, the error is %s", self.name, err) <NEW_LINE> <DEDENT> return {} <NEW_LINE> <DEDENT> def dump(self, config): <NEW_LINE> <INDENT> result = { "status": 0, "msg": "OK", } <NEW_LINE> try: <NEW_LINE> <INDENT> result["values"] = [{"key": k, "value": v} for k, v in config.items()] <NEW_LINE> return result <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> LOGGER.error("config %s: fail to dump config to threathunter json, he error is %s", self.name, err) <NEW_LINE> result["values"] = [] <NEW_LINE> <DEDENT> return result
Parse config from json with threathunter format. Threathunter api uses special json format.
625990804f6381625f19a206
class WussStructureInitTests(StructureStringInitTests): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.Struct = WussStructure <NEW_LINE> self.Empty = '' <NEW_LINE> self.NoPairs = '__--_' <NEW_LINE> self.OneHelix = '[{(<()>)}]' <NEW_LINE> self.ManyHelices = '<,,(({___})~((:((({{__}}),))),,<<[(__)]>>)):::>' <NEW_LINE> self.TooManyOpen = '{<[___]>::' <NEW_LINE> self.TooManyClosed = '<<___>>>::' <NEW_LINE> self.Invalid = '__!<><>'
Test for initializing WussStructures
62599080be7bc26dc9252bad
class TemplateParameters(ASTNode): <NEW_LINE> <INDENT> positional = List(PositionalParameter) <NEW_LINE> keywords = List(KeywordParameter) <NEW_LINE> starparam = Str()
An AST node for template parameters.
6259908066673b3332c31eaf
class CompanyCreateView(LoginRequiredMixin, CreateView): <NEW_LINE> <INDENT> model = Company <NEW_LINE> template_name = 'add_or_update_company.html' <NEW_LINE> form_class = CompanyForm <NEW_LINE> success_url = reverse_lazy('companies') <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> form.instance.added_by = self.request.user <NEW_LINE> return super().form_valid(form)
This view is responsible for adding companies.
625990805fdd1c0f98e5fa2f
class ZookeeperTest(unittest.TestCase): <NEW_LINE> <INDENT> @mock.patch('builtins.open', create=True) <NEW_LINE> def test_zookeeper_configuration_script_data(self, open_mock): <NEW_LINE> <INDENT> config = configuration.Zookeeper( hostname='zookeeper', ldap_hostname='ldap_host', ipa_server_hostname='ipa_server_hostname', otp='otp', idx='idx' ) <NEW_LINE> expected_script_data = { 'provision-base.sh': [ 'DOMAIN', 'HOSTNAME', 'LDAP_HOSTNAME' ], 'install-ipa-client-with-otp.sh': ['OTP'], 'provision-zookeeper.sh': ['DOMAIN', 'IPA_SERVER_HOSTNAME', 'IDX'], } <NEW_LINE> self.assertCountEqual( [s['name'] for s in config.setup_scripts], expected_script_data.keys() ) <NEW_LINE> for script_data in config.setup_scripts: <NEW_LINE> <INDENT> self.assertCountEqual( expected_script_data[script_data['name']], script_data['vars'].keys() )
Tests zookeeper configuration
625990804f88993c371f127a
class V1beta3_PodList(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'apiVersion': 'str', 'items': 'list[V1beta3_Pod]', 'kind': 'str', 'resourceVersion': 'str', 'selfLink': 'str' } <NEW_LINE> self.attributeMap = { 'apiVersion': 'apiVersion', 'items': 'items', 'kind': 'kind', 'resourceVersion': 'resourceVersion', 'selfLink': 'selfLink' } <NEW_LINE> self.apiVersion = None <NEW_LINE> self.items = None <NEW_LINE> self.kind = None <NEW_LINE> self.resourceVersion = None <NEW_LINE> self.selfLink = None
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62599080d268445f2663a8b6
class VirtualDiskAdapterTypeTest(test.TestCase): <NEW_LINE> <INDENT> def test_is_valid(self): <NEW_LINE> <INDENT> self.assertTrue(volumeops.VirtualDiskAdapterType.is_valid("lsiLogic")) <NEW_LINE> self.assertTrue(volumeops.VirtualDiskAdapterType.is_valid("busLogic")) <NEW_LINE> self.assertTrue(volumeops.VirtualDiskAdapterType.is_valid( "lsiLogicsas")) <NEW_LINE> self.assertTrue(volumeops.VirtualDiskAdapterType.is_valid("ide")) <NEW_LINE> self.assertFalse(volumeops.VirtualDiskAdapterType.is_valid("pvscsi")) <NEW_LINE> <DEDENT> def test_validate(self): <NEW_LINE> <INDENT> volumeops.VirtualDiskAdapterType.validate("lsiLogic") <NEW_LINE> volumeops.VirtualDiskAdapterType.validate("busLogic") <NEW_LINE> volumeops.VirtualDiskAdapterType.validate("lsiLogicsas") <NEW_LINE> volumeops.VirtualDiskAdapterType.validate("ide") <NEW_LINE> self.assertRaises(error_util.InvalidAdapterTypeException, volumeops.VirtualDiskAdapterType.validate, "pvscsi") <NEW_LINE> <DEDENT> def test_get_adapter_type(self): <NEW_LINE> <INDENT> self.assertEqual("lsiLogic", volumeops.VirtualDiskAdapterType.get_adapter_type( "lsiLogic")) <NEW_LINE> self.assertEqual("busLogic", volumeops.VirtualDiskAdapterType.get_adapter_type( "busLogic")) <NEW_LINE> self.assertEqual("lsiLogic", volumeops.VirtualDiskAdapterType.get_adapter_type( "lsiLogicsas")) <NEW_LINE> self.assertEqual("ide", volumeops.VirtualDiskAdapterType.get_adapter_type( "ide")) <NEW_LINE> self.assertRaises(error_util.InvalidAdapterTypeException, volumeops.VirtualDiskAdapterType.get_adapter_type, "pvscsi")
Unit tests for VirtualDiskAdapterType.
625990807d847024c075de8d
class LoginForm(Form): <NEW_LINE> <INDENT> email = StringField("Email", validators = [DataRequired()]) <NEW_LINE> password = PasswordField("Password", validators = [DataRequired()]) <NEW_LINE> submit = SubmitField('Submit')
form template for login in
6259908055399d3f05627fc5
class TestReleaseApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = swagger_client.apis.release_api.ReleaseApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_create(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_all(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update(self): <NEW_LINE> <INDENT> pass
ReleaseApi unit test stubs
6259908063b5f9789fe86c1a
class TestQuickSort(unittest.TestCase): <NEW_LINE> <INDENT> def test_base_case(self): <NEW_LINE> <INDENT> B = [1] <NEW_LINE> self.assertEqual(B, qS.quickSort(B, 0, 0)) <NEW_LINE> <DEDENT> def test_array_of_length_5(self): <NEW_LINE> <INDENT> D = [3, 5, 4, 1, 2] <NEW_LINE> DPrime = [1, 2, 3, 4, 5] <NEW_LINE> self.assertEqual(DPrime, qS.quickSort(D, 0, 4)) <NEW_LINE> <DEDENT> def test_if_l_out_of_array_array_returned(self): <NEW_LINE> <INDENT> D = [3, 5, 4, 1, 2] <NEW_LINE> self.assertEqual(D, qS.quickSort(D, 8, 4)) <NEW_LINE> <DEDENT> def test_error_if_r_in_array(self): <NEW_LINE> <INDENT> D = [3, 5, 4, 1, 2] <NEW_LINE> self.assertRaises(IndexError, qS.quickSort, D, 0, 6)
Unit test quickSort subroutine.
62599080796e427e5385022c
class Map(SchemaField): <NEW_LINE> <INDENT> def __init__(self, target_name=None, converter=None, key_converter=converters.ToJsonString, value_converter=converters.ToJsonString): <NEW_LINE> <INDENT> super(Map, self).__init__(target_name, converter) <NEW_LINE> self.key_converter = key_converter <NEW_LINE> self.value_converter = value_converter <NEW_LINE> <DEDENT> def _VisitInternal(self, value): <NEW_LINE> <INDENT> ValidateType(value, dict) <NEW_LINE> result = {} <NEW_LINE> for key, dict_value in value.items(): <NEW_LINE> <INDENT> if self.key_converter: <NEW_LINE> <INDENT> key = self.key_converter(key) <NEW_LINE> <DEDENT> if self.value_converter: <NEW_LINE> <INDENT> dict_value = self.value_converter(dict_value) <NEW_LINE> <DEDENT> result[key] = dict_value <NEW_LINE> <DEDENT> return result
Represents a leaf node where the value itself is a map. Expected input type: Dictionary Output type: Dictionary
62599080f548e778e596d044
class ParseError(Error): <NEW_LINE> <INDENT> pass
Error that is raised when value data cannot be parsed.
625990802c8b7c6e89bd5297
class CTD_ANON_11 (structLinkType): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = None <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/home/claudio/Applications/eudat/b2safe/manifest/mets.xsd', 483, 4) <NEW_LINE> _ElementMap = structLinkType._ElementMap.copy() <NEW_LINE> _AttributeMap = structLinkType._AttributeMap.copy() <NEW_LINE> _AttributeWildcard = pyxb.binding.content.Wildcard(process_contents=pyxb.binding.content.Wildcard.PC_lax, namespace_constraint=(pyxb.binding.content.Wildcard.NC_not, 'http://www.loc.gov/METS/')) <NEW_LINE> _ElementMap.update({ }) <NEW_LINE> _AttributeMap.update({ })
The structural link section element <structLink> allows for the specification of hyperlinks between the different components of a METS structure that are delineated in a structural map. This element is a container for a single, repeatable element, <smLink> which indicates a hyperlink between two nodes in the structural map. The <structLink> section in the METS document is identified using its XML ID attributes.
62599080442bda511e95dab0
class Consumer(object): <NEW_LINE> <INDENT> @remote <NEW_LINE> def unregister(self): <NEW_LINE> <INDENT> log.info('Consumer has been unregistered. ' 'Katello agent will no longer function until ' 'this system is reregistered.')
When a consumer is unregistered, Katello notifies the goferd.
625990808a349b6b43687d10
class BinariesCriteria(object): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> self_dict = copy.copy(self.__dict__) <NEW_LINE> self_dict['hash'] = None <NEW_LINE> other_dict = copy.copy(other.__dict__) <NEW_LINE> other_dict['hash'] = None <NEW_LINE> return (isinstance(other, self.__class__) and self_dict == other_dict) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __init__(self, os_type=None, branch=None, version=None, distribution=None, cpu_arch="x86_64", debug=False, project=None, git_hash=None, variant=None): <NEW_LINE> <INDENT> self.os_type = os_type <NEW_LINE> self.variant = variant <NEW_LINE> self.branch = branch <NEW_LINE> self.version = version <NEW_LINE> self.distribution = distribution <NEW_LINE> self.cpu_arch = cpu_arch <NEW_LINE> self.debug = debug <NEW_LINE> self.project = project <NEW_LINE> self.git_hash = git_hash <NEW_LINE> self.hash = None <NEW_LINE> system_type = platform.system() <NEW_LINE> if os_type is None and variant is None: <NEW_LINE> <INDENT> if system_type == 'Windows': <NEW_LINE> <INDENT> self.os_type = "win32" <NEW_LINE> self.variant = "windows-64" <NEW_LINE> <DEDENT> elif system_type == 'Linux': <NEW_LINE> <INDENT> self.os_type = "linux" <NEW_LINE> self.variant = "linux-64" <NEW_LINE> <DEDENT> elif system_type == 'Darwin': <NEW_LINE> <INDENT> self.os_type = "osx" <NEW_LINE> self.variant = "osx-108" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.os_type = "sunos5" <NEW_LINE> self.variant = "solaris-64-bit" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def init_from_current_binaries(current_binaries): <NEW_LINE> <INDENT> criteria = BinariesCriteria(branch=current_binaries.branch, version=current_binaries.revision, os_type=current_binaries.os_type, cpu_arch=current_binaries.cpu_arch, distribution=current_binaries.distribution) <NEW_LINE> if current_binaries.md5 is not None and current_binaries.hash is None: <NEW_LINE> <INDENT> criteria.hash = current_binaries.md5 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> criteria.hash = current_binaries.hash <NEW_LINE> <DEDENT> return criteria
The Criteria used for downloading a set of binaries.
62599080be7bc26dc9252baf
class AuthenticatedAndGroupMember(permissions.IsAuthenticatedOrReadOnly): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return request.user.is_staff or obj.group in request.user.groups.all()
Users can only manipulate objects belonging to their group(s).
6259908060cbc95b06365ac6
class PythonExpression(ASTNode): <NEW_LINE> <INDENT> ast = Typed(ast.Expression)
An ASTNode representing a Python expression.
6259908092d797404e3898b6
class Rotate2D(object): <NEW_LINE> <INDENT> def __init__(self, rotation, reference=None, lazy=False): <NEW_LINE> <INDENT> self.rotation = rotation <NEW_LINE> self.lazy = lazy <NEW_LINE> self.reference = reference <NEW_LINE> self.tx = tio.ANTsTransform( precision="float", dimension=2, transform_type="AffineTransform" ) <NEW_LINE> if self.reference is not None: <NEW_LINE> <INDENT> self.tx.set_fixed_parameters(self.reference.get_center_of_mass()) <NEW_LINE> <DEDENT> <DEDENT> def transform(self, X=None, y=None): <NEW_LINE> <INDENT> rotation = self.rotation <NEW_LINE> theta = math.pi / 180 * rotation <NEW_LINE> rotation_matrix = np.array( [[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0]] ) <NEW_LINE> self.tx.set_parameters(rotation_matrix) <NEW_LINE> if self.lazy or X is None: <NEW_LINE> <INDENT> return self.tx <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if y is None: <NEW_LINE> <INDENT> return self.tx.apply_to_image(X, reference=self.reference) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ( self.tx.apply_to_image(X, reference=self.reference), self.tx.apply_to_image(y, reference=self.reference), )
Create an ANTs Affine Transform with a specified level of rotation.
62599080a8370b77170f1e85
class DecoderBlock(chainer.Chain): <NEW_LINE> <INDENT> def __init__(self, in_ch=3, mid_ch=0, out_ch=13, ksize=3, stride=1, pad=1, residual=False, nobias=False, outsize=None, upsample=False, use_bn=True, use_prelu=False): <NEW_LINE> <INDENT> super(DecoderBlock, self).__init__() <NEW_LINE> self.residual = residual <NEW_LINE> mid_ch = int(in_ch / 4) <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> this_mod = sys.modules[__name__] <NEW_LINE> conv_type = "ConvBN" if use_bn else "Conv" <NEW_LINE> activation = "PReLU" if use_prelu else "ReLU" <NEW_LINE> ConvBlock = getattr(this_mod, conv_type + activation) <NEW_LINE> self.conv1 = ConvBlock(in_ch, mid_ch, 1, 1, 0, nobias=True) <NEW_LINE> conv_type2 = conv_type + activation <NEW_LINE> ConvBlock = getattr(this_mod, conv_type2) <NEW_LINE> self.conv2 = ConvBlock(mid_ch, mid_ch, ksize, stride, pad, nobias=False, upsample=upsample, outsize=None) <NEW_LINE> ConvBlock = getattr(this_mod, conv_type) <NEW_LINE> self.conv3 = ConvBlock(mid_ch, out_ch, 1, 1, 0, nobias=True) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> h1 = self.conv1(x) <NEW_LINE> h1 = self.conv2(h1) <NEW_LINE> h1 = self.conv3(h1) <NEW_LINE> if self.residual: <NEW_LINE> <INDENT> return F.relu(h1 + x) <NEW_LINE> <DEDENT> return F.relu(h1) <NEW_LINE> <DEDENT> def predict(self, x): <NEW_LINE> <INDENT> h1 = self.conv1(x) <NEW_LINE> h1 = self.conv2(h1) <NEW_LINE> h1 = self.conv3(h1) <NEW_LINE> if self.residual: <NEW_LINE> <INDENT> return F.relu(h1 + x) <NEW_LINE> <DEDENT> return F.relu(h1)
DecoderBlock Abstract
6259908076e4537e8c3f1033
class DiscoSNSTests(TestCase): <NEW_LINE> <INDENT> @mock_sns <NEW_LINE> def get_region(self): <NEW_LINE> <INDENT> return boto.connect_sns().region.name <NEW_LINE> <DEDENT> @mock_sns <NEW_LINE> def test_constructor(self): <NEW_LINE> <INDENT> disco_sns = DiscoSNS(account_id=ACCOUNT_ID) <NEW_LINE> self.assertIsNotNone(disco_sns.sns) <NEW_LINE> <DEDENT> @mock_sns <NEW_LINE> def test_create_topic(self): <NEW_LINE> <INDENT> disco_sns = DiscoSNS(account_id=ACCOUNT_ID) <NEW_LINE> disco_sns.create_topic(TOPIC) <NEW_LINE> topics_json = disco_sns.sns.get_all_topics() <NEW_LINE> topic_arn = topics_json["ListTopicsResponse"]["ListTopicsResult"]["Topics"][0]['TopicArn'] <NEW_LINE> self.assertIn(TOPIC, topic_arn) <NEW_LINE> <DEDENT> @mock_sns <NEW_LINE> def test_subscribe_emails(self): <NEW_LINE> <INDENT> disco_sns = DiscoSNS(account_id=ACCOUNT_ID) <NEW_LINE> disco_sns.create_topic(TOPIC) <NEW_LINE> disco_sns.subscribe(TOPIC, SUBSCRIPTION_EMAIL_LIST) <NEW_LINE> self.assertGreater(disco_sns.sns.get_all_subscriptions(), 0) <NEW_LINE> <DEDENT> @mock_sns <NEW_LINE> def test_subscribe_url(self): <NEW_LINE> <INDENT> disco_sns = DiscoSNS(account_id=ACCOUNT_ID) <NEW_LINE> disco_sns.create_topic(TOPIC) <NEW_LINE> disco_sns.subscribe(TOPIC, [SUBSCRIPTION_URL]) <NEW_LINE> self.assertGreater(disco_sns.sns.get_all_subscriptions(), 0) <NEW_LINE> <DEDENT> @mock_sns <NEW_LINE> def test_topic_arn_from_name(self): <NEW_LINE> <INDENT> disco_sns = DiscoSNS(account_id=ACCOUNT_ID) <NEW_LINE> arn = disco_sns.topic_arn_from_name(TOPIC) <NEW_LINE> self.assertEqual(arn, "arn:aws:sns:{0}:{1}:{2}".format(self.get_region(), ACCOUNT_ID, TOPIC)) <NEW_LINE> <DEDENT> @mock_sns <NEW_LINE> def test_get_topics_to_delete(self): <NEW_LINE> <INDENT> env = "ci" <NEW_LINE> existing_topics = ["astro_topic1_ci_critical", "astro_topic1_staging_critical", "astro_topic2_ci_critical", "astro_topic1_another-ci_critical", "test"] <NEW_LINE> desired_topics = ["astro_topic1_ci_critical"] <NEW_LINE> expected_topic_to_delete = ["astro_topic2_ci_critical"] <NEW_LINE> topic_to_delete = DiscoSNS.get_topics_to_delete(existing_topics, desired_topics, env) <NEW_LINE> self.assertItemsEqual(expected_topic_to_delete, topic_to_delete)
Test DiscoSNS class
625990802c8b7c6e89bd5299
class NotAnIntervalError(Error): <NEW_LINE> <INDENT> pass
Raised when user input string is not in valid interval form.
62599080a05bb46b3848be82
class FieldPreparationErrors(Exception, collections.Mapping): <NEW_LINE> <INDENT> def __init__(self, exceptions): <NEW_LINE> <INDENT> message = 'Setting the field{} {} failed.'.format( 's' if len(exceptions) > 1 else '', ', '.join('"{}"'.format(name) for name in exceptions) ) <NEW_LINE> Exception.__init__(self, message) <NEW_LINE> self._exceptions = exceptions <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> return self._exceptions[name] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._exceptions) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._exceptions) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> hash_value = Exception.__hash__(self) <NEW_LINE> for name in self._exceptions: <NEW_LINE> <INDENT> current_hash = hash(name) ^ hash(self._exceptions[name]) <NEW_LINE> hash_value = hash_value ^ current_hash <NEW_LINE> <DEDENT> return hash_value <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, FieldPreparationErrors) and self.message == other.message and self._exceptions == other._exceptions)
This exception is thrown if preparation of at least one field fails, when setting multiple field at once by assigning a mapping to the ``FIELDS`` attribute on a field container instance. This exception is a mapping from field names to the appropriate exception objects thrown by the :meth:`Field.prepare` calls.
62599080656771135c48ad8a
class LoginSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> token = serializers.SerializerMethodField('get_json_web_token') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Account <NEW_LINE> fields = ('token',) <NEW_LINE> <DEDENT> def get_json_web_token(self, obj): <NEW_LINE> <INDENT> return get_json_web_token(obj)
Account Signup serializer to handle user registration.
625990804a966d76dd5f099a
class Timer(object): <NEW_LINE> <INDENT> def __init__(self, description, param=None, silent=None, verbose=None, too_long=0): <NEW_LINE> <INDENT> self.template = description <NEW_LINE> self.param = wrap(coalesce(param, {})) <NEW_LINE> self.verbose = coalesce(verbose, False if silent is True else True) <NEW_LINE> self.agg = 0 <NEW_LINE> self.too_long = too_long <NEW_LINE> self.start = 0 <NEW_LINE> self.end = 0 <NEW_LINE> self.interval = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if self.verbose and self.too_long == 0: <NEW_LINE> <INDENT> Log.note("Timer start: " + self.template, stack_depth=1, **self.param) <NEW_LINE> <DEDENT> self.start = time() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.end = time() <NEW_LINE> self.interval = self.end - self.start <NEW_LINE> self.agg += self.interval <NEW_LINE> self.param.duration = timedelta(seconds=self.interval) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> if self.too_long == 0: <NEW_LINE> <INDENT> Log.note("Timer end : " + self.template + " (took {{duration}})", default_params=self.param, stack_depth=1) <NEW_LINE> <DEDENT> elif self.interval >= self.too_long: <NEW_LINE> <INDENT> Log.note("Time too long: " + self.template + " ({{duration}})", default_params=self.param, stack_depth=1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def duration(self): <NEW_LINE> <INDENT> end = time() <NEW_LINE> if not self.end: <NEW_LINE> <INDENT> return Duration(end - self.start) <NEW_LINE> <DEDENT> return Duration(self.interval) <NEW_LINE> <DEDENT> @property <NEW_LINE> def total(self): <NEW_LINE> <INDENT> if not self.end: <NEW_LINE> <INDENT> Log.error("please ask for total time outside the context of measuring") <NEW_LINE> <DEDENT> return Duration(self.agg)
USAGE: with Timer("doing hard time"): something_that_takes_long() OUTPUT: doing hard time took 45.468 sec param - USED WHEN LOGGING debug - SET TO False TO DISABLE THIS TIMER
62599080aad79263cf43026f
class Workflow(resource.Resource): <NEW_LINE> <INDENT> id = wtypes.text <NEW_LINE> name = wtypes.text <NEW_LINE> namespace = wtypes.text <NEW_LINE> input = wtypes.text <NEW_LINE> definition = wtypes.text <NEW_LINE> tags = [wtypes.text] <NEW_LINE> scope = SCOPE_TYPES <NEW_LINE> project_id = wtypes.text <NEW_LINE> created_at = wtypes.text <NEW_LINE> updated_at = wtypes.text <NEW_LINE> @classmethod <NEW_LINE> def sample(cls): <NEW_LINE> <INDENT> return cls(id='123e4567-e89b-12d3-a456-426655440000', name='flow', input='param1, param2', definition='HERE GOES' 'WORKFLOW DEFINITION IN MISTRAL DSL v2', tags=['large', 'expensive'], scope='private', project_id='a7eb669e9819420ea4bd1453e672c0a7', created_at='1970-01-01T00:00:00.000000', updated_at='1970-01-01T00:00:00.000000', namespace='') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _set_input(cls, obj, wf_spec): <NEW_LINE> <INDENT> input_list = [] <NEW_LINE> if wf_spec: <NEW_LINE> <INDENT> input = wf_spec.get('input', []) <NEW_LINE> for param in input: <NEW_LINE> <INDENT> if isinstance(param, dict): <NEW_LINE> <INDENT> for k, v in param.items(): <NEW_LINE> <INDENT> input_list.append("%s=%s" % (k, v)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> input_list.append(param) <NEW_LINE> <DEDENT> <DEDENT> setattr(obj, 'input', ", ".join(input_list) if input_list else '') <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, d): <NEW_LINE> <INDENT> obj = super(Workflow, cls).from_dict(d) <NEW_LINE> return cls._set_input(obj, d.get('spec')) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_db_model(cls, db_model): <NEW_LINE> <INDENT> obj = super(Workflow, cls).from_db_model(db_model) <NEW_LINE> return cls._set_input(obj, db_model.spec)
Workflow resource.
625990804428ac0f6e659fe4
class mac_netstat(mac_tasks.mac_tasks): <NEW_LINE> <INDENT> def render_text(self, outfd, data): <NEW_LINE> <INDENT> self.table_header(outfd, [("Proto", "6"), ("Local IP", "20"), ("Local Port", "6"), ("Remote IP", "20"), ("Remote Port", "6"), ("State", "20"), ("Process", "24")]) <NEW_LINE> for proc in data: <NEW_LINE> <INDENT> for (family, info) in proc.netstat(): <NEW_LINE> <INDENT> if family == 1: <NEW_LINE> <INDENT> (socket, path) = info <NEW_LINE> if path: <NEW_LINE> <INDENT> outfd.write("UNIX {0}\n".format(path)) <NEW_LINE> <DEDENT> <DEDENT> elif family in [2, 30]: <NEW_LINE> <INDENT> (socket, proto, lip, lport, rip, rport, state) = info <NEW_LINE> self.table_row(outfd, proto, lip, lport, rip, rport, state, "{}/{}".format(proc.p_comm, proc.p_pid))
Lists active per-process network connections
625990807c178a314d78e945
class TimeWrapper: <NEW_LINE> <INDENT> warned = False <NEW_LINE> def sleep(self, *args, **kwargs): <NEW_LINE> <INDENT> if not TimeWrapper.warned: <NEW_LINE> <INDENT> TimeWrapper.warned = True <NEW_LINE> _LOGGER.warning("Using time.sleep can reduce the performance of " "Home Assistant") <NEW_LINE> <DEDENT> time.sleep(*args, **kwargs) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(time, attr)
Wrapper of the time module.
62599080be7bc26dc9252bb0
class TestDemoUtilities(unittest.TestCase): <NEW_LINE> <INDENT> def test_sys_path_inserted(self): <NEW_LINE> <INDENT> path = os.path.join("dirname", "file.py") <NEW_LINE> with demo_path(path): <NEW_LINE> <INDENT> self.assertIn("dirname", sys.path) <NEW_LINE> <DEDENT> self.assertNotIn("dirname", sys.path)
Test utility functions in the _demo module.
6259908063b5f9789fe86c1e
class ScaleImage(BrowserView): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> self.params = self.request.form <NEW_LINE> self.path = self.params.get('path', []) <NEW_LINE> if self.path: <NEW_LINE> <INDENT> self.path = self.path.split(';') <NEW_LINE> <DEDENT> self.uid = self.params.get('uid', []) <NEW_LINE> if self.uid: <NEW_LINE> <INDENT> self.uid = self.uid.split(';') <NEW_LINE> <DEDENT> self.scale = self.params.get('scale', None) <NEW_LINE> self.width = self.params.get('width', None) <NEW_LINE> self.height = self.params.get('height', None) <NEW_LINE> <DEDENT> def _to_json(self, data): <NEW_LINE> <INDENT> pretty = json.dumps(data, sort_keys=True, indent=4) <NEW_LINE> minutes = 20 <NEW_LINE> seconds = minutes * 60 <NEW_LINE> self.request.response.setHeader('Cache-Control', 's-maxage=%d' % int(seconds)) <NEW_LINE> self.request.response.setHeader('Access-Control-Allow-Origin', '*') <NEW_LINE> self.request.response.setHeader('Content-Type', 'application/json') <NEW_LINE> return pretty <NEW_LINE> <DEDENT> def _get_image_data(self, image): <NEW_LINE> <INDENT> image_data = {} <NEW_LINE> scales = image.restrictedTraverse('@@images') <NEW_LINE> thumb = None <NEW_LINE> if self.scale: <NEW_LINE> <INDENT> thumb = scales.scale('image', self.scale) <NEW_LINE> <DEDENT> elif self.width and self.height: <NEW_LINE> <INDENT> thumb = scales.scale('image', width=self.width, height=self.height) <NEW_LINE> <DEDENT> if thumb: <NEW_LINE> <INDENT> image_data['path'] = '/'.join(image.getPhysicalPath()) <NEW_LINE> image_data['description'] = cgi.escape(str(image.Description())) <NEW_LINE> image_data['height'] = thumb.height <NEW_LINE> image_data['mimetype'] = thumb.mimetype <NEW_LINE> image_data['scale'] = self.scale <NEW_LINE> image_data['tag'] = cgi.escape(str(thumb.tag())) <NEW_LINE> image_data['title'] = cgi.escape(str(image.Title())) <NEW_LINE> image_data['uid'] = thumb.uid <NEW_LINE> image_data['url'] = thumb.url <NEW_LINE> image_data['width'] = thumb.width <NEW_LINE> <DEDENT> return image_data <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> data = [] <NEW_LINE> if self.path or self.uid: <NEW_LINE> <INDENT> for path in self.path: <NEW_LINE> <INDENT> image = api.content.get(path=path) <NEW_LINE> if image: <NEW_LINE> <INDENT> image_data = self._get_image_data(image) <NEW_LINE> data.append(image_data) <NEW_LINE> <DEDENT> <DEDENT> for uid in self.uid: <NEW_LINE> <INDENT> image = api.content.get(UID=uid) <NEW_LINE> if image: <NEW_LINE> <INDENT> image_data = self._get_image_data(image) <NEW_LINE> data.append(image_data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> image_data = self._get_image_data(self.context) <NEW_LINE> data.append(image_data) <NEW_LINE> <DEDENT> if len(data) == 1: <NEW_LINE> <INDENT> data = data[0] <NEW_LINE> <DEDENT> return self._to_json(data) <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> self.update() <NEW_LINE> return self.render()
Returns JSON with resized image information
625990804c3428357761bd70
class Customer(models.Model): <NEW_LINE> <INDENT> app = models.ForeignKey(Application, verbose_name=_('Application'), help_text=_('The application that holds this customer record')) <NEW_LINE> name = models.CharField(_('İsim'), max_length=100, help_text=_('Name of the customer')) <NEW_LINE> mail = models.CharField(_('E-posta'), max_length=150, help_text=_('E-mail of the customer')) <NEW_LINE> mobile = models.CharField(_('Telefon'), max_length=20, help_text=_('Mobile phone number of the customer (0XXX XXX XX XX)')) <NEW_LINE> address = models.CharField(_('Adres'), max_length=150, help_text=_('Address of the customer')) <NEW_LINE> timestamp = models.DateTimeField(_('zamanpulu'), auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['timestamp'] <NEW_LINE> get_latest_by = "timestamp" <NEW_LINE> verbose_name = _('Customer') <NEW_LINE> verbose_name_plural = _('Customers') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '%s [Tel: %s]' % (self.name, self.mobile)
musteri kayitlari
625990807d847024c075de93
class Route(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "route" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.ipv6_destination_cfg = [] <NEW_LINE> self.ip_destination_cfg = [] <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value)
This class does not support CRUD Operations please use parent. :param ipv6_destination_cfg: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"distance": {"description": "Route's administrative distance (default: match any)", "minimum": 1, "type": "number", "maximum": 255, "format": "number"}, "v6mask": {"description": "IPv6 Destination Prefix", "minimum": 0, "type": "number", "maximum": 128, "format": "number"}, "protocol": {"enum": ["any", "static", "dynamic"], "type": "string", "description": "any: "Match any routing protocol (default)"; static: "Match only static routes (added by user)"; dynamic: "Match routes added by dynamic routing protocols (e.g. OSPF)"; ", "format": "enum"}, "priority-cost": {"description": "The amount the priority will decrease if the route is missing. help-val The amount the priority will decrease if the route is not present", "minimum": 1, "type": "number", "maximum": 255, "format": "number"}, "ipv6-destination": {"type": "string", "description": "IPv6 Destination Prefix", "format": "ipv6-address"}, "gatewayv6": {"type": "string", "description": "Match the route's gateway (next-hop) (default: match any)", "format": "ipv6-address"}, "optional": true}}]} :param ip_destination_cfg: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"distance": {"description": "Route's administrative distance (default: match any)", "minimum": 1, "type": "number", "maximum": 255, "format": "number"}, "protocol": {"enum": ["any", "static", "dynamic"], "type": "string", "description": "any: "Match any routing protocol (default)"; static: "Match only static routes (added by user)"; dynamic: "Match routes added by dynamic routing protocols (e.g. OSPF)"; ", "format": "enum"}, "mask": {"type": "string", "description": "Destination prefix mask", "format": "ipv4-netmask"}, "priority-cost": {"description": "The amount the priority will decrease if the route is missing. help-val The amount the priority will decrease if the route is not present", "minimum": 1, "type": "number", "maximum": 255, "format": "number"}, "ip-destination": {"type": "string", "description": "Destination prefix", "format": "ipv4-address"}, "optional": true, "gateway": {"type": "string", "description": "Match the route's gateway (next-hop) (default: match any)", "format": "ipv4-address"}}}]} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
6259908023849d37ff852b6f
class CancelScriptWatcher(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "wm.sw_watch_end" <NEW_LINE> bl_label = "Stop Watching" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> context.scene.sw_settings.running = False <NEW_LINE> return {'FINISHED'}
Sets a flag which tells the modal to cancel itself.
625990803d592f4c4edbc8ba
@freeze_time("2010-10-10 00:00:00") <NEW_LINE> class BaseBallotVoteTestCase(TestCase): <NEW_LINE> <INDENT> urls = 'django_elect.tests.urls' <NEW_LINE> def run(self, result=None): <NEW_LINE> <INDENT> if not hasattr(self, "ballot_type"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return super(BaseBallotVoteTestCase, self).run(result) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> user_model = apps.get_model(settings.DJANGO_ELECT_USER_MODEL) <NEW_LINE> self.user1 = user_model.objects.create_user(username="[email protected]", email='[email protected]', password="foo") <NEW_LINE> self.client.login(username="[email protected]", password="foo") <NEW_LINE> self.election = Election.objects.create( name="current", vote_start=datetime(2010, 10, 1), vote_end=datetime(2010, 10, 11)) <NEW_LINE> self.election.allowed_voters.add(self.user1) <NEW_LINE> ballot1 = self.election.ballots.create(id=1, type=self.ballot_type, seats_available=2, is_secret=True, write_in_available=True, introduction="something something") <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> ballot1.candidates.create(id=Candidate.objects.count() + 1, first_name="Ballot 1", last_name="Candidate %i" % i) <NEW_LINE> <DEDENT> ballot2 = self.election.ballots.create(id=2, type=self.ballot_type, seats_available=4, is_secret=False, write_in_available=False) <NEW_LINE> for i in range(1, 7): <NEW_LINE> <INDENT> ballot2.candidates.create(id=Candidate.objects.count() + 1, first_name="Ballot 2", last_name="Candidate %i" % i) <NEW_LINE> <DEDENT> <DEDENT> def test_generic(self): <NEW_LINE> <INDENT> ballot_type = self.ballot_type <NEW_LINE> response = self.client.get("/election/") <NEW_LINE> self.assertContains(response, "something something", 1) <NEW_LINE> for b in self.election.ballots.all(): <NEW_LINE> <INDENT> for c in b.candidates.all(): <NEW_LINE> <INDENT> self.assertContains(response, c.get_name()) <NEW_LINE> <DEDENT> <DEDENT> cand = Candidate.objects.create(ballot=self.election.ballots.all()[0], first_name="Ralph", last_name="Nader", write_in=True) <NEW_LINE> self.assertNotContains(response, cand.get_name()) <NEW_LINE> cand.delete() <NEW_LINE> self.assertContains(response, 'id="id_ballot1-write_in_1"') <NEW_LINE> self.assertNotContains(response, 'id="id_ballot2-write_in_1"') <NEW_LINE> response = self.client.post("/election/") <NEW_LINE> self.assertEqual(response.status_code, 200)
Base class for testing the vote() view using specific ballots
62599080d268445f2663a8b9
class BayeuxChannel(object): <NEW_LINE> <INDENT> __slots__ = ('name', '_clients', '_subchannels') <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self._clients = [] <NEW_LINE> self._subchannels = {} <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<BayeuxChannel name=%s>' % self.name <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def split(cls, name): <NEW_LINE> <INDENT> return name.split('/')[1:] if name != '/' else [] <NEW_LINE> <DEDENT> def _on_dead_client(self, wclient): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._clients.remove(wclient) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def add_client(self, client, segs): <NEW_LINE> <INDENT> if not segs: <NEW_LINE> <INDENT> wclient = weakref.ref(client, self._on_dead_client) <NEW_LINE> self._clients.append(wclient) <NEW_LINE> return <NEW_LINE> <DEDENT> name = segs.pop(0) <NEW_LINE> try: <NEW_LINE> <INDENT> ch = self._subchannels[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> ch = BayeuxChannel(name) <NEW_LINE> self._subchannels[name] = ch <NEW_LINE> <DEDENT> ch.add_client(client, segs) <NEW_LINE> <DEDENT> def remove_client(self, client, segs): <NEW_LINE> <INDENT> if not segs: <NEW_LINE> <INDENT> wclient = weakref.ref(client) <NEW_LINE> self._clients.remove(wclient) <NEW_LINE> return <NEW_LINE> <DEDENT> name = segs.pop(0) <NEW_LINE> try: <NEW_LINE> <INDENT> ch = self._subchannels[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> ch.add_client(client, segs) <NEW_LINE> <DEDENT> def collect_clients(self, clients, segs): <NEW_LINE> <INDENT> if not segs: <NEW_LINE> <INDENT> clients.update([wclient() for wclient in self._clients]) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ch = self._subchannels['**'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ch.collect_clients(clients, None) <NEW_LINE> <DEDENT> if len(segs) == 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ch = self._subchannels['*'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ch.collect_clients(clients, None) <NEW_LINE> <DEDENT> <DEDENT> name = segs.pop(0) <NEW_LINE> try: <NEW_LINE> <INDENT> ch = self._subchannels[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ch.collect_clients(clients, segs)
Represents a Bayeux channel and operations on it.
62599080f548e778e596d048
class Scheduler(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, Scheduler, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, Scheduler, name) <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def init(self, start=True): <NEW_LINE> <INDENT> return _pilot.Scheduler_init(self, start) <NEW_LINE> <DEDENT> def isFinished(self): <NEW_LINE> <INDENT> return _pilot.Scheduler_isFinished(self) <NEW_LINE> <DEDENT> def exUpdateState(self): <NEW_LINE> <INDENT> return _pilot.Scheduler_exUpdateState(self) <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return _pilot.Scheduler_getName(self) <NEW_LINE> <DEDENT> def getTaskName(self, *args): <NEW_LINE> <INDENT> return _pilot.Scheduler_getTaskName(self, *args) <NEW_LINE> <DEDENT> def getNextTasks(self, *args): <NEW_LINE> <INDENT> return _pilot.Scheduler_getNextTasks(self, *args) <NEW_LINE> <DEDENT> def selectRunnableTasks(self, *args): <NEW_LINE> <INDENT> return _pilot.Scheduler_selectRunnableTasks(self, *args) <NEW_LINE> <DEDENT> def notifyFrom(self, *args): <NEW_LINE> <INDENT> return _pilot.Scheduler_notifyFrom(self, *args) <NEW_LINE> <DEDENT> def getDeploymentTree(self): <NEW_LINE> <INDENT> return _pilot.Scheduler_getDeploymentTree(self) <NEW_LINE> <DEDENT> def isPlacementPredictableB4Run(self): <NEW_LINE> <INDENT> return _pilot.Scheduler_isPlacementPredictableB4Run(self) <NEW_LINE> <DEDENT> def isMultiplicitySpecified(self, *args): <NEW_LINE> <INDENT> return _pilot.Scheduler_isMultiplicitySpecified(self, *args) <NEW_LINE> <DEDENT> def forceMultiplicity(self, *args): <NEW_LINE> <INDENT> return _pilot.Scheduler_forceMultiplicity(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _pilot.delete_Scheduler <NEW_LINE> __del__ = lambda self : None;
Proxy of C++ YACS::ENGINE::Scheduler class
62599080f548e778e596d049
class LoginMainWindow(base_frame_view.BaseFrameView): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super(LoginMainWindow, self).__init__(parent) <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_field(self): <NEW_LINE> <INDENT> return text_field.UIATextField(self.parent, type='UIATextField') <NEW_LINE> <DEDENT> @property <NEW_LINE> def password_field(self): <NEW_LINE> <INDENT> return secure_text_field.UIASecureTextField(self.parent, type='UIASecureTextField') <NEW_LINE> <DEDENT> @property <NEW_LINE> def login_button(self): <NEW_LINE> <INDENT> name_ = '登录' <NEW_LINE> return button.UIAButton(self.parent, name=name_) <NEW_LINE> <DEDENT> def input_account(self, phone_number): <NEW_LINE> <INDENT> log.logger.info("开始清空账号内容") <NEW_LINE> self.account_field.clear_text_field() <NEW_LINE> log.logger.info("账号内容清空完毕,开始输入账号") <NEW_LINE> self.account_field.send_keys(phone_number) <NEW_LINE> time.sleep(2) <NEW_LINE> <DEDENT> def input_password(self, password): <NEW_LINE> <INDENT> log.logger.info("开始清空密码内容") <NEW_LINE> self.password_field.clear_text_field() <NEW_LINE> log.logger.info("密码内容清空完毕,开始输入密码") <NEW_LINE> self.password_field.send_keys(password) <NEW_LINE> time.sleep(2) <NEW_LINE> <DEDENT> def tap_login_button(self, auto=True): <NEW_LINE> <INDENT> log.logger.info("开始点击登录按钮") <NEW_LINE> self.login_button.tap() <NEW_LINE> log.logger.info("完成点击登录按钮") <NEW_LINE> if auto: <NEW_LINE> <INDENT> if self.wait_window(windows.WindowNames.LOGIN_FRIEND_RECOMMEND, 5): <NEW_LINE> <INDENT> log.logger.info("登录后首先进入了好友推荐页") <NEW_LINE> log.logger.info("点击好友推荐页的完成按钮") <NEW_LINE> curr_friend_window = login_friend_recommend_window.LoginFriendRecommendWindow(self.parent) <NEW_LINE> curr_friend_window.tap_finish_button() <NEW_LINE> <DEDENT> <DEDENT> if self.wait_window(windows.WindowNames.IN_MAIN): <NEW_LINE> <INDENT> log.logger.info("登陆成功,成功进入In主页") <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.logger.info("登陆失败,进入In主页面失败") <NEW_LINE> return False
Summary: 登陆活动页 Attributes: parent: 该活动页的父亲framework
62599080be7bc26dc9252bb1
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class _ShareHandler(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_instance(cls, remote): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_from_id(cls, share_id, client): <NEW_LINE> <INDENT> share = manila.get_share(client, share_id, raise_on_error=True) <NEW_LINE> mounter_class = _share_types[share.share_proto] <NEW_LINE> return mounter_class(share, client) <NEW_LINE> <DEDENT> def __init__(self, share, client): <NEW_LINE> <INDENT> self.share = share <NEW_LINE> self.client = client <NEW_LINE> <DEDENT> def allow_access_to_instance(self, instance, share_config): <NEW_LINE> <INDENT> access_level = self._get_access_level(share_config) <NEW_LINE> accesses = list(filter(lambda x: (x.access_type == 'ip' and x.access_to == instance.internal_ip), self.share.access_list())) <NEW_LINE> if accesses: <NEW_LINE> <INDENT> access = accesses[0] <NEW_LINE> if access.access_level not in ('ro', 'rw'): <NEW_LINE> <INDENT> LOG.warning( _LW("Unknown permission level {access_level} on share " "id {share_id} for ip {ip}. Leaving pre-existing " "permissions.").format( access_level=access.access_level, share_id=self.share.id, ip=instance.internal_ip)) <NEW_LINE> <DEDENT> elif access.access_level == 'ro' and access_level == 'rw': <NEW_LINE> <INDENT> self.share.deny(access.id) <NEW_LINE> self.share.allow('ip', instance.internal_ip, access_level) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.share.allow('ip', instance.internal_ip, access_level) <NEW_LINE> <DEDENT> <DEDENT> @abc.abstractmethod <NEW_LINE> def mount_to_instance(self, remote, share_info): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def unmount_from_instance(self, remote, share_info): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _get_access_level(self, share_config): <NEW_LINE> <INDENT> return share_config.get('access_level', 'rw') <NEW_LINE> <DEDENT> def _default_mount(self): <NEW_LINE> <INDENT> return '/mnt/{0}'.format(self.share.id) <NEW_LINE> <DEDENT> def _get_path(self, share_info): <NEW_LINE> <INDENT> return share_info.get('path', self._default_mount())
Handles mounting of a single share to any number of instances.
625990805fdd1c0f98e5fa37
class ValiFilteredSelectMultiple(FilteredSelectMultiple): <NEW_LINE> <INDENT> def get_context(self, name, value, attrs): <NEW_LINE> <INDENT> context = super(ValiFilteredSelectMultiple, self).get_context(name, value, attrs) <NEW_LINE> context['widget']['attrs']['class'] = 'selectfilter' <NEW_LINE> if self.is_stacked: <NEW_LINE> <INDENT> context['widget']['attrs']['class'] += 'stacked' <NEW_LINE> <DEDENT> context['widget']['attrs']['data-field-name'] = self.verbose_name <NEW_LINE> context['widget']['attrs']['data-is-stacked'] = int(self.is_stacked) <NEW_LINE> return context
customize FilteredSelectMultiple, not used for now
625990804c3428357761bd72
class Info(mlbgame.object.Object): <NEW_LINE> <INDENT> def nice_output(self): <NEW_LINE> <INDENT> return '{0} ({1})'.format(self.club_full_name, self.club.upper()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.nice_output()
Holds information about the league or teams Properties: club club_common_name club_common_url club_full_name club_id club_spanish_name dc_site display_code division es_track_code esp_common_name esp_common_url facebook facebook_es fanphotos_url fb_app_id field google_tag_manager googleplus_id historical_team_code id instagram instagram_id league location medianet_id mobile_es_url mobile_short_code mobile_url mobile_url_base name_display_long name_display_short newsletter_category_id newsletter_group_id photostore_url pinterest pinterest_verification pressbox_title pressbox_url primary primary_link secondary snapchat snapchat_es team_code team_id tertiary timezone track_code track_filter tumblr twitter twitter_es url_cache url_esp url_prod vine
625990802c8b7c6e89bd529d
class Expect(object): <NEW_LINE> <INDENT> def __init__(self, actual_data): <NEW_LINE> <INDENT> self.actual_data = actual_data <NEW_LINE> self.negate = False <NEW_LINE> <DEDENT> def not_(self): <NEW_LINE> <INDENT> self.negate = True <NEW_LINE> return self <NEW_LINE> <DEDENT> def to_be(self, expected_data): <NEW_LINE> <INDENT> if self.negate and self.actual_data is expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'not_to_be') <NEW_LINE> <DEDENT> elif not self.negate and self.actual_data is not expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'to_be') <NEW_LINE> <DEDENT> <DEDENT> def to_equal(self, expected_data): <NEW_LINE> <INDENT> if self.negate and self.actual_data == expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'not_to_equal') <NEW_LINE> <DEDENT> elif not self.negate and self.actual_data != expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'to_equal') <NEW_LINE> <DEDENT> <DEDENT> def to_be_less_than(self, expected_data): <NEW_LINE> <INDENT> if self.negate and self.actual_data < expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than') <NEW_LINE> <DEDENT> elif not self.negate and not self.actual_data < expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'to_be_less_than') <NEW_LINE> <DEDENT> <DEDENT> def to_be_greater_than(self, expected_data): <NEW_LINE> <INDENT> if self.negate and self.actual_data > expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'not_to_be_greater_than') <NEW_LINE> <DEDENT> elif not self.negate and not self.actual_data > expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'to_be_greater_than') <NEW_LINE> <DEDENT> <DEDENT> def to_be_less_than_or_equal_to(self, expected_data): <NEW_LINE> <INDENT> if self.negate and self.actual_data <= expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than_or_equal_to') <NEW_LINE> <DEDENT> elif not self.negate and not self.actual_data <= expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'to_be_less_than_or_equal_to') <NEW_LINE> <DEDENT> <DEDENT> def to_be_greater_than_or_equal_to(self, expected_data): <NEW_LINE> <INDENT> if self.negate and self.actual_data >= expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'not_to_be_greater_than_or_equal_to') <NEW_LINE> <DEDENT> elif not self.negate and not self.actual_data >= expected_data: <NEW_LINE> <INDENT> raise ExpectationException(self.actual_data, expected_data, 'to_be_greater_than_or_equal_to')
A class for making assertions on data.
625990807b180e01f3e49dc1
class Main: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.config() <NEW_LINE> sys.exit(self.run()) <NEW_LINE> <DEDENT> except (EOFError, KeyboardInterrupt): <NEW_LINE> <INDENT> sys.exit(114) <NEW_LINE> <DEDENT> except SystemExit as exception: <NEW_LINE> <INDENT> sys.exit(exception) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def config() -> None: <NEW_LINE> <INDENT> if hasattr(signal, 'SIGPIPE'): <NEW_LINE> <INDENT> signal.signal(signal.SIGPIPE, signal.SIG_DFL) <NEW_LINE> <DEDENT> if os.name == 'nt': <NEW_LINE> <INDENT> argv = [] <NEW_LINE> for arg in sys.argv: <NEW_LINE> <INDENT> files = glob.glob(arg) <NEW_LINE> if files: <NEW_LINE> <INDENT> argv.extend(files) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> argv.append(arg) <NEW_LINE> <DEDENT> <DEDENT> sys.argv = argv <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def run() -> int: <NEW_LINE> <INDENT> options = Options() <NEW_LINE> Menu(options).open() <NEW_LINE> return 0
Main class
62599080e1aae11d1e7cf56e
class StringCompressTest(unittest.TestCase): <NEW_LINE> <INDENT> data = [('aabbb', 'a2b3'), ('aabbccaa', 'aabbccaa'), ('', None), ('a', 'a'), (None, None)] <NEW_LINE> def test_compress_string(self): <NEW_LINE> <INDENT> for inp_string, output in self.data: <NEW_LINE> <INDENT> self.assertEqual(output, compress(inp_string))
Test Cases for compressing the strings
62599080dc8b845886d55072
class Visualizer(): <NEW_LINE> <INDENT> def __init__(self, root, name, subdir_label='img_label'): <NEW_LINE> <INDENT> self.img_label_path = os.path.join(root, name, subdir_label) <NEW_LINE> <DEDENT> def save_img(self, fn, img_label): <NEW_LINE> <INDENT> assert isinstance(img_label, ndarray) <NEW_LINE> self.save_fp = os.path.join(self.img_label_path, fn + '.png') <NEW_LINE> mpimg.imsave(fname=self.save_fp, arr=img_label) <NEW_LINE> assert os.path.isfile(self.save_fp)
此 class 用来存储所有图像, 图像内容共有如下 X 个: 1. img_origin 2. img_label '.png' Draw_Label-master | |__ dataset (saveroot = 'Draw_Label-master//dataset') | |__ 恶性 ( name = '恶性') | | |__ img_origin (sub_dir_origin = 'img_origin') | | |__ img_label (sub_dir_label = 'img_label) | |__ 良性 | | |__ img_origin | | |__ img_label
6259908044b2445a339b76b9
class MaccabiGamesGoalsTiming(object): <NEW_LINE> <INDENT> def __init__(self, maccabi_games_stats: MaccabiGamesStats): <NEW_LINE> <INDENT> self.maccabi_games_stats = maccabi_games_stats <NEW_LINE> self.games = maccabi_games_stats.games <NEW_LINE> <DEDENT> def fastest_two_goals(self, top_games_number=_TOP_GAMES_NUMBER) -> List[GameGoalTiming]: <NEW_LINE> <INDENT> return self._top_games_with_minimum_goals_time_frame(2)[:top_games_number] <NEW_LINE> <DEDENT> def fastest_three_goals(self, top_games_number=_TOP_GAMES_NUMBER) -> List[GameGoalTiming]: <NEW_LINE> <INDENT> return self._top_games_with_minimum_goals_time_frame(3)[:top_games_number] <NEW_LINE> <DEDENT> def fastest_four_goals(self, top_games_number=_TOP_GAMES_NUMBER) -> List[GameGoalTiming]: <NEW_LINE> <INDENT> return self._top_games_with_minimum_goals_time_frame(4)[:top_games_number] <NEW_LINE> <DEDENT> def _top_games_with_minimum_goals_time_frame(self, goals_number: int) -> List[GameGoalTiming]: <NEW_LINE> <INDENT> games_with_enough_goals = [game for game in self.maccabi_games_stats if game.maccabi_score >= goals_number] <NEW_LINE> games_goals_timings = [(game, _minimum_goals_time_frame_for_a_game(game, goals_number)) for game in games_with_enough_goals] <NEW_LINE> games_goals_timings_without_errors = [item for item in games_goals_timings if item[1] is not None] <NEW_LINE> return sorted(games_goals_timings_without_errors, key=lambda item: item[1])
This class will handle all goals timing statistics.
625990805fc7496912d48fc7
class _FakeUrllib2Request(object): <NEW_LINE> <INDENT> def __init__(self, uri): <NEW_LINE> <INDENT> self.uri = uri <NEW_LINE> self.headers = Headers() <NEW_LINE> self.type, rest = splittype(self.uri.decode('charmap')) <NEW_LINE> self.host, rest = splithost(rest) <NEW_LINE> <DEDENT> def has_header(self, header): <NEW_LINE> <INDENT> return self.headers.hasHeader(header) <NEW_LINE> <DEDENT> def add_unredirected_header(self, name, value): <NEW_LINE> <INDENT> self.headers.addRawHeader(name, value) <NEW_LINE> <DEDENT> def get_full_url(self): <NEW_LINE> <INDENT> return self.uri <NEW_LINE> <DEDENT> def get_header(self, name, default=None): <NEW_LINE> <INDENT> headers = self.headers.getRawHeaders(name, default) <NEW_LINE> if headers is not None: <NEW_LINE> <INDENT> return headers[0] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_host(self): <NEW_LINE> <INDENT> return self.host <NEW_LINE> <DEDENT> def get_type(self): <NEW_LINE> <INDENT> return self.type <NEW_LINE> <DEDENT> def is_unverifiable(self): <NEW_LINE> <INDENT> return False
A fake C{urllib2.Request} object for C{cookielib} to work with. @see: U{http://docs.python.org/library/urllib2.html#request-objects} @type uri: C{str} @ivar uri: Request URI. @type headers: L{twisted.web.http_headers.Headers} @ivar headers: Request headers. @type type: C{str} @ivar type: The scheme of the URI. @type host: C{str} @ivar host: The host[:port] of the URI. @since: 11.1
62599080f548e778e596d04b
class DayLogAnalyze(Base): <NEW_LINE> <INDENT> __tablename__ = "DayLogAnalyze" <NEW_LINE> id = Column(Integer , nullable = False , primary_key = True) <NEW_LINE> date = Column(LONGTEXT , nullable = False) <NEW_LINE> api_order = Column(LONGTEXT , nullable = False) <NEW_LINE> ip_order = Column(LONGTEXT , nullable = False) <NEW_LINE> every_hour_count = Column(LONGTEXT , nullable = False) <NEW_LINE> device_distribute = Column(LONGTEXT , nullable = False) <NEW_LINE> call_count = Column(Integer , nullable = False) <NEW_LINE> ip_count = Column(Integer , nullable = False) <NEW_LINE> ios_version = Column(LONGTEXT , nullable = True) <NEW_LINE> android_version = Column(LONGTEXT , nullable = True)
每日日志重要信息记录
62599080fff4ab517ebcf2d1
class DemoApp(wx.App): <NEW_LINE> <INDENT> ASPECT_RATIOS = [(4, 3), (16, 8)] <NEW_LINE> def OnRadioSelect(self, event): <NEW_LINE> <INDENT> aspect_ratio = self.ASPECT_RATIOS[event.GetInt()] <NEW_LINE> self.render_window_panel.aspect_ratio = aspect_ratio <NEW_LINE> <DEDENT> def OnInit(self): <NEW_LINE> <INDENT> frame = wx.Frame(None, -1, u'RenderWindowPanel demo', size=(400, 400)) <NEW_LINE> aspect_radio = wx.RadioBox( frame, -1, choices=['%s:%s' %ar for ar in self.ASPECT_RATIOS]) <NEW_LINE> render_window_panel = RenderWindowPanel(frame, -1) <NEW_LINE> frame.Bind(wx.EVT_RADIOBOX, self.OnRadioSelect) <NEW_LINE> sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> sizer.Add(aspect_radio, 0, wx.ALL|wx.EXPAND, 5) <NEW_LINE> sizer.Add(render_window_panel, 1, wx.ALL|wx.EXPAND, 5) <NEW_LINE> frame.SetSizer(sizer) <NEW_LINE> frame.Layout() <NEW_LINE> frame.Show(True) <NEW_LINE> self.render_window_panel = render_window_panel <NEW_LINE> self.SetTopWindow(frame) <NEW_LINE> renderer = vtk.vtkRenderer() <NEW_LINE> source = vtk.vtkConeSource() <NEW_LINE> source.SetResolution(8) <NEW_LINE> mapper = vtk.vtkPolyDataMapper() <NEW_LINE> mapper.SetInput(source.GetOutput()) <NEW_LINE> actor = vtk.vtkActor() <NEW_LINE> actor.SetMapper(mapper) <NEW_LINE> renderer.AddActor(actor) <NEW_LINE> render_window_panel.add_renderer(renderer) <NEW_LINE> return True
Demonstrative application.
62599080aad79263cf430273
class GuaraniPresence(models.Model): <NEW_LINE> <INDENT> presence = models.BooleanField(_('Indigenous Presence')) <NEW_LINE> date = models.DateField(_('Date')) <NEW_LINE> source = models.CharField(_('Source'), max_length=512) <NEW_LINE> village = models.ForeignKey( IndigenousVillage, verbose_name=_('Village'), related_name='guarani_presence_annual_series') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> get_latest_by = 'date' <NEW_LINE> verbose_name = _('Indigenous Presence') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}: {}'.format(self.village.name, self.presence)
We have been asked to rename all Guarani Presence fields to Indigenous Presence. So, changed on the presentation - the backend stays the same
625990801f5feb6acb1646b3
class ParserState: <NEW_LINE> <INDENT> NORMAL = 1 <NEW_LINE> COMMA = 2 <NEW_LINE> STRING = 3 <NEW_LINE> STRING_ESCAPE = 4
A namespace for an enumeration.
6259908092d797404e3898b9
class AcornChildrenSource(BaseAcornSource): <NEW_LINE> <INDENT> def create_default(self, name, obj): <NEW_LINE> <INDENT> setattr(obj, name, []) <NEW_LINE> <DEDENT> def fromxml(self, name, obj, xml_el): <NEW_LINE> <INDENT> child_cls = self.meta['type'] <NEW_LINE> child_tag = child_cls.xml_tag <NEW_LINE> children_objs = [] <NEW_LINE> setattr(obj, name, children_objs) <NEW_LINE> for child in xml_el.iterfind(child_tag): <NEW_LINE> <INDENT> children_objs.append(child_cls.fromxml(child)) <NEW_LINE> <DEDENT> <DEDENT> def toxml(self, name, obj, xml_el): <NEW_LINE> <INDENT> for child in getattr(obj, name): <NEW_LINE> <INDENT> child.toxml(xml_el)
Load a series of objects from the direct children (children's children are ignored). .. code-block:: XML <person> <weapon type='sword'/> <weapon type='bow'/> <weapon type='dirk'/> </person> .. code-block:: python class Weapon(Acorn): ... class Person(Acorn): xml_tag = 'person' acorn_content = Acorn.parse_content({ ... 'weapons': {'type': Weapon, 'src': 'children'} }) person = Person.fromxml(...) print(person.weapons) [<Weapon object at 0x7fab52......>, <Weapon object at 0x7fab52......>, <Weapon object at 0x7fab52......>] TODO: write about recursion trick for children/child
62599080a8370b77170f1e8b
class Node: <NEW_LINE> <INDENT> def __init__(self, info): <NEW_LINE> <INDENT> self.info = info <NEW_LINE> <DEDENT> def visit(self, visitor): <NEW_LINE> <INDENT> return visitor(self) <NEW_LINE> <DEDENT> def toBB(self, Labellist, cBB): <NEW_LINE> <INDENT> raise NotImplementedError('%s' % self.__class__) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.info.__str__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "-->" + self.__str__() + "<--"
Base class for all nodes in AST. All methods raise exceptions to ensure proper derivation.
625990804527f215b58eb6fd
class Solution: <NEW_LINE> <INDENT> def lastPosition(self, nums, target): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> start, end = 0, len(nums) -1 <NEW_LINE> while(start + 1 < end): <NEW_LINE> <INDENT> mid = int( (start + end) / 2 ) <NEW_LINE> if nums[mid] == target: <NEW_LINE> <INDENT> start = mid <NEW_LINE> <DEDENT> elif nums[mid] < target: <NEW_LINE> <INDENT> start = mid <NEW_LINE> <DEDENT> elif nums[mid] > target: <NEW_LINE> <INDENT> end = mid <NEW_LINE> <DEDENT> <DEDENT> if nums[end] == target: <NEW_LINE> <INDENT> return end <NEW_LINE> <DEDENT> if nums[start] == target: <NEW_LINE> <INDENT> return start <NEW_LINE> <DEDENT> return -1
@param nums: An integer array sorted in ascending order @param target: An integer @return: An integer
62599080f548e778e596d04c
class TagasaurisUnauthorizedException(TagasaurisApiException): <NEW_LINE> <INDENT> pass
Not authorized to Tagasauris.
62599080656771135c48ad8d
class MyInt(type): <NEW_LINE> <INDENT> def __call__(cls, *args, **kwargs): <NEW_LINE> <INDENT> print("-- 내가 정의한 int 클래스 -- ", args) <NEW_LINE> return type.__call__(cls, *args, **kwargs)
커스텀 Int 클래스. __call__ 매직메서드는 객체가 초기화 될때 수행할 메서드임.
62599080e1aae11d1e7cf56f
class NASPool(Base): <NEW_LINE> <INDENT> __tablename__ = 'nas_pools' <NEW_LINE> __table_args__ = ( Comment('NAS IP pools'), Index('nas_pools_u_linkage', 'nasid', 'poolid', unique=True), Index('nas_pools_i_poolid', 'poolid'), { 'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8', 'info': { 'cap_menu': 'BASE_ADMIN', 'cap_read': 'NAS_LIST', 'cap_create': 'NAS_EDIT', 'cap_edit': 'NAS_EDIT', 'cap_delete': 'NAS_EDIT', 'menu_name': _('NAS IP Pools'), 'default_sort': ({'property': 'nasid', 'direction': 'ASC'},), 'grid_view': ('npid', 'nas', 'pool'), 'grid_hidden': ('npid',), 'form_view': ('nas', 'pool'), 'create_wizard': SimpleWizard(title=_('Add new NAS IP pool')) } }) <NEW_LINE> id = Column( 'npid', UInt32(), Sequence('nas_pools_npid_seq'), Comment('NAS IP pool ID'), primary_key=True, nullable=False, info={ 'header_string': _('ID') }) <NEW_LINE> nas_id = Column( 'nasid', UInt32(), ForeignKey('nas_def.nasid', name='nas_pools_fk_nasid', ondelete='CASCADE', onupdate='CASCADE'), Comment('Network access server ID'), nullable=False, info={ 'header_string': _('NAS'), 'column_flex': 1 }) <NEW_LINE> pool_id = Column( 'poolid', UInt32(), ForeignKey('ippool_def.poolid', name='nas_pools_fk_poolid', ondelete='CASCADE', onupdate='CASCADE'), Comment('IP address pool ID'), nullable=False, info={ 'header_string': _('Pool'), 'column_flex': 1 })
NAS IP Pools
62599080ad47b63b2c5a930b
class OrderItem(models.Model): <NEW_LINE> <INDENT> order = models.ForeignKey(Order, related_name='items') <NEW_LINE> product = models.ForeignKey('catalog.Product') <NEW_LINE> price = models.DecimalField(max_digits=9, decimal_places=2, help_text='Unit price of the product') <NEW_LINE> quantity = models.IntegerField() <NEW_LINE> taxes = models.DecimalField(max_digits=9, decimal_places=2) <NEW_LINE> sub_total = models.DecimalField(max_digits=9, decimal_places=2) <NEW_LINE> total = models.DecimalField(max_digits=9, decimal_places=2) <NEW_LINE> tax_rate = models.FloatField(default=0.0) <NEW_LINE> tax_method = models.CharField(max_length=2, choices=Tax.TAX_METHODS) <NEW_LINE> updated_on = models.DateTimeField(auto_now=True) <NEW_LINE> updated_by = models.CharField(max_length=100) <NEW_LINE> created_on = models.DateTimeField(auto_now_add=True) <NEW_LINE> created_by = models.CharField(max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'sales_order_item' <NEW_LINE> verbose_name_plural = 'Order Items'
Represents a purchase product
625990805fc7496912d48fc8
class AdaptorEthAdvFilterProfile(ManagedObject): <NEW_LINE> <INDENT> consts = AdaptorEthAdvFilterProfileConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = MoMeta("AdaptorEthAdvFilterProfile", "adaptorEthAdvFilterProfile", "eth-adv-filter", VersionMeta.Version151a, "InputOutput", 0x1f, [], ["admin", "ls-config-policy", "ls-network", "ls-server-policy"], [u'adaptorHostEthIfProfile'], [], ["Get", "Set"]) <NEW_LINE> prop_meta = { "admin_state": MoPropertyMeta("admin_state", "adminState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x2, None, None, None, [], []), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } <NEW_LINE> prop_map = { "adminState": "admin_state", "childAction": "child_action", "dn": "dn", "rn": "rn", "status": "status", } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.admin_state = None <NEW_LINE> self.child_action = None <NEW_LINE> self.status = None <NEW_LINE> ManagedObject.__init__(self, "AdaptorEthAdvFilterProfile", parent_mo_or_dn, **kwargs)
This is AdaptorEthAdvFilterProfile class.
62599080f9cc0f698b1c6029
class CASAuth(BaseAuth): <NEW_LINE> <INDENT> name = 'CAS' <NEW_LINE> login_inputs = ['username', 'password'] <NEW_LINE> logout_possible = True <NEW_LINE> def __init__(self, auth_server, login_path="/login", logout_path="/logout", validate_path="/validate"): <NEW_LINE> <INDENT> BaseAuth.__init__(self) <NEW_LINE> self.cas = PyCAS(auth_server, login_path=login_path, validate_path=validate_path, logout_path=logout_path) <NEW_LINE> <DEDENT> def request(self, request, user_obj, **kw): <NEW_LINE> <INDENT> ticket = request.args.get("ticket", "") <NEW_LINE> action = request.args.get("action", "") <NEW_LINE> logoutRequest = request.args.get("logoutRequest", []) <NEW_LINE> p = urlparse.urlparse(request.url) <NEW_LINE> url = urlparse.urlunparse((p.scheme, p.netloc, p.path, "", "", "")) <NEW_LINE> if user_obj and user_obj.valid: <NEW_LINE> <INDENT> return user_obj, True <NEW_LINE> <DEDENT> if not ticket and not "login" == action: <NEW_LINE> <INDENT> return user_obj, True <NEW_LINE> <DEDENT> if ticket: <NEW_LINE> <INDENT> valid, username = self.cas.validate_ticket(url, ticket) <NEW_LINE> if valid: <NEW_LINE> <INDENT> u = user.User(request, auth_username=username, auth_method=self.name) <NEW_LINE> u.valid = valid <NEW_LINE> u.create_or_update(True) <NEW_LINE> return u, True <NEW_LINE> <DEDENT> <DEDENT> request.http_redirect(self.cas.login_url(url)) <NEW_LINE> return user_obj, True <NEW_LINE> <DEDENT> def logout(self, request, user_obj, **kw): <NEW_LINE> <INDENT> if self.name and user_obj and user_obj.auth_method == self.name: <NEW_LINE> <INDENT> user_obj.valid = False <NEW_LINE> request.cfg.session_service.destroy_session(request, request.session) <NEW_LINE> p = urlparse.urlparse(request.url) <NEW_LINE> url = urlparse.urlunparse((p.scheme, p.netloc, p.path, "", "", "")) <NEW_LINE> request.http_redirect(self.cas.logout_url(url)) <NEW_LINE> <DEDENT> return user_obj, False
handle login from CAS
625990805fdd1c0f98e5fa3a
class CreateTemplateCommand(CreateModelCommand): <NEW_LINE> <INDENT> @property <NEW_LINE> def short_name(self): <NEW_LINE> <INDENT> return 'create-model-template' <NEW_LINE> <DEDENT> def add_args(self, parser): <NEW_LINE> <INDENT> parser.add_argument( 'template_name', help="Template name", type=str, ) <NEW_LINE> parser.add_argument( 'model_file', help="Model file", type=str, ) <NEW_LINE> parser.add_argument( '-f', '--force', help="Overwrite if present", action='store_true', ) <NEW_LINE> <DEDENT> async def exec(self, args): <NEW_LINE> <INDENT> loud = Loud(**self.config) <NEW_LINE> settings = self._load_model_json(args.model_file) <NEW_LINE> if args.force and loud.templates.exists(args.template_name): <NEW_LINE> <INDENT> loud.templates.delete(args.template_name) <NEW_LINE> <DEDENT> loud.templates.create( settings, args.template_name)
Create a new model template.
62599080099cdd3c63676157
class ReplStringifier( FreeVarStringifier, ListStringifier, LitNormalStringifier ): <NEW_LINE> <INDENT> pass
A stringifier for REPL output. This translates free variables into identifiers _a, _b, etc. and represents literals in the usual, human-readable, way.
62599080442bda511e95dab4
class ValidationError(ClientError): <NEW_LINE> <INDENT> pass
Base validation error.
625990808a349b6b43687d18