code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class TestHoneywellRound(unittest.TestCase): <NEW_LINE> <INDENT> def setup_method(self, method): <NEW_LINE> <INDENT> def fake_temperatures(force_refresh=None): <NEW_LINE> <INDENT> temps = [ {'id': '1', 'temp': 20, 'setpoint': 21, 'thermostat': 'main', 'name': 'House'}, {'id': '2', 'temp': 21, 'setpoint': 22, 'thermostat': 'DOMESTIC_HOT_WATER'}, ] <NEW_LINE> return temps <NEW_LINE> <DEDENT> self.device = mock.MagicMock() <NEW_LINE> self.device.temperatures.side_effect = fake_temperatures <NEW_LINE> self.round1 = honeywell.RoundThermostat(self.device, '1', True, 16) <NEW_LINE> self.round2 = honeywell.RoundThermostat(self.device, '2', False, 17) <NEW_LINE> <DEDENT> def test_attributes(self): <NEW_LINE> <INDENT> self.assertEqual('House', self.round1.name) <NEW_LINE> self.assertEqual(TEMP_CELSIUS, self.round1.temperature_unit) <NEW_LINE> self.assertEqual(20, self.round1.current_temperature) <NEW_LINE> self.assertEqual(21, self.round1.target_temperature) <NEW_LINE> self.assertFalse(self.round1.is_away_mode_on) <NEW_LINE> self.assertEqual('Hot Water', self.round2.name) <NEW_LINE> self.assertEqual(TEMP_CELSIUS, self.round2.temperature_unit) <NEW_LINE> self.assertEqual(21, self.round2.current_temperature) <NEW_LINE> self.assertEqual(None, self.round2.target_temperature) <NEW_LINE> self.assertFalse(self.round2.is_away_mode_on) <NEW_LINE> <DEDENT> def test_away_mode(self): <NEW_LINE> <INDENT> self.assertFalse(self.round1.is_away_mode_on) <NEW_LINE> self.round1.turn_away_mode_on() <NEW_LINE> self.assertTrue(self.round1.is_away_mode_on) <NEW_LINE> self.assertEqual(self.device.set_temperature.call_count, 1) <NEW_LINE> self.assertEqual( self.device.set_temperature.call_args, mock.call('House', 16) ) <NEW_LINE> self.device.set_temperature.reset_mock() <NEW_LINE> self.round1.turn_away_mode_off() <NEW_LINE> self.assertFalse(self.round1.is_away_mode_on) <NEW_LINE> self.assertEqual(self.device.cancel_temp_override.call_count, 1) <NEW_LINE> self.assertEqual( self.device.cancel_temp_override.call_args, mock.call('House') ) <NEW_LINE> <DEDENT> def test_set_temperature(self): <NEW_LINE> <INDENT> self.round1.set_temperature(temperature=25) <NEW_LINE> self.assertEqual(self.device.set_temperature.call_count, 1) <NEW_LINE> self.assertEqual( self.device.set_temperature.call_args, mock.call('House', 25) ) <NEW_LINE> <DEDENT> def test_set_operation_mode(self: unittest.TestCase) -> None: <NEW_LINE> <INDENT> self.round1.set_operation_mode('cool') <NEW_LINE> self.assertEqual('cool', self.round1.current_operation) <NEW_LINE> self.assertEqual('cool', self.device.system_mode) <NEW_LINE> self.round1.set_operation_mode('heat') <NEW_LINE> self.assertEqual('heat', self.round1.current_operation) <NEW_LINE> self.assertEqual('heat', self.device.system_mode) | A test class for Honeywell Round thermostats. | 62599072a05bb46b3848bd9d |
@content( 'Password Resets', icon='icon-tags' ) <NEW_LINE> @implementer(IPasswordResets) <NEW_LINE> class PasswordResets(Folder): <NEW_LINE> <INDENT> def _gen_random_token(self): <NEW_LINE> <INDENT> length = random.choice(range(10, 16)) <NEW_LINE> chars = string.letters + string.digits <NEW_LINE> return ''.join(random.choice(chars) for _ in range(length)) <NEW_LINE> <DEDENT> def add_reset(self, user): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> token = self._gen_random_token() <NEW_LINE> if not token in self: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> reset = PasswordReset() <NEW_LINE> self[token] = reset <NEW_LINE> reset.__acl__ = [(Allow, Everyone, ('sdi.view',))] <NEW_LINE> objectmap = self.find_service('objectmap') <NEW_LINE> objectmap.connect(user, reset, UserToPasswordReset) <NEW_LINE> return reset | Object representing the current set of password reset requests | 62599072627d3e7fe0e0876b |
class reActiveRas(Handler): <NEW_LINE> <INDENT> def control(self): <NEW_LINE> <INDENT> self.is_valid(self.ras_ip, str) <NEW_LINE> self.is_valid_content(self.ras_ip, self.IP_PATTERN) <NEW_LINE> <DEDENT> def setup(self, ras_ip): <NEW_LINE> <INDENT> self.ras_ip = ras_ip | Reactive ras method class. | 625990725166f23b2e244cb7 |
class WebSocketView(web.View): <NEW_LINE> <INDENT> @asyncio.coroutine <NEW_LINE> def get(self): <NEW_LINE> <INDENT> ws = web.WebSocketResponse() <NEW_LINE> dispatch = dispatcher.Dispatcher(ws) <NEW_LINE> yield from ws.prepare(self.request) <NEW_LINE> dispatch.event(events.create_web_socket()) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = yield from ws.receive() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if msg.tp == aiohttp.MsgType.text: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> event = events.parse_event(msg.data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> event = events.close_web_socket() <NEW_LINE> ws.send_str(event.to_json()) <NEW_LINE> <DEDENT> if event.etype == 'close_web_socket': <NEW_LINE> <INDENT> yield from ws.close() <NEW_LINE> break <NEW_LINE> <DEDENT> if event.etype == 'user_input': <NEW_LINE> <INDENT> ws.send_str(event.to_json()) <NEW_LINE> dispatch.event(event) <NEW_LINE> <DEDENT> <DEDENT> elif msg.tp == aiohttp.MsgType.error: <NEW_LINE> <INDENT> print('websocket connection closed with exception %s' % ws.exception()) <NEW_LINE> <DEDENT> <DEDENT> dispatch.event(events.close_web_socket()) <NEW_LINE> print('websocket connection closed') <NEW_LINE> return ws | Websocket endpoint. | 625990725fcc89381b266dc9 |
class Bundle(object): <NEW_LINE> <INDENT> def __init__(self, name, path, url, files, type): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.path = path <NEW_LINE> self.url = url <NEW_LINE> if not url.endswith("/"): <NEW_LINE> <INDENT> raise ValueError("Bundle URLs must end with a '/'.") <NEW_LINE> <DEDENT> self.files = files <NEW_LINE> self.type = type <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def check_attr(cls, attrs, attr): <NEW_LINE> <INDENT> errmsg = "Invalid bundle: %r attribute %r required." % (attrs, attr) <NEW_LINE> assert attr in attrs, errmsg <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, attrs): <NEW_LINE> <INDENT> for attr in ("type", "name", "path", "url", "files"): <NEW_LINE> <INDENT> cls.check_attr(attrs, attr) <NEW_LINE> <DEDENT> if attrs["type"] == "javascript": <NEW_LINE> <INDENT> return JavascriptBundle(attrs["name"], attrs["path"], attrs["url"], attrs["files"], attrs["type"], attrs.get("minify", False), attrs.get("minify_new_lines", True)) <NEW_LINE> <DEDENT> elif attrs["type"] == "css": <NEW_LINE> <INDENT> return CssBundle(attrs["name"], attrs["path"], attrs["url"], attrs["files"], attrs["type"], attrs.get("minify", False)) <NEW_LINE> <DEDENT> elif attrs["type"] == "png-sprite": <NEW_LINE> <INDENT> cls.check_attr(attrs, "css_file") <NEW_LINE> return PngSpriteBundle(attrs["name"], attrs["path"], attrs["url"], attrs["files"], attrs["type"], attrs["css_file"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise InvalidBundleType(attrs["type"]) <NEW_LINE> <DEDENT> <DEDENT> def get_paths(self): <NEW_LINE> <INDENT> return [os.path.join(self.path, f) for f in self.files] <NEW_LINE> <DEDENT> def get_extension(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_bundle_filename(self): <NEW_LINE> <INDENT> return self.name + self.get_extension() <NEW_LINE> <DEDENT> def get_bundle_path(self): <NEW_LINE> <INDENT> filename = self.get_bundle_filename() <NEW_LINE> return os.path.join(self.path, filename) <NEW_LINE> <DEDENT> def get_bundle_url(self): <NEW_LINE> <INDENT> filename = self.get_bundle_filename() <NEW_LINE> version = versioning.get_bundle_versions().get(self.name, filename) <NEW_LINE> return self.url + filename + "?" + version <NEW_LINE> <DEDENT> def make_bundle(self, versioner): <NEW_LINE> <INDENT> self._make_bundle() <NEW_LINE> if versioner: <NEW_LINE> <INDENT> versioner.update_bundle_version(self) <NEW_LINE> <DEDENT> <DEDENT> def do_text_bundle(self, minifier=None): <NEW_LINE> <INDENT> with open(self.get_bundle_path(), "w+") as output: <NEW_LINE> <INDENT> generator = concatenate_files(self.get_paths()) <NEW_LINE> if minifier: <NEW_LINE> <INDENT> output.write(minifier("".join(generator))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output.write("".join(generator)) | Base class for a bundle of media files.
A bundle is a collection of related static files that can be concatenated
together and served as a single file to improve performance. | 62599072e1aae11d1e7cf47f |
class CompanySerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Company <NEW_LINE> fields = '__all__' <NEW_LINE> read_only_fields = ('id',) | Serializer for LinkedIn comapnies | 6259907238b623060ffaa4c6 |
class Colleague(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, mediator): <NEW_LINE> <INDENT> self.__mediator = mediator <NEW_LINE> <DEDENT> @property <NEW_LINE> def mediator(self): <NEW_LINE> <INDENT> return self.__mediator <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def send(self, message): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def notify(self, message): <NEW_LINE> <INDENT> pass | 抽象同事类 | 62599072283ffb24f3cf518d |
class ExperimentalData(Data): <NEW_LINE> <INDENT> def __init__(self, values, verrors, coords, cerrors, units): <NEW_LINE> <INDENT> super(ExperimentalData, self).__init__(coords=coords, values=values, verrors=verrors, cerrors=cerrors, units=units) <NEW_LINE> return | ExperimentalData is a form of Data which issues a Warning upon any use
if there are not valid values for any or all of the error or units. | 625990724428ac0f6e659e18 |
class EventHandler(FileSystemEventHandler): <NEW_LINE> <INDENT> def __init__(self, working_dir, config_factory): <NEW_LINE> <INDENT> self.working_dir = working_dir <NEW_LINE> self.config_factory = config_factory <NEW_LINE> self.config = self.initial_config_load() <NEW_LINE> self.io_handler = IOHandler(working_dir) <NEW_LINE> <DEDENT> def initial_config_load(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print(" * Loading config") <NEW_LINE> return self.config_factory.load_config() <NEW_LINE> <DEDENT> except ConfigError as e: <NEW_LINE> <INDENT> print(" * {}Error reloading config{}:\n{}".format( color(FG.red), color(), str(e), )) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> def on_any_event(self, event): <NEW_LINE> <INDENT> super(EventHandler, self).on_any_event(event) <NEW_LINE> if event.event_type == "moved": <NEW_LINE> <INDENT> events = [ FileEvent(event.src_path, event.event_type + "_from", event.is_directory), FileEvent(event.dest_path, event.event_type + "_to", event.is_directory), ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> events = [ FileEvent(event.src_path, event.event_type, event.is_directory), ] <NEW_LINE> <DEDENT> for event in events: <NEW_LINE> <INDENT> self.on_any_single_event(event) <NEW_LINE> <DEDENT> <DEDENT> def on_any_single_event(self, event): <NEW_LINE> <INDENT> matches = matching.does_match(self.config.task.fileset, event) <NEW_LINE> if event.basename != ".watchcode.log": <NEW_LINE> <INDENT> logger.info(u"Event: {:<60s} {:<12} {}".format( event.path_normalized, event.type, u"✓" if matches else u"○", )) <NEW_LINE> <DEDENT> if matches: <NEW_LINE> <INDENT> launch_info = LaunchInfo( old_config=self.config, trigger=event, config_factory=self.config_factory, on_task_finished=self.on_task_finished, ) <NEW_LINE> self.io_handler.trigger(launch_info) <NEW_LINE> <DEDENT> <DEDENT> def on_task_finished(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> <DEDENT> def on_manual_trigger(self, is_initial=False): <NEW_LINE> <INDENT> if is_initial: <NEW_LINE> <INDENT> trigger = InitialTrigger() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trigger = ManualTrigger() <NEW_LINE> <DEDENT> launch_info = LaunchInfo( old_config=self.config, trigger=trigger, config_factory=self.config_factory, on_task_finished=self.on_task_finished, ) <NEW_LINE> self.io_handler.trigger(launch_info) | Watchcode's main event handler | 625990723539df3088ecdb7a |
class ButtonGrp(QGroupBox): <NEW_LINE> <INDENT> def __init__(self, game: GameModel): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.game = game <NEW_LINE> def bet_button_func(): <NEW_LINE> <INDENT> if self.bet_line.text().isdigit(): <NEW_LINE> <INDENT> bet = int(self.bet_line.text()) <NEW_LINE> self.bet_line.clear() <NEW_LINE> self.game.bet_button(bet) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.bet_line.clear() <NEW_LINE> msg = QMessageBox() <NEW_LINE> msg.setText('There was no bet!') <NEW_LINE> msg.exec() <NEW_LINE> <DEDENT> <DEDENT> self.setLayout(QVBoxLayout()) <NEW_LINE> self.bet_line = QLineEdit() <NEW_LINE> self.bet_line.setPlaceholderText('Enter bet') <NEW_LINE> self.bet_line.resize(100, 5) <NEW_LINE> bet_button = QPushButton('Bet') <NEW_LINE> bet_button.clicked.connect(bet_button_func) <NEW_LINE> self.layout().addWidget(self.bet_line) <NEW_LINE> self.layout().addWidget(bet_button) <NEW_LINE> call_button = QPushButton('Call') <NEW_LINE> call_button.clicked.connect(self.game.call_button) <NEW_LINE> self.layout().addWidget(call_button) <NEW_LINE> fold_button = QPushButton('Fold') <NEW_LINE> fold_button.clicked.connect(self.game.fold_button) <NEW_LINE> self.layout().addWidget(fold_button) <NEW_LINE> check_button = QPushButton('Check') <NEW_LINE> check_button.clicked.connect(self.game.check_button) <NEW_LINE> self.layout().addWidget(check_button) <NEW_LINE> all_in_button = QPushButton('All in!') <NEW_LINE> all_in_button.clicked.connect(self.game.all_in_button) <NEW_LINE> self.layout().addWidget(all_in_button) | A widget that represents buttons in the game.
:param game: Game model. | 625990728e7ae83300eea975 |
class User(ResourceMixin, ModelBase): <NEW_LINE> <INDENT> __tablename__ = "user" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String, unique=True, nullable=False) <NEW_LINE> roles = Column(String, nullable=False, default="") <NEW_LINE> def get_roles(self): <NEW_LINE> <INDENT> return self.roles.split(",") <NEW_LINE> <DEDENT> def set_roles(self, roles): <NEW_LINE> <INDENT> self.roles = ",".join(roles) | User Model | 62599072adb09d7d5dc0be4f |
class Statement(Statements): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vartype = None <NEW_LINE> self.identifiers = None | <declaracao> := <tipo> : <identificadores> | 6259907244b2445a339b75d0 |
class Rar5Info(RarInfo): <NEW_LINE> <INDENT> extract_version = 50 <NEW_LINE> header_crc = None <NEW_LINE> header_size = None <NEW_LINE> header_offset = None <NEW_LINE> data_offset = None <NEW_LINE> block_type = None <NEW_LINE> block_flags = None <NEW_LINE> add_size = 0 <NEW_LINE> block_extra_size = 0 <NEW_LINE> volume_number = None <NEW_LINE> _md_class = None <NEW_LINE> _md_expect = None <NEW_LINE> def _must_disable_hack(self): <NEW_LINE> <INDENT> return False | Shared fields for RAR5 records. | 62599072a17c0f6771d5d81d |
class BoundCollectionBuilder(CollectionBuilder): <NEW_LINE> <INDENT> def __init__(self, dataset_collection): <NEW_LINE> <INDENT> self.dataset_collection = dataset_collection <NEW_LINE> if dataset_collection.populated: <NEW_LINE> <INDENT> raise Exception("Cannot reset elements of an already populated dataset collection.") <NEW_LINE> <DEDENT> collection_type = dataset_collection.collection_type <NEW_LINE> collection_type_description = COLLECTION_TYPE_DESCRIPTION_FACTORY.for_collection_type(collection_type) <NEW_LINE> super().__init__(collection_type_description) <NEW_LINE> <DEDENT> def populate_partial(self): <NEW_LINE> <INDENT> elements = self.build_elements() <NEW_LINE> type_plugin = self._collection_type_description.rank_type_plugin() <NEW_LINE> set_collection_elements(self.dataset_collection, type_plugin, elements, self.associated_identifiers) <NEW_LINE> <DEDENT> def populate(self): <NEW_LINE> <INDENT> self.populate_partial() <NEW_LINE> self.dataset_collection.mark_as_populated() | More stateful builder that is bound to a particular model object. | 6259907256b00c62f0fb41b4 |
class ResetPassword(APIView): <NEW_LINE> <INDENT> def get(self, request,reset_id, format=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = Usr.objects.get(reset_id=reset_id) <NEW_LINE> serializer = UsrSerializer(user) <NEW_LINE> key=serializer.data.get('reset_id') <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> return Response(serializer.data) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> return HttpResponse("null") <NEW_LINE> <DEDENT> return HttpResponse("WOrofsjdnj") <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = UsrSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | Reset password app | 625990724428ac0f6e659e19 |
class Solution1: <NEW_LINE> <INDENT> def numIslands(self, grid): <NEW_LINE> <INDENT> if not grid or not grid[0]: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> m = len(grid) <NEW_LINE> n = len(grid[0]) <NEW_LINE> numIslands = 0 <NEW_LINE> totalIslands = 0 <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> if grid[i][j] == 1: <NEW_LINE> <INDENT> totalIslands += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> uf = UnionFind(m * n) <NEW_LINE> uf.setCount(totalIslands) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> print("At: (%s, %s), value: %s" %(i, j, grid[i][j])) <NEW_LINE> if grid[i][j]: <NEW_LINE> <INDENT> if i > 0 and grid[i - 1][j]: <NEW_LINE> <INDENT> uf.union(i * n + j, (i - 1) * n + j) <NEW_LINE> <DEDENT> if i < m - 1 and grid[i + 1][j]: <NEW_LINE> <INDENT> uf.union(i * n + j, (i + 1) * n + j) <NEW_LINE> <DEDENT> if j > 0 and grid[i][j - 1]: <NEW_LINE> <INDENT> uf.union(i * n + j, i * n + (j - 1)) <NEW_LINE> <DEDENT> if j < n - 1 and grid[i][j + 1]: <NEW_LINE> <INDENT> uf.union(i * n + j, i * n + (j + 1)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return uf.getCount() | @param grid: a boolean 2D matrix
@return: an integer | 625990724527f215b58eb612 |
class Field(object): <NEW_LINE> <INDENT> def __init__(self, name, type='STRING', mode='NULLABLE'): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = type <NEW_LINE> self.mode = mode <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return { 'name': self.name, 'type': self.type, 'mode': self.mode, } | A field of a CSV or BigQuery table representation of a CCDA. | 62599072a219f33f346c80ef |
class MeasureSum(object): <NEW_LINE> <INDENT> __slots__ = ("_measures",) <NEW_LINE> def __init__(self, *measures): <NEW_LINE> <INDENT> self._measures = measures <NEW_LINE> <DEDENT> def __rmul__(self, other): <NEW_LINE> <INDENT> integrals = [other * m for m in self._measures] <NEW_LINE> return sum(integrals) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Measure): <NEW_LINE> <INDENT> return MeasureSum(*(self._measures + (other,))) <NEW_LINE> <DEDENT> elif isinstance(other, MeasureSum): <NEW_LINE> <INDENT> return MeasureSum(*(self._measures + other._measures)) <NEW_LINE> <DEDENT> return NotImplemented <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{\n " + "\n + ".join(map(str, self._measures)) + "\n}" | Represents a sum of measures.
This is a notational intermediate object to translate the notation
f*(ds(1)+ds(3))
into
f*ds(1) + f*ds(3) | 62599072bf627c535bcb2db1 |
class Trigger(object): <NEW_LINE> <INDENT> def __init__(self, connection=None, name=None, autoscale_group=None, dimensions=None, measure_name=None, statistic=None, unit=None, period=60, lower_threshold=None, lower_breach_scale_increment=None, upper_threshold=None, upper_breach_scale_increment=None, breach_duration=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.connection = connection <NEW_LINE> self.dimensions = dimensions <NEW_LINE> self.breach_duration = breach_duration <NEW_LINE> self.upper_breach_scale_increment = upper_breach_scale_increment <NEW_LINE> self.created_time = None <NEW_LINE> self.upper_threshold = upper_threshold <NEW_LINE> self.status = None <NEW_LINE> self.lower_threshold = lower_threshold <NEW_LINE> self.period = period <NEW_LINE> self.lower_breach_scale_increment = lower_breach_scale_increment <NEW_LINE> self.statistic = statistic <NEW_LINE> self.unit = unit <NEW_LINE> self.namespace = None <NEW_LINE> if autoscale_group: <NEW_LINE> <INDENT> self.autoscale_group = weakref.proxy(autoscale_group) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.autoscale_group = None <NEW_LINE> <DEDENT> self.measure_name = measure_name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Trigger:%s' % (self.name) <NEW_LINE> <DEDENT> def startElement(self, name, attrs, connection): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def endElement(self, name, value, connection): <NEW_LINE> <INDENT> if name == 'BreachDuration': <NEW_LINE> <INDENT> self.breach_duration = value <NEW_LINE> <DEDENT> elif name == 'TriggerName': <NEW_LINE> <INDENT> self.name = value <NEW_LINE> <DEDENT> elif name == 'Period': <NEW_LINE> <INDENT> self.period = value <NEW_LINE> <DEDENT> elif name == 'CreatedTime': <NEW_LINE> <INDENT> self.created_time = value <NEW_LINE> <DEDENT> elif name == 'Statistic': <NEW_LINE> <INDENT> self.statistic = value <NEW_LINE> <DEDENT> elif name == 'Unit': <NEW_LINE> <INDENT> self.unit = value <NEW_LINE> <DEDENT> elif name == 'Namespace': <NEW_LINE> <INDENT> self.namespace = value <NEW_LINE> <DEDENT> elif name == 'AutoScalingGroupName': <NEW_LINE> <INDENT> self.autoscale_group_name = value <NEW_LINE> <DEDENT> elif name == 'MeasureName': <NEW_LINE> <INDENT> self.measure_name = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, name, value) <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.connection.create_trigger(self) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> params = { 'TriggerName' : self.name, 'AutoScalingGroupName' : self.autoscale_group_name, } <NEW_LINE> req =self.connection.get_object('DeleteTrigger', params, Request) <NEW_LINE> self.connection.last_request = req <NEW_LINE> return req | An auto scaling trigger.
@type name: str
@param name: The name for this trigger
@type autoscale_group: str
@param autoscale_group: The name of the AutoScalingGroup that will be
associated with the trigger. The AutoScalingGroup
that will be affected by the trigger when it is
activated.
@type dimensions: list
@param dimensions: List of tuples, i.e.
('ImageId', 'i-13lasde') etc.
@type measure_name: str
@param measure_name: The measure name associated with the metric used by
the trigger to determine when to activate, for
example, CPU, network I/O, or disk I/O.
@type statistic: str
@param statistic: The particular statistic used by the trigger when
fetching metric statistics to examine.
@type period: int
@param period: The period associated with the metric statistics in
seconds. Valid Values: 60 or a multiple of 60.
@type unit:
@param unit
@type lower_threshold:
@param lower_threshold | 6259907201c39578d7f143a7 |
class GameEnviroment(metaclass=ABCMeta): <NEW_LINE> <INDENT> done = False <NEW_LINE> params = None <NEW_LINE> _bestAction = None <NEW_LINE> _bestReward = None <NEW_LINE> _bestAvgReward = 0 <NEW_LINE> def __init__(self, n_bandits): <NEW_LINE> <INDENT> self.params = EnvParams(n_bandits) <NEW_LINE> <DEDENT> def _beforeGetReward(self,action): <NEW_LINE> <INDENT> if action>=self.params["N_bandits"]: <NEW_LINE> <INDENT> raise ValueError("Got action= %d but action must be < N_bandits=%d" % (action, self.params["N_bandits"])) <NEW_LINE> <DEDENT> <DEDENT> def _getReward(self,action): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def _afterGetReward(self,rewards,action): <NEW_LINE> <INDENT> self._bestAction = np.argmax(rewards) <NEW_LINE> self._bestReward = np.max(rewards) <NEW_LINE> pass <NEW_LINE> <DEDENT> def getReward(self,action): <NEW_LINE> <INDENT> self._beforeGetReward(action) <NEW_LINE> rewards = [self._getReward(a) for a in self.params["ActionRange"]] <NEW_LINE> self._afterGetReward(rewards,action) <NEW_LINE> return rewards[action] <NEW_LINE> <DEDENT> def getRewardSample(self,sample_size=100): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for action in self.params["ActionRange"]: <NEW_LINE> <INDENT> subresult = [] <NEW_LINE> for i in range(sample_size): <NEW_LINE> <INDENT> subresult.append(self._getReward(action)) <NEW_LINE> <DEDENT> result.append(subresult) <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def getBestReward(self): <NEW_LINE> <INDENT> return self._bestReward <NEW_LINE> <DEDENT> def getBestAction(self): <NEW_LINE> <INDENT> return self._bestAction <NEW_LINE> <DEDENT> def getBestAvgReward(self): <NEW_LINE> <INDENT> return self._bestAvgReward <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.done = False <NEW_LINE> self._bestAction = None <NEW_LINE> self._bestReward = None <NEW_LINE> pass | Base class for game enviroment
Attributes:
done - flag for end game
params - public enviroment params | 625990727d43ff2487428085 |
class ScanTaskSerializer(NotEmptySerializer): <NEW_LINE> <INDENT> sequence_number = IntegerField(required=False, min_value=0, read_only=True) <NEW_LINE> source = SourceField(queryset=Source.objects.all()) <NEW_LINE> scan_type = ChoiceField( required=False, choices=ScanTask.SCANTASK_TYPE_CHOICES) <NEW_LINE> status = ChoiceField(required=False, read_only=True, choices=ScanTask.STATUS_CHOICES) <NEW_LINE> status_message = CharField(required=False) <NEW_LINE> systems_count = IntegerField(required=False, min_value=0, read_only=True) <NEW_LINE> systems_scanned = IntegerField(required=False, min_value=0, read_only=True) <NEW_LINE> systems_failed = IntegerField(required=False, min_value=0, read_only=True) <NEW_LINE> systems_unreachable = IntegerField( required=False, min_value=0, read_only=True) <NEW_LINE> start_time = DateTimeField(required=False, read_only=True) <NEW_LINE> end_time = DateTimeField(required=False, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = ScanTask <NEW_LINE> fields = ['sequence_number', 'source', 'scan_type', 'status', 'status_message', 'systems_count', 'systems_scanned', 'systems_failed', 'systems_unreachable', 'start_time', 'end_time'] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def validate_source(source): <NEW_LINE> <INDENT> if not source: <NEW_LINE> <INDENT> raise ValidationError(_(messages.ST_REQ_SOURCE)) <NEW_LINE> <DEDENT> return source | Serializer for the ScanTask model. | 62599072f548e778e596ce73 |
class Signer: <NEW_LINE> <INDENT> def __init__(self, signer_key: SignerKey, weight) -> "None": <NEW_LINE> <INDENT> self.signer_key: SignerKey = signer_key <NEW_LINE> self.weight: int = weight <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def ed25519_public_key(cls, account_id: str, weight: int) -> "Signer": <NEW_LINE> <INDENT> signer_key = SignerKey.ed25519_public_key(account_id) <NEW_LINE> return cls(signer_key, weight) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def pre_auth_tx(cls, pre_auth_tx_hash: bytes, weight: int) -> "Signer": <NEW_LINE> <INDENT> signer_key = SignerKey.pre_auth_tx(pre_auth_tx_hash) <NEW_LINE> return cls(signer_key, weight) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def sha256_hash(cls, sha256_hash: bytes, weight: int) -> "Signer": <NEW_LINE> <INDENT> signer_key = SignerKey.sha256_hash(sha256_hash) <NEW_LINE> return cls(signer_key, weight) <NEW_LINE> <DEDENT> def to_xdr_object(self) -> stellar_xdr.Signer: <NEW_LINE> <INDENT> return stellar_xdr.Signer( self.signer_key.to_xdr_object(), stellar_xdr.Uint32(self.weight) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xdr_object(cls, xdr_object: stellar_xdr.Signer) -> "Signer": <NEW_LINE> <INDENT> weight = xdr_object.weight.uint32 <NEW_LINE> signer_key = SignerKey.from_xdr_object(xdr_object.key) <NEW_LINE> return cls(signer_key, weight) <NEW_LINE> <DEDENT> def __eq__(self, other: object) -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return self.signer_key == other.signer_key and self.weight == other.weight <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"<Signer [signer_key={self.signer_key}, weight={self.weight}]>" | The :class:`Signer` object, which represents an account signer on Stellar's network.
:param signer_key: The signer object
:param weight: The weight of the key | 6259907216aa5153ce401dbe |
class HelpdeskEditForm(base.EditForm): <NEW_LINE> <INDENT> form_fields = (form.Fields(IHelpdesk).select('title','description','persistent') + form.Fields(IHelpdesk, for_display=True).select('botJid','botPassword')) <NEW_LINE> label = _(u"Edit jabber Helpdesk") <NEW_LINE> form_name = _(u"Helpdesk settings") | Edit form for projects
| 62599072aad79263cf43009b |
class WinType(Enum): <NEW_LINE> <INDENT> pass | A way in which a match is won (e.g. pin, disqualification). | 6259907267a9b606de547716 |
class cableInsulationDetails(EmbeddedDocument): <NEW_LINE> <INDENT> name = StringField(required=True, choices=cableVar.list_insulationType) <NEW_LINE> conductorTemperature = IntField(required=True) <NEW_LINE> maxTemperature = IntField(required=True) <NEW_LINE> code = StringField(required=True, choices=cableVar.list_insulationCode, default=cableVar.default_insulationCode) | :param name:
:param conductorTemperature:
:param maxTemperature: # maximum conductor temperature. Assumes degrees C | 625990724a966d76dd5f07d0 |
class WorkersConfig: <NEW_LINE> <INDENT> _rq_workers_str = ['RQ', 'rq'] <NEW_LINE> def __init__(self, use_for_all: bool = False, worker_type: Optional[str] = None, worker_pool_kwargs: Optional[Dict[str, Any]] = None): <NEW_LINE> <INDENT> self.use_for_all = use_for_all <NEW_LINE> self._check_worker_type(worker_type) <NEW_LINE> self.worker_type = worker_type <NEW_LINE> self.worker_pool_kwargs = worker_pool_kwargs or {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _check_worker_type(cls, worker_type: str): <NEW_LINE> <INDENT> if worker_type not in {*cls._rq_workers_str}: <NEW_LINE> <INDENT> raise ValueError('worker type {} not understood'.format(worker_type)) <NEW_LINE> <DEDENT> <DEDENT> def get_worker_pool(self) -> BaseWorkerPool: <NEW_LINE> <INDENT> if self.worker_type in self._rq_workers_str: <NEW_LINE> <INDENT> return RQWorkerPool(**self.worker_pool_kwargs) <NEW_LINE> <DEDENT> raise ValueError('worker type {} not understood'.format(self.worker_type)) | the configuration of Chariots Workerpolls | 6259907297e22403b383c7e8 |
class Class: <NEW_LINE> <INDENT> def __init__(self, code): <NEW_LINE> <INDENT> self.code = code | docstring for Class | 625990727047854f46340c9c |
class colorconvertEvents(sublime_plugin.EventListener): <NEW_LINE> <INDENT> def on_selection_modified(self, view): <NEW_LINE> <INDENT> sels = view.sel() <NEW_LINE> global _hr <NEW_LINE> global _hg <NEW_LINE> global _hb <NEW_LINE> global _r <NEW_LINE> global _g <NEW_LINE> global _b <NEW_LINE> global _h <NEW_LINE> global _s <NEW_LINE> global _l <NEW_LINE> global _alpha <NEW_LINE> if len(sels) is 1 and sels[0].empty(): <NEW_LINE> <INDENT> _hr = None <NEW_LINE> _hg = None <NEW_LINE> _hb = None <NEW_LINE> _r = None <NEW_LINE> _g = None <NEW_LINE> _b = None <NEW_LINE> _h = None <NEW_LINE> _s = None <NEW_LINE> _l = None <NEW_LINE> alpha = 1.0 | Event listener for the ColorConvert plugin.
Attributes:
sublime_plugin.EventListener: Sublime Text class basis. | 62599072097d151d1a2c2958 |
class FakeFile: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.file = '' <NEW_LINE> <DEDENT> def write(self, text): <NEW_LINE> <INDENT> self.file += text <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> return self.file | Use to capture the output | 62599072be8e80087fbc0976 |
class OAuthSettingsHelper: <NEW_LINE> <INDENT> _remote_app = None <NEW_LINE> _remote_rest_app = None <NEW_LINE> def __init__( self, title, description, base_url, app_key, icon=None, access_token_url=None, authorize_url=None, access_token_method="POST", request_token_params=None, request_token_url=None, precedence_mask=None, **kwargs, ): <NEW_LINE> <INDENT> self.base_url = "{}/".format(base_url.rstrip("/")) <NEW_LINE> icon = icon or "" <NEW_LINE> request_token_params = request_token_params or {"scope": ""} <NEW_LINE> access_token_url = access_token_url or f"{self.base_url}oauth2/token" <NEW_LINE> authorize_url = authorize_url or f"{self.base_url}oauth2/authorize" <NEW_LINE> precedence_mask = precedence_mask or { "email": True, "password": False, "profile": { "username": False, "full_name": False, }, } <NEW_LINE> self.base_app = dict( title=title, description=description, icon=icon, precedence_mask=precedence_mask, params=dict( base_url=self.base_url, request_token_params=request_token_params, request_token_url=request_token_url, access_token_url=access_token_url, access_token_method=access_token_method, authorize_url=authorize_url, app_key=app_key, **kwargs, ), ) <NEW_LINE> <DEDENT> def get_handlers(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def remote_app(self): <NEW_LINE> <INDENT> self._remote_app = dict(self.base_app) <NEW_LINE> self._remote_app.update(self.get_handlers()) <NEW_LINE> return self._remote_app <NEW_LINE> <DEDENT> def get_rest_handlers(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def remote_rest_app(self): <NEW_LINE> <INDENT> self._remote_rest_app = dict(self.base_app) <NEW_LINE> self._remote_rest_app.update(self.get_rest_handlers()) <NEW_LINE> return self._remote_rest_app | Helper for creating REMOTE_APP configuration dictionaries for OAuth. | 6259907221bff66bcd72454e |
class LinuxIntelCompiler(Compiler): <NEW_LINE> <INDENT> def __init__(self, cppargs=[], ldargs=[], cpp=False, comm=None): <NEW_LINE> <INDENT> opt_flags = ['-Ofast', '-xHost'] <NEW_LINE> if configuration['debug']: <NEW_LINE> <INDENT> opt_flags = ['-O0', '-g'] <NEW_LINE> <DEDENT> cc = "mpicc" <NEW_LINE> stdargs = ["-std=gnu11"] <NEW_LINE> if cpp: <NEW_LINE> <INDENT> cc = "mpicxx" <NEW_LINE> stdargs = [] <NEW_LINE> <DEDENT> cppargs = stdargs + ['-fPIC', '-no-multibyte-chars'] + opt_flags + cppargs <NEW_LINE> ldargs = ['-shared'] + ldargs <NEW_LINE> super(LinuxIntelCompiler, self).__init__(cc, cppargs=cppargs, ldargs=ldargs, cpp=cpp, comm=comm) | The intel compiler for building a shared library on linux systems.
:arg cppargs: A list of arguments to pass to the C compiler
(optional).
:arg ldargs: A list of arguments to pass to the linker (optional).
:arg cpp: Are we actually using the C++ compiler?
:kwarg comm: Optional communicator to compile the code on (only
rank 0 compiles code) (defaults to COMM_WORLD). | 62599072ac7a0e7691f73dd0 |
class ArticleDetailSerialazer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Article <NEW_LINE> fields = '__all__' | 1 статья | 62599072b7558d5895464ba6 |
class canvas_descr: <NEW_LINE> <INDENT> def __init__(self, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True): <NEW_LINE> <INDENT> self.x_title = x_title; <NEW_LINE> self.y_title = y_title; <NEW_LINE> self.x_lim = x_lim; <NEW_LINE> self.y_lim = y_lim; <NEW_LINE> self.x_labels = x_labels; <NEW_LINE> self.y_labels = y_labels; | !
@brief Describes plot where dynamic is displayed.
@details Used by 'dynamic_visualizer' class. | 625990724e4d562566373ced |
class DecimalField(CoreDecimalField): <NEW_LINE> <INDENT> def populate_obj(self, obj, name): <NEW_LINE> <INDENT> setattr(obj, name, float(self.data)) <NEW_LINE> <DEDENT> def process_formdata(self, valuelist): <NEW_LINE> <INDENT> if valuelist and valuelist[0]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.use_locale: <NEW_LINE> <INDENT> self.data = self._parse_decimal(valuelist[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = decimal.Decimal(valuelist[0]) <NEW_LINE> <DEDENT> <DEDENT> except (decimal.InvalidOperation, ValueError): <NEW_LINE> <INDENT> self.data = None <NEW_LINE> raise ValueError(self.gettext('Not a valid decimal value')) | Customized decimal field. | 6259907256b00c62f0fb41b6 |
class ResponseInstructions(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ResponseInstructions): <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. | 62599072bf627c535bcb2db3 |
class BDQN_TS(BDQN): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(mode="ts", **kwargs) <NEW_LINE> self.reset_ts = None <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> super().build() <NEW_LINE> agent_w = [blr.w for blr in self.agent_blr] <NEW_LINE> target_w = [blr.resample_w() for blr in self.target_blr] <NEW_LINE> self.reset_ts = tf_utils.assign_vars(agent_w, target_w, name="reset_ts") <NEW_LINE> <DEDENT> def reset(self, sess): <NEW_LINE> <INDENT> sess.run(self.reset_ts) | Bayesian Double DQN with Thompson Sampling exploration policy | 62599072f548e778e596ce74 |
class ContextFilter(logging.Filter): <NEW_LINE> <INDENT> def filter(self, record): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if hasattr(cherrypy, 'serving'): <NEW_LINE> <INDENT> request = cherrypy.serving.request <NEW_LINE> remote = request.remote <NEW_LINE> record.ip = remote.name or remote.ip <NEW_LINE> if 'X-Forwarded-For' in request.headers: <NEW_LINE> <INDENT> record.ip = request.headers['X-Forwarded-For'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> record.ip = "none" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> record.user = cherrypy.session['user'].username <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> record.user = "none" <NEW_LINE> <DEDENT> return True | This is a filter which injects contextual information into the log. | 625990727d43ff2487428086 |
class Node: <NEW_LINE> <INDENT> __slots__ = "data", "prev", "next" <NEW_LINE> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.next = None <NEW_LINE> self.prev = None | Implements the nodes in a doubly linked list | 625990724e4d562566373cee |
class spikegeneratorModel(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = '' <NEW_LINE> self.codeobject_name = '' <NEW_LINE> self.N = 0 | Class that contains all relevant information of a spike generator group. | 62599072baa26c4b54d50b93 |
class TestApiFunc: <NEW_LINE> <INDENT> @patch('pyvesync_v2.helpers.requests.get', autospec=True) <NEW_LINE> def test_api_get(self, get_mock): <NEW_LINE> <INDENT> get_mock.return_value = Mock(ok=True, status_code=200) <NEW_LINE> get_mock.return_value.json.return_value = {'code': 0} <NEW_LINE> mock_return = Helpers.call_api('/call/location', method='get') <NEW_LINE> assert mock_return == ({'code': 0}, 200) <NEW_LINE> <DEDENT> @patch('pyvesync_v2.helpers.requests.post', autospec=True) <NEW_LINE> def test_api_post(self, post_mock): <NEW_LINE> <INDENT> post_mock.return_value = Mock(ok=True, status_code=200) <NEW_LINE> post_mock.return_value.json.return_value = {'code': 0} <NEW_LINE> mock_return = Helpers.call_api('/call/location', method='post') <NEW_LINE> assert mock_return == ({'code': 0}, 200) <NEW_LINE> <DEDENT> @patch('pyvesync_v2.helpers.requests.put', autospec=True) <NEW_LINE> def test_api_put(self, put_mock): <NEW_LINE> <INDENT> put_mock.return_value = Mock(ok=True, status_code=200) <NEW_LINE> put_mock.return_value.json.return_value = {'code': 0} <NEW_LINE> mock_return = Helpers.call_api('/call/location', method='put') <NEW_LINE> assert mock_return == ({'code': 0}, 200) <NEW_LINE> <DEDENT> @patch('pyvesync_v2.helpers.requests.get', autospec=True) <NEW_LINE> def test_api_bad_response(self, api_mock): <NEW_LINE> <INDENT> api_mock.return_value = Mock(ok=True, status_code=500) <NEW_LINE> api_mock.return_value.json.return_value = {} <NEW_LINE> mock_return = Helpers.call_api('/call/location', method='get') <NEW_LINE> assert mock_return == (None, None) <NEW_LINE> <DEDENT> @patch('pyvesync_v2.helpers.requests.get', autospec=True) <NEW_LINE> def test_api_exception(self, api_mock, caplog): <NEW_LINE> <INDENT> caplog.set_level(logging.DEBUG) <NEW_LINE> api_mock.return_value.raiseError.side_effect = Mock( side_effect=Exception) <NEW_LINE> Helpers.call_api('/call/location', method='get') <NEW_LINE> assert len(caplog.records) == 2 | Test call_api() method. | 6259907266673b3332c31ce6 |
class ImportCompilationTest(_common.TestCase, ImportHelper): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.setup_beets() <NEW_LINE> self._create_import_dir(3) <NEW_LINE> self._setup_import_session() <NEW_LINE> self.matcher = AutotagStub().install() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.teardown_beets() <NEW_LINE> self.matcher.restore() <NEW_LINE> <DEDENT> def test_asis_homogenous_sets_albumartist(self): <NEW_LINE> <INDENT> self.importer.add_choice(importer.action.ASIS) <NEW_LINE> self.importer.run() <NEW_LINE> self.assertEqual(self.lib.albums().get().albumartist, u'Tag Artist') <NEW_LINE> for item in self.lib.items(): <NEW_LINE> <INDENT> self.assertEqual(item.albumartist, u'Tag Artist') <NEW_LINE> <DEDENT> <DEDENT> def test_asis_heterogenous_sets_various_albumartist(self): <NEW_LINE> <INDENT> self.import_media[0].artist = u'Other Artist' <NEW_LINE> self.import_media[0].save() <NEW_LINE> self.import_media[1].artist = u'Another Artist' <NEW_LINE> self.import_media[1].save() <NEW_LINE> self.importer.add_choice(importer.action.ASIS) <NEW_LINE> self.importer.run() <NEW_LINE> self.assertEqual(self.lib.albums().get().albumartist, u'Various Artists') <NEW_LINE> for item in self.lib.items(): <NEW_LINE> <INDENT> self.assertEqual(item.albumartist, u'Various Artists') <NEW_LINE> <DEDENT> <DEDENT> def test_asis_heterogenous_sets_sompilation(self): <NEW_LINE> <INDENT> self.import_media[0].artist = u'Other Artist' <NEW_LINE> self.import_media[0].save() <NEW_LINE> self.import_media[1].artist = u'Another Artist' <NEW_LINE> self.import_media[1].save() <NEW_LINE> self.importer.add_choice(importer.action.ASIS) <NEW_LINE> self.importer.run() <NEW_LINE> for item in self.lib.items(): <NEW_LINE> <INDENT> self.assertTrue(item.comp) <NEW_LINE> <DEDENT> <DEDENT> def test_asis_sets_majority_albumartist(self): <NEW_LINE> <INDENT> self.import_media[0].artist = u'Other Artist' <NEW_LINE> self.import_media[0].save() <NEW_LINE> self.import_media[1].artist = u'Other Artist' <NEW_LINE> self.import_media[1].save() <NEW_LINE> self.importer.add_choice(importer.action.ASIS) <NEW_LINE> self.importer.run() <NEW_LINE> self.assertEqual(self.lib.albums().get().albumartist, u'Other Artist') <NEW_LINE> for item in self.lib.items(): <NEW_LINE> <INDENT> self.assertEqual(item.albumartist, u'Other Artist') <NEW_LINE> <DEDENT> <DEDENT> def test_asis_albumartist_tag_sets_albumartist(self): <NEW_LINE> <INDENT> self.import_media[0].artist = u'Other Artist' <NEW_LINE> self.import_media[1].artist = u'Another Artist' <NEW_LINE> for mediafile in self.import_media: <NEW_LINE> <INDENT> mediafile.albumartist = u'Album Artist' <NEW_LINE> mediafile.mb_albumartistid = u'Album Artist ID' <NEW_LINE> mediafile.save() <NEW_LINE> <DEDENT> self.importer.add_choice(importer.action.ASIS) <NEW_LINE> self.importer.run() <NEW_LINE> self.assertEqual(self.lib.albums().get().albumartist, u'Album Artist') <NEW_LINE> self.assertEqual(self.lib.albums().get().mb_albumartistid, u'Album Artist ID') <NEW_LINE> for item in self.lib.items(): <NEW_LINE> <INDENT> self.assertEqual(item.albumartist, u'Album Artist') <NEW_LINE> self.assertEqual(item.mb_albumartistid, u'Album Artist ID') | Test ASIS import of a folder containing tracks with different artists.
| 62599072dd821e528d6da5f5 |
class HaarLikeFeatureExtractor(FeatureExtractorBase): <NEW_LINE> <INDENT> mFeatureSet = None <NEW_LINE> mDo45 = True <NEW_LINE> def __init__(self, fname=None, do45=True): <NEW_LINE> <INDENT> self.mDo45 = True <NEW_LINE> self.mFeatureset=None; <NEW_LINE> if(fname is not None): <NEW_LINE> <INDENT> self.readWavelets(fname) <NEW_LINE> <DEDENT> <DEDENT> def readWavelets(self, fname,nfeats=-1): <NEW_LINE> <INDENT> self.mFeatureSet = [] <NEW_LINE> f = open(fname,'r') <NEW_LINE> temp = f.read() <NEW_LINE> f.close() <NEW_LINE> data = temp.split() <NEW_LINE> count = int(data.pop(0)) <NEW_LINE> self.mFeatureset = [] <NEW_LINE> if(nfeats > -1): <NEW_LINE> <INDENT> count = min(count,nfeats) <NEW_LINE> <DEDENT> while len(data) > 0: <NEW_LINE> <INDENT> name = data.pop(0) <NEW_LINE> nRegions = int(data.pop(0)) <NEW_LINE> region = [] <NEW_LINE> for i in range(nRegions): <NEW_LINE> <INDENT> region.append(tuple(map(float,data[0:5]))) <NEW_LINE> data = data[5:] <NEW_LINE> <DEDENT> feat = HaarLikeFeature(name,region) <NEW_LINE> self.mFeatureSet.append(feat) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def saveWavelets(self, fname): <NEW_LINE> <INDENT> f = open(fname,'w') <NEW_LINE> f.write(str(len(self.mFeatureSet))+'\n\n') <NEW_LINE> for i in range(len(self.mFeatureSet)): <NEW_LINE> <INDENT> self.mFeatureSet[i].writeToFile(f) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> return None <NEW_LINE> <DEDENT> def extract(self, img): <NEW_LINE> <INDENT> regular = img.integralImage() <NEW_LINE> retVal = [] <NEW_LINE> for i in range(len(self.mFeatureSet)): <NEW_LINE> <INDENT> retVal.append(self.mFeatureSet[i].apply(regular)) <NEW_LINE> <DEDENT> if(self.mDo45): <NEW_LINE> <INDENT> slant = img.integralImage(tilted=True) <NEW_LINE> for i in range(len(self.mFeatureSet)): <NEW_LINE> <INDENT> retVal.append(self.mFeatureSet[i].apply(regular)) <NEW_LINE> <DEDENT> <DEDENT> return retVal <NEW_LINE> <DEDENT> def getFieldNames(self): <NEW_LINE> <INDENT> retVal = [] <NEW_LINE> for i in range( len(self.mFeatureSet)): <NEW_LINE> <INDENT> retVal.append(self.mFeatureSet[i].mName) <NEW_LINE> <DEDENT> if( self.mDo45 ): <NEW_LINE> <INDENT> for i in range( len(self.mFeatureSet)): <NEW_LINE> <INDENT> name = "Angle_"+self.mFeatureSet[i].mName <NEW_LINE> retVal.append(name) <NEW_LINE> <DEDENT> <DEDENT> return retVal <NEW_LINE> <DEDENT> def getNumFields(self): <NEW_LINE> <INDENT> mult = 1 <NEW_LINE> if(self.mDo45): <NEW_LINE> <INDENT> mult = 2 <NEW_LINE> <DEDENT> return mult*len(self.mFeatureset) | This is used generate Haar like features from an image. These
Haar like features are used by a the classifiers of machine learning
to help identify objects or things in the picture by their features,
or in this case haar features.
For a more in-depth review of Haar Like features see:
http://en.wikipedia.org/wiki/Haar-like_features | 625990727047854f46340c9e |
class SentenceIndexTeacher(IndexTeacher): <NEW_LINE> <INDENT> def __init__(self, opt, shared=None): <NEW_LINE> <INDENT> super().__init__(opt, shared) <NEW_LINE> try: <NEW_LINE> <INDENT> import nltk <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ImportError('Please install nltk (e.g. pip install nltk).') <NEW_LINE> <DEDENT> st_path = 'tokenizers/punkt/{0}.pickle'.format('english') <NEW_LINE> try: <NEW_LINE> <INDENT> self.sent_tok = nltk.data.load(st_path) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> nltk.download('punkt') <NEW_LINE> self.sent_tok = nltk.data.load(st_path) <NEW_LINE> <DEDENT> <DEDENT> def get(self, episode_idx, entry_idx=None): <NEW_LINE> <INDENT> article_idx, paragraph_idx, qa_idx = self.examples[episode_idx] <NEW_LINE> article = self.squad[article_idx] <NEW_LINE> paragraph = article['paragraphs'][paragraph_idx] <NEW_LINE> qa = paragraph['qas'][qa_idx] <NEW_LINE> context = paragraph['context'] <NEW_LINE> question = qa['question'] <NEW_LINE> answers = [] <NEW_LINE> if not qa['is_impossible']: <NEW_LINE> <INDENT> answers = [a['text'] for a in qa['answers']] <NEW_LINE> <DEDENT> edited_answers = [] <NEW_LINE> for answer in answers: <NEW_LINE> <INDENT> new_answer = answer.replace( '.', '').replace('?', '').replace('!', '') <NEW_LINE> context = context.replace(answer, new_answer) <NEW_LINE> edited_answers.append(new_answer) <NEW_LINE> <DEDENT> edited_sentences = self.sent_tok.tokenize(context) <NEW_LINE> sentences = [] <NEW_LINE> for sentence in edited_sentences: <NEW_LINE> <INDENT> for i in range(len(edited_answers)): <NEW_LINE> <INDENT> sentence = sentence.replace(edited_answers[i], answers[i]) <NEW_LINE> sentences.append(sentence) <NEW_LINE> <DEDENT> <DEDENT> for i in range(len(edited_answers)): <NEW_LINE> <INDENT> context = context.replace(edited_answers[i], answers[i]) <NEW_LINE> <DEDENT> labels = [] <NEW_LINE> label_starts = [] <NEW_LINE> for sentence in sentences: <NEW_LINE> <INDENT> for answer in answers: <NEW_LINE> <INDENT> if answer in sentence and sentence not in labels: <NEW_LINE> <INDENT> labels.append(sentence) <NEW_LINE> label_starts.append(context.index(sentence)) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(labels) == 0: <NEW_LINE> <INDENT> labels.append('') <NEW_LINE> <DEDENT> plausible = [] <NEW_LINE> if qa['is_impossible']: <NEW_LINE> <INDENT> plausible = qa['plausible_answers'] <NEW_LINE> <DEDENT> action = { 'id': 'squad', 'text': context + '\n' + question, 'labels': labels, 'plausible_answers': plausible, 'episode_done': True, 'answer_starts': label_starts } <NEW_LINE> return action | Index teacher where the labels are the sentences the contain the true
answer. | 62599072097d151d1a2c295a |
class StockInvestorRequest(StockInvestorTaskBase): <NEW_LINE> <INDENT> def __init__(self, api_key, stock, start_date, end_date): <NEW_LINE> <INDENT> super(StockInvestorRequest, self).__init__(api_key, stock, start_date, end_date) | StockInvestorRequest
Base handler of content for processed Task requests. | 62599072627d3e7fe0e0876f |
class PyPIJSONLocator(Locator): <NEW_LINE> <INDENT> def __init__(self, url, **kwargs): <NEW_LINE> <INDENT> super(PyPIJSONLocator, self).__init__(**kwargs) <NEW_LINE> self.base_url = ensure_slash(url) <NEW_LINE> <DEDENT> def get_distribution_names(self): <NEW_LINE> <INDENT> raise NotImplementedError('Not available from this locator') <NEW_LINE> <DEDENT> def _get_project(self, name): <NEW_LINE> <INDENT> result = {'urls': {}, 'digests': {}} <NEW_LINE> url = urljoin(self.base_url, '%s/json' % quote(name)) <NEW_LINE> try: <NEW_LINE> <INDENT> resp = self.opener.open(url) <NEW_LINE> data = resp.read().decode() <NEW_LINE> d = json.loads(data) <NEW_LINE> md = Metadata(scheme=self.scheme) <NEW_LINE> data = d['info'] <NEW_LINE> md.name = data['name'] <NEW_LINE> md.version = data['version'] <NEW_LINE> md.license = data.get('license') <NEW_LINE> md.keywords = data.get('keywords', []) <NEW_LINE> md.summary = data.get('summary') <NEW_LINE> dist = Distribution(md) <NEW_LINE> dist.locator = self <NEW_LINE> urls = d['urls'] <NEW_LINE> result[md.version] = dist <NEW_LINE> for info in d['urls']: <NEW_LINE> <INDENT> url = info['url'] <NEW_LINE> dist.download_urls.add(url) <NEW_LINE> dist.digests[url] = self._get_digest(info) <NEW_LINE> result['urls'].setdefault(md.version, set()).add(url) <NEW_LINE> result['digests'][url] = self._get_digest(info) <NEW_LINE> <DEDENT> for version, infos in list(d['releases'].items()): <NEW_LINE> <INDENT> if version == md.version: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> omd = Metadata(scheme=self.scheme) <NEW_LINE> omd.name = md.name <NEW_LINE> omd.version = version <NEW_LINE> odist = Distribution(omd) <NEW_LINE> odist.locator = self <NEW_LINE> result[version] = odist <NEW_LINE> for info in infos: <NEW_LINE> <INDENT> url = info['url'] <NEW_LINE> odist.download_urls.add(url) <NEW_LINE> odist.digests[url] = self._get_digest(info) <NEW_LINE> result['urls'].setdefault(version, set()).add(url) <NEW_LINE> result['digests'][url] = self._get_digest(info) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.errors.put(text_type(e)) <NEW_LINE> logger.exception('JSON fetch failed: %s', e) <NEW_LINE> <DEDENT> return result | This locator uses PyPI's JSON interface. It's very limited in functionality
and probably not worth using. | 62599072e1aae11d1e7cf481 |
class ESMTPDowngradeTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.clientProtocol = smtp.ESMTPClient( b"testpassword", None, b"testuser") <NEW_LINE> <DEDENT> def test_requireHELOFallbackOperates(self): <NEW_LINE> <INDENT> transport = StringTransport() <NEW_LINE> self.clientProtocol.requireAuthentication = False <NEW_LINE> self.clientProtocol.requireTransportSecurity = False <NEW_LINE> self.clientProtocol.heloFallback = True <NEW_LINE> self.clientProtocol.makeConnection(transport) <NEW_LINE> self.clientProtocol.dataReceived(b"220 localhost\r\n") <NEW_LINE> transport.clear() <NEW_LINE> self.clientProtocol.dataReceived(b"500 not an esmtp server\r\n") <NEW_LINE> self.assertEqual(b"HELO testuser\r\n", transport.value()) <NEW_LINE> <DEDENT> def test_requireAuthFailsHELOFallback(self): <NEW_LINE> <INDENT> transport = StringTransport() <NEW_LINE> self.clientProtocol.requireAuthentication = True <NEW_LINE> self.clientProtocol.requireTransportSecurity = False <NEW_LINE> self.clientProtocol.heloFallback = True <NEW_LINE> self.clientProtocol.makeConnection(transport) <NEW_LINE> self.clientProtocol.dataReceived(b"220 localhost\r\n") <NEW_LINE> transport.clear() <NEW_LINE> self.clientProtocol.dataReceived(b"500 not an esmtp server\r\n") <NEW_LINE> self.assertEqual("QUIT\r\n", transport.value()) <NEW_LINE> <DEDENT> def test_requireTLSFailsHELOFallback(self): <NEW_LINE> <INDENT> transport = StringTransport() <NEW_LINE> self.clientProtocol.requireAuthentication = False <NEW_LINE> self.clientProtocol.requireTransportSecurity = True <NEW_LINE> self.clientProtocol.heloFallback = True <NEW_LINE> self.clientProtocol.makeConnection(transport) <NEW_LINE> self.clientProtocol.dataReceived(b"220 localhost\r\n") <NEW_LINE> transport.clear() <NEW_LINE> self.clientProtocol.dataReceived(b"500 not an esmtp server\r\n") <NEW_LINE> self.assertEqual(b"QUIT\r\n", transport.value()) <NEW_LINE> <DEDENT> def test_requireTLSAndHELOFallbackSucceedsIfOverTLS(self): <NEW_LINE> <INDENT> transport = StringTransport() <NEW_LINE> directlyProvides(transport, interfaces.ISSLTransport) <NEW_LINE> self.clientProtocol.requireAuthentication = False <NEW_LINE> self.clientProtocol.requireTransportSecurity = True <NEW_LINE> self.clientProtocol.heloFallback = True <NEW_LINE> self.clientProtocol.makeConnection(transport) <NEW_LINE> self.clientProtocol.dataReceived(b"220 localhost\r\n") <NEW_LINE> transport.clear() <NEW_LINE> self.clientProtocol.dataReceived(b"500 not an esmtp server\r\n") <NEW_LINE> self.assertEqual(b"HELO testuser\r\n", transport.value()) | Tests for the ESMTP -> SMTP downgrade functionality in L{smtp.ESMTPClient}. | 625990727047854f46340c9f |
class McCallModel: <NEW_LINE> <INDENT> def __init__(self, alpha=0.2, beta=0.98, gamma=0.7, c=6.0, sigma=2.0, w_vec=None, p_vec=None): <NEW_LINE> <INDENT> self.alpha, self.beta, self.gamma, self.c = alpha, beta, gamma, c <NEW_LINE> self.sigma = sigma <NEW_LINE> if w_vec is None: <NEW_LINE> <INDENT> n = 60 <NEW_LINE> self.w_vec = np.linspace(10, 20, n) <NEW_LINE> a, b = 600, 400 <NEW_LINE> dist = BetaBinomial(n-1, a, b) <NEW_LINE> self.p_vec = dist.pdf() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.w_vec = w_vec <NEW_LINE> self.p_vec = p_vec | Stores the parameters and functions associated with a given model. | 62599072283ffb24f3cf5191 |
class variate_generator: <NEW_LINE> <INDENT> def __init__(self, engine, distribution): <NEW_LINE> <INDENT> self.engine = engine <NEW_LINE> self.distribution = distribution <NEW_LINE> <DEDENT> def seed(self, value): <NEW_LINE> <INDENT> self.engine.seed(value) <NEW_LINE> self.distribution.reset() <NEW_LINE> <DEDENT> def __call__(self, shape=None): <NEW_LINE> <INDENT> if shape is None: <NEW_LINE> <INDENT> return self.distribution(self.engine) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> l = [self.distribution(self.engine) for k in range(numpy.prod(shape))] <NEW_LINE> return numpy.array(l).reshape(shape) | A pure-python version of the boost::variate_generator<> class
Keyword parameters:
engine
An instance of the RNG you would like to use. This has to be an
object of the class :py:class:`bob.core.random.mt19937`, already
initialized.
distribution
The distribution to respect when generating scalars using the engine.
The distribution object should be previously initialized. | 62599072cc0a2c111447c745 |
class TestTaskByDidList(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testTaskByDidList(self): <NEW_LINE> <INDENT> model = artikcloud.models.task_by_did_list.TaskByDidList() | TaskByDidList unit test stubs | 62599072d486a94d0ba2d8a7 |
class ClickLogger(Logger): <NEW_LINE> <INDENT> def success(self, message: str): <NEW_LINE> <INDENT> self.log(LogTag.SUCCESS, message, LogColor.SUCCESS) <NEW_LINE> <DEDENT> def info(self, message: str): <NEW_LINE> <INDENT> self.log(LogTag.INFO, message, LogColor.INFO) <NEW_LINE> <DEDENT> def warn(self, message: str): <NEW_LINE> <INDENT> self.log(LogTag.WARN, message, LogColor.WARN) <NEW_LINE> <DEDENT> def error(self, message: str): <NEW_LINE> <INDENT> self.log(LogTag.ERROR, message, LogColor.ERROR) <NEW_LINE> <DEDENT> def critical(self, message: str): <NEW_LINE> <INDENT> self.log(LogTag.CRITICAL, message, LogColor.CRITICAL) <NEW_LINE> <DEDENT> def log(self, tag: LogTag, message: str, color: LogColor): <NEW_LINE> <INDENT> click.secho(f"[ {tag.name[:4]} ] {message}", fg=color.value) | Logger that uses click logging utilities to log to stdout.
Format in the form of:
[ TAG ] MESSAGE | 62599072b7558d5895464ba7 |
class Product_admin(admin.ModelAdmin): <NEW_LINE> <INDENT> pass | Admin View for Product Model | 62599072ac7a0e7691f73dd2 |
class HTMLFile(XHTMLFile): <NEW_LINE> <INDENT> class_mimetypes = ['text/html'] <NEW_LINE> class_extension = 'html' <NEW_LINE> @classmethod <NEW_LINE> def get_skeleton(cls, title=''): <NEW_LINE> <INDENT> skeleton = ( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n' ' "http://www.w3.org/TR/html4/loose.dtd">\n' '<html>\n' ' <head>\n' ' <meta http-equiv="Content-Type" content="text/html;' 'charset=UTF-8">\n' ' <title>%(title)s</title>\n' ' </head>\n' ' <body></body>\n' '</html>') <NEW_LINE> return skeleton % {'title': title} <NEW_LINE> <DEDENT> def _load_state_from_file(self, file): <NEW_LINE> <INDENT> data = file.read() <NEW_LINE> stream = HTMLParser(data) <NEW_LINE> self.events = list(stream) <NEW_LINE> <DEDENT> def load_state_from_string(self, string): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> stream = HTMLParser(string) <NEW_LINE> self.events = list(stream) <NEW_LINE> <DEDENT> to_str = XHTMLFile.to_html <NEW_LINE> def translate(self, catalog, srx_handler=None): <NEW_LINE> <INDENT> stream = translate(self.events, catalog, srx_handler) <NEW_LINE> return stream_to_str_as_html(stream) | HTML files are a lot like XHTML, only the parsing and the output is
different, so we inherit from XHTMLFile instead of TextFile, even if the
mime type is 'text/html'.
The parsing is based on the HTMLParser class, which has a more object
oriented approach than the expat parser used for xml, i.e. we inherit
from HTMLParser. | 6259907256b00c62f0fb41b8 |
class RemoveExpiredSessions(superdesk.Command): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> self.remove_expired_sessions() <NEW_LINE> <DEDENT> def remove_expired_sessions(self): <NEW_LINE> <INDENT> expiry_minutes = app.settings['SESSION_EXPIRY_MINUTES'] <NEW_LINE> expiration_time = utcnow() - timedelta(minutes=expiry_minutes) <NEW_LINE> logger.info('Deleting session not updated since {}'.format(expiration_time)) <NEW_LINE> query = {'_updated': {'$lte': date_to_str(expiration_time)}} <NEW_LINE> sessions = get_resource_service('auth').get(req=None, lookup=query) <NEW_LINE> for session in sessions: <NEW_LINE> <INDENT> get_resource_service('auth').delete_action({'_id': str(session['_id'])}) <NEW_LINE> <DEDENT> self._update_online_users() <NEW_LINE> <DEDENT> def _update_online_users(self): <NEW_LINE> <INDENT> online_users = self._get_online_users() <NEW_LINE> active_sessions_ids = self._get_active_session_ids() <NEW_LINE> for user in online_users: <NEW_LINE> <INDENT> session_preferences = user.get('session_preferences', {}) <NEW_LINE> active = {_id: data for _id, data in session_preferences.items() if active_sessions_ids.get(_id)} <NEW_LINE> if len(active) != len(session_preferences): <NEW_LINE> <INDENT> get_resource_service('users').system_update(user['_id'], {'session_preferences': active}, user) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _get_active_session_ids(self): <NEW_LINE> <INDENT> active_sessions = get_resource_service('auth').get(req=None, lookup={}) <NEW_LINE> return {str(sess['_id']): True for sess in active_sessions} <NEW_LINE> <DEDENT> def _get_online_users(self): <NEW_LINE> <INDENT> return get_resource_service('users').get_from_mongo(None, { 'session_preferences': {'$exists': True, '$nin': [None, {}]} }) | Remove expired sessions from db.
Using ``SESSION_EXPIRY_MINUTES`` config.
Example:
::
$ python manage.py session:gc | 62599072f9cc0f698b1c5f3f |
class MustContainAtSymbolError(Error): <NEW_LINE> <INDENT> pass | The email does not contain @. | 62599072d486a94d0ba2d8a8 |
class CardCollection(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._cards = [] <NEW_LINE> <DEDENT> def add_card(self, card): <NEW_LINE> <INDENT> if type(card) is not Card: <NEW_LINE> <INDENT> raise InvalidCardException(( 'The first argument to the CardCollection.add_card' 'method must be an instance of the Card class.')) <NEW_LINE> <DEDENT> self._cards.append(card) <NEW_LINE> <DEDENT> def count(self): <NEW_LINE> <INDENT> return len(self._cards) <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self.count() == 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = '' <NEW_LINE> for card in self._cards: <NEW_LINE> <INDENT> result += str(card) + ' ' <NEW_LINE> <DEDENT> return result.rstrip() | The cards in a CardCollection are arranged in any order. A
CardCollection can contain any number of cards. | 625990721b99ca40022901aa |
class ErrorHarCaptureTest(HarCaptureTestBase): <NEW_LINE> <INDENT> @expectedFailure <NEW_LINE> def test_har_is_captured_on_error_in_error_mode(self): <NEW_LINE> <INDENT> self.should_capture = 1 <NEW_LINE> self.visit_pages() <NEW_LINE> raise Exception('Raising generic exception so that this test will error.') <NEW_LINE> <DEDENT> @expectedFailure <NEW_LINE> def test_har_is_captured_on_failure_in_error_mode(self): <NEW_LINE> <INDENT> self.should_capture = 1 <NEW_LINE> self.visit_pages() <NEW_LINE> self.assertTrue(False) <NEW_LINE> <DEDENT> def test_har_is_not_captured_on_success_in_error_mode(self): <NEW_LINE> <INDENT> self.should_capture = 0 <NEW_LINE> self.visit_pages() <NEW_LINE> self.assertTrue(True) <NEW_LINE> <DEDENT> def test_explicit_har_capture_doesnt_work_in_error_mode(self): <NEW_LINE> <INDENT> self.should_capture = 0 <NEW_LINE> with self.assertRaises(MethodNotEnabledInCurrentMode): <NEW_LINE> <INDENT> self.har_capturer.add_page(self.browser, 'ButtonPage') <NEW_LINE> <DEDENT> with self.assertRaises(MethodNotEnabledInCurrentMode): <NEW_LINE> <INDENT> self.har_capturer.save_har(self.browser) | How the har_mode is set: using environment var `BOK_CHOY_HAR_MODE`. This can
be overridden for an individual test class using the @attr decorator from
the nose.plugin.attrib module. | 625990725166f23b2e244cbd |
class Command(BaseCommand): <NEW_LINE> <INDENT> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument('filename') <NEW_LINE> parser.add_argument('--log', dest='log') <NEW_LINE> <DEDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> if options['log']: <NEW_LINE> <INDENT> logging.basicConfig(filename=options['log'], level=logging.DEBUG) <NEW_LINE> <DEDENT> with open(options['filename']) as e_file: <NEW_LINE> <INDENT> lines = [line.strip().split(',') for line in e_file] <NEW_LINE> <DEDENT> User.objects.filter(is_staff=False).update(is_active=False) <NEW_LINE> usernames = [row[0].strip() for row in lines] <NEW_LINE> try: <NEW_LINE> <INDENT> active_users = User.objects.filter(username__in=usernames) <NEW_LINE> active_users.update(is_active=True) <NEW_LINE> not_active_students = User.objects.filter(is_active=False) <NEW_LINE> if not_active_students: <NEW_LINE> <INDENT> for user in not_active_students: <NEW_LINE> <INDENT> print("{} {} is no longer active.".format(user.first_name, user.last_name)) <NEW_LINE> <DEDENT> <DEDENT> print("\n Active user count: {}\n Non-active user count: {} ".format(active_users.count(), not_active_students.count())) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> string = 'ERROR: \n Exception: {e}'.format(e=e) <NEW_LINE> print(string) <NEW_LINE> logging.error(string) | A command for updating whether students are active. Expects a comma
separated list, where the username is the first object, and the rest are ignored
If the name is not in the list, the student will be made inactive. | 6259907263b5f9789fe86a4d |
class IterableLoopInterface(TaskInterface): <NEW_LINE> <INDENT> iterable = Str('0.0').tag(pref=True) <NEW_LINE> def check(self, *args, **kwargs): <NEW_LINE> <INDENT> test = True <NEW_LINE> traceback = {} <NEW_LINE> task = self.task <NEW_LINE> err_path = task.task_path + '/' + task.task_name <NEW_LINE> try: <NEW_LINE> <INDENT> iterable = task.format_and_eval_string(self.iterable) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> test = False <NEW_LINE> mess = 'Loop task did not success to compute the iterable: {}' <NEW_LINE> traceback[err_path] = mess.format(e) <NEW_LINE> return test, traceback <NEW_LINE> <DEDENT> if isinstance(iterable, Iterable): <NEW_LINE> <INDENT> task.write_in_database('point_number', len(iterable)) <NEW_LINE> if 'value' in task.task_database_entries: <NEW_LINE> <INDENT> task.write_in_database('value', next(iter(iterable))) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> test = False <NEW_LINE> traceback[err_path] = 'The computed iterable is not iterable.' <NEW_LINE> <DEDENT> return test, traceback <NEW_LINE> <DEDENT> def perform(self): <NEW_LINE> <INDENT> task = self.task <NEW_LINE> iterable = task.format_and_eval_string(self.iterable) <NEW_LINE> task.perform_loop(iterable) | Common logic for all loop tasks.
| 625990722ae34c7f260ac9d4 |
class WeatherViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> @method_decorator(cache_page(60*2)) <NEW_LINE> def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> weather_url = 'http://api.openweathermap.org/data/2.5/weather?q='+ kwargs.get('city')+','+kwargs.get('country')+ '&appid=1508a9a4840a5574c822d70ca2132032' <NEW_LINE> weather_response = requests.get(weather_url) <NEW_LINE> if weather_response.status_code == 404: <NEW_LINE> <INDENT> raise InvalidPlace <NEW_LINE> <DEDENT> response_dict = format_weather(weather_response) <NEW_LINE> return Response( response_dict, status=status.HTTP_200_OK, content_type='application/json') | Allows the users to get the weather | 62599072e5267d203ee6d032 |
class PPO(NPO): <NEW_LINE> <INDENT> def __init__(self, optimizer=None, optimizer_args=None, **kwargs): <NEW_LINE> <INDENT> if optimizer is None: <NEW_LINE> <INDENT> optimizer = FirstOrderOptimizer <NEW_LINE> if optimizer_args is None: <NEW_LINE> <INDENT> optimizer_args = dict() <NEW_LINE> <DEDENT> <DEDENT> super(PPO, self).__init__( pg_loss=PGLoss.CLIP, optimizer=optimizer, optimizer_args=optimizer_args, **kwargs) | Proximal Policy Optimization.
See https://arxiv.org/abs/1707.06347. | 625990728e7ae83300eea97b |
class DatabaseIterator(object): <NEW_LINE> <INDENT> def __init__(self, curs): <NEW_LINE> <INDENT> self.curs = curs <NEW_LINE> self.iter = curs.__iter__() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def convert(self, row): <NEW_LINE> <INDENT> return row <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.convert(self.iter.next()) <NEW_LINE> <DEDENT> except (StopIteration, GeneratorExit): <NEW_LINE> <INDENT> self.curs.close() <NEW_LINE> raise | A DatabaseIterator supplies on-the-fly translation of database-
specific column values (such as cx_Oracle's BLOB data types), one
row at a time. The database cursor is used as sub-iterator so
that data is only read and converted on actual use.
Subclasses override the convert() method, which should return a
sequence where possible database-specific values have been type
converted. | 62599072091ae35668706522 |
class SQLiTemplate(BaseTemplate): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SQLiTemplate, self).__init__() <NEW_LINE> self.name = self.get_vulnerability_name() <NEW_LINE> <DEDENT> def create_vuln(self): <NEW_LINE> <INDENT> v = self.create_base_vuln() <NEW_LINE> url = self.url <NEW_LINE> if self.method.upper() == 'GET': <NEW_LINE> <INDENT> url.querystring = self.data <NEW_LINE> <DEDENT> v.set_method(self.method) <NEW_LINE> v.set_name(self.name) <NEW_LINE> v.set_var(self.vulnerable_parameter) <NEW_LINE> v.set_url(url) <NEW_LINE> v.set_dc(self.data) <NEW_LINE> freq = FuzzableRequest(url, method=self.method, dc=self.data) <NEW_LINE> mutant = Mutant(freq) <NEW_LINE> mutant.set_var(self.vulnerable_parameter) <NEW_LINE> mutant.set_dc(self.data) <NEW_LINE> mutant.set_original_value(self.data[self.vulnerable_parameter][0]) <NEW_LINE> v.set_mutant(mutant) <NEW_LINE> return v <NEW_LINE> <DEDENT> def get_kb_location(self): <NEW_LINE> <INDENT> return ('sqli', 'sqli') <NEW_LINE> <DEDENT> def get_vulnerability_name(self): <NEW_LINE> <INDENT> return '(Blind) SQL injection' <NEW_LINE> <DEDENT> def get_vulnerability_desc(self): <NEW_LINE> <INDENT> return 'Blind and error based SQL injection vulnerability.' | Vulnerability template for SQL injection vulnerability. | 62599072ac7a0e7691f73dd4 |
class Proto(RuleChoice): <NEW_LINE> <INDENT> tcp = 'tcp' <NEW_LINE> udp = 'udp' <NEW_LINE> icmp = 'icmp' <NEW_LINE> @property <NEW_LINE> def rule(self): <NEW_LINE> <INDENT> return 'proto=' + str(self) | Protocol name | 62599072a8370b77170f1cb5 |
class WellSample(object): <NEW_LINE> <INDENT> def __init__(self, node): <NEW_LINE> <INDENT> self.node = node <NEW_LINE> <DEDENT> def get_ID(self): <NEW_LINE> <INDENT> return self.node.get("ID") <NEW_LINE> <DEDENT> def set_ID(self, value): <NEW_LINE> <INDENT> self.node.set("ID", value) <NEW_LINE> <DEDENT> ID = property(get_ID, set_ID) <NEW_LINE> def get_PositionX(self): <NEW_LINE> <INDENT> return get_float_attr(self.node, "PositionX") <NEW_LINE> <DEDENT> def set_PositionX(self, value): <NEW_LINE> <INDENT> self.node.set("PositionX", str(value)) <NEW_LINE> <DEDENT> PositionX = property(get_PositionX, set_PositionX) <NEW_LINE> def get_PositionY(self): <NEW_LINE> <INDENT> return get_float_attr(self.node, "PositionY") <NEW_LINE> <DEDENT> def set_PositionY(self, value): <NEW_LINE> <INDENT> self.node.set("PositionY", str(value)) <NEW_LINE> <DEDENT> PositionY = property(get_PositionY, set_PositionY) <NEW_LINE> def get_Timepoint(self): <NEW_LINE> <INDENT> return self.node.get("Timepoint") <NEW_LINE> <DEDENT> def set_Timepoint(self, value): <NEW_LINE> <INDENT> if isinstance(value, datetime.datetime): <NEW_LINE> <INDENT> value = value.isoformat() <NEW_LINE> <DEDENT> self.node.set("Timepoint", value) <NEW_LINE> <DEDENT> Timepoint = property(get_Timepoint, set_Timepoint) <NEW_LINE> def get_Index(self): <NEW_LINE> <INDENT> return get_int_attr(self.node, "Index") <NEW_LINE> <DEDENT> def set_Index(self, value): <NEW_LINE> <INDENT> self.node.set("Index", str(value)) <NEW_LINE> <DEDENT> Index = property(get_Index, set_Index) <NEW_LINE> def get_ImageRef(self): <NEW_LINE> <INDENT> ref = self.node.find(qn(NS_SPW, "ImageRef")) <NEW_LINE> if ref is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ref.get("ID") <NEW_LINE> <DEDENT> def set_ImageRef(self, value): <NEW_LINE> <INDENT> ref = self.node.find(qn(NS_SPW, "ImageRef")) <NEW_LINE> if ref is None: <NEW_LINE> <INDENT> ref = ElementTree.SubElement(self.node, qn(NS_SPW, "ImageRef")) <NEW_LINE> <DEDENT> ref.set("ID", value) <NEW_LINE> <DEDENT> ImageRef = property(get_ImageRef, set_ImageRef) | The WellSample is a location within a well | 625990727d847024c075dcc4 |
class ts_quest_labels(dtable): <NEW_LINE> <INDENT> quest_sn = datt(ts_quest_seqno, doc='题号') <NEW_LINE> type = datt(str, len=1, doc='标签类型: T标签, C分类') <NEW_LINE> labels = datt(array(int), doc='标签') <NEW_LINE> updated_ts = datt(datetime, doc='更新时间') <NEW_LINE> __dobject_key__ = [quest_sn, type] | 题目的标签(Tag) | 625990727d43ff2487428088 |
class BernoulliRV(RandomVariable): <NEW_LINE> <INDENT> def __init__(self, p): <NEW_LINE> <INDENT> self.p_ = p <NEW_LINE> <DEDENT> def sample_success(self): <NEW_LINE> <INDENT> return scipy.stats.bernoulli.rvs(self.p_) <NEW_LINE> <DEDENT> def p(self): <NEW_LINE> <INDENT> return self.p_ <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return self.p_ <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Bernoulli({})'.format(self.p_) | Bernoulli RV class for use with Beta-Bernoulli bandit testing | 625990721f5feb6acb1644de |
class GeneralDeltaTLineAnalyzer(GeneralLineAnalyzer): <NEW_LINE> <INDENT> def __init__(self, doTimelines=True, doFiles=True, singleFile=False, startTime=None, endTime=None): <NEW_LINE> <INDENT> GeneralLineAnalyzer.__init__(self, titles=["deltaT"], doTimelines=doTimelines, doFiles=doFiles, singleFile=singleFile, startTime=startTime, endTime=endTime) <NEW_LINE> self.exp=re.compile(continutityRegExp) <NEW_LINE> self.registerRegexp(self.exp) <NEW_LINE> <DEDENT> def addToFiles(self,match): <NEW_LINE> <INDENT> self.files.write("deltaT",self.parent.getTime(),match.groups()) <NEW_LINE> <DEDENT> def addToTimelines(self,match): <NEW_LINE> <INDENT> self.lines.setValue("deltaT",match.groups()[0]) | Parses line for continuity information | 62599072aad79263cf4300a1 |
class GetFormNode(template.Node): <NEW_LINE> <INDENT> def __init__(self, form_class, context_var, request): <NEW_LINE> <INDENT> self.context_var = context_var <NEW_LINE> self.request = template.Variable(request) <NEW_LINE> self.form_class = form_class <NEW_LINE> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> request = self.request.resolve(context) <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> form = self.form_class(request.POST) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = self.form_class() <NEW_LINE> <DEDENT> context[self.context_var] = form <NEW_LINE> return '' | Template node to return a queryset in a specified
variable in the context | 625990724e4d562566373cf2 |
class SubmitNewRequest(SubmitNewRequest): <NEW_LINE> <INDENT> tool_name = 'slip' <NEW_LINE> task_model_name = 'SlipTask' <NEW_LINE> celery_task_func = run <NEW_LINE> form_list = [DataSelectionForm, AdditionalOptionsForm] | Submit new request REST API Endpoint
Extends the SubmitNewRequest abstract class - required attributes are the tool_name,
task_model_name, form_list, and celery_task_func
Note:
celery_task_func should be callable with .delay() and take a single argument of a TaskModel pk.
See the dc_algorithm.views docstrings for more information. | 6259907276e4537e8c3f0e6a |
class JuliaConsoleLexer(Lexer): <NEW_LINE> <INDENT> name = 'Julia console' <NEW_LINE> aliases = ['jlcon'] <NEW_LINE> def get_tokens_unprocessed(self, text): <NEW_LINE> <INDENT> jllexer = JuliaLexer(**self.options) <NEW_LINE> curcode = '' <NEW_LINE> insertions = [] <NEW_LINE> for match in line_re.finditer(text): <NEW_LINE> <INDENT> line = match.group() <NEW_LINE> if line.startswith('julia>'): <NEW_LINE> <INDENT> insertions.append((len(curcode), [(0, Generic.Prompt, line[:6])])) <NEW_LINE> curcode += line[6:] <NEW_LINE> <DEDENT> elif line.startswith(' '): <NEW_LINE> <INDENT> idx = len(curcode) <NEW_LINE> line = "\n" + line <NEW_LINE> token = (0, Generic.Traceback, line) <NEW_LINE> insertions.append((idx, [token])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if curcode: <NEW_LINE> <INDENT> for item in do_insertions( insertions, jllexer.get_tokens_unprocessed(curcode)): <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> curcode = '' <NEW_LINE> insertions = [] <NEW_LINE> <DEDENT> yield match.start(), Generic.Output, line <NEW_LINE> <DEDENT> <DEDENT> if curcode: <NEW_LINE> <INDENT> for item in do_insertions( insertions, jllexer.get_tokens_unprocessed(curcode)): <NEW_LINE> <INDENT> yield item | For Julia console sessions. Modeled after MatlabSessionLexer.
.. versionadded:: 1.6 | 6259907267a9b606de547719 |
class StdOutListener(StreamListener): <NEW_LINE> <INDENT> def on_data(self, data): <NEW_LINE> <INDENT> decoded = json.loads(data) <NEW_LINE> if 'media' not in decoded['entities']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> string = decoded['entities']['media'][0]['media_url'] <NEW_LINE> path = 'imgs/'+decoded['user']['screen_name']+'_'+decoded['id_str']+'.jpg' <NEW_LINE> img = urllib.request.urlopen(string) <NEW_LINE> localFile = open(path, 'wb') <NEW_LINE> localFile.write(img.read()) <NEW_LINE> localFile.close() <NEW_LINE> print('@'+decoded['user']['screen_name']+' -> '+string) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def on_error(self, status): <NEW_LINE> <INDENT> f.close() <NEW_LINE> print(status) | A listener handles tweets that are received from the stream.
This is a basic listener that just prints received tweets to stdout. | 6259907297e22403b383c7ee |
class _ModuleManager(_ManageReload): <NEW_LINE> <INDENT> def __init__(self, name, *, reset_name=True): <NEW_LINE> <INDENT> super().__init__(name) <NEW_LINE> self._reset_name = reset_name <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> super().__enter__() <NEW_LINE> self._module = sys.modules.get(self._name) <NEW_LINE> if not self._is_reload: <NEW_LINE> <INDENT> self._module = type(_io)(self._name) <NEW_LINE> self._module.__initializing__ = True <NEW_LINE> sys.modules[self._name] = self._module <NEW_LINE> <DEDENT> elif self._reset_name: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._module.__name__ = self._name <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self._module <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> self._module.__initializing__ = False <NEW_LINE> del self._module <NEW_LINE> super().__exit__(*args) | Context manager which returns the module to be loaded.
Does the proper unloading from sys.modules upon failure. | 625990728a43f66fc4bf3a80 |
class TFGauss2D(Gauss2D): <NEW_LINE> <INDENT> name = 'TF + Gauss2D' <NEW_LINE> parameterNames = ['TF Height', 'Gauss Height', 'X Center', 'Y Center', 'TF X Radius', 'TF Y Radius', 'Gauss X Width', 'Gauss Y Width', 'Offset'] <NEW_LINE> def __init__(self, im=None): <NEW_LINE> <INDENT> super(TFGauss2D, self).__init__(im) <NEW_LINE> self.fitParameters = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0] <NEW_LINE> self.fitParmSD = [0.0] * len(self.parameterNames) <NEW_LINE> self.guess = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0] <NEW_LINE> <DEDENT> def autoGuess(self): <NEW_LINE> <INDENT> gaussGuess = super(TFGauss2D, self).autoGuess() <NEW_LINE> (height, center_x, center_y, width_x, width_y, offset) = gaussGuess <NEW_LINE> self.guess = [height, height/2.0, center_x, center_y, width_x*2.0, width_y*2.0, width_x*2.0, width_y*2.0, offset] <NEW_LINE> return self.guess <NEW_LINE> <DEDENT> def fitFunction(self, h_tf, h_g, cx, cy, rx, ry, wx, wy, offset): <NEW_LINE> <INDENT> def isG0(a): <NEW_LINE> <INDENT> return a * (a > 0) <NEW_LINE> <DEDENT> return lambda x, y: ((isG0(h_tf * (1 - ((x - cx) / rx)**2 - ((y-cy) / ry) ** 2))) + h_g * np.exp(-(((cx - x)/wx) ** 2 + ((cy - y) / wy) ** 2) / 2.0) + offset) | Fitter class for a 2D Thomas Fermi profile | 625990724c3428357761bba0 |
class DynamicNetwork: <NEW_LINE> <INDENT> def __init__(self, num_ues, num_aps, scale): <NEW_LINE> <INDENT> self.num_ues = num_ues <NEW_LINE> self.num_aps = num_aps <NEW_LINE> self.scale = scale | Simulation of a cellular network where APs are dynamically positioned in
every cell of the grid. | 625990725166f23b2e244cbf |
class Filez(SurrogatePK, Model): <NEW_LINE> <INDENT> __tablename__ = "files" <NEW_LINE> user_id = reference_col("users", nullable=True) <NEW_LINE> user = relationship("User", cascade="all,delete", backref="fileusers") <NEW_LINE> when_uploaded = Column(db.DateTime(), nullable=False, default=datetime.utcnow) <NEW_LINE> is_private = db.Column(db.Boolean, nullable=True) <NEW_LINE> rid = db.Column(UUID(as_uuid=True), unique=True, nullable=False) <NEW_LINE> description = db.Column(db.String, nullable=False) <NEW_LINE> def __init__(self, is_private, description, rid, **kwargs): <NEW_LINE> <INDENT> db.Model.__init__( self, is_private=is_private, description=description, rid=rid, **kwargs ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<id: {}, desc: {}, when: {}>".format( self.id, self.description, self.rid, self.when_uploaded ) | Table with uploaded raw GPX files. | 625990725fcc89381b266dcd |
class MinimumMaximum(Component): <NEW_LINE> <INDENT> def set_data(self, data): <NEW_LINE> <INDENT> pertinent = read_path_dict(data, self.source) <NEW_LINE> if pertinent: <NEW_LINE> <INDENT> self.minimum = pertinent.get('minimum') <NEW_LINE> self.maximum = pertinent.get('maximum') <NEW_LINE> self.value = pertinent.get('current') <NEW_LINE> self.step = pertinent.get('step', 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ComponentException('Data %s has no source key : %s.' % (str(data), self.source)) <NEW_LINE> <DEDENT> <DEDENT> def left(self, unit=1): <NEW_LINE> <INDENT> self.value -= self.step * unit <NEW_LINE> if self.value < self.minimum: <NEW_LINE> <INDENT> self.value = self.minimum <NEW_LINE> <DEDENT> self.publish_change(self.value) <NEW_LINE> <DEDENT> def right(self, unit=1): <NEW_LINE> <INDENT> self.value += self.step * unit <NEW_LINE> if self.value > self.maximum: <NEW_LINE> <INDENT> self.value = self.maximum <NEW_LINE> <DEDENT> self.publish_change(self.value) | Abstract class for component with a current / minimum / maximum
data model.
Components should be able to read in a data dictionary a structure
containing "minimum", "maximum" and "current". | 62599072097d151d1a2c295e |
class WasbPrefixSensor(BaseSensorOperator): <NEW_LINE> <INDENT> template_fields = ('container_name', 'prefix') <NEW_LINE> @apply_defaults <NEW_LINE> def __init__(self, container_name, prefix, wasb_conn_id='wasb_default', check_options=None, *args, **kwargs): <NEW_LINE> <INDENT> super(WasbPrefixSensor, self).__init__(*args, **kwargs) <NEW_LINE> if check_options is None: <NEW_LINE> <INDENT> check_options = {} <NEW_LINE> <DEDENT> self.wasb_conn_id = wasb_conn_id <NEW_LINE> self.container_name = container_name <NEW_LINE> self.prefix = prefix <NEW_LINE> self.check_options = check_options <NEW_LINE> <DEDENT> def poke(self, context): <NEW_LINE> <INDENT> self.log.info( 'Poking for prefix: {self.prefix}\n' 'in wasb://{self.container_name}'.format(**locals()) ) <NEW_LINE> hook = WasbHook(wasb_conn_id=self.wasb_conn_id) <NEW_LINE> return hook.check_for_prefix(self.container_name, self.prefix, **self.check_options) | Waits for blobs matching a prefix to arrive on Azure Blob Storage.
:param container_name: Name of the container.
:type container_name: str
:param prefix: Prefix of the blob.
:type prefix: str
:param wasb_conn_id: Reference to the wasb connection.
:type wasb_conn_id: str
:param check_options: Optional keyword arguments that
`WasbHook.check_for_prefix()` takes.
:type check_options: dict | 625990722ae34c7f260ac9d5 |
@ddt.ddt <NEW_LINE> class RedeemCodeEmbargoTests(UrlResetMixin, ModuleStoreTestCase): <NEW_LINE> <INDENT> USERNAME = 'bob' <NEW_LINE> PASSWORD = 'test' <NEW_LINE> URLCONF_MODULES = ['embargo'] <NEW_LINE> @patch.dict(settings.FEATURES, {'EMBARGO': True}) <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(RedeemCodeEmbargoTests, self).setUp() <NEW_LINE> self.course = CourseFactory.create() <NEW_LINE> self.user = UserFactory.create(username=self.USERNAME, password=self.PASSWORD) <NEW_LINE> result = self.client.login(username=self.user.username, password=self.PASSWORD) <NEW_LINE> self.assertTrue(result, msg="Could not log in") <NEW_LINE> <DEDENT> @ddt.data('get', 'post') <NEW_LINE> @patch.dict(settings.FEATURES, {'EMBARGO': True}) <NEW_LINE> def test_registration_code_redemption_embargo(self, method): <NEW_LINE> <INDENT> reg_code = CourseRegistrationCode.objects.create( code="abcd1234", course_id=self.course.id, created_by=self.user ) <NEW_LINE> with restrict_course(self.course.id) as redirect_url: <NEW_LINE> <INDENT> url = reverse( 'register_code_redemption', kwargs={'registration_code': 'abcd1234'} ) <NEW_LINE> response = getattr(self.client, method)(url) <NEW_LINE> self.assertRedirects(response, redirect_url) <NEW_LINE> <DEDENT> is_redeemed = RegistrationCodeRedemption.objects.filter( registration_code=reg_code ).exists() <NEW_LINE> self.assertFalse(is_redeemed) <NEW_LINE> is_enrolled = CourseEnrollment.is_enrolled(self.user, self.course.id) <NEW_LINE> self.assertFalse(is_enrolled) | Test blocking redeem code redemption based on country access rules. | 62599072ec188e330fdfa190 |
class ICollectionFilterResultListSort(ICollectionFilterBaseSchema): <NEW_LINE> <INDENT> sort_on = schema.Tuple( title=_("label_sort_on", u"Enabled sort indexes"), description=_("help_sort_on", u"Select the indexes which can be sorted on."), value_type=schema.Choice( title=u"Index", vocabulary="collective.collectionfilter.SortOnIndexes", ), required=True, ) <NEW_LINE> widget("sort_on", SelectFieldWidget, pattern_options=dict(orderable=True)) <NEW_LINE> input_type = schema.Choice( title=_("label_input_type", u"Input Type"), description=_( "help_input_type", u"Select how the UI of the collection filter should be rendered. " u"Wether as links, as checkboxes and radiobuttons or checkboxes and dropdowns.", ), required=True, vocabulary="collective.collectionfilter.InputType", ) | Schema for the result list sorting. | 62599072283ffb24f3cf5195 |
class Lwm2mBootstrapServer(HelperBase): <NEW_LINE> <INDENT> def __init__(self, arguments="", timeout=3, encoding="utf8"): <NEW_LINE> <INDENT> base_path = str(Path(__file__).parent.absolute()) <NEW_LINE> self.pexpectobj = pexpect.spawn(base_path + "/../../build-wakaama/examples/" "bootstrap_server/bootstrap_server " + arguments, encoding=encoding, timeout=timeout) <NEW_LINE> self.pexpectobj.logfile = open(base_path + "/lwm2mbootstrapserver_log.txt", "w", encoding="utf-8") | Bootstrap-server subclass of HelperBase | 625990723539df3088ecdb82 |
class Dwarf(Race): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Dwarf, self).__init__() <NEW_LINE> self.name = "Dwarf" <NEW_LINE> self.plural = "Dwarves" <NEW_LINE> self.size = "small" <NEW_LINE> self.desc = ("|gDwarves|n are short, stocky demi-humans with long, " "respectable beards and heavy stout bodies. Their skin " "is earthen toned and their hair black, gray or dark " "brown. Stubborn but practical; dwarves love grand " "feasts and strong ale. They can be dangerous opponents, " "able to fight with any weapon, melee or ranged. They " "admire craftsmanship and are fond of gold and stonework. " "Dwarves are dependable fighters and sturdy against " "magical influences. ") <NEW_LINE> self.foci = [load_focus(f) for f in ('brawn', 'resilience', 'alertness')] <NEW_LINE> self.bonuses = {'WILL': 1} | Class representing dwarf attributes. | 625990724f6381625f19a11f |
class TotalLogFile(logfile.LogFile): <NEW_LINE> <INDENT> def __init__(self, name, directory, steal_stdio=False, **kwargs): <NEW_LINE> <INDENT> self._steal_stdio = steal_stdio <NEW_LINE> self._null_fd = os.open("/dev/null", os.O_RDWR) <NEW_LINE> logfile.LogFile.__init__(self, name, directory, **kwargs) <NEW_LINE> <DEDENT> def _do_stdio(self): <NEW_LINE> <INDENT> file_fd = self._file.fileno() <NEW_LINE> os.dup2(self._null_fd, 0) <NEW_LINE> os.dup2(file_fd, 1) <NEW_LINE> os.dup2(file_fd, 2) <NEW_LINE> <DEDENT> def _openFile(self): <NEW_LINE> <INDENT> logfile.LogFile._openFile(self) <NEW_LINE> if self._steal_stdio: <NEW_LINE> <INDENT> self._do_stdio() <NEW_LINE> <DEDENT> <DEDENT> def stdio(self): <NEW_LINE> <INDENT> self._steal_stdio = True <NEW_LINE> if not self.closed: <NEW_LINE> <INDENT> self._do_stdio() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> os.dup2(self._null_fd, 1) <NEW_LINE> os.dup2(self._null_fd, 2) <NEW_LINE> logfile.LogFile.close(self) | A log file that can optionally steal stdio | 62599072adb09d7d5dc0be57 |
class ClientsTestCase( unittest.TestCase ): <NEW_LINE> <INDENT> def setUp( self ): <NEW_LINE> <INDENT> self.mockRSS = mock.MagicMock() <NEW_LINE> self.GOCCli = GOCDBClient() <NEW_LINE> self.GGUSCli = GGUSTicketsClient() | Base class for the clients test cases
| 625990724e4d562566373cf3 |
class IpconfigError(CommandError): <NEW_LINE> <INDENT> pass | An exception to raise if the command fails. | 625990727d847024c075dcc6 |
class HTTPAuthResource(object): <NEW_LINE> <INDENT> implements(iweb.IResource) <NEW_LINE> def __init__(self, wrappedResource, credentialFactories, portal, interfaces): <NEW_LINE> <INDENT> self.wrappedResource = wrappedResource <NEW_LINE> self.credentialFactories = dict([(factory.scheme, factory) for factory in credentialFactories]) <NEW_LINE> self.portal = portal <NEW_LINE> self.interfaces = interfaces <NEW_LINE> <DEDENT> def _loginSucceeded(self, avatar, request): <NEW_LINE> <INDENT> request.avatarInterface, request.avatar = avatar <NEW_LINE> directlyProvides(request, IAuthenticatedRequest) <NEW_LINE> def _addAuthenticateHeaders(request, response): <NEW_LINE> <INDENT> if response.code == responsecode.UNAUTHORIZED: <NEW_LINE> <INDENT> if not response.headers.hasHeader('www-authenticate'): <NEW_LINE> <INDENT> newResp = UnauthorizedResponse(self.credentialFactories, request.remoteAddr) <NEW_LINE> response.headers.setHeader( 'www-authenticate', newResp.headers.getHeader('www-authenticate')) <NEW_LINE> <DEDENT> <DEDENT> return response <NEW_LINE> <DEDENT> _addAuthenticateHeaders.handleErrors = True <NEW_LINE> request.addResponseFilter(_addAuthenticateHeaders) <NEW_LINE> return self.wrappedResource <NEW_LINE> <DEDENT> def _loginFailed(self, result, request): <NEW_LINE> <INDENT> result.trap(error.UnauthorizedLogin, error.UnhandledCredentials) <NEW_LINE> return failure.Failure( http.HTTPError( UnauthorizedResponse( self.credentialFactories, request.remoteAddr))) <NEW_LINE> <DEDENT> def login(self, factory, response, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> creds = factory.decode(response, request) <NEW_LINE> <DEDENT> except error.LoginFailed: <NEW_LINE> <INDENT> raise http.HTTPError(UnauthorizedResponse( self.credentialFactories, request.remoteAddr)) <NEW_LINE> <DEDENT> return self.portal.login(creds, None, *self.interfaces ).addCallbacks(self._loginSucceeded, self._loginFailed, (request,), None, (request,), None) <NEW_LINE> <DEDENT> def authenticate(self, request): <NEW_LINE> <INDENT> authHeader = request.headers.getHeader('authorization') <NEW_LINE> if authHeader is None: <NEW_LINE> <INDENT> return self.portal.login(credentials.Anonymous(), None, *self.interfaces ).addCallbacks(self._loginSucceeded, self._loginFailed, (request,), None, (request,), None) <NEW_LINE> <DEDENT> elif authHeader[0] not in self.credentialFactories: <NEW_LINE> <INDENT> raise http.HTTPError(UnauthorizedResponse( self.credentialFactories, request.remoteAddr)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.login(self.credentialFactories[authHeader[0]], authHeader[1], request) <NEW_LINE> <DEDENT> <DEDENT> def locateChild(self, request, seg): <NEW_LINE> <INDENT> return self.authenticate(request), seg <NEW_LINE> <DEDENT> def renderHTTP(self, request): <NEW_LINE> <INDENT> def _renderResource(resource): <NEW_LINE> <INDENT> return resource.renderHTTP(request) <NEW_LINE> <DEDENT> d = self.authenticate(request) <NEW_LINE> d.addCallback(_renderResource) <NEW_LINE> return d | I wrap a resource to prevent it being accessed unless the authentication
can be completed using the credential factory, portal, and interfaces
specified. | 625990727d43ff2487428089 |
class QwtProject(PyQtProject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.bindings_factories = [QwtBindings] <NEW_LINE> <DEDENT> def update(self, tool): <NEW_LINE> <INDENT> super().update(tool) <NEW_LINE> self.sip_include_dirs.append(join(PyQt5.__path__[0], 'bindings')) | The Qwt Project class. | 6259907255399d3f05627e05 |
class MySplashScreen(wx.SplashScreen): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> aBitmap = wx.Image(name = "/opt/sidesa/png/1.png").ConvertToBitmap() <NEW_LINE> aBitmap1 = wx.Image(name = "/opt/sidesa/png/1.png").ConvertToBitmap() <NEW_LINE> splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT <NEW_LINE> splashDuration = 2000 <NEW_LINE> wx.SplashScreen.__init__(self, aBitmap1, splashStyle, splashDuration, parent) <NEW_LINE> self.Bind(wx.EVT_CLOSE, self.OnExit) <NEW_LINE> wx.Yield() <NEW_LINE> <DEDENT> def OnExit(self, evt): <NEW_LINE> <INDENT> self.Hide() <NEW_LINE> self.main = frm_sideka_menu.create(None) <NEW_LINE> self.main.Show() <NEW_LINE> evt.Skip() | Create a splash screen widget.
| 62599072baa26c4b54d50b99 |
class PatchClampStimPulseAnalyzer(GenericStimPulseAnalyzer): <NEW_LINE> <INDENT> def __init__(self, rec): <NEW_LINE> <INDENT> GenericStimPulseAnalyzer.__init__(self, rec) <NEW_LINE> self._evoked_spikes = None <NEW_LINE> <DEDENT> def pulses(self, channel='command'): <NEW_LINE> <INDENT> if self._pulses.get(channel) is None: <NEW_LINE> <INDENT> trace = self.rec[channel] <NEW_LINE> pulses = find_square_pulses(trace) <NEW_LINE> self._pulses[channel] = [] <NEW_LINE> for p in pulses: <NEW_LINE> <INDENT> start = p.global_start_time <NEW_LINE> stop = p.global_start_time + p.duration <NEW_LINE> self._pulses[channel].append((start, stop, p.amplitude)) <NEW_LINE> <DEDENT> <DEDENT> return self._pulses[channel] <NEW_LINE> <DEDENT> def pulse_chunks(self): <NEW_LINE> <INDENT> pre_trace = self.rec['primary'] <NEW_LINE> pulses = self.pulses() <NEW_LINE> stim_pulses = pulses[1:] if self.rec.has_inserted_test_pulse else pulses <NEW_LINE> chunks = [] <NEW_LINE> for i,pulse in enumerate(stim_pulses): <NEW_LINE> <INDENT> pulse_start_time, pulse_end_time, amp = pulse <NEW_LINE> if amp < 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> start_time = pulse_start_time - 2e-3 <NEW_LINE> stop_time = pulse_end_time + 4e-3 <NEW_LINE> if i < len(stim_pulses) - 1: <NEW_LINE> <INDENT> next_pulse_time = stim_pulses[i+1][0] <NEW_LINE> stop_time = min(stop_time, next_pulse_time) <NEW_LINE> <DEDENT> chunk = self.rec.time_slice(start_time, stop_time) <NEW_LINE> chunk.meta['pulse_edges'] = [pulse_start_time, pulse_end_time] <NEW_LINE> chunk.meta['pulse_amplitude'] = amp <NEW_LINE> chunk.meta['pulse_n'] = i <NEW_LINE> chunks.append(chunk) <NEW_LINE> <DEDENT> return chunks <NEW_LINE> <DEDENT> def evoked_spikes(self): <NEW_LINE> <INDENT> if self._evoked_spikes is None: <NEW_LINE> <INDENT> spike_info = [] <NEW_LINE> for i,chunk in enumerate(self.pulse_chunks()): <NEW_LINE> <INDENT> pulse_edges = chunk.meta['pulse_edges'] <NEW_LINE> spikes = detect_evoked_spikes(chunk, pulse_edges) <NEW_LINE> spike_info.append({'pulse_n': chunk.meta['pulse_n'], 'pulse_start': pulse_edges[0], 'pulse_end': pulse_edges[1], 'spikes': spikes}) <NEW_LINE> <DEDENT> self._evoked_spikes = spike_info <NEW_LINE> <DEDENT> return self._evoked_spikes | Used for analyzing a patch clamp recording with square-pulse stimuli.
| 625990723317a56b869bf1bb |
class Blockchain(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.chain = DB.child('chain').get().val() <NEW_LINE> if self.chain is None: <NEW_LINE> <INDENT> self.chain = [] <NEW_LINE> self.current_transactions = [] <NEW_LINE> self.new_block(previous_hash=1, proof=100) <NEW_LINE> self.nodes = set() <NEW_LINE> <DEDENT> <DEDENT> def new_block(self, proof, previous_hash=None): <NEW_LINE> <INDENT> index = len(self.chain) + 1 <NEW_LINE> block = Block(index, time(), self.current_transactions, proof, previous_hash) <NEW_LINE> self.current_transactions = [] <NEW_LINE> DB.child("chain").child("blocks").push(block.__dict__) <NEW_LINE> return block | Constructor | 625990725166f23b2e244cc1 |
class TestSuperUserOr403(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.request_factory = RequestFactory() <NEW_LINE> list_name = 'foolist.example.org' <NEW_LINE> list_id = 'foolist.example.org' <NEW_LINE> self.mock_list = create_mock_list(dict( fqdn_listname=list_name, list_id=list_id)) <NEW_LINE> <DEDENT> @patch.object(Client, 'get_list') <NEW_LINE> def test_anonymous_user(self, mock_get_list): <NEW_LINE> <INDENT> mock_get_list.return_value = self.mock_list <NEW_LINE> request = self.request_factory.get( '/lists/foolist.example.org/settings/') <NEW_LINE> request.user = AnonymousUser() <NEW_LINE> self.assertRaises(PermissionDenied, dummy_superuser_required, request) <NEW_LINE> <DEDENT> @patch.object(Client, 'get_list') <NEW_LINE> def test_normal_user(self, mock_get_list): <NEW_LINE> <INDENT> mock_get_list.return_value = self.mock_list <NEW_LINE> request = self.request_factory.get( '/lists/foolist.example.org/settings/') <NEW_LINE> request.user = create_user() <NEW_LINE> self.assertRaises(PermissionDenied, dummy_superuser_required, request) <NEW_LINE> <DEDENT> @patch.object(Client, 'get_list') <NEW_LINE> def test_super_user(self, mock_get_list): <NEW_LINE> <INDENT> mock_get_list.return_value = self.mock_list <NEW_LINE> request = self.request_factory.get( '/lists/foolist.example.org/settings/') <NEW_LINE> request.user = create_user() <NEW_LINE> request.user.is_superuser = True <NEW_LINE> request.user.save() <NEW_LINE> self.assertTrue(dummy_superuser_required(request)) | Tests superuser_required auth decorator | 625990721f037a2d8b9e54e1 |
class FrontEndTestCase(TestCase): <NEW_LINE> <INDENT> fixtures = ['myblog_test_fixture.json', ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.now = datetime.datetime.utcnow().replace(tzinfo=utc) <NEW_LINE> self.timedelta = datetime.timedelta(15) <NEW_LINE> author = User.objects.get(pk=1) <NEW_LINE> for count in range(1, 11): <NEW_LINE> <INDENT> post = Post(title="Post %d Title" % count, text="foo", author=author) <NEW_LINE> if count < 6: <NEW_LINE> <INDENT> pubdate = self.now - self.timedelta * count <NEW_LINE> post.published_date = pubdate <NEW_LINE> <DEDENT> post.save() <NEW_LINE> <DEDENT> <DEDENT> def test_list_only_published(self): <NEW_LINE> <INDENT> resp = self.client.get('/') <NEW_LINE> resp_text = resp.content.decode(resp.charset) <NEW_LINE> self.assertTrue("Recent Posts" in resp_text) <NEW_LINE> for count in range(1, 11): <NEW_LINE> <INDENT> title = "Post %d Title" % count <NEW_LINE> if count < 6: <NEW_LINE> <INDENT> self.assertContains(resp, title, count=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertNotContains(resp, title) | test views provided in the front-end | 6259907299cbb53fe68327d7 |
class GDetectorElement(object): <NEW_LINE> <INDENT> def __init__(self, description): <NEW_LINE> <INDENT> self.desc = description <NEW_LINE> self.circles = [] <NEW_LINE> self.boxes = [] <NEW_LINE> self.circles.append( TEllipse(0., 0., self.desc.volume.outer.rad, self.desc.volume.outer.rad) ) <NEW_LINE> dz = self.desc.volume.outer.z <NEW_LINE> radius = self.desc.volume.outer.rad <NEW_LINE> self.boxes.append( TBox(-dz, -radius, dz, radius) ) <NEW_LINE> if self.desc.volume.inner: <NEW_LINE> <INDENT> self.circles.append( TEllipse(0., 0., self.desc.volume.inner.rad, self.desc.volume.inner.rad)) <NEW_LINE> dz = self.desc.volume.inner.z <NEW_LINE> radius = self.desc.volume.inner.rad <NEW_LINE> self.boxes.append( TBox(-dz, -radius, dz, radius) ) <NEW_LINE> <DEDENT> color = COLORS[self.desc.material.name] <NEW_LINE> oc = self.circles[0] <NEW_LINE> ob = self.boxes[0] <NEW_LINE> for shape in [oc, ob]: <NEW_LINE> <INDENT> if color: <NEW_LINE> <INDENT> shape.SetFillColor(color) <NEW_LINE> shape.SetFillStyle(1001) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shape.SetFillStyle(0) <NEW_LINE> <DEDENT> shape.SetLineColor(1) <NEW_LINE> shape.SetLineStyle(1) <NEW_LINE> <DEDENT> if len(self.circles)==2: <NEW_LINE> <INDENT> ic = self.circles[1] <NEW_LINE> ib = self.boxes[1] <NEW_LINE> for shape in [ic, ib]: <NEW_LINE> <INDENT> if color: <NEW_LINE> <INDENT> shape.SetFillColor(0) <NEW_LINE> shape.SetFillStyle(1001) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shape.SetFillStyle(0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def draw(self, projection): <NEW_LINE> <INDENT> if projection == 'xy': <NEW_LINE> <INDENT> for circle in self.circles: <NEW_LINE> <INDENT> circle.Draw('same') <NEW_LINE> <DEDENT> <DEDENT> elif projection in ['xz', 'yz']: <NEW_LINE> <INDENT> for box in self.boxes: <NEW_LINE> <INDENT> box.Draw('samel') <NEW_LINE> <DEDENT> <DEDENT> elif 'thetaphi' in projection: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('implement drawing for projection ' + projection ) | TODO improve design?
there could be one detector element per view,
and they would all be linked together. | 6259907271ff763f4b5e9096 |
class ACStatus(object): <NEW_LINE> <INDENT> def __init__(self, ac, data): <NEW_LINE> <INDENT> self.ac = ac <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _str_to_num(s): <NEW_LINE> <INDENT> f = float(s) <NEW_LINE> if f == int(f): <NEW_LINE> <INDENT> return int(f) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def temp_cur_c(self): <NEW_LINE> <INDENT> return self._str_to_num(self.data['TempCur']) <NEW_LINE> <DEDENT> @property <NEW_LINE> def temp_cur_f(self): <NEW_LINE> <INDENT> return self.ac.c2f[self.temp_cur_c] <NEW_LINE> <DEDENT> @property <NEW_LINE> def temp_cfg_c(self): <NEW_LINE> <INDENT> return self._str_to_num(self.data['TempCfg']) <NEW_LINE> <DEDENT> @property <NEW_LINE> def temp_cfg_f(self): <NEW_LINE> <INDENT> return self.ac.c2f[self.temp_cfg_c] <NEW_LINE> <DEDENT> @property <NEW_LINE> def mode(self): <NEW_LINE> <INDENT> return ACMode(lookup_enum('OpMode', self.data, self.ac)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fan_speed(self): <NEW_LINE> <INDENT> return ACFanSpeed(lookup_enum('WindStrength', self.data, self.ac)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def horz_swing(self): <NEW_LINE> <INDENT> return ACHSwingMode(lookup_enum('WDirHStep', self.data, self.ac)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def vert_swing(self): <NEW_LINE> <INDENT> return ACVSwingMode(lookup_enum('WDirVStep', self.data, self.ac)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> op = ACOp(lookup_enum('Operation', self.data, self.ac)) <NEW_LINE> return op != ACOp.OFF | Higher-level information about an AC device's current status.
| 625990722ae34c7f260ac9d7 |
class lineTracker(Tracker): <NEW_LINE> <INDENT> def __init__(self,dotted=False,scolor=None,swidth=None,ontop=False): <NEW_LINE> <INDENT> line = coin.SoLineSet() <NEW_LINE> line.numVertices.setValue(2) <NEW_LINE> self.coords = coin.SoCoordinate3() <NEW_LINE> self.coords.point.setValues(0,2,[[0,0,0],[1,0,0]]) <NEW_LINE> Tracker.__init__(self,dotted,scolor,swidth,[self.coords,line],ontop,name="lineTracker") <NEW_LINE> <DEDENT> def p1(self,point=None): <NEW_LINE> <INDENT> if point: <NEW_LINE> <INDENT> self.coords.point.set1Value(0,point.x,point.y,point.z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Vector(self.coords.point.getValues()[0].getValue()) <NEW_LINE> <DEDENT> <DEDENT> def p2(self,point=None): <NEW_LINE> <INDENT> if point: <NEW_LINE> <INDENT> self.coords.point.set1Value(1,point.x,point.y,point.z) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Vector(self.coords.point.getValues()[-1].getValue()) <NEW_LINE> <DEDENT> <DEDENT> def getLength(self): <NEW_LINE> <INDENT> p1 = Vector(self.coords.point.getValues()[0].getValue()) <NEW_LINE> p2 = Vector(self.coords.point.getValues()[-1].getValue()) <NEW_LINE> return (p2.sub(p1)).Length | A Line tracker, used by the tools that need to draw temporary lines | 625990722c8b7c6e89bd50d5 |
class NgramFilter(Filter): <NEW_LINE> <INDENT> __inittypes__ = dict(minsize=int, maxsize=int) <NEW_LINE> def __init__(self, minsize, maxsize=None, at=None): <NEW_LINE> <INDENT> self.min = minsize <NEW_LINE> self.max = maxsize or minsize <NEW_LINE> self.at = 0 <NEW_LINE> if at == "start": <NEW_LINE> <INDENT> self.at = -1 <NEW_LINE> <DEDENT> elif at == "end": <NEW_LINE> <INDENT> self.at = 1 <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return other and self.__class__ is other.__class__ and self.min == other.min and self.max == other.max <NEW_LINE> <DEDENT> def __call__(self, tokens): <NEW_LINE> <INDENT> assert hasattr(tokens, "__iter__") <NEW_LINE> at = self.at <NEW_LINE> for t in tokens: <NEW_LINE> <INDENT> text = t.text <NEW_LINE> if len(text) < self.min: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> chars = t.chars <NEW_LINE> if chars: <NEW_LINE> <INDENT> startchar = t.startchar <NEW_LINE> <DEDENT> if t.mode == "query": <NEW_LINE> <INDENT> size = min(self.max, len(t.text)) <NEW_LINE> if at == -1: <NEW_LINE> <INDENT> t.text = text[:size] <NEW_LINE> if chars: <NEW_LINE> <INDENT> t.endchar = startchar + size <NEW_LINE> <DEDENT> yield t <NEW_LINE> <DEDENT> elif at == 1: <NEW_LINE> <INDENT> t.text = text[0 - size:] <NEW_LINE> if chars: <NEW_LINE> <INDENT> t.startchar = t.endchar - size <NEW_LINE> <DEDENT> yield t <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for start in xrange(0, len(text) - size + 1): <NEW_LINE> <INDENT> t.text = text[start:start + size] <NEW_LINE> if chars: <NEW_LINE> <INDENT> t.startchar = startchar + start <NEW_LINE> t.endchar = startchar + start + size <NEW_LINE> <DEDENT> yield t <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if at == -1: <NEW_LINE> <INDENT> limit = min(self.max, len(text)) <NEW_LINE> for size in xrange(self.min, limit + 1): <NEW_LINE> <INDENT> t.text = text[:size] <NEW_LINE> if chars: <NEW_LINE> <INDENT> t.endchar = startchar + size <NEW_LINE> <DEDENT> yield t <NEW_LINE> <DEDENT> <DEDENT> elif at == 1: <NEW_LINE> <INDENT> if chars: <NEW_LINE> <INDENT> original_startchar = t.startchar <NEW_LINE> <DEDENT> start = max(0, len(text) - self.max) <NEW_LINE> for i in xrange(start, len(text) - self.min + 1): <NEW_LINE> <INDENT> t.text = text[i:] <NEW_LINE> if chars: <NEW_LINE> <INDENT> t.startchar = original_startchar + i <NEW_LINE> <DEDENT> yield t <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for start in xrange(0, len(text) - self.min + 1): <NEW_LINE> <INDENT> for size in xrange(self.min, self.max + 1): <NEW_LINE> <INDENT> end = start + size <NEW_LINE> if end > len(text): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> t.text = text[start:end] <NEW_LINE> if chars: <NEW_LINE> <INDENT> t.startchar = startchar + start <NEW_LINE> t.endchar = startchar + end <NEW_LINE> <DEDENT> yield t | Splits token text into N-grams.
>>> rext = RegexTokenizer()
>>> stream = rext("hello there")
>>> ngf = NgramFilter(4)
>>> [token.text for token in ngf(stream)]
["hell", "ello", "ther", "here"] | 62599072a8370b77170f1cb8 |
class ProductionConfig(BaseConfig): <NEW_LINE> <INDENT> SECRET_KEY = 'prod' | Production configuration | 625990728e7ae83300eea97e |
class UnionAll(BinaryOperator): <NEW_LINE> <INDENT> def __init__(self, left=None, right=None): <NEW_LINE> <INDENT> BinaryOperator.__init__(self, left, right) <NEW_LINE> <DEDENT> def num_tuples(self): <NEW_LINE> <INDENT> return self.left.num_tuples() + self.right.num_tuples() <NEW_LINE> <DEDENT> def copy(self, other): <NEW_LINE> <INDENT> BinaryOperator.copy(self, other) <NEW_LINE> <DEDENT> def scheme(self): <NEW_LINE> <INDENT> return self.left.scheme() <NEW_LINE> <DEDENT> def shortStr(self): <NEW_LINE> <INDENT> return self.opname() | Bag union. | 62599072aad79263cf4300a4 |
class CallStaticMethod: <NEW_LINE> <INDENT> def __init__(self, classname: str, method: str, api: CLRApi = None): <NEW_LINE> <INDENT> self.classname = classname <NEW_LINE> self.method = method <NEW_LINE> self.api = api if api is not None else CLRApi.get() <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return self.api.call(self.classname, self.method, *args) | Static Method Call Stub | 6259907232920d7e50bc7935 |
@Callback.register("gradient-debug") <NEW_LINE> class GradDebug(Callback): <NEW_LINE> <INDENT> def __init__(self, stop_at: Optional[List[int]] = None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if stop_at is not None: <NEW_LINE> <INDENT> self.stop_at = stop_at <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stop_at = [] <NEW_LINE> <DEDENT> self._get_batch_num_total_this_epoch: Optional[[Callable[[], int] ]] = None <NEW_LINE> <DEDENT> @handle_event(Events.TRAINING_START) <NEW_LINE> def training_start(self, trainer: "CallbackTrainer") -> None: <NEW_LINE> <INDENT> torch.autograd.set_detect_anomaly(True) <NEW_LINE> self._get_batch_num_total_this_epoch = lambda: trainer.batches_this_epoch <NEW_LINE> <DEDENT> @handle_event(Events.BATCH_START, priority=200) <NEW_LINE> def batch_start(self, trainer: "CallbackTrainer") -> None: <NEW_LINE> <INDENT> batch_num = self._get_batch_num_total_this_epoch() <NEW_LINE> if batch_num in self.stop_at: <NEW_LINE> <INDENT> import pdb <NEW_LINE> pdb.set_trace() | Sets `torch.autograd.set_detect_anomaly` to true
at the start of training | 6259907244b2445a339b75d5 |
class Config: <NEW_LINE> <INDENT> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> SECRET_KEY = os.environ.get("SECRET_KEY") <NEW_LINE> UPLOADED_PHOTOS_DEST = 'app/static/photos' <NEW_LINE> AIL_SERVER = 'smtp.googlemail.com' <NEW_LINE> MAIL_PORT = 587 <NEW_LINE> MAIL_USE_TLS = False <NEW_LINE> MAIL_USE_SSL = True <NEW_LINE> MAIL_USERNAME = os.environ.get("MAIL_USERNAME") <NEW_LINE> MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD") <NEW_LINE> SUBJECT_PREFIX = 'Pizza' <NEW_LINE> SENDER_EMAIL = '[email protected]' <NEW_LINE> SIMPLEMDE_JS_IIFE = True <NEW_LINE> SIMPLEMDE_USE_CDN = True <NEW_LINE> @staticmethod <NEW_LINE> def init_app(app): <NEW_LINE> <INDENT> pass | Main configurations class | 62599072a17c0f6771d5d822 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.