code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class HyperVReplicaAzureEventDetails(EventProviderSpecificDetails): <NEW_LINE> <INDENT> _validation = { 'instance_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'instance_type': {'key': 'instanceType', 'type': 'str'}, 'container_name': {'key': 'containerName', 'type': 'str'}, 'fabric_name': {'key': 'fabricName', 'type': 'str'}, 'remote_container_name': {'key': 'remoteContainerName', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(HyperVReplicaAzureEventDetails, self).__init__(**kwargs) <NEW_LINE> self.instance_type = 'HyperVReplicaAzure' <NEW_LINE> self.container_name = kwargs.get('container_name', None) <NEW_LINE> self.fabric_name = kwargs.get('fabric_name', None) <NEW_LINE> self.remote_container_name = kwargs.get('remote_container_name', None) | Model class for event details of a HyperVReplica E2A event.
All required parameters must be populated in order to send to Azure.
:param instance_type: Required. Gets the class type. Overridden in derived classes.Constant
filled by server.
:type instance_type: str
:param container_name: The container friendly name.
:type container_name: str
:param fabric_name: The fabric friendly name.
:type fabric_name: str
:param remote_container_name: The remote container name.
:type remote_container_name: str | 6259906d2ae34c7f260ac92d |
class ConsumerAction(object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, action_str, params=None, try_num=0, max_try_num=0): <NEW_LINE> <INDENT> self.action_str = action_str <NEW_LINE> self.params = params <NEW_LINE> self.try_num = try_num <NEW_LINE> self.max_try_num = max_try_num <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.action() <NEW_LINE> self.success() <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.fail() <NEW_LINE> log.getConsumerLog().exception("consumerAction exception...") <NEW_LINE> <DEDENT> <DEDENT> @abstractmethod <NEW_LINE> def action(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def success(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def fail(self): <NEW_LINE> <INDENT> pass | python中没有像java的抽象方法一说,所以这里定义的方法只是告诉继承该类的子类
需要实现哪些方法,类似定义了一个约束
这里为了实现类似java抽象方法,使用了abc库 | 6259906d2c8b7c6e89bd502b |
class ImageIter(mx.io.DataIter): <NEW_LINE> <INDENT> def __init__(self, data_root, data_list, batch_size, data_shape, num_label, name=None): <NEW_LINE> <INDENT> super(ImageIter, self).__init__() <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.data_shape = data_shape <NEW_LINE> self.num_label = num_label <NEW_LINE> self.data_root = data_root <NEW_LINE> self.dataset_lst_file = open(data_list) <NEW_LINE> self.provide_data = [('data', (batch_size, 1, data_shape[1], data_shape[0]))] <NEW_LINE> self.provide_label = [('label', (self.batch_size, self.num_label))] <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> data = [] <NEW_LINE> label = [] <NEW_LINE> cnt = 0 <NEW_LINE> for m_line in self.dataset_lst_file: <NEW_LINE> <INDENT> img_lst = m_line.strip().split(' ') <NEW_LINE> img_path = os.path.join(self.data_root, img_lst[0]) <NEW_LINE> cnt += 1 <NEW_LINE> img = Image.open(img_path).resize(self.data_shape, Image.BILINEAR).convert('L') <NEW_LINE> img = np.array(img).reshape((1, self.data_shape[1], self.data_shape[0])) <NEW_LINE> data.append(img) <NEW_LINE> ret = np.zeros(self.num_label, int) <NEW_LINE> for idx in range(1, len(img_lst)): <NEW_LINE> <INDENT> ret[idx-1] = int(img_lst[idx]) <NEW_LINE> <DEDENT> label.append(ret) <NEW_LINE> if cnt % self.batch_size == 0: <NEW_LINE> <INDENT> data_all = [mx.nd.array(data)] <NEW_LINE> label_all = [mx.nd.array(label)] <NEW_LINE> data_names = ['data'] <NEW_LINE> label_names = ['label'] <NEW_LINE> data.clear() <NEW_LINE> label.clear() <NEW_LINE> yield SimpleBatch(data_names, data_all, label_names, label_all) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> if self.dataset_lst_file.seekable(): <NEW_LINE> <INDENT> self.dataset_lst_file.seek(0) | Iterator class for generating captcha image data | 6259906d23849d37ff8528f9 |
class MissingSConscriptWarning(Exception): <NEW_LINE> <INDENT> pass | Fake MissingSConscriptWarning | 6259906d5fcc89381b266d79 |
class Assigment(Node): <NEW_LINE> <INDENT> def __init__(self, value, children): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.children = children <NEW_LINE> self.id = Node.newID() <NEW_LINE> <DEDENT> def evaluate(self, st): <NEW_LINE> <INDENT> _, declared_type, offset = st.getter(self.children[0].value) <NEW_LINE> child_value, child_type = self.children[1].evaluate(st) <NEW_LINE> st.setter(self.children[0].value, child_value, child_type) <NEW_LINE> Assembler.write_line("MOV [EBP-{}], EBX ; {} = {} ".format(offset, self.children[0].value, child_value)) | Value: "="
Children: [Identifier (String), Value (Boolean or Int)]
Usage: Assigment("=", [identifier, Parser.parseRelExpression()]) | 6259906dac7a0e7691f73d2c |
class CTLBB6OrbitInputForm(FlaskForm): <NEW_LINE> <INDENT> orbit = IntegerField( 'Orbit', ) <NEW_LINE> star = StringField( 'Star', validators=[Optional(), Regexp(STAR_REGEXP)] ) <NEW_LINE> submit = SubmitField('Submit') <NEW_LINE> def validate_orbit(self, field): <NEW_LINE> <INDENT> if isinstance(field.data, int): <NEW_LINE> <INDENT> if int(field.data) not in range(0, 20): <NEW_LINE> <INDENT> raise ValidationError( 'Invalid value for orbit (must be in range 0-19)' ) | Input form for CT LBB6 orbit | 6259906da17c0f6771d5d7cb |
class LxPs(gdb.Command): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LxPs, self).__init__("lx-ps", gdb.COMMAND_DATA) <NEW_LINE> <DEDENT> def invoke(self, arg, from_tty): <NEW_LINE> <INDENT> for task in task_lists(): <NEW_LINE> <INDENT> thread_info = task["stack"].cast(thread_info_type.get_type().pointer()) <NEW_LINE> gdb.write("{address} {pid} 0x{tid:02x} {comm}\n".format( address=task, pid=task["pid"], tid=int(thread_info["tid"]), comm=task["comm"].string())) | Dump Linux tasks. | 6259906df548e778e596cdd2 |
class TestNonMatchingFaultInjection(xds_url_map_testcase.XdsUrlMapTestCase): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def client_init_config(rpc: str, metadata: str): <NEW_LINE> <INDENT> return 'EmptyCall', metadata <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def url_map_change( host_rule: HostRule, path_matcher: PathMatcher) -> Tuple[HostRule, PathMatcher]: <NEW_LINE> <INDENT> path_matcher["routeRules"] = [ _build_fault_injection_route_rule(abort_percentage=100, delay_percentage=100) ] <NEW_LINE> return host_rule, path_matcher <NEW_LINE> <DEDENT> def xds_config_validate(self, xds_config: DumpedXdsConfig): <NEW_LINE> <INDENT> self.assertNumEndpoints(xds_config, 1) <NEW_LINE> self.assertEqual( "/grpc.testing.TestService/UnaryCall", xds_config.rds['virtualHosts'][0]['routes'][0]['match']['path']) <NEW_LINE> filter_config = xds_config.rds['virtualHosts'][0]['routes'][0][ 'typedPerFilterConfig']['envoy.filters.http.fault'] <NEW_LINE> self.assertEqual('20s', filter_config['delay']['fixedDelay']) <NEW_LINE> self.assertEqual(1000000, filter_config['delay']['percentage']['numerator']) <NEW_LINE> self.assertEqual('MILLION', filter_config['delay']['percentage']['denominator']) <NEW_LINE> self.assertEqual(401, filter_config['abort']['httpStatus']) <NEW_LINE> self.assertEqual(1000000, filter_config['abort']['percentage']['numerator']) <NEW_LINE> self.assertEqual('MILLION', filter_config['abort']['percentage']['denominator']) <NEW_LINE> self.assertNotIn( 'envoy.filters.http.fault', xds_config.rds['virtualHosts'][0]['routes'][1].get( 'typedPerFilterConfig', {})) <NEW_LINE> <DEDENT> def rpc_distribution_validate(self, test_client: XdsTestClient): <NEW_LINE> <INDENT> self.assertRpcStatusCode(test_client, expected=(ExpectedResult( rpc_type=RpcTypeEmptyCall, status_code=grpc.StatusCode.OK, ratio=1),), length=_LENGTH_OF_RPC_SENDING_SEC, tolerance=_NON_RANDOM_ERROR_TOLERANCE) | EMPTY_CALL is not fault injected, so it should succeed. | 6259906da219f33f346c804d |
class ImageVisualizationBase(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> @abc.abstractmethod <NEW_LINE> def save(local_path, cluster_hdfs_path): <NEW_LINE> <INDENT> return | Abstract for image visualization | 6259906d71ff763f4b5e8fec |
class DispatchContext(object): <NEW_LINE> <INDENT> current = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._old_ctx = DispatchContext.current <NEW_LINE> <DEDENT> def query(self, target, workload_key, has_complex_op, dag, func_name): <NEW_LINE> <INDENT> ret = self._query_inside(target, workload_key, func_name) <NEW_LINE> if ret is None: <NEW_LINE> <INDENT> ret = self._old_ctx.query(target, workload_key, has_complex_op, dag, func_name) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def update(self, target, workload_key, state): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _query_inside(self, target, workload_key, func_name): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._old_ctx = DispatchContext.current <NEW_LINE> DispatchContext.current = self <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, ptype, value, trace): <NEW_LINE> <INDENT> DispatchContext.current = self._old_ctx | Base class of dispatch context. | 6259906d7047854f46340bfb |
class VerifyVersionCommand(install): <NEW_LINE> <INDENT> description = "verify that the git tag matches our version" <NEW_LINE> def run(self): <NEW_LINE> <INDENT> tag = os.getenv("CIRCLE_TAG") <NEW_LINE> if tag.lstrip("v") != VERSION: <NEW_LINE> <INDENT> info = f"Git tag: {tag} does not match the version of this app: {VERSION}".format( tag, VERSION ) <NEW_LINE> sys.exit(info) | Custom command to verify that the git tag matches our version | 6259906d009cb60464d02d7a |
@python_2_unicode_compatible <NEW_LINE> class RackReservation(models.Model): <NEW_LINE> <INDENT> rack = models.ForeignKey('Rack', related_name='reservations', editable=False, on_delete=models.CASCADE) <NEW_LINE> units = ArrayField(models.PositiveSmallIntegerField()) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> user = models.ForeignKey(User, editable=False, on_delete=models.PROTECT) <NEW_LINE> description = models.CharField(max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['created'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return u"Reservation for rack {}".format(self.rack) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if self.units: <NEW_LINE> <INDENT> invalid_units = [u for u in self.units if u not in self.rack.units] <NEW_LINE> if invalid_units: <NEW_LINE> <INDENT> raise ValidationError({ 'units': u"Invalid unit(s) for {}U rack: {}".format( self.rack.u_height, ', '.join([str(u) for u in invalid_units]), ), }) <NEW_LINE> <DEDENT> reserved_units = [] <NEW_LINE> for resv in self.rack.reservations.exclude(pk=self.pk): <NEW_LINE> <INDENT> reserved_units += resv.units <NEW_LINE> <DEDENT> conflicting_units = [u for u in self.units if u in reserved_units] <NEW_LINE> if conflicting_units: <NEW_LINE> <INDENT> raise ValidationError({ 'units': 'The following units have already been reserved: {}'.format( ', '.join([str(u) for u in conflicting_units]), ) }) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def unit_list(self): <NEW_LINE> <INDENT> group = (list(x) for _, x in groupby(sorted(self.units), lambda x, c=count(): next(c) - x)) <NEW_LINE> return ', '.join('-'.join(map(str, (g[0], g[-1])[:len(g)])) for g in group) | One or more reserved units within a Rack. | 6259906d4428ac0f6e659d78 |
class Im(EmailImParent): <NEW_LINE> <INDENT> _qname = GDATA_TEMPLATE % 'im' <NEW_LINE> protocol = 'protocol' | The gd:im element.
An instant messaging address associated with the containing entity. | 6259906d16aa5153ce401d1f |
class FinalError(RuntimeError): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message | This error is raised when you assign to a final variable | 6259906d4e4d562566373c4c |
class Entities(CollectionBase): <NEW_LINE> <INDENT> find_valid_constrains = ['format','offset','limit','order_by', 'application','entity',] <NEW_LINE> findOne_valid_constrains = ['format', 'id'] <NEW_LINE> def __init__(self, key,secret,host,app_id): <NEW_LINE> <INDENT> self.consumer_key = key <NEW_LINE> self.consumer_secret = secret <NEW_LINE> self.host = host <NEW_LINE> self.app_id= app_id <NEW_LINE> self.next_url = None <NEW_LINE> self.previous_url = None <NEW_LINE> <DEDENT> def find(self, params={}): <NEW_LINE> <INDENT> if self.app_id: <NEW_LINE> <INDENT> params['application'] = self.app_id <NEW_LINE> <DEDENT> meta, items = self._find('entity' ,params) <NEW_LINE> entities=[] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> entity = Entity(self.consumer_key, self.consumer_secret, self.host, item) <NEW_LINE> entities.append(entity) <NEW_LINE> <DEDENT> return meta, entities <NEW_LINE> <DEDENT> def findOne(self, entity_id, params={}): <NEW_LINE> <INDENT> if self.app_id: <NEW_LINE> <INDENT> params['application'] = self.app_id <NEW_LINE> <DEDENT> item = self._findOne('entity',entity_id, params) <NEW_LINE> entity = Entity(self.consumer_key, self.consumer_secret, self.host,item) <NEW_LINE> return entity <NEW_LINE> <DEDENT> def new(self): <NEW_LINE> <INDENT> entity = Entity(self.consumer_key,self.consumer_secret,self.host) <NEW_LINE> entity.application = self.app_id <NEW_LINE> return entity <NEW_LINE> <DEDENT> def delete(self, entity_id): <NEW_LINE> <INDENT> entity = self.findOne(entity_id) <NEW_LINE> if int(self.app_id) == int(entity.application): <NEW_LINE> <INDENT> return entity.delete() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ErrorPermission("can not perform delete for non owner") | find() Return collection of Activity
** parameter application is required
** parameter deleted is to filter not-deleted app. | 6259906d283ffb24f3cf50ee |
class ArticlePeopleRelationship(Orderable, models.Model): <NEW_LINE> <INDENT> article = ParentalKey( 'ArticlePage', related_name='article_author_relationship' ) <NEW_LINE> author = models.ForeignKey( 'base.Author', related_name='author_article_relationship' ) <NEW_LINE> panels = [ SnippetChooserPanel('author') ] | This defines the relationship between the `People` within the `base`
app and the BlogPage below. This allows People to be added to a BlogPage.
We have created a two way relationship between BlogPage and People using
the ParentalKey and ForeignKey | 6259906de76e3b2f99fda247 |
class Card(ListableAPIResource, CreateableAPIResource, UpdateableAPIResource, DeletableAPIResource): <NEW_LINE> <INDENT> @property <NEW_LINE> def required_create_params(self): <NEW_LINE> <INDENT> return [ {'name': 'allowance', 'type': Allowance}, {'name': 'description', 'type': str}, {'name': 'is_virtual', 'type': bool} ] | Emburse Card Resource
API DOC: https://www.emburse.com/api/v1/docs#card | 6259906d8a43f66fc4bf39da |
class Thread(HFAsk): <NEW_LINE> <INDENT> fid: str <NEW_LINE> subject: str <NEW_LINE> message: str <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "threads" | Create a thread on a subforum | 6259906da17c0f6771d5d7cc |
class AdderTimetable: <NEW_LINE> <INDENT> def __init__( self, db_conn: 'asyncpg.Connection', status_handler: 'AbstractStatusTimetableHandler' ): <NEW_LINE> <INDENT> self.db_conn = db_conn <NEW_LINE> self.db = Database(self.db_conn) <NEW_LINE> self.status_handler = status_handler <NEW_LINE> <DEDENT> async def add_timetable_from_structure(self, timetable: 'uaviak_parser.structures.Timetable') -> None: <NEW_LINE> <INDENT> is_exist = await self.db.is_exist_timetable(timetable.date) <NEW_LINE> if is_exist: <NEW_LINE> <INDENT> self.status_handler.add_timetable_error(TimetableExistError(timetable)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.db.add_new_timetable(timetable) <NEW_LINE> self.status_handler.add_timetable_ok(timetable) <NEW_LINE> <DEDENT> <DEDENT> async def add_timetable_from_text(self, text: Union['uaviak_parser.TextTimetable', str]) -> None: <NEW_LINE> <INDENT> if isinstance(text, str): <NEW_LINE> <INDENT> text = uaviak_parser.TextTimetable.parse(text) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> timetable = text.parse_text() <NEW_LINE> <DEDENT> except uaviak_parser.exceptions.GetTimetableError as e: <NEW_LINE> <INDENT> self.status_handler.add_timetable_error(e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.add_timetable_from_structure(timetable) <NEW_LINE> <DEDENT> <DEDENT> async def add_timetable_from_html(self, html: Union['uaviak_parser.HtmlTimetable', str]) -> None: <NEW_LINE> <INDENT> if isinstance(html, str): <NEW_LINE> <INDENT> html = uaviak_parser.HtmlTimetable(html) <NEW_LINE> <DEDENT> await self.add_timetable_from_text(html.parse_html()) <NEW_LINE> <DEDENT> async def add_timetable_from_site(self) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> html = await uaviak_parser.HtmlTimetable.load() <NEW_LINE> <DEDENT> except uaviak_parser.exceptions.GetHtmlError as e: <NEW_LINE> <INDENT> self.status_handler.add_timetable_error(e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.add_timetable_from_html(html) | Класс, добавляющий новое расписание в БД из разных форматов.
| 6259906d435de62698e9d64c |
class _SerializableColumnGetter(object): <NEW_LINE> <INDENT> def __init__(self, colkeys): <NEW_LINE> <INDENT> self.colkeys = colkeys <NEW_LINE> self.composite = len(colkeys) > 1 <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return _SerializableColumnGetter, (self.colkeys,) <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> state = instance_state(value) <NEW_LINE> m = _state_mapper(state) <NEW_LINE> key = [m._get_state_attr_by_column( state, state.dict, m.mapped_table.columns[k]) for k in self.colkeys] <NEW_LINE> if self.composite: <NEW_LINE> <INDENT> return tuple(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return key[0] | Column-based getter used in version 0.7.6 only.
Remains here for pickle compatibility with 0.7.6. | 6259906d01c39578d7f14358 |
class V1ConfigMapEnvSource(object): <NEW_LINE> <INDENT> openapi_types = { 'name': 'str', 'optional': 'bool' } <NEW_LINE> attribute_map = { 'name': 'name', 'optional': 'optional' } <NEW_LINE> def __init__(self, name=None, optional=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._name = None <NEW_LINE> self._optional = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if optional is not None: <NEW_LINE> <INDENT> self.optional = optional <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def optional(self): <NEW_LINE> <INDENT> return self._optional <NEW_LINE> <DEDENT> @optional.setter <NEW_LINE> def optional(self, optional): <NEW_LINE> <INDENT> self._optional = optional <NEW_LINE> <DEDENT> def to_dict(self, serialize=False): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def convert(x): <NEW_LINE> <INDENT> if hasattr(x, "to_dict"): <NEW_LINE> <INDENT> args = getfullargspec(x.to_dict).args <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> return x.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.to_dict(serialize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> attr = self.attribute_map.get(attr, attr) if serialize else attr <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: convert(x), value )) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], convert(item[1])), value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = convert(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, V1ConfigMapEnvSource): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1ConfigMapEnvSource): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259906d2ae34c7f260ac92f |
class BenchDB(object): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> if not os.path.isfile(path): <NEW_LINE> <INDENT> self.conn = self.setup() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.conn = sqlite3.connect(path) <NEW_LINE> <DEDENT> <DEDENT> def setup(self): <NEW_LINE> <INDENT> conn = sqlite3.connect(self.path) <NEW_LINE> cur = conn.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> cur.execute("create table benchmarks " "(addedon integer, cwd text, command text, result text)") <NEW_LINE> cur.execute("create unique index if not exists " "benchmark on benchmarks (cwd, command)") <NEW_LINE> conn.commit() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> cur.close() <NEW_LINE> <DEDENT> return conn <NEW_LINE> <DEDENT> def get(self, cwd, command): <NEW_LINE> <INDENT> cur = self.conn.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> cur.execute("select addedon, result from benchmarks " "where cwd = ? and command = ?", (cwd, command)) <NEW_LINE> addedon, result = cur.fetchone() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> cur.close() <NEW_LINE> <DEDENT> return (addedon, json.loads(result)) <NEW_LINE> <DEDENT> def put(self, cwd, command, result): <NEW_LINE> <INDENT> result = json.dumps([str(x) for x in result]) <NEW_LINE> cur = self.conn.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> cur.execute("replace into benchmarks " "(addedon, cwd, command, result) " "values (datetime(), ?, ?, ?)", (cwd, command, result)) <NEW_LINE> self.conn.commit() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> cur.close() <NEW_LINE> <DEDENT> <DEDENT> def putmany(self, stats): <NEW_LINE> <INDENT> for stat in stats: <NEW_LINE> <INDENT> self.put(stat[0], stat[1], stat[2:]) | Persist recorded benchmark scores.
Example:
>>> from os import tmpnam, remove
>>> dbname = tmpnam()
>>> db = BenchDB(dbname)
>>> db.put('/tmp', 'ls', [1, 2, 3])
>>> db.get('/tmp', 'ls')[1]
[1, 2, 3]
>>> remove(dbname) | 6259906d44b2445a339b7582 |
class IconChooserButton(Gtk.Button): <NEW_LINE> <INDENT> __gsignals__ = { "filename-changed" : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } <NEW_LINE> def __init__(self, dialog): <NEW_LINE> <INDENT> Gtk.Button.__init__(self) <NEW_LINE> dialog.set_icon_from_file(PGlobs.default_icon) <NEW_LINE> hbox = Gtk.HBox() <NEW_LINE> hbox.set_spacing(4) <NEW_LINE> image = Gtk.Image() <NEW_LINE> hbox.pack_start(image, False, padding=1) <NEW_LINE> label = Gtk.Label() <NEW_LINE> label.set_alignment(0, 0.5) <NEW_LINE> label.set_ellipsize(Pango.EllipsizeMode.END) <NEW_LINE> hbox.pack_start(label) <NEW_LINE> vsep = Gtk.VSeparator() <NEW_LINE> hbox.pack_start(vsep, False) <NEW_LINE> rightmost_icon = Gtk.Image.new_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.MENU) <NEW_LINE> hbox.pack_start(rightmost_icon, False) <NEW_LINE> self.add(hbox) <NEW_LINE> hbox.show_all() <NEW_LINE> self.connect("clicked", self._cb_clicked, dialog) <NEW_LINE> self._dialog = dialog <NEW_LINE> self._image = image <NEW_LINE> self._label = label <NEW_LINE> self.set_filename(dialog.get_filename()) <NEW_LINE> <DEDENT> def set_filename(self, f): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> disp = GLib.filename_display_name(f) <NEW_LINE> pb = GdkPixbuf.Pixbuf.new_from_file_at_size(f, 16, 16) <NEW_LINE> <DEDENT> except (GLib.GError, TypeError): <NEW_LINE> <INDENT> self._label.set_text(_("(None)")) <NEW_LINE> self._image.clear() <NEW_LINE> self._filename = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._label.set_text(disp) <NEW_LINE> self._image.set_from_pixbuf(pb) <NEW_LINE> self._filename = f <NEW_LINE> self._dialog.set_filename(f) <NEW_LINE> <DEDENT> self.emit("filename-changed", self._filename) <NEW_LINE> <DEDENT> def get_filename(self): <NEW_LINE> <INDENT> return self._filename <NEW_LINE> <DEDENT> def _cb_clicked(self, button, dialog): <NEW_LINE> <INDENT> response = dialog.run() <NEW_LINE> if response == Gtk.ResponseType.OK: <NEW_LINE> <INDENT> self.set_filename(dialog.get_filename()) <NEW_LINE> <DEDENT> elif response == Gtk.ResponseType.NONE: <NEW_LINE> <INDENT> filename = self.get_filename() <NEW_LINE> if filename is not None: <NEW_LINE> <INDENT> dialog.set_filename(filename) <NEW_LINE> <DEDENT> self.set_filename(None) <NEW_LINE> <DEDENT> dialog.hide() <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr in Gtk.FileChooser.__dict__: <NEW_LINE> <INDENT> return getattr(self._dialog, attr) <NEW_LINE> <DEDENT> raise AttributeError("%s has no attribute, %s" % ( self, attr)) | Imitate a FileChooserButton but specific to image types.
The image rather than the mime-type icon is shown on the button. | 6259906d7c178a314d78e80f |
class ModuleNamingScheme(object): <NEW_LINE> <INDENT> __metaclass__ = Singleton <NEW_LINE> REQUIRED_KEYS = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.log = fancylogger.getLogger(self.__class__.__name__, fname=False) <NEW_LINE> <DEDENT> def is_sufficient(self, keys): <NEW_LINE> <INDENT> if self.REQUIRED_KEYS is not None: <NEW_LINE> <INDENT> return set(keys).issuperset(set(self.REQUIRED_KEYS)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise EasyBuildError("Constant REQUIRED_KEYS is not defined, " "should specify required easyconfig parameters.") <NEW_LINE> <DEDENT> <DEDENT> def requires_toolchain_details(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def det_full_module_name(self, ec): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def det_short_module_name(self, ec): <NEW_LINE> <INDENT> return self.det_full_module_name(ec) <NEW_LINE> <DEDENT> def det_install_subdir(self, ec): <NEW_LINE> <INDENT> return self.det_full_module_name(ec) <NEW_LINE> <DEDENT> def det_module_subdir(self, ec): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def det_module_symlink_paths(self, ec): <NEW_LINE> <INDENT> return [ec['moduleclass']] <NEW_LINE> <DEDENT> def det_modpath_extensions(self, ec): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def det_user_modpath_extensions(self, ec): <NEW_LINE> <INDENT> return self.det_modpath_extensions(ec) <NEW_LINE> <DEDENT> def det_init_modulepaths(self, ec): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def expand_toolchain_load(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_short_modname_for(self, short_modname, name): <NEW_LINE> <INDENT> modname_regex = re.compile('^%s(/\S+)?$' % re.escape(name)) <NEW_LINE> res = bool(modname_regex.match(short_modname)) <NEW_LINE> self.log.debug("Checking whether '%s' is a module name for software with name '%s' via regex %s: %s", short_modname, name, modname_regex.pattern, res) <NEW_LINE> return res | Abstract class for a module naming scheme implementation. | 6259906d2c8b7c6e89bd502d |
class ViewSpaceSideBarManager(plugin.ViewSpacePlugin): <NEW_LINE> <INDENT> def __init__(self, viewspace): <NEW_LINE> <INDENT> self._line_numbers = False <NEW_LINE> self._linenumberarea = None <NEW_LINE> viewspace.viewChanged.connect(self.updateView) <NEW_LINE> <DEDENT> def loadSettings(self): <NEW_LINE> <INDENT> s = QSettings() <NEW_LINE> s.beginGroup("sidebar") <NEW_LINE> line_numbers = s.value("line_numbers", self._line_numbers) in (True, "true") <NEW_LINE> self.setLineNumbersVisible(line_numbers) <NEW_LINE> <DEDENT> def saveSettings(self): <NEW_LINE> <INDENT> s = QSettings() <NEW_LINE> s.beginGroup("sidebar") <NEW_LINE> s.setValue("line_numbers", self.lineNumbersVisible()) <NEW_LINE> <DEDENT> def copySettings(self, other): <NEW_LINE> <INDENT> self.setLineNumbersVisible(other.lineNumbersVisible()) <NEW_LINE> <DEDENT> def setLineNumbersVisible(self, visible): <NEW_LINE> <INDENT> if visible == self._line_numbers: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._line_numbers = visible <NEW_LINE> self.updateView() <NEW_LINE> <DEDENT> def lineNumbersVisible(self): <NEW_LINE> <INDENT> return self._line_numbers <NEW_LINE> <DEDENT> def updateView(self): <NEW_LINE> <INDENT> view = self.viewSpace().activeView() <NEW_LINE> if not view: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def add(widget): <NEW_LINE> <INDENT> from widgets import borderlayout <NEW_LINE> if QApplication.isRightToLeft(): <NEW_LINE> <INDENT> side = borderlayout.RIGHT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> side = borderlayout.LEFT <NEW_LINE> <DEDENT> borderlayout.BorderLayout.get(view).addWidget(widget, side) <NEW_LINE> <DEDENT> if self._line_numbers: <NEW_LINE> <INDENT> if not self._linenumberarea: <NEW_LINE> <INDENT> from widgets import linenumberarea <NEW_LINE> self._linenumberarea = linenumberarea.LineNumberArea() <NEW_LINE> <DEDENT> add(self._linenumberarea) <NEW_LINE> self._linenumberarea.setTextEdit(view) <NEW_LINE> <DEDENT> elif self._linenumberarea: <NEW_LINE> <INDENT> self._linenumberarea.deleteLater() <NEW_LINE> self._linenumberarea = None | Manages SideBar settings and behaviour for one ViewSpace. | 6259906d3539df3088ecdae5 |
class PostModel(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'posts' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> title = db.Column(db.String(100)) <NEW_LINE> slug = db.Column(db.Text, unique=True) <NEW_LINE> body = db.Column(db.String(100), unique=True) <NEW_LINE> published = db.Column(db.Boolean, default=False) <NEW_LINE> number_of_visits = db.Column(db.Integer, default=0) <NEW_LINE> def save_to_db(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def delete_from_db(self): <NEW_LINE> <INDENT> db.session.delete(self) <NEW_LINE> db.session.commit() | Create a Post table | 6259906dcc0a2c111447c6f4 |
class InputTypeError(TypeError): <NEW_LINE> <INDENT> def __init__(self, name, value, expected_type): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.expected_type = expected_type <NEW_LINE> self.message = "Argument `{name}` is of type `{observed_type}`, not `{expected_type}`.".format( name=name, observed_type=type(value), expected_type=expected_type ) <NEW_LINE> super(TypeError, self).__init__(self.message) | TypeError raised when a runtime value is not the expected type | 6259906dd486a94d0ba2d806 |
class IPloneArticleTool(Interface): <NEW_LINE> <INDENT> pass | Services and options for PloneArticle contents | 6259906db7558d5895464b55 |
class DeletedMessage(DataClassObject): <NEW_LINE> <INDENT> _json_schema: dict = DeletedMessageSchema <NEW_LINE> json_validator = get_compiled_validator(_json_schema) <NEW_LINE> @log_type_exception('DeletedMessage') <NEW_LINE> def __init__(self, data: dict, client: HivenClient): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._message_id = data.get('message_id') <NEW_LINE> self._house_id = data.get('house_id') <NEW_LINE> self._room_id = data.get('room_id') <NEW_LINE> self._client = client <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"Deleted message in room {self.room_id}" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def format_obj_data(cls, data: dict) -> dict: <NEW_LINE> <INDENT> data = cls.validate(data) <NEW_LINE> data['message_id'] = data['id'] <NEW_LINE> return data <NEW_LINE> <DEDENT> @property <NEW_LINE> def message_id(self) -> Optional[str]: <NEW_LINE> <INDENT> return getattr(self, '_message_id') <NEW_LINE> <DEDENT> @property <NEW_LINE> def house_id(self) -> Optional[str]: <NEW_LINE> <INDENT> return getattr(self, '_house_id') <NEW_LINE> <DEDENT> @property <NEW_LINE> def room_id(self) -> Optional[str]: <NEW_LINE> <INDENT> return getattr(self, '_room_id') | Represents a Deleted Message in a Room | 6259906d283ffb24f3cf50f0 |
class Screen: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.screen = [[' ']*(lines - 1) for _ in range(columns)] <NEW_LINE> self.objects = [] <NEW_LINE> self.is_active = False <NEW_LINE> <DEDENT> def drawbg(self): <NEW_LINE> <INDENT> print(bg("dark_gray"), end="") <NEW_LINE> <DEDENT> def take_over(self): <NEW_LINE> <INDENT> clear() <NEW_LINE> self.is_active = True <NEW_LINE> self.drawbg() <NEW_LINE> hide() <NEW_LINE> set_echo(False) <NEW_LINE> reverted = revert_x_to_y(self) <NEW_LINE> for i in reverted: <NEW_LINE> <INDENT> print("".join(i)) <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.is_active is False: <NEW_LINE> <INDENT> raise Exception("Screen must be active to update") <NEW_LINE> <DEDENT> clear() <NEW_LINE> self.drawbg() <NEW_LINE> reverted = revert_x_to_y(self) <NEW_LINE> for i in reverted: <NEW_LINE> <INDENT> print("".join(i)) <NEW_LINE> <DEDENT> <DEDENT> def return_over(self): <NEW_LINE> <INDENT> self.is_active = False <NEW_LINE> print(attr('reset')) <NEW_LINE> show() <NEW_LINE> set_echo(True) <NEW_LINE> clear() <NEW_LINE> <DEDENT> def draw(self, obj): <NEW_LINE> <INDENT> if not isinstance(obj, Drawable): <NEW_LINE> <INDENT> raise Exception("obj must be of type Drawable or inheritent thereof") <NEW_LINE> <DEDENT> obj.draw_on(self) <NEW_LINE> <DEDENT> def input(self, text): <NEW_LINE> <INDENT> show() <NEW_LINE> set_echo(True) <NEW_LINE> res = input(bg("dark_gray") + text) <NEW_LINE> clear() <NEW_LINE> hide() <NEW_LINE> set_echo(False) <NEW_LINE> return res | Screen object.
Used for controlling the screen.
The creation of this object takes no arguments.
You should only create one for every session, then take over the screen with take_over()
Update the screen with update() and return the screen with return_over()
Properties:
Format: name: type: description
screen: list: Screen data by individual characters
is_active: bool: Shows if the screen is active
Functions:
Format: name: return_type: description
drawbg: None: Draws a dark gray background. Used internally.
take_over: None: Takes over the terminal for the screen object.
update: None: Updates the screen.
return_over: None: Returns the screen to the terminal.
draw: None: Receives a Drawable object and renders it onto the array.
Call update() to actually put the object on screen. | 6259906d8a43f66fc4bf39dc |
class ListTableResource(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[Table]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ListTableResource, self).__init__(**kwargs) <NEW_LINE> self.value = None <NEW_LINE> self.next_link = None | Response schema. Contains list of tables returned.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: List of tables returned.
:vartype value: list[~azure.mgmt.storage.v2021_08_01.models.Table]
:ivar next_link: Request URL that can be used to query next page of tables.
:vartype next_link: str | 6259906d6e29344779b01e9e |
class GpsBatchSampler(object): <NEW_LINE> <INDENT> def __init__(self, data, batch_dim=0): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.batch_dim = batch_dim <NEW_LINE> self.num_data = data[0].shape[batch_dim] <NEW_LINE> for d in data: <NEW_LINE> <INDENT> assert d.shape[batch_dim] == self.num_data, "Bad shape on axis %d: %s, (expected %d)" % (batch_dim, str(d.shape), self.num_data) <NEW_LINE> <DEDENT> <DEDENT> def with_replacement(self, batch_size=10): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> batch_idx = np.random.randint(0, self.num_data, size=batch_size) <NEW_LINE> batch = [data[batch_idx] for data in self.data] <NEW_LINE> yield batch <NEW_LINE> <DEDENT> <DEDENT> def iterate(self, batch_size=10, epochs=float('inf'), shuffle=True): <NEW_LINE> <INDENT> raise NotImplementedError() | Samples data, from GPS code TODO | 6259906d167d2b6e312b81b2 |
class FunctionRelease(LocalRelease): <NEW_LINE> <INDENT> def __init__(self, releaseFunction, delay=0): <NEW_LINE> <INDENT> super(FunctionRelease, self).__init__() <NEW_LINE> self.releaseRatesList = [] <NEW_LINE> self.totRelease = 0 <NEW_LINE> self.currentPeriod = 0 <NEW_LINE> self.lastNonZero = 0 <NEW_LINE> delayArray = np.zeros(delay) <NEW_LINE> while ( self.totRelease < 1 and self.currentPeriod < 500 ): <NEW_LINE> <INDENT> currentRelease = releaseFunction(self.currentPeriod) <NEW_LINE> self.releaseRatesList.append(currentRelease) <NEW_LINE> if currentRelease != 0: <NEW_LINE> <INDENT> self.lastNonZero = self.currentPeriod <NEW_LINE> <DEDENT> self.totRelease += currentRelease <NEW_LINE> self.currentPeriod += 1 <NEW_LINE> <DEDENT> if self.currentPeriod - 1 != self.lastNonZero: <NEW_LINE> <INDENT> self.releaseRatesList = self.releaseRatesList[: self.lastNonZero + 1] <NEW_LINE> <DEDENT> if self.totRelease > 1: <NEW_LINE> <INDENT> self.releaseRatesList[-1] += 1 - self.totRelease <NEW_LINE> <DEDENT> self.releaseList = np.concatenate((delayArray, self.releaseRatesList)) | A material release plan based on a distribution function that returns a release rate for every period. The time instant of the relese is relative to the time of material storage in the stock.
Parameters:
----------------
releaseFunction: function
function that return the relative release rate for a period
delay: Integer
delay time in periods, befor the release starts. | 6259906d627d3e7fe0e086d1 |
class Observer(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def update(self): <NEW_LINE> <INDENT> pass | Observer of the events in the pub-sub objects relation | 6259906d44b2445a339b7583 |
class Repository(object, metaclass=ABCMeta): <NEW_LINE> <INDENT> def find_observations(self, indicator_code=None, area_code=None, year=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_indicators_by_code(self, code): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_countries_by_code_name_or_income(self, code): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def observation_uri(self, observation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_observation_country_and_indicator_name(self, observation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def insert_observation(self, observation): <NEW_LINE> <INDENT> pass | Abstract implementation of generic queries for managing observations. | 6259906df548e778e596cdd6 |
class TicTacToeBoard: <NEW_LINE> <INDENT> NROWS = 3 <NEW_LINE> NCOLS = 3 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.board = BitGameBoard(self.NROWS, self.NCOLS) <NEW_LINE> <DEDENT> def set(self, row, col, value): <NEW_LINE> <INDENT> if self.board.get(row, col) != GameBoardPlayer.NONE: <NEW_LINE> <INDENT> raise ValueError(f"{row} {col} already has {self.board.get(row, col)}") <NEW_LINE> <DEDENT> self.board.set(row, col, value) <NEW_LINE> <DEDENT> def get(self, row, col): <NEW_LINE> <INDENT> return self.board.get(row, col) <NEW_LINE> <DEDENT> def get_winner(self): <NEW_LINE> <INDENT> return self.board.get_winner() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.board.__str__() | A class that represents a Tic Tac Toe game board.
It's a thin wrapper around the actual game board | 6259906dac7a0e7691f73d31 |
class TreeItemAttr(object): <NEW_LINE> <INDENT> def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, colBorder=wx.NullColour,font=wx.NullFont): <NEW_LINE> <INDENT> self._colText = colText <NEW_LINE> self._colBack = colBack <NEW_LINE> self._colBorder = colBorder <NEW_LINE> self._font = font <NEW_LINE> <DEDENT> def SetTextColour(self, colText): <NEW_LINE> <INDENT> self._colText = colText <NEW_LINE> <DEDENT> def SetBackgroundColour(self, colBack): <NEW_LINE> <INDENT> self._colBack = colBack <NEW_LINE> <DEDENT> def SetBorderColour(self, colBorder): <NEW_LINE> <INDENT> self._colBorder = colBorder <NEW_LINE> <DEDENT> def SetFont(self, font): <NEW_LINE> <INDENT> self._font = font <NEW_LINE> <DEDENT> def HasTextColour(self): <NEW_LINE> <INDENT> return self._colText != wx.NullColour and self._colText.IsOk() <NEW_LINE> <DEDENT> def HasBackgroundColour(self): <NEW_LINE> <INDENT> return self._colBack != wx.NullColour and self._colBack.IsOk() <NEW_LINE> <DEDENT> def HasBorderColour(self): <NEW_LINE> <INDENT> return self._colBorder != wx.NullColour and self._colBorder.IsOk() <NEW_LINE> <DEDENT> def HasFont(self): <NEW_LINE> <INDENT> return self._font != wx.NullFont and self._font.IsOk() <NEW_LINE> <DEDENT> def GetTextColour(self): <NEW_LINE> <INDENT> return self._colText <NEW_LINE> <DEDENT> def GetBackgroundColour(self): <NEW_LINE> <INDENT> return self._colBack <NEW_LINE> <DEDENT> def GetBorderColour(self): <NEW_LINE> <INDENT> return self._colBorder <NEW_LINE> <DEDENT> def GetFont(self): <NEW_LINE> <INDENT> return self._font | Creates the item attributes (text colour, background colour and font).
:note: This class is inspired by the wxWidgets generic implementation of :class:`TreeItemAttr`. | 6259906d99cbb53fe6832731 |
class TextDataUpload(BaseDataUpload): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> super().__init__(client) <NEW_LINE> <DEDENT> async def upload_data(self, records, job_id): <NEW_LINE> <INDENT> variables = { 'file': open(records, 'r'), 'records': records, 'jobId': job_id } <NEW_LINE> response = await self._client.execute(UPLOAD_PARTNER_TEXT_MUTATION, variables=variables) <NEW_LINE> print(await response.json()) <NEW_LINE> return None | upload text data | 6259906d8da39b475be04a36 |
class EventList(QtGui.QListWidget): <NEW_LINE> <INDENT> signal_emptyList=pyqtSignal() <NEW_LINE> signal_newEvent=pyqtSignal() <NEW_LINE> signal_notEmptyList=pyqtSignal() <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(EventList, self).__init__() <NEW_LINE> self.vlcInstance=vlc.Instance('--input-repeat=-1') <NEW_LINE> self.alarmPlayer=self.vlcInstance.media_player_new() <NEW_LINE> self.alarmPlayer.set_media(self.vlcInstance.media_new(statics.sndAlarmPath)) <NEW_LINE> self.itemDoubleClicked.connect(self.dblClickAction) <NEW_LINE> <DEDENT> @pyqtSlot() <NEW_LINE> def dblClickAction(self): <NEW_LINE> <INDENT> dialog=DlgAlarmConfirmation(self.item(self.currentRow())) <NEW_LINE> ret=dialog.exec_() <NEW_LINE> if ret==1: self.takeItem(self.currentRow()) <NEW_LINE> if self.count()==0: <NEW_LINE> <INDENT> self.alarmPlayer.stop() <NEW_LINE> self.signal_emptyList.emit() <NEW_LINE> <DEDENT> <DEDENT> def appendEvent(self, event): <NEW_LINE> <INDENT> self.addItem(event) <NEW_LINE> self.alarmPlayer.play() <NEW_LINE> self.signal_newEvent.emit() <NEW_LINE> if self.count() > 0: <NEW_LINE> <INDENT> self.signal_notEmptyList.emit() | List of events to approve in system | 6259906da8370b77170f1c10 |
class Solution(): <NEW_LINE> <INDENT> def insertionSort(self, list): <NEW_LINE> <INDENT> for i in range(1, len(list)): <NEW_LINE> <INDENT> candidate = list[i] <NEW_LINE> position = i <NEW_LINE> while candidate < list[position - 1] and position > 0: <NEW_LINE> <INDENT> list[position] = list[position - 1] <NEW_LINE> position -= 1 <NEW_LINE> <DEDENT> list[position] = candidate <NEW_LINE> <DEDENT> return list <NEW_LINE> <DEDENT> def mergeSort(self, list): <NEW_LINE> <INDENT> if len(list) == 1: <NEW_LINE> <INDENT> return list <NEW_LINE> <DEDENT> mid = len(list) // 2 <NEW_LINE> lefthalf = list[:mid] <NEW_LINE> righthalf = list[mid:] <NEW_LINE> lefthalf = self.mergeSort(lefthalf) <NEW_LINE> righthalf = self.mergeSort(righthalf) <NEW_LINE> i, j, k = 0, 0, 0 <NEW_LINE> while i < len(lefthalf) and j < len(righthalf): <NEW_LINE> <INDENT> if lefthalf[i] < righthalf[j]: <NEW_LINE> <INDENT> list[k] = lefthalf[i] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> list[k] = righthalf[i] <NEW_LINE> j += 1 <NEW_LINE> <DEDENT> k += 1 <NEW_LINE> <DEDENT> if i < len(lefthalf): <NEW_LINE> <INDENT> list[k:] = lefthalf[i:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> list[k:] = righthalf[j:] <NEW_LINE> <DEDENT> return list <NEW_LINE> <DEDENT> def quickSort(self, list): <NEW_LINE> <INDENT> self.subQuickSort(list, 0, len(list)-1) <NEW_LINE> return list <NEW_LINE> <DEDENT> def subQuickSort(self, list, start, end): <NEW_LINE> <INDENT> if start < end: <NEW_LINE> <INDENT> split = self.partition(list, start, end) <NEW_LINE> self.subQuickSort(list, start, split-1) <NEW_LINE> self.subQuickSort(list, split+1, end) <NEW_LINE> <DEDENT> <DEDENT> def partition(self, list, start, end): <NEW_LINE> <INDENT> pivotvalue = list[start] <NEW_LINE> leftmark = start + 1 <NEW_LINE> rightmark = end <NEW_LINE> done = False <NEW_LINE> while not done: <NEW_LINE> <INDENT> while leftmark <= rightmark and list[leftmark] <= pivotvalue: <NEW_LINE> <INDENT> leftmark += 1 <NEW_LINE> <DEDENT> while leftmark <= rightmark and list[rightmark] >= pivotvalue: <NEW_LINE> <INDENT> rightmark -= 1 <NEW_LINE> <DEDENT> if leftmark > rightmark: <NEW_LINE> <INDENT> done = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> list[leftmark], list[rightmark] = list[rightmark], list[leftmark] <NEW_LINE> <DEDENT> <DEDENT> list[start], list[rightmark] = list[rightmark], list[start] <NEW_LINE> return rightmark <NEW_LINE> <DEDENT> def countingSort(self, list, maxValue): <NEW_LINE> <INDENT> count = [0]*maxValue <NEW_LINE> for num in list: <NEW_LINE> <INDENT> count[num] += 1 <NEW_LINE> <DEDENT> res = [] <NEW_LINE> for i in range(maxValue): <NEW_LINE> <INDENT> while count[i] > 0: <NEW_LINE> <INDENT> res.append(i) <NEW_LINE> count[i] -= 1 <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> def heapSort(self, list): <NEW_LINE> <INDENT> res = [] <NEW_LINE> pq = PriorityQueue() <NEW_LINE> for num in list: <NEW_LINE> <INDENT> pq.put(num) <NEW_LINE> <DEDENT> while not pq.empty(): <NEW_LINE> <INDENT> res.append(pq.get()) <NEW_LINE> <DEDENT> return res | sort | 6259906d76e4537e8c3f0dcd |
class Tenants(object): <NEW_LINE> <INDENT> def __init__(self, values, links): <NEW_LINE> <INDENT> self.values = values <NEW_LINE> self.links = links <NEW_LINE> <DEDENT> def to_xml(self): <NEW_LINE> <INDENT> dom = etree.Element("tenants") <NEW_LINE> dom.set(u"xmlns", "http://docs.openstack.org/identity/api/v2.0") <NEW_LINE> for t in self.values: <NEW_LINE> <INDENT> dom.append(t.to_dom()) <NEW_LINE> <DEDENT> for t in self.links: <NEW_LINE> <INDENT> dom.append(t.to_dom()) <NEW_LINE> <DEDENT> return etree.tostring(dom) <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> values = [t.to_dict()["tenant"] for t in self.values] <NEW_LINE> links = [t.to_dict()["links"] for t in self.links] <NEW_LINE> return json.dumps({"tenants": {"values": values, "links": links}}) | A collection of tenants. | 6259906d99fddb7c1ca639f6 |
@implementer(IHostnameResolver) <NEW_LINE> class CachingHostnameResolver: <NEW_LINE> <INDENT> def __init__(self, reactor, cache_size): <NEW_LINE> <INDENT> self.reactor = reactor <NEW_LINE> self.original_resolver = reactor.nameResolver <NEW_LINE> dnscache.limit = cache_size <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_crawler(cls, crawler, reactor): <NEW_LINE> <INDENT> if crawler.settings.getbool('DNSCACHE_ENABLED'): <NEW_LINE> <INDENT> cache_size = crawler.settings.getint('DNSCACHE_SIZE') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cache_size = 0 <NEW_LINE> <DEDENT> return cls(reactor, cache_size) <NEW_LINE> <DEDENT> def install_on_reactor(self): <NEW_LINE> <INDENT> self.reactor.installNameResolver(self) <NEW_LINE> <DEDENT> def resolveHostName( self, resolutionReceiver, hostName, portNumber=0, addressTypes=None, transportSemantics="TCP" ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> addresses = dnscache[hostName] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return self.original_resolver.resolveHostName( _CachingResolutionReceiver(resolutionReceiver, hostName), hostName, portNumber, addressTypes, transportSemantics, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resolutionReceiver.resolutionBegan(HostResolution(hostName)) <NEW_LINE> for addr in addresses: <NEW_LINE> <INDENT> resolutionReceiver.addressResolved(addr) <NEW_LINE> <DEDENT> resolutionReceiver.resolutionComplete() <NEW_LINE> return resolutionReceiver | Experimental caching resolver. Resolves IPv4 and IPv6 addresses,
does not support setting a timeout value for DNS requests. | 6259906d01c39578d7f1435a |
class InferenceController(JoinTreeListener): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def apply(bbn): <NEW_LINE> <INDENT> PotentialInitializer.init(bbn) <NEW_LINE> ug = Moralizer.moralize(bbn) <NEW_LINE> cliques = Triangulator.triangulate(ug) <NEW_LINE> join_tree = Transformer.transform(cliques) <NEW_LINE> join_tree.parent_info = {node.id: bbn.get_parents_ordered(node.id) for node in bbn.get_nodes()} <NEW_LINE> Initializer.initialize(join_tree) <NEW_LINE> Propagator.propagate(join_tree) <NEW_LINE> join_tree.set_listener(InferenceController()) <NEW_LINE> return join_tree <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def reapply(join_tree, cpts): <NEW_LINE> <INDENT> jt = copy.deepcopy(join_tree) <NEW_LINE> jt.update_bbn_cpts(cpts) <NEW_LINE> jt.listener = None <NEW_LINE> jt.evidences = dict() <NEW_LINE> PotentialInitializer.reinit(jt) <NEW_LINE> Initializer.initialize(jt) <NEW_LINE> Propagator.propagate(jt) <NEW_LINE> jt.set_listener(InferenceController()) <NEW_LINE> return jt <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def apply_from_serde(join_tree): <NEW_LINE> <INDENT> join_tree.listener = None <NEW_LINE> join_tree.evidences = dict() <NEW_LINE> PotentialInitializer.reinit(join_tree) <NEW_LINE> Initializer.initialize(join_tree) <NEW_LINE> Propagator.propagate(join_tree) <NEW_LINE> join_tree.set_listener(InferenceController()) <NEW_LINE> return join_tree <NEW_LINE> <DEDENT> def evidence_retracted(self, join_tree): <NEW_LINE> <INDENT> Initializer.initialize(join_tree) <NEW_LINE> Propagator.propagate(join_tree) <NEW_LINE> <DEDENT> def evidence_updated(self, join_tree): <NEW_LINE> <INDENT> Propagator.propagate(join_tree) | Inference controller. | 6259906ddd821e528d6da5a6 |
class SwitchPortBinding(model_base.BASEV2): <NEW_LINE> <INDENT> __tablename__ = "switch_port_bindings" <NEW_LINE> port_id = sa.Column(sa.String(255), primary_key=True) <NEW_LINE> network_id = sa.Column(sa.String(255), primary_key=True) <NEW_LINE> switch_port_id = sa.Column( sa.String(36), sa.ForeignKey("switch_ports.id"), primary_key=True) <NEW_LINE> state = sa.Column(sa.String(255), default=SwitchPortBindingState.INACTIVE) <NEW_LINE> def as_dict(self): <NEW_LINE> <INDENT> return { u"port_id": self.port_id, u"network_id": self.network_id, u"switch_port_id": self.switch_port_id, u"state": self.state } | Keep track of which neutron ports are bound to which
physical switchports. | 6259906d8e71fb1e983bd312 |
class Overseer(Actor): <NEW_LINE> <INDENT> def __init__(self, hive, id): <NEW_LINE> <INDENT> super(Overseer, self).__init__(hive, id) <NEW_LINE> self.message_routing.update( {"init_world": self.init_world}) <NEW_LINE> <DEDENT> def init_world(self, message): <NEW_LINE> <INDENT> room = self.hive.create_actor(WarehouseRoom) <NEW_LINE> for is_droid_clean in droid_list(5, 8): <NEW_LINE> <INDENT> droid = self.hive.create_actor( Droid, infected=is_droid_clean, room=room) <NEW_LINE> yield self.wait_on_message( to=droid, directive="register_with_room") <NEW_LINE> <DEDENT> security_robot = self.hive.create_actor(SecurityRobot) <NEW_LINE> self.hive.send_message( to=security_robot, directive="begin_mission", body={"room": room}) | Actor that initializes the world of this demo and starts the mission. | 6259906dac7a0e7691f73d33 |
class PatientChangeForm(ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Patient <NEW_LINE> fields = ('email', 'password', 'first_name', 'birth_date', 'last_name', 'is_active', 'is_admin', 'is_content_manager') <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"] | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 6259906dfff4ab517ebcf065 |
class StorageError(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'error': {'key': 'error', 'type': 'StorageErrorError'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(StorageError, self).__init__(**kwargs) <NEW_LINE> self.error = kwargs.get('error', None) | StorageError.
:param error: The service error response object.
:type error: ~azure.storage.filedatalake.models.StorageErrorError | 6259906d7c178a314d78e811 |
class TestTCP(unittest.TestCase): <NEW_LINE> <INDENT> def test_client_server(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> server = Mserver.TCPServer(opts={'open': True}) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Skipping because of server open failure") <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> client = Mclient.TCPClient(opts={'open': True}) <NEW_LINE> for line in ['one', 'two', 'three']: <NEW_LINE> <INDENT> server.writeline(line) <NEW_LINE> self.assertEqual(line, client.read_msg().rstrip('\n')) <NEW_LINE> pass <NEW_LINE> <DEDENT> for line in ['four', 'five', 'six']: <NEW_LINE> <INDENT> client.writeline(line) <NEW_LINE> self.assertEqual(line, server.read_msg().rstrip('\n')) <NEW_LINE> pass <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("Skipping because of client open failure") <NEW_LINE> pass <NEW_LINE> <DEDENT> client.close() <NEW_LINE> server.close() <NEW_LINE> return | Tests TCPServer and TCPClient | 6259906d0a50d4780f7069e6 |
class Equal_(_BinaryOperator): <NEW_LINE> <INDENT> def _get_ref_field(self, param_store): <NEW_LINE> <INDENT> return "({}) = ({})".format( self._lhs._get_ref_field(param_store), self._rhs._get_ref_field(param_store)) | SQL `=` operator. | 6259906d009cb60464d02d80 |
class EaseOutEaseInTweener ( Tweener ): <NEW_LINE> <INDENT> def at ( self, t ): <NEW_LINE> <INDENT> return ((tanh( 5.0 * t - 2.5 ) / tanh25) + 1.0) / 2.0 | Defines the EaseInEaseOutTweener class that does an 'Ease In/Ease Out'
motion 'tween. | 6259906dcb5e8a47e493cda8 |
class Seq(_SeqAbstractBaseClass): <NEW_LINE> <INDENT> def __init__(self, data, length=None): <NEW_LINE> <INDENT> if length is None: <NEW_LINE> <INDENT> if isinstance(data, (bytes, SequenceDataAbstractBaseClass)): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> <DEDENT> elif isinstance(data, (bytearray, _SeqAbstractBaseClass)): <NEW_LINE> <INDENT> self._data = bytes(data) <NEW_LINE> <DEDENT> elif isinstance(data, str): <NEW_LINE> <INDENT> self._data = bytes(data, encoding="ASCII") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError( "data should be a string, bytes, bytearray, Seq, or MutableSeq object" ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if data is not None: <NEW_LINE> <INDENT> raise ValueError("length should be None if data is None") <NEW_LINE> <DEDENT> self._data = _UndefinedSequenceData(length) <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self._data) <NEW_LINE> <DEDENT> def tomutable(self): <NEW_LINE> <INDENT> warnings.warn( "myseq.tomutable() is deprecated; please use MutableSeq(myseq) instead.", BiopythonDeprecationWarning, ) <NEW_LINE> return MutableSeq(self) <NEW_LINE> <DEDENT> def encode(self, encoding="utf-8", errors="strict"): <NEW_LINE> <INDENT> warnings.warn( "myseq.encode has been deprecated; please use bytes(myseq) instead.", BiopythonDeprecationWarning, ) <NEW_LINE> return str(self).encode(encoding, errors) <NEW_LINE> <DEDENT> def complement(self): <NEW_LINE> <INDENT> if isinstance(self._data, _UndefinedSequenceData): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> if (b"U" in self._data or b"u" in self._data) and ( b"T" in self._data or b"t" in self._data ): <NEW_LINE> <INDENT> raise ValueError("Mixed RNA/DNA found") <NEW_LINE> <DEDENT> elif b"U" in self._data or b"u" in self._data: <NEW_LINE> <INDENT> ttable = _rna_complement_table <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ttable = _dna_complement_table <NEW_LINE> <DEDENT> return Seq(self._data.translate(ttable)) <NEW_LINE> <DEDENT> def reverse_complement(self): <NEW_LINE> <INDENT> return self.complement()[::-1] <NEW_LINE> <DEDENT> def ungap(self, gap="-"): <NEW_LINE> <INDENT> if not gap: <NEW_LINE> <INDENT> raise ValueError("Gap character required.") <NEW_LINE> <DEDENT> elif len(gap) != 1 or not isinstance(gap, str): <NEW_LINE> <INDENT> raise ValueError(f"Unexpected gap character, {gap!r}") <NEW_LINE> <DEDENT> return self.replace(gap, b"") | Read-only sequence object (essentially a string with biological methods).
Like normal python strings, our basic sequence object is immutable.
This prevents you from doing my_seq[5] = "A" for example, but does allow
Seq objects to be used as dictionary keys.
The Seq object provides a number of string like methods (such as count,
find, split and strip).
The Seq object also provides some biological methods, such as complement,
reverse_complement, transcribe, back_transcribe and translate (which are
not applicable to protein sequences). | 6259906d99cbb53fe6832733 |
class Edit(AdminService): <NEW_LINE> <INDENT> name = 'zato.channel.amqp.edit' <NEW_LINE> class SimpleIO(AdminSIO): <NEW_LINE> <INDENT> request_elem = 'zato_channel_amqp_edit_request' <NEW_LINE> response_elem = 'zato_channel_amqp_edit_response' <NEW_LINE> input_required = ('id', 'cluster_id', 'name', 'is_active', 'def_id', 'queue', 'consumer_tag_prefix', 'service', 'pool_size', 'ack_mode','prefetch_count') <NEW_LINE> input_optional = ('data_format',) <NEW_LINE> output_required = ('id', 'name') <NEW_LINE> <DEDENT> def handle(self): <NEW_LINE> <INDENT> input = self.request.input <NEW_LINE> with closing(self.odb.session()) as session: <NEW_LINE> <INDENT> existing_one = session.query(ChannelAMQP.id). filter(ConnDefAMQP.cluster_id==input.cluster_id). filter(ChannelAMQP.def_id==ConnDefAMQP.id). filter(ChannelAMQP.name==input.name). filter(ChannelAMQP.id!=input.id). first() <NEW_LINE> if existing_one: <NEW_LINE> <INDENT> raise Exception('An AMQP channel `{}` already exists on this cluster'.format(input.name)) <NEW_LINE> <DEDENT> service = session.query(Service). filter(Cluster.id==input.cluster_id). filter(Service.cluster_id==Cluster.id). filter(Service.name==input.service). first() <NEW_LINE> if not service: <NEW_LINE> <INDENT> msg = 'Service [{0}] does not exist on this cluster'.format(input.service) <NEW_LINE> raise Exception(msg) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> item = session.query(ChannelAMQP).filter_by(id=input.id).one() <NEW_LINE> old_name = item.name <NEW_LINE> item.name = input.name <NEW_LINE> item.is_active = input.is_active <NEW_LINE> item.queue = input.queue <NEW_LINE> item.consumer_tag_prefix = input.consumer_tag_prefix <NEW_LINE> item.def_id = input.def_id <NEW_LINE> item.service = service <NEW_LINE> item.pool_size = input.pool_size <NEW_LINE> item.ack_mode = input.ack_mode <NEW_LINE> item.prefetch_count = input.prefetch_count <NEW_LINE> item.data_format = input.data_format <NEW_LINE> session.add(item) <NEW_LINE> session.commit() <NEW_LINE> input.action = CHANNEL.AMQP_EDIT.value <NEW_LINE> input.def_name = item.def_.name <NEW_LINE> input.id = item.id <NEW_LINE> input.old_name = old_name <NEW_LINE> input.service_name = service.name <NEW_LINE> self.broker_client.publish(input) <NEW_LINE> self.response.payload.id = item.id <NEW_LINE> self.response.payload.name = item.name <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.logger.error('Could not update the AMQP definition, e:`%s`', format_exc()) <NEW_LINE> session.rollback() <NEW_LINE> raise | Updates an AMQP channel.
| 6259906d5fc7496912d48e8e |
class ActokFinal(WaitActokStep): <NEW_LINE> <INDENT> def step_handler(self, ch, method, properties, body): <NEW_LINE> <INDENT> super().step_handler(ch, method, properties, body) <NEW_LINE> self.print_step_info() <NEW_LINE> self.success() | Checks the TAOK message and if it's OK the test is finished with a PASS result.
Expected reception: Activation Ok message (TAOK).
Sends after check: None. | 6259906d32920d7e50bc7892 |
class SectionsListAPIView(ListAPIView): <NEW_LINE> <INDENT> serializer_class = CourseSectionSerializer <NEW_LINE> permission_classes = [IsAuthenticatedOrReadOnly] <NEW_LINE> model = serializer_class.Meta.model <NEW_LINE> lookup_field = 'course__slug' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> course__slug = self.kwargs["course__slug"] <NEW_LINE> queryset = self.model.objects.filter(course__slug=course__slug) <NEW_LINE> return queryset | View that returns a list of sections & handles the creation of
sections & returns data back | 6259906d63b5f9789fe869af |
class Host(): <NEW_LINE> <INDENT> def __init__(self, uri = 'qemu:///system'): <NEW_LINE> <INDENT> self.uri = uri <NEW_LINE> <DEDENT> def libvirtTest(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> libvirt.open(self.uri) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def executeVirsh(self, command): <NEW_LINE> <INDENT> command = command.replace(";","") <NEW_LINE> c = commands.getoutput("virsh -c " + self.uri + " " + command) <NEW_LINE> return c <NEW_LINE> <DEDENT> def undefineByName(self, name): <NEW_LINE> <INDENT> connection = libvirt.open(self.uri) <NEW_LINE> domain = connection.lookupByName(name) <NEW_LINE> try: <NEW_LINE> <INDENT> domain.destroy() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> domain.undefine() <NEW_LINE> <DEDENT> def getDomains(self): <NEW_LINE> <INDENT> connection = libvirt.open(self.uri) <NEW_LINE> domainnames = connection.listDefinedDomains() <NEW_LINE> domains = [] <NEW_LINE> for domainid in domainnames: <NEW_LINE> <INDENT> dom = connection.lookupByName(domainid) <NEW_LINE> domain = Domain(self.uri, dom.name()) <NEW_LINE> domarray = {} <NEW_LINE> domarray['name'] = domain.getName() <NEW_LINE> domarray['state'] = domain.getState() <NEW_LINE> domains.append(domarray) <NEW_LINE> <DEDENT> domainids = connection.listDomainsID() <NEW_LINE> for domainid in domainids: <NEW_LINE> <INDENT> dom = connection.lookupByID(domainid) <NEW_LINE> domain = Domain(self.uri, dom.name()) <NEW_LINE> domarray = {} <NEW_LINE> domarray['name'] = domain.getName() <NEW_LINE> domarray['state'] = domain.getState() <NEW_LINE> domains.append(domarray) <NEW_LINE> <DEDENT> return domains <NEW_LINE> <DEDENT> def definexml(self, xmldesc): <NEW_LINE> <INDENT> connection = libvirt.open(self.uri) <NEW_LINE> try: <NEW_LINE> <INDENT> connection.defineXML(xmldesc) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> except libvirt.libvirtError as e: <NEW_LINE> <INDENT> return str(e) <NEW_LINE> <DEDENT> <DEDENT> def getPools(self): <NEW_LINE> <INDENT> connection= libvirt.open(self.uri) <NEW_LINE> pools = [] <NEW_LINE> for poolname in connection.listDefinedStoragePools(): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> pool.setName(poolname) <NEW_LINE> pools.append(pool) <NEW_LINE> <DEDENT> for poolname in connection.listStoragePools(): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> pool.setName(poolname) <NEW_LINE> pools.append(pool) <NEW_LINE> <DEDENT> return pools | Host wirtualizacyjny
Domyślne uri - kvm => qemu:///system | 6259906d167d2b6e312b81b4 |
class TestViewsWithoutGas(TestViews): <NEW_LINE> <INDENT> fixtures = [ 'dsmr_frontend/test_energysupplierprice.json', 'dsmr_frontend/test_statistics.json', ] <NEW_LINE> support_gas = False <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(TestViewsWithoutGas, self).setUp() <NEW_LINE> self.assertFalse(GasConsumption.objects.exists()) | Same tests as above, but without any GAS related data. | 6259906d5fcc89381b266d7d |
class Setting(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'setting' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> free_download_max_once = db.Column(db.Integer) <NEW_LINE> free_download_one_day = db.Column(db.Integer) <NEW_LINE> _free_download_step_ = db.Column(db.String(128)) <NEW_LINE> free_download_search_limit = db.Column(db.Integer) <NEW_LINE> charge_download_search_limit = db.Column(db.Integer) <NEW_LINE> free_download_speed = db.Column(db.Integer) <NEW_LINE> user_download_speed = db.Column(db.Integer) <NEW_LINE> memb_download_speed = db.Column(db.Integer) <NEW_LINE> notices = db.relationship('Notice', order_by=desc(Notice.id), backref="setting", lazy='dynamic') <NEW_LINE> @property <NEW_LINE> def free_download_step(self): <NEW_LINE> <INDENT> step = [] <NEW_LINE> for s in self._free_download_step_.split(','): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> step.append(int(s)) <NEW_LINE> <DEDENT> except ValueError as exc: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return tuple(step) <NEW_LINE> <DEDENT> @free_download_step.setter <NEW_LINE> def free_download_step(self, value): <NEW_LINE> <INDENT> if isinstance(value, list) or isinstance(value, tuple): <NEW_LINE> <INDENT> step = ','.join(str(x) for x in value) <NEW_LINE> self._free_download_step_ = step <NEW_LINE> <DEDENT> <DEDENT> free_download_step = synonym('_free_download_step_', descriptor=free_download_step) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Setting :{}>'.format(self.id) | setting 表 | 6259906d2c8b7c6e89bd5032 |
class GaussianNoiseGenerator(NoiseGenerator): <NEW_LINE> <INDENT> def __init__(self, rand=None): <NEW_LINE> <INDENT> if rand is None: <NEW_LINE> <INDENT> rand = afwMath.Random() <NEW_LINE> <DEDENT> self.rand = rand <NEW_LINE> <DEDENT> def getRandomImage(self, bb): <NEW_LINE> <INDENT> rim = afwImage.ImageF(bb.getWidth(), bb.getHeight()) <NEW_LINE> rim.setXY0(bb.getMinX(), bb.getMinY()) <NEW_LINE> afwMath.randomGaussianImage(rim, self.rand) <NEW_LINE> return rim | Abstract base for Gaussian noise generators.
| 6259906d21bff66bcd7244b3 |
class NewMonitor(Event): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> Event.__init__(self) <NEW_LINE> self.hw = kw.get('hw') <NEW_LINE> self.ip = kw.get('ip') <NEW_LINE> self.dpid = kw.get('dpid') <NEW_LINE> self.switch_port = kw.get('switch_port') <NEW_LINE> self.match = kw.get('match') <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self | NewMonitor事件,包括host的各种信息 | 6259906d2c8b7c6e89bd5033 |
class ComputeTargetPoolsAggregatedListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> pageToken = _messages.StringField(3) <NEW_LINE> project = _messages.StringField(4, required=True) | A ComputeTargetPoolsAggregatedListRequest object.
Fields:
filter: Filter expression for filtering listed resources.
maxResults: Maximum count of results to be returned.
pageToken: Tag returned by a previous list request when that list was
truncated to maxResults. Used to continue a previous list request.
project: Name of the project scoping this request. | 6259906dd486a94d0ba2d80b |
class TextDialog(Dialog): <NEW_LINE> <INDENT> _input_ports = [('label', basic_modules.String, {'optional': True, 'defaults': "['']"}), ('default', basic_modules.String, {'optional': True, 'defaults': "['']"})] <NEW_LINE> _output_ports = [('result', basic_modules.String)] <NEW_LINE> mode = QtGui.QLineEdit.Normal <NEW_LINE> def compute(self): <NEW_LINE> <INDENT> if self.has_input('title'): <NEW_LINE> <INDENT> title = self.get_input('title') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> title = 'VisTrails Dialog' <NEW_LINE> <DEDENT> label = self.get_input('label') <NEW_LINE> default = self.get_input('default') <NEW_LINE> self.cacheable_dialog = self.get_input('cacheable') <NEW_LINE> (result, ok) = QtGui.QInputDialog.getText(None, title, label, self.mode, default) <NEW_LINE> if not ok: <NEW_LINE> <INDENT> raise ModuleError(self, "Canceled") <NEW_LINE> <DEDENT> self.set_output('result', str(result)) | Ask the user to provide a string interactively.
When this module is executed, a dialog window will be shown with the given
message. Execution will continue with the user-provided string as the
output once the user confirms. If the user clicks 'cancel', execution will
stop.
Optionally, the answer from the user can be cached for this session. | 6259906d99cbb53fe6832734 |
class PasswordLoginSerializer(serializers.Serializer): <NEW_LINE> <INDENT> phone = deepcopy(phone_field) <NEW_LINE> password = serializers.CharField() | PasswordLogin serializer. | 6259906d9c8ee82313040dae |
class LanaCoinTestNet(LanaCoin): <NEW_LINE> <INDENT> name = 'test-lanacoin' <NEW_LINE> seeds = ('test1.lanacoin.com', 'test2.lanacoin.com', ) <NEW_LINE> port = 17506 <NEW_LINE> message_start = b'\xcc\xcb\xd2\x7f' <NEW_LINE> base58_prefixes = { 'PUBKEY_ADDR': 111, 'SCRIPT_ADDR': 196, 'SECRET_KEY': 239 } | Class with all the necessary LANA testing network information based on
http://www.github.com/LanaCoin/lanacoin/blob/master/src/chainparams.cpp
(date of access: 02/11/2018) | 6259906d442bda511e95d97e |
class Action27(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> raise NotImplementedError('%s not implemented' % ( str(self))) | Mouse/Keyboard->Set Num Lock on | 6259906d3539df3088ecdae9 |
class TableFrame(BoxLayout): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> super(TableFrame, self).__init__(**kw) <NEW_LINE> r, g, b = kw.get('color', prop.table_color) <NEW_LINE> x, y, w, h=self.rectangle() <NEW_LINE> with self.canvas: <NEW_LINE> <INDENT> ctx.Color(r, g, b, mode='hsv') <NEW_LINE> self._outline=vtx.Line(rectangle=(x, y, w, h), width=.5) <NEW_LINE> <DEDENT> self.bind(pos=self.on_pos_size_change, size=self.on_pos_size_change) <NEW_LINE> <DEDENT> def on_pos_size_change(self, instance, value): <NEW_LINE> <INDENT> self._outline.rectangle = self.rectangle() <NEW_LINE> <DEDENT> def rectangle(self): <NEW_LINE> <INDENT> x, y = self.pos <NEW_LINE> w, h = self.size <NEW_LINE> x += 1 <NEW_LINE> y += 1 <NEW_LINE> w -= 2 <NEW_LINE> h -= 2 <NEW_LINE> return x, y, w, h | table frame/outline | 6259906dbe8e80087fbc08da |
class ContextInjector(logging.Filter): <NEW_LINE> <INDENT> def filter(self, record): <NEW_LINE> <INDENT> current_process = ContextInjector.get_current_process() <NEW_LINE> current_hostname = socket.gethostname() <NEW_LINE> record.host = current_hostname <NEW_LINE> record.proc = current_process <NEW_LINE> record.pid = '-' <NEW_LINE> if not isinstance(current_process, str): <NEW_LINE> <INDENT> record.pid = current_process.pid <NEW_LINE> proc_name = current_process.name <NEW_LINE> if callable(proc_name): <NEW_LINE> <INDENT> proc_name = proc_name() <NEW_LINE> <DEDENT> record.proc_name = proc_name <NEW_LINE> cmd_line = current_process.cmdline <NEW_LINE> if callable(cmd_line): <NEW_LINE> <INDENT> cmd_line = cmd_line() <NEW_LINE> <DEDENT> record.command_line = " ".join(cmd_line) <NEW_LINE> <DEDENT> record.callstack = self.format_callstack() <NEW_LINE> record.url = '-' <NEW_LINE> record.args = '-' <NEW_LINE> record.form = '-' <NEW_LINE> record.username = '-' <NEW_LINE> try: <NEW_LINE> <INDENT> record.url = flask.request.url <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> record.args = flask.request.args <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> record.form = dict(flask.request.form) <NEW_LINE> if 'csrf_token' in record.form: <NEW_LINE> <INDENT> record.form['csrf_token'] = 'Was present, is cleaned up' <NEW_LINE> <DEDENT> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> record.username = "%s -- %s" % ( flask.g.user.id, flask.g.user.email) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def format_callstack(): <NEW_LINE> <INDENT> ind = 0 <NEW_LINE> for ind, frame in enumerate(f[0] for f in inspect.stack()): <NEW_LINE> <INDENT> if '__name__' not in frame.f_globals: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> modname = frame.f_globals['__name__'].split('.')[0] <NEW_LINE> if modname != "logging": <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> def _format_frame(frame): <NEW_LINE> <INDENT> return ' File "%s", line %i in %s\n %s' % (frame) <NEW_LINE> <DEDENT> stack = traceback.extract_stack() <NEW_LINE> stack = stack[:-ind] <NEW_LINE> return "\n".join([_format_frame(frame) for frame in stack]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_current_process(): <NEW_LINE> <INDENT> mypid = os.getpid() <NEW_LINE> if not psutil: <NEW_LINE> <INDENT> return "Could not import psutil for %r" % mypid <NEW_LINE> <DEDENT> for proc in psutil.process_iter(): <NEW_LINE> <INDENT> if proc.pid == mypid: <NEW_LINE> <INDENT> return proc <NEW_LINE> <DEDENT> <DEDENT> raise ValueError("Could not find process %r" % mypid) | Logging filter that adds context to log records.
Filters are typically used to "filter" log records. They declare a filter
method that can return True or False. Only records with 'True' will
actually be logged.
Here, we somewhat abuse the concept of a filter. We always return true,
but we use the opportunity to hang important contextual information on the
log record to later be used by the logging Formatter. We don't normally
want to see all this stuff in normal log records, but we *do* want to see
it when we are emailed error messages. Seeing an error, but not knowing
which host it comes from, is not that useful.
https://docs.python.org/2/howto/logging-cookbook.html#filters-contextual
This code has been originally written by Ralph Bean for the fedmsg
project:
https://github.com/fedora-infra/fedmsg/
and can be found at:
https://infrastructure.fedoraproject.org/cgit/ansible.git/tree/roles/fedmsg/base/templates/logging.py.j2 | 6259906da219f33f346c8055 |
class GameStats: <NEW_LINE> <INDENT> def __init__(self, ai_game): <NEW_LINE> <INDENT> self.settings = ai_game.settings <NEW_LINE> self.reset_stats() <NEW_LINE> <DEDENT> def reset_stats(self): <NEW_LINE> <INDENT> self.ships_left = self.settings.ship_limit | Track statistics for Alien Invasion | 6259906d7c178a314d78e812 |
class POLDICreatePeaksFromCellTestBetaQuartz(ReflectionCheckingTest): <NEW_LINE> <INDENT> data = [ ([1, 0, 0], 4.32710, 7.74737, 6), ([1, 0, 1], 3.38996, 19.7652, 12), ([1, 0, 2], 2.30725, 2.96401, 12), ([1, 0, 6], 0.88968, 3.15179, 12) ] <NEW_LINE> def runTest(self): <NEW_LINE> <INDENT> peaks_betaSiO2 = PoldiCreatePeaksFromCell( SpaceGroup="P 62 2 2", Atoms="Si 1/2 0 0 1.0 0.025; O 0.41570 0.20785 1/6 1.0 0.058", a=4.9965, c=5.4546, LatticeSpacingMin=0.885) <NEW_LINE> self.assertEqual(peaks_betaSiO2.rowCount(), 65) <NEW_LINE> self.checkReflections(peaks_betaSiO2, self.data, 1e-5) | Structure factor check for:
SiO2 (beta-quartz, high temperature), 10.1127/ejm/2/1/0063
Notes: Non-centrosymmetric, hexagonal, with coordinate 1/6 | 6259906d26068e7796d4e187 |
class EngineerList(models.Model): <NEW_LINE> <INDENT> id_engineer = models.AutoField(primary_key=True) <NEW_LINE> engineer_en = models.CharField(max_length=64) <NEW_LINE> engineer_cn = models.CharField(max_length=64) <NEW_LINE> engineer_zone = models.CharField(max_length=64) <NEW_LINE> id_brand = models.ForeignKey(SpareBrandList, null=True, blank=True) <NEW_LINE> engineer_phone = models.CharField(max_length=64) <NEW_LINE> engineer_ID = models.CharField(max_length=64) <NEW_LINE> engineer_enable = models.BooleanField(default=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '%s %s' %(self.id_brand.brand_en,self.engineer_en) | 厂商工程师名单 | 6259906d8da39b475be04a3a |
class SummonerChampionMastery(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'summoner_champion_mastery' <NEW_LINE> summ_id = db.Column(db.Integer, db.ForeignKey('summoner.id'), primary_key=True) <NEW_LINE> champ_id = db.Column(db.Integer, db.ForeignKey('champion.id'), primary_key=True) <NEW_LINE> mastery_score = db.Column(db.Integer) <NEW_LINE> def __init__(self, score, pid, cid): <NEW_LINE> <INDENT> self.mastery_score = score <NEW_LINE> self.summ_id = pid <NEW_LINE> self.champ_id = cid | Maps the db.relationship between Summoners and Champions
A Summoner can have multiple Champions
A Champion can be unlocked by multiple Summoners
Each Summoner has respective Mastery Points with a corresponding Champion
This many-to-many db.relationship is represented thru an association table | 6259906d7d43ff2487428038 |
class OxliCountGraph(OxliBinary): <NEW_LINE> <INDENT> def sniff(self, filename): <NEW_LINE> <INDENT> return OxliBinary._sniff(filename, b"01") | OxliCountGraph starts with "OXLI" + one byte version number +
8-bit binary '1'
Test file generated via::
load-into-counting.py --n_tables 1 --max-tablesize 1 \
oxli_countgraph.oxlicg khmer/tests/test-data/100-reads.fq.bz2
using khmer 2.0
>>> from galaxy.datatypes.sniff import get_test_fname
>>> fname = get_test_fname( 'sequence.csfasta' )
>>> OxliCountGraph().sniff( fname )
False
>>> fname = get_test_fname( "oxli_countgraph.oxlicg" )
>>> OxliCountGraph().sniff( fname )
True | 6259906dfff4ab517ebcf068 |
class TestFlamingo(unittest.TestCase): <NEW_LINE> <INDENT> def check_consistent(self, query, results, dist, msg=None): <NEW_LINE> <INDENT> for e in results: <NEW_LINE> <INDENT> self.assertTrue(dist >= flamingo.distance(query, e), msg=msg) <NEW_LINE> <DEDENT> <DEDENT> def check_search(self, indexer, query, expected, dist): <NEW_LINE> <INDENT> ret = indexer.search(query, dist) <NEW_LINE> self.assertEqual(ret, expected) <NEW_LINE> self.check_consistent(query, ret, dist, "Got expected array, but expected had incorrect value") <NEW_LINE> <DEDENT> def test_basic(self): <NEW_LINE> <INDENT> words = ["apple", "banana", "orange"] <NEW_LINE> indexer = flamingo.WrapperSimpleEd(words) <NEW_LINE> for w in words: <NEW_LINE> <INDENT> self.check_search(indexer, w, [w], 0) <NEW_LINE> self.check_search(indexer, w, [w], 1) <NEW_LINE> <DEDENT> words = ["ABCDEFGHIJ"[:i] for i in range(1, 10)] <NEW_LINE> indexer = flamingo.WrapperSimpleEd(words) <NEW_LINE> for d in range(5): <NEW_LINE> <INDENT> self.assertEqual(indexer.search(words[5], d), words[5 - d:6 + d]) <NEW_LINE> <DEDENT> <DEDENT> def test_barcodes(self): <NEW_LINE> <INDENT> for l in range(1, 6): <NEW_LINE> <INDENT> barcodes = all_length(l) <NEW_LINE> indexer = flamingo.WrapperSimpleEd(barcodes) <NEW_LINE> for b in barcodes: <NEW_LINE> <INDENT> self.check_search(indexer, b, [b], 0) <NEW_LINE> results = indexer.search(b, 1) <NEW_LINE> self.assertEqual(len(results), 1 + 3 * l) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_distance(self): <NEW_LINE> <INDENT> self.assertEqual(flamingo.distance("apple", "aaple"), 1) <NEW_LINE> self.assertEqual(flamingo.distance("A", "AAA"), 2) <NEW_LINE> self.assertEqual(flamingo.distance("apple", "applesauce"), 5) | Tests the flamingo WrapperSimpleEd | 6259906da8370b77170f1c15 |
class ConnectionFromController(AMP): <NEW_LINE> <INDENT> implements(IQueuer) <NEW_LINE> def __init__(self, transactionFactory, whenConnected, boxReceiver=None, locator=None): <NEW_LINE> <INDENT> super(ConnectionFromController, self).__init__(boxReceiver, locator) <NEW_LINE> self._txnFactory = transactionFactory <NEW_LINE> self.whenConnected = whenConnected <NEW_LINE> from twisted.internet import reactor <NEW_LINE> self.reactor = reactor <NEW_LINE> <DEDENT> def transactionFactory(self, *args, **kwargs): <NEW_LINE> <INDENT> txn = self._txnFactory(*args, **kwargs) <NEW_LINE> txn._queuer = self <NEW_LINE> return txn <NEW_LINE> <DEDENT> def startReceivingBoxes(self, sender): <NEW_LINE> <INDENT> super(ConnectionFromController, self).startReceivingBoxes(sender) <NEW_LINE> self.whenConnected(self) <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def enqueueWork(self, txn, workItemType, **kw): <NEW_LINE> <INDENT> work = yield workItemType.makeJob(txn, **kw) <NEW_LINE> self.callRemote(EnqueuedJob) <NEW_LINE> returnValue(work) <NEW_LINE> <DEDENT> @PerformJob.responder <NEW_LINE> def executeJobHere(self, job): <NEW_LINE> <INDENT> d = JobItem.ultimatelyPerform(self.transactionFactory, job) <NEW_LINE> d.addCallback(lambda ignored: {}) <NEW_LINE> return d | A L{ConnectionFromController} is the connection to a controller
process, in a worker process. It processes requests from its own
controller to do work. It is the opposite end of the connection from
L{ConnectionFromWorker}. | 6259906d7b25080760ed8909 |
class StringConstant( Constant, bytes ): <NEW_LINE> <INDENT> def __repr__( self ): <NEW_LINE> <INDENT> return '%s (%s)'%(self.name,super(Constant,self).__str__()) | String constants | 6259906d32920d7e50bc7894 |
class MultiFiles: <NEW_LINE> <INDENT> def __init__(self, file_list): <NEW_LINE> <INDENT> self._file = {} <NEW_LINE> self._events = {} <NEW_LINE> self._events_table = {} <NEW_LINE> self._camera_config = {} <NEW_LINE> self.camera_config = None <NEW_LINE> paths = [] <NEW_LINE> for file_name in file_list: <NEW_LINE> <INDENT> paths.append(file_name) <NEW_LINE> Provenance().add_input_file(file_name, role='r0.sub.evt') <NEW_LINE> <DEDENT> from protozfits import File <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._file[path] = File(path) <NEW_LINE> self._events_table[path] = File(path).Events <NEW_LINE> self._events[path] = next(self._file[path].Events) <NEW_LINE> if 'CameraConfig' in self._file[path].__dict__.keys(): <NEW_LINE> <INDENT> self._camera_config[path] = next(self._file[path].CameraConfig) <NEW_LINE> if(self.camera_config is None): <NEW_LINE> <INDENT> self.camera_config = self._camera_config[path] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> assert (self.camera_config) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self.next_event() <NEW_LINE> <DEDENT> def next_event(self): <NEW_LINE> <INDENT> if not self._events: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> min_path = min( self._events.items(), key=lambda item: item[1].event_id, )[0] <NEW_LINE> next_event = self._events[min_path] <NEW_LINE> try: <NEW_LINE> <INDENT> self._events[min_path] = next(self._file[min_path].Events) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> del self._events[min_path] <NEW_LINE> <DEDENT> return next_event <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> total_length = sum( len(table) for table in self._events_table.values() ) <NEW_LINE> return total_length <NEW_LINE> <DEDENT> def num_inputs(self): <NEW_LINE> <INDENT> return len(self._file) | This class open all the files in file_list and read the events following
the event_id order | 6259906d32920d7e50bc7895 |
class SourceTargetRegexpWarningDto(SegmentWarning): <NEW_LINE> <INDENT> swagger_types = { 'description': 'str' } <NEW_LINE> attribute_map = { 'description': 'description' } <NEW_LINE> def __init__(self, description=None): <NEW_LINE> <INDENT> self._description = None <NEW_LINE> self.discriminator = None <NEW_LINE> if description is not None: <NEW_LINE> <INDENT> self.description = description <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @description.setter <NEW_LINE> def description(self, description): <NEW_LINE> <INDENT> self._description = description <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> if issubclass(SourceTargetRegexpWarningDto, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = 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, SourceTargetRegexpWarningDto): <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. | 6259906d796e427e5384ffc6 |
class ReserveEquipment(models.Model): <NEW_LINE> <INDENT> reserve = models.ForeignKey('inventory.Reserve') <NEW_LINE> equipment = models.ForeignKey('inventory.Equipment') | Для хранения забронированного инвенторя который пробивает менеджер | 6259906ddd821e528d6da5a8 |
@implementer(IEncodable) <NEW_LINE> class _OPTHeader(tputil.FancyStrMixin, tputil.FancyEqMixin, object): <NEW_LINE> <INDENT> showAttributes = ( ('name', lambda n: nativeString(n.name)), 'type', 'udpPayloadSize', 'extendedRCODE', 'version', 'dnssecOK', 'options') <NEW_LINE> compareAttributes = ( 'name', 'type', 'udpPayloadSize', 'extendedRCODE', 'version', 'dnssecOK', 'options') <NEW_LINE> def __init__(self, udpPayloadSize=4096, extendedRCODE=0, version=0, dnssecOK=False, options=None): <NEW_LINE> <INDENT> self.udpPayloadSize = udpPayloadSize <NEW_LINE> self.extendedRCODE = extendedRCODE <NEW_LINE> self.version = version <NEW_LINE> self.dnssecOK = dnssecOK <NEW_LINE> if options is None: <NEW_LINE> <INDENT> options = [] <NEW_LINE> <DEDENT> self.options = options <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return Name(b'') <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return OPT <NEW_LINE> <DEDENT> def encode(self, strio, compDict=None): <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> for o in self.options: <NEW_LINE> <INDENT> o.encode(b) <NEW_LINE> <DEDENT> optionBytes = b.getvalue() <NEW_LINE> RRHeader( name=self.name.name, type=self.type, cls=self.udpPayloadSize, ttl=( self.extendedRCODE << 24 | self.version << 16 | self.dnssecOK << 15), payload=UnknownRecord(optionBytes) ).encode(strio, compDict) <NEW_LINE> <DEDENT> def decode(self, strio, length=None): <NEW_LINE> <INDENT> h = RRHeader() <NEW_LINE> h.decode(strio, length) <NEW_LINE> h.payload = UnknownRecord(readPrecisely(strio, h.rdlength)) <NEW_LINE> newOptHeader = self.fromRRHeader(h) <NEW_LINE> for attrName in self.compareAttributes: <NEW_LINE> <INDENT> if attrName not in ('name', 'type'): <NEW_LINE> <INDENT> setattr(self, attrName, getattr(newOptHeader, attrName)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def fromRRHeader(cls, rrHeader): <NEW_LINE> <INDENT> options = None <NEW_LINE> if rrHeader.payload is not None: <NEW_LINE> <INDENT> options = [] <NEW_LINE> optionsBytes = BytesIO(rrHeader.payload.data) <NEW_LINE> optionsBytesLength = len(rrHeader.payload.data) <NEW_LINE> while optionsBytes.tell() < optionsBytesLength: <NEW_LINE> <INDENT> o = _OPTVariableOption() <NEW_LINE> o.decode(optionsBytes) <NEW_LINE> options.append(o) <NEW_LINE> <DEDENT> <DEDENT> return cls( udpPayloadSize=rrHeader.cls, extendedRCODE=rrHeader.ttl >> 24, version=rrHeader.ttl >> 16 & 0xff, dnssecOK=(rrHeader.ttl & 0xffff) >> 15, options=options ) | An OPT record header.
@ivar name: The DNS name associated with this record. Since this
is a pseudo record, the name is always an L{Name} instance
with value b'', which represents the DNS root zone. This
attribute is a readonly property.
@ivar type: The DNS record type. This is a fixed value of 41
(C{dns.OPT} for OPT Record. This attribute is a readonly
property.
@see: L{_OPTHeader.__init__} for documentation of other public
instance attributes.
@see: L{https://tools.ietf.org/html/rfc6891#section-6.1.2}
@since: 13.2 | 6259906d8e71fb1e983bd316 |
class FollowJoystick(Command): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("FollowJoystick") <NEW_LINE> self.ahrs = AHRS.create_spi() <NEW_LINE> self.stick = oi.joystick <NEW_LINE> self.angle = 0 <NEW_LINE> self.stime = None <NEW_LINE> self.xInv = -1 <NEW_LINE> self.yInv = -1 <NEW_LINE> self.zInv = 1 <NEW_LINE> if config.centric: <NEW_LINE> <INDENT> self.angle = self.ahrs.getAngle() <NEW_LINE> <DEDENT> <DEDENT> def initalize(self): <NEW_LINE> <INDENT> self.stime = time.time() <NEW_LINE> <DEDENT> def dumpInfo(self, x_speed, y_speed, z_speed, angle): <NEW_LINE> <INDENT> subsystems.smartdashboard.putNumber("x_speed", x_speed) <NEW_LINE> subsystems.smartdashboard.putNumber("y_speed", y_speed) <NEW_LINE> subsystems.smartdashboard.putNumber("z_speed", z_speed) <NEW_LINE> subsystems.smartdashboard.putNumber("angle", angle) <NEW_LINE> <DEDENT> def inputNoise(self, input): <NEW_LINE> <INDENT> return input if abs(input) < 0.02 else 0 <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if self.stick.getRawButton(2): <NEW_LINE> <INDENT> self.ahrs.reset() <NEW_LINE> <DEDENT> currentRotationRate = self.stick.getTwist() <NEW_LINE> subsystems.drivetrain.driveCartesian( self.inputNoise(oi.joystick.getX()) * self.xInv, self.inputNoise(oi.joystick.getY()) * self.yInv, currentRotationRate * self.zInv, self.angle, ) <NEW_LINE> <DEDENT> def end(self): <NEW_LINE> <INDENT> subsystems.drivetrain.set(0, 0, 0, 0) <NEW_LINE> <DEDENT> def isFinished(self): <NEW_LINE> <INDENT> return self.stime is not None and time.time() - self.stime > self.len <NEW_LINE> <DEDENT> def interrupted(self): <NEW_LINE> <INDENT> self.end() | Command that reads the joystick's y axis and use that value to control
the speed of the SingleMotor subsystem.
This operates during the Teleop period of a competition. | 6259906d1f5feb6acb16443f |
class Dog: <NEW_LINE> <INDENT> def speak(self): <NEW_LINE> <INDENT> return "Woof!" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Dog" | one of the object to by returned | 6259906d7d847024c075dc2b |
class NativeStringToBytesTests(TestCase): <NEW_LINE> <INDENT> def test_list(self): <NEW_LINE> <INDENT> l = [1, 2, 3] <NEW_LINE> self.assertThat( lambda: native_string_to_bytes(l), raises_exception( TypeError, ), ) <NEW_LINE> <DEDENT> def test_none(self): <NEW_LINE> <INDENT> self.assertRaises( TypeError, lambda: native_string_to_bytes(None), ) <NEW_LINE> <DEDENT> def test_bytes_py2(self): <NEW_LINE> <INDENT> if str is not bytes: <NEW_LINE> <INDENT> self.skipTest("skipping test on Python 3") <NEW_LINE> <DEDENT> self.assertThat( native_string_to_bytes(b"hello world"), Equals(b"hello world"), ) <NEW_LINE> <DEDENT> def test_bytes_py3(self): <NEW_LINE> <INDENT> if str is bytes: <NEW_LINE> <INDENT> self.skipTest("skipping test on Python 2") <NEW_LINE> <DEDENT> self.assertThat( lambda: native_string_to_bytes(b"hello world"), raises_exception( TypeError, ), ) <NEW_LINE> <DEDENT> def test_unicode_py2(self): <NEW_LINE> <INDENT> if str is not bytes: <NEW_LINE> <INDENT> self.skipTest("skipping test on Python 3.") <NEW_LINE> <DEDENT> self.assertThat( lambda: native_string_to_bytes(u"hello world"), raises_exception( TypeError, ), ) <NEW_LINE> <DEDENT> def test_unicode_py3(self): <NEW_LINE> <INDENT> if str is bytes: <NEW_LINE> <INDENT> self.skipTest( "native_string_to_bytes() does not accept unicode input on " "Python 2", ) <NEW_LINE> <DEDENT> self.assertThat( native_string_to_bytes(u"hello world"), Equals(b"hello world"), ) | Tests for ``native_string_to_bytes``. | 6259906d66673b3332c31c4c |
class EntityDeleteRequest(ODataHttpRequest): <NEW_LINE> <INDENT> def __init__(self, url, connection, handler, entity_set, entity_key): <NEW_LINE> <INDENT> super(EntityDeleteRequest, self).__init__(url, connection, handler) <NEW_LINE> self._logger = logging.getLogger(LOGGER_NAME) <NEW_LINE> self._entity_set = entity_set <NEW_LINE> self._entity_key = entity_key <NEW_LINE> self._logger.debug('New instance of EntityDeleteRequest for entity type: %s', entity_set.entity_type.name) <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return self._entity_set.name + self._entity_key.to_key_string() <NEW_LINE> <DEDENT> def get_method(self): <NEW_LINE> <INDENT> return 'DELETE' | Used for deleting entity (DELETE operations on a single entity) | 6259906d4428ac0f6e659d81 |
class InvalidMetaName(Exception): <NEW_LINE> <INDENT> pass | Raised for invalid metadata names. | 6259906d99cbb53fe6832737 |
@test(groups=["rsdns.eventlet"], enabled=CAN_USE_EVENTLET) <NEW_LINE> class RsdnsEventletTests(object): <NEW_LINE> <INDENT> def assert_record_created(self, index): <NEW_LINE> <INDENT> msg = "Record %d wasn't created!" % index <NEW_LINE> assert_true(index in self.new_records, msg) <NEW_LINE> <DEDENT> @before_class(enabled=WHITE_BOX and RUN_DNS) <NEW_LINE> def create_driver(self): <NEW_LINE> <INDENT> self.driver = utils.import_object(FLAGS.dns_driver) <NEW_LINE> self.entry_factory = RsDnsInstanceEntryFactory() <NEW_LINE> self.test_uuid = uuid.uuid4().hex <NEW_LINE> self.new_records = {} <NEW_LINE> <DEDENT> def make_record(self, index): <NEW_LINE> <INDENT> uuid = "eventlet-%s-%d" % (self.test_uuid, index) <NEW_LINE> instance = {'uuid': uuid} <NEW_LINE> entry = self.entry_factory.create_entry(instance) <NEW_LINE> entry.name = uuid + "." + self.entry_factory.default_dns_zone.name <NEW_LINE> entry.content = "123.123.123.123" <NEW_LINE> self.driver.create_entry(entry) <NEW_LINE> self.new_records[index] = True <NEW_LINE> <DEDENT> @test(enabled=WHITE_BOX and RUN_DNS) <NEW_LINE> def use_dns_from_a_single_thread(self): <NEW_LINE> <INDENT> self.new_records = {} <NEW_LINE> for index in range(-1, -5, -1): <NEW_LINE> <INDENT> self.make_record(index) <NEW_LINE> self.assert_record_created(index) <NEW_LINE> <DEDENT> <DEDENT> @test(enabled=WHITE_BOX and RUN_DNS) <NEW_LINE> def use_dns_from_multiple_greenthreads(self): <NEW_LINE> <INDENT> self.new_records = {} <NEW_LINE> def make_record(index): <NEW_LINE> <INDENT> def __cb(): <NEW_LINE> <INDENT> self.make_record(index) <NEW_LINE> self.assert_record_created(index) <NEW_LINE> return index <NEW_LINE> <DEDENT> return __cb <NEW_LINE> <DEDENT> pile = eventlet.GreenPile() <NEW_LINE> indices = range(1, 4) <NEW_LINE> for index in indices: <NEW_LINE> <INDENT> pile.spawn(make_record(index)) <NEW_LINE> <DEDENT> list(pile) <NEW_LINE> for index in indices: <NEW_LINE> <INDENT> self.assert_record_created(index) | Makes sure the RSDNS client can be used from multiple green threads. | 6259906d009cb60464d02d84 |
class Segment(object): <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> assert text is None or isinstance(text, str) <NEW_LINE> if text is None: <NEW_LINE> <INDENT> self.tokens = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = re.sub(CLEANUP_REGEXES["img"], "token_img", text) <NEW_LINE> text = re.sub(CLEANUP_REGEXES["html"], '', text) <NEW_LINE> text = re.sub(CLEANUP_REGEXES["tags"], '', text) <NEW_LINE> text = re.sub(CLEANUP_REGEXES["url"], "token_url", text) <NEW_LINE> self.tokens = preprocess(text) <NEW_LINE> <DEDENT> self.terms = set(self.tokens) <NEW_LINE> self.document = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' '.join(self.tokens).__str__() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ' '.join(self.tokens).__repr__() | A document segment object that corresponds to the
<OrgQSubject>, <OrgQBody>, <RelQSubject>, <RelQBody>, or <RelCText>
XML element from SemEval 2016/2017 Task 3 datasets. | 6259906d1b99ca400229015d |
class Sentence(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.items: List[TransItem] = [] <NEW_LINE> <DEDENT> def best_for_flags(self, flags: Flags) -> List[TransItem]: <NEW_LINE> <INDENT> best_score: int = 0 <NEW_LINE> best_list: List[TransItem] = [] <NEW_LINE> for item in self.items: <NEW_LINE> <INDENT> score = item.score(flags) <NEW_LINE> if score == best_score: <NEW_LINE> <INDENT> best_list.append(item) <NEW_LINE> <DEDENT> elif score > best_score: <NEW_LINE> <INDENT> best_list = [item] <NEW_LINE> best_score = score <NEW_LINE> <DEDENT> <DEDENT> return best_list <NEW_LINE> <DEDENT> def render(self, flags: Flags) -> Text: <NEW_LINE> <INDENT> return random.choice(self.best_for_flags(flags)).value <NEW_LINE> <DEDENT> def append(self, item: TransItem): <NEW_LINE> <INDENT> self.items.append(item) <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> return bool(self.items) <NEW_LINE> <DEDENT> def update(self, new: 'Sentence', flags: Flags): <NEW_LINE> <INDENT> items = [i for i in self.items if i.flags != flags] <NEW_LINE> items.extend(new.items) <NEW_LINE> self.items = items | A single sentence. The main goal of this class is to provide an easy way to
get a random sentence from the list and to see if the list is valid. | 6259906d3317a56b869bf16b |
class Creator: <NEW_LINE> <INDENT> def Name(self): <NEW_LINE> <INDENT> return "none" <NEW_LINE> <DEDENT> def Create(self, theGraphEditor): <NEW_LINE> <INDENT> return none <NEW_LINE> <DEDENT> def CheckDirtyAndCreate(self, theGraphEditor): <NEW_LINE> <INDENT> if theGraphEditor.dirty == 1: <NEW_LINE> <INDENT> if not askokcancel("Open Graph", "Graph changed since last saved. Do you want to overwrite it?"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> self.Create(theGraphEditor) | This class provides an abstract Creator as
a base for actual Creator implementations | 6259906d7047854f46340c06 |
class MsgAck(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.start_chunk = 0 <NEW_LINE> self.end_chunk = 0 <NEW_LINE> self.one_way_delay_sample = 0 <NEW_LINE> <DEDENT> def BuildBinaryMessage(self): <NEW_LINE> <INDENT> wb = bytearray() <NEW_LINE> wb[0:] = pack('>cIIQ', bytes([MsgTypes.ACK]), self.start_chunk, self.end_chunk, self.one_way_delay_sample) <NEW_LINE> return wb <NEW_LINE> <DEDENT> def ParseReceivedData(self, data): <NEW_LINE> <INDENT> contents = unpack('>IIQ', data) <NEW_LINE> self.start_chunk = contents[0] <NEW_LINE> self.end_chunk = contents[1] <NEW_LINE> self.one_way_delay_sample = contents[2] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str("[ACK] Start: {0}; End: {1}; Delay sample: {2};" .format( self.start_chunk, self.end_chunk, self.one_way_delay_sample)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() | A class representing ACK message | 6259906d3346ee7daa338286 |
class SoftAssertionError(AssertionError): <NEW_LINE> <INDENT> def __init__(self, failed_assertions): <NEW_LINE> <INDENT> self.failed_assertions = failed_assertions <NEW_LINE> super(SoftAssertionError, self).__init__(str(self)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '\n'.join(self.failed_assertions) | Exception class containing failed assertions | 6259906d2c8b7c6e89bd5037 |
class InvalidRow: <NEW_LINE> <INDENT> def __init__(self, number, validation_error, values): <NEW_LINE> <INDENT> self.number = number <NEW_LINE> self.error = validation_error <NEW_LINE> self.values = values <NEW_LINE> try: <NEW_LINE> <INDENT> self.error_dict = validation_error.message_dict <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.error_dict = {NON_FIELD_ERRORS: validation_error.messages} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def field_specific_errors(self): <NEW_LINE> <INDENT> return { key: value for key, value in self.error_dict.items() if key != NON_FIELD_ERRORS } <NEW_LINE> <DEDENT> @property <NEW_LINE> def non_field_specific_errors(self): <NEW_LINE> <INDENT> return self.error_dict.get(NON_FIELD_ERRORS, []) <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_count(self): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for error_list in self.error_dict.values(): <NEW_LINE> <INDENT> count += len(error_list) <NEW_LINE> <DEDENT> return count | A row that resulted in one or more ``ValidationError`` being raised during import. | 6259906d7b180e01f3e49c8c |
class DeleteMediaByID(RestServlet): <NEW_LINE> <INDENT> PATTERNS = admin_patterns("/media/(?P<server_name>[^/]*)/(?P<media_id>[^/]*)$") <NEW_LINE> def __init__(self, hs: "HomeServer"): <NEW_LINE> <INDENT> self.store = hs.get_datastore() <NEW_LINE> self.auth = hs.get_auth() <NEW_LINE> self.server_name = hs.hostname <NEW_LINE> self.media_repository = hs.get_media_repository() <NEW_LINE> <DEDENT> async def on_DELETE( self, request: SynapseRequest, server_name: str, media_id: str ) -> Tuple[int, JsonDict]: <NEW_LINE> <INDENT> await assert_requester_is_admin(self.auth, request) <NEW_LINE> if self.server_name != server_name: <NEW_LINE> <INDENT> raise SynapseError(HTTPStatus.BAD_REQUEST, "Can only delete local media") <NEW_LINE> <DEDENT> if await self.store.get_local_media(media_id) is None: <NEW_LINE> <INDENT> raise NotFoundError("Unknown media") <NEW_LINE> <DEDENT> logging.info("Deleting local media by ID: %s", media_id) <NEW_LINE> deleted_media, total = await self.media_repository.delete_local_media_ids( [media_id] ) <NEW_LINE> return HTTPStatus.OK, {"deleted_media": deleted_media, "total": total} | Delete local media by a given ID. Removes it from this server. | 6259906d1f5feb6acb164441 |
class CoffeeMaker(DeviceWithOpState, DeviceWithPrograms, DeviceWithRemoteStart): <NEW_LINE> <INDENT> PROGRAMS = [ {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.Espresso"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoMacchiato"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.Coffee"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.Cappuccino"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.LatteMacchiato"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.CaffeLatte"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Americano"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.EspressoDoppio"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.FlatWhite"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Galao"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.MilkFroth"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.WarmMilk"}, {"name": "ConsumerProducts.CoffeeMaker.Program.Beverage.Ristretto"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Cortado"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeCortado"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.WienerMelange"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KleinerBrauner"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.GrosserBrauner"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Verlaengerter"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.VerlaengerterBraun"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeConLeche"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.CafeAuLait"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Doppio"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Kaapi"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.KoffieVerkeerd"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.Garoto"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.RedEye"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.BlackEye"}, {"name": "ConsumerProducts.CoffeeMaker.Program.CoffeeWorld.DeadEye"}, ] <NEW_LINE> power_off_state = BSH_POWER_STANDBY <NEW_LINE> def get_entity_info(self): <NEW_LINE> <INDENT> remote_start = self.get_remote_start() <NEW_LINE> op_state_sensor = self.get_opstate_sensor() <NEW_LINE> program_sensors = self.get_program_sensors() <NEW_LINE> program_switches = self.get_program_switches() <NEW_LINE> return { "binary_sensor": [remote_start], "switch": program_switches, "sensor": program_sensors + op_state_sensor, } | Coffee maker class. | 6259906d7d847024c075dc2d |
class Obstacle(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, x, y,filename,directory = ''): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image,self.rect = load_image(filename,directory,-1) <NEW_LINE> self.rect.x = x <NEW_LINE> self.rect.y = y | This class represents the obstacles. | 6259906d99cbb53fe6832739 |
class UserQuota(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRUCT, 'throughput', (emq.queue.ttypes.Throughput, emq.queue.ttypes.Throughput.thrift_spec), None, ), (2, TType.I64, 'queueNumber', None, None, ), ) <NEW_LINE> def __init__(self, throughput=None, queueNumber=None,): <NEW_LINE> <INDENT> self.throughput = throughput <NEW_LINE> self.queueNumber = queueNumber <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.throughput = emq.queue.ttypes.Throughput() <NEW_LINE> self.throughput.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.I64: <NEW_LINE> <INDENT> self.queueNumber = iprot.readI64(); <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('UserQuota') <NEW_LINE> if self.throughput is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('throughput', TType.STRUCT, 1) <NEW_LINE> self.throughput.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.queueNumber is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('queueNumber', TType.I64, 2) <NEW_LINE> oprot.writeI64(self.queueNumber) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.throughput) <NEW_LINE> value = (value * 31) ^ hash(self.queueNumber) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Copyright 2015, Xiaomi.
All rights reserved.
Author: [email protected]
Attributes:
- throughput: The restriction of user throughput;
- queueNumber: The number of queues owned by one user;
| 6259906dfff4ab517ebcf06b |
class StatCache(object): <NEW_LINE> <INDENT> _Key = NamedTuple("_Key", (("path", Text), ("follow_symlink", bool))) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._cache = {} <NEW_LINE> <DEDENT> def Get(self, path: Text, follow_symlink: bool = True) -> Stat: <NEW_LINE> <INDENT> key = self._Key(path=path, follow_symlink=follow_symlink) <NEW_LINE> try: <NEW_LINE> <INDENT> return self._cache[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> value = Stat.FromPath(path, follow_symlink=follow_symlink) <NEW_LINE> self._cache[key] = value <NEW_LINE> if not follow_symlink and not value.IsSymlink(): <NEW_LINE> <INDENT> self._cache[self._Key(path=path, follow_symlink=True)] = value <NEW_LINE> <DEDENT> return value | An utility class for avoiding unnecessary syscalls to `[l]stat`.
This class is useful in situations where manual bookkeeping of stat results
in order to prevent extra system calls becomes tedious and complicates control
flow. This class makes sure that no unnecessary system calls are made and is
smart enough to cache symlink results when a file is not a symlink. | 6259906d4527f215b58eb5c8 |
class CustomUserManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, username, password, **extra_fields): <NEW_LINE> <INDENT> user = self.model(username=username, **extra_fields) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_merchant(self, username, password, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault('is_merchant', True) <NEW_LINE> extra_fields.setdefault('is_active', True) <NEW_LINE> if extra_fields.get('is_merchant') is not True: <NEW_LINE> <INDENT> raise ValueError(_('Merchant must have is_merchant=True.')) <NEW_LINE> <DEDENT> return self.create_user(username, password, **extra_fields) <NEW_LINE> <DEDENT> def create_superuser(self, username, password, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault('is_staff', True) <NEW_LINE> extra_fields.setdefault('is_superuser', True) <NEW_LINE> extra_fields.setdefault('is_active', True) <NEW_LINE> if extra_fields.get('is_superuser') is not True: <NEW_LINE> <INDENT> raise ValueError(_('Superuser must have is_superuser=True.')) <NEW_LINE> <DEDENT> return self.create_user(username, password, **extra_fields) | Custom user model manager where email is the unique identifiers
for authentication instead of usernames. | 6259906d0a50d4780f7069e9 |
class V3ClusterMember(NamedTuple): <NEW_LINE> <INDENT> id: int <NEW_LINE> name: str <NEW_LINE> peer_urls: List[str] <NEW_LINE> client_urls: List[str] | Represent ectd cluster node (v3) and its parameters
:param id: Unique node id
:type id: int
:param name: Unique node name (usually hostname)
:type name: str
:param peer_urls: List of URLs advertised to peers
:type peer_urls: List[str]
:param client_urls: List of URLs advertised to clients
:type client_urls: List[str] | 6259906d97e22403b383c758 |
class QuadRule(object): <NEW_LINE> <INDENT> def __init__(self, order, dimension): <NEW_LINE> <INDENT> self._order = order <NEW_LINE> self._dimension = dimension <NEW_LINE> self._points = [None] * (dimension + 1) <NEW_LINE> self._weights = [None] * (dimension + 1) <NEW_LINE> self._set_data() <NEW_LINE> <DEDENT> def _set_data(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def order(self): <NEW_LINE> <INDENT> return self._order <NEW_LINE> <DEDENT> @property <NEW_LINE> def dimension(self): <NEW_LINE> <INDENT> return self._dimension <NEW_LINE> <DEDENT> @property <NEW_LINE> def points(self): <NEW_LINE> <INDENT> return copy.deepcopy(self._points) <NEW_LINE> <DEDENT> @property <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> return copy.deepcopy(self._weights) | Provides an abstract base class for all quadrature rules.
Parameters
----------
order : int
The polynomial order up to which the quadrature should be exact | 6259906dcb5e8a47e493cdab |
class Authorization(Find, Post): <NEW_LINE> <INDENT> path = "v1/payments/authorization" <NEW_LINE> def capture(self, attributes): <NEW_LINE> <INDENT> return self.post('capture', attributes, Capture) <NEW_LINE> <DEDENT> def void(self): <NEW_LINE> <INDENT> return self.post('void', {}, self) <NEW_LINE> <DEDENT> def reauthorize(self): <NEW_LINE> <INDENT> return self.post('reauthorize', self, self) | Enables looking up, voiding and capturing authorization and reauthorize payments
Helpful links::
https://developer.paypal.com/docs/api/#authorizations
https://developer.paypal.com/docs/integration/direct/capture-payment/#authorize-the-payment
Usage::
>>> authorization = Authorization.find("")
>>> capture = authorization.capture({ "amount": { "currency": "USD", "total": "1.00" } })
>>> authorization.void() # return True or False | 6259906d8da39b475be04a3e |
class LotteryLotto(Lottery): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LotteryLotto, self).__init__() <NEW_LINE> self._name = "Lotto" <NEW_LINE> self._sets_of_balls = 1 <NEW_LINE> self._main_balls = SetOfBalls("main", 59) <NEW_LINE> self._available_parsers.append(LotteryParserLottoNL()) <NEW_LINE> self._available_parsers.append(LotteryParserLottoMW()) <NEW_LINE> self._line_generation_methods.append( LotteryTicketLineGeneratorLotto1()) <NEW_LINE> self._line_generation_methods.append( LotteryTicketLineGeneratorLotto1A()) <NEW_LINE> self._line_generation_methods.append( LotteryTicketLineGeneratorLotto2()) <NEW_LINE> self._line_generation_methods.append( LotteryTicketLineGeneratorLotto2A()) <NEW_LINE> self._stats_generation_methods.append( LotteryStatsGenerationMethodLotto1()) <NEW_LINE> LOGGER.info("Initialised parsers:") <NEW_LINE> for parser in self._available_parsers: <NEW_LINE> <INDENT> LOGGER.info(parser.name) <NEW_LINE> <DEDENT> <DEDENT> def get_new_draw(self): <NEW_LINE> <INDENT> return LottoDraw() <NEW_LINE> <DEDENT> def get_sets_of_balls(self): <NEW_LINE> <INDENT> return [self._main_balls] <NEW_LINE> <DEDENT> def get_balls_in_date_range(self, oldest_date, newest_date): <NEW_LINE> <INDENT> LOGGER.debug("LL:gbidr, len %d, from %s to %s", len(self.draws), str(oldest_date), str(newest_date)) <NEW_LINE> main_balls = [] <NEW_LINE> for lottery_draw in self.draws: <NEW_LINE> <INDENT> LOGGER.debug("LL:gbidr, lottery draw date %s", str(lottery_draw.draw_date)) <NEW_LINE> gt_oldest = lottery_draw.draw_date >= oldest_date <NEW_LINE> lt_newest = lottery_draw.draw_date <= newest_date <NEW_LINE> LOGGER.debug("LL:gbidr, lottery draw date %s, gt %d, lt %d", str(lottery_draw.draw_date), gt_oldest, lt_newest) <NEW_LINE> if gt_oldest and lt_newest: <NEW_LINE> <INDENT> LOGGER.debug("LL:gbidr, draw: %d", lottery_draw.main_balls[0]) <NEW_LINE> main_balls.append(lottery_draw.main_balls[0]) <NEW_LINE> main_balls.append(lottery_draw.main_balls[1]) <NEW_LINE> main_balls.append(lottery_draw.main_balls[2]) <NEW_LINE> main_balls.append(lottery_draw.main_balls[3]) <NEW_LINE> main_balls.append(lottery_draw.main_balls[4]) <NEW_LINE> main_balls.append(lottery_draw.main_balls[5]) <NEW_LINE> main_balls.append(lottery_draw.bonus_ball) <NEW_LINE> <DEDENT> <DEDENT> return (main_balls, []) | The UK Lotto lottery. | 6259906d4428ac0f6e659d84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.