code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ArPyRetFunctor_Bool(ArRetFunctor_Bool,ArPyFunctor): <NEW_LINE> <INDENT> thisown = _swig_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> this = _AriaPy.new_ArPyRetFunctor_Bool(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def invokeR(self): <NEW_LINE> <INDENT> return _AriaPy.ArPyRetFunctor_Bool_invokeR(self) <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return _AriaPy.ArPyRetFunctor_Bool_getName(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _AriaPy.delete_ArPyRetFunctor_Bool <NEW_LINE> __del__ = lambda self : None;
Proxy of C++ ArPyRetFunctor_Bool class
6259903696565a6dacd2d82d
class ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'Name', 'type': 'str'}, 'display_name': {'key': 'DisplayName', 'type': 'str'}, 'description': {'key': 'Description', 'type': 'str'}, 'help_url': {'key': 'HelpUrl', 'type': 'str'}, 'is_hidden': {'key': 'IsHidden', 'type': 'bool'}, 'is_enabled_by_default': {'key': 'IsEnabledByDefault', 'type': 'bool'}, 'is_in_preview': {'key': 'IsInPreview', 'type': 'bool'}, 'supports_email_notifications': {'key': 'SupportsEmailNotifications', 'type': 'bool'}, } <NEW_LINE> def __init__(self, name=None, display_name=None, description=None, help_url=None, is_hidden=None, is_enabled_by_default=None, is_in_preview=None, supports_email_notifications=None): <NEW_LINE> <INDENT> super(ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions, self).__init__() <NEW_LINE> self.name = name <NEW_LINE> self.display_name = display_name <NEW_LINE> self.description = description <NEW_LINE> self.help_url = help_url <NEW_LINE> self.is_hidden = is_hidden <NEW_LINE> self.is_enabled_by_default = is_enabled_by_default <NEW_LINE> self.is_in_preview = is_in_preview <NEW_LINE> self.supports_email_notifications = supports_email_notifications
Static definitions of the ProactiveDetection configuration rule (same values for all components). :param name: The rule name :type name: str :param display_name: The rule name as it is displayed in UI :type display_name: str :param description: The rule description :type description: str :param help_url: URL which displays aditional info about the proactive detection rule :type help_url: str :param is_hidden: A flag indicating whether the rule is hidden (from the UI) :type is_hidden: bool :param is_enabled_by_default: A flag indicating whether the rule is enabled by default :type is_enabled_by_default: bool :param is_in_preview: A flag indicating whether the rule is in preview :type is_in_preview: bool :param supports_email_notifications: A flag indicating whether email notifications are supported for detections for this rule :type supports_email_notifications: bool
625990368c3a8732951f769b
class RosMsgInt64(RosSchema): <NEW_LINE> <INDENT> _valid_ros_msgtype = std_msgs.Int64 <NEW_LINE> _generated_ros_msgtype = std_msgs.Int64 <NEW_LINE> data = RosInt64()
RosMsgInt64 handles serialization from std_msgs.Int64 to python dict and deserialization from python dict to std_msgs.Int64 You should use strict Schema to trigger exceptions when trying to manipulate an unexpected type. >>> schema = RosMsgInt64(strict=True) >>> rosmsgFortytwo = std_msgs.Int64(data=42) >>> unmarshalledFortytwo, errors = schema.load(rosmsgFortytwo) >>> marshmallow.pprint(unmarshalledFortytwo) if not errors else print("ERRORS {0}".format(errors)) {'data': 42} >>> value, errors = schema.dump(unmarshalledFortytwo) >>> type(value) if not errors else print("ERRORS {0}".format(errors)) <class 'std_msgs.msg._Int64.Int64'> >>> print(value) if not errors else print("ERRORS {0}".format(errors)) data: 42 Invalidate message would report: >>> rosmsgFortytwo = std_msgs.UInt8(data=42) >>> unmarshalledFortytwo, errors = schema.load(rosmsgFortytwo) Traceback (most recent call last): ... PyrosSchemasValidationError: data type should be <class 'std_msgs.msg._Int64.Int64'> Note since PEP https://www.python.org/dev/peps/pep-0237/ (python 2.4) int and long should mean the same thing for python Load is the inverse of dump (getting only data member): >>> import random >>> randomRosInt = std_msgs.Int64(random.choice([4, 2, 1])) >>> schema.dump(schema.load(randomRosInt).data).data == randomRosInt True
6259903666673b3332c31537
class Validator(GenericValidator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.regexp = re.compile(r'^\d{9,10}$') <NEW_LINE> <DEDENT> def validate(self, vat_number): <NEW_LINE> <INDENT> if super(Validator, self).validate(vat_number) is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> vat_number = str(vat_number) <NEW_LINE> if (len(vat_number)==9): <NEW_LINE> <INDENT> checksum = int(vat_number[8]) <NEW_LINE> a1 = self.sum_weights(list(range(1,9)), vat_number[:8]) <NEW_LINE> r1 = a1 % 11 <NEW_LINE> if r1 == 10: <NEW_LINE> <INDENT> a2 = self.sum_weights(list(range(3,11)), vat_number[:8]) <NEW_LINE> r2 = a2 % 11 <NEW_LINE> if r2 == 10: <NEW_LINE> <INDENT> r = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = r2 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> r = r1 <NEW_LINE> <DEDENT> return checksum == r <NEW_LINE> <DEDENT> checksum = int(vat_number[9]) <NEW_LINE> weights = [2, 4, 8, 5, 10, 9, 7, 3, 6] <NEW_LINE> a1 = self.sum_weights(weights, vat_number[:9]) <NEW_LINE> r1 = a1 % 11 <NEW_LINE> if r1 == 10: <NEW_LINE> <INDENT> r = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = r1 <NEW_LINE> <DEDENT> if checksum == r: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> checksum = int(vat_number[9]) <NEW_LINE> weights = [21, 19, 17, 13, 11, 9, 7, 3, 1] <NEW_LINE> a1 = self.sum_weights(weights, vat_number[:9]) <NEW_LINE> r = a1 % 10 <NEW_LINE> if checksum == r: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> checksum = int(vat_number[9]) <NEW_LINE> weights = [4, 3, 2, 7, 6, 5, 4, 3, 2] <NEW_LINE> a1 = self.sum_weights(weights, vat_number[:9]) <NEW_LINE> r1 = 11 - a1 % 11 <NEW_LINE> if r1 == 11: <NEW_LINE> <INDENT> r = 0 <NEW_LINE> <DEDENT> elif r1 == 10: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = r1 <NEW_LINE> <DEDENT> if checksum == r: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
For rules see /docs/VIES-VAT Validation Routines-v15.0.doc
625990368c3a8732951f769c
class TestExtLinkBugs(TestCase): <NEW_LINE> <INDENT> def test_issue_212(self): <NEW_LINE> <INDENT> def closer(x): <NEW_LINE> <INDENT> def w(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if x: <NEW_LINE> <INDENT> x.close() <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return w <NEW_LINE> <DEDENT> orig_name = self.mktemp() <NEW_LINE> new_name = self.mktemp() <NEW_LINE> f = File(orig_name, 'w') <NEW_LINE> self.addCleanup(closer(f)) <NEW_LINE> f.create_group('a') <NEW_LINE> f.close() <NEW_LINE> g = File(new_name, 'w') <NEW_LINE> self.addCleanup(closer(g)) <NEW_LINE> g['link'] = ExternalLink(orig_name, '/') <NEW_LINE> g.close() <NEW_LINE> h = File(new_name, 'r') <NEW_LINE> self.addCleanup(closer(h)) <NEW_LINE> self.assertIsInstance(h['link']['a'], Group)
Bugs: Specific regressions for external links
62599036d164cc61758220b7
class Apcer(Metric): <NEW_LINE> <INDENT> def __init__(self, name, threshold=None): <NEW_LINE> <INDENT> super(Apcer, self).__init__(name, 'APCER') <NEW_LINE> self.threshold = threshold <NEW_LINE> self.threshold_needed = True <NEW_LINE> <DEDENT> def compute(self, y_score, y_true): <NEW_LINE> <INDENT> attack_ids = np.unique(y_true) <NEW_LINE> attack_ids = np.trim_zeros(attack_ids) <NEW_LINE> result_attacks = [] <NEW_LINE> for ind_attack in attack_ids: <NEW_LINE> <INDENT> array_attacks = y_score[y_true == ind_attack] <NEW_LINE> result = array_attacks[array_attacks >= self.threshold].shape[0] / float(len(array_attacks)) <NEW_LINE> result_attacks.append(result) <NEW_LINE> <DEDENT> return 100*max(result_attacks), self.threshold <NEW_LINE> <DEDENT> def set_threshold(self, threshold): <NEW_LINE> <INDENT> self.threshold = threshold
Attack Presentation Classification Error Rate: proportion of attack presentations incorrectly classified as bona fide presentations
62599036287bf620b6272d2d
class Actor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc1_units=128, fc2_units=64): <NEW_LINE> <INDENT> super(Actor, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc1_units) <NEW_LINE> self.bn1 = nn.BatchNorm1d(state_size) <NEW_LINE> self.fc2 = nn.Linear(fc1_units, fc2_units) <NEW_LINE> self.fc3 = nn.Linear(fc2_units, action_size) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.fc1.weight.data.uniform_(*hidden_init(self.fc1)) <NEW_LINE> self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) <NEW_LINE> self.fc3.weight.data.uniform_(-3e-3, 3e-3) <NEW_LINE> <DEDENT> def forward(self, state): <NEW_LINE> <INDENT> state = self.bn1(state) <NEW_LINE> x = F.relu(self.fc1(state)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> x = self.fc3(x) <NEW_LINE> return F.tanh(x)
Actor (Policy) Model.
6259903676d4e153a661db13
class CoordTwoDim(BaseObject): <NEW_LINE> <INDENT> description = 'A two-dimensional coordinate (a pair of reals).' <NEW_LINE> default_value = [0.0, 0.0] <NEW_LINE> SCHEMA = { 'type': 'list', 'len': 2, 'items': Real.SCHEMA, }
2D coordinate class.
62599036596a897236128de0
class Command(object): <NEW_LINE> <INDENT> def __init__(self, manager): <NEW_LINE> <INDENT> self.manager = manager <NEW_LINE> <DEDENT> def get_usage(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def get_help(self): <NEW_LINE> <INDENT> return self.__class__.__doc__.strip() <NEW_LINE> <DEDENT> def run(self, args): <NEW_LINE> <INDENT> raise CommandError("Command not implemented.")
Base class for a cloud command.
625990360a366e3fb87ddb2a
class CurveFit(AnalysisBase): <NEW_LINE> <INDENT> def __init__(self, options): <NEW_LINE> <INDENT> super().__init__(options) <NEW_LINE> self.residual = None <NEW_LINE> self.poly = None <NEW_LINE> <DEDENT> def _xaxis(self): <NEW_LINE> <INDENT> if 'xaxis' in self.options: <NEW_LINE> <INDENT> xaxis = self.options['xaxis'] <NEW_LINE> if not isinstance(self.data, list) or len(self.data) != len(xaxis): <NEW_LINE> <INDENT> raise ValueError("'xaxis' must have the same length as data") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> xaxis = np.linspace(0, len(self.data)-1, len(self.data), dtype=int) <NEW_LINE> <DEDENT> return xaxis <NEW_LINE> <DEDENT> def _quality(self): <NEW_LINE> <INDENT> if 'optimal' not in self.options: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> optimal = self.options['optimal'] <NEW_LINE> if not isinstance(optimal, list): <NEW_LINE> <INDENT> raise TypeError("Optimal must be a list") <NEW_LINE> <DEDENT> xaxis = self._xaxis() <NEW_LINE> if len(xaxis) != len(optimal): <NEW_LINE> <INDENT> raise ValueError("'xaxis' and optimal must have same length") <NEW_LINE> <DEDENT> degree = self.options['degree'] <NEW_LINE> optp = np.polyfit(xaxis, optimal, degree) <NEW_LINE> optr = np.polyval(optp, xaxis) <NEW_LINE> residual = self.results['residual'] <NEW_LINE> return float(np.sum(((optr-residual)**2)/np.mean(self.data))) <NEW_LINE> <DEDENT> def _run(self): <NEW_LINE> <INDENT> if 'degree' not in self.options: <NEW_LINE> <INDENT> raise RuntimeError("Curve fit needs 'degree' options set") <NEW_LINE> <DEDENT> degree = self.options['degree'] <NEW_LINE> if not isinstance(degree, int) or degree < 1: <NEW_LINE> <INDENT> raise ValueError("degree must be integer > 1") <NEW_LINE> <DEDENT> xaxis = self._xaxis() <NEW_LINE> poly = np.polyfit(xaxis, self.data, degree) <NEW_LINE> residual = np.polyval(poly, xaxis) <NEW_LINE> self.results['poly'] = poly <NEW_LINE> self.results['residual'] = residual <NEW_LINE> self.results['quality'] = self._quality() <NEW_LINE> <DEDENT> def get_value(self, key): <NEW_LINE> <INDENT> if key == 'quality' and self.done: <NEW_LINE> <INDENT> self.results['quality'] = self._quality() <NEW_LINE> <DEDENT> return super().get_value(key) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "CurveFit" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> string = "[ " + repr(self.poly) + ", " + repr(self.residual) + " ]" <NEW_LINE> return string
Curve Fit
62599036cad5886f8bdc591d
class ProjManAPIView(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> response = {'url': request.build_absolute_uri('projects')} <NEW_LINE> return Response(response)
List ProjMan API endpoints
62599036dc8b845886d546f7
class DirectoryClient(): <NEW_LINE> <INDENT> def __init__(self, address, port): <NEW_LINE> <INDENT> self._address = address <NEW_LINE> self._port = port <NEW_LINE> <DEDENT> def register(self, address, port): <NEW_LINE> <INDENT> context = zmq.Context() <NEW_LINE> socket = context.socket(zmq.REQ) <NEW_LINE> socket.connect('tcp://{}:{}'.format(self._address, self._port)) <NEW_LINE> socket.send_string('register {} {}'.format(address, port)) <NEW_LINE> socket.recv_string() <NEW_LINE> socket.close() <NEW_LINE> <DEDENT> def list(self): <NEW_LINE> <INDENT> context = zmq.Context() <NEW_LINE> socket = context.socket(zmq.REQ) <NEW_LINE> socket.connect('tcp://{}:{}'.format(self._address, self._port)) <NEW_LINE> socket.send_string('list') <NEW_LINE> string = socket.recv_string() <NEW_LINE> socket.close() <NEW_LINE> return dict(json.loads(string))
Directory Client Class
6259903650485f2cf55dc0c3
@six.add_metaclass(_template_meta(b"Can not found item with matched id", "找不到数据库对象")) <NEW_LINE> class IDError(CGTeamWorkException): <NEW_LINE> <INDENT> pass
Indicate can't specify shot id on cgtw.
625990361f5feb6acb163d37
class HtmlPrettifyMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if not settings.PRETTIFY_HTML: <NEW_LINE> <INDENT> raise MiddlewareNotUsed <NEW_LINE> <DEDENT> <DEDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> if response['Content-Type'].split(';', 1)[0] == 'text/html': <NEW_LINE> <INDENT> response.content = BeautifulSoup(response.content).prettify() <NEW_LINE> <DEDENT> return response
HTML code prettification middleware.
62599036d99f1b3c44d067e9
class PhysicalHost(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> hostname = models.CharField(max_length=256, null=False) <NEW_LINE> service = models.TextField(null=True) <NEW_LINE> machine_room = models.TextField(null=True) <NEW_LINE> cabinet = models.TextField(null=True) <NEW_LINE> sn = models.CharField(max_length=256) <NEW_LINE> datacenter = models.ForeignKey(to=DataCenter, on_delete=models.CASCADE) <NEW_LINE> hardwareinfo = models.ForeignKey(to=HardwareInfo, on_delete=models.CASCADE) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'physicalhost' <NEW_LINE> permissions = ( ("修改物理主机", "Can modify all physicalhost"), ("删除物理主机", "Can add all physicalhost"), ("修改指定数据中心下的物理主机", "Can modify all physicalhost by the datacenter"), ("删除指定数据中心下的物理主机", "Can modify all physicalhost by the datacenter"), ) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.hostname
hostname 主机名 purchase 购买时间 service 维保时长 machine_room 机房 cabinet 机柜号 sn 主板sn号 主机唯一标示 datacenter 关联datacenter
62599036287bf620b6272d2f
class open(): <NEW_LINE> <INDENT> async def request_v4(self, record): <NEW_LINE> <INDENT> record.tape['path'] = record.b.device.decode() <NEW_LINE> if(record.b.mode == const.NDMP_TAPE_READ_MODE): <NEW_LINE> <INDENT> mode = os.O_RDONLY|os.O_NONBLOCK <NEW_LINE> <DEDENT> elif(record.b.mode in [const.NDMP_TAPE_WRITE_MODE, const.NDMP_TAPE_RAW_MODE, const.NDMP_TAPE_RAW2_MODE]): <NEW_LINE> <INDENT> mode = os.O_WRONLY|os.O_NONBLOCK <NEW_LINE> <DEDENT> record.tape['fd'] = os.open(record.tape['path'], mode, 0) <NEW_LINE> record.tape['opened'] = True <NEW_LINE> stdlog.info('TAPE> device ' + record.tape['path'] + ' opened') <NEW_LINE> <DEDENT> async def reply_v4(self, record): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> request_v3 = request_v4 <NEW_LINE> reply_v3 = reply_v4
This request opens the tape device in the specified mode. This operation is required before any other tape requests can be executed.
625990363eb6a72ae038b7ad
class Icontentview(form.Schema, IImageScaleTraversable): <NEW_LINE> <INDENT> pass
Description of the Example Type
6259903673bcbd0ca4bcb3cd
@python_2_unicode_compatible <NEW_LINE> class Post(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=70) <NEW_LINE> body = models.TextField() <NEW_LINE> created_time = models.DateTimeField() <NEW_LINE> modified_time = models.DateTimeField() <NEW_LINE> excerpt = models.CharField(max_length=200, blank=True) <NEW_LINE> category = models.ForeignKey(Category) <NEW_LINE> tags = models.ManyToManyField(Tag, blank=True) <NEW_LINE> author = models.ForeignKey(User) <NEW_LINE> view = models.PositiveIntegerField(default=0) <NEW_LINE> def increase_views(self): <NEW_LINE> <INDENT> self.view += 1 <NEW_LINE> self.save(update_fields=['view']) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('blog:detail', kwargs={'pk': self.pk}) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['-created_time'] <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.excerpt: <NEW_LINE> <INDENT> md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) <NEW_LINE> self.excerpt = strip_tags(md.convert(self.body))[:54] <NEW_LINE> <DEDENT> super(Post, self).save(*args, **kwargs)
文章的数据库表稍微复杂一点,主要是涉及的字段更多。
62599036ac7a0e7691f7362e
class VOCSemanticSegmentationDataset(VOCSemanticSegmentationDataset): <NEW_LINE> <INDENT> def __init__(self, data_dir='auto', split='train'): <NEW_LINE> <INDENT> if split not in ['train', 'trainval', 'val', 'test']: <NEW_LINE> <INDENT> raise ValueError( 'please pick split from \'train\', \'trainval\', \'val\', ' '\'test\'') <NEW_LINE> <DEDENT> if data_dir == 'auto': <NEW_LINE> <INDENT> data_dir = voc_utils.get_voc('2012', split) <NEW_LINE> <DEDENT> id_list_file = os.path.join( data_dir, 'ImageSets/Segmentation/{0}.txt'.format(split)) <NEW_LINE> self.ids = [id_.strip() for id_ in open(id_list_file)] <NEW_LINE> self.data_dir = data_dir
Dataset class for the semantic segmantion task of PASCAL `VOC2012`_. The class name of the label :math:`l` is :math:`l` th element of :obj:`chainercv.datasets.voc_semantic_segmentation_label_names`. .. _`VOC2012`: http://host.robots.ox.ac.uk/pascal/VOC/voc2012/ Args: data_dir (string): Path to the root of the training data. If this is :obj:`auto`, this class will automatically download data for you under :obj:`$CHAINER_DATASET_ROOT/pfnet/chainercv/voc`. split ({'train', 'val', 'trainval'}): Select a split of the dataset.
6259903691af0d3eaad3af76
class CrocodocLoaderService(object): <NEW_LINE> <INDENT> user = None <NEW_LINE> reviewdocument = None <NEW_LINE> service = None <NEW_LINE> @property <NEW_LINE> def crocodoc_uuid_recorded(self): <NEW_LINE> <INDENT> return self.reviewdocument.crocodoc_uuid not in [None, ''] <NEW_LINE> <DEDENT> def __init__(self, user, reviewdocument): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.reviewdocument = reviewdocument <NEW_LINE> self.ensure_reviewer() <NEW_LINE> upload_immediately = False <NEW_LINE> if self.crocodoc_uuid_recorded is False: <NEW_LINE> <INDENT> upload_immediately = True <NEW_LINE> <DEDENT> self.reviewdocument.ensure_file() <NEW_LINE> self.service = CrocoDocConnectService(document_object=self.reviewdocument.document, app_label='attachment', field_name='executed_file', upload_immediately=upload_immediately, reviewer=self.reviewdocument.reviewer) <NEW_LINE> self.ensure_local_reference_crocodoc_uuid() <NEW_LINE> <DEDENT> def ensure_local_reference_crocodoc_uuid(self): <NEW_LINE> <INDENT> self.ensure_reset_copied_reviewdocument() <NEW_LINE> if self.service.is_new is True or self.crocodoc_uuid_recorded is False: <NEW_LINE> <INDENT> if self.service.obj.uuid: <NEW_LINE> <INDENT> self.reviewdocument.crocodoc_uuid = self.service.obj.uuid <NEW_LINE> self.reviewdocument.save(update_fields=['crocodoc_uuid']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error('Crocodoc Service did not provide a uuid for the reviewdocument: %s for revision: %s on item: %s' % (self.reviewdocument, self.reviewdocument.document, self.reviewdocument.document.item.slug)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def ensure_reset_copied_reviewdocument(self): <NEW_LINE> <INDENT> if self.reviewdocument.document.primary_reviewdocument and self.reviewdocument.document.primary_reviewdocument.crocodoc_uuid == self.service.obj.uuid: <NEW_LINE> <INDENT> crocodoc_object = self.service.obj <NEW_LINE> crocodoc_object.crocodoc_uuid = None <NEW_LINE> <DEDENT> <DEDENT> def ensure_reviewer(self): <NEW_LINE> <INDENT> if self.reviewdocument.reviewer is None: <NEW_LINE> <INDENT> self.reviewdocument.save() <NEW_LINE> <DEDENT> <DEDENT> def ensure_local_file(self): <NEW_LINE> <INDENT> if self.reviewdocument.ensure_file(): <NEW_LINE> <INDENT> self.service.generate() <NEW_LINE> <DEDENT> <DEDENT> def process(self): <NEW_LINE> <INDENT> CROCODOC_PARAMS = { "user": { "name": self.user.get_full_name(), "id": self.user.pk }, "sidebar": 'auto', "editable": self.reviewdocument.is_current, "admin": False, "downloadable": True, "copyprotected": False, "demo": False, } <NEW_LINE> return { 'crocodoc': self.service.obj.crocodoc_service, 'crocodoc_view_url': self.service.obj.crocodoc_service.view_url(**CROCODOC_PARAMS), 'CROCODOC_PARAMS': CROCODOC_PARAMS, }
Class to provide kwargs used to populate html template with params also used to provide url
625990364e696a045264e6c5
class PrivacySettingsForm(SiteSettingsForm): <NEW_LINE> <INDENT> terms_of_service_url = forms.URLField( label=_('Terms of service URL'), required=False, help_text=_('URL to your terms of service. This will be displayed on ' 'the My Account page and during login and registration.'), widget=forms.widgets.URLInput(attrs={ 'size': 80, })) <NEW_LINE> privacy_policy_url = forms.URLField( label=_('Privacy policy URL'), required=False, help_text=_('URL to your privacy policy. This will be displayed on ' 'the My Account page and during login and registration.'), widget=forms.widgets.URLInput(attrs={ 'size': 80, })) <NEW_LINE> privacy_info_html = forms.CharField( label=_('Privacy information'), required=False, help_text=_('A description of the privacy guarantees for users on ' 'this server. This will be displayed on the My Account ' '-> Your Privacy page. HTML is allowed.'), widget=forms.widgets.Textarea(attrs={ 'cols': 60, })) <NEW_LINE> privacy_enable_user_consent = forms.BooleanField( label=_('Require consent for usage of personal information'), required=False, help_text=_('Require consent from users when using their personally ' 'identifiable information (usernames, e-mail addresses, ' 'etc.) for when talking to third-party services, like ' 'Gravatar. This is required for EU GDPR compliance.')) <NEW_LINE> def save(self): <NEW_LINE> <INDENT> self.siteconfig.set(AvatarServiceRegistry.ENABLE_CONSENT_CHECKS, self.cleaned_data['privacy_enable_user_consent']) <NEW_LINE> super(PrivacySettingsForm, self).save() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> title = _('User Privacy Settings') <NEW_LINE> fieldsets = ( { 'classes': ('wide',), 'fields': ( 'terms_of_service_url', 'privacy_policy_url', 'privacy_info_html', 'privacy_enable_user_consent', ), }, )
Site-wide user privacy settings for Review Board.
625990368c3a8732951f769f
class IsActive(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> return request.user.is_active
Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute.
625990361d351010ab8f4c61
class WebsocketToPubSubEmitter: <NEW_LINE> <INDENT> def __init__(self, ws_url_arg, project_id_arg, topic_arg, seconds_arg=None): <NEW_LINE> <INDENT> self.publisher = PubSubPublisher(project_id_arg, topic_arg) <NEW_LINE> self.url = ws_url_arg <NEW_LINE> self.seconds = seconds_arg <NEW_LINE> self.ws = None <NEW_LINE> self.run() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> websocket.enableTrace(True) <NEW_LINE> self.ws = websocket.WebSocketApp(self.url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close) <NEW_LINE> self.ws.counter = 0 <NEW_LINE> self.ws.on_open = self.on_open <NEW_LINE> log.log_info("{} - Starting listening on: {} Messages will be published to: {}".format( self.__class__.__name__, self.url, str(self.publisher))) <NEW_LINE> self.ws.run_forever() <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> self.publisher.publish_message(message) <NEW_LINE> log.log_debug("{} - Acquired message: {}".format(self.__class__.__name__, message)) <NEW_LINE> self.ws.counter += 1 <NEW_LINE> <DEDENT> def on_error(self, error): <NEW_LINE> <INDENT> print(error) <NEW_LINE> <DEDENT> def on_close(self): <NEW_LINE> <INDENT> log.log_info("{} - Websocket closed".format(self.__class__.__name__)) <NEW_LINE> <DEDENT> def on_open(self): <NEW_LINE> <INDENT> def run(*args): <NEW_LINE> <INDENT> if self.seconds: <NEW_LINE> <INDENT> log.log_info("{} - Running for {} seconds".format(self.__class__.__name__, self.seconds)) <NEW_LINE> sleep(self.seconds) <NEW_LINE> self.ws.close() <NEW_LINE> log.log_info("{} - Published {} messages in {} seconds. That is {:.2f} mps!".format( self.__class__.__name__, self.ws.counter, self.seconds, self.ws.counter/self.seconds)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.log_info("{} - Running forever".format(self.__class__.__name__, self.seconds)) <NEW_LINE> while True: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> thread.start_new_thread(run, ()) <NEW_LINE> <DEDENT> def return_count(self): <NEW_LINE> <INDENT> return self.ws.counter
Class responsible for reading data from any Websocket (ws_url_arg) and sending it to pub/sub topic using PubSubPublisher class.
625990368a43f66fc4bf32d2
class CuratedExhibitAdmin(admin.StackedInline): <NEW_LINE> <INDENT> model = CuratedExhibit <NEW_LINE> raw_id_fields = ['exhibit'] <NEW_LINE> fields = [ 'exhibit', 'custom_title', 'thumbnail', 'publish_date' ] <NEW_LINE> extra = 0
Admin for a CuratedExhibit
625990368e05c05ec3f6f6fe
class Last: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def exec_num(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exec_np(data, ignore_nodata=True, dimension=0): <NEW_LINE> <INDENT> if is_empty(data): <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> n_dims = len(data.shape) <NEW_LINE> if ignore_nodata: <NEW_LINE> <INDENT> data = np.flip(data, axis=dimension) <NEW_LINE> last_elem = first(data, ignore_nodata=ignore_nodata, dimension=dimension) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> idx_last = create_slices(-1, axis=dimension, n_axes=n_dims) <NEW_LINE> last_elem = data[idx_last] <NEW_LINE> <DEDENT> return last_elem <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exec_xar(data, ignore_nodata=True, dimension=None): <NEW_LINE> <INDENT> if len(data) == 0: <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> if dimension is None: <NEW_LINE> <INDENT> dimension = 0 <NEW_LINE> <DEDENT> if type(dimension) == str: <NEW_LINE> <INDENT> dimension = dimension <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dimension = data.dims[dimension] <NEW_LINE> <DEDENT> data_dim = data.transpose(dimension, ...) <NEW_LINE> data_last = data_dim[-1] <NEW_LINE> if ignore_nodata: <NEW_LINE> <INDENT> i = len(data_dim) - 1 <NEW_LINE> while (data_last.fillna(999) != data_last).any() and i >= 0: <NEW_LINE> <INDENT> data_last = data_last.fillna(data_dim[i]) <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> <DEDENT> return data_last <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exec_da(): <NEW_LINE> <INDENT> pass
Class implementing all 'last' processes.
6259903621bff66bcd723dad
class SafariExtensions(BaseModel): <NEW_LINE> <INDENT> uid = BigIntegerField(help_text="The local user that owns the extension") <NEW_LINE> name = TextField(help_text="Extension display name") <NEW_LINE> identifier = TextField(help_text="Extension identifier") <NEW_LINE> version = TextField(help_text="Extension long version") <NEW_LINE> sdk = TextField(help_text="Bundle SDK used to compile extension") <NEW_LINE> update_url = TextField(help_text="Extension-supplied update URI") <NEW_LINE> author = TextField(help_text="Optional extension author") <NEW_LINE> developer_id = TextField(help_text="Optional developer identifier") <NEW_LINE> description = TextField(help_text="Optional extension description text") <NEW_LINE> path = TextField(help_text="Path to extension XAR bundle") <NEW_LINE> safari_extensions = ForeignKeyField(MacOS_Users, backref='uid') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> table_name = "safari_extensions"
Safari browser extension details for all users. Examples: select count(*) from users JOIN safari_extensions using (uid)
62599036b57a9660fecd2bc2
class SetUpCaches(object): <NEW_LINE> <INDENT> def __init__(self, client_root): <NEW_LINE> <INDENT> self.canonical_path = CanonicalPath() <NEW_LINE> self.includepath_map = RelpathMapToIndex() <NEW_LINE> self.directory_map = DirectoryMapToIndex() <NEW_LINE> self.realpath_map = CanonicalMapToIndex(self.canonical_path.Canonicalize) <NEW_LINE> self.dirname_cache = DirnameCache(self.includepath_map, self.directory_map, self.realpath_map) <NEW_LINE> self.compiler_defaults = compiler_defaults.CompilerDefaults( self.canonical_path.Canonicalize, client_root) <NEW_LINE> self.systemdir_prefix_cache = SystemdirPrefixCache( self.compiler_defaults.system_dirs_default_all) <NEW_LINE> self.simple_build_stat = SimpleBuildStat() <NEW_LINE> self.build_stat_cache = BuildStatCache(self.includepath_map, self.directory_map, self.realpath_map) <NEW_LINE> self.IsIncludepathIndex = (lambda x: isinstance(x, int) and 0 < x < self.includepath_map.Length()) <NEW_LINE> self.IsSearchdirIndex = (lambda x: isinstance(x, int) and 0 < x < self.directory_map.Length()) <NEW_LINE> self.IsCurrdirIndex = (lambda x: isinstance(x, int) and 0 < x < self.directory_map.Length()) <NEW_LINE> self.IsFilepathPair = (lambda x: isinstance(x, tuple) and len(x) == 2 and self.IsSearchdirIndex(x[0]) and self.IsIncludepathIndex(x[1])) <NEW_LINE> self.IsRealpathIndex = (lambda x: isinstance(x, int) and 0 < x < self.realpath_map.Length())
Erect the edifice of caches. Instance variables: includepath_map: RelpathMapToIndex directory_map: DirectoryMapToIndex realpath_map: CanonicalMapToIndex canonical_path: CanonicalPath build_stat_cache: BuildStatCache dirname_cache: DirnameCache simple_build_stat: SimpleBuildStat client_root: a path such as /dev/shm/tmpX.include_server-X-1 (used during default system dir determination) IsFilepathIndex: test for filepath index IsDirectoryIndex: test for director index IsRealpathIndex: test for realpath index IsFilepathPair: test for filepath pair
62599036287bf620b6272d30
class PositionalArgument(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> raise NotImplementedError("Please use the parameterized constructor.") <NEW_LINE> <DEDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name
A positional argument definition (needed when registering a command handler).
62599036507cdc57c63a5ee1
class Station(BaseModel): <NEW_LINE> <INDENT> id_station = PrimaryKeyField() <NEW_LINE> station_number = IntegerField() <NEW_LINE> station_name = CharField(255) <NEW_LINE> contract_name = CharField(255) <NEW_LINE> address = CharField(255) <NEW_LINE> banking = BooleanField() <NEW_LINE> bonus = BooleanField() <NEW_LINE> status = BooleanField() <NEW_LINE> operational_bike_stands = IntegerField() <NEW_LINE> available_bike_stands = IntegerField() <NEW_LINE> available_bikes = IntegerField() <NEW_LINE> last_update = BigIntegerField() <NEW_LINE> latitude = FloatField() <NEW_LINE> longitude = FloatField() <NEW_LINE> city_name = CharField(255) <NEW_LINE> country_code = CharField(255)
Represents the Station SQL table
625990363eb6a72ae038b7af
class VerifiedHTTPSConnection(HTTPSConnection): <NEW_LINE> <INDENT> cert_reqs = None <NEW_LINE> ca_certs = None <NEW_LINE> ssl_version = None <NEW_LINE> assert_fingerprint = None <NEW_LINE> def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None): <NEW_LINE> <INDENT> self.key_file = key_file <NEW_LINE> self.cert_file = cert_file <NEW_LINE> self.cert_reqs = cert_reqs <NEW_LINE> self.ca_certs = ca_certs <NEW_LINE> self.assert_hostname = assert_hostname <NEW_LINE> self.assert_fingerprint = assert_fingerprint <NEW_LINE> <DEDENT> @asyncio.coroutine <NEW_LINE> def connect(self): <NEW_LINE> <INDENT> resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs) <NEW_LINE> resolved_ssl_version = resolve_ssl_version(self.ssl_version) <NEW_LINE> is_time_off = datetime.date.today() < RECENT_DATE <NEW_LINE> if is_time_off: <NEW_LINE> <INDENT> warnings.warn(( 'System time is way off (before {0}). This will probably ' 'lead to SSL verification errors').format(RECENT_DATE), SystemTimeWarning ) <NEW_LINE> <DEDENT> server_hostname = self._tunnel_host or self.host <NEW_LINE> self._context = create_context(self.key_file, self.cert_file, cert_reqs=resolved_cert_reqs, ca_certs=self.ca_certs, server_hostname=server_hostname, ssl_version=resolved_ssl_version) <NEW_LINE> yield from super(VerifiedHTTPSConnection, self).connect() <NEW_LINE> if self.assert_fingerprint: <NEW_LINE> <INDENT> assert_fingerprint(self.notSock.peercert(binary_form=True), self.assert_fingerprint) <NEW_LINE> <DEDENT> elif resolved_cert_reqs != ssl.CERT_NONE and self.assert_hostname is not False: <NEW_LINE> <INDENT> match_hostname(self.notSock.peercert(), self.assert_hostname or server_hostname) <NEW_LINE> <DEDENT> self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or self.assert_fingerprint is not None)
Based on httplib.HTTPSConnection but wraps the socket with SSL certification.
625990366e29344779b01799
class SearchSubscription(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(UserProxy, related_name='search_subscriptions', help_text='The user who subscribed to the search.') <NEW_LINE> dataset = models.ForeignKey(Dataset, related_name='search_subscriptions', null=True, default=None, help_text='The dataset to be searched or null if all are to be searched.') <NEW_LINE> category = models.ForeignKey(Category, related_name='search_subscriptions', null=True, default=None, help_text='A category to be searched or null if all are to be searched.') <NEW_LINE> query = models.CharField(max_length=256, help_text='The search query to executed.') <NEW_LINE> query_url = models.CharField(max_length=256, help_text='Query encoded for URL.') <NEW_LINE> query_human = models.TextField( help_text='Human-readable description of the query being run.') <NEW_LINE> last_run = models.DateTimeField(auto_now=True, help_text='The last time this search this was run.') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'panda' <NEW_LINE> verbose_name_plural = 'SearchSubscription' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> if self.dataset: <NEW_LINE> <INDENT> return '%s is searching for %s in %s' % (self.user, self.query, self.dataset) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '%s is searching for %s in all datasets' % (self.user, self.query)
A log of a user search.
62599036596a897236128de4
class SimpleTokenizer(TokenizerBase): <NEW_LINE> <INDENT> def __init__(self, strip_chars=None, index=None, ): <NEW_LINE> <INDENT> super(SimpleTokenizer, self).__init__(index=index) <NEW_LINE> if strip_chars is not None: <NEW_LINE> <INDENT> self.strip_chars = strip_chars <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.strip_chars = "".join(set(DEFAULT_STRIP_CHARS + DEFAULT_SPLIT_CHARS)) <NEW_LINE> <DEDENT> <DEDENT> def tokenize(self, text): <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> for tok in text.split(): <NEW_LINE> <INDENT> tok = tok.strip(self.strip_chars) <NEW_LINE> if tok: <NEW_LINE> <INDENT> tok = self.index.token_to_id(tok) <NEW_LINE> tokens.append(tok) <NEW_LINE> <DEDENT> <DEDENT> return tokens
It will split a text on any white-char (like python's str.split()) and strip any chars from beginning and end of tokens contained in strip_chars.
6259903663f4b57ef0086617
class Predecessor(object): <NEW_LINE> <INDENT> def __init__(self, props=None, base_obj=None): <NEW_LINE> <INDENT> self._base = None <NEW_LINE> if base_obj is not None: <NEW_LINE> <INDENT> self._base = base_obj <NEW_LINE> <DEDENT> self._in_critical_path = Boolean() <NEW_LINE> self._invalid = Boolean() <NEW_LINE> self._lag = TypedObject(Duration) <NEW_LINE> self._row_id = Number() <NEW_LINE> self._row_number = Number() <NEW_LINE> self._type = EnumeratedValue(PredecessorType) <NEW_LINE> if props: <NEW_LINE> <INDENT> deserialize(self, props) <NEW_LINE> <DEDENT> self.__initialized = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def in_critical_path(self): <NEW_LINE> <INDENT> return self._in_critical_path.value <NEW_LINE> <DEDENT> @in_critical_path.setter <NEW_LINE> def in_critical_path(self, value): <NEW_LINE> <INDENT> self._in_critical_path.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def invalid(self): <NEW_LINE> <INDENT> return self._invalid.value <NEW_LINE> <DEDENT> @invalid.setter <NEW_LINE> def invalid(self, value): <NEW_LINE> <INDENT> self._invalid.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def lag(self): <NEW_LINE> <INDENT> return self._lag.value <NEW_LINE> <DEDENT> @lag.setter <NEW_LINE> def lag(self, value): <NEW_LINE> <INDENT> self._lag.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def row_id(self): <NEW_LINE> <INDENT> return self._row_id.value <NEW_LINE> <DEDENT> @row_id.setter <NEW_LINE> def row_id(self, value): <NEW_LINE> <INDENT> self._row_id.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def row_number(self): <NEW_LINE> <INDENT> return self._row_number.value <NEW_LINE> <DEDENT> @row_number.setter <NEW_LINE> def row_number(self, value): <NEW_LINE> <INDENT> self._row_number.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, value): <NEW_LINE> <INDENT> self._type.set(value) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return serialize(self) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return json.dumps(self.to_dict()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.to_json()
Smartsheet Predecessor data model.
625990368a349b6b43687388
class ReceiverInstance(BaseHandler): <NEW_LINE> <INDENT> @transport_security_check('receiver') <NEW_LINE> @authenticated('receiver') <NEW_LINE> @inlineCallbacks <NEW_LINE> def get(self): <NEW_LINE> <INDENT> receiver_status = yield get_receiver_settings(self.current_user.user_id, self.request.language) <NEW_LINE> self.set_status(200) <NEW_LINE> self.finish(receiver_status) <NEW_LINE> <DEDENT> @transport_security_check('receiver') <NEW_LINE> @authenticated('receiver') <NEW_LINE> @inlineCallbacks <NEW_LINE> def put(self): <NEW_LINE> <INDENT> request = self.validate_message(self.request.body, requests.receiverReceiverDesc) <NEW_LINE> receiver_status = yield update_receiver_settings(self.current_user.user_id, request, self.request.language) <NEW_LINE> self.set_status(200) <NEW_LINE> self.finish(receiver_status)
This class permit to the receiver to modify some of their fields: Receiver.description Receiver.password and permit the overall view of all the Tips related to the receiver GET and PUT /receiver/preferences
62599036b830903b9686ed1d
class ServiceInterface(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, service_mode: ServiceMode , exit_callback=None): <NEW_LINE> <INDENT> self._service_mode = service_mode <NEW_LINE> self._exit_callback = exit_callback <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_async(self): <NEW_LINE> <INDENT> return self._service_mode == ServiceMode.ASYNC <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def process_event(self, event: AbstractEvent): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def add_event(self, event: AbstractEvent): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __iadd__(self, other): <NEW_LINE> <INDENT> self.add_event(other) <NEW_LINE> <DEDENT> def cancel(self, key): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def contains(self, key): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def close_recorders(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def create_recorders(self, recorder_db_name): <NEW_LINE> <INDENT> raise NotImplementedError
interface for services
625990368c3a8732951f76a1
class pyAlarmAlarmTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_CreateAlarm(self): <NEW_LINE> <INDENT> alarmTime = datetime.time(5, 0, 0) <NEW_LINE> alarm = Alarm("Work", "Monday", "elixir", 5, False, alarmTime, True) <NEW_LINE> self.assertEqual(False, alarm.isRepeatable, "Success")
description of class
62599036c432627299fa4140
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) <NEW_LINE> class RemoveProfileAlpha(RemoveProfile): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> os_arg = base.ChoiceArgument( '--operating-system', choices=('linux', 'windows'), required=False, default='linux', help_str='Specifies the profile type to remove.') <NEW_LINE> os_arg.AddToParser(parser)
Remove the posix account information for the current user.
6259903666673b3332c3153d
class ContentType(LazyLoader): <NEW_LINE> <INDENT> def __init__(self, root, filename='[Content_Types].xml'): <NEW_LINE> <INDENT> super(ContentType, self).__init__(root=root, filename=filename) <NEW_LINE> self.ovr = OrderedDict() <NEW_LINE> <DEDENT> def register_overrides(self): <NEW_LINE> <INDENT> self.load() <NEW_LINE> for node in self.xpath("/type:Types/type:Override"): <NEW_LINE> <INDENT> filename = node.attrib["PartName"] <NEW_LINE> self.ovr[filename] = node <NEW_LINE> <DEDENT> <DEDENT> def tablename_changed(self, filename, name): <NEW_LINE> <INDENT> ofn = "/"+filename <NEW_LINE> node = self.ovr[ofn] <NEW_LINE> new_name = tools.renamed(node.attrib["PartName"], name) <NEW_LINE> del self.ovr[ofn] <NEW_LINE> node.attrib["PartName"] = new_name <NEW_LINE> self.ovr[new_name] = node <NEW_LINE> self.invalidate()
ContentType reflects [Content_Types].xml
62599036796e427e5384f8c4
class SingleConditionMethod(AnalysisMethod): <NEW_LINE> <INDENT> def __init__(self, short_name, long_name, short_desc, long_desc, ctrldata, annotation_path, output, replicates="Sum", normalization=None, LOESS=False, ignoreCodon=True, NTerminus=0.0, CTerminus=0.0, wxobj=None): <NEW_LINE> <INDENT> AnalysisMethod.__init__(self, short_name, long_name, short_desc, long_desc, output, annotation_path, wxobj) <NEW_LINE> self.ctrldata = ctrldata <NEW_LINE> self.replicates = replicates <NEW_LINE> self.normalization = normalization <NEW_LINE> self.LOESS = LOESS <NEW_LINE> self.ignoreCodon = ignoreCodon <NEW_LINE> self.NTerminus = NTerminus <NEW_LINE> self.CTerminus = CTerminus
Class to be inherited by analysis methods that determine essentiality in a single condition (e.g. Gumbel, Binomial, HMM).
6259903650485f2cf55dc0c7
class MagmasAndAdditiveMagmas(Category_singleton): <NEW_LINE> <INDENT> class SubcategoryMethods: <NEW_LINE> <INDENT> @cached_method <NEW_LINE> def Distributive(self): <NEW_LINE> <INDENT> return self._with_axiom('Distributive') <NEW_LINE> <DEDENT> <DEDENT> def super_categories(self): <NEW_LINE> <INDENT> return [Magmas(), AdditiveMagmas()] <NEW_LINE> <DEDENT> Distributive = LazyImport('sage.categories.distributive_magmas_and_additive_magmas', 'DistributiveMagmasAndAdditiveMagmas', at_startup=True)
The category of sets `(S,+,*)` with an additive operation '+' and a multiplicative operation `*` EXAMPLES:: sage: from sage.categories.magmas_and_additive_magmas import MagmasAndAdditiveMagmas sage: C = MagmasAndAdditiveMagmas(); C Category of magmas and additive magmas This is the base category for the categories of rings and their variants:: sage: C.Distributive() Category of distributive magmas and additive magmas sage: C.Distributive().Associative().AdditiveAssociative().AdditiveCommutative().AdditiveUnital().AdditiveInverse() Category of rngs sage: C.Distributive().Associative().AdditiveAssociative().AdditiveCommutative().AdditiveUnital().Unital() Category of semirings sage: C.Distributive().Associative().AdditiveAssociative().AdditiveCommutative().AdditiveUnital().AdditiveInverse().Unital() Category of rings This category is really meant to represent the intersection of the categories of :class:`Magmas` and :class:`AdditiveMagmas`; however Sage's infrastructure does not allow yet to model this:: sage: Magmas() & AdditiveMagmas() Join of Category of magmas and Category of additive magmas sage: Magmas() & AdditiveMagmas() # todo: not implemented Category of magmas and additive magmas TESTS:: sage: TestSuite(MagmasAndAdditiveMagmas()).run()
62599036d53ae8145f9195ad
class EditInternalAd(forms.Form): <NEW_LINE> <INDENT> internalad_id = forms.ModelChoiceField(required=False, queryset=Internalad.objects.all(), label='Campaign Name') <NEW_LINE> contentSpecific = forms.CharField(required=False, max_length=30, label='Content Specific') <NEW_LINE> keywords = forms.CharField(required=False, max_length=30, label='Keywords') <NEW_LINE> activeDate = forms.DateField(required=False, label='Active Date(mm/dd/yyyy)', widget=forms.widgets.DateInput(format="%m/%d/%Y")) <NEW_LINE> expiredDate = forms.DateField(required=False, label='Expired Date(mm/dd/yyyy)', widget=forms.widgets.DateInput(format="%m/%d/%Y")) <NEW_LINE> noOfImpressions = forms.IntegerField(required=False, label='# of Impressions') <NEW_LINE> priority = forms.IntegerField(required=False, label='Priority') <NEW_LINE> maxImpressions = forms.IntegerField(required=False, label='Max. Impressions') <NEW_LINE> targetpages = forms.CharField(required=False, label='Target Pages', widget=forms.Textarea) <NEW_LINE> ad = forms.CharField(required=False, label='Ad', widget=forms.Textarea) <NEW_LINE> adType = forms.ChoiceField(required=False, choices=[('Image','(300 x 250)'), ('Banner1', '(160 x 600)'), ('Banner2', '(728 x 90)')], widget=forms.RadioSelect) <NEW_LINE> myHiddenField = forms.BooleanField(widget = forms.HiddenInput(attrs={'id':'myHiddenFieldValue'}), required=False)
# The EditInternalAd Class will display # form to Update internal ads by selecting # internal ad displayed in combobox
62599036507cdc57c63a5ee3
class Requests(_DownloadableProxyMixin, _ItemsResourceProxy): <NEW_LINE> <INDENT> def add(self, url, status, method, rs, duration, ts, parent=None, fp=None): <NEW_LINE> <INDENT> return self._origin.add( url, status, method, rs, parent, duration, ts, fp=fp)
Representation of collection of job requests. Not a public constructor: use :class:`~scrapinghub.client.jobs.Job` instance to get a :class:`Requests` instance. See :attr:`~scrapinghub.client.jobs.Job.requests` attribute. Please note that :meth:`list` method can use a lot of memory and for a large amount of logs it's recommended to iterate through it via :meth:`iter` method (all params and available filters are same for both methods). Usage: - retrieve all requests from a job:: >>> job.requests.iter() <generator object mpdecode at 0x10f5f3aa0> - iterate through the requests:: >>> for reqitem in job.requests.iter(count=1): ... print(reqitem['time']) 1482233733870 - retrieve single request from a job:: >>> job.requests.list(count=1) [{ 'duration': 354, 'fp': '6d748741a927b10454c83ac285b002cd239964ea', 'method': 'GET', 'rs': 1270, 'status': 200,a 'time': 1482233733870, 'url': 'https://example.com' }]
6259903676d4e153a661db16
class SeriesViewSet(aaSembleV1ViewSet): <NEW_LINE> <INDENT> lookup_field = selff.default_lookup_field <NEW_LINE> lookup_value_regex = selff.default_lookup_value_regex <NEW_LINE> queryset = buildsvc_models.Series.objects.all() <NEW_LINE> serializer_class = selff.serializers.SeriesSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return self.queryset.filter(repository__in=buildsvc_models.Repository.lookup_by_user(self.request.user))
API endpoint that allows series to be viewed or edited.
62599036cad5886f8bdc5920
class NotFollowerTwFriend(models.Model): <NEW_LINE> <INDENT> id_str = models.CharField(max_length=25, unique=True, primary_key=True) <NEW_LINE> screen_name = models.CharField(max_length=20, unique=True) <NEW_LINE> name = models.CharField(max_length=25) <NEW_LINE> description = models.TextField(default='') <NEW_LINE> statuses_count = models.PositiveIntegerField(default=0) <NEW_LINE> followers_count = models.PositiveIntegerField(default=0) <NEW_LINE> friends_count = models.PositiveIntegerField(default=0) <NEW_LINE> created_at = models.CharField(max_length=50) <NEW_LINE> location = models.CharField(max_length=100, default='') <NEW_LINE> avg_tweetsperday = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) <NEW_LINE> tff_ratio = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) <NEW_LINE> need_unfollow = models.BooleanField(default=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.id_str
Model for Twitter friend who aren't follower
6259903630c21e258be99957
class WorkloadOrder(BASE, NovaBase): <NEW_LINE> <INDENT> __tablename__ = 'workload_orders' <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> status = Column(String(255)) <NEW_LINE> workload_id = Column(Integer) <NEW_LINE> instances = Column(Integer) <NEW_LINE> memory_mb = Column(Integer) <NEW_LINE> workload = orm.relationship(Workload, foreign_keys=workload_id, primaryjoin='and_(' 'WorkloadOrder.workload_id == Workload.id,' 'Workload.deleted == 0,' 'WorkloadOrder.deleted == 0)')
Represents a Order related to a Workload.
62599036b57a9660fecd2bc5
class ChangeUserForm(happyforms.ModelForm): <NEW_LINE> <INDENT> email = forms.EmailField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('first_name', 'last_name', 'email') <NEW_LINE> <DEDENT> def _clean_names(self, data): <NEW_LINE> <INDENT> if not re.match(r'(^[A-Za-z\' ]+$)', data): <NEW_LINE> <INDENT> raise ValidationError('Please use only Latin characters.') <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def clean_first_name(self): <NEW_LINE> <INDENT> data = self.cleaned_data['first_name'] <NEW_LINE> return self._clean_names(data) <NEW_LINE> <DEDENT> def clean_last_name(self): <NEW_LINE> <INDENT> data = self.cleaned_data['last_name'] <NEW_LINE> return self._clean_names(data) <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> self.instance.username = USERNAME_ALGO(self.instance.email) <NEW_LINE> super(ChangeUserForm, self).save()
Form to change user details.
625990368a349b6b4368738a
class FunderCompanyProcurementTable(tables.Table): <NEW_LINE> <INDENT> company = tables.LinkColumn('serbia:companies', args=[A('company.company.pk')], accessor='company.company.name', verbose_name='company') <NEW_LINE> procurement = tables.LinkColumn('serbia:procurements', args=[A('procurement.pk')], accessor='procurement.subject', verbose_name='procurement') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = models.FunderCompanyProcurement <NEW_LINE> attrs = {"class": "paleblue table table-striped table-bordered"} <NEW_LINE> exclude = ('id', 'created', 'updated', 'hash', 'basemodel_ptr')
political donors companies in procurement table
625990368c3a8732951f76a3
class PrettyDict(AttrDict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _BREAK_LINES = kwargs.pop("breakLines", False) <NEW_LINE> super(PrettyDict, self).__init__(*args, **kwargs) <NEW_LINE> dict.__setattr__(self, "_BREAK_LINES", _BREAK_LINES) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> parts = [] <NEW_LINE> for k, v in sorted(self.items()): <NEW_LINE> <INDENT> kv = repr(k) + ": " <NEW_LINE> try: <NEW_LINE> <INDENT> kv += v._short_repr() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> kv += repr(v) <NEW_LINE> <DEDENT> parts.append(kv) <NEW_LINE> <DEDENT> return "{" + (",\n " if self._BREAK_LINES else ", ").join(parts) + "}"
Displays an abbreviated repr of values where possible. Inherits from AttrDict, so a callable value will be lazily converted to an actual value.
6259903650485f2cf55dc0c9
class TestCanonicalMAFunction(_ATestCanonical): <NEW_LINE> <INDENT> _condition = _canonical_parse = (u'foo("bar", 955CCA77, >, <, >=, <=, ==, ' u'!=)')
Tests if a multi-argument function parses correctly. Also checks all types of arguments.
6259903676d4e153a661db17
class Unsubscribed(Message): <NEW_LINE> <INDENT> MESSAGE_TYPE = 35 <NEW_LINE> def __init__(self, request, subscription=None, reason=None): <NEW_LINE> <INDENT> assert (type(request) is int) <NEW_LINE> assert (subscription is None or type(subscription) is int) <NEW_LINE> assert(reason is None or isinstance(reason, string_types)) <NEW_LINE> assert((request != 0 and subscription is None) or (request == 0 and subscription != 0)) <NEW_LINE> Message.__init__(self) <NEW_LINE> self.request = request <NEW_LINE> self.subscription = subscription <NEW_LINE> self.reason = reason <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse(wmsg): <NEW_LINE> <INDENT> assert(len(wmsg) > 0 and wmsg[0] == Unsubscribed.MESSAGE_TYPE) <NEW_LINE> if len(wmsg) not in [2, 3]: <NEW_LINE> <INDENT> raise ProtocolError("invalid message length {0} for UNSUBSCRIBED".format(len(wmsg))) <NEW_LINE> <DEDENT> request = check_or_raise_id(wmsg[1], "'request' in UNSUBSCRIBED") <NEW_LINE> subscription = None <NEW_LINE> reason = None <NEW_LINE> if len(wmsg) > 2: <NEW_LINE> <INDENT> details = check_or_raise_extra(wmsg[2], "'details' in UNSUBSCRIBED") <NEW_LINE> if "subscription" in details: <NEW_LINE> <INDENT> details_subscription = details["subscription"] <NEW_LINE> if type(details_subscription) is not int: <NEW_LINE> <INDENT> raise ProtocolError("invalid type {0} for 'subscription' detail in UNSUBSCRIBED".format(type(details_subscription))) <NEW_LINE> <DEDENT> subscription = details_subscription <NEW_LINE> <DEDENT> if "reason" in details: <NEW_LINE> <INDENT> reason = check_or_raise_uri(details["reason"], "'reason' in UNSUBSCRIBED") <NEW_LINE> <DEDENT> <DEDENT> obj = Unsubscribed(request, subscription, reason) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def marshal(self): <NEW_LINE> <INDENT> if self.reason is not None or self.subscription is not None: <NEW_LINE> <INDENT> details = {} <NEW_LINE> if self.reason is not None: <NEW_LINE> <INDENT> details["reason"] = self.reason <NEW_LINE> <DEDENT> if self.subscription is not None: <NEW_LINE> <INDENT> details["subscription"] = self.subscription <NEW_LINE> <DEDENT> return [Unsubscribed.MESSAGE_TYPE, self.request, details] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [Unsubscribed.MESSAGE_TYPE, self.request] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Unsubscribed(request={0}, reason={1}, subscription={2})".format(self.request, self.reason, self.subscription)
A WAMP ``UNSUBSCRIBED`` message. Formats: * ``[UNSUBSCRIBED, UNSUBSCRIBE.Request|id]`` * ``[UNSUBSCRIBED, UNSUBSCRIBE.Request|id, Details|dict]``
6259903673bcbd0ca4bcb3d4
class Random_enhance_spl(object): <NEW_LINE> <INDENT> def __init__(self, min_value = -0.2, max_value = 0.2): <NEW_LINE> <INDENT> self.enhance_number = random.uniform(min_value, max_value) <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> spec = sample[0] <NEW_LINE> spec = spec.squeeze() <NEW_LINE> spec = spec + self.enhance_number <NEW_LINE> return np.expand_dims(spec, axis=0), sample[1]
random enhance sound pressure level on spectrogram
625990364e696a045264e6c8
class BucketScanLog(object): <NEW_LINE> <INDENT> def __init__(self, log_dir, name): <NEW_LINE> <INDENT> self.log_dir = log_dir <NEW_LINE> self.name = name <NEW_LINE> self.fh = None <NEW_LINE> self.count = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return os.path.join(self.log_dir, "%s.json" % self.name) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if self.log_dir is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.fh = open(self.path, 'w') <NEW_LINE> self.fh.write("[\n") <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type=None, exc_value=None, exc_frame=None): <NEW_LINE> <INDENT> if self.fh is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.fh.write("[]") <NEW_LINE> self.fh.write("\n]") <NEW_LINE> self.fh.close() <NEW_LINE> if not self.count: <NEW_LINE> <INDENT> os.remove(self.fh.name) <NEW_LINE> <DEDENT> self.fh = None <NEW_LINE> return False <NEW_LINE> <DEDENT> def add(self, keys): <NEW_LINE> <INDENT> self.count += len(keys) <NEW_LINE> if self.fh is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.fh.write(json.dumps(keys)) <NEW_LINE> self.fh.write(",\n")
Offload remediated key ids to a disk file in batches A bucket keyspace is effectively infinite, we need to store partial results out of memory, this class provides for a json log on disk with partial write support. json output format: - [list_of_serialized_keys], - [] # Empty list of keys at end when we close the buffer
62599036d10714528d69ef31
@dataclass <NEW_LINE> class Grid1D(Grid): <NEW_LINE> <INDENT> cells: List[Cell] <NEW_LINE> def __len__(self): <NEW_LINE> <INDENT> return len(self.cells) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> return self.cells[i] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "".join(list(map(str, self.cells)))
Represents a grid of cells.
625990368c3a8732951f76a5
class PostGroupIdDatasetSpec(): <NEW_LINE> <INDENT> def __init__(self, group_id, dataset_add_list, dataset_remove_list): <NEW_LINE> <INDENT> self.group_id = group_id <NEW_LINE> self.dataset_add_list = dataset_add_list <NEW_LINE> self.dataset_remove_list = dataset_remove_list <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> return json.dumps({'dataSetsToAdd': self.dataset_add_list, 'dataSetsToRemove': self.dataset_remove_list}) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{cls}(group_id={x.group_id!r}, dataset_add_list={x.dataset_add_list!r}, dataset_remove_list={x.dataset_remove_list})'.format(cls=self.__class__.__name__, x=self)
Class that helps validate and format the data being sent to LI when modifying datasets associated to a group. DISCLAIMER: At the time of writing this API was a technical preview.
62599036d18da76e235b79f5
class S3BucketPolicyWildcardActionRule(GenericWildcardPolicyRule): <NEW_LINE> <INDENT> AWS_RESOURCE = S3BucketPolicy
Soon to be replaced by `GenericResourceWildcardPolicyRule`. Checks for use of the wildcard `*` character in the Actions of Policy Documents of S3 Bucket Policies. This rule is a subclass of `GenericWildcardPolicyRule`. Filters context: | Parameter | Type | Description | |:-----------------------:|:--------------------------------:|:--------------------------------------------------------------:| |`config` | str | `config` variable available inside the rule | |`extras` | str | `extras` variable available inside the rule | |`logical_id` | str | ID used in Cloudformation to refer the resource being analysed | |`resource` | `S3BucketPolicy` | Resource that is being addressed |
6259903650485f2cf55dc0cb
class Metric(object): <NEW_LINE> <INDENT> def sample(self, value, sample_rate, timestamp=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def flush(self, timestamp): <NEW_LINE> <INDENT> raise NotImplementedError()
A base metric class that accepts points, slices them into time intervals and performs roll-ups within those intervals.
625990361f5feb6acb163d3f
class user(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> user = models.CharField(max_length=64, unique=True) <NEW_LINE> first_name = models.CharField(_('Nombre'), max_length=30, blank=True) <NEW_LINE> last_name = models.CharField(_('Apellidos'), max_length=30, blank=True) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> area = models.CharField( _(u'Área Administrativa'), choices=lbl_area, blank=True, null=True, max_length=32) <NEW_LINE> position = models.CharField( _('Nombre del puesto'), choices=lbl_position, blank=True, null=True, max_length=32, help_text=_(u'Papel o posisición de la persona responsable')) <NEW_LINE> boss = models.ForeignKey("self", null=True, blank=True, related_name="user_boss") <NEW_LINE> USERNAME_FIELD = 'user' <NEW_LINE> objects = PeopleBaseUserManager() <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.user <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.user
docstring for user.
62599036287bf620b6272d36
class LazyDynamicMapping(LazyDynamicBase, Mapping): <NEW_LINE> <INDENT> def __init__( self, data: Mapping = {}, resolver: DataResolver = None, scope: DataResolverScope = None, parent=None, ): <NEW_LINE> <INDENT> super().__init__(data, resolver, scope, parent) <NEW_LINE> self._expressions = self._data.get("@expressions", {}) <NEW_LINE> self._conditions = self._data.get("@conditions", {}) <NEW_LINE> self._data = {k: v for k, v in self._data.items() if self._eval_condition(k)} <NEW_LINE> <DEDENT> def _eval_condition(self, key: str): <NEW_LINE> <INDENT> if key in {"@expressions", "@conditions"}: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> condition = self._conditions.get(key) <NEW_LINE> if isinstance(condition, str) and not self._resolver.eval( condition, self, self._scope ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def _transform_kv(self, key: str, value): <NEW_LINE> <INDENT> expression = self._expressions.get(key) <NEW_LINE> if isinstance(expression, str): <NEW_LINE> <INDENT> value = self._resolver.eval(expression, self, self._scope) <NEW_LINE> <DEDENT> return self._transform_object(value) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._transform_kv(key, self._data.get(key)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._data) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._data) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> result = self._data.get(key, default) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._transform_kv(key, result) <NEW_LINE> <DEDENT> def with_scope(self, scope: DataResolverScope): <NEW_LINE> <INDENT> return LazyDynamicMapping(self._data, self._resolver, scope)
Lazy dynamic implementation of Mapping.
6259903650485f2cf55dc0cc
class Shape(object): <NEW_LINE> <INDENT> def __init__(self, raw_shape, dim=None): <NEW_LINE> <INDENT> super(Shape, self).__init__() <NEW_LINE> self.dim = dim <NEW_LINE> w = len(raw_shape[0]) <NEW_LINE> for line in raw_shape: <NEW_LINE> <INDENT> if len(line) != w: <NEW_LINE> <INDENT> print("len('{}') != len('{}')".format(line, w)) <NEW_LINE> print('Shape dimensions should not be jagged.') <NEW_LINE> raise IndexError <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if min([int(entry) for entry in line]) < 0: <NEW_LINE> <INDENT> print('All Shape entries should be non-negative.') <NEW_LINE> raise ValueError <NEW_LINE> <DEDENT> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> print('All Shape entries should be ints.') <NEW_LINE> raise e <NEW_LINE> <DEDENT> <DEDENT> max_value = max([max_from_string(row) for row in raw_shape]) <NEW_LINE> if dim is None: <NEW_LINE> <INDENT> self.dim = max_value + 1 <NEW_LINE> <DEDENT> elif dim < max_value + 1: <NEW_LINE> <INDENT> print('provided shape dim is too low for board entries.') <NEW_LINE> self.dim = max_value + 1 <NEW_LINE> print('setting dim = {}'.format(max_value + 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dim = dim <NEW_LINE> <DEDENT> self.values = get_small_array(raw_shape, self.dim) <NEW_LINE> self.width = w <NEW_LINE> self.height = len(raw_shape) <NEW_LINE> self._string = [[str(value) for value in row] for row in self.values] <NEW_LINE> self.pos_bound = None <NEW_LINE> self.valid_positions = Positions([]) <NEW_LINE> self.current_position = None <NEW_LINE> <DEDENT> def get_size(self): <NEW_LINE> <INDENT> return sum(sum(row) for row in self.values) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.values) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.values[key] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '\n'.join([' '.join(row) for row in self._string]) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return True if self.values == other.values else False
Shape.values is array of strings of bits representing shape
625990363eb6a72ae038b7b5
class Cifar10(tfds.core.GeneratorBasedBuilder): <NEW_LINE> <INDENT> VERSION = tfds.core.Version("1.0.2") <NEW_LINE> def _info(self): <NEW_LINE> <INDENT> return tfds.core.DatasetInfo( builder=self, description=("The CIFAR-10 dataset consists of 60000 32x32 colour " "images in 10 classes, with 6000 images per class. There " "are 50000 training images and 10000 test images."), features=tfds.features.FeaturesDict({ "image": tfds.features.Image(shape=_CIFAR_IMAGE_SHAPE), "label": tfds.features.ClassLabel(num_classes=10), }), supervised_keys=("image", "label"), urls=["https://www.cs.toronto.edu/~kriz/cifar.html"], citation=_CITATION, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _cifar_info(self): <NEW_LINE> <INDENT> return CifarInfo( name=self.name, url="https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz", train_files=[ "data_batch_1.bin", "data_batch_2.bin", "data_batch_3.bin", "data_batch_4.bin", "data_batch_5.bin" ], test_files=["test_batch.bin"], prefix="cifar-10-batches-bin/", label_files=["batches.meta.txt"], label_keys=["label"], ) <NEW_LINE> <DEDENT> def _split_generators(self, dl_manager): <NEW_LINE> <INDENT> cifar_path = dl_manager.download_and_extract(self._cifar_info.url) <NEW_LINE> cifar_info = self._cifar_info <NEW_LINE> cifar_path = os.path.join(cifar_path, cifar_info.prefix) <NEW_LINE> for label_key, label_file in zip(cifar_info.label_keys, cifar_info.label_files): <NEW_LINE> <INDENT> labels_path = os.path.join(cifar_path, label_file) <NEW_LINE> with tf.io.gfile.GFile(labels_path) as label_f: <NEW_LINE> <INDENT> label_names = [name for name in label_f.read().split("\n") if name] <NEW_LINE> <DEDENT> self.info.features[label_key].names = label_names <NEW_LINE> <DEDENT> def gen_filenames(filenames): <NEW_LINE> <INDENT> for f in filenames: <NEW_LINE> <INDENT> yield os.path.join(cifar_path, f) <NEW_LINE> <DEDENT> <DEDENT> return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, num_shards=10, gen_kwargs={"filepaths": gen_filenames(cifar_info.train_files)}), tfds.core.SplitGenerator( name=tfds.Split.TEST, num_shards=1, gen_kwargs={"filepaths": gen_filenames(cifar_info.test_files)}), ] <NEW_LINE> <DEDENT> def _generate_examples(self, filepaths): <NEW_LINE> <INDENT> label_keys = self._cifar_info.label_keys <NEW_LINE> for path in filepaths: <NEW_LINE> <INDENT> for labels, np_image in _load_data(path, len(label_keys)): <NEW_LINE> <INDENT> row = dict(zip(label_keys, labels)) <NEW_LINE> row["image"] = np_image <NEW_LINE> yield row
CIFAR-10.
62599036be383301e0254962
class Author(models.Model): <NEW_LINE> <INDENT> first_name = models.CharField(max_length=100) <NEW_LINE> last_name = models.CharField(max_length=100) <NEW_LINE> date_of_birth = models.DateField(null=True, blank=True) <NEW_LINE> date_of_death = models.DateField('died', null=True, blank=True) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('author-detail', args=[str(self.id)]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s, %s' % (self.last_name, self.first_name) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['last_name']
Modelo que representa un autor
62599036d53ae8145f9195b1
class TestStreamingTradex(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 make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return StreamingTradex( cvol = 'a', date = 'a', last = '0', price = '0', size = '0', exch = '0', symbol = '0', type = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return StreamingTradex( ) <NEW_LINE> <DEDENT> <DEDENT> def testStreamingTradex(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True)
StreamingTradex unit test stubs
6259903676d4e153a661db18
class TournamentDetailView(generic.DetailView): <NEW_LINE> <INDENT> context_object_name = 'tournament' <NEW_LINE> template_name = 'housing/tournament-detail.html' <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> return get_object_or_404( models.Tournament, slug=self.kwargs.get('slug'), slug_key=self.kwargs.get('slug_key'), )
View the details of a specific tournament.
6259903671ff763f4b5e88e7
class TestMoat: <NEW_LINE> <INDENT> def test_Moat_S2(self): <NEW_LINE> <INDENT> data_string = "043e3702010000aabb611d12e12b0d09475648353130325f43423942030388ec02010515ff0010AABBCCDDEEFF11111111d46103cbbe0a0000aa" <NEW_LINE> data = bytes(bytearray.fromhex(data_string)) <NEW_LINE> ble_parser = BleParser() <NEW_LINE> sensor_msg, tracker_msg = ble_parser.parse_data(data) <NEW_LINE> assert sensor_msg["firmware"] == "Moat" <NEW_LINE> assert sensor_msg["type"] == "Moat S2" <NEW_LINE> assert sensor_msg["mac"] == "E1121D61BBAA" <NEW_LINE> assert sensor_msg["packet"] == "no packet id" <NEW_LINE> assert sensor_msg["data"] <NEW_LINE> assert sensor_msg["temperature"] == 20.300 <NEW_LINE> assert sensor_msg["humidity"] == 93.127 <NEW_LINE> assert sensor_msg["battery"] == 19.5 <NEW_LINE> assert sensor_msg["rssi"] == -86
Tests for the Moat parser
625990361d351010ab8f4c68
class Bitfield(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def from_bytes(byte_array): <NEW_LINE> <INDENT> return Bitfield(len(byte_array) * 8, initializer=byte_array) <NEW_LINE> <DEDENT> def __init__(self, length, default=False, initializer=None): <NEW_LINE> <INDENT> self._length = length <NEW_LINE> num_bytes, leftover_bits = divmod(length, 8) <NEW_LINE> initializer = initializer or chr(255 if default else 0) * (num_bytes + (leftover_bits > 0)) <NEW_LINE> self._array = array.array('B', initializer) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_bytes(self): <NEW_LINE> <INDENT> return len(self._array) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._array == other._array <NEW_LINE> <DEDENT> def as_bytes(self): <NEW_LINE> <INDENT> return ''.join(map(chr, self._array)) <NEW_LINE> <DEDENT> def fill(self, value): <NEW_LINE> <INDENT> for k in range(len(value)): <NEW_LINE> <INDENT> self._array[k] = ord(value[k]) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> byte_index = (index / 8) <NEW_LINE> bit_index = index % 8 <NEW_LINE> byte = self._array[byte_index] <NEW_LINE> return True if (byte & (1 << bit_index)) else False <NEW_LINE> <DEDENT> def __setitem__(self, index, value): <NEW_LINE> <INDENT> byte_index = (index / 8) <NEW_LINE> bit_index = index % 8 <NEW_LINE> if value: <NEW_LINE> <INDENT> self._array[byte_index] |= (1 << bit_index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._array[byte_index] &= (~(1 << bit_index) % 256) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, index): <NEW_LINE> <INDENT> if index >= len(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self[index] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._length
Naive implementation of a vector of booleans with __getitem__ and __setitem__.
6259903694891a1f408b9fa0
class ClarifyRepeat(Move): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Move.__init__(self, name = 'clarify_step_repeat', prior_moves = ['Recept repeat'], context = [['recept_stappen',5,{'no-input': 0.0, 'no-match': 0.0}],['recept_toelichting',5,{'no-input': 0.0, 'no-match': 0.0}]], suggestions = ['volgende','duidelijk','dankje'] ) <NEW_LINE> <DEDENT> def preconditions_met(self,infostate,knowledge): <NEW_LINE> <INDENT> return Move.preconditions_met(self,infostate) <NEW_LINE> <DEDENT> def effects(self,infostate,knowledge): <NEW_LINE> <INDENT> Move.effects(self,infostate) <NEW_LINE> infostate['shared']['qud'] = infostate['private']['plan'][0] + '_repeat'
ClarifyRepeat ===== Class to model the preconditions and effects of the move to repeat a step
6259903630c21e258be9995a
class Ship: <NEW_LINE> <INDENT> def __init__(self, nam, att, dfns, hul, shld): <NEW_LINE> <INDENT> self._name = nam <NEW_LINE> self._attack = att <NEW_LINE> self._defense = dfns <NEW_LINE> self._shields = shld <NEW_LINE> self._hull = hul <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return(self._name) <NEW_LINE> <DEDENT> def setattack(self, att): <NEW_LINE> <INDENT> self._attack = att <NEW_LINE> <DEDENT> def attack(self, closerange=False, longrange=False): <NEW_LINE> <INDENT> if closerange: <NEW_LINE> <INDENT> attadd = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attadd = 0 <NEW_LINE> <DEDENT> return(self._attack + attadd) <NEW_LINE> <DEDENT> @property <NEW_LINE> def defense(self): <NEW_LINE> <INDENT> return(self._defense) <NEW_LINE> <DEDENT> @property <NEW_LINE> def shields(self): <NEW_LINE> <INDENT> return(self._shields) <NEW_LINE> <DEDENT> @property <NEW_LINE> def hits(self): <NEW_LINE> <INDENT> return(self._shields + self._hull) <NEW_LINE> <DEDENT> def attacktarget(self, targetship, closerange=False, longrange=False, evade=False): <NEW_LINE> <INDENT> ag = AggDice.AggDice() <NEW_LINE> if longrange: <NEW_LINE> <INDENT> defadd = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> defadd = 0 <NEW_LINE> <DEDENT> ag.setupdice(self.attack(closerange, longrange), targetship.defense + defadd) <NEW_LINE> hitsreqd = targetship.hits <NEW_LINE> avgrndsnorm = hitsreqd / ag.avghits() <NEW_LINE> avgrndsattfoc = hitsreqd / ag.avghits(True, False) <NEW_LINE> avgrndsdeffoc = hitsreqd / ag.avghits(False, True) <NEW_LINE> if evade: <NEW_LINE> <INDENT> avghits = ag.avghits(False, False, True) <NEW_LINE> if avghits > 0: <NEW_LINE> <INDENT> avgrndsdefevade = hitsreqd / avghits <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> avgrndsdefevade = -1 <NEW_LINE> <DEDENT> avghitsattfoc = ag.avghits(True, False, True) <NEW_LINE> if avghitsattfoc > 0: <NEW_LINE> <INDENT> avgrndsdefevadeattfoc = hitsreqd / avghitsattfoc <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> avgrndsdefevadeattfoc = -1 <NEW_LINE> <DEDENT> <DEDENT> attdicedpr = targetship.attack() / avgrndsnorm <NEW_LINE> avgrndstillcrits = targetship.shields / ag.avghits() <NEW_LINE> print(self.name + " attacking " + targetship.name + ":") <NEW_LINE> print("Avg rounds no focus to destroy: " + str(avgrndsnorm)) <NEW_LINE> print("Avg rounds attack focus to destroy: " + str(avgrndsattfoc)) <NEW_LINE> print("Avg rounds defense focus to destroy: " + str(avgrndsdeffoc)) <NEW_LINE> if evade: <NEW_LINE> <INDENT> print("Avg rounds defense evade to destroy: " + str(avgrndsdefevade)) <NEW_LINE> print("Avg rounds attack focus + defense evade to destroy: " + str(avgrndsdefevadeattfoc)) <NEW_LINE> <DEDENT> print("Avg rounds before crits: " + str(avgrndstillcrits)) <NEW_LINE> print("Attack dice destroyed per round: " + str(attdicedpr)) <NEW_LINE> <DEDENT> def faceoff(self, atknb): <NEW_LINE> <INDENT> print("------------------------------------") <NEW_LINE> self.attacktarget(atknb) <NEW_LINE> print("------------------------------------") <NEW_LINE> atknb.attacktarget(self) <NEW_LINE> print("------------------------------------")
Base class for different ship types
6259903696565a6dacd2d833
class Cert(cert_manager.Cert): <NEW_LINE> <INDENT> def __init__(self, certificate, private_key, intermediates=None, private_key_passphrase=None): <NEW_LINE> <INDENT> self.certificate = certificate <NEW_LINE> self.intermediates = intermediates <NEW_LINE> self.private_key = private_key <NEW_LINE> self.private_key_passphrase = private_key_passphrase <NEW_LINE> <DEDENT> def get_certificate(self): <NEW_LINE> <INDENT> return self.certificate <NEW_LINE> <DEDENT> def get_intermediates(self): <NEW_LINE> <INDENT> return self.intermediates <NEW_LINE> <DEDENT> def get_private_key(self): <NEW_LINE> <INDENT> return self.private_key <NEW_LINE> <DEDENT> def get_private_key_passphrase(self): <NEW_LINE> <INDENT> return self.private_key_passphrase
Representation of a Cert for local storage.
6259903615baa723494630e9
class LunchBot: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.BOT_ID = os.environ.get("BOT_ID") <NEW_LINE> self.BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') <NEW_LINE> self.AT_BOT = "<@" + self.BOT_ID + ">" <NEW_LINE> self.slack_client = SlackClient(self.BOT_TOKEN) <NEW_LINE> self.EXAMPLE_COMMAND = "lunch?" <NEW_LINE> self.READ_WEBSOCKET_DELAY = 1 <NEW_LINE> foods_file = "food_options.yaml" <NEW_LINE> self.food_choices = load(open(foods_file, 'r')) <NEW_LINE> <DEDENT> def runBot(self): <NEW_LINE> <INDENT> if self.slack_client.rtm_connect(): <NEW_LINE> <INDENT> print("Lunchbot connected and running!") <NEW_LINE> while True: <NEW_LINE> <INDENT> command, channel = self.parse_slack_output(self.slack_client.rtm_read()) <NEW_LINE> if command and channel: <NEW_LINE> <INDENT> self.handle_command(command, channel) <NEW_LINE> <DEDENT> time.sleep(self.READ_WEBSOCKET_DELAY) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("Can't connect to slack, have you set up environment variables for BOT_ID and SLACK_BOT_TOKEN ?") <NEW_LINE> <DEDENT> <DEDENT> def getRandomRecomendation(self): <NEW_LINE> <INDENT> choice = random.choice(self.food_choices) <NEW_LINE> response = """I'm thinking %s Here's some nearby places""" % choice['name'] <NEW_LINE> places = mapsClient().placesSearch(keyword=choice['search_term']) <NEW_LINE> for place in places: <NEW_LINE> <INDENT> response += "\n<%s|%s> - %s away" % (place['url'], place['name'], place['distance']) <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> def handle_command(self, command, channel): <NEW_LINE> <INDENT> if self.AT_BOT.lower() in command: <NEW_LINE> <INDENT> command = command.split(self.AT_BOT.lower())[1].split()[0] <NEW_LINE> if command: <NEW_LINE> <INDENT> places = mapsClient().placesSearch(keyword=command) <NEW_LINE> if places: <NEW_LINE> <INDENT> response = "I found these restaurants for %s " % command <NEW_LINE> for place in places: <NEW_LINE> <INDENT> response += "\n<%s|%s> - %s away" % (place['url'], place['name'], place['distance']) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> response = "I couldn't find anything nearby for %s" % command <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> response = self.getRandomRecomendation() <NEW_LINE> <DEDENT> <DEDENT> elif self.EXAMPLE_COMMAND in command: <NEW_LINE> <INDENT> response = self.getRandomRecomendation() <NEW_LINE> <DEDENT> self.slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True) <NEW_LINE> <DEDENT> def parse_slack_output(self, slack_rtm_output): <NEW_LINE> <INDENT> output_list = slack_rtm_output <NEW_LINE> if output_list and len(output_list) > 0: <NEW_LINE> <INDENT> for output in output_list: <NEW_LINE> <INDENT> if output and 'text' in output and (self.EXAMPLE_COMMAND in output['text'] or self.AT_BOT in output['text']): <NEW_LINE> <INDENT> return output['text'].lower(), output['channel'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None, None
For using google maps to get lunch reccomendations over slack
62599036711fe17d825e1543
class Engine: <NEW_LINE> <INDENT> pass
Emulates SQLAlchemy look-a-like in our examples.
6259903666673b3332c31542
class ReadCase(object): <NEW_LINE> <INDENT> decimals=3 <NEW_LINE> def test_read_comment(self): <NEW_LINE> <INDENT> with open(self.expected_comment_file) as f: <NEW_LINE> <INDENT> expected_comment = f.next() <NEW_LINE> <DEDENT> with gro.open(self.test_file_name, decimals=self.decimals) as f: <NEW_LINE> <INDENT> f.next() <NEW_LINE> self.assertEqual(f.comment, expected_comment) <NEW_LINE> <DEDENT> <DEDENT> def test_read_crd(self): <NEW_LINE> <INDENT> with open(self.expected_crds_file) as f: <NEW_LINE> <INDENT> expected_crds = 10. * np.array([float(x) for x in f.read().split()]) <NEW_LINE> <DEDENT> with gro.open(self.test_file_name, decimals=self.decimals) as f: <NEW_LINE> <INDENT> crds = f.next() <NEW_LINE> <DEDENT> for (expected, crd) in it.izip_longest(expected_crds, crds): <NEW_LINE> <INDENT> self.assertAlmostEqual(expected, crd, self.decimals)
Test reading a known mdrd file.
62599036a8ecb0332587236d
class Movable(Collidable): <NEW_LINE> <INDENT> def __init__(self, x, y, w, h, a, cb): <NEW_LINE> <INDENT> Collidable.__init__(self, x, y, w, h, a, cb) <NEW_LINE> self.speed = 3 <NEW_LINE> self.dx, self.dy = self.set_direction() <NEW_LINE> self.a_dict = {'idle': sorted(os.listdir('images/movable'), key=Movable.natural_key)} <NEW_LINE> self.a_list = self.a_dict[self.a_status] <NEW_LINE> self.a_frame_rate = 30 <NEW_LINE> <DEDENT> def set_direction(self): <NEW_LINE> <INDENT> return self.speed * math.sin(self.a * math.pi / 180), self.speed * math.cos(self.a * math.pi / 180) <NEW_LINE> <DEDENT> def a_move(self): <NEW_LINE> <INDENT> self.a_status = 'move' <NEW_LINE> self.a_step = 0
functions with 'a_' for assigning current animation (on move button pressed)
6259903607d97122c4217deb
class BackupProductionShinePostgres(luigi.Task): <NEW_LINE> <INDENT> task_namespace = 'backup' <NEW_LINE> host = luigi.Parameter(default='access') <NEW_LINE> service = luigi.Parameter(default='access_shinedb') <NEW_LINE> db = luigi.Parameter(default='shine') <NEW_LINE> remote_host_backup_folder = luigi.Parameter(default='/data/shine/postgresql/data') <NEW_LINE> hdfs_backup_folder = luigi.Parameter(default='/2_backups/') <NEW_LINE> date = luigi.DateParameter(default=datetime.date.today()) <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return BackupRemoteDockerPostgres(host=self.host, service=self.service, db=self.db, remote_host_backup_folder=self.remote_host_backup_folder, date=self.date) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> bkp_path = os.path.join(self.hdfs_backup_folder,"%s/%s/%s.pgdump-%s" % (self.host, self.service, self.db, self.date.strftime('%Y%m%d'))) <NEW_LINE> return luigi.contrib.hdfs.HdfsTarget(path=bkp_path, format=PlainFormat()) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> with open(self.input().path, 'rb') as reader: <NEW_LINE> <INDENT> with self.output().open('w') as writer: <NEW_LINE> <INDENT> for chunk in reader: <NEW_LINE> <INDENT> writer.write(chunk) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_backup_size(self): <NEW_LINE> <INDENT> return self.output().fs.count(self.output().path).get('content_size', None) <NEW_LINE> <DEDENT> def get_metrics(self,registry): <NEW_LINE> <INDENT> g = Gauge('ukwa_database_backup_size_bytes', 'Size of a database backup.', labelnames=['db'], registry=registry) <NEW_LINE> g.labels(db=self.db).set(self.get_backup_size())
This task runs a Docker PostgreSQL backup task for a specific system (production Shine) and then pushes the backup file up to HDFS.
6259903650485f2cf55dc0cd
@unittest.skipIf(tests.MYSQL_VERSION >= (5, 7, 5), "MySQL {0} does not support old password auth".format( tests.MYSQL_VERSION_TXT)) <NEW_LINE> class BugOra18415927(tests.MySQLConnectorTests): <NEW_LINE> <INDENT> user = { 'username': 'nativeuser', 'password': 'nativeP@ss', } <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> config = tests.get_mysql_config() <NEW_LINE> host = config['host'] <NEW_LINE> database = config['database'] <NEW_LINE> cnx = connection.MySQLConnection(**config) <NEW_LINE> try: <NEW_LINE> <INDENT> cnx.cmd_query("DROP USER '{user}'@'{host}'".format( host=host, user=self.user['username'])) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> create_user = "CREATE USER '{user}'@'{host}' " <NEW_LINE> cnx.cmd_query(create_user.format(user=self.user['username'], host=host)) <NEW_LINE> passwd = ("SET PASSWORD FOR '{user}'@'{host}' = " "PASSWORD('{password}')").format( user=self.user['username'], host=host, password=self.user['password']) <NEW_LINE> cnx.cmd_query(passwd) <NEW_LINE> grant = "GRANT ALL ON {database}.* TO '{user}'@'{host}'" <NEW_LINE> cnx.cmd_query(grant.format(database=database, user=self.user['username'], host=host)) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> config = tests.get_mysql_config() <NEW_LINE> host = config['host'] <NEW_LINE> cnx = connection.MySQLConnection(**config) <NEW_LINE> cnx.cmd_query("DROP USER '{user}'@'{host}'".format( host=host, user=self.user['username'])) <NEW_LINE> <DEDENT> def test_auth_response(self): <NEW_LINE> <INDENT> config = tests.get_mysql_config() <NEW_LINE> config['unix_socket'] = None <NEW_LINE> config['user'] = self.user['username'] <NEW_LINE> config['password'] = self.user['password'] <NEW_LINE> config['client_flags'] = [-constants.ClientFlag.SECURE_CONNECTION] <NEW_LINE> try: <NEW_LINE> <INDENT> cnx = connection.MySQLConnection(**config) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> self.fail("Connection failed: {0}".format(exc))
BUG#18415927: AUTH_RESPONSE VARIABLE INCREMENTED WITHOUT BEING DEFINED
6259903607d97122c4217dec
class WelcomePage(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> username = self.request.get('username') <NEW_LINE> if valid_username(username): <NEW_LINE> <INDENT> welcome_text = "<h1>Welcome, " + username + "!</h1>" <NEW_LINE> self.response.write(welcome_text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect('/signup')
Handles requests coming to "/welcome", builds Welcome page
62599036d53ae8145f9195b3
class ScreenBase: <NEW_LINE> <INDENT> WIDTH_PX = 256 <NEW_LINE> HEIGHT_PX = 240 <NEW_LINE> VISIBLE_HEIGHT_PX = 224 <NEW_LINE> VISIBLE_WIDTH_PX = 240 <NEW_LINE> def __init__(self, ppu, scale=3, vertical_overscan=False, horizontal_overscan=False): <NEW_LINE> <INDENT> self.ppu = ppu <NEW_LINE> self.width = self.WIDTH_PX if horizontal_overscan else self.VISIBLE_WIDTH_PX <NEW_LINE> self.height = self.HEIGHT_PX if vertical_overscan else self.VISIBLE_HEIGHT_PX <NEW_LINE> self.scale = scale <NEW_LINE> self.vertical_overscan = vertical_overscan <NEW_LINE> self.horizontal_overscan = horizontal_overscan <NEW_LINE> self._text_buffer = [] <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def add_text(self, text, position, color, ttl=1): <NEW_LINE> <INDENT> self._text_buffer.append((text, position, color, ttl)) <NEW_LINE> <DEDENT> def update_text(self): <NEW_LINE> <INDENT> self._text_buffer = [(txt, pos, col, ttl - 1) for (txt, pos, col, ttl) in self._text_buffer if ttl > 1]
Base class for screens. Not library specific.
6259903676d4e153a661db19
class ValoresDao(object): <NEW_LINE> <INDENT> __banco='' <NEW_LINE> def __init__(self, banco): <NEW_LINE> <INDENT> self.__banco=banco <NEW_LINE> <DEDENT> def add(self,valores): <NEW_LINE> <INDENT> sql = "INSERT INTO `values`(`VALUE`, `DATETIME`, `tag_idTAG`) VALUES (%f"%valores.getValor()+",'"+str(valores.getDataHora())+"',%d)"%valores.getIdTag() <NEW_LINE> return self.__banco.exe(sql) <NEW_LINE> <DEDENT> def remove(self,id): <NEW_LINE> <INDENT> sql = "DELETE FROM valores WHERE idValores=%d"%id <NEW_LINE> return self.__banco.exe(sql) <NEW_LINE> <DEDENT> def update(self,valores): <NEW_LINE> <INDENT> sql = "UPDATE valores SET VALOR=%f"%valores.getValor()+",DATAHORA='"+valores.getDataHora()+"',tag_idTAG=%d"%valores.getIdTag()+" WHERE idValores=%d"%valores.getIdValores() <NEW_LINE> return self.__banco.exe(sql) <NEW_LINE> <DEDENT> def retrieve(self,id): <NEW_LINE> <INDENT> sql = "SELECT * FROM `values` WHERE idVALUES=%d"%id <NEW_LINE> self.__banco.exe(sql) <NEW_LINE> stringValores=self.__banco.cursor.fetchone() <NEW_LINE> return Valores(stringValores[1],stringValores[2],stringValores[3],stringValores[0]) <NEW_LINE> <DEDENT> def last(self,id): <NEW_LINE> <INDENT> sql="SELECT * FROM `values` WHERE idVALUES=(SELECT MAX(idVALUES) FROM `values` WHERE tag_idTAG=%d)"%id <NEW_LINE> self.__banco.exe(sql) <NEW_LINE> stringValores=self.__banco.cursor.fetchone() <NEW_LINE> return Valores(stringValores[1],stringValores[2],stringValores[3],stringValores[0])
classdocs
62599036a4f1c619b294f72f
class Battery: <NEW_LINE> <INDENT> def __init__(self, battery_size=75): <NEW_LINE> <INDENT> self.battery_size = battery_size <NEW_LINE> <DEDENT> def describe_battery(self): <NEW_LINE> <INDENT> print(f"This car has a {self.battery_size}-KWh battery") <NEW_LINE> <DEDENT> def get_range(self): <NEW_LINE> <INDENT> if self.battery_size == 75: <NEW_LINE> <INDENT> range = 260 <NEW_LINE> <DEDENT> elif self.battery_size == 100: <NEW_LINE> <INDENT> range = 315 <NEW_LINE> <DEDENT> print(f"This car can go about {range} miles on a full charge.")
A simple attempt to model a battery for an electric car.
6259903673bcbd0ca4bcb3d8
class Condition(AttrDict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> for key, value in self.items(): <NEW_LINE> <INDENT> if not key.isidentifier() or iskeyword(key): <NEW_LINE> <INDENT> raise ValueError('Keys must be valid python expressions.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def set_superset_condition(self, superset_condition): <NEW_LINE> <INDENT> for key, value in superset_condition.items(): <NEW_LINE> <INDENT> if not hasattr(self, key): <NEW_LINE> <INDENT> setattr(self, key, value)
Represent environmental parameters that are constant in time. Conditions (subclass of AttrDict) group environemental parameters of individual boxes or the whole BoxModelSystem. Conditions are constants. That means that they are assumed to not change in time and that their values must not be callables. Args: dict or **kwargs: keys must be valid python variable names, values must not be callables.
6259903615baa723494630eb
class HttpEquiv(HtmlTagAttribute): <NEW_LINE> <INDENT> belongs_to = ['Meta']
Provides an HTTP header for the information/value of the content attribute
6259903694891a1f408b9fa1
class EventStatus(externals.atom.core.XmlElement): <NEW_LINE> <INDENT> _qname = GDATA_TEMPLATE % 'eventStatus' <NEW_LINE> value = 'value'
The gd:eventStatus element.
62599036d18da76e235b79f7
class RegisterHandler(BaseHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> mobile = self.json_args.get("mobile") <NEW_LINE> sms_code = self.json_args.get("phonecode") <NEW_LINE> password = self.json_args.get("password") <NEW_LINE> if not all([mobile, sms_code, password]): <NEW_LINE> <INDENT> return self.write({"errno": RET.PARAMERR, "errmsg": "参数错误"}) <NEW_LINE> <DEDENT> if not re.match(r"^1\d{10}$", mobile): <NEW_LINE> <INDENT> return self.write({"errno": RET.PARAMERR, "errmsg": "手机号格式错误"}) <NEW_LINE> <DEDENT> if "2468" != sms_code: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> real_code = self.redis.get("SMSCode" + mobile) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> return self.write(dict(errno=RET.DBERR, errmsg="读取验证码异常")) <NEW_LINE> <DEDENT> if not real_code: <NEW_LINE> <INDENT> return self.write(dict(errno=RET.PARAMERR, errmsg="验证码过期")) <NEW_LINE> <DEDENT> if real_code != str(sms_code): <NEW_LINE> <INDENT> return self.write({"errno": RET.PARAMERR, "errmsg": "验证码无效!"}) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.redis.delete("SMSCode" % mobile) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> <DEDENT> <DEDENT> password = hashlib.sha256(password + config.passwd_hash_key).hexdigest() <NEW_LINE> sql = "insert into ih_user_profile(up_name,up_mobile,up_passwd) values(%(name)s,%(mobile)s,%(passwd)s)" <NEW_LINE> try: <NEW_LINE> <INDENT> user_id = self.db.execute(sql, name=mobile, mobile=mobile, passwd=password) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> return self.write({"errno": RET.DATAEXIST, "errmsg": "手机号已注册!"}) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> session = Session(self) <NEW_LINE> session.data['user_id'] = user_id <NEW_LINE> session.data['name'] = mobile <NEW_LINE> session.data['mobile'] = mobile <NEW_LINE> session.save() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> <DEDENT> self.write({"errno": RET.OK, "errmsg": "OK"})
注册
62599036b57a9660fecd2bcc
@attr.s <NEW_LINE> class RowPanel(Panel): <NEW_LINE> <INDENT> collapsed = attr.ib(default=False, validator=instance_of(bool)) <NEW_LINE> panels = attr.ib(default=attr.Factory(list), validator=instance_of(list)) <NEW_LINE> collapsed = attr.ib(default=False, validator=instance_of(bool)) <NEW_LINE> def _iter_panels(self): <NEW_LINE> <INDENT> return iter(self.panels) <NEW_LINE> <DEDENT> def _map_panels(self, f): <NEW_LINE> <INDENT> self = f(self) <NEW_LINE> return attr.evolve(self, panels=list(map(f, self.panels))) <NEW_LINE> <DEDENT> def to_json_data(self): <NEW_LINE> <INDENT> return self.panel_json( { 'collapsed': self.collapsed, 'panels': self.panels, 'type': ROW_TYPE } )
Generates Row panel json structure. :param title: title of the panel :param collapsed: set True if row should be collapsed :param panels: list of panels in the row, only to be used when collapsed=True
62599036c432627299fa4148
class TestMachinesPkView(APITestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.url = reverse(transitionscbv_machines_pk, args=('matter',)) <NEW_LINE> <DEDENT> def test_get_request_succeeds(self): <NEW_LINE> <INDENT> response = self.client.get(self.url) <NEW_LINE> eq_(response.status_code, 200) <NEW_LINE> <DEDENT> def test_options_request_succeeds(self): <NEW_LINE> <INDENT> response = self.client.options(self.url) <NEW_LINE> eq_(response.status_code, 200) <NEW_LINE> <DEDENT> def test_put_request_fails(self): <NEW_LINE> <INDENT> response = self.client.put(self.url) <NEW_LINE> eq_(response.status_code, 405) <NEW_LINE> <DEDENT> def test_delete_request_fails(self): <NEW_LINE> <INDENT> response = self.client.delete(self.url) <NEW_LINE> eq_(response.status_code, 405) <NEW_LINE> <DEDENT> def test_post_request_with_no_data_fails(self): <NEW_LINE> <INDENT> response = self.client.post(self.url, {}) <NEW_LINE> eq_(response.status_code, 405)
Tests the transitionscbv_machines_pk FBV.
6259903616aa5153ce40163d
class VehicleStatsDecorationsBatteryMilliVolts(object): <NEW_LINE> <INDENT> openapi_types = { 'value': 'int' } <NEW_LINE> attribute_map = { 'value': 'value' } <NEW_LINE> def __init__(self, value=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._value = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and value is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `value`, must not be `None`") <NEW_LINE> <DEDENT> self._value = value <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VehicleStatsDecorationsBatteryMilliVolts): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VehicleStatsDecorationsBatteryMilliVolts): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
625990360a366e3fb87ddb38
class TableOfContents(Report): <NEW_LINE> <INDENT> def __init__(self, database, options, user): <NEW_LINE> <INDENT> Report.__init__(self, database, options, user) <NEW_LINE> self._user = user <NEW_LINE> menu = options.menu <NEW_LINE> <DEDENT> def write_report(self): <NEW_LINE> <INDENT> self.doc.insert_toc()
This report class generates a table of contents for a book.
62599036be383301e0254967
class JSONBiserialisable(JSONSerialisable, JSONDeserialisable[SelfType], ABC): <NEW_LINE> <INDENT> @ensure_error_type(JSONSerialisationError, "Error copying object using JSON serialisation: {0}") <NEW_LINE> def json_copy(self, validate: bool = True) -> SelfType: <NEW_LINE> <INDENT> return self.from_raw_json(self.to_raw_json(validate), False)
Interface for classes which implement both JSONSerialisable and JSONDeserialisable[T].
62599036287bf620b6272d3b
class Client(object): <NEW_LINE> <INDENT> def __init__(self, config=None, create_data_service_auth=DataServiceAuth): <NEW_LINE> <INDENT> if not config: <NEW_LINE> <INDENT> config = create_config() <NEW_LINE> <DEDENT> self.dds_connection = DDSConnection(config, create_data_service_auth) <NEW_LINE> <DEDENT> def get_projects(self): <NEW_LINE> <INDENT> return self.dds_connection.get_projects() <NEW_LINE> <DEDENT> def get_project_by_id(self, project_id): <NEW_LINE> <INDENT> return self.dds_connection.get_project_by_id(project_id) <NEW_LINE> <DEDENT> def get_project_by_name(self, project_name): <NEW_LINE> <INDENT> projects = [project for project in self.get_projects() if project.name == project_name] <NEW_LINE> if not projects: <NEW_LINE> <INDENT> raise ItemNotFound("No project named {} found.".format(project_name)) <NEW_LINE> <DEDENT> if len(projects) != 1: <NEW_LINE> <INDENT> raise DDSUserException("Multiple projects found with name {}.".format(project_name)) <NEW_LINE> <DEDENT> return projects[0] <NEW_LINE> <DEDENT> def create_project(self, name, description): <NEW_LINE> <INDENT> return self.dds_connection.create_project(name, description) <NEW_LINE> <DEDENT> def get_folder_by_id(self, folder_id): <NEW_LINE> <INDENT> return self.dds_connection.get_folder_by_id(folder_id) <NEW_LINE> <DEDENT> def get_file_by_id(self, file_id): <NEW_LINE> <INDENT> return self.dds_connection.get_file_by_id(file_id) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.dds_connection.close()
Client that connects to the DDSConnection base on ~/.ddsclient configuration. This configuration can be customized by passing in a ddsc.config.Config object
62599036a4f1c619b294f730
class JavaWriter(object): <NEW_LINE> <INDENT> OPEN_GROUPERS = ("(", "{", "[") <NEW_LINE> CLOSE_GROUPERS = (")", "}", "]") <NEW_LINE> INDENT_SIZE = 4 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.grouper_stack = [] <NEW_LINE> self.code_base = [] <NEW_LINE> self.current_indent_count = 0 <NEW_LINE> <DEDENT> def add_line(self, line): <NEW_LINE> <INDENT> code_line = line.strip() <NEW_LINE> if code_line == "": <NEW_LINE> <INDENT> self.code_base.append(code_line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for token in code_line: <NEW_LINE> <INDENT> if token in JavaWriter.OPEN_GROUPERS: <NEW_LINE> <INDENT> self.grouper_stack.insert(0, token) <NEW_LINE> <DEDENT> elif token in JavaWriter.CLOSE_GROUPERS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> match = self.grouper_stack.pop() <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise JavaSyntaxError(code_line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if code_line[len(code_line) - 1] in JavaWriter.CLOSE_GROUPERS: <NEW_LINE> <INDENT> self.current_indent_count -= 4 <NEW_LINE> <DEDENT> indent = " " * self.current_indent_count <NEW_LINE> self.code_base.append(indent + code_line) <NEW_LINE> if code_line[len(code_line) - 1] in JavaWriter.OPEN_GROUPERS: <NEW_LINE> <INDENT> self.current_indent_count += 4 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n".join(self.code_base)
Write you those Java strings. Features "syntax check" as - brace matching - auto indent
6259903673bcbd0ca4bcb3d9
class MadstError(Exception): <NEW_LINE> <INDENT> def __init__(self, str): <NEW_LINE> <INDENT> super().__init__(str)
Base class
6259903630c21e258be9995e
class Event(Item): <NEW_LINE> <INDENT> tag = "VEVENT"
Internal event class.
62599036d4950a0f3b1116e8
class InternalEntityServiceServicer(object): <NEW_LINE> <INDENT> def CreateEntityType(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def UpdateEntityType(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Manages entity types in the Data API, for internal usage. This service is deprecated and replaced by the corresponding operations in EntityService.
62599036b830903b9686ed22
class DistanceMatrix(object): <NEW_LINE> <INDENT> __api_urls = { "base" : "https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?" } <NEW_LINE> __distance_matrix = [] <NEW_LINE> __response = {} <NEW_LINE> __last_requested = [] <NEW_LINE> __number_of_requests_saved = 0 <NEW_LINE> __number_of_requests_made = 0 <NEW_LINE> @staticmethod <NEW_LINE> def get_matrix(geocodes:list, api_key:str, key='travelDistance', travelMode='driving') -> list: <NEW_LINE> <INDENT> if key not in ["travelDistance", "travelDuration"]: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> response = DistanceMatrix.__request_matrix(geocodes=geocodes, api_key=api_key, travelMode=travelMode) <NEW_LINE> grid = DistanceMatrix.__build_matrix(geocodes=geocodes, response=response) <NEW_LINE> matrix = [] <NEW_LINE> for row in grid: <NEW_LINE> <INDENT> matrix.append([x[key] for x in row]) <NEW_LINE> <DEDENT> return (matrix) <NEW_LINE> <DEDENT> def __identical_list(list1: list, list2: list) -> bool: <NEW_LINE> <INDENT> return (len(set(list1) - set(list2)) == 0 and len(set(list2) - set(list1)) == 0) <NEW_LINE> <DEDENT> def __build_matrix(geocodes:list, response:requests.Response) -> list: <NEW_LINE> <INDENT> matrix = [] <NEW_LINE> if len(response) > 0 and ('statusCode' in response.keys() and response['statusCode'] == 200): <NEW_LINE> <INDENT> row = [] <NEW_LINE> for counter, item in enumerate(response["resourceSets"][0]['resources'][0]['results']): <NEW_LINE> <INDENT> keys_of_interest = ["travelDistance", "travelDuration"] <NEW_LINE> result = {key : item[key] for key in keys_of_interest} <NEW_LINE> row.append(result) <NEW_LINE> if (counter + 1) % len(geocodes) == 0: <NEW_LINE> <INDENT> matrix.append(row) <NEW_LINE> row = [] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if len(response) > 0 and ('statusCode' in response.keys()): <NEW_LINE> <INDENT> print(f"Execution stopped with HTTP code {response['statusCode']} {response['statusDescription']}") <NEW_LINE> <DEDENT> <DEDENT> return matrix <NEW_LINE> <DEDENT> def __request_matrix(geocodes:list, api_key:str, travelMode:str) -> requests.Response: <NEW_LINE> <INDENT> DistanceMatrix.__number_of_requests_made += 1 <NEW_LINE> condition1 = len(DistanceMatrix.__response) == 0 or DistanceMatrix.__response['statusCode'] != 200 <NEW_LINE> condition2 = not(DistanceMatrix.__identical_list(DistanceMatrix.__last_requested, geocodes)) <NEW_LINE> if condition1 or condition2: <NEW_LINE> <INDENT> DistanceMatrix.__last_requested = geocodes <NEW_LINE> parameters = { "origins": '; '.join(geocodes), "destinations" : '; '.join(geocodes), "travelMode" : travelMode, "key" : api_key } <NEW_LINE> url = DistanceMatrix.__api_urls['base'] <NEW_LINE> response = requests.get(url, params=parameters) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> DistanceMatrix.__response = response.json() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> DistanceMatrix.__number_of_requests_saved += 1 <NEW_LINE> <DEDENT> return DistanceMatrix.__response
This class defines the mechanics for requesting a distance/duration matrix from a set of locations. This implementation relies on Microsoft Bing Maps DistanceMatrix API. A distance/duration can be requested by simply running the following line: Typical usage example: matrix = DistanceMatrix.get_matrix(geocodes, 'travelDistance', 'driving') Attributes: None. More information about the Bing Maps DistanceMatrix API can be found here:
62599036b57a9660fecd2bce
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class KeyManager(object): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def create_key(self, ctxt, algorithm='AES', length=256, expiration=None, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def store_key(self, ctxt, key, expiration=None, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def copy_key(self, ctxt, key_id, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_key(self, ctxt, key_id, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def delete_key(self, ctxt, key_id, **kwargs): <NEW_LINE> <INDENT> pass
Base Key Manager Interface A Key Manager is responsible for managing encryption keys for volumes. A Key Manager is responsible for creating, reading, and deleting keys.
62599036e76e3b2f99fd9b5f
class HardNegativePairSelector(PairSelector): <NEW_LINE> <INDENT> def __init__(self, cpu=True): <NEW_LINE> <INDENT> super(HardNegativePairSelector, self).__init__() <NEW_LINE> self.cpu = cpu <NEW_LINE> <DEDENT> def get_pairs(self, embeddings, labels): <NEW_LINE> <INDENT> if self.cpu: <NEW_LINE> <INDENT> embeddings = embeddings.cpu() <NEW_LINE> <DEDENT> distance_matrix = pdist(embeddings.data) <NEW_LINE> labels = labels.cpu().data.numpy() <NEW_LINE> all_pairs = np.array(list(combinations(range(len(labels)), 2))) <NEW_LINE> all_pairs = torch.LongTensor(all_pairs) <NEW_LINE> positive_pairs = all_pairs[(labels[all_pairs[:, 0]] == labels[all_pairs[:, 1]]).nonzero()] <NEW_LINE> negative_pairs = all_pairs[(labels[all_pairs[:, 0]] != labels[all_pairs[:, 1]]).nonzero()] <NEW_LINE> negative_distances = distance_matrix[negative_pairs[:, 0], negative_pairs[:, 1]] <NEW_LINE> negative_distances = negative_distances.cpu().data.numpy() <NEW_LINE> top_negatives = np.argpartition(negative_distances, len(positive_pairs))[:len(positive_pairs)] <NEW_LINE> top_negative_pairs = negative_pairs[torch.LongTensor(top_negatives)] <NEW_LINE> return positive_pairs, top_negative_pairs
Creates all possible positive pairs. For negative pairs, pairs with smallest distance are taken into consideration, matching the number of positive pairs.
625990361f5feb6acb163d45
class WebFunction(object): <NEW_LINE> <INDENT> def __init__(self, func, name, args, return_value, print_name=''): <NEW_LINE> <INDENT> super(WebFunction, self).__init__() <NEW_LINE> self.func = func <NEW_LINE> self.name = name <NEW_LINE> self.args = args or [] <NEW_LINE> for arg in self.args: <NEW_LINE> <INDENT> if arg.parent is not None: <NEW_LINE> <INDENT> raise ValueError( "The Argument is already associated to another WebFunction (%s)" % arg.parent.name) <NEW_LINE> <DEDENT> arg.parent = weakref.proxy(self) <NEW_LINE> <DEDENT> self.return_value = return_value <NEW_LINE> self.help_message = format_doc(func.__doc__) <NEW_LINE> self._print_name = print_name <NEW_LINE> <DEDENT> def arg_names(self): <NEW_LINE> <INDENT> return [arg.name for arg in self.args] <NEW_LINE> <DEDENT> @property <NEW_LINE> def print_name(self): <NEW_LINE> <INDENT> return self._print_name or format_name(self.name)
A function to be published on the web UI
6259903650485f2cf55dc0d2
class ListVirtualHubsResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualHub]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ListVirtualHubsResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None)
Result of the request to list VirtualHubs. It contains a list of VirtualHubs and a URL nextLink to get the next set of results. :param value: List of VirtualHubs. :type value: list[~azure.mgmt.network.v2018_11_01.models.VirtualHub] :param next_link: URL to get the next set of operation list results if there are any. :type next_link: str
6259903630c21e258be99960
class TestAnonymousId(PloneSurveyTestCase): <NEW_LINE> <INDENT> def afterSetUp(self): <NEW_LINE> <INDENT> self.createSubSurvey() <NEW_LINE> <DEDENT> def testAnonymousIdGeneration(self): <NEW_LINE> <INDENT> s1 = getattr(self, 's1') <NEW_LINE> now = DateTime() <NEW_LINE> self.logout() <NEW_LINE> userid = s1.getSurveyId() <NEW_LINE> expected_userid = 'Anonymous' + '@' + str(now) <NEW_LINE> assert userid[:-9] == expected_userid[:-9], "Anonymous id generation not working - %s" % userid
Ensure anonymous id is correctly constructed
6259903630c21e258be99961
class Disk(_messages.Message): <NEW_LINE> <INDENT> class TypeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> TYPE_UNSPECIFIED = 0 <NEW_LINE> PERSISTENT_HDD = 1 <NEW_LINE> PERSISTENT_SSD = 2 <NEW_LINE> LOCAL_SSD = 3 <NEW_LINE> <DEDENT> autoDelete = _messages.BooleanField(1) <NEW_LINE> name = _messages.StringField(2) <NEW_LINE> readOnly = _messages.BooleanField(3) <NEW_LINE> sizeGb = _messages.IntegerField(4) <NEW_LINE> source = _messages.StringField(5) <NEW_LINE> type = _messages.EnumField('TypeValueValuesEnum', 6)
A Google Compute Engine disk resource specification. Enums: TypeValueValuesEnum: The type of the disk to create, if applicable. Fields: autoDelete: Specifies whether or not to delete the disk when the pipeline completes. This field is applicable only for newly created disks. See ht tps://cloud.google.com/compute/docs/reference/latest/instances#resource for more details. name: Required. The name of the disk that can be used in the pipeline parameters. Must be 1 - 63 characters and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? readOnly: Specifies how a sourced-base persistent disk will be mounted. See https://cloud.google.com/compute/docs/disks/persistent- disks#use_multi_instances for more details. sizeGb: The size of the disk. This field is not applicable for local SSD. source: The full or partial URL of the persistent disk to attach. See https://cloud.google.com/compute/docs/reference/latest/instances#resourc e and https://cloud.google.com/compute/docs/disks/persistent- disks#snapshots for more details. type: The type of the disk to create, if applicable.
625990368c3a8732951f76ad
class TfidfVectorizer(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.base_path = os.path.dirname(__file__) <NEW_LINE> self.dictionary_path = os.path.join(self.base_path, "dictionary") <NEW_LINE> self.tf_idf_model_path = os.path.join(self.base_path, "tfidf") <NEW_LINE> self.stemmer = NepStemmer() <NEW_LINE> self.tf_idf_model = None <NEW_LINE> <DEDENT> def get_tokens(self, document): <NEW_LINE> <INDENT> if not self.stemmer: <NEW_LINE> <INDENT> raise Exception("Stemmer not available") <NEW_LINE> <DEDENT> return self.stemmer.get_stems(document) <NEW_LINE> <DEDENT> def construct_model(self, documents): <NEW_LINE> <INDENT> logging.basicConfig( format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO ) <NEW_LINE> logging.info("Obtaining word tokens") <NEW_LINE> tokens = [self.get_tokens(document) for document in documents] <NEW_LINE> logging.info("Constructing dictionary") <NEW_LINE> self.dictionary = Dictionary(tokens) <NEW_LINE> self.dictionary.filter_extremes(no_below=5, no_above=0.5, keep_n=1000) <NEW_LINE> self.dictionary.compactify() <NEW_LINE> self.dictionary.save(self.dictionary_path) <NEW_LINE> logging.info("Constructing TF-IDF model") <NEW_LINE> self.tf_idf_model = TfidfModel(dictionary=self.dictionary) <NEW_LINE> self.tf_idf_model.save(self.tf_idf_model_path) <NEW_LINE> <DEDENT> def load_data(self): <NEW_LINE> <INDENT> if not self.tf_idf_model: <NEW_LINE> <INDENT> if not os.path.exists(self.tf_idf_model_path): <NEW_LINE> <INDENT> raise Exception('TF-IDF model file not found') <NEW_LINE> <DEDENT> self.dictionary = Dictionary.load(self.dictionary_path) <NEW_LINE> self.tf_idf_model = TfidfModel.load(self.tf_idf_model_path) <NEW_LINE> <DEDENT> <DEDENT> def doc2vector(self, document): <NEW_LINE> <INDENT> tokens = self.get_tokens(document) <NEW_LINE> bag_of_words = self.dictionary.doc2bow(tokens) <NEW_LINE> return (self.tf_idf_model[bag_of_words]) <NEW_LINE> <DEDENT> def obtain_feature_vector(self, document): <NEW_LINE> <INDENT> self.load_data() <NEW_LINE> tf_idf_vector = matutils.sparse2full( self.doc2vector(document), self.no_of_features ).reshape(1, -1) <NEW_LINE> return tf_idf_vector <NEW_LINE> <DEDENT> def obtain_feature_matrix(self, documents): <NEW_LINE> <INDENT> self.load_data() <NEW_LINE> input_matrix_sparse = [ self.doc2vector(x) for x in documents ] <NEW_LINE> no_of_features = len(self.tf_idf_model.idfs) <NEW_LINE> input_matrix = matutils.corpus2dense( input_matrix_sparse, no_of_features ).transpose() <NEW_LINE> return input_matrix
Transform text to tf-idf representation
625990365e10d32532ce41ad