code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class TestIoK8sApiCoreV1ConfigMap(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 testIoK8sApiCoreV1ConfigMap(self): <NEW_LINE> <INDENT> pass
IoK8sApiCoreV1ConfigMap unit test stubs
62598fbbaad79263cf42e965
class Webpage: <NEW_LINE> <INDENT> def __init__(self, name, url, title_tag, body_tag, next_tag): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.url = url <NEW_LINE> self.title_tag = title_tag <NEW_LINE> self.body_tag = body_tag <NEW_LINE> self.next_tag = next_tag <NEW_LINE> logging.info('Succesfully initialized site: {} - {}'.format(self.url, self.name))
Contains information about website structure
62598fbb956e5f7376df5746
class DbBarData(ModelBase): <NEW_LINE> <INDENT> id = AutoField() <NEW_LINE> symbol: str = CharField() <NEW_LINE> exchange: str = CharField() <NEW_LINE> datetime: datetime = DateTimeField() <NEW_LINE> interval: str = CharField() <NEW_LINE> volume: float = FloatField() <NEW_LINE> open_interest: float = FloatField() <NEW_LINE> open_price: float = FloatField() <NEW_LINE> high_price: float = FloatField() <NEW_LINE> low_price: float = FloatField() <NEW_LINE> close_price: float = FloatField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> database = db <NEW_LINE> indexes = ((("symbol", "exchange", "interval", "datetime"), True),) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_bar(bar: BarData): <NEW_LINE> <INDENT> db_bar = DbBarData() <NEW_LINE> db_bar.symbol = bar.symbol <NEW_LINE> db_bar.exchange = bar.exchange.value <NEW_LINE> db_bar.datetime = bar.datetime <NEW_LINE> db_bar.interval = bar.interval.value <NEW_LINE> db_bar.volume = bar.volume <NEW_LINE> db_bar.open_interest = bar.open_interest <NEW_LINE> db_bar.open_price = bar.open_price <NEW_LINE> db_bar.high_price = bar.high_price <NEW_LINE> db_bar.low_price = bar.low_price <NEW_LINE> db_bar.close_price = bar.close_price <NEW_LINE> return db_bar <NEW_LINE> <DEDENT> def to_bar(self): <NEW_LINE> <INDENT> bar = BarData( symbol=self.symbol, exchange=Exchange(self.exchange), datetime=self.datetime, interval=Interval(self.interval), volume=self.volume, open_price=self.open_price, high_price=self.high_price, open_interest=self.open_interest, low_price=self.low_price, close_price=self.close_price, gateway_name="DB", ) <NEW_LINE> return bar <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def save_all(objs: List["DbBarData"]): <NEW_LINE> <INDENT> dicts = [i.to_dict() for i in objs] <NEW_LINE> with db.atomic(): <NEW_LINE> <INDENT> if driver is Driver.POSTGRESQL: <NEW_LINE> <INDENT> for bar in dicts: <NEW_LINE> <INDENT> DbBarData.insert(bar).on_conflict( update=bar, conflict_target=( DbBarData.symbol, DbBarData.exchange, DbBarData.interval, DbBarData.datetime, ), ).execute() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for c in chunked(dicts, 50): <NEW_LINE> <INDENT> DbBarData.insert_many( c).on_conflict_replace().execute()
Candlestick bar data for database storage. Index is defined unique with datetime, interval, symbol
62598fbbadb09d7d5dc0a70d
class Agent(): <NEW_LINE> <INDENT> def __init__(self, action_space): <NEW_LINE> <INDENT> self.action_space = action_space <NEW_LINE> <DEDENT> def act(self, obs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def update(self, obs, actions, rewards, new_obs): <NEW_LINE> <INDENT> pass
Parent abstract Agent.
62598fbbe5267d203ee6ba91
class TransportFailedException(TransportException): <NEW_LINE> <INDENT> pass
The transport has failed to deliver the message due to an internal error; a new instance of the transport should be used to retry.
62598fbb283ffb24f3cf3a14
class ShortThrower(ThrowerAnt): <NEW_LINE> <INDENT> name = 'Short' <NEW_LINE> food_cost = 2 <NEW_LINE> min_range = 0 <NEW_LINE> max_range = 3 <NEW_LINE> def nearest_bee(self, hive): <NEW_LINE> <INDENT> current = self.place <NEW_LINE> transition = 0 <NEW_LINE> while current != hive and transition >= ShortThrower.min_range and transition <= ShortThrower.max_range : <NEW_LINE> <INDENT> if current.bees: <NEW_LINE> <INDENT> return random_or_none(current.bees) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current = current.entrance <NEW_LINE> transition += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> implemented = True
A ThrowerAnt that only throws leaves at Bees at most 3 places away.
62598fbb5fcc89381b266215
class TestWriteFiles(base.CloudTestCase): <NEW_LINE> <INDENT> def test_b64(self): <NEW_LINE> <INDENT> out = self.get_data_file('file_b64') <NEW_LINE> self.assertIn('ASCII text', out) <NEW_LINE> <DEDENT> def test_binary(self): <NEW_LINE> <INDENT> out = self.get_data_file('file_binary') <NEW_LINE> self.assertIn('ELF 64-bit LSB executable, x86-64, version 1', out) <NEW_LINE> <DEDENT> def test_gzip(self): <NEW_LINE> <INDENT> out = self.get_data_file('file_gzip') <NEW_LINE> self.assertIn('POSIX shell script, ASCII text executable', out) <NEW_LINE> <DEDENT> def test_text(self): <NEW_LINE> <INDENT> out = self.get_data_file('file_text') <NEW_LINE> self.assertIn('ASCII text', out)
Example cloud-config test
62598fbbdc8b845886d5374a
class Wiktionary(BaseCommand): <NEW_LINE> <INDENT> wikiName = "Wiktionary" <NEW_LINE> wikiUrl = "http://en.wiktionary.org" <NEW_LINE> wikiApi = "/w/api.php" <NEW_LINE> wikiBase = "/wiki" <NEW_LINE> maxMessageSize = 0 <NEW_LINE> level = AuthLevels.User <NEW_LINE> def __init__(self, bot, channel, user, args): <NEW_LINE> <INDENT> params = { 'query' : ''.join(args).lower(), 'name' : self.wikiName, 'url' : self.wikiUrl, 'api' : self.wikiApi, 'base' : self.wikiBase, 'maxsize' : self.maxMessageSize } <NEW_LINE> try: <NEW_LINE> <INDENT> wikiplugin = bot.plugins['reference.Wiki'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = wikiplugin.command(channel, user, params) <NEW_LINE> bot.replyout(channel, user, response)
English Wiktionary Lookup Command
62598fbb3d592f4c4edbb04f
class DescribeReplicationInstancesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RegistryId = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RegistryId = params.get("RegistryId") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit")
DescribeReplicationInstances请求参数结构体
62598fbb57b8e32f525081e5
class TravelTracker(App): <NEW_LINE> <INDENT> current_sort = StringProperty() <NEW_LINE> sorting_code = ListProperty() <NEW_LINE> def build(self): <NEW_LINE> <INDENT> self.title = "Travel Tracker" <NEW_LINE> self.root = Builder.load_file("travel_app.kv") <NEW_LINE> self.sorting_code = SORTING_DICT.keys() <NEW_LINE> self.root.ids.sorting_type.text = self.sorting_code[1] <NEW_LINE> print(self.root.ids.sorting_type.text) <NEW_LINE> return self.root <NEW_LINE> <DEDENT> def change_sorting(self, sorting_code): <NEW_LINE> <INDENT> self.root.ids.missing_id_name.text = SORTING_DICT[self.root.ids.sorting_type.text] <NEW_LINE> <DEDENT> def clear_place(self, instance): <NEW_LINE> <INDENT> self.root.ids.name_entry.text = "" <NEW_LINE> self.root.ids.country_entry.text = "" <NEW_LINE> self.root.ids.priority_entry .text = "" <NEW_LINE> <DEDENT> def create_widget(self): <NEW_LINE> <INDENT> self.place_collect = PlaceCollection() <NEW_LINE> self.place_collect.load_places(FILENAME) <NEW_LINE> for place in self.place_collect.places: <NEW_LINE> <INDENT> temp_button = Button(text=place, id=place) <NEW_LINE> temp_button.bind(on_release=self.create_widget()) <NEW_LINE> self.root.ids.entries_box.add_widget(temp_button) <NEW_LINE> <DEDENT> <DEDENT> def change_status(self): <NEW_LINE> <INDENT> self.root.ids.status_text.text = SORTING_DICT[self.sorting_code] <NEW_LINE> self.place_collection.sort(SORTING_DICT[self.sorting_code]) <NEW_LINE> <DEDENT> def save_list(self): <NEW_LINE> <INDENT> self.save_list(FILENAME)
Create the Travel Tracker class
62598fbb4428ac0f6e6586b5
class RecordParser(AbstractParser): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> import warnings <NEW_LINE> warnings.warn("Bio.Compass._RecordParser is deprecated; please use the read() and parse() functions in this module instead", Bio.BiopythonDeprecationWarning) <NEW_LINE> self._scanner = _Scanner() <NEW_LINE> self._consumer = _Consumer() <NEW_LINE> <DEDENT> def parse(self, handle): <NEW_LINE> <INDENT> if isinstance(handle, File.UndoHandle): <NEW_LINE> <INDENT> uhandle = handle <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> uhandle = File.UndoHandle(handle) <NEW_LINE> <DEDENT> self._scanner.feed(uhandle, self._consumer) <NEW_LINE> return self._consumer.data
Parses compass results into a Record object (DEPRECATED).
62598fbb099cdd3c636754ab
class Hocuspocus(): <NEW_LINE> <INDENT> key = Fernet.generate_key() <NEW_LINE> cipher_suite = Fernet(key) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> print(Hocuspocus.key) <NEW_LINE> <DEDENT> def hocus(*arg): <NEW_LINE> <INDENT> message_sombre = Hocuspocus.cipher_suite.encrypt(arg[0]) <NEW_LINE> return message_sombre <NEW_LINE> <DEDENT> def pocus(*arg): <NEW_LINE> <INDENT> message_claire = Hocuspocus.cipher_suite.decrypt(arg[0])
Class servant à encrypter et décrypter
62598fbb9c8ee8231304023d
class AmphoraConfigUpdate(BaseAmphoraTask): <NEW_LINE> <INDENT> def execute(self, amphora, flavor): <NEW_LINE> <INDENT> if flavor: <NEW_LINE> <INDENT> topology = flavor.get(constants.LOADBALANCER_TOPOLOGY, CONF.controller_worker.loadbalancer_topology) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> topology = CONF.controller_worker.loadbalancer_topology <NEW_LINE> <DEDENT> agent_cfg_tmpl = agent_jinja_cfg.AgentJinjaTemplater() <NEW_LINE> agent_config = agent_cfg_tmpl.build_agent_config( amphora.get(constants.ID), topology) <NEW_LINE> db_amp = self.amphora_repo.get(db_apis.get_session(), id=amphora[constants.ID]) <NEW_LINE> try: <NEW_LINE> <INDENT> self.amphora_driver.update_amphora_agent_config(db_amp, agent_config) <NEW_LINE> <DEDENT> except driver_except.AmpDriverNotImplementedError: <NEW_LINE> <INDENT> LOG.error('Amphora {} does not support agent configuration ' 'update. Please update the amphora image for this ' 'amphora. Skipping.'. format(amphora.get(constants.ID)))
Task to push a new amphora agent configuration to the amphora.
62598fbb851cf427c66b8448
class TextFileInputNode(Node, ProgrammingNodeTree): <NEW_LINE> <INDENT> bl_idname = "TextFileInputNode" <NEW_LINE> bl_label = "Text File Input" <NEW_LINE> bl_icon = "OBJECT_DATA" <NEW_LINE> def uda(self, context): <NEW_LINE> <INDENT> self.update() <NEW_LINE> <DEDENT> tfile = PointerProperty(type=Text, name="tfile", update=uda) <NEW_LINE> def init(self, context): <NEW_LINE> <INDENT> self.outputs.new("StringSocket", "String").callback() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.tfile is not None: <NEW_LINE> <INDENT> update_value(self, "String", self.tfile.as_string()) <NEW_LINE> <DEDENT> <DEDENT> def copy(self, node): <NEW_LINE> <INDENT> print("Copying from node ", node) <NEW_LINE> for inp in self.inputs: <NEW_LINE> <INDENT> if hasattr(inp, "callback"): <NEW_LINE> <INDENT> inp.callback() <NEW_LINE> <DEDENT> <DEDENT> for outp in self.outputs: <NEW_LINE> <INDENT> if hasattr(outp, "callback"): <NEW_LINE> <INDENT> outp.callback() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def free(self): <NEW_LINE> <INDENT> print("Removing node ", self, ", Goodbye!") <NEW_LINE> <DEDENT> def draw_buttons(self, context, layout): <NEW_LINE> <INDENT> layout.template_ID(self, "tfile", new="text.new", unlink="text.unlink", open="text.open") <NEW_LINE> <DEDENT> def draw_label(self): <NEW_LINE> <INDENT> return "Text File Input"
Text File Input Node
62598fbb92d797404e388c2c
class SimpleUDPListener(Actor): <NEW_LINE> <INDENT> @manage(['host', 'port']) <NEW_LINE> def init(self, address): <NEW_LINE> <INDENT> self.host, self.port = address.split(':') <NEW_LINE> try: <NEW_LINE> <INDENT> self.port = int(self.port) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.port = 0 <NEW_LINE> <DEDENT> self.setup() <NEW_LINE> <DEDENT> def did_migrate(self): <NEW_LINE> <INDENT> self.setup() <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.use('calvinsys.network.serverhandler', shorthand='server') <NEW_LINE> self.listener = self['server'].start(self.host, self.port, "udp") <NEW_LINE> <DEDENT> @stateguard(lambda self: self.listener and self.listener.have_data()) <NEW_LINE> @condition(action_output=['data']) <NEW_LINE> def receive(self): <NEW_LINE> <INDENT> message = self.listener.data_get() <NEW_LINE> return (message["data"],) <NEW_LINE> <DEDENT> action_priority = (receive,) <NEW_LINE> requires = ['calvinsys.network.serverhandler']
Listen for UDP messages on a given port. Address is of the form "ip:port" (note: ip is ipv4) Output: data : data in packets received on the UDP port will forwarded as tokens.
62598fbbfff4ab517ebcd976
class SplitDateTime(DateTime): <NEW_LINE> <INDENT> def __init__(self, date, time, *args, **kwargs): <NEW_LINE> <INDENT> super(DateTime, self).__init__(*args, **kwargs) <NEW_LINE> self.date = date <NEW_LINE> self.time = time <NEW_LINE> <DEDENT> def output(self, key, obj): <NEW_LINE> <INDENT> date = fields.get_value(self.date, obj) if self.date else None <NEW_LINE> time = fields.get_value(self.time, obj) <NEW_LINE> if time == __date_time_null_value__: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> if not date: <NEW_LINE> <INDENT> return self.format_time(time) <NEW_LINE> <DEDENT> date_time = date + time <NEW_LINE> tz = get_timezone() <NEW_LINE> return self.format(date_time, timezone=tz) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def format_time(time): <NEW_LINE> <INDENT> t = datetime.datetime.utcfromtimestamp(time) <NEW_LINE> return t.strftime("%H%M%S")
custom date format from 2 fields: - one for the date (in timestamp to midnight) - one for the time in seconds from midnight the date can be null (for example when the time is for a period like for calendar schedule) if the date is not null be convert to local using the default timezone if the date is null, we do not convert anything. Thus the given date HAS to be previously converted to local if that is what is wanted
62598fbbaad79263cf42e967
class Operator(object): <NEW_LINE> <INDENT> def __init__(self, tag=None): <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<%s%s at 0x%x>" % ( type(self).__name__, self._tagstr(), id(self)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> strs = (s for s in (self._descstr(), self._tagstr()) if s) <NEW_LINE> return "%s{%s}" % (type(self).__name__, ' '.join(strs)) <NEW_LINE> <DEDENT> def _descstr(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def _tagstr(self): <NEW_LINE> <INDENT> return (' "%s"' % self.tag) if self.tag is not None else '' <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_signals(self): <NEW_LINE> <INDENT> return self._all_signals <NEW_LINE> <DEDENT> def _update_all_signals(self): <NEW_LINE> <INDENT> if all(hasattr(self, x) for x in ('reads', 'sets', 'incs', 'updates')): <NEW_LINE> <INDENT> self._all_signals = ( self.reads + self.sets + self.incs + self.updates) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def incs(self): <NEW_LINE> <INDENT> return self._incs <NEW_LINE> <DEDENT> @incs.setter <NEW_LINE> def incs(self, val): <NEW_LINE> <INDENT> self._incs = val <NEW_LINE> self._update_all_signals() <NEW_LINE> <DEDENT> @property <NEW_LINE> def reads(self): <NEW_LINE> <INDENT> return self._reads <NEW_LINE> <DEDENT> @reads.setter <NEW_LINE> def reads(self, val): <NEW_LINE> <INDENT> self._reads = val <NEW_LINE> self._update_all_signals() <NEW_LINE> <DEDENT> @property <NEW_LINE> def sets(self): <NEW_LINE> <INDENT> return self._sets <NEW_LINE> <DEDENT> @sets.setter <NEW_LINE> def sets(self, val): <NEW_LINE> <INDENT> self._sets = val <NEW_LINE> self._update_all_signals() <NEW_LINE> <DEDENT> @property <NEW_LINE> def updates(self): <NEW_LINE> <INDENT> return self._updates <NEW_LINE> <DEDENT> @updates.setter <NEW_LINE> def updates(self, val): <NEW_LINE> <INDENT> self._updates = val <NEW_LINE> self._update_all_signals() <NEW_LINE> <DEDENT> def init_signals(self, signals): <NEW_LINE> <INDENT> for sig in self.all_signals: <NEW_LINE> <INDENT> if sig not in signals: <NEW_LINE> <INDENT> signals.init(sig) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def make_step(self, signals, dt, rng): <NEW_LINE> <INDENT> raise NotImplementedError("subclasses must implement this method.")
Base class for operator instances understood by Nengo. During one simulator timestep, a `.Signal` can experience 1. at most one set operator (optional) 2. any number of increments 3. any number of reads 4. at most one update in this specific order. A ``set`` defines the state of the signal at time :math:`t`, the start of the simulation timestep. That state can then be modified by ``increment`` operations. A signal's state will only be ``read`` after all increments are complete. The state is then finalized by an ``update``, which denotes the state that the signal should be at time :math:`t + dt`. Each operator must keep track of the signals that it manipulates, and which of these four types of manipulations is done to each signal so that the simulator can order all of the operators properly. .. note:: There are intentionally no default values for the `~.Operator.reads`, `~.Operator.sets`, `~.Operator.incs`, and `~.Operator.updates` properties to ensure that subclasses explicitly set these values. Parameters ---------- tag : str, optional (Default: None) A label associated with the operator, for debugging purposes. Attributes ---------- tag : str or None A label associated with the operator, for debugging purposes.
62598fbb3346ee7daa337711
class RecipientYear(models.Model): <NEW_LINE> <INDENT> recipient = models.ForeignKey('Recipient', db_index=True) <NEW_LINE> name = models.TextField(null=True) <NEW_LINE> year = models.IntegerField(blank=True, null=True) <NEW_LINE> country = models.CharField(blank=True, max_length=2) <NEW_LINE> total = models.FloatField(default=0.0, null=True, db_index=True) <NEW_LINE> objects = RecipientYearManager() <NEW_LINE> class Meta(): <NEW_LINE> <INDENT> ordering = ('-total',) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('recipient_view', args=[self.country, self.recipient_id, slugify(self.name)])
Denormalized model containing the total each recipient received per year.
62598fbb167d2b6e312b7108
class FileHistory(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._history_file_name = 'file.history' <NEW_LINE> self._history_file_path = '' <NEW_LINE> if os.name == 'nt': <NEW_LINE> <INDENT> self._history_file_path = os.path.dirname(os.getenv('POSE')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._history_file_path = os.getenv('HIH') <NEW_LINE> <DEDENT> self._history_file_full_path = os.path.join( self._history_file_path, self._history_file_name ) <NEW_LINE> self._buffer = [] <NEW_LINE> self._history = dict() <NEW_LINE> self._read() <NEW_LINE> self._parse() <NEW_LINE> <DEDENT> def _read(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> history_file = open(self._history_file_full_path) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> self._buffer = [] <NEW_LINE> return <NEW_LINE> <DEDENT> self._buffer = history_file.readlines() <NEW_LINE> self._buffer = [line.strip() for line in self._buffer] <NEW_LINE> history_file.close() <NEW_LINE> <DEDENT> def _parse(self): <NEW_LINE> <INDENT> self._history = dict() <NEW_LINE> buffer_list = self._buffer <NEW_LINE> key_name = '' <NEW_LINE> path_list = [] <NEW_LINE> len_buffer = len(buffer_list) <NEW_LINE> for i in range(len_buffer): <NEW_LINE> <INDENT> if buffer_list[i] == '{': <NEW_LINE> <INDENT> key_name = buffer_list[i - 1] <NEW_LINE> path_list = [] <NEW_LINE> for j in range(i + 1, len_buffer): <NEW_LINE> <INDENT> current_element = buffer_list[j] <NEW_LINE> if current_element != '}': <NEW_LINE> <INDENT> path_list.append(current_element) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = j + 1 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self._history[key_name] = path_list <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_recent_files(self, type_name=''): <NEW_LINE> <INDENT> if type_name == '' or type_name is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._history.get(type_name, [])
A Houdini recent file history parser Holds the data in a dictionary, where the keys are the file types and the values are string list of recent file paths of that type
62598fbb236d856c2adc9509
class AzureBlob(StorageManager): <NEW_LINE> <INDENT> _BLOB_FILE = ("https://%(storage)s.blob.core.windows.net/" "%(container)s/%(blob)s") <NEW_LINE> _REMOTE_FILE = collections.namedtuple( "RemoteFile", ["store", "storage", "container", "blob"]) <NEW_LINE> _URL_FORMAT = re.compile(r'http.*\/\/(?P<storage>[^.]+)[^/]+\/' r'(?P<container>[^/]+)\/*(?P<blob>[^/]*)') <NEW_LINE> _BLOB_CHUNK_DATA_SIZE = 4 * 1024 * 1024 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(AzureBlob, self).__init__() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def check_resource(cls, resource): <NEW_LINE> <INDENT> return cls._URL_FORMAT.match(resource or "") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse_remote(cls, filename): <NEW_LINE> <INDENT> blob_file = cls._URL_FORMAT.search(filename) <NEW_LINE> return cls._REMOTE_FILE("blob", storage=blob_file.group("storage"), container=blob_file.group("container"), blob=blob_file.group("blob")) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def connect(cls, resource): <NEW_LINE> <INDENT> file_info = cls.parse_remote(resource) <NEW_LINE> return azure_storage.BlobService(file_info.storage) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def download(cls, filename, input_dir, dl_dir=None): <NEW_LINE> <INDENT> file_info = cls.parse_remote(filename) <NEW_LINE> if not dl_dir: <NEW_LINE> <INDENT> dl_dir = os.path.join(input_dir, file_info.container, os.path.dirname(file_info.storage)) <NEW_LINE> utils.safe_makedir(dl_dir) <NEW_LINE> <DEDENT> out_file = os.path.join(dl_dir, os.path.basename(file_info.storage)) <NEW_LINE> if not utils.file_exists(out_file): <NEW_LINE> <INDENT> with file_transaction({}, out_file) as tx_out_file: <NEW_LINE> <INDENT> blob_service = cls.connect(filename) <NEW_LINE> blob_service.get_blob_to_path( container_name=file_info.container, blob_name=file_info.blob, file_path=tx_out_file) <NEW_LINE> <DEDENT> <DEDENT> return out_file <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def list(cls, path): <NEW_LINE> <INDENT> output = [] <NEW_LINE> path_info = cls.parse_remote(path) <NEW_LINE> blob_service = azure_storage.BlobService(path_info.storage) <NEW_LINE> try: <NEW_LINE> <INDENT> blob_enum = blob_service.list_blobs(path_info.container) <NEW_LINE> <DEDENT> except azure.WindowsAzureMissingResourceError: <NEW_LINE> <INDENT> return output <NEW_LINE> <DEDENT> for item in blob_enum: <NEW_LINE> <INDENT> output.append(cls._BLOB_FILE.format(storage=path_info.storage, container=path_info.container, blob=item.name)) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def open(cls, filename): <NEW_LINE> <INDENT> file_info = cls.parse_remote(filename) <NEW_LINE> blob_service = cls.connect(filename) <NEW_LINE> return BlobHandle(blob_service=blob_service, container=file_info.container, blob=file_info.blob, chunk_size=cls._BLOB_CHUNK_DATA_SIZE)
Azure Blob storage service manager.
62598fbbd486a94d0ba2c161
class CaptureImage(object): <NEW_LINE> <INDENT> def __init__(self, Type, *args): <NEW_LINE> <INDENT> self.bitmap = win32ui.CreateBitmap() <NEW_LINE> {'Window': self.extract_window, 'DC': self.build_from_dc}[Type](*args) <NEW_LINE> <DEDENT> def extract_window(self, windowName): <NEW_LINE> <INDENT> Handle = identify_window(windowName) <NEW_LINE> Width, Height= dimension_window(*win32gui.GetWindowRect(Handle)) <NEW_LINE> dcHandle = win32gui.GetWindowDC(Handle) <NEW_LINE> DC = win32ui.CreateDCFromHandle(dcHandle) <NEW_LINE> self.build_from_dc(DC, Width, Height) <NEW_LINE> <DEDENT> def build_from_dc(self, DC, Width, Height): <NEW_LINE> <INDENT> self.dimensions = DIMENSIONS(Width, Height) <NEW_LINE> self.connect_dc(DC, Width, Height) <NEW_LINE> self.update_from_dc(DC, Width, Height) <NEW_LINE> <DEDENT> def connect_dc(self, DC, Width, Height): <NEW_LINE> <INDENT> self.context = DC.CreateCompatibleDC() <NEW_LINE> self.bitmap.CreateCompatibleBitmap(DC, Width, Height) <NEW_LINE> self.context.SelectObject(self.bitmap) <NEW_LINE> <DEDENT> def update_from_dc(self, DC, Width, Height): <NEW_LINE> <INDENT> self.context.BitBlt((0,0), (Width, Height), DC, (0,0), 13369376) <NEW_LINE> <DEDENT> @property <NEW_LINE> def raw_data(self): <NEW_LINE> <INDENT> return self.bitmap.GetBitmapBits() <NEW_LINE> <DEDENT> def save(self, filePathname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.bitmap.SaveBitmapFile(self.context, filePathname) <NEW_LINE> <DEDENT> except win32ui.error: <NEW_LINE> <INDENT> errorMsg = 'No such file or directory: {}'.format(filePathname) <NEW_LINE> raise FileNotFoundError(errorMsg) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, indexPair): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> intRGB = self.context.GetPixel(*indexPair) <NEW_LINE> <DEDENT> except win32ui.error: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> return convert_integer_rgb(intRGB) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> bgrxColors = [iter(self.bitmap.GetBitmapBits())] * 4 <NEW_LINE> rgbColors = (PIXEL(R, G, B) for B, G, R, _ in zip(*bgrxColors)) <NEW_LINE> Rows = [rgbColors] * self.dimensions.width <NEW_LINE> return zip(*Rows) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}'.format(self.__class__.__name__)
Returns object to retain, manage and preform screen captures.
62598fbb091ae35668704db5
class _ColorFormatter(Formatter): <NEW_LINE> <INDENT> colors = set(colors) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(_ColorFormatter, self).__init__() <NEW_LINE> self._depth = len(inspect.stack()) <NEW_LINE> <DEDENT> def get_value(self, key, args, kwargs): <NEW_LINE> <INDENT> if key == 'color' and kwargs.get('color') in self.colors: <NEW_LINE> <INDENT> return '\03{{{0}}}'.format(kwargs[key]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(_ColorFormatter, self).get_value(key, args, kwargs) <NEW_LINE> <DEDENT> <DEDENT> def parse(self, format_string): <NEW_LINE> <INDENT> previous_literal = '' <NEW_LINE> for literal, field, spec, conv in super(_ColorFormatter, self).parse( format_string): <NEW_LINE> <INDENT> if field in self.colors: <NEW_LINE> <INDENT> if spec: <NEW_LINE> <INDENT> raise ValueError( 'Color field "{0}" in "{1}" uses format spec ' 'information "{2}"'.format(field, format_string, spec)) <NEW_LINE> <DEDENT> elif conv: <NEW_LINE> <INDENT> raise ValueError( 'Color field "{0}" in "{1}" uses conversion ' 'information "{2}"'.format(field, format_string, conv)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not literal or literal[-1] != '\03': <NEW_LINE> <INDENT> literal += '\03' <NEW_LINE> <DEDENT> if '\03' in literal[:-1]: <NEW_LINE> <INDENT> raise ValueError(r'Literal text in {0} contains ' r'\03'.format(format_string)) <NEW_LINE> <DEDENT> previous_literal += literal + '{' + field + '}' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if '\03' in literal: <NEW_LINE> <INDENT> raise ValueError(r'Literal text in {0} contains ' r'\03'.format(format_string)) <NEW_LINE> <DEDENT> yield previous_literal + literal, field, spec, conv <NEW_LINE> previous_literal = '' <NEW_LINE> <DEDENT> <DEDENT> if previous_literal: <NEW_LINE> <INDENT> yield previous_literal, None, None, None <NEW_LINE> <DEDENT> <DEDENT> def _vformat(self, *args, **kwargs): <NEW_LINE> <INDENT> result = super(_ColorFormatter, self)._vformat(*args, **kwargs) <NEW_LINE> if isinstance(result, tuple): <NEW_LINE> <INDENT> additional_params = result[1:] <NEW_LINE> result = result[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> additional_params = tuple() <NEW_LINE> <DEDENT> result = self._convert_bytes(result) <NEW_LINE> if additional_params: <NEW_LINE> <INDENT> result = (result, ) + additional_params <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def _convert_bytes(self, result): <NEW_LINE> <INDENT> if PY2 and isinstance(result, str): <NEW_LINE> <INDENT> assert result == b'' <NEW_LINE> result = '' <NEW_LINE> <DEDENT> elif not isinstance(result, UnicodeType): <NEW_LINE> <INDENT> result = UnicodeType(result) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def vformat(self, format_string, args, kwargs): <NEW_LINE> <INDENT> if self.colors.intersection(kwargs): <NEW_LINE> <INDENT> raise ValueError('Keyword argument(s) use valid color(s): ' + '", "'.join(self.colors.intersection(kwargs))) <NEW_LINE> <DEDENT> if not isinstance(format_string, UnicodeType): <NEW_LINE> <INDENT> raise TypeError('expected str, got {0}'.format(type(format_string))) <NEW_LINE> <DEDENT> return super(_ColorFormatter, self).vformat(format_string, args, kwargs)
Special string formatter which skips colors.
62598fbb2c8b7c6e89bd3959
class CarboxamideNToTyrOH(HydrogenBond): <NEW_LINE> <INDENT> def __init__(self, model, rcutoff=3.2, *args, **kwds): <NEW_LINE> <INDENT> HydrogenBond.__init__(self, model, *args, **kwds) <NEW_LINE> listik1 = model.atom_lister('rat', rats=['GLNNE2', 'ASNND2']) <NEW_LINE> listik2 = model.atom_lister('rat', rats=['TYROH']) <NEW_LINE> self.store_lists(listik1, listik2, self.__class__.__name__, rcutoff=rcutoff, sameres=True) <NEW_LINE> <DEDENT> def get_namegh(self, namei): <NEW_LINE> <INDENT> return get_nqn_names(namei) <NEW_LINE> <DEDENT> def get_namekl(self, namej): <NEW_LINE> <INDENT> return get_tyr_names(namej)
Asn/Gln carboxamide nitrogen (donor) to Tyr hydroxyl oxygen (acceptor)
62598fbb4f88993c371f05d6
class TagKeysClientMeta(type): <NEW_LINE> <INDENT> _transport_registry = OrderedDict() <NEW_LINE> _transport_registry["grpc"] = TagKeysGrpcTransport <NEW_LINE> _transport_registry["grpc_asyncio"] = TagKeysGrpcAsyncIOTransport <NEW_LINE> def get_transport_class( cls, label: str = None, ) -> Type[TagKeysTransport]: <NEW_LINE> <INDENT> if label: <NEW_LINE> <INDENT> return cls._transport_registry[label] <NEW_LINE> <DEDENT> return next(iter(cls._transport_registry.values()))
Metaclass for the TagKeys client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects.
62598fbb627d3e7fe0e07045
class UserProfileSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.UserProfile <NEW_LINE> fields = ('id', 'name', 'email', 'password') <NEW_LINE> extra_kwargs = { 'password': { 'write_only': True, 'style': { 'input_type': 'password' } } } <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'] ) <NEW_LINE> return user <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> if 'password' in validated_data: <NEW_LINE> <INDENT> password = validated_data.pop('password') <NEW_LINE> instance.set_password(password) <NEW_LINE> <DEDENT> return super().update(instance, validated_data)
Serializers a user profile object
62598fbbad47b63b2c5a79e7
class MinioException(Exception): <NEW_LINE> <INDENT> pass
Base Minio exception.
62598fbb60cbc95b063644d2
class NullNode(SceneNode): <NEW_LINE> <INDENT> _enabled = False <NEW_LINE> def __bool__(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def draw_idle(self): <NEW_LINE> <INDENT> pass
Non-existent node.
62598fbb21bff66bcd722dfd
class NonRecoverableError(CustodianError): <NEW_LINE> <INDENT> def __init__(self, message, raises, handler): <NEW_LINE> <INDENT> super().__init__(message, raises) <NEW_LINE> self.handler = handler
Error raised when a handler found an error but could not fix it
62598fbb796e427e5384e929
class ComplexVote(Vote): <NEW_LINE> <INDENT> __mapper_args__ = {'polymorphic_identity': 'complex'} <NEW_LINE> @property <NEW_LINE> def polymorphic_base(self): <NEW_LINE> <INDENT> return Vote <NEW_LINE> <DEDENT> @property <NEW_LINE> def proposal(self): <NEW_LINE> <INDENT> return self.ballot('proposal', create=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def counter_proposal(self): <NEW_LINE> <INDENT> return self.ballot('counter-proposal', create=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tie_breaker(self): <NEW_LINE> <INDENT> return self.ballot('tie-breaker', create=True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_answer(counted, proposal, counter_proposal, tie_breaker): <NEW_LINE> <INDENT> if not (counted and proposal and counter_proposal and tie_breaker): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if proposal.accepted and counter_proposal.accepted: <NEW_LINE> <INDENT> if tie_breaker.accepted: <NEW_LINE> <INDENT> return 'proposal' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'counter-proposal' <NEW_LINE> <DEDENT> <DEDENT> elif proposal.accepted: <NEW_LINE> <INDENT> return 'proposal' <NEW_LINE> <DEDENT> elif counter_proposal.accepted: <NEW_LINE> <INDENT> return 'counter-proposal' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'rejected' <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def answer(self): <NEW_LINE> <INDENT> return self.get_answer( self.counted, self.proposal, self.counter_proposal, self.tie_breaker ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def yeas_percentage(self): <NEW_LINE> <INDENT> if self.answer in ('proposal', 'rejected'): <NEW_LINE> <INDENT> subject = self.proposal <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subject = self.counter_proposal <NEW_LINE> <DEDENT> return subject.yeas / ((subject.yeas + subject.nays) or 1) * 100
A complex vote with proposal, counter-proposal and tie-breaker.
62598fbb3539df3088ecc440
class CmdSocedit(Commande): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Commande.__init__(self, "socedit", "socedit") <NEW_LINE> self.groupe = "administrateur" <NEW_LINE> self.schema = "<ident>" <NEW_LINE> self.nom_categorie = "batisseur" <NEW_LINE> self.aide_courte = "ouvre l'éditeur d'attitude" <NEW_LINE> self.aide_longue = "Cette commande permet d'accéder à l'éditeur d'attitude. Elle " "prend en paramètre l'identifiant de l'attitude (que des " "minuscules, des chiffres et le signe |ent|_|ff|). Si l'attitude " "n'existe pas, elle est créée." <NEW_LINE> <DEDENT> def interpreter(self, personnage, dic_masques): <NEW_LINE> <INDENT> cle = dic_masques["ident"].ident <NEW_LINE> attitude = type(self).importeur.communication.attitudes. ajouter_ou_modifier(cle) <NEW_LINE> editeur = type(self).importeur.interpreteur.construire_editeur( "socedit", personnage, attitude) <NEW_LINE> personnage.contextes.ajouter(editeur) <NEW_LINE> editeur.actualiser()
Commande 'socedit'
62598fbbd268445f26639c4e
class AsyncAND(defer.Deferred): <NEW_LINE> <INDENT> def __init__(self, deferredList): <NEW_LINE> <INDENT> defer.Deferred.__init__(self) <NEW_LINE> if not deferredList: <NEW_LINE> <INDENT> self.callback(None) <NEW_LINE> return <NEW_LINE> <DEDENT> self.remaining = len(deferredList) <NEW_LINE> self._fired = False <NEW_LINE> for d in deferredList: <NEW_LINE> <INDENT> d.addCallbacks(self._cbDeferred, self._cbDeferred, callbackArgs=(True,), errbackArgs=(False,)) <NEW_LINE> <DEDENT> <DEDENT> def _cbDeferred(self, result, succeeded): <NEW_LINE> <INDENT> self.remaining -= 1 <NEW_LINE> if succeeded: <NEW_LINE> <INDENT> if not self._fired and self.remaining == 0: <NEW_LINE> <INDENT> self._fired = True <NEW_LINE> self.callback(None) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not self._fired: <NEW_LINE> <INDENT> self._fired = True <NEW_LINE> self.errback(result) <NEW_LINE> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result
Like DeferredList, but results are discarded and failures handled in a more convenient fashion. Create me with a list of Deferreds. I will fire my callback (with None) if and when all of my component Deferreds fire successfully. I will fire my errback when and if any of my component Deferreds errbacks, in which case I will absorb the failure. If a second Deferred errbacks, I will not absorb that failure. This means that you can put a bunch of Deferreds together into an AsyncAND and then forget about them. If all succeed, the AsyncAND will fire. If one fails, that Failure will be propagated to the AsyncAND. If multiple ones fail, the first Failure will go to the AsyncAND and the rest will be left unhandled (and therefore logged).
62598fbb4428ac0f6e6586b7
class Agent(object): <NEW_LINE> <INDENT> configuration: Configuration <NEW_LINE> decorators: List[Decorator] <NEW_LINE> def __init__(self, configuration: Configuration, decorators: List[Decorator] = None): <NEW_LINE> <INDENT> self.configuration = configuration <NEW_LINE> if decorators is None: <NEW_LINE> <INDENT> decorators = [] <NEW_LINE> <DEDENT> self.decorators = decorators <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self.configuration.evaluate() <NEW_LINE> self.configuration.if_trigger_update() <NEW_LINE> for decorator in self.decorators: <NEW_LINE> <INDENT> decorator.execute(self.configuration)
Monitor agent that will be constantly verifying if the URL is healthy and updating the component.
62598fbbcc40096d6161a2a3
class Run(webapp2.RequestHandler): <NEW_LINE> <INDENT> def post(self, job_id): <NEW_LINE> <INDENT> job = job_module.JobFromId(job_id) <NEW_LINE> try: <NEW_LINE> <INDENT> job.Run() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> job.put()
Handler that runs a Pinpoint job.
62598fbb7b180e01f3e49119
class CfsInsInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.UserId = None <NEW_LINE> self.UserGroupId = None <NEW_LINE> self.CfsId = None <NEW_LINE> self.MountInsId = None <NEW_LINE> self.LocalMountDir = None <NEW_LINE> self.RemoteMountDir = None <NEW_LINE> self.IpAddress = None <NEW_LINE> self.MountVpcId = None <NEW_LINE> self.MountSubnetId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.UserId = params.get("UserId") <NEW_LINE> self.UserGroupId = params.get("UserGroupId") <NEW_LINE> self.CfsId = params.get("CfsId") <NEW_LINE> self.MountInsId = params.get("MountInsId") <NEW_LINE> self.LocalMountDir = params.get("LocalMountDir") <NEW_LINE> self.RemoteMountDir = params.get("RemoteMountDir") <NEW_LINE> self.IpAddress = params.get("IpAddress") <NEW_LINE> self.MountVpcId = params.get("MountVpcId") <NEW_LINE> self.MountSubnetId = params.get("MountSubnetId")
Configuration information of the CFS instance associated with function
62598fbb498bea3a75a57cb8
class MeasureAreaController(AnalysisControllerBase): <NEW_LINE> <INDENT> def __init__(self, giface, mapWindow): <NEW_LINE> <INDENT> AnalysisControllerBase.__init__( self, giface=giface, mapWindow=mapWindow) <NEW_LINE> self._graphicsType = 'polygon' <NEW_LINE> <DEDENT> def _doAnalysis(self, coords): <NEW_LINE> <INDENT> self.MeasureArea(coords) <NEW_LINE> <DEDENT> def _disconnectAll(self): <NEW_LINE> <INDENT> self._mapWindow.mouseLeftDown.disconnect(self._start) <NEW_LINE> self._mapWindow.mouseLeftUp.disconnect(self._addPoint) <NEW_LINE> self._mapWindow.mouseDClick.disconnect(self.Stop) <NEW_LINE> <DEDENT> def _connectAll(self): <NEW_LINE> <INDENT> self._mapWindow.mouseLeftDown.connect(self._start) <NEW_LINE> self._mapWindow.mouseLeftUp.connect(self._addPoint) <NEW_LINE> self._mapWindow.mouseDClick.connect(self.Stop) <NEW_LINE> <DEDENT> def _getPen(self): <NEW_LINE> <INDENT> return wx.Pen(colour='green', width=2, style=wx.SOLID) <NEW_LINE> <DEDENT> def Stop(self, restore=True): <NEW_LINE> <INDENT> if not self.IsActive(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> AnalysisControllerBase.Stop(self, restore=restore) <NEW_LINE> self._giface.WriteCmdLog(_('Measuring finished')) <NEW_LINE> <DEDENT> def Start(self): <NEW_LINE> <INDENT> if self.IsActive(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> AnalysisControllerBase.Start(self) <NEW_LINE> self._giface.WriteWarning( _( 'Click and drag with left mouse button ' 'to measure.%s' 'Double click with left button to clear.') % (os.linesep)) <NEW_LINE> self._giface.WriteCmdLog(_('Measuring area:')) <NEW_LINE> <DEDENT> def MeasureArea(self, coords): <NEW_LINE> <INDENT> coordinates = coords + [coords[0]] <NEW_LINE> coordinates = ','.join([str(item) for sublist in coordinates for item in sublist]) <NEW_LINE> result = RunCommand( 'm.measure', flags='g', coordinates=coordinates, read=True).strip() <NEW_LINE> result = parse_key_val(result) <NEW_LINE> if 'units' not in result: <NEW_LINE> <INDENT> self._giface.WriteWarning( _("Units not recognized, measurement failed.")) <NEW_LINE> unit = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unit = result['units'].split(',')[1] <NEW_LINE> <DEDENT> if 'area' not in result: <NEW_LINE> <INDENT> text = _("Area: {area} {unit}\n").format(area=0, unit=unit) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = _("Area: {area} {unit}\n").format( area=result['area'], unit=unit) <NEW_LINE> <DEDENT> self._giface.WriteLog(text, notification=Notification.MAKE_VISIBLE)
Class controls measuring area in map display.
62598fbb44b2445a339b6a3f
class ThresholdedReLU(layers.Layer): <NEW_LINE> <INDENT> def __init__(self, threshold=1.0, name=None): <NEW_LINE> <INDENT> super(ThresholdedReLU, self).__init__() <NEW_LINE> self._threshold = threshold <NEW_LINE> self._name = name <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return F.thresholded_relu(x, self._threshold, self._name) <NEW_LINE> <DEDENT> def extra_repr(self): <NEW_LINE> <INDENT> name_str = ', name={}'.format(self._name) if self._name else '' <NEW_LINE> return 'threshold={}{}'.format(self._threshold, name_str)
Thresholded ReLU Activation .. math:: ThresholdedReLU(x) = \\begin{cases} x, \\text{if } x > threshold \\\\ 0, \\text{otherwise} \\end{cases} Parameters: threshold (float, optional): The value of threshold for ThresholdedReLU. Default is 1.0 name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`. Shape: - input: Tensor with any shape. - output: Tensor with the same shape as input. Examples: .. code-block:: python import paddle import numpy as np x = paddle.to_tensor(np.array([2., 0., 1.])) m = paddle.nn.ThresholdedReLU() out = m(x) # [2., 0., 0.]
62598fbb0fa83653e46f5078
class TestV1ReplicaSet(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 testV1ReplicaSet(self): <NEW_LINE> <INDENT> pass
V1ReplicaSet unit test stubs
62598fbbaad79263cf42e969
class AdaptiveScaleWrapper: <NEW_LINE> <INDENT> target_size = 35. <NEW_LINE> image_min_side = 832 <NEW_LINE> def __init__(self, detector, scales=(0.8, 1, 1.25)): <NEW_LINE> <INDENT> assert detector.image_min_side == self.image_min_side <NEW_LINE> self.detector = detector <NEW_LINE> self.scales = scales <NEW_LINE> <DEDENT> def detect(self, image): <NEW_LINE> <INDENT> bboxes, scores = self.detector.detect(image) <NEW_LINE> if len(bboxes) == 0: <NEW_LINE> <INDENT> return bboxes, scores <NEW_LINE> <DEDENT> size = (bboxes[:, 2:4] - bboxes[:, 0:2]).mean() <NEW_LINE> size *= (self.image_min_side / min(*image.size)) <NEW_LINE> scale = self.target_size / size <NEW_LINE> detectors = [ResizedImageWrapper(self.detector, scale * s) for s in self.scales] <NEW_LINE> voting_wrapper = BboxVoting(detectors) <NEW_LINE> bboxes, scores = voting_wrapper.detect(image) <NEW_LINE> return bboxes, scores
Adaptive scale detection wrapper.
62598fbb236d856c2adc950a
class ClearCacheMixin(object): <NEW_LINE> <INDENT> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> call_command('clear_cache') <NEW_LINE> super().save_model(request, obj, form, change) <NEW_LINE> <DEDENT> def delete_model(self, request, obj): <NEW_LINE> <INDENT> call_command('clear_cache') <NEW_LINE> super().delete_model(request, obj)
Mixin that overrides the `save` and `delete` methods of Django's ModelAdmin class to clear the cache whenever an object is added or changed.
62598fbb71ff763f4b5e790e
class GenericBox(GW.BaseBox): <NEW_LINE> <INDENT> modified = QC.Signal([], [object]) <NEW_LINE> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.init() <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_modified_signal(self): <NEW_LINE> <INDENT> return(self.modified[object]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_types(self): <NEW_LINE> <INDENT> return([bool, float, int, str]) <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> box_layout = GL.QHBoxLayout(self) <NEW_LINE> box_layout.setContentsMargins(0, 0, 0, 0) <NEW_LINE> self.box_layout = box_layout <NEW_LINE> type_box = GW.QComboBox() <NEW_LINE> type_box.addItems(sorted([x.__name__ for x in self.supported_types])) <NEW_LINE> type_box.setSizePolicy(QW.QSizePolicy.Fixed, QW.QSizePolicy.Fixed) <NEW_LINE> set_box_value(type_box, -1) <NEW_LINE> get_modified_signal(type_box).connect(self.create_value_box) <NEW_LINE> box_layout.addWidget(type_box) <NEW_LINE> self.type_box = type_box <NEW_LINE> value_box = GW.QWidget() <NEW_LINE> box_layout.addWidget(value_box) <NEW_LINE> self.value_box = value_box <NEW_LINE> <DEDENT> @QC.Slot() <NEW_LINE> def modified_signal_slot(self): <NEW_LINE> <INDENT> self.modified[object].emit(get_box_value(self.value_box)) <NEW_LINE> <DEDENT> @QC.Slot(str) <NEW_LINE> def create_value_box(self, value_type): <NEW_LINE> <INDENT> value_box = GW.type_box_dict[eval(value_type)]() <NEW_LINE> value_box.setSizePolicy(QW.QSizePolicy.Expanding, QW.QSizePolicy.Fixed) <NEW_LINE> cur_item = self.box_layout.replaceWidget(self.value_box, value_box) <NEW_LINE> cur_item.widget().close() <NEW_LINE> del cur_item <NEW_LINE> self.value_box = value_box <NEW_LINE> <DEDENT> def get_box_value(self, *value_sig): <NEW_LINE> <INDENT> if type(self.value_box) is GW.QWidget: <NEW_LINE> <INDENT> return(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return(get_box_value(self.value_box, *value_sig)) <NEW_LINE> <DEDENT> <DEDENT> def set_box_value(self, value, *value_sig): <NEW_LINE> <INDENT> set_box_value(self.type_box, type(value).__name__) <NEW_LINE> set_box_value(self.value_box, value, *value_sig)
Defines the :class:`~GenericBox` class. This class is used for making a generic value box that only accepts single values, unlike :class:`~LongGenericBox`. It currently supports inputs of type bool; float; int; and str.
62598fbbadb09d7d5dc0a711
class WorldBorder(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> area = models.IntegerField() <NEW_LINE> pop2005 = models.IntegerField('Population 2005') <NEW_LINE> fips = models.CharField('FIPS Code', max_length=2) <NEW_LINE> iso2 = models.CharField('2 Digit ISO', max_length=2) <NEW_LINE> iso3 = models.CharField('3 Digit ISO', max_length=3) <NEW_LINE> un = models.IntegerField('United Nations Code') <NEW_LINE> region = models.IntegerField('Region Code') <NEW_LINE> subregion = models.IntegerField('Sub-Region Code') <NEW_LINE> lon = models.FloatField() <NEW_LINE> lat = models.FloatField() <NEW_LINE> mpoly = models.MultiPolygonField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Za svako dato polje u .shp kreiramo njemu odgovarajuće u modelu
62598fbb097d151d1a2c11c8
@with_input_types(Tuple[T, TimestampType]) <NEW_LINE> @with_output_types(T) <NEW_LINE> class LatestCombineFn(core.CombineFn): <NEW_LINE> <INDENT> def create_accumulator(self): <NEW_LINE> <INDENT> return (None, window.MIN_TIMESTAMP) <NEW_LINE> <DEDENT> def add_input(self, accumulator, element): <NEW_LINE> <INDENT> if accumulator[1] > element[1]: <NEW_LINE> <INDENT> return accumulator <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return element <NEW_LINE> <DEDENT> <DEDENT> def merge_accumulators(self, accumulators): <NEW_LINE> <INDENT> result = self.create_accumulator() <NEW_LINE> for accumulator in accumulators: <NEW_LINE> <INDENT> result = self.add_input(result, accumulator) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def extract_output(self, accumulator): <NEW_LINE> <INDENT> return accumulator[0]
CombineFn to get the element with the latest timestamp from a PCollection.
62598fbb091ae35668704db7
class ReplyTopicTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.board = Board.objects.create(name='Django', description='Django board') <NEW_LINE> self.username = 'john' <NEW_LINE> self.password = '123' <NEW_LINE> user = User.objects.create_user(username=self.username, password=self.password) <NEW_LINE> self.topic = Topic.objects.create(subject='Hello world', board=self.board, starter=user) <NEW_LINE> Post.objects.create(message='Lorem ipsum dolor sit amet', topic=self.topic, created_by=user) <NEW_LINE> self.url = reverse('reply_topic', kwargs={'pk': self.board.pk, 'topic_pk': self.topic.pk})
Base test case to be used in all `reply_topic` view tests
62598fbb55399d3f056266a9
class SvnTagDialog(QDialog, Ui_SvnTagDialog): <NEW_LINE> <INDENT> def __init__(self, taglist, reposURL, standardLayout, parent=None): <NEW_LINE> <INDENT> super(SvnTagDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.okButton = self.buttonBox.button(QDialogButtonBox.Ok) <NEW_LINE> self.okButton.setEnabled(False) <NEW_LINE> self.tagCombo.clear() <NEW_LINE> self.tagCombo.addItems(sorted(taglist)) <NEW_LINE> if reposURL is not None and reposURL != "": <NEW_LINE> <INDENT> self.tagCombo.setEditText(reposURL) <NEW_LINE> <DEDENT> if not standardLayout: <NEW_LINE> <INDENT> self.TagActionGroup.setEnabled(False) <NEW_LINE> <DEDENT> msh = self.minimumSizeHint() <NEW_LINE> self.resize(max(self.width(), msh.width()), msh.height()) <NEW_LINE> <DEDENT> def on_tagCombo_editTextChanged(self, text): <NEW_LINE> <INDENT> self.okButton.setDisabled(text == "") <NEW_LINE> <DEDENT> def getParameters(self): <NEW_LINE> <INDENT> tag = self.tagCombo.currentText() <NEW_LINE> tagOp = 0 <NEW_LINE> if self.createRegularButton.isChecked(): <NEW_LINE> <INDENT> tagOp = 1 <NEW_LINE> <DEDENT> elif self.createBranchButton.isChecked(): <NEW_LINE> <INDENT> tagOp = 2 <NEW_LINE> <DEDENT> elif self.deleteRegularButton.isChecked(): <NEW_LINE> <INDENT> tagOp = 4 <NEW_LINE> <DEDENT> elif self.deleteBranchButton.isChecked(): <NEW_LINE> <INDENT> tagOp = 8 <NEW_LINE> <DEDENT> return (tag, tagOp)
Class implementing a dialog to enter the data for a tagging operation.
62598fbb4a966d76dd5ef068
class WhiteKing(King, Piece): <NEW_LINE> <INDENT> symbol = u'\u2654' <NEW_LINE> simple_simbol = u'WK' <NEW_LINE> name = u'WhiteKing' <NEW_LINE> color = Color.WHITE <NEW_LINE> def __init__(self, has_moved=False): <NEW_LINE> <INDENT> self.has_moved = has_moved
The White King chess piece.
62598fbb3d592f4c4edbb053
class DNSManager(utils.IdentifierMixin, object): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.service = self.client['Dns_Domain'] <NEW_LINE> self.record = self.client['Dns_Domain_ResourceRecord'] <NEW_LINE> self.resolvers = [self._get_zone_id_from_name] <NEW_LINE> <DEDENT> def _get_zone_id_from_name(self, name): <NEW_LINE> <INDENT> results = self.client['Account'].getDomains( filter={"domains": {"name": utils.query_filter(name)}}) <NEW_LINE> return [x['id'] for x in results] <NEW_LINE> <DEDENT> def list_zones(self, **kwargs): <NEW_LINE> <INDENT> return self.client['Account'].getDomains(**kwargs) <NEW_LINE> <DEDENT> def get_zone(self, zone_id, records=True): <NEW_LINE> <INDENT> mask = None <NEW_LINE> if records: <NEW_LINE> <INDENT> mask = 'resourceRecords' <NEW_LINE> <DEDENT> return self.service.getObject(id=zone_id, mask=mask) <NEW_LINE> <DEDENT> def create_zone(self, zone, serial=None): <NEW_LINE> <INDENT> return self.service.createObject({ 'name': zone, 'serial': serial or time.strftime('%Y%m%d01'), "resourceRecords": {}}) <NEW_LINE> <DEDENT> def delete_zone(self, zone_id): <NEW_LINE> <INDENT> return self.service.deleteObject(id=zone_id) <NEW_LINE> <DEDENT> def edit_zone(self, zone): <NEW_LINE> <INDENT> self.service.editObject(zone) <NEW_LINE> <DEDENT> def create_record(self, zone_id, record, record_type, data, ttl=60): <NEW_LINE> <INDENT> return self.record.createObject({ 'domainId': zone_id, 'ttl': ttl, 'host': record, 'type': record_type, 'data': data}) <NEW_LINE> <DEDENT> def delete_record(self, record_id): <NEW_LINE> <INDENT> self.record.deleteObject(id=record_id) <NEW_LINE> <DEDENT> def get_record(self, record_id): <NEW_LINE> <INDENT> return self.record.getObject(id=record_id) <NEW_LINE> <DEDENT> def get_records(self, zone_id, ttl=None, data=None, host=None, record_type=None): <NEW_LINE> <INDENT> _filter = utils.NestedDict() <NEW_LINE> if ttl: <NEW_LINE> <INDENT> _filter['resourceRecords']['ttl'] = utils.query_filter(ttl) <NEW_LINE> <DEDENT> if host: <NEW_LINE> <INDENT> _filter['resourceRecords']['host'] = utils.query_filter(host) <NEW_LINE> <DEDENT> if data: <NEW_LINE> <INDENT> _filter['resourceRecords']['data'] = utils.query_filter(data) <NEW_LINE> <DEDENT> if record_type: <NEW_LINE> <INDENT> _filter['resourceRecords']['type'] = utils.query_filter( record_type.lower()) <NEW_LINE> <DEDENT> results = self.service.getResourceRecords( id=zone_id, mask='id,expire,domainId,host,minimum,refresh,retry,' 'mxPriority,ttl,type,data,responsiblePerson', filter=_filter.to_dict(), ) <NEW_LINE> return results <NEW_LINE> <DEDENT> def edit_record(self, record): <NEW_LINE> <INDENT> self.record.editObject(record, id=record['id']) <NEW_LINE> <DEDENT> def dump_zone(self, zone_id): <NEW_LINE> <INDENT> return self.service.getZoneFileContents(id=zone_id)
Manage SoftLayer DNS. See product information here: http://www.softlayer.com/DOMAIN-SERVICES :param SoftLayer.API.BaseClient client: the client instance
62598fbb796e427e5384e92b
class AbstractSTREnityListView(QListView): <NEW_LINE> <INDENT> def __init__(self, parent=None, **kwargs): <NEW_LINE> <INDENT> super(AbstractSTREnityListView, self).__init__(parent) <NEW_LINE> self._model = QStandardItemModel(self) <NEW_LINE> self._model.setColumnCount(1) <NEW_LINE> self.setModel(self._model) <NEW_LINE> self.setEditTriggers(QAbstractItemView.NoEditTriggers) <NEW_LINE> self._model.itemChanged.connect(self._on_item_changed) <NEW_LINE> self._profile = kwargs.get('profile', None) <NEW_LINE> self._social_tenure = kwargs.get('social_tenure', None) <NEW_LINE> if not self._profile is None: <NEW_LINE> <INDENT> self._load_profile_entities() <NEW_LINE> <DEDENT> if not self._social_tenure is None: <NEW_LINE> <INDENT> self._select_str_entities() <NEW_LINE> <DEDENT> <DEDENT> def _on_item_changed(self, item): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def profile(self): <NEW_LINE> <INDENT> return self._profile <NEW_LINE> <DEDENT> @profile.setter <NEW_LINE> def profile(self, profile): <NEW_LINE> <INDENT> self._profile = profile <NEW_LINE> self._load_profile_entities() <NEW_LINE> <DEDENT> @property <NEW_LINE> def social_tenure(self): <NEW_LINE> <INDENT> return self._social_tenure <NEW_LINE> <DEDENT> @social_tenure.setter <NEW_LINE> def social_tenure(self, social_tenure): <NEW_LINE> <INDENT> self._social_tenure = social_tenure <NEW_LINE> self._select_str_entities() <NEW_LINE> <DEDENT> def _select_str_entities(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _load_profile_entities(self): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> for e in self._profile.user_entities(): <NEW_LINE> <INDENT> self._add_entity(e) <NEW_LINE> <DEDENT> <DEDENT> def _add_entity(self, entity): <NEW_LINE> <INDENT> item = QStandardItem( GuiUtils.get_icon('table.png'), entity.short_name ) <NEW_LINE> item.setCheckable(True) <NEW_LINE> item.setCheckState(Qt.Unchecked) <NEW_LINE> self._model.appendRow(item) <NEW_LINE> <DEDENT> def select_entities(self, entities): <NEW_LINE> <INDENT> self.clear_selection() <NEW_LINE> for e in entities: <NEW_LINE> <INDENT> name = e.short_name <NEW_LINE> self.select_entity(name) <NEW_LINE> <DEDENT> <DEDENT> def selected_entities(self): <NEW_LINE> <INDENT> selected_items = [] <NEW_LINE> for i in range(self._model.rowCount()): <NEW_LINE> <INDENT> item = self._model.item(i) <NEW_LINE> if item.checkState() == Qt.Checked: <NEW_LINE> <INDENT> selected_items.append(item.text()) <NEW_LINE> <DEDENT> <DEDENT> return selected_items <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self._model.clear() <NEW_LINE> self._model.setColumnCount(1) <NEW_LINE> <DEDENT> def clear_selection(self): <NEW_LINE> <INDENT> for i in range(self._model.rowCount()): <NEW_LINE> <INDENT> item = self._model.item(i) <NEW_LINE> if item.checkState() == Qt.Checked: <NEW_LINE> <INDENT> item.setCheckState(Qt.Unchecked) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def select_entity(self, name): <NEW_LINE> <INDENT> items = self._model.findItems(name) <NEW_LINE> if len(items) > 0: <NEW_LINE> <INDENT> item = items[0] <NEW_LINE> if item.checkState() == Qt.Unchecked: <NEW_LINE> <INDENT> item.setCheckState(Qt.Checked) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def deselect_entity(self, name): <NEW_LINE> <INDENT> items = self._model.findItems(name) <NEW_LINE> if len(items) > 0: <NEW_LINE> <INDENT> item = items[0] <NEW_LINE> if item.checkState() == Qt.Checked: <NEW_LINE> <INDENT> item.setCheckState(Qt.Unchecked)
A widget for listing and selecting one or more STR entities. .. versionadded:: 1.7
62598fbb5fc7496912d48346
@dataclass <NEW_LINE> class Inst: <NEW_LINE> <INDENT> tvar: TypeVariable <NEW_LINE> typeclass: str <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"{self.typeclass} {self.tvar}"
States the `tvar` is an instance of type class `typeclass`
62598fbb97e22403b383b09d
class NavViewDashWidget(IconToolButton): <NEW_LINE> <INDENT> def __init__(self, context, name='NavView'): <NEW_LINE> <INDENT> super(NavViewDashWidget, self).__init__(name) <NEW_LINE> self.context = context <NEW_LINE> self._icon = self.load_image('nav.png') <NEW_LINE> self._clicked_icon = self.load_image('nav-click.png') <NEW_LINE> self._icons = [make_icon(self._icon)] <NEW_LINE> self._clicked_icons = [make_icon(self._clicked_icon)] <NEW_LINE> self.setIcon(make_icon(self._icon)) <NEW_LINE> self._nav_view = None <NEW_LINE> self.clicked.connect(self._show_nav_view) <NEW_LINE> <DEDENT> def _show_nav_view(self): <NEW_LINE> <INDENT> if not self._nav_view: <NEW_LINE> <INDENT> self._nav_view = NavViewWidget() <NEW_LINE> self._nav_view.destroyed.connect(self._view_closed) <NEW_LINE> <DEDENT> self.context.add_widget(self._nav_view) <NEW_LINE> <DEDENT> def _view_closed(self): <NEW_LINE> <INDENT> self._nav_view = None
A widget which launches a nav_view widget in order to view and interact with the ROS nav stack :param context: The plugin context in which to dsiplay the nav_view :type context: qt_gui.plugin_context.PluginContext :param name: The widgets name :type name: str
62598fbb498bea3a75a57cba
class InferenceInfo(object): <NEW_LINE> <INDENT> def __init__(self,csp,variable,value,inferenceProcedure): <NEW_LINE> <INDENT> self._variableDomains = copy.deepcopy(csp.getVariableDomains()) <NEW_LINE> self._affectedVariables = [] <NEW_LINE> self._inferenceProcedure = inferenceProcedure <NEW_LINE> self._affectedVariablesMap = {} <NEW_LINE> <DEDENT> def isFailure(self,csp,variable,value): <NEW_LINE> <INDENT> for av in self._affectedVariables: <NEW_LINE> <INDENT> if len(av[1]) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def doInference(self,csp,variable,value): <NEW_LINE> <INDENT> return self._inferenceProcedure.doInference(self,csp,variable,value) <NEW_LINE> <DEDENT> def getAffectedVariables(self): <NEW_LINE> <INDENT> return self._affectedVariables <NEW_LINE> <DEDENT> def addToAffectedVariables(self,var,domainList): <NEW_LINE> <INDENT> self._affectedVariablesMap[var] = domainList <NEW_LINE> <DEDENT> def getDomainsOfAffectedVariables(self,var): <NEW_LINE> <INDENT> if var in self._affectedVariablesMap: <NEW_LINE> <INDENT> return self._affectedVariablesMap[var] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def setInferencesToAssignments(self,assignment,csp): <NEW_LINE> <INDENT> for var,domains in self._affectedVariablesMap.items(): <NEW_LINE> <INDENT> csp.addVariableDomain(var,domains) <NEW_LINE> <DEDENT> <DEDENT> def restoreDomains(self,csp): <NEW_LINE> <INDENT> csp.setVariableDomains(self._variableDomains)
classdocs
62598fbbff9c53063f51a7e4
class ResidueList(list): <NEW_LINE> <INDENT> def __init__(self, parm): <NEW_LINE> <INDENT> list.__init__(self, [Residue(parm.parm_data['RESIDUE_LABEL'][i], i+1) for i in range(parm.ptr('nres'))]) <NEW_LINE> for i, val in enumerate(parm.parm_data['RESIDUE_POINTER']): <NEW_LINE> <INDENT> start = val - 1 <NEW_LINE> try: <NEW_LINE> <INDENT> end = parm.parm_data['RESIDUE_POINTER'][i+1] - 1 <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> end = parm.parm_data['POINTERS'][NATOM] <NEW_LINE> <DEDENT> for j in range(start, end): <NEW_LINE> <INDENT> self[i].add_atom(parm.atom_list[j]) <NEW_LINE> <DEDENT> <DEDENT> self.parm = parm
Array of Residues.
62598fbb0fa83653e46f507a
class MWidget(HasTraits): <NEW_LINE> <INDENT> tooltip = Str() <NEW_LINE> context_menu = Instance("pyface.action.menu_manager.MenuManager") <NEW_LINE> def create(self): <NEW_LINE> <INDENT> self._create() <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> self._remove_event_listeners() <NEW_LINE> self.control = None <NEW_LINE> <DEDENT> <DEDENT> def _create(self): <NEW_LINE> <INDENT> self.control = self._create_control(self.parent) <NEW_LINE> self._initialize_control() <NEW_LINE> self._add_event_listeners() <NEW_LINE> <DEDENT> def _create_control(self, parent): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _initialize_control(self): <NEW_LINE> <INDENT> self._set_control_tooltip(self.tooltip) <NEW_LINE> <DEDENT> def _add_event_listeners(self): <NEW_LINE> <INDENT> self.observe(self._tooltip_updated, "tooltip", dispatch="ui") <NEW_LINE> self.observe( self._context_menu_updated, "context_menu", dispatch="ui" ) <NEW_LINE> if self.control is not None and self.context_menu is not None: <NEW_LINE> <INDENT> self._observe_control_context_menu() <NEW_LINE> <DEDENT> <DEDENT> def _remove_event_listeners(self): <NEW_LINE> <INDENT> if self.control is not None and self.context_menu is not None: <NEW_LINE> <INDENT> self._observe_control_context_menu(remove=True) <NEW_LINE> <DEDENT> self.observe( self._context_menu_updated, "context_menu", dispatch="ui", remove=True, ) <NEW_LINE> self.observe( self._tooltip_updated, "tooltip", dispatch="ui", remove=True ) <NEW_LINE> <DEDENT> def _get_control_tooltip(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _set_control_tooltip(self, tooltip): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _observe_control_context_menu(self, remove=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _handle_control_context_menu(self, event): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _tooltip_updated(self, event): <NEW_LINE> <INDENT> tooltip = event.new <NEW_LINE> if self.control is not None: <NEW_LINE> <INDENT> self._set_control_tooltip(tooltip) <NEW_LINE> <DEDENT> <DEDENT> def _context_menu_updated(self, event): <NEW_LINE> <INDENT> if self.control is not None: <NEW_LINE> <INDENT> if event.new is None: <NEW_LINE> <INDENT> self._observe_control_context_menu(remove=True) <NEW_LINE> <DEDENT> if event.old is None: <NEW_LINE> <INDENT> self._observe_control_context_menu()
The mixin class that contains common code for toolkit specific implementations of the IWidget interface.
62598fbb56ac1b37e6302384
@dataclass <NEW_LINE> class MinuteNumber(AdminMessage): <NEW_LINE> <INDENT> ADMIN_ID = 0x00 <NEW_LINE> MESSAGE_SIZE = 1 <NEW_LINE> minute: int <NEW_LINE> def __post_init__(self): <NEW_LINE> <INDENT> assert 1 <= self.minute <= 10, "minute must be in range(1, 11)" <NEW_LINE> <DEDENT> def marshal(self): <NEW_LINE> <INDENT> buf = bytearray() <NEW_LINE> buf.append(self.minute) <NEW_LINE> return bytes(buf) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def unmarshal(cls, raw: bytes): <NEW_LINE> <INDENT> minute, data = raw[0], raw[1:] <NEW_LINE> assert len(data) == 0, "Extra bytes remaining!" <NEW_LINE> return MinuteNumber(minute) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return {"type": self.ADMIN_ID, "minute": self.minute}
Minute marker (Deprecated in M2)
62598fbb66656f66f7d5a589
class TracedFile(File): <NEW_LINE> <INDENT> READ_THEN_WRITTEN = 0 <NEW_LINE> ONLY_READ = 1 <NEW_LINE> WRITTEN = 2 <NEW_LINE> what = None <NEW_LINE> def __init__(self, path): <NEW_LINE> <INDENT> path = Path(path) <NEW_LINE> size = None <NEW_LINE> if path.exists(): <NEW_LINE> <INDENT> if path.is_link(): <NEW_LINE> <INDENT> self.comment = "Link to %s" % path.read_link(absolute=True) <NEW_LINE> <DEDENT> elif path.is_dir(): <NEW_LINE> <INDENT> self.comment = "Directory" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> size = path.size() <NEW_LINE> self.comment = hsize(size) <NEW_LINE> <DEDENT> <DEDENT> File.__init__(self, path, size) <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> if self.what is None: <NEW_LINE> <INDENT> self.what = TracedFile.ONLY_READ <NEW_LINE> <DEDENT> <DEDENT> def write(self): <NEW_LINE> <INDENT> if self.what is None: <NEW_LINE> <INDENT> self.what = TracedFile.WRITTEN <NEW_LINE> <DEDENT> elif self.what == TracedFile.ONLY_READ: <NEW_LINE> <INDENT> self.what = TracedFile.READ_THEN_WRITTEN
Override of `~reprozip.common.File` that reads stats from filesystem.
62598fbb7cff6e4e811b5bb8
class BJ_Card(karty.Card): <NEW_LINE> <INDENT> ACE_VALUE = 1 <NEW_LINE> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> if self.is_face_up: <NEW_LINE> <INDENT> v = BJ_Card. RANKS.index(self.rank) + 1 <NEW_LINE> if v > 10: <NEW_LINE> <INDENT> v = 10 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> v = None <NEW_LINE> <DEDENT> return v
Karta do blackjacka
62598fbbadb09d7d5dc0a713
class IPortalFooter(IPageElement): <NEW_LINE> <INDENT> pass
portal footer
62598fbb2c8b7c6e89bd395c
class CodeGRECO(ModelView, ModelSQL): <NEW_LINE> <INDENT> __name__ = "portrait.codegreco" <NEW_LINE> code = fields.Char( string=u'Code', help=u'Code GRECO', required=True, ) <NEW_LINE> name = fields.Char( string=u'Nom', help=u'Nom GRECO', required=True, ) <NEW_LINE> domaine = fields.Char( string=u'Domaine', help=u'Domaine GRECO', ) <NEW_LINE> r = fields.Integer( string=u'Red color', help=u'Red of RVB color', ) <NEW_LINE> v = fields.Integer( string=u'Green color', help=u'Green of RVB color', ) <NEW_LINE> b = fields.Integer( string=u'Blue color', help=u'Blue of RVB color', )
Code couleur GRECO
62598fbb5166f23b2e243575
class Answer(Region): <NEW_LINE> <INDENT> _is_correct_locator = (By.CSS_SELECTOR, '.correct-incorrect svg') <NEW_LINE> _answer_letter_locator = (By.CSS_SELECTOR, '.answer-letter') <NEW_LINE> _answer_content_locator = (By.CSS_SELECTOR, '.answer-content') <NEW_LINE> _has_image_locator = (By.CSS_SELECTOR, '.answer-content img') <NEW_LINE> _feedback_content_locator = ( By.CSS_SELECTOR, '.question-feedback-content') <NEW_LINE> @property <NEW_LINE> def is_correct(self) -> bool: <NEW_LINE> <INDENT> return bool(self.find_elements(*self._is_correct_locator)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def letter(self) -> str: <NEW_LINE> <INDENT> return self.find_element(*self._answer_letter_locator).text <NEW_LINE> <DEDENT> @property <NEW_LINE> def answer(self) -> str: <NEW_LINE> <INDENT> return (self.find_element(*self._answer_content_locator) .get_attribute('textContent')) <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_image(self) -> bool: <NEW_LINE> <INDENT> return bool(self.find_elements(*self._has_image_locator)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def image_text(self) -> str: <NEW_LINE> <INDENT> if self.has_image: <NEW_LINE> <INDENT> return (self.find_element(*self._has_image_locator) .get_attribute('alt')) <NEW_LINE> <DEDENT> return ''
An answer option.
62598fbb5fcc89381b266218
class ForAllPSE(list): <NEW_LINE> <INDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> def wrapper(*args, **kargs): <NEW_LINE> <INDENT> threads = [] <NEW_LINE> for o in self: <NEW_LINE> <INDENT> threads.append(utils.InterruptedThread(o.__getattribute__(name), args=args, kwargs=kargs)) <NEW_LINE> <DEDENT> for t in threads: <NEW_LINE> <INDENT> t.start() <NEW_LINE> <DEDENT> result = [] <NEW_LINE> for t in threads: <NEW_LINE> <INDENT> ret = {} <NEW_LINE> try: <NEW_LINE> <INDENT> ret["return"] = t.join() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> ret["exception"] = sys.exc_info() <NEW_LINE> ret["args"] = args <NEW_LINE> ret["kargs"] = kargs <NEW_LINE> <DEDENT> result.append(ret) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> return wrapper
Parallel version of and suppress exception.
62598fbbbf627c535bcb163c
class QuestionForm(forms.Form): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.helper = FormHelper() <NEW_LINE> self.helper.form_method = 'post' <NEW_LINE> self.helper.form_tag = kwargs.get('form_tag', True) <NEW_LINE> if 'form_tag' in kwargs: <NEW_LINE> <INDENT> del kwargs['form_tag'] <NEW_LINE> <DEDENT> self.engagement_survey = kwargs.get('engagement_survey') <NEW_LINE> self.answered_survey = kwargs.get('answered_survey') <NEW_LINE> if not self.answered_survey: <NEW_LINE> <INDENT> del kwargs['engagement_survey'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del kwargs['answered_survey'] <NEW_LINE> <DEDENT> self.helper.form_class = kwargs.get('form_class', '') <NEW_LINE> self.question = kwargs.get('question') <NEW_LINE> if not self.question: <NEW_LINE> <INDENT> raise ValueError('Need a question to render') <NEW_LINE> <DEDENT> del kwargs['question'] <NEW_LINE> super(QuestionForm, self).__init__(*args, **kwargs)
Base class for a Question
62598fbb26068e7796d4caf2
class AddressAlreadyInUse(Exception): <NEW_LINE> <INDENT> pass
Address is already used by other service.
62598fbb01c39578d7f12f13
class Ident(ctypes.Structure): <NEW_LINE> <INDENT> _fields_ = [('ei_mag0', ctypes.c_ubyte), ('ei_mag1', ctypes.c_ubyte), ('ei_mag2', ctypes.c_ubyte), ('ei_mag3', ctypes.c_ubyte), ('ei_class', ctypes.c_ubyte), ('ei_data', ctypes.c_ubyte), ('ei_version', ctypes.c_ubyte), ('ei_osabi', ctypes.c_ubyte), ('ei_abiversion', ctypes.c_ubyte), ('ei_pad', ctypes.c_ubyte * 7)] <NEW_LINE> def __init__(self, endianess, elfclass): <NEW_LINE> <INDENT> self.ei_mag0 = 0x7F <NEW_LINE> self.ei_mag1 = ord('E') <NEW_LINE> self.ei_mag2 = ord('L') <NEW_LINE> self.ei_mag3 = ord('F') <NEW_LINE> self.ei_class = elfclass <NEW_LINE> self.ei_data = endianess <NEW_LINE> self.ei_version = EV_CURRENT
Represents the ELF ident array in the ehdr structure.
62598fbb5fc7496912d48347
class Security(Base): <NEW_LINE> <INDENT> __tablename__ = "security" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> symbol = Column(String, unique=True) <NEW_LINE> namespace = Column(String) <NEW_LINE> in_symbol = Column(String) <NEW_LINE> updater = Column(String) <NEW_LINE> currency = Column(String) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f"<Security (id={self.id},symbol={self.symbol})>"
The security / symbol entity Adding a record here should enable it for updated automatically. Contains the link to Yahoo symbol and should replace SymbolMap.
62598fbbd486a94d0ba2c167
class DVCSLoader(BaseLoader): <NEW_LINE> <INDENT> def cleanup(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def has_contents(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_contents(self) -> Iterable[BaseContent]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def has_directories(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_directories(self) -> Iterable[Directory]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def has_revisions(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_revisions(self) -> Iterable[Revision]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def has_releases(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_releases(self) -> Iterable[Release]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_snapshot(self) -> Snapshot: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def eventful(self) -> bool: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def store_data(self) -> None: <NEW_LINE> <INDENT> assert self.origin <NEW_LINE> if self.save_data_path: <NEW_LINE> <INDENT> self.save_data() <NEW_LINE> <DEDENT> if self.has_contents(): <NEW_LINE> <INDENT> for obj in self.get_contents(): <NEW_LINE> <INDENT> if isinstance(obj, Content): <NEW_LINE> <INDENT> self.storage.content_add([obj]) <NEW_LINE> <DEDENT> elif isinstance(obj, SkippedContent): <NEW_LINE> <INDENT> self.storage.skipped_content_add([obj]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError(f"Unexpected content type: {obj}") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.has_directories(): <NEW_LINE> <INDENT> for directory in self.get_directories(): <NEW_LINE> <INDENT> self.storage.directory_add([directory]) <NEW_LINE> <DEDENT> <DEDENT> if self.has_revisions(): <NEW_LINE> <INDENT> for revision in self.get_revisions(): <NEW_LINE> <INDENT> self.storage.revision_add([revision]) <NEW_LINE> <DEDENT> <DEDENT> if self.has_releases(): <NEW_LINE> <INDENT> for release in self.get_releases(): <NEW_LINE> <INDENT> self.storage.release_add([release]) <NEW_LINE> <DEDENT> <DEDENT> snapshot = self.get_snapshot() <NEW_LINE> self.storage.snapshot_add([snapshot]) <NEW_LINE> self.flush() <NEW_LINE> self.loaded_snapshot_id = snapshot.id
This base class is a pattern for dvcs loaders (e.g. git, mercurial). Those loaders are able to load all the data in one go. For example, the loader defined in swh-loader-git :class:`BulkUpdater`. For other loaders (stateful one, (e.g :class:`SWHSvnLoader`), inherit directly from :class:`BaseLoader`.
62598fbb091ae35668704dbb
class Parameter(AbstraktParameter): <NEW_LINE> <INDENT> def __init__(self, verzeichnis, fmin, fmax, fitfunktion, fenster, ordnung, phase_modus, phase_versatz, df, pixel, bereich_links, bereich_rechts, amp_min, amp_max, guete_min, guete_max, off_min, off_max): <NEW_LINE> <INDENT> AbstraktParameter.__init__( self, verzeichnis, fmin, fmax, fitfunktion, fenster, ordnung, phase_modus, phase_versatz, df, bereich_links, bereich_rechts, amp_min, amp_max, guete_min, guete_max, off_min, off_max ) <NEW_LINE> self.pixel = pixel
Alle für den Fit einer Rastermessung nötigen Messparameter
62598fbb2c8b7c6e89bd395f
class Process(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.log_comp_times = False <NEW_LINE> self.is_paused = False <NEW_LINE> <DEDENT> def on_tick(self, sim): <NEW_LINE> <INDENT> raise NotImplementedError("should be implemented by child class") <NEW_LINE> <DEDENT> def pause(self): <NEW_LINE> <INDENT> self.is_paused = True <NEW_LINE> <DEDENT> def resume(self): <NEW_LINE> <INDENT> self.is_paused = False
Processes implement the ``on_tick`` method called by the simulation.
62598fbb627d3e7fe0e0704b
class QuestionModelTest(TestCase): <NEW_LINE> <INDENT> def test_was_published_recently_with_future_question(self): <NEW_LINE> <INDENT> time = timezone.now() + datetime.timedelta(days=30) <NEW_LINE> future_question = Question(pub_date=time) <NEW_LINE> self.assertIs(future_question.was_published_recently(), False) <NEW_LINE> <DEDENT> def test_was_published_recently_with_old_question(self): <NEW_LINE> <INDENT> time = timezone.now() - datetime.timedelta(days=1, seconds=1) <NEW_LINE> old_question = Question(pub_date=time) <NEW_LINE> self.assertIs(old_question.was_published_recently(), False) <NEW_LINE> <DEDENT> def test_was_published_recently_with_recent_question(self): <NEW_LINE> <INDENT> time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) <NEW_LINE> recent_question = Question(pub_date=time) <NEW_LINE> self.assertIs(recent_question.was_published_recently(), True)
Check obj model
62598fbba219f33f346c699f
class DistributedLargeBlobSenderAI(DistributedObjectAI.DistributedObjectAI): <NEW_LINE> <INDENT> notify = DirectNotifyGlobal.directNotify.newCategory('DistributedLargeBlobSenderAI') <NEW_LINE> def __init__(self, air, zoneId, targetAvId, data, useDisk=0): <NEW_LINE> <INDENT> DistributedObjectAI.DistributedObjectAI.__init__(self, air) <NEW_LINE> self.targetAvId = targetAvId <NEW_LINE> self.mode = 0 <NEW_LINE> if useDisk: <NEW_LINE> <INDENT> self.mode |= LargeBlobSenderConsts.USE_DISK <NEW_LINE> <DEDENT> self.generateWithRequired(zoneId) <NEW_LINE> s = str(data) <NEW_LINE> if useDisk: <NEW_LINE> <INDENT> import os <NEW_LINE> import random <NEW_LINE> origDir = os.getcwd() <NEW_LINE> bPath = LargeBlobSenderConsts.getLargeBlobPath() <NEW_LINE> try: <NEW_LINE> <INDENT> os.chdir(bPath) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> DistributedLargeBlobSenderAI.notify.error( 'could not access %s' % bPath) <NEW_LINE> <DEDENT> while 1: <NEW_LINE> <INDENT> num = random.randrange((1 << 30)-1) <NEW_LINE> filename = LargeBlobSenderConsts.FilePattern % num <NEW_LINE> try: <NEW_LINE> <INDENT> os.stat(filename) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> f = open(filename, 'wb') <NEW_LINE> f.write(s) <NEW_LINE> f.close() <NEW_LINE> os.chdir(origDir) <NEW_LINE> self.sendUpdateToAvatarId(self.targetAvId, 'setFilename', [filename]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> chunkSize = LargeBlobSenderConsts.ChunkSize <NEW_LINE> while len(s) > 0: <NEW_LINE> <INDENT> self.sendUpdateToAvatarId(self.targetAvId, 'setChunk', [s[:chunkSize]]) <NEW_LINE> s = s[chunkSize:] <NEW_LINE> <DEDENT> self.sendUpdateToAvatarId(self.targetAvId, 'setChunk', ['']) <NEW_LINE> <DEDENT> <DEDENT> def getMode(self): <NEW_LINE> <INDENT> return self.mode <NEW_LINE> <DEDENT> def getTargetAvId(self): <NEW_LINE> <INDENT> return self.targetAvId <NEW_LINE> <DEDENT> def setAck(self): <NEW_LINE> <INDENT> DistributedLargeBlobSenderAI.notify.debug('setAck') <NEW_LINE> assert self.air.getAvatarIdFromSender() == self.targetAvId <NEW_LINE> self.requestDelete()
DistributedLargeBlobSenderAI: for sending large chunks of data through the DC system to a specific avatar
62598fbb63b5f9789fe85308
class Divide(StochasticParameter): <NEW_LINE> <INDENT> def __init__(self, other_param, val, elementwise=False): <NEW_LINE> <INDENT> super(Divide, self).__init__() <NEW_LINE> self.other_param = handle_continuous_param(other_param, "other_param") <NEW_LINE> self.val = handle_continuous_param(val, "val") <NEW_LINE> self.elementwise = elementwise <NEW_LINE> <DEDENT> def _draw_samples(self, size, random_state): <NEW_LINE> <INDENT> seed = random_state.randint(0, 10**6, 1)[0] <NEW_LINE> samples = self.other_param.draw_samples(size, random_state=ia.new_random_state(seed)) <NEW_LINE> elementwise = self.elementwise and not isinstance(self.val, Deterministic) <NEW_LINE> if elementwise: <NEW_LINE> <INDENT> val_samples = self.val.draw_samples( size, random_state=ia.new_random_state(seed+1) ) <NEW_LINE> val_samples[val_samples == 0] = 1 <NEW_LINE> return np.divide( force_np_float_dtype(samples), force_np_float_dtype(val_samples) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val_sample = self.val.draw_sample( random_state=ia.new_random_state(seed+1) ) <NEW_LINE> if val_sample == 0: <NEW_LINE> <INDENT> val_sample = 1 <NEW_LINE> <DEDENT> return force_np_float_dtype(samples) / float(val_sample) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Divide(%s, %s, %s)" % (str(self.other_param), str(self.val), self.elementwise)
Parameter to divide other parameter's results with. This parameter will automatically prevent division by zero (uses 1.0) as the denominator in these cases. Parameters ---------- other_param : number or tuple of two number or list of number or StochasticParameter Other parameter which's sampled values are to be divided. val : number or tuple of two number or list of number or StochasticParameter Denominator to use. If this is a StochasticParameter, either a single or multiple values will be sampled and used as the denominator(s). elementwise : bool, optional(default=False) Controls the sampling behaviour when `val` is a StochasticParameter. If set to False, a single value will be sampled from val and used as the constant denominator. If set to True and `_draw_samples(size=S)` is called, `S` values will be sampled from `val` and used as the elementwise denominators for the results of `other_param`. Examples -------- >>> param = Divide(Uniform(0.0, 1.0), 2) Converts a uniform range [0.0, 1.0) to [0, 0.5).
62598fbb76e4537e8c3ef740
class DigitalException(Exception): <NEW_LINE> <INDENT> message = _("An unknown exception occurred.") <NEW_LINE> code = 500 <NEW_LINE> def __init__(self, message=None, **kwargs): <NEW_LINE> <INDENT> self.kwargs = kwargs <NEW_LINE> if 'code' not in self.kwargs and hasattr(self, 'code'): <NEW_LINE> <INDENT> self.kwargs['code'] = self.code <NEW_LINE> <DEDENT> if message: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.message = self.message % kwargs <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception('Exception in string format operation, ' 'kwargs: %s', kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> if CONF.fatal_exception_format_errors: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> except cfg.NoSuchOptError: <NEW_LINE> <INDENT> if CONF.oslo_versionedobjects.fatal_exception_format_errors: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> super(DigitalException, self).__init__(self.message) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if six.PY3: <NEW_LINE> <INDENT> return self.message <NEW_LINE> <DEDENT> return self.message.encode('utf-8') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.message <NEW_LINE> <DEDENT> def format_message(self): <NEW_LINE> <INDENT> if self.__class__.__name__.endswith('_Remote'): <NEW_LINE> <INDENT> return self.args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return six.text_type(self)
Base Digital Exception To correctly use this class, inherit from it and define a 'message' property. That message will get printf'd with the keyword arguments provided to the constructor.
62598fbb21bff66bcd722e03
class Test(EntryPoint): <NEW_LINE> <INDENT> pass
测试相关的工具.
62598fbb4c3428357761a455
class StripePercentField(StripeFieldMixin, models.DecimalField): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> defaults = { 'decimal_places': 2, 'max_digits': 5, 'validators': [MinValueValidator(1.00), MaxValueValidator(100.00)] } <NEW_LINE> defaults.update(kwargs) <NEW_LINE> super().__init__(*args, **defaults)
A field used to define a percent according to djstripe logic.
62598fbb283ffb24f3cf3a1c
class VideoListSorted: <NEW_LINE> <INDENT> def __init__(self, path_response, context_name, context_id, req_sort_order_type): <NEW_LINE> <INDENT> self.perpetual_range_selector = path_response.get('_perpetual_range_selector') <NEW_LINE> self.data = path_response <NEW_LINE> self.context_name = context_name <NEW_LINE> has_data = bool((context_id and path_response.get(context_name) and path_response[context_name].get(context_id)) or (not context_id and path_response.get(context_name))) <NEW_LINE> self.data_lists = {} <NEW_LINE> self.videos = OrderedDict() <NEW_LINE> self.artitem = None <NEW_LINE> self.contained_titles = None <NEW_LINE> self.videoids = None <NEW_LINE> if has_data: <NEW_LINE> <INDENT> self.data_lists = path_response[context_name][context_id][req_sort_order_type] if context_id else path_response[context_name][req_sort_order_type] <NEW_LINE> self.videos = OrderedDict(resolve_refs(self.data_lists, self.data)) <NEW_LINE> if self.videos: <NEW_LINE> <INDENT> self.artitem = listvalues(self.videos)[0] <NEW_LINE> self.contained_titles = _get_titles(self.videos) <NEW_LINE> try: <NEW_LINE> <INDENT> self.videoids = _get_videoids(self.videos) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.videoids = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return _check_sentinel(self.data_lists[key]) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> return _check_sentinel(self.data_lists.get(key, default))
A video list
62598fbbcc0a2c111447b1a7
class RandomAgent(agents.base_agent.RlAgent): <NEW_LINE> <INDENT> def __init__(self, action_space): <NEW_LINE> <INDENT> self.action_space = action_space <NEW_LINE> <DEDENT> def act(self, state): <NEW_LINE> <INDENT> return self.action_space.sample() <NEW_LINE> <DEDENT> def receive_reward(self, reward, terminal): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def total_reward(self): <NEW_LINE> <INDENT> pass
The world's simplest agent!
62598fbb796e427e5384e92f
class VoteInfo: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.option: str = '' <NEW_LINE> self.votes: float = 0.0 <NEW_LINE> self.cleared_votes: float = 0 <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return pformat(protobuf_to_dict(self.to_raw())) <NEW_LINE> <DEDENT> def from_raw(self, i: pb.VoteInfo) -> AccountInfo.VoteInfo: <NEW_LINE> <INDENT> self.option = i.option <NEW_LINE> self.votes = i.votes <NEW_LINE> self.cleared_votes = i.cleared_votes <NEW_LINE> return self <NEW_LINE> <DEDENT> def to_raw(self) -> pb.VoteInfo: <NEW_LINE> <INDENT> return pb.VoteInfo( option=self.option, votes=self.votes, cleared_votes=self.cleared_votes )
Contains information about vote info. Attributes: option: Vote option votes: Current votes cleared_votes: Votes that has been clead
62598fbb5fdd1c0f98e5e12b
class Query(QueryComponent): <NEW_LINE> <INDENT> class Method(enum.Enum): <NEW_LINE> <INDENT> SELECT = 0 <NEW_LINE> CONSTRUCT = 1 <NEW_LINE> <DEDENT> def __init__(self, result_vars=[], default_url="http://dbpedia.org/sparql", formatter=BasicFormatter()): <NEW_LINE> <INDENT> self._children = [] <NEW_LINE> self.method = Query.Method.SELECT <NEW_LINE> self.result_vars = result_vars <NEW_LINE> self.default_url = default_url <NEW_LINE> self.result_format = SPARQLWrapper.JSON <NEW_LINE> self.result_limit = None <NEW_LINE> self.result_offset = None <NEW_LINE> self.order_by = None <NEW_LINE> self.distinct_results = True <NEW_LINE> self.formatter = formatter <NEW_LINE> <DEDENT> def _serialize_prefix(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def _serialize_result_clause(self): <NEW_LINE> <INDENT> result_clause = self.method.name + " " <NEW_LINE> if self.distinct_results: <NEW_LINE> <INDENT> result_clause += "DISTINCT " <NEW_LINE> <DEDENT> if self.result_vars: <NEW_LINE> <INDENT> for result_var in self.result_vars: <NEW_LINE> <INDENT> result_clause += "?{} ".format(str(result_var)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result_clause += "* " <NEW_LINE> <DEDENT> result_clause += "WHERE {" <NEW_LINE> return result_clause <NEW_LINE> <DEDENT> def _serialize_query_pattern(self): <NEW_LINE> <INDENT> query_pattern = "" <NEW_LINE> for child in self._children: <NEW_LINE> <INDENT> query_pattern += child.serialize() <NEW_LINE> <DEDENT> return query_pattern <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> prefix = self._serialize_prefix() <NEW_LINE> result_clause = self._serialize_result_clause() <NEW_LINE> query_pattern = self._serialize_query_pattern() <NEW_LINE> tail = "}" <NEW_LINE> if self.order_by: <NEW_LINE> <INDENT> tail += " ORDER BY " + serialize_rdf_term(self.order_by) <NEW_LINE> <DEDENT> if self.result_limit: <NEW_LINE> <INDENT> tail += " LIMIT " + str(self.result_limit) <NEW_LINE> if self.result_offset: <NEW_LINE> <INDENT> tail += " OFFSET " + str(self.result_offset) <NEW_LINE> <DEDENT> <DEDENT> return prefix + result_clause + query_pattern + tail <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.formatter.format(self.serialize()) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for child in self._children: <NEW_LINE> <INDENT> yield child <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._children[key] <NEW_LINE> <DEDENT> def add(self, component): <NEW_LINE> <INDENT> if not isinstance(component, QueryComponent): <NEW_LINE> <INDENT> component = Triple(*component) <NEW_LINE> <DEDENT> self._children.append(component) <NEW_LINE> <DEDENT> def execute(self, sparql_url=None): <NEW_LINE> <INDENT> if sparql_url is None: <NEW_LINE> <INDENT> sparql_url = self.default_url <NEW_LINE> <DEDENT> sparql = SPARQLWrapper.SPARQLWrapper(sparql_url) <NEW_LINE> sparql.setQuery(self.serialize()) <NEW_LINE> sparql.setReturnFormat(self.result_format) <NEW_LINE> return sparql.query().convert()
Representation of a SPARQL Query. Attributes: method (QueryMethod): Determines the SPARQL query method (e.g., SELECT, CONSTRUCT) result_vars (list): A list of BNodes to be selected from the query results default_url (string): Default remote SPARQL url used when 'execute' is called result_format: format of values returned by 'execute' result_limit (int): Number of results to return from 'execute' distinct_results (bool): Add 'DISTINCT' to QueryMethod.SELECT queries
62598fbb56b00c62f0fb2a55
class LinearSelfAttn(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_size, dropout=None): <NEW_LINE> <INDENT> super(LinearSelfAttn, self).__init__() <NEW_LINE> self.linear = nn.Linear(input_size, 1) <NEW_LINE> self.dropout = dropout <NEW_LINE> <DEDENT> def forward(self, x, x_mask): <NEW_LINE> <INDENT> x = self.dropout(x) <NEW_LINE> x_flat = x.contiguous().view(-1, x.size(-1)) <NEW_LINE> scores = self.linear(x_flat).view(x.size(0), x.size(1)) <NEW_LINE> scores.data.masked_fill_(x_mask.data, -float('inf')) <NEW_LINE> alpha = F.softmax(scores, 1) <NEW_LINE> return alpha.unsqueeze(1).bmm(x).squeeze(1)
Self attention over a sequence: * o_i = softmax(Wx_i) for x_i in X.
62598fbb956e5f7376df574b
class Section: <NEW_LINE> <INDENT> def __init__(self, content: str, section_type: str='section'): <NEW_LINE> <INDENT> self.section_type = section_type <NEW_LINE> self.content = content <NEW_LINE> <DEDENT> def tex(self) -> str: <NEW_LINE> <INDENT> return f'{BACKSLASH}{self.section_type}{{{self.content}}}'
Represents a depth-aware header
62598fbb091ae35668704dbd
class ActivityProperty(files.FileProperty): <NEW_LINE> <INDENT> pass
A convenience wrapper for creating filters for Activity searches. Usage: filters = [ActivityProperty('color') == 'blue'] ActivitiesService.get_activities(['create'], filters=filters)
62598fbb4f88993c371f05da
class ReportChartInline(admin.TabularInline): <NEW_LINE> <INDENT> extra = 1 <NEW_LINE> form = ReportChartForm <NEW_LINE> model = MSQCdbModels.ReportChart <NEW_LINE> raw_id_fields = ('chart',) <NEW_LINE> sortable_field_name = "position" <NEW_LINE> def formfield_for_dbfield(self, db_field, **kwargs): <NEW_LINE> <INDENT> if db_field.name in self.raw_id_fields: <NEW_LINE> <INDENT> kwargs.pop("request", None) <NEW_LINE> fType = db_field.rel.__class__.__name__ <NEW_LINE> if fType == "ManyToOneRel": <NEW_LINE> <INDENT> kwargs['widget'] = VerboseForeignKeyRawIdWidget(db_field.rel, site) <NEW_LINE> <DEDENT> elif fType == "ManyToManyRel": <NEW_LINE> <INDENT> kwargs['widget'] = VerboseManyToManyRawIdWidget(db_field.rel, site) <NEW_LINE> <DEDENT> return db_field.formfield(**kwargs) <NEW_LINE> <DEDENT> return super(ReportChartInline, self).formfield_for_dbfield(db_field, **kwargs)
Admin config for ReportChart InLine.
62598fbb2c8b7c6e89bd3960
class UnicodeNamedObjectTest(S3ApiVerificationTestBase): <NEW_LINE> <INDENT> utf8_key_name = u"utf8ファイル名.txt" <NEW_LINE> def test_unicode_object(self): <NEW_LINE> <INDENT> bucket = self.conn.create_bucket(self.bucket_name) <NEW_LINE> k = Key(bucket) <NEW_LINE> k.key = UnicodeNamedObjectTest.utf8_key_name <NEW_LINE> k.set_contents_from_string(self.data) <NEW_LINE> self.assertEqual(k.get_contents_as_string(), self.data) <NEW_LINE> self.assertIn(UnicodeNamedObjectTest.utf8_key_name, [obj.key for obj in bucket.list()]) <NEW_LINE> <DEDENT> def test_delete_object(self): <NEW_LINE> <INDENT> bucket = self.conn.create_bucket(self.bucket_name) <NEW_LINE> k = Key(bucket) <NEW_LINE> k.key = UnicodeNamedObjectTest.utf8_key_name <NEW_LINE> k.delete() <NEW_LINE> self.assertNotIn(UnicodeNamedObjectTest.utf8_key_name, [obj.key for obj in bucket.list()])
test to check unicode object name works
62598fbbbe383301e0253998
class Sony12(protocol_base.IrProtocolBase): <NEW_LINE> <INDENT> irp = '{40k,600,lsb}<1,-1|2,-1>(4,-1,F:7,D:5,^45m)*' <NEW_LINE> frequency = 40000 <NEW_LINE> bit_count = 12 <NEW_LINE> encoding = 'lsb' <NEW_LINE> _lead_in = [TIMING * 4, -TIMING] <NEW_LINE> _lead_out = [45000] <NEW_LINE> _middle_timings = [] <NEW_LINE> _bursts = [[TIMING, -TIMING], [TIMING * 2, -TIMING]] <NEW_LINE> _code_order = [ ['F', 7], ['D', 5], ] <NEW_LINE> _parameters = [ ['F', 0, 6], ['D', 7, 11], ] <NEW_LINE> encode_parameters = [ ['device', 0, 31], ['function', 0, 127], ] <NEW_LINE> def encode( self, device: int, function: int, repeat_count: int = 0 ) -> protocol_base.IRCode: <NEW_LINE> <INDENT> params = dict( D=device, F=function, ) <NEW_LINE> packet = self._build_packet(**params) <NEW_LINE> params['frequency'] = self.frequency <NEW_LINE> code = protocol_base.IRCode( self, packet[:] * (repeat_count + 1), [packet[:]] * (repeat_count + 1), params, repeat_count ) <NEW_LINE> return code
IR decoder for the Sony12 protocol.
62598fbb5166f23b2e243579
class CloningVisitor(ClauseVisitor): <NEW_LINE> <INDENT> def copy_and_process(self, list_): <NEW_LINE> <INDENT> return [self.traverse(x) for x in list_] <NEW_LINE> <DEDENT> def traverse(self, obj): <NEW_LINE> <INDENT> return cloned_traverse(obj, self.__traverse_options__, self._visitor_dict)
Base class for visitor objects which can traverse using the cloned_traverse() function.
62598fbb5fcc89381b26621a
class LikeFunction(LikeFunctionBase): <NEW_LINE> <INDENT> def __init__(self, log=False): <NEW_LINE> <INDENT> super(LikeFunction, self).__init__(log) <NEW_LINE> self.mappings = OrderedDict() <NEW_LINE> return <NEW_LINE> <DEDENT> def get_value(self, x): <NEW_LINE> <INDENT> for rng, f in reversed(self.mappings.items()): <NEW_LINE> <INDENT> if x in rng: <NEW_LINE> <INDENT> return f(x) <NEW_LINE> <DEDENT> <DEDENT> return self.default(x) <NEW_LINE> <DEDENT> def _str(self): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for r, f in self.mappings.items(): <NEW_LINE> <INDENT> res.append('{} -> {}'.format(r, f._mydoc)) <NEW_LINE> <DEDENT> return res
Gegneral form. Maps separate values or ranges according to their functions. Mapping information is in self.mappings, which is an OrderedDict of the form `range -> function`.
62598fbb4527f215b58ea070
class HeaderFITSParser(HeaderPlainTextParser): <NEW_LINE> <INDENT> def to_string(self): <NEW_LINE> <INDENT> data = super(HeaderFITSParser, self).to_string() <NEW_LINE> data = [data[i:i + 80] for i in range(0, len(data), 80)] <NEW_LINE> data = ('\r\n'.join(data)) <NEW_LINE> return data.strip()
A parser for FITS headers.
62598fbb4c3428357761a457
class Yn00(Paml): <NEW_LINE> <INDENT> def __init__(self, alignment = None, working_dir = None, out_file = None): <NEW_LINE> <INDENT> Paml.__init__(self, alignment, working_dir, out_file) <NEW_LINE> self.ctl_file = "yn00.ctl" <NEW_LINE> self._options = {"verbose": None, "icode": None, "weighting": None, "commonf3x4": None, "ndata": None} <NEW_LINE> <DEDENT> def write_ctl_file(self): <NEW_LINE> <INDENT> self._set_rel_paths() <NEW_LINE> if True: <NEW_LINE> <INDENT> ctl_handle = open(self.ctl_file, 'w') <NEW_LINE> ctl_handle.write("seqfile = %s\n" % self._rel_alignment) <NEW_LINE> ctl_handle.write("outfile = %s\n" % self._rel_out_file) <NEW_LINE> for option in self._options.items(): <NEW_LINE> <INDENT> if option[1] is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ctl_handle.write("%s = %s\n" % (option[0], option[1])) <NEW_LINE> <DEDENT> ctl_handle.close() <NEW_LINE> <DEDENT> <DEDENT> def read_ctl_file(self, ctl_file): <NEW_LINE> <INDENT> temp_options = {} <NEW_LINE> if not os.path.isfile(ctl_file): <NEW_LINE> <INDENT> raise IOError("File not found: %r" % ctl_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctl_handle = open(ctl_file) <NEW_LINE> for line in ctl_handle: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> uncommented = line.split("*",1)[0] <NEW_LINE> if uncommented != "": <NEW_LINE> <INDENT> if "=" not in uncommented: <NEW_LINE> <INDENT> ctl_handle.close() <NEW_LINE> raise AttributeError( "Malformed line in control file:\n%r" % line) <NEW_LINE> <DEDENT> (option, value) = uncommented.split("=") <NEW_LINE> option = option.strip() <NEW_LINE> value = value.strip() <NEW_LINE> if option == "seqfile": <NEW_LINE> <INDENT> self.alignment = value <NEW_LINE> <DEDENT> elif option == "outfile": <NEW_LINE> <INDENT> self.out_file = value <NEW_LINE> <DEDENT> elif option not in self._options: <NEW_LINE> <INDENT> ctl_handle.close() <NEW_LINE> raise KeyError("Invalid option: %s" % option) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if "." in value or "e-" in value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> converted_value = float(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> converted_value = value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> converted_value = int(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> converted_value = value <NEW_LINE> <DEDENT> <DEDENT> temp_options[option] = converted_value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ctl_handle.close() <NEW_LINE> <DEDENT> for option in self._options.keys(): <NEW_LINE> <INDENT> if option in temp_options.keys(): <NEW_LINE> <INDENT> self._options[option] = temp_options[option] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._options[option] = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run(self, ctl_file = None, verbose = False, command = "yn00", parse = True): <NEW_LINE> <INDENT> Paml.run(self, ctl_file, verbose, command) <NEW_LINE> if parse: <NEW_LINE> <INDENT> results = read(self.out_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = None <NEW_LINE> <DEDENT> return results
This class implements an interface to yn00, part of the PAML package.
62598fbb63d6d428bbee294c
class ExtraPanelTabTestCase(TestCase): <NEW_LINE> <INDENT> def get_tab_type_dicts(self, tab_types): <NEW_LINE> <INDENT> if tab_types: <NEW_LINE> <INDENT> return [{'tab_type': tab_type} for tab_type in tab_types.split(',')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> def get_course_with_tabs(self, tabs=None): <NEW_LINE> <INDENT> if tabs is None: <NEW_LINE> <INDENT> tabs = [] <NEW_LINE> <DEDENT> course = collections.namedtuple('MockCourse', ['tabs']) <NEW_LINE> if isinstance(tabs, str): <NEW_LINE> <INDENT> course.tabs = self.get_tab_type_dicts(tabs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> course.tabs = tabs <NEW_LINE> <DEDENT> return course
Tests adding and removing extra course tabs.
62598fbbf548e778e596b742
class VectorQuantization(autograd.Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(ctx, input, codebook): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_outputs): <NEW_LINE> <INDENT> pass
https://pytorch.org/docs/stable/notes/extending.html
62598fbb26068e7796d4caf6
class WarpAugmentation(Augmentation): <NEW_LINE> <INDENT> def __init__(self, fliph_probability=0., flipv_probability=0., translation=(0, 0), rotation=(0, 0), scale=(1, 1), shear=(0, 0), diffeomorphism=[], diff_fix_border=False, fill_mode='edge', ): <NEW_LINE> <INDENT> self.fliph_probability = _parse_parameter(fliph_probability) <NEW_LINE> self.flipv_probability = _parse_parameter(flipv_probability) <NEW_LINE> self.translation = _parse_parameter(translation) <NEW_LINE> self.rotation = _parse_parameter(rotation) <NEW_LINE> self.scale = _parse_parameter(scale) <NEW_LINE> self.shear = _parse_parameter(shear) <NEW_LINE> self.diffeomorphism = [(_parse_parameter(s), _parse_parameter(i)) for s, i in diffeomorphism] <NEW_LINE> self.diff_fix_border = _parse_parameter(diff_fix_border) <NEW_LINE> self.fill_mode = fill_mode <NEW_LINE> <DEDENT> def get_transformation(self, shape): <NEW_LINE> <INDENT> scale = self.scale() <NEW_LINE> if type(self.scale()) in (float, int): <NEW_LINE> <INDENT> scale = (scale, scale) <NEW_LINE> <DEDENT> diffeomorphism = [(diff_scale(), diff_intensity()) for diff_scale, diff_intensity in self.diffeomorphism] <NEW_LINE> return WarpTransformation( bool(random.random() < self.flipv_probability()), bool(random.random() < self.fliph_probability()), (self.translation(), self.translation()), self.rotation(), scale, self.shear(), diffeomorphism, self.diff_fix_border(), self.fill_mode, shape)
Perform random warping transformation on the input data. Parameters can be either constant values, a list/tuple containing the lower and upper bounds for a uniform distribution or a value generating function: Examples: * WarpAugmentation(rotation=0.5 * np.pi) * WarpAugmentation(rotation=(-0.25 * np.pi, 0.25 * np.pi)) * WarpAugmentation(rotation=lambda: np.random.normal(0, np.pi)) Example Usage: .. code-block:: python aug = WarpAugmentation(rotation=(0.2 * np.pi)) # apply aug to each sample of the batch batch_aug = aug(batch) # get a transformation trans = aug.get_transformation(batch.shape[1:]) # value of the rotation is available rot = trans.rotation # transform first sample in batch x_aug = trans(batch[0]) Sensible starting values for parameter tuning: * fliph_probability = 0.5 * flipv_probability = 0.5 * translation = (-5, 5) * rotation = (-np.pi / 8, np.pi / 8) * scale= (0.9, 1.1) * shear = (-0.1 * np.pi, 0.1 * np.pi) * diffeomorphism = [(8, .75)] Args: fliph_probability: probability of random flips on horizontal (first) axis flipv_probability: probability of random flips on vertial (second) axis translation: translation of image data among all axis rotation: rotation angle in counter-clockwise direction as radians scale: scale as proportion of input size shear: shear angle in counter-clockwise direction as radians. diffeomorphism: list of diffeomorphism parameters. Elements must be of ``(scale, intensity)``. diff_fix_border: fix_border parameter of diffeomorphism augmentation fill_mode (default 'edge'): one of corresponse to numpy.pad mode
62598fbb4428ac0f6e6586bf
@dataclass(eq=False, repr=False) <NEW_LINE> class FilterKernel(AbstractKernel): <NEW_LINE> <INDENT> iqs: List[float] = field(default_factory=list) <NEW_LINE> bias: float = 0.0e+0
A filter kernel to produce scalar readout features from acquired readout waveforms.
62598fbb97e22403b383b0a3
class UserViewset(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = UserSerializer
User viewset
62598fbbd268445f26639c52
class Failure(Exception): <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> self.text = text
Class exception.
62598fbb851cf427c66b8452
class Topic(models.Model): <NEW_LINE> <INDENT> text = models.CharField(max_length=200) <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> owner = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.text
A topic the user is learning about
62598fbb0fa83653e46f5080
class Penetration(BroabModel): <NEW_LINE> <INDENT> HEMISPHERE_CHOICES = ( ('R','Right'), ('L', 'Left'), ) <NEW_LINE> hemisphere = models.CharField(max_length=1, choices=HEMISPHERE_CHOICES) <NEW_LINE> rostral = models.FloatField(default=0.0,help_text='negative is Caudal') <NEW_LINE> lateral = models.FloatField(default=0.0) <NEW_LINE> alpha_angle = models.FloatField(default=90) <NEW_LINE> beta_angle = models.FloatField(default=0.0) <NEW_LINE> rotation_angle = models.FloatField(default=0.0) <NEW_LINE> depth_max = models.FloatField(null=True,blank=True) <NEW_LINE> electrode = models.ForeignKey(Electrode) <NEW_LINE> subject = models.ForeignKey(Subject) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "%s, %s: %s(%s,%s)" % (self.subject,self.electrode,self.hemisphere,self.rostral,self.lateral)
a single penetration of a neural probe - foreign key to probe - has multiple depths - in a subject - coordinates & reference/system
62598fbb8a349b6b436863d8
class MongoengineUpdater(object): <NEW_LINE> <INDENT> def __init__(self, datalayer): <NEW_LINE> <INDENT> self.datalayer = datalayer <NEW_LINE> <DEDENT> def _transform_updates_to_mongoengine_kwargs(self, resource, updates): <NEW_LINE> <INDENT> field_cls = self.datalayer.cls_map[resource] <NEW_LINE> nopfx = lambda x: field_cls._reverse_db_field_map[x] <NEW_LINE> return dict(("set__%s" % nopfx(k), v) for (k, v) in iteritems(updates)) <NEW_LINE> <DEDENT> def _has_empty_list_recurse(self, value): <NEW_LINE> <INDENT> if value == []: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> return self._has_empty_list(value) <NEW_LINE> <DEDENT> elif isinstance(value, list): <NEW_LINE> <INDENT> for val in value: <NEW_LINE> <INDENT> if self._has_empty_list_recurse(val): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def _has_empty_list(self, updates): <NEW_LINE> <INDENT> for key, value in iteritems(updates): <NEW_LINE> <INDENT> if self._has_empty_list_recurse(value): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def _update_using_update_one(self, resource, id_, updates): <NEW_LINE> <INDENT> kwargs = self._transform_updates_to_mongoengine_kwargs(resource, updates) <NEW_LINE> qset = lambda: self.datalayer.cls_map.objects(resource) <NEW_LINE> qry = qset()(id=id_) <NEW_LINE> res = qry.update_one(write_concern=self.datalayer._wc(resource), **kwargs) <NEW_LINE> return res <NEW_LINE> <DEDENT> def _update_document(self, doc, updates): <NEW_LINE> <INDENT> for db_field, value in iteritems(updates): <NEW_LINE> <INDENT> field_name = doc._reverse_db_field_map[db_field] <NEW_LINE> field = doc._fields[field_name] <NEW_LINE> if value is None: <NEW_LINE> <INDENT> doc[field_name] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> doc[field_name] = field.to_python(value) <NEW_LINE> <DEDENT> <DEDENT> return doc <NEW_LINE> <DEDENT> def _update_using_save(self, resource, id_, updates): <NEW_LINE> <INDENT> model = self.datalayer.cls_map.objects(resource)(id=id_).get() <NEW_LINE> self._update_document(model, updates) <NEW_LINE> model.save(write_concern=self.datalayer._wc(resource)) <NEW_LINE> return model <NEW_LINE> <DEDENT> def update(self, resource, id_, updates): <NEW_LINE> <INDENT> opt = self.datalayer.mongoengine_options <NEW_LINE> if opt.get("use_document_save_for_patch", True): <NEW_LINE> <INDENT> res = self._update_using_save(resource, id_, updates) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = self._update_using_update_one(resource, id_, updates) <NEW_LINE> <DEDENT> return res
Helper class for managing updates (PATCH requests) through mongoengine ODM layer. Updates are managed in this class cecause sometimes things need to get dirty and there would be unnecessary 'helper' methods in the main class MongoengineDataLayer causing namespace pollution.
62598fbb656771135c48980a
class RateViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Rate.objects.all().order_by('currency', '-date') <NEW_LINE> serializer_class = RateSerializer
API endpoint that allows rates to be viewed or edited.
62598fbb236d856c2adc950e
class ExpressRouteConnectionList(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteConnection]'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["ExpressRouteConnection"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ExpressRouteConnectionList, self).__init__(**kwargs) <NEW_LINE> self.value = value
ExpressRouteConnection list. :param value: The list of ExpressRoute connections. :type value: list[~azure.mgmt.network.v2019_11_01.models.ExpressRouteConnection]
62598fbba8370b77170f057c
class HyperElasticFamilyData(Struct): <NEW_LINE> <INDENT> data_shapes = { 'mtx_f': ('n_el', 'n_qp', 'dim', 'dim'), 'det_f': ('n_el', 'n_qp', 1, 1), 'sym_b': ('n_el', 'n_qp', 'sym', 1), 'tr_b': ('n_el', 'n_qp', 1, 1), 'in2_b': ('n_el', 'n_qp', 1, 1), 'sym_c' : ('n_el', 'n_qp', 'sym', 1), 'tr_c' : ('n_el', 'n_qp', 1, 1), 'in2_c' : ('n_el', 'n_qp', 1, 1), 'sym_inv_c' : ('n_el', 'n_qp', 'sym', 1), 'green_strain': ('n_el', 'n_qp', 'sym', 1), 'inv_f': ('n_el', 'n_qp', 'dim', 'dim'), } <NEW_LINE> def init_data_struct(self, state_shape, name='family_data'): <NEW_LINE> <INDENT> from sfepy.mechanics.tensors import dim2sym <NEW_LINE> n_el, n_qp, dim, n_en, n_c = state_shape <NEW_LINE> sym = dim2sym(dim); sym <NEW_LINE> shdict = dict(( (k, v) for k, v in six.iteritems(locals()) if k in ['n_el', 'n_qp', 'dim', 'n_en', 'n_c', 'sym'])) <NEW_LINE> data = Struct(name=name) <NEW_LINE> setattr(data, 'names', self.data_names) <NEW_LINE> for key in self.data_names: <NEW_LINE> <INDENT> shape = [shdict[sh] if type(sh) is str else sh for sh in self.data_shapes[key]] <NEW_LINE> setattr(data, key, nm.zeros(shape, dtype=nm.float64)) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def __call__(self, state, region, integral, integration, step=0, derivative=None): <NEW_LINE> <INDENT> step_cache = state.evaluate_cache.setdefault(self.cache_name, {}) <NEW_LINE> cache = step_cache.setdefault(step, {}) <NEW_LINE> key = (region.name, integral.order, integration) <NEW_LINE> data_key = key + (derivative,) <NEW_LINE> if data_key in cache: <NEW_LINE> <INDENT> data = cache[data_key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vg, _ = state.field.get_mapping(region, integral, integration, get_saved=True) <NEW_LINE> vec = state(step=step, derivative=derivative) <NEW_LINE> st_shape = state.get_data_shape(integral, integration, region.name) <NEW_LINE> data = self.init_data_struct(st_shape) <NEW_LINE> fargs = tuple([getattr(data, k) for k in self.data_names]) <NEW_LINE> fargs = fargs + (vec, vg, state.field.econn) <NEW_LINE> self.family_function(*fargs) <NEW_LINE> cache[data_key] = data <NEW_LINE> <DEDENT> return data
Base class for hyperelastic family data. The common (family) data are cached in the evaluate cache of state variable.
62598fbbd486a94d0ba2c16b
class AbsColorLight(AbsColorTemperatureLight, HasColorHSB): <NEW_LINE> <INDENT> _type = "color_light" <NEW_LINE> def set_color(self, hue: float, saturation: float) -> None: <NEW_LINE> <INDENT> raise NotImplementedError()
AbsColorTemperatureLight is an abstraction of all lighting devices with controllable color temperature
62598fbb7d43ff24874274d2
class ScanInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.CallbackUrl = None <NEW_LINE> self.ScanTypes = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.CallbackUrl = params.get("CallbackUrl") <NEW_LINE> self.ScanTypes = params.get("ScanTypes")
需要扫描的应用的服务信息
62598fbb091ae35668704dbf