code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Sensor(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) | Each data source | 6259907f7d847024c075de75 |
class BaseTransaccionDetalle(BaseTabla): <NEW_LINE> <INDENT> registro_padre = database.Column(database.String(50), nullable=True) <NEW_LINE> registro_padre_id = database.Column(database.String(75), nullable=True) <NEW_LINE> referencia = database.Column(database.String(50), nullable=True) <NEW_LINE> referencia_id = database.Column(database.String(75), nullable=True) | Base para crear transacciones en la entidad. | 6259907f23849d37ff852b51 |
class Poll(models.Model): <NEW_LINE> <INDENT> error_css_class = 'error' <NEW_LINE> DRINKS = ( ('v', 'Водка'), ('b', 'Пиво'), ('j', 'Сок'), ('w', 'Вино'), ('l', 'Вино'), ) <NEW_LINE> PRESENCE_STATUSES = ( ('t', 'Приду'), ('f', "Не приду"), ) <NEW_LINE> user = models.ForeignKey('auth.User') <NEW_LINE> drink = models.CharField(max_length=1, choices=DRINKS) <NEW_LINE> presence = models.CharField(max_length=1, choices=PRESENCE_STATUSES) | The polls | 6259907f4527f215b58eb6ec |
class Smartdenovo(MakefilePackage): <NEW_LINE> <INDENT> homepage = "https://github.com/ruanjue/smartdenovo" <NEW_LINE> git = "https://github.com/ruanjue/smartdenovo.git" <NEW_LINE> version('master', branch='master') <NEW_LINE> depends_on('sse2neon', when='target=aarch64:') <NEW_LINE> patch('aarch64.patch', sha256='7dd4bca28aafb0680cc1823aa58ac9000819993538e92628554666c4b3acc470', when='target=aarch64:') <NEW_LINE> patch('inline-limit.patch', sha256='9f514ed72c37cf52ee2ffbe06f9ca1ed5a3e0819dab5876ecd83107c5e5bed81') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> install_files = [ 'pairaln', 'wtpre', 'wtcyc', 'wtmer', 'wtzmo', 'wtobt', 'wtclp', 'wtext', 'wtgbo', 'wtlay', 'wtcns', 'wtmsa' ] <NEW_LINE> mkdirp(prefix.bin) <NEW_LINE> for f in install_files: <NEW_LINE> <INDENT> install(f, prefix.bin) | SMARTdenovo is a de novo assembler for PacBio and Oxford Nanopore
(ONT) data. | 6259907fa8370b77170f1e68 |
class PoolCollection(NamedTuple): <NEW_LINE> <INDENT> pools: List[Pool] <NEW_LINE> total_entries: int | List of Pools with metadata | 6259907fd486a94d0ba2da4f |
class OutputControl(OptionContainer): <NEW_LINE> <INDENT> def __init__(self, dirpath, filepath=None): <NEW_LINE> <INDENT> super().__init__(OutputControlOption, dirpath, filepath) <NEW_LINE> <DEDENT> def set_option(self, name=None, period=None, sum=0, instant=1, mean=0, variance=0, min=0, max=0, mode=0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> o = self.get_option(name, strict=True) <NEW_LINE> o.period = period <NEW_LINE> o.sum = sum <NEW_LINE> o.instant = instant <NEW_LINE> o.mean = mean <NEW_LINE> o.variance = variance <NEW_LINE> o.min = min <NEW_LINE> o.max = max <NEW_LINE> o.mode = mode <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if name in OUTPUT_META['variables']: <NEW_LINE> <INDENT> self.options.append(OutputControlOption( name, period, sum, instant, mean, variance, min, max, mode)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __setitem__(self, name, value): <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> assert len(value) == 8 <NEW_LINE> self.set_option(name, *value) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> self.set_option(name, **value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( 'To set output control options you need to provide' ' a dictionary or list in the respective formats:' '\n' '{"period": val1, "sum": val2, "instant": val3,' ' "mean": val4,' ' "variance": val5, "min": val6,' ' "max": val7, "mode": val8}' '\n or \n' '[val1, val2, val3, val4, val5, val6, val7, val8]') <NEW_LINE> <DEDENT> <DEDENT> def get_constructor_args(self, line): <NEW_LINE> <INDENT> return [l.strip() for l in line.split('!')[0].split('|')] | The OutputControl object manages what output SUMMA will
write out. Each output variable is stored in the `options`
list as an `OutputControlOption`. These options are
automatically populated on instantiation, and can be
added or modified through the `set_option` method. | 6259907f7b180e01f3e49db1 |
class StatusNeed(Need): <NEW_LINE> <INDENT> def action(self, tasker, status, **kw): <NEW_LINE> <INDENT> result = (tasker.status == status) <NEW_LINE> console.profuse("Need Tasker {0} status is {1} = {2}\n".format( tasker.name, StatusNames[status], result)) <NEW_LINE> return result <NEW_LINE> <DEDENT> def resolve(self, tasker, **kwa): <NEW_LINE> <INDENT> parms = super(StatusNeed, self).resolve( **kwa) <NEW_LINE> if not isinstance(tasker, tasking.Tasker): <NEW_LINE> <INDENT> if tasker not in tasking.Tasker.Names: <NEW_LINE> <INDENT> raise excepting.ResolveError("ResolveError: Bad need done tasker link", tasker, self.name) <NEW_LINE> <DEDENT> tasker = tasking.Tasker.Names[tasker] <NEW_LINE> <DEDENT> parms['tasker'] = tasker <NEW_LINE> return parms <NEW_LINE> <DEDENT> def cloneParms(self, parms, clones, **kw): <NEW_LINE> <INDENT> parms = super(StatusNeed,self).cloneParms(parms, clones, **kw) <NEW_LINE> tasker = parms.get('tasker') <NEW_LINE> if isinstance(tasker, tasking.Tasker): <NEW_LINE> <INDENT> if tasker.name in clones: <NEW_LINE> <INDENT> parms['tasker'] = clones[tasker.name][1].name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parms['tasker'] = tasker.name <NEW_LINE> <DEDENT> <DEDENT> elif tasker: <NEW_LINE> <INDENT> if tasker in clones: <NEW_LINE> <INDENT> parms['tasker'] = clones[tasker][1].name <NEW_LINE> <DEDENT> <DEDENT> return parms | StatusNeed Need
parameters:
tasker
status | 6259907f4f88993c371f126e |
class _CompatCredentialsNotFoundError(CredentialsNotFoundError, ValueError): <NEW_LINE> <INDENT> pass | To nudge external code from ValueErrors, we raise a compatibility subclass. | 6259907f656771135c48ad7c |
class CreateTargetGroupResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TargetGroupId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TargetGroupId = params.get("TargetGroupId") <NEW_LINE> self.RequestId = params.get("RequestId") | CreateTargetGroup response structure.
| 6259907ffff4ab517ebcf2b0 |
class LocalizedApplication(aiohttp.web.Application): <NEW_LINE> <INDENT> async def _handle(self, request): <NEW_LINE> <INDENT> language = request.path.split('/')[1] <NEW_LINE> if language not in settings.I18N_LANGUAGES: <NEW_LINE> <INDENT> language = settings.I18N_PRIMARY_LANGUAGE <NEW_LINE> <DEDENT> url = str(request.rel_url).replace('/%s' % language, '') <NEW_LINE> new_request = request.clone(rel_url=url) <NEW_LINE> new_request.locale = i18n.get(language) <NEW_LINE> new_request.language = language <NEW_LINE> return await super()._handle(new_request) | Special version of the :see:aiohttp application
that overrides the handler and takes care of extracting
the preferred language from the URL.
This applies to URLs such as:
/ro/about
/en/about | 6259907f4a966d76dd5f097f |
class ProxySurface: <NEW_LINE> <INDENT> def __init__(self, parent, rect, real_surface, offset=(0, 0)): <NEW_LINE> <INDENT> self.offset = offset <NEW_LINE> self.x = self.y = 0 <NEW_LINE> if rect[0] < 0: self.x = rect[0] <NEW_LINE> if rect[1] < 0: self.y = rect[1] <NEW_LINE> self.real_surface = real_surface <NEW_LINE> if real_surface == None: <NEW_LINE> <INDENT> self.mysubsurface = parent.mysubsurface.subsurface(parent.mysubsurface.get_rect().clip(rect)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mysubsurface = real_surface.subsurface(real_surface.get_rect().clip(rect)) <NEW_LINE> <DEDENT> rect[0], rect[1] = 0, 0 <NEW_LINE> self.rect = rect <NEW_LINE> <DEDENT> def blit(self, s, pos, rect=None): <NEW_LINE> <INDENT> if rect == None: rect = s.get_rect() <NEW_LINE> pos = (pos[0] + self.offset[0] + self.x, pos[1] + self.offset[1] + self.y) <NEW_LINE> self.mysubsurface.blit(s, pos, rect) <NEW_LINE> <DEDENT> def subsurface(self, rect): return ProxySurface(self, pygame.Rect(rect).move(self.offset[0] + self.x, self.offset[1] + self.y),self.real_surface) <NEW_LINE> def fill(self, color, rect=None): <NEW_LINE> <INDENT> if rect != None: self.mysubsurface.fill(color, rect) <NEW_LINE> else: self.mysubsurface.fill(color) <NEW_LINE> <DEDENT> def get_rect(self): return self.rect <NEW_LINE> def get_width(self): return self.rect[2] <NEW_LINE> def get_height(self): return self.rect[3] <NEW_LINE> def get_abs_offset(): return self.rect[:2] <NEW_LINE> def get_abs_parent(): return self.mysubsurface.get_abs_parent() <NEW_LINE> def set_clip(self, rect=None): <NEW_LINE> <INDENT> if rect == None: self.mysubsurface.set_clip() <NEW_LINE> else: <NEW_LINE> <INDENT> rect = [rect[0] + self.offset[0] + self.x, rect[1] + self.offset[0] + self.y, rect[2], rect[3]] <NEW_LINE> self.mysubsurface.set_clip(rect) | A surface-like object which smartly handle out-of-area blitting.
<pre>ProxySurface(parent, rect, real_surface=None, offset=(0, 0))</pre>
<p>only one of parent and real_surface should be supplied (non None)</p>
<dl>
<dt>parent<dd>a ProxySurface object
<dt>real_surface<dd>a pygame Surface object
</dl>
<strong>Variables</strong>
<dl>
<dt>mysubsurface<dd>a real and valid pygame.Surface object to be used
for blitting.
<dt>x, y<dd>if the proxy surface is lefter or higher than the parent,
x, y hold the diffs.
<dt>offset<dd>an optional feature which let you scroll the whole blitted
content.
</dl> | 6259907f5fdd1c0f98e5fa18 |
class SearchView(ListView): <NEW_LINE> <INDENT> template_name = "admin/admin_products.html" <NEW_LINE> context_object_name = 'products' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> query = self.request.GET.get('q') <NEW_LINE> if query: <NEW_LINE> <INDENT> return Product.objects.filter(name__icontains=query) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Product.objects.all() | Admin search view | 6259907f099cdd3c63676146 |
class NoteTranslator(EntityTranslator): <NEW_LINE> <INDENT> def __init__(self, session=None): <NEW_LINE> <INDENT> EntityTranslator.__init__(self, session) <NEW_LINE> self.register('project', convert_project) <NEW_LINE> self.register('user', convert_user) <NEW_LINE> self.register('addressings_to', convert_recipients) <NEW_LINE> self.register('addressings_cc', convert_recipients) <NEW_LINE> self.register('note_links', convert_links) <NEW_LINE> self.register('custom_entity10_sg_notes_custom_entity10s', convert_links) | Note property translator.
Assigning this translator to a Note model will cause inbound property values to be converted.
.. versionadded:: v00_02_00
.. versionchanged:: v00_03_00
Removed obsolete internal conversion methods, update to support grenade.common.translator.Translator
changes.
.. versionchanged:: v00_04_00
Inherit from the grenade.translators.entity.EntityTranslator to gain access to standard Shotgun entity translation behaviour | 6259907f3617ad0b5ee07be8 |
class Objective(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Objective, self).__init__() <NEW_LINE> self.radius = settings.OBJECTIVE_RADIUS <NEW_LINE> r = self.radius <NEW_LINE> self.image = pygame.Surface((r*2, r*2), pygame.SRCALPHA) <NEW_LINE> pygame.draw.circle(self.image, colors.GREEN, (r, r), r, 0) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.image = self.image.convert_alpha() <NEW_LINE> self.rect.x = random.randrange(settings.SCREEN_SIZE[0]) <NEW_LINE> self.rect.y = random.randrange(settings.SCREEN_SIZE[1]) | The objective of the game is to reach this | 6259907fbf627c535bcb2f6a |
class ModuleConfigWizardOther(ModelView): <NEW_LINE> <INDENT> __name__ = 'ir.module.config_wizard.other' <NEW_LINE> percentage = fields.Float('Percentage', readonly=True) <NEW_LINE> @staticmethod <NEW_LINE> def default_percentage(): <NEW_LINE> <INDENT> pool = Pool() <NEW_LINE> Item = pool.get('ir.module.config_wizard.item') <NEW_LINE> done = Item.search([ ('state', '=', 'done'), ], count=True) <NEW_LINE> all = Item.search([], count=True) <NEW_LINE> return done / all | Module Config Wizard Other | 6259907f7cff6e4e811b74da |
class UserAborted(Exception): <NEW_LINE> <INDENT> pass | User aborted by pressing the Stop button
on the main window's toolbar. | 6259907f23849d37ff852b53 |
class News: <NEW_LINE> <INDENT> def __init__(self,source,author,title,description,url,urlToImage,publishedAt,content,category,country,language): <NEW_LINE> <INDENT> self.source =source <NEW_LINE> self.author = author <NEW_LINE> self.title = title <NEW_LINE> self.description = description <NEW_LINE> self.url = url <NEW_LINE> self.urlToImage = urlToImage <NEW_LINE> self.publishedAt = publishedAt <NEW_LINE> self.content = content <NEW_LINE> self.category = category <NEW_LINE> self.country = country <NEW_LINE> self.language = language | news class to define news Objects | 6259907f63b5f9789fe86c02 |
class FileFilter(object): <NEW_LINE> <INDENT> def __init__(self, *filenames): <NEW_LINE> <INDENT> self.filenames = filenames <NEW_LINE> <DEDENT> def filter(self, regex, repl, **kwargs): <NEW_LINE> <INDENT> return filter_file(regex, repl, *self.filenames, **kwargs) | Convenience class for calling ``filter_file`` a lot. | 6259907f76e4537e8c3f101a |
class WallboxSensor(CoordinatorEntity, Entity): <NEW_LINE> <INDENT> def __init__(self, coordinator, idx, ent, config): <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self._properties = CONF_SENSOR_TYPES[ent] <NEW_LINE> self._name = f"{config.title} {self._properties[CONF_NAME]}" <NEW_LINE> self._icon = self._properties[CONF_ICON] <NEW_LINE> self._unit = self._properties[CONF_UNIT_OF_MEASUREMENT] <NEW_LINE> self._ent = ent <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self.coordinator.data[self._ent] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return self._unit <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self._icon | Representation of the Wallbox portal. | 6259907f4f88993c371f126f |
class ZmqREPConnection(ZmqConnection): <NEW_LINE> <INDENT> socketType = constants.ROUTER <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._routingInfo = {} <NEW_LINE> ZmqConnection.__init__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def reply(self, messageId, *messageParts): <NEW_LINE> <INDENT> routingInfo = self._routingInfo.pop(messageId) <NEW_LINE> self.send(routingInfo + [messageId, b''] + list(messageParts)) <NEW_LINE> <DEDENT> def messageReceived(self, message): <NEW_LINE> <INDENT> i = message.index(b'') <NEW_LINE> assert i > 0 <NEW_LINE> (routingInfo, msgId, payload) = ( message[:i - 1], message[i - 1], message[i + 1:]) <NEW_LINE> msgParts = payload[0:] <NEW_LINE> self._routingInfo[msgId] = routingInfo <NEW_LINE> self.gotMessage(msgId, *msgParts) <NEW_LINE> <DEDENT> def gotMessage(self, messageId, *messageParts): <NEW_LINE> <INDENT> raise NotImplementedError(self) | A Reply ZeroMQ connection.
This is implemented with an underlying ROUTER socket, but the semantics
are close to REP socket. | 6259907f4a966d76dd5f0981 |
class BaseKernel(object): <NEW_LINE> <INDENT> def __init__(self, x_rank, ydim=1.): <NEW_LINE> <INDENT> self.xrank_ = theano.shared(x_rank) <NEW_LINE> self.ydim_ = ydim <NEW_LINE> <DEDENT> def build_result(self, X1, X2): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_params(self): <NEW_LINE> <INDENT> raise NotImplementedError | Abstract base class for kernel implementations in theano.
A kernel function by definition, computes the inner product
of two data points in a transformed space. Each class
is defined by some underlying kernel function, but is designed
to operate on complete data sets, not individual pairs of
data points. Thus, the output is the complete kernel matrix made
up of evaluations of the kernel function on every pair of data
points in the input data sets. That is, if the input data
sets are X1=[x11, ... x1N] and X2=[x21,...x2N], and the
underlying kernel function is k(x, x'), then the output
from these classes is
K(X1, X2) = [[k(x11, x21),...k(x1N, x21)]
,..., ,..., ,...,
[k(x11, x2M),...,k(x1N, x2M)]]
This is implemented in the 'build_result' function of every class.
This matrix represents the covariance matrix of a Gaussian Process
defined on the input space. If this Gaussian Process is scalar-valued
(the usual case), then the kernel function will also be scalar-valued.
However, if the GP is vector-valued, with dimensionality d, then the
kernel function is matrix-valued (where each output is shape d x d)
and the total kernel matrix will be a block matrix of size Nd x Md.
Additionally, 'build_result' constructs a symbolic
expression for the above equation, within the theano framework.
Thus build_result takes as input two symbolic theano tensors and
any required parameters are theano shared variables.
This base class simply enforces the existence of 'build_result'
and a 'get_params' function, which should return the relevant
parameters for the kernel. This class is truly abstract, and will
raise a NotImplementedError if one attempts to instantiate it.
The initializing argument x_rank and associated member variable xrank_
simply sets the rank of the tensors that are input to build_result.
This is mostly used as a check for classes that use this kernel.
It also contains an optional argument, ydim, that sets the dimensionality
of the Gaussian Process this kernel describes. This is usually 1 (for a
scalar-valued GP), but in some cases can be greater than 1.
Args:
x_rank (int): rank of the input tensor
ydim (int): dimensionality of the GP this kernel models
Attributes:
xrank_ (theano shared int): rank of the input tensor
ydim_ (int): dimensionality of the GP this kernel models | 6259907f442bda511e95daa4 |
class SocketCommunicator(rosebot.communicator.Communicator): <NEW_LINE> <INDENT> def __init__(self, address, connect=True, wait_for_acknowledgement=True, send_acknowledgement=False, is_debug=False): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.read_buffer_size = 4096 <NEW_LINE> self.bytes_read_but_not_yet_returned = bytearray() <NEW_LINE> super().__init__(connect=connect, wait_for_acknowledgement=wait_for_acknowledgement, send_acknowledgement=send_acknowledgement, is_debug=is_debug) <NEW_LINE> <DEDENT> def establish_connection(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print(self.address) <NEW_LINE> self.socket_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self.socket_connection.connect((self.address, 2000)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> time.sleep(1) <NEW_LINE> bytes_read = self.socket_connection.recv(self.read_buffer_size) <NEW_LINE> print('Initial bytes read:', bytes_read) <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> return self.socket_connection.shutdown(socket.SHUT_RDWR) <NEW_LINE> <DEDENT> def send_bytes(self, bytes_to_send): <NEW_LINE> <INDENT> self.socket_connection.sendall(bytes_to_send) <NEW_LINE> return len(bytes_to_send) <NEW_LINE> <DEDENT> def receive_bytes(self, number_of_bytes_to_return=1): <NEW_LINE> <INDENT> num_bytes = number_of_bytes_to_return <NEW_LINE> while True: <NEW_LINE> <INDENT> if self.is_debug: <NEW_LINE> <INDENT> print('bytes in buffer:', self.bytes_read_but_not_yet_returned) <NEW_LINE> <DEDENT> if len(self.bytes_read_but_not_yet_returned) >= num_bytes: <NEW_LINE> <INDENT> result = self.bytes_read_but_not_yet_returned[:num_bytes] <NEW_LINE> self.bytes_read_but_not_yet_returned = self.bytes_read_but_not_yet_returned[num_bytes:] <NEW_LINE> break <NEW_LINE> <DEDENT> bytes_read = self.socket_connection.recv(self.read_buffer_size) <NEW_LINE> if self.is_debug: <NEW_LINE> <INDENT> print('bytes read:', bytes_read) <NEW_LINE> <DEDENT> self.bytes_read_but_not_yet_returned += bytes_read <NEW_LINE> <DEDENT> if self.is_debug: <NEW_LINE> <INDENT> print('result:', result) <NEW_LINE> <DEDENT> if len(result) == 1: <NEW_LINE> <INDENT> return int(result[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result | Uses a socket to send and receive messages to/from the robot
| 6259907f7cff6e4e811b74dc |
class KeywordsWidget(forms.MultiWidget): <NEW_LINE> <INDENT> class Media: <NEW_LINE> <INDENT> js = content_media_urls("js/jquery-1.4.4.min.js", "js/keywords_field.js") <NEW_LINE> <DEDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> widgets = (forms.HiddenInput, forms.TextInput(attrs={"class": "vTextField"})) <NEW_LINE> super(KeywordsWidget, self).__init__(widgets, attrs) <NEW_LINE> self._ids = [] <NEW_LINE> <DEDENT> def decompress(self, value): <NEW_LINE> <INDENT> if hasattr(value, "select_related"): <NEW_LINE> <INDENT> keywords = [a.keyword for a in value.select_related("keyword")] <NEW_LINE> if keywords: <NEW_LINE> <INDENT> keywords = [(str(k.id), k.title) for k in keywords] <NEW_LINE> self._ids, words = zip(*keywords) <NEW_LINE> return (",".join(self._ids), ", ".join(words)) <NEW_LINE> <DEDENT> <DEDENT> return ("", "") <NEW_LINE> <DEDENT> def format_output(self, rendered_widgets): <NEW_LINE> <INDENT> rendered = super(KeywordsWidget, self).format_output(rendered_widgets) <NEW_LINE> links = "" <NEW_LINE> for keyword in Keyword.objects.all().order_by("title"): <NEW_LINE> <INDENT> prefix = "+" if str(keyword.id) not in self._ids else "-" <NEW_LINE> links += ("<a href='#'>%s%s</a>" % (prefix, unicode(keyword))) <NEW_LINE> <DEDENT> rendered += mark_safe("<p class='keywords-field'>%s</p>" % links) <NEW_LINE> return rendered <NEW_LINE> <DEDENT> def value_from_datadict(self, data, files, name): <NEW_LINE> <INDENT> return data.get("%s_0" % name, "") | Form field for the ``KeywordsField`` generic relation field. Since
the admin with model forms has no form field for generic
relations, this form field provides a single field for managing
the keywords. It contains two actual widgets, a text input for
entering keywords, and a hidden input that stores the ID of each
``Keyword`` instance.
The attached JavaScript adds behaviour so that when the form is
submitted, an AJAX post is made that passes the list of keywords
in the text input, and returns a list of keyword IDs which are
then entered into the hidden input before the form submits. The
list of IDs in the hidden input is what is used when retrieving
an actual value from the field for the form. | 6259907f7d847024c075de79 |
class CertificateValidationError(CertificateException): <NEW_LINE> <INDENT> pass | An exception raised when certificate information is invalid. | 6259907f4527f215b58eb6ee |
class InboxMailList(JsonView): <NEW_LINE> <INDENT> @check_inbox <NEW_LINE> def prepare_context(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.inbox: <NEW_LINE> <INDENT> mails = Mail.objects.get_inbox_mails(request.inbox) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mails = Mail.objects.get_user_mails(request.user) <NEW_LINE> <DEDENT> from_date = request.GET.get('from_date') <NEW_LINE> if from_date: <NEW_LINE> <INDENT> mails = mails.filter(date__gt=from_date) <NEW_LINE> <DEDENT> count = request.GET.get('count', 50) <NEW_LINE> if count and count != 'all': <NEW_LINE> <INDENT> mails = mails[:count] <NEW_LINE> <DEDENT> prepare_mail_data = lambda mail: { 'subject': mail.subject, 'from_email': mail.from_email_pretty, 'to_email': mail.to_email, 'date': mail.date.strftime('%Y-%m-%d %H:%M:%S'), 'readed': mail.is_readed(request.user), 'few_lines': mail.few_lines, 'url': reverse('mail-json', args=(mail.id,)) } <NEW_LINE> return {'mails': map(prepare_mail_data, mails)} | Returns mails for inbox or for all inboxes in json format. | 6259907f4a966d76dd5f0983 |
class TransactionIndexable(object): <NEW_LINE> <INDENT> @indexed(LongFieldType(stored=True), attr_query_name="tx_state") <NEW_LINE> def idx_tx_state(self): <NEW_LINE> <INDENT> return 0 | Internal fields to temporaty index documents that have been committed
to model index mid transaction | 6259907f97e22403b383c99d |
class TemplateState(MegaState): <NEW_LINE> <INDENT> def __init__(self, Candidate): <NEW_LINE> <INDENT> StateA = Candidate.state_a <NEW_LINE> StateB = Candidate.state_b <NEW_LINE> transition_map, target_scheme_n = combine_maps(StateA.transition_map, StateB.transition_map) <NEW_LINE> ski_db = StateKeyIndexDB(StateA.state_index_sequence() + StateB.state_index_sequence()) <NEW_LINE> MegaState.__init__(self, index.get(), transition_map, ski_db) <NEW_LINE> self.uniform_entry_CommandList = UniformObject.from_iterable(( StateA.uniform_entry_CommandList, StateB.uniform_entry_CommandList)) <NEW_LINE> self.__target_scheme_n = target_scheme_n <NEW_LINE> self.__engine_type = None <NEW_LINE> MegaState.bad_company_set(self, StateA.bad_company().union(StateB.bad_company())) <NEW_LINE> <DEDENT> def _finalize_entry_CommandLists(self): <NEW_LINE> <INDENT> for state_index in self.ski_db.implemented_state_index_set: <NEW_LINE> <INDENT> state_key = self.ski_db.map_state_index_to_state_key(state_index) <NEW_LINE> self.entry.action_db_update(From = state_index, To = state_index, FromOutsideCmd = TemplateStateKeySet(state_key), FromInsideCmd = None) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def _finalize_content(self, TheAnalyzer): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def target_scheme_n(self): <NEW_LINE> <INDENT> return self.__target_scheme_n <NEW_LINE> <DEDENT> def _get_target_by_state_key(self, Begin, End, TargetScheme, StateKey): <NEW_LINE> <INDENT> return TargetScheme.get_door_id_by_state_key(StateKey) <NEW_LINE> <DEDENT> def _assert_consistency(self, CompressionType, RemainingStateIndexSet, TheAnalyzer): <NEW_LINE> <INDENT> pass | _________________________________________________________________________
Implements multiple AnalyzerState-s in one single state. Its transition
map, its entry and drop-out sections function are based on a 'state_key'.
That is, when a 'state_key' of an implemented AnalyzerState is set, the
transition map, the entry and drop-out sections act the same as the
correspondent sections in the original AnalyzerState.
____________________________________________________________________________ | 6259907ff548e778e596d02f |
class AttrDict(dict): <NEW_LINE> <INDENT> def __init__(self, other=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if other is not None: <NEW_LINE> <INDENT> for key, value in other.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self[key] = AttrDict(value) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self[key] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def nested_update(self, other): <NEW_LINE> <INDENT> for key, value in other.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self[key].nested_update(value) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self[key] = value <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> __getattr__ = dict.__getitem__ <NEW_LINE> __setattr__ = dict.__setitem__ | Defines an attribute dictionary that allows the user to address keys as
if they were attributes.
`AttrDict` inherits from `dict`, so it can be used everywhere where `dict` is expected.
The __init__ constructs an empty `AttrDict` or recursively initialises an `AttrDict`
from a (maybe nested) `dict`.
Args:
other (dict): Either dictionary (can be nested) to initialise an `AttrDict` from
or None to construct an empty `AttrDict`. | 6259907f55399d3f05627fb1 |
class WPConfirmEPaymentSkipjack( conferences.WPConferenceDefaultDisplayBase ): <NEW_LINE> <INDENT> def __init__( self, rh, conf, reg ): <NEW_LINE> <INDENT> conferences.WPConferenceDefaultDisplayBase.__init__(self, rh, conf) <NEW_LINE> self._registrant = reg <NEW_LINE> <DEDENT> def _getBody( self, params ): <NEW_LINE> <INDENT> wc = WConfirmEPaymentSkipjack( self._conf, self._registrant) <NEW_LINE> <DEDENT> def _defineSectionMenu( self ): <NEW_LINE> <INDENT> conferences.WPConferenceDefaultDisplayBase._defindeSectionMenu(self) <NEW_LINE> self._sectionMenu.setCurrentItem(self._regFormOpt) | Confirmation page for Skipjack callback | 6259907f4428ac0f6e659fcc |
class Literal(Expression): <NEW_LINE> <INDENT> def __new__(cls, term): <NEW_LINE> <INDENT> if term == None: <NEW_LINE> <INDENT> return NULL <NEW_LINE> <DEDENT> if term is True: <NEW_LINE> <INDENT> return TRUE <NEW_LINE> <DEDENT> if term is False: <NEW_LINE> <INDENT> return FALSE <NEW_LINE> <DEDENT> if is_data(term) and term.get("date"): <NEW_LINE> <INDENT> return cls.lang[DateOp(term.get("date"))] <NEW_LINE> <DEDENT> return object.__new__(cls) <NEW_LINE> <DEDENT> def __init__(self, value): <NEW_LINE> <INDENT> Expression.__init__(self, None) <NEW_LINE> self.simplified = True <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def define(cls, expr): <NEW_LINE> <INDENT> return Literal(expr.get("literal")) <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if other == None: <NEW_LINE> <INDENT> if self._value == None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> elif self._value == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if is_literal(other): <NEW_LINE> <INDENT> return (self._value == other._value) or (self.json == other.json) <NEW_LINE> <DEDENT> <DEDENT> def __data__(self): <NEW_LINE> <INDENT> return {"literal": self.value} <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @property <NEW_LINE> def json(self): <NEW_LINE> <INDENT> if self._value == "": <NEW_LINE> <INDENT> self._json = '""' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._json = value2json(self._value) <NEW_LINE> <DEDENT> return self._json <NEW_LINE> <DEDENT> def vars(self): <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> def map(self, map_): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def missing(self): <NEW_LINE> <INDENT> if self._value in [None, Null]: <NEW_LINE> <INDENT> return TRUE <NEW_LINE> <DEDENT> if self.value == "": <NEW_LINE> <INDENT> return TRUE <NEW_LINE> <DEDENT> return FALSE <NEW_LINE> <DEDENT> def __call__(self, row=None, rownum=None, rows=None): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self._json <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self._json) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return python_type_to_json_type[self._value.__class__] <NEW_LINE> <DEDENT> @simplified <NEW_LINE> def partial_eval(self): <NEW_LINE> <INDENT> return self | A literal JSON document | 6259907fbe7bc26dc9252ba4 |
class IperfClientConstants(object): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> options = ('udp', 'bandwidth', 'dualtest', 'num', 'tradeoff', 'time', 'fileinput', 'stdin', 'listenport', 'parallel', 'ttl') <NEW_LINE> bandwidth = '_bandwidth' <NEW_LINE> num = '_num' <NEW_LINE> tradeoff = '_tradeoff' <NEW_LINE> time = '_time' <NEW_LINE> stdin = '_stdin' <NEW_LINE> listenport = '_listenport' <NEW_LINE> parallel = '_parallel' <NEW_LINE> ttl = '_ttl' | Constants for the IperfClientSettings | 6259907f5fc7496912d48fba |
class Student: <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self, attrs=None): <NEW_LINE> <INDENT> if attrs is not None: <NEW_LINE> <INDENT> listLatt = [x for x in attrs if x in list(self.__dict__.keys())] <NEW_LINE> try: <NEW_LINE> <INDENT> return self.__dict__[listLatt] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self.__dict__ | Student class
| 6259907f7d847024c075de7b |
class ReceptiveFieldsConverter(Converter): <NEW_LINE> <INDENT> def __init__(self, sigma2, max_x, n_fields, k_round): <NEW_LINE> <INDENT> self.sigma2 = sigma2 <NEW_LINE> self.max_x = max_x <NEW_LINE> self.n_fields = n_fields <NEW_LINE> self.k_round = k_round <NEW_LINE> <DEDENT> def convert(self, x, y): <NEW_LINE> <INDENT> def get_gaussian(x, sigma2, mu): <NEW_LINE> <INDENT> return (1 / np.sqrt(2 * sigma2 * np.pi)) * np.e ** (- (x - mu) ** 2 / (2 * sigma2)) <NEW_LINE> <DEDENT> output = {'input': [], 'class': []} <NEW_LINE> h_mu = self.max_x / (self.n_fields - 1) <NEW_LINE> max_y = np.round(get_gaussian(h_mu, self.sigma2, h_mu), 0) <NEW_LINE> mu = np.tile(np.linspace(0, self.max_x, self.n_fields), len(x[0])) <NEW_LINE> X = np.repeat(x, self.n_fields, axis=1) <NEW_LINE> assert len(mu) == len(X[0]) <NEW_LINE> X = max_y - np.round(get_gaussian(X, self.sigma2, mu), self.k_round) <NEW_LINE> output = {'input': X.reshape(X.shape[0], X.shape[1], 1), 'class': y} <NEW_LINE> return output | Class for receptive fields data conversion | 6259907f92d797404e3898ab |
class LabelledLoader(): <NEW_LINE> <INDENT> def __init__(self, array_module): <NEW_LINE> <INDENT> self.xp = array_module <NEW_LINE> self.device = None <NEW_LINE> self.workers = {} <NEW_LINE> self.sources = {} <NEW_LINE> <DEDENT> def get_samples(self, data_dir): <NEW_LINE> <INDENT> for d in os.listdir(data_dir): <NEW_LINE> <INDENT> path = os.path.join(data_dir, d) <NEW_LINE> if not os.path.isdir(path): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> files = os.listdir(path) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> if '.png' in f: <NEW_LINE> <INDENT> yield (d, os.path.join(path, f)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_samples_forgeries(self, data_dir, user=''): <NEW_LINE> <INDENT> for d in os.listdir(data_dir): <NEW_LINE> <INDENT> path = os.path.join(data_dir, d) <NEW_LINE> classes = os.listdir(path) <NEW_LINE> for c in classes: <NEW_LINE> <INDENT> cpath = os.path.join(path, c) <NEW_LINE> if not os.path.isdir(cpath): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not user in c: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> files = os.listdir(cpath) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> if '.png' in f: <NEW_LINE> <INDENT> yield (int('Forged' in cpath), os.path.join(cpath, f)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_samples_dedicated_forgery(self, data_dir): <NEW_LINE> <INDENT> for d in os.listdir(data_dir): <NEW_LINE> <INDENT> path = os.path.join(data_dir, d) <NEW_LINE> classes = os.listdir(path) <NEW_LINE> for c in classes: <NEW_LINE> <INDENT> cpath = os.path.join(path, c) <NEW_LINE> if not os.path.isdir(cpath): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> files = os.listdir(cpath) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> if '.png' in f: <NEW_LINE> <INDENT> label = 0 if 'Forged' in cpath else c <NEW_LINE> yield (label, os.path.join(cpath, f)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def create_sources(self, data_dir, batchsize, split=0.9): <NEW_LINE> <INDENT> samples = list(self.get_samples_forgeries(data_dir)) <NEW_LINE> np.random.shuffle(samples) <NEW_LINE> num_train_samples = int(len(samples) * split) <NEW_LINE> train_samples = samples[:num_train_samples] <NEW_LINE> test_samples = samples[num_train_samples:] <NEW_LINE> self.create_source("train", train_samples, batchsize) <NEW_LINE> self.create_source("test", test_samples, batchsize) <NEW_LINE> <DEDENT> def create_source(self, name, data, bs): <NEW_LINE> <INDENT> self.sources[name] = queue.Queue(QUEUE_SIZE) <NEW_LINE> worker = DataProvider(self.sources[name], data, bs, self.xp, self.device) <NEW_LINE> self.workers[name] = worker <NEW_LINE> worker.start() <NEW_LINE> <DEDENT> def get_batch(self, source_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.sources[source_name].get(timeout=1) <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def use_device(self, device_id): <NEW_LINE> <INDENT> self.device = device_id | A Data Loader that provides batches of data with corresponding labels
for classification. | 6259907f5166f23b2e244e76 |
class HttpBackend(pymatrix.backend.base.BackendBase): <NEW_LINE> <INDENT> _session = None <NEW_LINE> _hostname = None <NEW_LINE> _port = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._session = None <NEW_LINE> <DEDENT> async def connect( self, hostname, port): <NEW_LINE> <INDENT> if(self._session is not None): <NEW_LINE> <INDENT> await self.disconnect() <NEW_LINE> self.hostname = None <NEW_LINE> self._port = None <NEW_LINE> <DEDENT> real_port = port <NEW_LINE> if(real_port is None): <NEW_LINE> <INDENT> real_port = pymatrix.backend.base.DEFAULT_MARIX_PORT <NEW_LINE> <DEDENT> self._session = aiohttp.ClientSession() <NEW_LINE> self._hostname = hostname <NEW_LINE> self._port = real_port <NEW_LINE> <DEDENT> async def disconnect(self): <NEW_LINE> <INDENT> await self._session.close() <NEW_LINE> self._session = None <NEW_LINE> <DEDENT> async def write_event(self, message: RestMessage): <NEW_LINE> <INDENT> response = await self._session.request( method=message.method, url="http://{hostname}:{port}{url}".format( hostname=self._hostname, port=self._port, url=message.url), json=message.body, headers=message.headers ) <NEW_LINE> return_response = Response(await response.json(), True if response.status >= 400 else False) <NEW_LINE> return return_response <NEW_LINE> <DEDENT> async def read_events(self): <NEW_LINE> <INDENT> pass | A HTTP backend | 6259907f7047854f46340e54 |
class ContactPhoneSerializer(ContactAssociationSerializer): <NEW_LINE> <INDENT> class Meta(ContactAssociationSerializer.Meta): <NEW_LINE> <INDENT> model = models.ContactPhone <NEW_LINE> fields = ContactAssociationSerializer.Meta.fields + ( "phone", "phone_type") | ContactPhone model serializer class. | 6259907f091ae356687066de |
class ManagerTestBase(DatabaseTestBase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(ManagerTestBase, self).setUp() <NEW_LINE> self.manager = APIManager(self.flaskapp, session=self.session) | Base class for tests that use a SQLAlchemy database and an
:class:`flask_restless.APIManager`.
The :class:`flask_restless.APIManager` is accessible at ``self.manager``. | 6259907f3346ee7daa3383b1 |
class Acceptor (essential.Acceptor): <NEW_LINE> <INDENT> pending_promise = None <NEW_LINE> pending_accepted = None <NEW_LINE> active = True <NEW_LINE> @property <NEW_LINE> def persistance_required(self): <NEW_LINE> <INDENT> return self.pending_promise is not None or self.pending_accepted is not None <NEW_LINE> <DEDENT> def recover(self, promised_id, accepted_id, accepted_value): <NEW_LINE> <INDENT> self.promised_id = promised_id <NEW_LINE> self.accepted_id = accepted_id <NEW_LINE> self.accepted_value = accepted_value <NEW_LINE> <DEDENT> def recv_prepare(self, from_uid, proposal_id): <NEW_LINE> <INDENT> if proposal_id == self.promised_id: <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> self.messenger.send_promise(from_uid, proposal_id, self.accepted_id, self.accepted_value) <NEW_LINE> <DEDENT> <DEDENT> elif proposal_id > self.promised_id: <NEW_LINE> <INDENT> if self.pending_promise is None: <NEW_LINE> <INDENT> self.promised_id = proposal_id <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self.pending_promise = from_uid <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> self.messenger.send_prepare_nack(from_uid, proposal_id, self.promised_id) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def recv_accept_request(self, from_uid, proposal_id, value): <NEW_LINE> <INDENT> if proposal_id == self.accepted_id and value == self.accepted_value: <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> self.messenger.send_accepted(proposal_id, value) <NEW_LINE> <DEDENT> <DEDENT> elif proposal_id >= self.promised_id: <NEW_LINE> <INDENT> if self.pending_accepted is None: <NEW_LINE> <INDENT> self.promised_id = proposal_id <NEW_LINE> self.accepted_value = value <NEW_LINE> self.accepted_id = proposal_id <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self.pending_accepted = from_uid <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> self.messenger.send_accept_nack(from_uid, proposal_id, self.promised_id) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def persisted(self): <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> if self.pending_promise: <NEW_LINE> <INDENT> self.messenger.send_promise(self.pending_promise, self.promised_id, self.accepted_id, self.accepted_value) <NEW_LINE> <DEDENT> if self.pending_accepted: <NEW_LINE> <INDENT> self.messenger.send_accepted(self.accepted_id, self.accepted_value) <NEW_LINE> <DEDENT> <DEDENT> self.pending_promise = None <NEW_LINE> self.pending_accepted = None | Acceptors act as the fault-tolerant memory for Paxos. To ensure correctness
in the presence of failure, Acceptors must be able to remember the promises
they've made even in the event of power outages. Consequently, any changes
to the promised_id, accepted_id, and/or accepted_value must be persisted to
stable media prior to sending promise and accepted messages. After calling
the recv_prepare() and recv_accept_request(), the property
'persistence_required' should be checked to see if persistence is required.
Note that because Paxos permits any combination of dropped packets, not
every promise/accepted message needs to be sent. This implementation only
responds to the first prepare/accept_request message received and ignores
all others until the Acceptor's values are persisted to stable media (which
is typically a slow process). After saving the promised_id, accepted_id,
and accepted_value variables, the "persisted" method must be called to send
the pending promise and/or accepted messages.
The 'active' attribute is a boolean value indicating whether or not
the Acceptor should send outgoing messages (defaults to True). Setting
this attribute to false places the Acceptor in a "passive" mode where
it processes all incoming messages but drops all messages it would
otherwise send. | 6259907f32920d7e50bc7ae0 |
class Cost_ABC(MABS.UntrainableAbstraction_ABC, MABS.Apply_ABC) : <NEW_LINE> <INDENT> def __init__(self, reverse=False, streams=["test", "train"], **kwargs) : <NEW_LINE> <INDENT> super(Cost_ABC, self).__init__(streams=streams, **kwargs) <NEW_LINE> self.setHP("reverse", reverse) <NEW_LINE> <DEDENT> def logApply(self, layer, **kwargs) : <NEW_LINE> <INDENT> message = "Applying '%s' on layer '%s'" % (self.name, self.getHP('parameter'), layer.name) <NEW_LINE> if self.getHP("reverse") : <NEW_LINE> <INDENT> message += " (reverse)" <NEW_LINE> <DEDENT> self.logEvent(message) <NEW_LINE> <DEDENT> def apply(self, layer, targets, outputs, stream) : <NEW_LINE> <INDENT> if self.getHP("reverse") : <NEW_LINE> <INDENT> return -self.run(targets, outputs, stream) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return self.run(targets, outputs, stream) <NEW_LINE> <DEDENT> <DEDENT> def run(self, targets, outputs, stream) : <NEW_LINE> <INDENT> raise NotImplemented("Must be implemented in child") | This is the interface a Cost must expose. In order for the trainer/recorder to know which attributes are hyper-parameters,
this class must also include a list attribute **self.hyperParameters** containing the names of all attributes that must be considered
as hyper-parameters. | 6259907f71ff763f4b5e924b |
class ColorMap(Color): <NEW_LINE> <INDENT> def __init__(self, colormap=[ColorMapStep(0, Color(0, 0, 0)), ColorMapStep(1, Color(1, 1, 1))]): <NEW_LINE> <INDENT> super().__init__(r=colormap[0].color.r, g=colormap[0].color.g, b=colormap[0].color.b, a=colormap[0].color.a, name='color_map') <NEW_LINE> self.colormap = colormap <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "ColorMap(r={}, g={}, b={}, a={}, colormap={})".format(self.r, self.g, self.b, self.a, self.colormap) <NEW_LINE> <DEDENT> def map(self, value): <NEW_LINE> <INDENT> def interpolate(x0, y0, x1, y1, xv): <NEW_LINE> <INDENT> if (y0 == y1): <NEW_LINE> <INDENT> return y0 <NEW_LINE> <DEDENT> return y0 + (( (y1 - y0) / (x1 - x0) ) * (xv - x0)) <NEW_LINE> <DEDENT> if (value <= self.colormap[0].step): <NEW_LINE> <INDENT> self.set(self.colormap[0].color) <NEW_LINE> return <NEW_LINE> <DEDENT> if (value >= self.colormap[-1].step): <NEW_LINE> <INDENT> self.set(self.colormap[-1].color) <NEW_LINE> return <NEW_LINE> <DEDENT> m0 = self.colormap[0] <NEW_LINE> for m1 in self.colormap[1:]: <NEW_LINE> <INDENT> if (value == m1.step): <NEW_LINE> <INDENT> self.set(m1.color) <NEW_LINE> return <NEW_LINE> <DEDENT> if (value < m1.step): <NEW_LINE> <INDENT> self.r = interpolate(m0.step, m0.color.r, m1.step, m1.color.r, value) <NEW_LINE> self.g = interpolate(m0.step, m0.color.g, m1.step, m1.color.g, value) <NEW_LINE> self.b = interpolate(m0.step, m0.color.b, m1.step, m1.color.b, value) <NEW_LINE> self.a = interpolate(m0.step, m0.color.a, m1.step, m1.color.a, value) <NEW_LINE> return <NEW_LINE> <DEDENT> m0 = m1 | ColorMap is a special case of Color() that defines a linear color map, mapping a range to a color.
By convention I expect we will use the range (0,1) but any range is actually possible.
The map is defined as a list of ColorMapStep, which maps a value to a color.
If the value we map is between two ColorMapStep the linear interpolation is calculated.
The ColorMap is a Color object - you can set r, g, b and a just like any other Color object.
However, it is intended that the color is set using map(), which maps a value in the
defined range to a color.
e.g.:
# default color map is black to 100% white
cm = ColorMap()
# set bead.color to 43% gray
bead.color.set(cm.map(0.43))
Example colormap covering all possible RGB colors, with both 0 and 1 set to 100% blue:
[
ColorMapStep(step=0, color=Color(1, 0, 0)),
ColorMapStep(step=1/3, color=Color(0, 1, 0)),
ColorMapStep(step=2/3, color=Color(0, 0, 1)),
ColorMapStep(step=1, color=Color(1, 0, 0))
]
Alpha channel can also be defined in the colormap.
For example, to map a range from 100% transparent to 100% opaque, do this:
[
ColorMapStep(step=0, color=Color(0, 0, 0, 0)),
ColorMapStep(step=1, color=Color(0, 0, 0, 1))
] | 6259907f97e22403b383c99f |
class Batch(): <NEW_LINE> <INDENT> def __init__(self, src, trg=None, max_len=40): <NEW_LINE> <INDENT> self.src = src <NEW_LINE> length = [min(max_len, len(x))+2 for x in self.src] <NEW_LINE> self.src_mask = torch.zeros((len(length), max_len + 2)) <NEW_LINE> self.max_len = max_len <NEW_LINE> for i,j in enumerate(length): <NEW_LINE> <INDENT> self.src_mask[i,range(j)]=1 <NEW_LINE> <DEDENT> if trg is not None: <NEW_LINE> <INDENT> self.trg = trg <NEW_LINE> self.trg_mask = self.make_std_mask(self.trg, max_len) <NEW_LINE> self.ntokens = self.src_mask.data.sum() <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def make_std_mask(tgt, max_len): <NEW_LINE> <INDENT> length = [min(max_len, len(x))+1 for x in tgt] <NEW_LINE> tgt_mask = torch.zeros((len(length), max_len + 1)) <NEW_LINE> for i,j in enumerate(length): <NEW_LINE> <INDENT> tgt_mask[i,range(j)]=1 <NEW_LINE> <DEDENT> tgt_mask = tgt_mask & Variable( subsequent_mask(max_len + 1).type_as(tgt_mask.data)) <NEW_LINE> return tgt_mask | Object for holding a batch of data with mask during training. | 6259907faad79263cf430259 |
class ConfigDialog(BaseDialog): <NEW_LINE> <INDENT> DEFAULT_CHANNEL_STATES = [True] * 4 <NEW_LINE> DEFAULT_COINCIDENCE_STATES = [True] + [False] * 3 <NEW_LINE> DEFAULT_CHANNEL_VETO_STATES = [False] * 3 <NEW_LINE> def __init__(self, channel_states=DEFAULT_CHANNEL_STATES, coincidence_states=DEFAULT_COINCIDENCE_STATES, veto_enabled=False, channel_veto_states=DEFAULT_CHANNEL_VETO_STATES): <NEW_LINE> <INDENT> BaseDialog.__init__(self, "Channel Configuration") <NEW_LINE> checked_channels = [] <NEW_LINE> checked_coincidences = [] <NEW_LINE> checked_channel_vetos = [] <NEW_LINE> for _channel, checked in enumerate(channel_states): <NEW_LINE> <INDENT> if checked: <NEW_LINE> <INDENT> checked_channels.append(_channel) <NEW_LINE> <DEDENT> <DEDENT> for _coincidence, checked in enumerate(coincidence_states): <NEW_LINE> <INDENT> if checked: <NEW_LINE> <INDENT> checked_coincidences.append(_coincidence) <NEW_LINE> <DEDENT> <DEDENT> for _veto, checked in enumerate(channel_veto_states): <NEW_LINE> <INDENT> if checked: <NEW_LINE> <INDENT> checked_channel_vetos.append(_veto) <NEW_LINE> <DEDENT> <DEDENT> layout = QtGui.QGridLayout(self) <NEW_LINE> layout.addWidget( self.choice_group(label="Select Channel", object_name="channel_checkbox", checked_items=checked_channels, left=300), 0, 0) <NEW_LINE> layout.addWidget( self.choice_group(radio=True, label="Trigger Condition", object_name="coincidence_checkbox", checked_items=checked_coincidences, item_labels=["Single", "Twofold", "Threefold", "Fourfold"], left=20), 0, 1) <NEW_LINE> layout.addWidget( self.choice_group(radio=True, label="Veto", checkable=True, checked=veto_enabled, object_name="veto_checkbox", checked_items=checked_channel_vetos, item_labels=["Chan1", "Chan2", "Chan3"], left=180), 0, 2) <NEW_LINE> layout.addWidget(self.button_box(left=30, top=300), 1, 2, 1, 2) <NEW_LINE> self.show() | Dialog to set the configuration
:param channel_states: activation states of the channels
:type channel_states: list of bool
:param coincidence_states: coincidence states
:type coincidence_states: list of bool
:param veto_enabled: enable veto group
:type veto_enabled: bool
:param channel_veto_states: channel veto
:type channel_veto_states: list of bool | 6259907fa05bb46b3848be78 |
class FormSubmissionFile(models.Model): <NEW_LINE> <INDENT> submission = models.ForeignKey( "FormSubmission", verbose_name=_("Submission"), on_delete=models.CASCADE, related_name="files", ) <NEW_LINE> field = models.CharField(verbose_name=_("Field"), max_length=255) <NEW_LINE> file = models.FileField(verbose_name=_("File"), upload_to="streamforms/") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.file.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ["field", "file"] <NEW_LINE> verbose_name = _("Form submission file") <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self.file.url | Data for a form submission file. | 6259907fec188e330fdfa34a |
class FileDataHttpReplacement(object): <NEW_LINE> <INDENT> def __init__(self, cache=None, timeout=None): <NEW_LINE> <INDENT> self.hit_counter = {} <NEW_LINE> <DEDENT> def request(self, uri, method="GET", body=None, headers=None, redirections=5): <NEW_LINE> <INDENT> path = urlparse.urlparse(uri)[2] <NEW_LINE> fname = os.path.join(HTTP_SRC_DIR, path[1:]) <NEW_LINE> if not os.path.exists(fname): <NEW_LINE> <INDENT> index = self.hit_counter.get(fname, 1) <NEW_LINE> if os.path.exists(fname + "." + str(index)): <NEW_LINE> <INDENT> self.hit_counter[fname] = index + 1 <NEW_LINE> fname = fname + "." + str(index) <NEW_LINE> <DEDENT> <DEDENT> if os.path.exists(fname): <NEW_LINE> <INDENT> f = file(fname, "r") <NEW_LINE> response = message_from_file(f) <NEW_LINE> f.close() <NEW_LINE> body = response.get_payload() <NEW_LINE> response_headers = httplib2.Response(response) <NEW_LINE> return (response_headers, body) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (httplib2.Response({"status": "404"}), "") <NEW_LINE> <DEDENT> <DEDENT> def add_credentials(self, name, password): <NEW_LINE> <INDENT> pass | Build a stand-in for httplib2.Http that takes its
response headers and bodies from files on disk
http://bitworking.org/news/172/Test-stubbing-httplib2 | 6259907f23849d37ff852b59 |
class ListPhotoTagsResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) | A ResultSet with methods tailored to the values returned by the ListPhotoTags Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 6259907f4c3428357761bd5b |
class OriginType(StringChoice): <NEW_LINE> <INDENT> choices = [ 'hypocenter', 'centroid', 'amplitude', 'macroseismic', 'rupture start', 'rupture end'] | Describes the origin type. | 6259907f5166f23b2e244e78 |
class Component(Base): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> linked_subsystems = list() <NEW_LINE> material = None <NEW_LINE> volume = None <NEW_LINE> object_sort = 'Component' <NEW_LINE> @property <NEW_LINE> def mass(self): <NEW_LINE> <INDENT> return self.volume * self.material.density | Abstract Base Class for components. | 6259907fa8370b77170f1e71 |
class CRMConnection(AuthenticationContext): <NEW_LINE> <INDENT> default_headers = {'Content-Type': 'application/json; charset=utf-8', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0', 'Accept': 'application/json'} <NEW_LINE> api_query_stem = '/api/data/v9.0/' <NEW_LINE> _session = None <NEW_LINE> _debug = False <NEW_LINE> _affinity_reset = None <NEW_LINE> def __init__(self, tenant, Debug=False, AffinityReset=None): <NEW_LINE> <INDENT> self._session = requests.session() <NEW_LINE> self._debug = Debug <NEW_LINE> self._affinity_reset = AffinityReset <NEW_LINE> for i in self.default_headers: <NEW_LINE> <INDENT> self._session.headers.update({i:self.default_headers[i]}) <NEW_LINE> <DEDENT> super(CRMConnection, self).__init__(tenant) <NEW_LINE> <DEDENT> def Get(self, url, data=None): <NEW_LINE> <INDENT> return self._session.get(url, data=json.dumps(data)) <NEW_LINE> <DEDENT> def Post(self, url, data): <NEW_LINE> <INDENT> return self._session.post(url, data=json.dumps(data)) <NEW_LINE> <DEDENT> def Patch(self, url, data): <NEW_LINE> <INDENT> return self._session.patch(url, data=json.dumps(data)) <NEW_LINE> <DEDENT> def Delete(self, url, data=None): <NEW_LINE> <INDENT> return self._session.delete(url) <NEW_LINE> <DEDENT> def dump_affinity_token(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_authed(self): <NEW_LINE> <INDENT> if len(self.cache._cache) >= 1: <NEW_LINE> <INDENT> if not (datetime.strptime(self.get_auth_value('expiresOn'), '%Y-%m-%d %H:%M:%S.%f') < datetime.now()): <NEW_LINE> <INDENT> self.default_headers.update({'Authorization':'Bearer ' + self.get_auth_value('accessToken')}) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get_auth_value(self, val, item=0): <NEW_LINE> <INDENT> if len(self.cache._cache) >= 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return list(self.cache._cache.values())[item][val] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise AttributeError(f'{val} is not in the token cache. ' + f'Verify items: {list(list(self.cache._cache.values())[item].keys())}') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError(f'Have you forgotten to acquire a token?.') <NEW_LINE> <DEDENT> <DEDENT> def lazy_acquire_token_with_username_password(self, resource, username, password): <NEW_LINE> <INDENT> return super(CRMConnection, self).acquire_token_with_username_password(resource, username, password, '51f81489-12ee-4a9e-aaae-a2591f45987d') | Implements AuthenticationContext from Python Adal Library
Adds additional functionality for Executing Py365CE Request Classes | 6259907f32920d7e50bc7ae2 |
class BaseGeometry(SpatialReferenceMixin): <NEW_LINE> <INDENT> def dumps(self, **kwargs): <NEW_LINE> <INDENT> if 'ensure_ascii' not in kwargs: <NEW_LINE> <INDENT> kwargs['ensure_ascii'] = False <NEW_LINE> <DEDENT> return json.dumps(self.json, **kwargs) | base geometry obect | 6259907fad47b63b2c5a92f1 |
@unique <NEW_LINE> class Currency(Enum): <NEW_LINE> <INDENT> ALL = 'ALL' <NEW_LINE> USD = 'USD' <NEW_LINE> HKD = 'HKD' <NEW_LINE> CNH = 'CNH' <NEW_LINE> SGD = 'SGD' | Enum for currency | 6259907f7c178a314d78e93b |
class MissingTypeKeyError(Exception): <NEW_LINE> <INDENT> pass | A 'type' key is missing from the JSON | 6259907f7cff6e4e811b74e2 |
@final <NEW_LINE> class TooLongYieldTupleViolation(ASTViolation): <NEW_LINE> <INDENT> error_template = 'Found too long yield tuple: {0}' <NEW_LINE> code = 227 | Forbids to yield too long tuples.
Reasoning:
Long yield tuples complicate generator using.
This rule helps to reduce complication.
Solution:
Use lists of similar type or wrapper objects.
.. versionadded:: 0.10.0 | 6259907f4f6381625f19a1ff |
class PickleableObject(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def read(cls, path, store_path=False, create_if_error=False, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(path, 'rb') as f: <NEW_LINE> <INDENT> the_object = pickle.load(f) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if not create_if_error: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> the_object = cls(**kwargs) <NEW_LINE> the_object.write(path, store_path=store_path) <NEW_LINE> <DEDENT> if store_path: <NEW_LINE> <INDENT> the_object._pickle_path = path <NEW_LINE> <DEDENT> return the_object <NEW_LINE> <DEDENT> def write(self, path=None, store_path=False, safe=False, backup=False, makedirs=False): <NEW_LINE> <INDENT> pickle_path = getattr(self, '_pickle_path', None) <NEW_LINE> path = path or pickle_path <NEW_LINE> if path is None: <NEW_LINE> <INDENT> raise ValueError('A path must be specified') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if pickle_path: <NEW_LINE> <INDENT> del self._pickle_path <NEW_LINE> <DEDENT> to_file( path, pickle_data=self, binary=True, safe=safe, backup=backup, makedirs=makedirs) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if store_path: <NEW_LINE> <INDENT> self._pickle_path = path <NEW_LINE> <DEDENT> elif pickle_path: <NEW_LINE> <INDENT> self._pickle_path = pickle_path | An :class:`object` serializable/deserializable by :mod:`pickle`. | 6259907f5fc7496912d48fbc |
class IndexAwareList(list): <NEW_LINE> <INDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> if len(self) > item: <NEW_LINE> <INDENT> return super(IndexAwareList, self).__getitem__(item) <NEW_LINE> <DEDENT> return None | List has awareness of its index bound | 6259907fa05bb46b3848be79 |
class FreeProvider(BaseProvider): <NEW_LINE> <INDENT> def required_keys(self): <NEW_LINE> <INDENT> return ['api_id', 'api_key'] <NEW_LINE> <DEDENT> def send(self, msg): <NEW_LINE> <INDENT> params = { 'user': self.params['api_id'], 'passwd': self.params['api_key'] } <NEW_LINE> f = FreeClient(**params) <NEW_LINE> res = f.send_sms(msg) <NEW_LINE> if res.status_code == 200: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if res.status_code == 400: <NEW_LINE> <INDENT> raise MissingConfigParameter() <NEW_LINE> <DEDENT> if res.status_code == 500: <NEW_LINE> <INDENT> raise ServerError() <NEW_LINE> <DEDENT> return False | This is a provider class for the French telco 'Free'.
>>> f = FreeProvider({'api_id': '12345678', 'api_key':'xyz'})
>>> f.send('Hello, World!')
True | 6259907f4c3428357761bd5d |
class TEX(Drawable): <NEW_LINE> <INDENT> def __init__(self, config=TEXConfig(), image=None): <NEW_LINE> <INDENT> self._color = config.color <NEW_LINE> self._formula = config.formula <NEW_LINE> self._position = config.position <NEW_LINE> self._background = config.background <NEW_LINE> self._alpha = config.alpha <NEW_LINE> if not image: <NEW_LINE> <INDENT> self._image = self._create_image() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._image = image <NEW_LINE> <DEDENT> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> conf = TEXConfig() <NEW_LINE> conf.color = self._color <NEW_LINE> conf.formula = self._formula <NEW_LINE> conf.position = self._position <NEW_LINE> conf.alpha = self._alpha <NEW_LINE> conf.background = self._background <NEW_LINE> return conf <NEW_LINE> <DEDENT> def fade_in(self, frames=2, start_opacity=0, final_opacity=1): <NEW_LINE> <INDENT> assert start_opacity < final_opacity <NEW_LINE> increment = (final_opacity - start_opacity) / float(frames) <NEW_LINE> alphas = [start_opacity + f*increment for f in range(frames)] <NEW_LINE> conf = self.get_config() <NEW_LINE> texobjs = [] <NEW_LINE> for alpha in alphas: <NEW_LINE> <INDENT> conf.alpha = alpha <NEW_LINE> texobjs.append(TEX(conf, self._image)) <NEW_LINE> <DEDENT> return texobjs <NEW_LINE> <DEDENT> def fade_out(self, frames=2, start_opacity=1, final_opacity=0): <NEW_LINE> <INDENT> assert start_opacity > final_opacity <NEW_LINE> increment = (final_opacity - start_opacity) / float(frames) <NEW_LINE> alphas = [start_opacity + f*increment for f in range(frames)] <NEW_LINE> conf = self.get_config() <NEW_LINE> texobjs = [] <NEW_LINE> for alpha in alphas: <NEW_LINE> <INDENT> conf.alpha = alpha <NEW_LINE> texobjs.append(TEX(conf, self._image)) <NEW_LINE> <DEDENT> return texobjs <NEW_LINE> <DEDENT> def render_to(self, image): <NEW_LINE> <INDENT> if not self._image: <NEW_LINE> <INDENT> img = self._create_image() <NEW_LINE> self._image = img <NEW_LINE> <DEDENT> size = self._image.size <NEW_LINE> maskimage = Image.new('RGBA', size) <NEW_LINE> newim = Image.blend(maskimage, self._image, self._alpha) <NEW_LINE> image.paste(newim, self._position, newim) <NEW_LINE> return image <NEW_LINE> <DEDENT> def _create_image(self): <NEW_LINE> <INDENT> if hasattr(self, '_image') and self._image: <NEW_LINE> <INDENT> return self._image <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> command = "tex2im -b transparent -t cyan" <NEW_LINE> subprocess.run([*command.split(), self._formula]) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> import traceback <NEW_LINE> print(traceback.format_exc()) <NEW_LINE> return None <NEW_LINE> <DEDENT> img = Image.open('out.png').convert('RGBA') <NEW_LINE> subprocess.run(["rm", "out.png"]) <NEW_LINE> return img | LaTex drawable class
Attributes
----------
_color: color of formula text
_formula: the formula
_position: position of the formula
_background: background color | 6259907f92d797404e3898ad |
class ChannelDispatchOperation(dbus.service.Object): <NEW_LINE> <INDENT> @dbus.service.method('org.freedesktop.Telepathy.ChannelDispatchOperation', in_signature='s', out_signature='') <NEW_LINE> def HandleWith(self, Handler): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @dbus.service.method('org.freedesktop.Telepathy.ChannelDispatchOperation', in_signature='', out_signature='') <NEW_LINE> def Claim(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @dbus.service.signal('org.freedesktop.Telepathy.ChannelDispatchOperation', signature='oss') <NEW_LINE> def ChannelLost(self, Channel, Error, Message): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @dbus.service.signal('org.freedesktop.Telepathy.ChannelDispatchOperation', signature='') <NEW_LINE> def Finished(self): <NEW_LINE> <INDENT> pass | A channel dispatch operation is an object in the ChannelDispatcher
representing a batch of unrequested channels being announced to
client
Approver
processes.
These objects can result from new incoming channels or channels
which are automatically created for some reason, but cannot result
from outgoing requests for channels.
More specifically, whenever the
Connection.Interface.Requests.NewChannels
signal contains channels whose
Requested
property is false, or whenever the
Connection.NewChannel
signal contains a channel with suppress_handler false,
one or more ChannelDispatchOperation objects are created for those
channels.
(If some channels in a NewChannels signal are in different bundles,
this is an error. The channel dispatcher SHOULD recover by treating
the NewChannels signal as if it had been several NewChannels signals
each containing one channel.)
First, the channel dispatcher SHOULD construct a list of all the
Handlers
that could handle all the channels (based on their HandlerChannelFilter
property), ordered by
priority in some implementation-dependent way. If there are handlers
which could handle all the channels, one channel dispatch operation
SHOULD be created for all the channels. If there are not, one channel
dispatch operation SHOULD be created for each channel, each with
a list of channel handlers that could handle that channel.
If no handler at all can handle a channel, the channel dispatcher
SHOULD terminate that channel instead of creating a channel dispatcher
for it. It is RECOMMENDED that the channel dispatcher closes
the channels using Channel.Interface.Destroyable.Destroy
if supported, or Channel.Close
otherwise. As a special case, the channel dispatcher SHOULD NOT close
ContactList
channels, and if Close fails, the channel dispatcher SHOULD ignore
that channel.
ContactList channels are strange. We hope to replace them with
something better, such as an interface on the Connection, in a
future version of this specification.
When listing channel handlers, priority SHOULD be given to
channel handlers that are already handling channels from the same
bundle.
If a handler with BypassApproval
= True could handle all of the channels in the dispatch
operation, then the channel dispatcher SHOULD call HandleChannels
on that handler, and (assuming the call succeeds) emit
Finished and stop processing those
channels without involving any approvers.
Some channel types can be picked up "quietly" by an existing
channel handler. If a Text
channel is added to an existing bundle containing a StreamedMedia
channel, there shouldn't be
any approvers, flashing icons or notification bubbles, if the
the UI for the StreamedMedia channel can just add a text box
and display the message.
Otherwise, the channel dispatcher SHOULD send the channel dispatch
operation to all relevant approvers (in parallel) and wait for an
approver to claim the channels or request that they are handled.
See
AddDispatchOperation
for more details on this.
Finally, if the approver requested it, the channel dispatcher SHOULD
send the channels to a handler. | 6259907fa8370b77170f1e72 |
class HIDProfile(Server): <NEW_LINE> <INDENT> conns = {} <NEW_LINE> sock = None <NEW_LINE> def __init__(self, bus, path, sock): <NEW_LINE> <INDENT> Server.__init__(self, bus, path) <NEW_LINE> self.sock = sock <NEW_LINE> <DEDENT> def Release(self): <NEW_LINE> <INDENT> print("Release") <NEW_LINE> self.quit() <NEW_LINE> <DEDENT> def RequestDisconnection(self, device): <NEW_LINE> <INDENT> print('RequestDisconnection (%s)' % device) <NEW_LINE> self.conns.pop(device).close() <NEW_LINE> <DEDENT> def NewConnection(self, device, fd, fd_properties): <NEW_LINE> <INDENT> print("New control connection (%s, %d, %s)" % (device, fd, fd_properties)) <NEW_LINE> self.conns[device] = HIDConnection(fd) <NEW_LINE> def new_intr_conn(ssock, ip_type): <NEW_LINE> <INDENT> sock, info = ssock.accept() <NEW_LINE> print("interrupt connection:", info) <NEW_LINE> self.conns[device].register_intr_socks(sock) <NEW_LINE> return False <NEW_LINE> <DEDENT> GLib.io_add_watch(self.sock, GLib.IO_IN, new_intr_conn) | <node>
<interface name='org.bluez.Profile1'>
<method name='Release'></method>
<method name='RequestDisconnection'>
<arg type='o' name='device' direction='in'/>
</method>
<method name='NewConnection'>
<arg type='o' name='device' direction='in'/>
<arg type='h' name='fd' direction='in'/>
<arg type='a{sv}' name='fd_properties' direction='in'/>
</method>
</interface>
</node>
| 6259907f796e427e5385021d |
class TableWidget(object): <NEW_LINE> <INDENT> def __init__(self, with_table_tag=True): <NEW_LINE> <INDENT> self.with_table_tag = with_table_tag <NEW_LINE> <DEDENT> def __call__(self, field, **kwargs): <NEW_LINE> <INDENT> html = [] <NEW_LINE> if self.with_table_tag: <NEW_LINE> <INDENT> kwargs.setdefault('id', field.id) <NEW_LINE> html.append(u'<table %s>' % html_params(**kwargs)) <NEW_LINE> <DEDENT> hidden = u'' <NEW_LINE> for subfield in field: <NEW_LINE> <INDENT> if subfield.type == 'HiddenField': <NEW_LINE> <INDENT> hidden += unicode(subfield) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> html.append(u'<tr><th>%s</th><td>%s%s</td></tr>' % (unicode(subfield.label), hidden, unicode(subfield))) <NEW_LINE> hidden = u'' <NEW_LINE> <DEDENT> <DEDENT> if self.with_table_tag: <NEW_LINE> <INDENT> html.append(u'</table>') <NEW_LINE> <DEDENT> if hidden: <NEW_LINE> <INDENT> html.append(hidden) <NEW_LINE> <DEDENT> return HTMLString(u''.join(html)) | Renders a list of fields as a set of table rows with th/td pairs.
If `with_table_tag` is True, then an enclosing <table> is placed around the
rows.
Hidden fields will not be displayed with a row, instead the field will be
pushed into a subsequent table row to ensure XHTML validity. Hidden fields
at the end of the field list will appear outside the table. | 6259907fd486a94d0ba2da59 |
class SelfEncodable(object): <NEW_LINE> <INDENT> def write_to(self, stream): <NEW_LINE> <INDENT> raise NotImplementedError("Subclasses must implement") <NEW_LINE> <DEDENT> def encode(self): <NEW_LINE> <INDENT> stream = StringIO() <NEW_LINE> self.write_to(stream) <NEW_LINE> return stream.getvalue() | Represents an object that can decode itself. | 6259907f3346ee7daa3383b3 |
class RuntimeDisplay(wx.Panel): <NEW_LINE> <INDENT> def __init__(self, parent, **kwargs): <NEW_LINE> <INDENT> wx.Panel.__init__(self, parent, **kwargs) <NEW_LINE> self._init_properties() <NEW_LINE> self._init_components() <NEW_LINE> self._do_layout() <NEW_LINE> <DEDENT> def set_font_style(self, style): <NEW_LINE> <INDENT> pointsize = self.cmd_textbox.GetFont().GetPointSize() <NEW_LINE> font = wx.Font(pointsize, style, wx.FONTWEIGHT_NORMAL, wx.FONTWEIGHT_BOLD, False) <NEW_LINE> self.cmd_textbox.SetFont(font) <NEW_LINE> <DEDENT> def _init_properties(self): <NEW_LINE> <INDENT> self.SetBackgroundColour('#F0F0F0') <NEW_LINE> <DEDENT> def _init_components(self): <NEW_LINE> <INDENT> self.text = wx.StaticText(self, label=i18n._("status")) <NEW_LINE> self.cmd_textbox = wx.TextCtrl( self, -1, "", style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH) <NEW_LINE> <DEDENT> def _do_layout(self): <NEW_LINE> <INDENT> sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> sizer.AddSpacer(10) <NEW_LINE> sizer.Add(self.text, 0, wx.LEFT, 30) <NEW_LINE> sizer.AddSpacer(10) <NEW_LINE> sizer.Add(self.cmd_textbox, 1, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 30) <NEW_LINE> sizer.AddSpacer(20) <NEW_LINE> self.SetSizer(sizer) <NEW_LINE> <DEDENT> def append_text(self, txt): <NEW_LINE> <INDENT> self.cmd_textbox.AppendText(txt) | Textbox displayed during the client program's execution. | 6259907fdc8b845886d5505d |
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField(u'Name', max_length=20) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def balance(self): <NEW_LINE> <INDENT> debit = Trade.objects.filter(dr_name=self).aggregate(Sum('amount'))['amount__sum'] <NEW_LINE> if debit is None: <NEW_LINE> <INDENT> debit = 0 <NEW_LINE> <DEDENT> credit = Trade.objects.filter(cr_name=self).aggregate(Sum('amount'))['amount__sum'] <NEW_LINE> if credit is None: <NEW_LINE> <INDENT> credit = 0 <NEW_LINE> <DEDENT> return debit - credit | 勘定科目 | 6259907f32920d7e50bc7ae4 |
class Malt(object): <NEW_LINE> <INDENT> def __init__(self,name,maker,max_yield,color,kolbach_min,kolbach_max): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.maker=maker <NEW_LINE> self.max_yield = max_yield <NEW_LINE> self.color=color <NEW_LINE> self.kolbach_min=kolbach_min <NEW_LINE> self.kolbach_max=kolbach_max <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> print('I am a MaltType object') | A class to store a malt's attributes in a brewing session | 6259907f5fdd1c0f98e5fa22 |
@public <NEW_LINE> class test(coroutine): <NEW_LINE> <INDENT> def __init__(self, timeout=None, expect_fail=False, expect_error=False, skip=False): <NEW_LINE> <INDENT> self.timeout = timeout <NEW_LINE> self.expect_fail = expect_fail <NEW_LINE> self.expect_error = expect_error <NEW_LINE> self.skip = skip <NEW_LINE> <DEDENT> def __call__(self, f): <NEW_LINE> <INDENT> super(test, self).__init__(f) <NEW_LINE> def _wrapped_test(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return RunningTest(self._func(*args, **kwargs), self) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise raise_error(self, str(e)) <NEW_LINE> <DEDENT> <DEDENT> _wrapped_test.im_test = True <NEW_LINE> _wrapped_test.name = self._func.__name__ <NEW_LINE> _wrapped_test.__name__ = self._func.__name__ <NEW_LINE> return _wrapped_test | Decorator to mark a function as a test
All tests are coroutines. The test decorator provides
some common reporting etc, a test timeout and allows
us to mark tests as expected failures.
KWargs:
timeout: (int)
value representing simulation timeout (not implemented)
expect_fail: (bool):
Don't mark the result as a failure if the test fails
expect_error: (bool):
Don't make the result as an error if an error is raised
This is for cocotb internal regression use
skip: (bool):
Don't execute this test as part of the regression | 6259907ff548e778e596d035 |
class Module(Thing): <NEW_LINE> <INDENT> def __init__(self, name, flavor, flavor2, loc, ship = None, isRing = False): <NEW_LINE> <INDENT> super().__init__(name, flavor) <NEW_LINE> self.loc = loc <NEW_LINE> self.isRing = isRing <NEW_LINE> if isRing: <NEW_LINE> <INDENT> self.ringModules = {"U":None, "D":None, "L":None, "R":None} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.objectList = [] <NEW_LINE> <DEDENT> if ship != None: <NEW_LINE> <INDENT> self.ship = ship <NEW_LINE> if loc > len(ship)-1: <NEW_LINE> <INDENT> for i in range(loc): <NEW_LINE> <INDENT> if i > len(ship)-1: <NEW_LINE> <INDENT> ship.append(None) <NEW_LINE> <DEDENT> <DEDENT> ship.append(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ship[loc] = self <NEW_LINE> <DEDENT> if loc == 0: <NEW_LINE> <INDENT> self.back = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.back = ship[loc-1] <NEW_LINE> self.back.front = self <NEW_LINE> <DEDENT> if len(ship) == loc+1: <NEW_LINE> <INDENT> self.front = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.front = ship[loc+1] <NEW_LINE> self.front.back = self <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.name) <NEW_LINE> <DEDENT> def getFront(self): <NEW_LINE> <INDENT> return self.front <NEW_LINE> <DEDENT> def getBack(self): <NEW_LINE> <INDENT> return self.back <NEW_LINE> <DEDENT> def getShip(self): <NEW_LINE> <INDENT> return self.ship <NEW_LINE> <DEDENT> def getLoc(self): <NEW_LINE> <INDENT> return self.loc <NEW_LINE> <DEDENT> def getRingMod(self): <NEW_LINE> <INDENT> if self.ring: <NEW_LINE> <INDENT> return self.ringModules <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def setRingModules(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def printShip(self): <NEW_LINE> <INDENT> text = "" <NEW_LINE> for module in ship: <NEW_LINE> <INDENT> text += str(module.getName(), end=" - ") <NEW_LINE> <DEDENT> return text <NEW_LINE> <DEDENT> def setLoc(self, loc): <NEW_LINE> <INDENT> if loc != self.loc: <NEW_LINE> <INDENT> if loc > len(self.ship)-1: <NEW_LINE> <INDENT> self.loc = loc <NEW_LINE> for i in range(loc): <NEW_LINE> <INDENT> if i > len(self.ship)-1: <NEW_LINE> <INDENT> self.ship.append(None) <NEW_LINE> <DEDENT> <DEDENT> self.ship.append(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ship[self.loc] = self.ship[loc] <NEW_LINE> self.ship[loc] = self <NEW_LINE> self.loc = loc <NEW_LINE> <DEDENT> if loc == 0: <NEW_LINE> <INDENT> self.back = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.back = ship[loc-1] <NEW_LINE> self.back.front = self <NEW_LINE> <DEDENT> if len(ship) == loc+1: <NEW_LINE> <INDENT> self.front = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.front = ship[loc+1] <NEW_LINE> self.front.back = self <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def addObject(self, object, location = ""): <NEW_LINE> <INDENT> self.objectList.append(object) <NEW_LINE> if location != "": <NEW_LINE> <INDENT> object.setLoc(str(location)) <NEW_LINE> <DEDENT> <DEDENT> def addObjects(self, *args): <NEW_LINE> <INDENT> for object in args: <NEW_LINE> <INDENT> self.objectList.append(object) | class for ship modules | 6259907f7c178a314d78e93c |
class Prefix(object): <NEW_LINE> <INDENT> def __init__(self, prefix): <NEW_LINE> <INDENT> self.prefix = prefix <NEW_LINE> self._parse() <NEW_LINE> <DEDENT> def _parse(self): <NEW_LINE> <INDENT> if "!" not in self.prefix or "@" not in self.prefix: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.nick, rest = self.prefix.split("!", maxsplit=1) <NEW_LINE> self.user, self.host = rest.split("@", maxsplit=1) <NEW_LINE> self.nick = IStr(self.nick) <NEW_LINE> self.user = IStr(self.user) <NEW_LINE> self.host = IStr(self.host) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Prefix({})".format(repr(self.prefix)) | Prefix represents a source of an IRC message, usually a hostmask.
Instance variables:
prefix The complete prefix.
nick A nickname, or None.
ident An ident/username, or None.
host A hostname, or None. | 6259907f5fdd1c0f98e5fa23 |
class WaypointSequenceResponse(HEREModel): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(WaypointSequenceResponse, self).__init__() <NEW_LINE> self.param_defaults = { "results": None, "errors": None, "warnings": None, } <NEW_LINE> for (param, default) in self.param_defaults.items(): <NEW_LINE> <INDENT> setattr(self, param, kwargs.get(param, default)) | A class representing the Fleet Telematics Waypoint Sequence response data. | 6259907f66673b3332c31ea3 |
class ZenossDataSource(TemplateRouter): <NEW_LINE> <INDENT> def __init__(self, url, headers, ssl_verify, ds_data): <NEW_LINE> <INDENT> super(ZenossDataSource, self).__init__(url, headers, ssl_verify) <NEW_LINE> uid = ds_data.pop('uid') <NEW_LINE> self.uid = uid.replace('/zport/dmd/', '', 1) <NEW_LINE> self.name = ds_data.pop('name') <NEW_LINE> self.id = ds_data.pop('id') <NEW_LINE> self.eventClass = ds_data.pop('eventClass') <NEW_LINE> self.eventKey = ds_data.pop('eventKey') <NEW_LINE> self.severity = ds_data.pop('severity') <NEW_LINE> self.type = ds_data.pop('type') <NEW_LINE> self.component = ds_data.pop('component') <NEW_LINE> self.properties = ds_data <NEW_LINE> self.parent = self.uid.split('/datasources/')[0] <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._router_request( self._make_request_data( 'deleteDataSource', dict(uid=self.uid), ) ) <NEW_LINE> <DEDENT> def get_data_points(self): <NEW_LINE> <INDENT> dp_data = self._router_request( self._make_request_data( 'getDataPoints', dict(uid=self.parent) ) ) <NEW_LINE> datapoints = [] <NEW_LINE> for dp in dp_data['data']: <NEW_LINE> <INDENT> if dp['name'].startswith(self.name): <NEW_LINE> <INDENT> datapoints.append( ZenossDataPoint( self.api_url, self.api_headers, self.ssl_verify, dp ) ) <NEW_LINE> <DEDENT> <DEDENT> return datapoints <NEW_LINE> <DEDENT> def list_data_points(self): <NEW_LINE> <INDENT> dp_data = self._router_request( self._make_request_data( 'getDataPoints', dict(uid=self.parent) ) ) <NEW_LINE> datapoints = [] <NEW_LINE> for dp in dp_data['data']: <NEW_LINE> <INDENT> if dp['name'].startswith(self.name): <NEW_LINE> <INDENT> datapoints.append(dp['uid'].replace('/zport/dmd/', '', 1)) <NEW_LINE> <DEDENT> <DEDENT> return datapoints <NEW_LINE> <DEDENT> def get_data_point(self, datapoint): <NEW_LINE> <INDENT> datapoint_uid = '{}/datapoints/{}'.format(self.uid, datapoint) <NEW_LINE> return self._get_data_point_by_uid(datapoint_uid) <NEW_LINE> <DEDENT> def add_data_point(self, datapoint): <NEW_LINE> <INDENT> response_data = self._router_request( self._make_request_data( 'addDataPoint', dict( dataSourceUid=self.uid, name=datapoint, ) ) ) <NEW_LINE> return self._get_data_point_by_uid( '{}/datapoints/{}'.format(self.uid, datapoint) ) <NEW_LINE> <DEDENT> def delete_data_point(self, datapoint): <NEW_LINE> <INDENT> datapoint_uid = '{}/datapoints/{}'.format(self.uid, datapoint) <NEW_LINE> return self._router_request( self._make_request_data( 'deleteDataPoint', dict(uid=datapoint_uid), ) ) | Class for Zenoss template data sources | 6259907f60cbc95b06365abe |
class BasePageObjectMeta(type): <NEW_LINE> <INDENT> def __new__(cls, name, bases, attrs): <NEW_LINE> <INDENT> instance = super(BasePageObjectMeta, cls).__new__(cls, name, bases, attrs) <NEW_LINE> for name, value in attrs.iteritems(): <NEW_LINE> <INDENT> if isinstance(value, BasePageElement): <NEW_LINE> <INDENT> setattr(instance, name, copy.deepcopy(value)) <NEW_LINE> <DEDENT> <DEDENT> if 'url' in attrs: <NEW_LINE> <INDENT> instance.url = copy.deepcopy(attrs['url']) <NEW_LINE> <DEDENT> return instance | Metaclass for all PageObjects. | 6259907fa05bb46b3848be7a |
class AsyncChannel(object): <NEW_LINE> <INDENT> _resolver_configured = False <NEW_LINE> @classmethod <NEW_LINE> def _config_resolver(cls, num_threads=10): <NEW_LINE> <INDENT> from tornado.netutil import Resolver <NEW_LINE> Resolver.configure( 'tornado.netutil.ThreadedResolver', num_threads=num_threads) <NEW_LINE> cls._resolver_configured = True | Parent class for Async communication channels | 6259907f1f5feb6acb16469e |
class X265BAdaptSignal: <NEW_LINE> <INDENT> def __init__(self, x265_handlers, inputs_page_handlers): <NEW_LINE> <INDENT> self.x265_handlers = x265_handlers <NEW_LINE> self.inputs_page_handlers = inputs_page_handlers <NEW_LINE> <DEDENT> def on_x265_b_adapt_combobox_changed(self, x265_b_adapt_combobox): <NEW_LINE> <INDENT> if self.x265_handlers.is_widgets_setting_up: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> b_adapt_index = x265_b_adapt_combobox.get_active() <NEW_LINE> for row in self.inputs_page_handlers.get_selected_rows(): <NEW_LINE> <INDENT> ffmpeg = row.ffmpeg <NEW_LINE> ffmpeg.video_settings.b_adapt = b_adapt_index <NEW_LINE> row.setup_labels() <NEW_LINE> <DEDENT> self.inputs_page_handlers.update_preview_page() | Handles the signal emitted when the x265 BAdapt option is changed. | 6259907f091ae356687066e4 |
class ToTensor(): <NEW_LINE> <INDENT> def np2th(self, arr): <NEW_LINE> <INDENT> if np.iscomplexobj(arr): <NEW_LINE> <INDENT> arr = arr.astype(np.complex64) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arr = arr.astype(np.float32) <NEW_LINE> <DEDENT> return utils.numpy_to_torch(arr) <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> for key in ['norm', 'mean', 'cov', 'ref_max', 'rss_max']: <NEW_LINE> <INDENT> if key in sample['attrs'].keys(): <NEW_LINE> <INDENT> sample['attrs'][key] = utils.numpy_to_torch( sample['attrs'][key]).to(torch.float32) <NEW_LINE> <DEDENT> <DEDENT> sample_dict = { "attrs": sample['attrs'], "fname": sample['fname'], "slidx": sample['slidx'], } <NEW_LINE> for k in [ 'input', 'kspace', 'smaps', 'target', 'target_rss', 'input_rss', 'input_rss_mean', 'acceleration', 'acceleration_true', ]: <NEW_LINE> <INDENT> if k in sample.keys(): <NEW_LINE> <INDENT> sample_dict.update({k: self.np2th(sample[k])}) <NEW_LINE> <DEDENT> <DEDENT> th_mask = self.np2th(sample['mask']) <NEW_LINE> th_mask.unsqueeze_(-1) <NEW_LINE> sample_dict.update({'mask': th_mask}) <NEW_LINE> if 'fg_mask' in sample.keys(): <NEW_LINE> <INDENT> sample_dict.update({"fg_mask": self.np2th(sample['fg_mask']).unsqueeze_(1), "fg_mask_norm": self.np2th(sample['fg_mask_norm']).unsqueeze_(1), "fg_mask_normedsqrt": self.np2th(sample['fg_mask_normedsqrt']).unsqueeze_(1), }) <NEW_LINE> <DEDENT> return sample_dict | Convert sample ndarrays to tensors. | 6259907f4527f215b58eb6f2 |
class Right(Either): <NEW_LINE> <INDENT> def map(self, func): <NEW_LINE> <INDENT> return func(self.value) | This class defines the Right side of an Either Monad | 6259907f3346ee7daa3383b4 |
class HBarGraph(twc.Widget): <NEW_LINE> <INDENT> template = 'rnms.templates.widgets.hbargraph' <NEW_LINE> title = twc.Param('Title of the Chart', default='') <NEW_LINE> graph_data = twc.Param('List of (label,pct,val)') | Small Horizontal Bar Graph Chart
graph_data should be a list of 3 item list
(label, percent, value label)
| 6259907f656771135c48ad82 |
class HiddenUnless(object): <NEW_LINE> <INDENT> field_flags = ('initially_hidden',) <NEW_LINE> def __init__(self, field, value=None, preserve_data=False): <NEW_LINE> <INDENT> self.field = field <NEW_LINE> self.value = value <NEW_LINE> self.preserve_data = preserve_data <NEW_LINE> <DEDENT> def __call__(self, form, field): <NEW_LINE> <INDENT> value = form[self.field].data <NEW_LINE> active = (value and self.value is None) or (value == self.value and self.value is not None) <NEW_LINE> if not active: <NEW_LINE> <INDENT> field.errors[:] = [] <NEW_LINE> if field.raw_data: <NEW_LINE> <INDENT> raise ValidationError("Received data for disabled field") <NEW_LINE> <DEDENT> if not self.preserve_data: <NEW_LINE> <INDENT> field.data = None <NEW_LINE> field.process_formdata([]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> field.data = None <NEW_LINE> field.process_data(field.object_data) <NEW_LINE> <DEDENT> raise StopValidation() | Hides and disables a field unless another field has a certain value.
:param field: The name of the other field to check
:param value: The value to check for. If unspecified, any truthy
value is accepted.
:param preserve_data: If True, a disabled field will keep whatever
``object_data`` it had before (i.e. data set
via `FormDefaults`). | 6259907ffff4ab517ebcf2bd |
class Partition(Object, metaclass=PartitionType): <NEW_LINE> <INDENT> block_device = ObjectFieldRelated( "device_id", "BlockDevice", readonly=True, pk=0, map_func=map_device_id_to_dict ) <NEW_LINE> id = ObjectField.Checked("id", check(int), readonly=True, pk=1) <NEW_LINE> uuid = ObjectField.Checked("uuid", check(str), readonly=True) <NEW_LINE> path = ObjectField.Checked("path", check(str), readonly=True) <NEW_LINE> size = ObjectField.Checked("size", check(int), readonly=True) <NEW_LINE> used_for = ObjectField.Checked("used_for", check(str), readonly=True) <NEW_LINE> filesystem = ObjectFieldRelated("filesystem", "Filesystem", readonly=True) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return super(Partition, self).__repr__(fields={"path", "size"}) <NEW_LINE> <DEDENT> async def delete(self): <NEW_LINE> <INDENT> await self._handler.delete( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, ) <NEW_LINE> <DEDENT> async def format(self, fstype, *, uuid=None): <NEW_LINE> <INDENT> self._reset( await self._handler.format( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, fstype=fstype, uuid=uuid, ) ) <NEW_LINE> <DEDENT> async def unformat(self): <NEW_LINE> <INDENT> self._reset( await self._handler.unformat( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, ) ) <NEW_LINE> <DEDENT> async def mount(self, mount_point, *, mount_options=None): <NEW_LINE> <INDENT> self._reset( await self._handler.mount( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, mount_point=mount_point, mount_options=mount_options, ) ) <NEW_LINE> <DEDENT> async def umount(self): <NEW_LINE> <INDENT> self._reset( await self._handler.unmount( system_id=self.block_device.node.system_id, device_id=self.block_device.id, id=self.id, ) ) | A partition on a block device. | 62599080f548e778e596d037 |
class Network_Node: <NEW_LINE> <INDENT> def __init__(self, host="0.0.0.0", port=0): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.game = Game() <NEW_LINE> self.view = None <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> @circuits.handler("read") <NEW_LINE> def read(self, *args): <NEW_LINE> <INDENT> if len(args) == 1: <NEW_LINE> <INDENT> socket = None <NEW_LINE> data = args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> socket, data = args <NEW_LINE> <DEDENT> event = debytify(data) <NEW_LINE> old_events = new_events = event.handle(self) <NEW_LINE> if event.broadcast and self.is_server: <NEW_LINE> <INDENT> print(self.broadcast, "BROADCASTING") <NEW_LINE> source_client = filter(lambda client: client.socket == socket, self.clients.values()) <NEW_LINE> self.broadcast(event, exclude_list=list(source_client)) <NEW_LINE> <DEDENT> while new_events: <NEW_LINE> <INDENT> old_events = list(new_events) <NEW_LINE> new_events = [] <NEW_LINE> for event in old_events: <NEW_LINE> <INDENT> print("Event", event) <NEW_LINE> caused_events = event.handle() <NEW_LINE> new_events.extend(caused_events) <NEW_LINE> if event.broadcast and self.is_server: <NEW_LINE> <INDENT> self.broadcast(event) <NEW_LINE> <DEDENT> for listener in type(event).listeners: <NEW_LINE> <INDENT> listener.handle(event) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.game.update() <NEW_LINE> self.view.update() <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> def broadcast(self, event, exclude_list=None): <NEW_LINE> <INDENT> print("Broadcasting event") <NEW_LINE> self.fire(write(bytify(event).encode("utf-8"))) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_server(self): <NEW_LINE> <INDENT> return hasattr(self, "clients") | Represents a node (In the graph-theory sense) in the network.
A node can be either a server or a client. Note: This object is
game-specific. (So feel free to put in wumpus-related information.)
Maybe one day the design will justify splitting this out from the game-related
information, but that day isn't today. | 625990807c178a314d78e93d |
class UserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('email', 'password', 'name') <NEW_LINE> extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} <NEW_LINE> <DEDENT> def create(self, validate_data): <NEW_LINE> <INDENT> return get_user_model().objects.create_user(**validate_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop('password', None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user | Serializers for the user object | 62599080aad79263cf43025f |
class MedianScaleNumpy(object): <NEW_LINE> <INDENT> def __init__(self, range_min=0.0, range_max=1.0): <NEW_LINE> <INDENT> self.scale = (range_min, range_max) <NEW_LINE> <DEDENT> def __call__(self, image): <NEW_LINE> <INDENT> mn = image.min(axis=(0, 1)) <NEW_LINE> md = np.median(image, axis=(0, 1)) <NEW_LINE> return self.scale[0] + (image - mn) * (self.scale[1] - self.scale[0]) / (md - mn) | Scale with median and mean of each channel of the numpy array i.e.
channel = (channel - mean) / std | 625990804428ac0f6e659fd4 |
class ImportWestwood3D(Operator, ImportHelper): <NEW_LINE> <INDENT> bl_idname = "import.westwood3d" <NEW_LINE> bl_label = "Import Westwood3D" <NEW_LINE> filename_ext = ".w3d" <NEW_LINE> filter_glob = StringProperty( default="*.w3d", options={'HIDDEN'}, ) <NEW_LINE> ignore_lightmap = BoolProperty( name="Don't import lightmaps", description="Lightmap data increases material count", default=True, ) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> return read_some_data(context, self.filepath, self.ignore_lightmap) | This appears in the tooltip of the operator and in the generated docs | 625990807cff6e4e811b74e6 |
class MutatedISA(ImplicitDict): <NEW_LINE> <INDENT> dss_response: MutatedISAResponse <NEW_LINE> notifications: Dict[str, fetch.Query] | Result of an attempt to mutate an ISA (including DSS & notifications) | 62599080aad79263cf430260 |
class StrategyFactory(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> factoryMethods = {} <NEW_LINE> @classmethod <NEW_LINE> def register(cls, name, method): <NEW_LINE> <INDENT> StrategyFactory.factoryMethods[name] = method <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, name, barFeed, symbols = None, broker = None, cash = 1000000, compounding = True, parms = None): <NEW_LINE> <INDENT> if not StrategyFactory.factoryMethods.has_key(name): <NEW_LINE> <INDENT> raise Exception('No strategy %s registered' % name) <NEW_LINE> <DEDENT> return StrategyFactory.factoryMethods[name](barFeed, symbols = symbols, broker = broker, cash = cash, compounding = compounding, parms = parms) | classdocs | 62599080be7bc26dc9252ba8 |
class HubDBMixin(object): <NEW_LINE> <INDENT> def __init__(self, session_factory): <NEW_LINE> <INDENT> self.db = session_factory() | Mixin for connecting to the hub database | 62599080ec188e330fdfa350 |
class TwoTerminal: <NEW_LINE> <INDENT> def __init__(self, pos_node: str, neg_node: str): <NEW_LINE> <INDENT> self.pos_node = pos_node <NEW_LINE> self.neg_node = neg_node <NEW_LINE> <DEDENT> @property <NEW_LINE> @abstractmethod <NEW_LINE> def impedance(self): <NEW_LINE> <INDENT> ... | A mixin class for components with two terminals.
| 6259908026068e7796d4e3e6 |
class Dispatcher: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.queue_timeout = QUEUE_TIMEOUT <NEW_LINE> self._commands = Queue() <NEW_LINE> self._results = Queue() <NEW_LINE> <DEDENT> def addCommand(self, command): <NEW_LINE> <INDENT> self._commands.put(command, block=True, timeout=self.queue_timeout) <NEW_LINE> return 'Command added' <NEW_LINE> <DEDENT> def getCommand(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._commands.get(block=True, timeout=self.queue_timeout) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> return 'ERROR: Command queue was empty' <NEW_LINE> <DEDENT> <DEDENT> def getCommandQueueSize(self): <NEW_LINE> <INDENT> return self._commands.qsize() <NEW_LINE> <DEDENT> def addResult(self, result): <NEW_LINE> <INDENT> self._results.put(result) <NEW_LINE> return 'Result added' <NEW_LINE> <DEDENT> def getResult(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._results.get(block=True, timeout=self.queue_timeout) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> return 'ERROR: Result queue was empty' <NEW_LINE> <DEDENT> <DEDENT> def getResultQueueSize(self): <NEW_LINE> <INDENT> size = self._results.qsize() <NEW_LINE> return size <NEW_LINE> <DEDENT> def setTimeout(self,timeout): <NEW_LINE> <INDENT> self.queue_timeout = timeout <NEW_LINE> return "Timeout set to %s seconds" % timeout <NEW_LINE> <DEDENT> def webDriver(self, request): <NEW_LINE> <INDENT> if request: <NEW_LINE> <INDENT> command_result = request.args.get('commandResult') <NEW_LINE> selenium_start = request.args.get('seleniumStart') <NEW_LINE> if command_result: <NEW_LINE> <INDENT> command_result = command_result.pop() <NEW_LINE> self.addResult(command_result) <NEW_LINE> <DEDENT> return self.getCommand() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "ERROR: Missing an HTTP REQUEST" <NEW_LINE> <DEDENT> <DEDENT> def apiDriver(self, command_string=""): <NEW_LINE> <INDENT> self.addCommand(command_string) <NEW_LINE> if command_string.find('testComplete') >= 0: <NEW_LINE> <INDENT> return 'test complete' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.getResult() | Sends commands to and receives results from a web browser.
Dispatcher:
_Computer Science_: A routine that controls the order in which input
and output devices obtain access to the processing system.
(source: http://dictionary.reference.com/search?q=dispatcher)
In Selenium, the Dispatcher class takes commands to be executed and puts
them in a queue for a web browser to read.
When the browser reads this queue for a command to execute, it adds the
previous command's result to the Dispatcher's result queue. | 6259908023849d37ff852b5f |
class Expression12(Expression): <NEW_LINE> <INDENT> def get(self, instance): <NEW_LINE> <INDENT> raise NotImplementedError('%s not implemented' % ( self.__class__.__name__)) | Get Background Color
Return type: Int | 62599080d268445f2663a8b1 |
class GarageDoor(Accessory): <NEW_LINE> <INDENT> category = CATEGORY_GARAGE_DOOR_OPENER <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._led = LED(17) <NEW_LINE> self._lock = None <NEW_LINE> self.add_preload_service("GarageDoorOpener").configure_char( "TargetDoorState", setter_callback=self.change_state ) <NEW_LINE> <DEDENT> def change_state(self, value): <NEW_LINE> <INDENT> if self._lock and self._lock.locked: <NEW_LINE> <INDENT> logging.info(f"Garage is locked, setting value {value}") <NEW_LINE> self.get_service("GarageDoorOpener").get_characteristic( "CurrentDoorState" ).set_value(value) <NEW_LINE> return <NEW_LINE> <DEDENT> logging.info("Garage door: %s", value) <NEW_LINE> self._led.on() <NEW_LINE> sleep(2) <NEW_LINE> self._led.off() <NEW_LINE> self.get_service("GarageDoorOpener").get_characteristic( "CurrentDoorState" ).set_value(value) <NEW_LINE> <DEDENT> def set_lock(self, lock): <NEW_LINE> <INDENT> self._lock = lock | Garage door opener | 62599080e1aae11d1e7cf565 |
class CallUnits(unittest.TestCase): <NEW_LINE> <INDENT> def testCase310(self): <NEW_LINE> <INDENT> arg = tdata + '/*/"""/[^//]*"""/(c.s.*|c.p.*)$' <NEW_LINE> resX = [ tdata + '/b/c/c.smod', tdata + '/b/c/c.pod', tdata + '/b/c/c.py', tdata + '/b/c/c.pl', tdata + '/b/c/c.pm', tdata + '/b/c/c.sh', tdata + '/b2/c/c.smod', tdata + '/b2/c/c.pod', tdata + '/b2/c/c.py', tdata + '/b2/c/c.pl', tdata + '/b2/c/c.pm', tdata + '/b2/c/c.sh', tdata + '/b3/smods/c.smod', tdata + '/b0/c/c.smod', tdata + '/b0/c/c.pod', tdata + '/b0/c/c.py', tdata + '/b0/c/c.pl', tdata + '/b0/c/c.pm', tdata + '/b0/c/c.sh', ] <NEW_LINE> from filesysobjects import V3K <NEW_LINE> if os.path.exists(tdata + '/b/c/c.pyc'): <NEW_LINE> <INDENT> resX.append(tdata + '/b/c/c.pyc') <NEW_LINE> <DEDENT> if os.path.exists(tdata + '/b2/c/c.pyc'): <NEW_LINE> <INDENT> resX.append(tdata + '/b2/c/c.pyc') <NEW_LINE> <DEDENT> if os.path.exists(tdata + '/b0/c/c.pyc'): <NEW_LINE> <INDENT> resX.append(tdata + '/b0/c/c.pyc') <NEW_LINE> <DEDENT> arg = filesysobjects.apppaths.normapppathx(arg, tpf='posix') <NEW_LINE> res = filesysobjects.pathtools.expandpath(arg, wildcards=W_RE) <NEW_LINE> res = [ filesysobjects.apppaths.normapppathx(x, tpf='posix') for x in res] <NEW_LINE> resX = [ filesysobjects.apppaths.normapppathx(x, tpf='posix') for x in resX] <NEW_LINE> self.assertEqual(sorted(res), sorted(resX)) | Sets the specific data array and required parameters for test case.
| 6259908044b2445a339b76b0 |
class AVBDiscriminator(pxd.Deterministic): <NEW_LINE> <INDENT> def __init__(self, channel_num, z_dim): <NEW_LINE> <INDENT> super().__init__(cond_var=["x", "z"], var=["t"], name="d") <NEW_LINE> self.disc_x = nn.Sequential( nn.Conv2d(channel_num, 32, 4, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 32, 4, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 64, 4, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 64, 4, stride=2, padding=1), nn.ReLU(), ) <NEW_LINE> self.fc_x = nn.Linear(1024, 256) <NEW_LINE> self.disc_z = nn.Sequential( nn.Linear(z_dim, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), ) <NEW_LINE> self.fc = nn.Linear(512, 1) <NEW_LINE> <DEDENT> def forward(self, x, z): <NEW_LINE> <INDENT> h_x = self.disc_x(x) <NEW_LINE> h_x = self.fc_x(h_x.view(-1, 1024)) <NEW_LINE> h_z = self.disc_z(z) <NEW_LINE> logits = self.fc(torch.cat([h_x, h_z], dim=1)) <NEW_LINE> probs = torch.sigmoid(logits) <NEW_LINE> t = torch.clamp(probs, 1e-6, 1 - 1e-6) <NEW_LINE> return {"t": t} | T(x, z) | 62599080a8370b77170f1e77 |
class HeadNode(TailNode): <NEW_LINE> <INDENT> def __init__(self, link=None, down=None): <NEW_LINE> <INDENT> TailNode.__init__(self, down) <NEW_LINE> self.link = TailNode() <NEW_LINE> self.skip = None <NEW_LINE> self.index = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ("HeadNode({0}, {1})".format(repr(self.link), repr(self.down))) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> arrow = '> ' <NEW_LINE> dash = ' -' <NEW_LINE> s = '' <NEW_LINE> temp = self <NEW_LINE> while temp.link and type(temp.link) != TailNode: <NEW_LINE> <INDENT> x = temp.skip - 1 <NEW_LINE> s += dash + 5 * x * ' ' + arrow + str(temp.link.data) <NEW_LINE> temp = temp.link <NEW_LINE> <DEDENT> return s + ' -' + (5 * (temp.skip - 1)) * ' ' + arrow <NEW_LINE> <DEDENT> def add(self, item): <NEW_LINE> <INDENT> temp = self._predecessor_head(item) <NEW_LINE> temp.link = ElementNode(item, temp.link) <NEW_LINE> <DEDENT> def add_down(self, head): <NEW_LINE> <INDENT> self.down = head <NEW_LINE> <DEDENT> def search(self, item): <NEW_LINE> <INDENT> if self.link and type(self.link) != TailNode: <NEW_LINE> <INDENT> temp = self.link <NEW_LINE> while temp.data != item: <NEW_LINE> <INDENT> if temp.link and type(temp.link) != TailNode: <NEW_LINE> <INDENT> temp = temp.link <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def delete(self, item): <NEW_LINE> <INDENT> if self.search(item) is True: <NEW_LINE> <INDENT> temp = self <NEW_LINE> while temp.link.data != item: <NEW_LINE> <INDENT> temp = temp.link <NEW_LINE> <DEDENT> temp.link = temp.link.link <NEW_LINE> <DEDENT> <DEDENT> def _predecessor_head(self, item): <NEW_LINE> <INDENT> p = self <NEW_LINE> if type(p.link) == TailNode: <NEW_LINE> <INDENT> return p <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while p.link and p.link.data < item: <NEW_LINE> <INDENT> if type(p.link.link) == TailNode: <NEW_LINE> <INDENT> return p.link <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = p.link <NEW_LINE> <DEDENT> <DEDENT> return p <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return _SkipIterHead(self) | A HeadNode object used in SkipList.
| 62599080dc8b845886d55061 |
class ProcessingStatus(atom.core.XmlElement): <NEW_LINE> <INDENT> _qname = SC_NAMESPACE_TEMPLATE % 'processing_status' | sc:processing_status element
| 62599080099cdd3c6367614d |
class RestaurantNoteSerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = RestaurantNote <NEW_LINE> fields = ('url', 'created', 'title', 'note_text', 'restaurant_id', 'favorite_dish', ) | This class defines the fields that get serialized/deserialized, related
to :model:`RestaurantNote`
author: Mark Ellis | 62599080442bda511e95daaa |
class AmFastError(Exception): <NEW_LINE> <INDENT> def _get_message(self): <NEW_LINE> <INDENT> return self._message <NEW_LINE> <DEDENT> def _set_message(self, message): <NEW_LINE> <INDENT> self._message = message <NEW_LINE> <DEDENT> message = property(_get_message, _set_message) | Base exception for this package. | 62599080aad79263cf430261 |
class Point(GeometryObject,IDisposable): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Create(coord,id=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReleaseManagedResources(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ReleaseUnmanagedResources(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> Coord=property(lambda self: object(),lambda self,v: None,lambda self: None) <NEW_LINE> Reference=property(lambda self: object(),lambda self,v: None,lambda self: None) | A 3D point. | 62599080283ffb24f3cf5347 |
class SNSPolicy(ServerlessResource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self["Type"] = "AWS::SNS::TopicPolicy" <NEW_LINE> self["Properties"] = { "PolicyDocument": { "Id": None, "Statement": [ { "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "sns:Publish", "Resource": None, } ], }, "Topics": [], } | Base class representing a SNS Topic Policy. Inherit and extend using dict interface | 625990807d847024c075de85 |
class Position: <NEW_LINE> <INDENT> def __init__(self, idx, ln, col, fn, ftxt): <NEW_LINE> <INDENT> self.idx = idx <NEW_LINE> self.ln = ln <NEW_LINE> self.col = col <NEW_LINE> self.fn = fn <NEW_LINE> self.ftxt = ftxt <NEW_LINE> <DEDENT> def advance(self, current_char=None): <NEW_LINE> <INDENT> self.idx += 1 <NEW_LINE> self.col += 1 <NEW_LINE> if current_char == '\n': <NEW_LINE> <INDENT> self.ln += 1 <NEW_LINE> self.col = 0 <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Position(self.idx, self.ln, self.col, self.fn, self.ftxt) | Class for keeping track of position.
Methods :
1. advance: updates current index pointer, if line ends, updates line number.
2. copy: returns a copy of its own POSITION object. | 6259908023849d37ff852b61 |
class TreeNode: <NEW_LINE> <INDENT> def __init__(self, init_quality=None, prior_probability=None): <NEW_LINE> <INDENT> self._quality_sum = 0 <NEW_LINE> self._quality_count = 0 <NEW_LINE> if init_quality is not None: <NEW_LINE> <INDENT> self.visit(init_quality) <NEW_LINE> <DEDENT> self.prior_probability = prior_probability <NEW_LINE> self.children = [] <NEW_LINE> <DEDENT> def visit(self, quality): <NEW_LINE> <INDENT> self._quality_sum += quality <NEW_LINE> self._quality_count += 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def quality(self): <NEW_LINE> <INDENT> return self._quality_sum / self._quality_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def count(self): <NEW_LINE> <INDENT> return self._quality_count <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> if self.is_leaf: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ( sum(child.quality * child.count for child in self.children) / sum(child.count for child in self.children) ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_leaf(self): <NEW_LINE> <INDENT> return not self.children | Node of the search tree.
Attrs:
children (list): List of children, indexed by action.
is_leaf (bool): Whether the node is a leaf, i.e. has not been expanded
yet. | 62599080d268445f2663a8b2 |
class TestSink(unittest.TestCase): <NEW_LINE> <INDENT> def test_instantiation(self): <NEW_LINE> <INDENT> id = "test_id" <NEW_LINE> stats = {} <NEW_LINE> decoder = Mock(name="decoder_object") <NEW_LINE> decoder.block_size = Mock(return_value=100) <NEW_LINE> c = simulator.sink.Sink(id, stats, decoder) <NEW_LINE> self.assertEqual(c.receiver.id, id) <NEW_LINE> self.assertEqual(c.receiver.decoder, decoder) | Class for testing Sink. | 6259908097e22403b383c9a8 |
class NickMask(six.text_type): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_params(cls, nick, user, host): <NEW_LINE> <INDENT> return cls('{nick}!{user}@{host}'.format(**vars())) <NEW_LINE> <DEDENT> @property <NEW_LINE> def nick(self): <NEW_LINE> <INDENT> nick, sep, userhost = self.partition("!") <NEW_LINE> return nick <NEW_LINE> <DEDENT> @property <NEW_LINE> def userhost(self): <NEW_LINE> <INDENT> nick, sep, userhost = self.partition("!") <NEW_LINE> return userhost or None <NEW_LINE> <DEDENT> @property <NEW_LINE> def host(self): <NEW_LINE> <INDENT> nick, sep, userhost = self.partition("!") <NEW_LINE> user, sep, host = userhost.partition('@') <NEW_LINE> return host or None <NEW_LINE> <DEDENT> @property <NEW_LINE> def user(self): <NEW_LINE> <INDENT> nick, sep, userhost = self.partition("!") <NEW_LINE> user, sep, host = userhost.partition('@') <NEW_LINE> return user or None | A nickmask (the source of an Event)
>>> nm = NickMask('[email protected]')
>>> print(nm.nick)
pinky
>>> print(nm.host)
example.com
>>> print(nm.user)
username
>>> isinstance(nm, six.text_type)
True
>>> nm = 'красный[email protected]'
>>> if not six.PY3: nm = nm.decode('utf-8')
>>> nm = NickMask(nm)
>>> isinstance(nm.nick, six.text_type)
True
Some messages omit the userhost. In that case, None is returned.
>>> nm = NickMask('irc.server.net')
>>> print(nm.nick)
irc.server.net
>>> nm.userhost
>>> nm.host
>>> nm.user | 62599080091ae356687066e8 |
class SolventShellsFeaturizer(Featurizer): <NEW_LINE> <INDENT> def __init__(self, solute_indices, solvent_indices, n_shells, shell_width, periodic=True): <NEW_LINE> <INDENT> self.solute_indices = solute_indices <NEW_LINE> self.solvent_indices = solvent_indices <NEW_LINE> self.n_shells = n_shells <NEW_LINE> self.shell_width = shell_width <NEW_LINE> self.periodic = periodic <NEW_LINE> self.n_solute = len(self.solute_indices) <NEW_LINE> self.n_features = self.n_solute * self.n_shells <NEW_LINE> <DEDENT> def partial_transform(self, traj): <NEW_LINE> <INDENT> n_shell = self.n_shells <NEW_LINE> shell_w = self.shell_width <NEW_LINE> shell_edges = np.linspace(0, shell_w * (n_shell + 1), num=(n_shell + 1), endpoint=True) <NEW_LINE> atom_pairs = np.zeros((len(self.solvent_indices), 2)) <NEW_LINE> shellcounts = np.zeros((traj.n_frames, self.n_solute, n_shell), dtype=int) <NEW_LINE> for i, solute_i in enumerate(self.solute_indices): <NEW_LINE> <INDENT> atom_pairs[:, 0] = solute_i <NEW_LINE> atom_pairs[:, 1] = self.solvent_indices <NEW_LINE> distances = md.compute_distances(traj, atom_pairs, periodic=self.periodic) <NEW_LINE> for j in range(n_shell): <NEW_LINE> <INDENT> shell_bool = np.logical_and( distances >= shell_edges[j], distances < shell_edges[j + 1] ) <NEW_LINE> shellcounts[:, i, j] = np.sum(shell_bool, axis=1) <NEW_LINE> <DEDENT> <DEDENT> shellcounts = analysis.normalize(shellcounts, shell_w) <NEW_LINE> shellcounts = analysis.reshape(shellcounts) <NEW_LINE> return shellcounts | Featurizer based on local, instantaneous water density.
Parameters
----------
solute_indices : np.ndarray, shape=(n_solute,1)
Indices of solute atoms
solvent_indices : np.ndarray, shape=(n_solvent, 1)
Indices of solvent atoms
n_shells : int
Number of shells to consider around each solute atom
shell_width : float
The width of each solvent atom
periodic : bool
Whether to consider a periodic system in distance calculations
Returns
-------
shellcounts : np.ndarray, shape=(n_frames, n_solute, n_shells)
Number of solvent atoms in shell_i around solute_i at frame_i
References
---------- | 62599080d486a94d0ba2da5f |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.