code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Problem(object): <NEW_LINE> <INDENT> def __init__(self, initial, goal=None): <NEW_LINE> <INDENT> self.initial = initial <NEW_LINE> self.goal = goal <NEW_LINE> <DEDENT> def actions(self, state): <NEW_LINE> <INDENT> raise NotImplementedError('Subclasses must implement abstract methods') <NEW_LINE> <DEDENT> def result(self, state, action): <NEW_LINE> <INDENT> raise NotImplementedError('Subclasses must implement abstract methods') <NEW_LINE> <DEDENT> def goal_test(self, state): <NEW_LINE> <INDENT> if isinstance(state, list): <NEW_LINE> <INDENT> return is_in(state, self.goal) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return state == self.goal <NEW_LINE> <DEDENT> <DEDENT> def path_cost(self, cost, state1, action, state2): <NEW_LINE> <INDENT> return cost + 1 <NEW_LINE> <DEDENT> def value(self, state): <NEW_LINE> <INDENT> raise NotImplementedError('Subclasses must implement abstract methods') | Abstract class representing a formal problem.
| 62598fe1091ae35668705287 |
class Len(Processor): <NEW_LINE> <INDENT> def __call__( self, values: Union[List[str], str], response: Response = None, default: str = "" ) -> Tuple[Union[List[str], str], Dict]: <NEW_LINE> <INDENT> return str(len(values)), {} | Return length | 62598fe1adb09d7d5dc0abe3 |
class PlaceCrop(object): <NEW_LINE> <INDENT> def __init__(self, size, start_x, start_y): <NEW_LINE> <INDENT> if isinstance(size, int): <NEW_LINE> <INDENT> self.size = (int(size), int(size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> self.start_x = start_x <NEW_LINE> self.start_y = start_y <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> th, tw = self.size <NEW_LINE> return img.crop((self.start_x, self.start_y, self.start_x + tw, self.start_y + th)) | Crops the given PIL.Image at the particular index.
Args:
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (w, h), a square crop (size, size) is
made. | 62598fe14c3428357761a91a |
class CompanyUrl(models.Model): <NEW_LINE> <INDENT> company_info = models.ForeignKey('CompanyInfo', related_name='company_url', db_constraint=False, null=True) <NEW_LINE> company_url = models.CharField(max_length=50, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.company_url | 公司网址 | 62598fe1d8ef3951e32c8192 |
class Action(BrowserSearchParams): <NEW_LINE> <INDENT> def __init__(self, position, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.kwargs = kwargs <NEW_LINE> self.position = position <NEW_LINE> <DEDENT> def getActionHash(self): <NEW_LINE> <INDENT> return hashlib.md5(f'{type(self).__name__}:{self.position}:{self.css}:{self.xpath}'.encode('utf-8')).hexdigest() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def execute(chain, action): <NEW_LINE> <INDENT> actionType = type(action).__name__ <NEW_LINE> try: <NEW_LINE> <INDENT> ret = getattr(chain, f'on{actionType}')(action) <NEW_LINE> logging.debug(f'Action::execute: Action executed succesfully, name=[{chain.name}], position=[{action.position}]') <NEW_LINE> return ret <NEW_LINE> <DEDENT> except ActionChainException as ex: <NEW_LINE> <INDENT> Action.publishActionError(chain, ex) <NEW_LINE> logging.info(f'{type(ex).__name__} thrown whilst processing') <NEW_LINE> return False <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> logging.warning(f'Action::execute:: {type(ex).__name__} thrown whilst processing name=[{chain.name}], position=[{action.position}], args=[{ex.args}]') <NEW_LINE> Action.publishUnhandledActionError(chain, ex, action) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def getActionableItem(self, action, driver): <NEW_LINE> <INDENT> item = self.search(driver) <NEW_LINE> logging.info(f'{type(self).__name__}::getActionableItem: have num_items=[{ 1 if not isinstance(item, list) else len(item)}]') <NEW_LINE> return item <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_params(): <NEW_LINE> <INDENT> return [self.__dict__().keys()] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def publishActionError(chain, actionException): <NEW_LINE> <INDENT> actionException.userID = chain.nannyClient.behalf <NEW_LINE> chain.nannyClient.put(f'/actionsmanager/reportActionError/{actionException.chainName}', payload=actionException.__dict__()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def publishUnhandledActionError(chain, exception, action): <NEW_LINE> <INDENT> logging.warning(f'Unhandled exception in action {action.__dict__()}, exception={exception.args}') <NEW_LINE> pass | Base action class | 62598fe1adb09d7d5dc0abe5 |
class Encryption(Packaging): <NEW_LINE> <INDENT> def __init__(self, encryption_mechanism=None, encryption_key=None): <NEW_LINE> <INDENT> super(Encryption, self).__init__() <NEW_LINE> self.encryption_mechanism = encryption_mechanism <NEW_LINE> self.encryption_key = encryption_key <NEW_LINE> <DEDENT> def to_obj(self): <NEW_LINE> <INDENT> obj = artifact_binding.EncryptionType() <NEW_LINE> if self.encryption_mechanism: <NEW_LINE> <INDENT> obj.set_encryption_mechanism(self.encryption_mechanism) <NEW_LINE> <DEDENT> if self.encryption_key: <NEW_LINE> <INDENT> obj.set_encryption_key(self.encryption_key) <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> dict_ = {} <NEW_LINE> dict_['packaging_type'] = 'encryption' <NEW_LINE> if self.encryption_mechanism: <NEW_LINE> <INDENT> dict_['encryption_mechanism'] = self.encryption_mechanism <NEW_LINE> <DEDENT> if self.encryption_key: <NEW_LINE> <INDENT> dict_['encryption_key'] = self.encryption_key <NEW_LINE> <DEDENT> return dict_ <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_obj(encryption_obj): <NEW_LINE> <INDENT> mechanism = encryption_obj.get_encryption_mechanism() <NEW_LINE> key = encryption_obj.get_encryption_key() <NEW_LINE> return Encryption.get_object(mechanism, key) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_dict(encryption_dict): <NEW_LINE> <INDENT> mechanism = encryption_dict.get('encryption_mechanism') <NEW_LINE> key = encryption_dict.get('encryption_key') <NEW_LINE> return Encryption.get_object(mechanism, key) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_object(mechanism, key): <NEW_LINE> <INDENT> if mechanism == 'xor': <NEW_LINE> <INDENT> return XOREncryption(key) <NEW_LINE> <DEDENT> if mechanism == 'PasswordProtected': <NEW_LINE> <INDENT> return PasswordProtectedZipEncryption(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unsupported encryption mechanism: %s" % mechanism) | An encryption packaging layer. | 62598fe1ab23a570cc2d50a6 |
class AssignmentGroupTag(models.Model): <NEW_LINE> <INDENT> assignment_group = models.ForeignKey(AssignmentGroup, related_name='tags', on_delete=models.CASCADE) <NEW_LINE> tag = models.SlugField(max_length=20, help_text='A tag can contain a-z, A-Z, 0-9 and "_".') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'core' <NEW_LINE> ordering = ['tag'] <NEW_LINE> unique_together = ('assignment_group', 'tag') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.tag | An AssignmentGroup can be tagged with zero or more tags using this class.
.. attribute:: assignment_group
The `AssignmentGroup`_ where this groups belongs.
.. attribute:: tag
The tag. Max 20 characters. Can only contain a-z, A-Z, 0-9 and "_". | 62598fe14c3428357761a91e |
class SiteSettingListAPIView(generics.ListAPIView): <NEW_LINE> <INDENT> serializer_class = SiteSettingSerializer <NEW_LINE> pagination_class = None <NEW_LINE> permission_classes = (IsAuthenticatedOrReadOnly,) <NEW_LINE> queryset = Table.objects.all() | list site settings details
GET /api/setting/ | 62598fe1d8ef3951e32c8195 |
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = db.Column( db.Integer, primary_key=True, ) <NEW_LINE> email = db.Column( db.Text, nullable=False, unique=True, ) <NEW_LINE> username = db.Column( db.Text, nullable=False, unique=True, ) <NEW_LINE> image_url = db.Column( db.Text, default="/static/images/default-pic.png", ) <NEW_LINE> header_image_url = db.Column( db.Text, default="/static/images/warbler-hero.jpg" ) <NEW_LINE> bio = db.Column( db.Text, ) <NEW_LINE> location = db.Column( db.Text, ) <NEW_LINE> password = db.Column( db.Text, nullable=False, ) <NEW_LINE> messages = db.relationship('Message') <NEW_LINE> followers = db.relationship( "User", secondary="follows", primaryjoin=(Follows.user_being_followed_id == id), secondaryjoin=(Follows.user_following_id == id) ) <NEW_LINE> following = db.relationship( "User", secondary="follows", primaryjoin=(Follows.user_following_id == id), secondaryjoin=(Follows.user_being_followed_id == id) ) <NEW_LINE> likes = db.relationship( 'Message', secondary="likes" , backref="likes_users" ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f"<User #{self.id}: {self.username}, {self.email}>" <NEW_LINE> <DEDENT> def is_followed_by(self, other_user): <NEW_LINE> <INDENT> found_user_list = [user for user in self.followers if user == other_user] <NEW_LINE> return len(found_user_list) == 1 <NEW_LINE> <DEDENT> def is_following(self, other_user): <NEW_LINE> <INDENT> found_user_list = [user for user in self.following if user == other_user] <NEW_LINE> return len(found_user_list) == 1 <NEW_LINE> <DEDENT> def is_like(self , check_message): <NEW_LINE> <INDENT> found_message_list = [message for message in self.likes if message.id == check_message.id] <NEW_LINE> return len(found_message_list) == 1 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def signup(cls, username, email, password, image_url): <NEW_LINE> <INDENT> hashed_pwd = bcrypt.generate_password_hash(password).decode('UTF-8') <NEW_LINE> user = User( username=username, email=email, password=hashed_pwd, image_url=image_url, ) <NEW_LINE> db.session.add(user) <NEW_LINE> return user <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def authenticate(cls, username, password): <NEW_LINE> <INDENT> user = cls.query.filter_by(username=username).first() <NEW_LINE> if user: <NEW_LINE> <INDENT> is_auth = bcrypt.check_password_hash(user.password, password) <NEW_LINE> if is_auth: <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> <DEDENT> return False | User in the system. | 62598fe1fbf16365ca794736 |
class ViewletManagerTile(Tile): <NEW_LINE> <INDENT> implements(IViewletManagerTile) <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> manager = self.data.get('manager') <NEW_LINE> viewName = self.data.get('view', None) <NEW_LINE> section = self.data.get('section', 'body') <NEW_LINE> view = findView(self, viewName) <NEW_LINE> managerObj = queryMultiAdapter((self.context, self.request, view), IViewletManager, name=manager) <NEW_LINE> managerObj.update() <NEW_LINE> if section == 'head': <NEW_LINE> <INDENT> return u"<html><head>%s</head></html>" % managerObj.render() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u"<html><body>%s</body></html>" % managerObj.render() | A tile that renders a viewlet manager. | 62598fe1ad47b63b2c5a7ec3 |
class KiwiDescriptionConflict(KiwiError): <NEW_LINE> <INDENT> pass | Exception raised if both, a description file and xml_content
is provided | 62598fe126238365f5fad1d7 |
class Four_Bar (pga.PGA, autosuper) : <NEW_LINE> <INDENT> def __init__ (self, args) : <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.F = 10. <NEW_LINE> self.E = 2e5 <NEW_LINE> self.L = 200. <NEW_LINE> self.sigma = 10. <NEW_LINE> q2 = self.q2 = sqrt (2) <NEW_LINE> b = self.F / self.sigma <NEW_LINE> minmax = [(b, 3*b), (q2 * b, 3 * b), (q2 * b, 3 * b), (b, 3 * b)] <NEW_LINE> d = dict ( maximize = False , num_eval = 2 , num_constraint = 0 , pop_size = 60 , num_replace = 60 , select_type = pga.PGA_SELECT_LINEAR , pop_replace_type = pga.PGA_POPREPL_NSGA_II , mutation_only = True , mutation_type = pga.PGA_MUTATION_DE , DE_crossover_prob = 0.8 , DE_crossover_type = pga.PGA_DE_CROSSOVER_BIN , DE_variant = pga.PGA_DE_VARIANT_RAND , DE_scale_factor = 0.85 , init = minmax , max_GA_iter = 100 , print_options = [pga.PGA_REPORT_STRING] , mutation_bounce_back = True ) <NEW_LINE> if args.random_seed : <NEW_LINE> <INDENT> d ['random_seed'] = args.random_seed <NEW_LINE> <DEDENT> self.__super.__init__ (float, 4, **d) <NEW_LINE> <DEDENT> def evaluate (self, p, pop) : <NEW_LINE> <INDENT> x = [] <NEW_LINE> for i in range (len (self)) : <NEW_LINE> <INDENT> x.append (self.get_allele (p, pop, i)) <NEW_LINE> <DEDENT> q2 = self.q2 <NEW_LINE> f1 = self.L * (2 * x [0] + q2 * x [1] + q2 * x [2] + x [3]) <NEW_LINE> f2 = self.F * self.L / self.E * (2 / x [0] + 2 * q2 / x [1] - 2 * q2 / x [2] + 2 / x [3]) <NEW_LINE> return f1, f2 | Example from [1]
[1] Tapabrata Ray, Kang Tai, and Kin Chye Seow. Multiobjective
design optimization by an evolutionary algorithm. Engineering
Optimization, 33(4):399–424, 2001. | 62598fe1ab23a570cc2d50a8 |
class Vimeo(Directive): <NEW_LINE> <INDENT> required_arguments = 1 <NEW_LINE> optional_arguments = 0 <NEW_LINE> option_spec = { 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'border': directives.length_or_unitless, 'align': align, 'allowfullscreen': boolean, } <NEW_LINE> has_content = False <NEW_LINE> def run(self): <NEW_LINE> <INDENT> self.options['uri'] = 'http://player.vimeo.com/video/' + self.arguments[0] <NEW_LINE> self.options.setdefault('width', '425px') <NEW_LINE> self.options.setdefault('height', '344px') <NEW_LINE> self.options.setdefault('align', 'center') <NEW_LINE> self.options.setdefault('border', '0') <NEW_LINE> self.options.setdefault('allowfullscreen', 'true') <NEW_LINE> return [iframe_flash_video('', **self.options)] | reStructuredText directive that creates an embed object to display
a video from Vimeo
Usage example::
.. vimeo:: QFwQIRwuAM0
:align: center
:height: 344
:width: 425 | 62598fe1187af65679d29f30 |
class Split(BaseEntity): <NEW_LINE> <INDENT> distance = Attribute(float, units=uh.meters) <NEW_LINE> elapsed_time = TimeIntervalAttribute() <NEW_LINE> elevation_difference = Attribute(float, units=uh.meters) <NEW_LINE> moving_time = TimeIntervalAttribute() <NEW_LINE> average_heartrate = Attribute(float) <NEW_LINE> split = Attribute(int) <NEW_LINE> pace_zone = Attribute(int) <NEW_LINE> average_speed = Attribute(float, units=uh.meters_per_second) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Split split={} distance={} elapsed_time={}>'.format(self.split, self.distance, self.elapsed_time) | A split -- may be metric or standard units (which has no bearing
on the units used in this object, just the binning of values). | 62598fe1091ae35668705291 |
class RandomManipulation(object): <NEW_LINE> <INDENT> num_hinge_atoms = None <NEW_LINE> def __init__(self, affected_atoms, max_amplitude, hinge_atoms): <NEW_LINE> <INDENT> if len(hinge_atoms) != self.num_hinge_atoms: <NEW_LINE> <INDENT> raise ValueError("The number of hinge atoms must be %i, got %i." % ( self.num_hinge_atoms, len(hinge_atoms) )) <NEW_LINE> <DEDENT> self.affected_atoms = affected_atoms <NEW_LINE> self.max_amplitude = max_amplitude <NEW_LINE> self.hinge_atoms = hinge_atoms <NEW_LINE> <DEDENT> def apply(self, coordinates): <NEW_LINE> <INDENT> transform = self.get_transformation(coordinates) <NEW_LINE> result = MolecularDistortion(self.affected_atoms, transform) <NEW_LINE> result.apply(coordinates) <NEW_LINE> return result <NEW_LINE> <DEDENT> def get_transformation(self, coordinates): <NEW_LINE> <INDENT> raise NotImplementedError | Base class for a random manipulation | 62598fe1fbf16365ca794738 |
class CmdGoto(MuxCommand): <NEW_LINE> <INDENT> key = "goto" <NEW_LINE> aliases = ["go"] <NEW_LINE> locks = "cmd:all()" <NEW_LINE> help_cateogory = "General" <NEW_LINE> arg_regex = r"\s.*?|$" <NEW_LINE> def func(self): <NEW_LINE> <INDENT> caller = self.caller <NEW_LINE> if not self.args: <NEW_LINE> <INDENT> caller.msg("你要去哪里?") <NEW_LINE> return <NEW_LINE> <DEDENT> obj = caller.search(self.args, location=caller.location) <NEW_LINE> if not obj: <NEW_LINE> <INDENT> caller.msg("没有找到%s" % (self.args)) <NEW_LINE> return <NEW_LINE> <DEDENT> if obj.access(self.caller, 'traverse'): <NEW_LINE> <INDENT> obj.at_traverse(caller, obj.destination) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if obj.db.err_traverse: <NEW_LINE> <INDENT> caller.msg(self.obj.db.err_traverse) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj.at_failed_traverse(caller) | goto exit
Usage:
goto exit | 62598fe150812a4eaa620f1c |
class PM_TreeView(QTreeView): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> QTreeView.__init__(self, parent) <NEW_LINE> self.parent = parent <NEW_LINE> self.setEnabled(True) <NEW_LINE> self.model = QDirModel( ['*.mmp', '*.MMP'], QDir.AllEntries|QDir.AllDirs|QDir.NoDotAndDotDot, QDir.Name ) <NEW_LINE> self.path = None <NEW_LINE> self.setModel(self.model) <NEW_LINE> self.setWindowTitle(self.tr("Tree View")) <NEW_LINE> self.setItemsExpandable(True) <NEW_LINE> self.setAlternatingRowColors(True) <NEW_LINE> self.setColumnWidth(0, 150) <NEW_LINE> self.setSortingEnabled(True) <NEW_LINE> self.sortByColumn(0, Qt.AscendingOrder) <NEW_LINE> self.setMinimumHeight(300) <NEW_LINE> for i in range(2, 4): <NEW_LINE> <INDENT> self.setColumnWidth(i, 4) <NEW_LINE> <DEDENT> filePath = os.path.dirname(os.path.abspath(sys.argv[0])) <NEW_LINE> libDir = os.path.normpath(filePath + '/../partlib') <NEW_LINE> self.libPathKey = '/nanorex/nE-1/libraryPath' <NEW_LINE> libDir = env.prefs.get(self.libPathKey, libDir) <NEW_LINE> if os.path.isdir(libDir): <NEW_LINE> <INDENT> self.rootDir = libDir <NEW_LINE> self.setRootPath(libDir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rootDir = None <NEW_LINE> env.history.message(redmsg("The part library directory: %s doesn't" " exist." %libDir)) <NEW_LINE> <DEDENT> self.show() <NEW_LINE> <DEDENT> def mouseReleaseEvent(self, evt): <NEW_LINE> <INDENT> if self.selectedItem() is not None: <NEW_LINE> <INDENT> self.parent.partChanged(self.selectedItem()) <NEW_LINE> <DEDENT> return QTreeView.mouseReleaseEvent(self, evt) <NEW_LINE> <DEDENT> def resizeEvent(self, evt): <NEW_LINE> <INDENT> if self.selectedItem() is not None: <NEW_LINE> <INDENT> self.parent.partChanged(self.selectedItem()) <NEW_LINE> <DEDENT> return QTreeView.resizeEvent(self, evt) <NEW_LINE> <DEDENT> def setRootPath(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.setRootIndex(self.model.index(path)) <NEW_LINE> <DEDENT> def selectedItem(self): <NEW_LINE> <INDENT> indexes = self.selectedIndexes() <NEW_LINE> if not indexes: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> index = indexes[0] <NEW_LINE> if not index.isValid(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.FileItem(str(self.model.filePath(index))) <NEW_LINE> <DEDENT> class FileItem: <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> dummy, self.fileName = os.path.split(path) <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return self.fileName <NEW_LINE> <DEDENT> def getFileObj(self): <NEW_LINE> <INDENT> return self.path | The PM_TreeView class provides a partlib object (as a 'treeview' of any user
specified directory) to the client code. The parts from the partlib can be
pasted in the 3D Workspace. | 62598fe14c3428357761a928 |
class GetSubscription(webapp2.RequestHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> request = json.loads(self.request.body) <NEW_LINE> subscription = Subscription.getInstance(request['project']) <NEW_LINE> self.response.write(json.dumps(subscription.to_dict())) | Remove a list of emails from the subscribe list. | 62598fe1091ae35668705297 |
class VideoPlayer(Container): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> tag = "video" | The HTML Video element (`<video>`) embeds a media player which supports
video playback into the document. You can use `<video>` for audio content
as well, but the `<audio>` element may provide a more appropriate user
experience. | 62598fe1d8ef3951e32c8199 |
class User(commands.MemberConverter): <NEW_LINE> <INDENT> async def convert(self, ctx, argument): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return await commands.MemberConverter().convert(ctx, argument) <NEW_LINE> <DEDENT> except commands.BadArgument: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return await commands.UserConverter().convert(ctx, argument) <NEW_LINE> <DEDENT> except commands.BadArgument: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> match = self._get_id_match(argument) <NEW_LINE> if match is None: <NEW_LINE> <INDENT> raise commands.BadArgument('User "{}" not found'.format(argument)) <NEW_LINE> <DEDENT> return discord.Object(int(match.group(1))) | A custom discord.py `Converter` that
supports `Member`, `User`, and string ID's. | 62598fe1fbf16365ca79473e |
class Observer: <NEW_LINE> <INDENT> r = JProperty() <NEW_LINE> def __init__(self, r, sources, observable='uvw', transform=None): <NEW_LINE> <INDENT> if not isinstance(sources, SourceCollection): <NEW_LINE> <INDENT> if isinstance(sources, Source): <NEW_LINE> <INDENT> sources = {'source': sources} <NEW_LINE> <DEDENT> sources = SourceCollection(sources) <NEW_LINE> <DEDENT> self.sources = sources <NEW_LINE> self.sources.observable = observable <NEW_LINE> self.sources.transform = transform or (lambda r, F: F) <NEW_LINE> self.r = r <NEW_LINE> <DEDENT> def E(self, t=0.0): <NEW_LINE> <INDENT> return self.sources.E(self.r(t), t) <NEW_LINE> <DEDENT> def B(self, t=0.0): <NEW_LINE> <INDENT> return self.sources.B(self.r(t), t) <NEW_LINE> <DEDENT> def S(self, t=0.0): <NEW_LINE> <INDENT> return self.sources.S(self.r(t), t) | "
A set of registered measurement locations that observes a collection of
sources. A convenient way to use jefpy. Yields E and B as functions of t.
These functions can be used directly or used as call-backs in visualizations. | 62598fe1d8ef3951e32c819a |
class RealDisk(Disk): <NEW_LINE> <INDENT> def __init__(self, size=DISKSIZE): <NEW_LINE> <INDENT> Disk.__init__(self, size=size, fits=7800, nre=1.0e-14, desc="real-world disk") | Specs from Schroeders 2007 FAST paper | 62598fe1ad47b63b2c5a7ecc |
class VigraRfPixelwiseClassifierFactory(LazyflowPixelwiseClassifierFactoryABC): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._args = args <NEW_LINE> self._kwargs = kwargs <NEW_LINE> <DEDENT> def create_and_train_pixelwise(self, feature_images, label_images, axistags=None): <NEW_LINE> <INDENT> logger.debug( 'training pixel-wise vigra RF' ) <NEW_LINE> all_features = numpy.ndarray( shape=(0, feature_images[0].shape[-1]), dtype=numpy.float32 ) <NEW_LINE> all_labels = numpy.ndarray( shape=(0,1), dtype=numpy.uint32 ) <NEW_LINE> for feature_image, label_image in zip(feature_images, label_images): <NEW_LINE> <INDENT> label_coords = numpy.nonzero(label_image)[:-1] <NEW_LINE> label_vector = label_image[label_coords] <NEW_LINE> feature_matrix = feature_image[label_coords] <NEW_LINE> all_features = numpy.concatenate((all_features, feature_matrix), axis=0) <NEW_LINE> all_labels = numpy.concatenate((all_labels, label_vector), axis=0) <NEW_LINE> <DEDENT> known_labels = numpy.unique(all_labels) <NEW_LINE> assert len(all_features) == len(all_labels) <NEW_LINE> classifier = vigra.learning.RandomForest(*self._args, **self._kwargs) <NEW_LINE> classifier.learnRF(all_features, all_labels) <NEW_LINE> return VigraRfPixelwiseClassifier( classifier, known_labels ) <NEW_LINE> <DEDENT> def get_halo_shape(self, data_axes): <NEW_LINE> <INDENT> halo = tuple(range( len(data_axes)-1 )) <NEW_LINE> return halo + (0,) <NEW_LINE> <DEDENT> def estimated_ram_usage_per_requested_predictionchannel(self): <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> temp_rf = vigra.learning.RandomForest( *self._args, **self._kwargs ) <NEW_LINE> return "Vigra Random Forest ({} trees)".format( temp_rf.treeCount() ) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return ( isinstance(other, type(self)) and self._args == other._args and self._kwargs == other._kwargs ) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) | An implementation of LazyflowPixelwiseClassifierFactoryABC using a vigra RandomForest.
This exists for testing purposes only. (it is normally better to use the vector-wise
classifier so lazyflow can cache the feature matrices).
This implementation is simple and un-optimized. | 62598fe1c4546d3d9def75c4 |
class DeleteStatement(Query): <NEW_LINE> <INDENT> def __init__(self, queryInput): <NEW_LINE> <INDENT> self.database = None <NEW_LINE> self.tableName, self.conditions = self.__parseDelete(queryInput) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if self.database is None: <NEW_LINE> <INDENT> print("!Failed to delete from table", self.tableName, "because no database is selected!") <NEW_LINE> return None <NEW_LINE> <DEDENT> table = self.database.getTableByName(self.tableName) <NEW_LINE> if table is None: <NEW_LINE> <INDENT> print("!Failed to delete from table", self.tableName, "because table does not exist!") <NEW_LINE> return None <NEW_LINE> <DEDENT> if not self.database.isWritable(table.tableName): <NEW_LINE> <INDENT> print(f"Error: Table {table.tableName} is locked!") <NEW_LINE> return <NEW_LINE> <DEDENT> table.delete(self.conditions) <NEW_LINE> self.database.successfulTransactions += 1 <NEW_LINE> <DEDENT> def __parseDelete(self, queryInput): <NEW_LINE> <INDENT> tableName = queryInput[0] <NEW_LINE> conditions = queryInput[2:] <NEW_LINE> return tableName, conditions | Models a DELETE statement in a SQL database | 62598fe1ab23a570cc2d50af |
@NoiseGenerator.register_class <NEW_LINE> class WhiteNoiseGenerator(NoiseGenerator): <NEW_LINE> <INDENT> NAME = 'white' <NEW_LINE> _SNR_VALUE_PAIRS = [ [0, -10], [-5, -15], [-10, -20], [-20, -30], ] <NEW_LINE> _NOISY_SIGNAL_FILENAME_TEMPLATE = 'noise_{0:d}_SNR.wav' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> NoiseGenerator.__init__(self) <NEW_LINE> <DEDENT> def _generate( self, input_signal_filepath, input_noise_cache_path, base_output_path): <NEW_LINE> <INDENT> input_signal = SignalProcessingUtils.load_wav(input_signal_filepath) <NEW_LINE> input_signal = SignalProcessingUtils.normalize(input_signal) <NEW_LINE> noise_signal = SignalProcessingUtils.generate_white_noise(input_signal) <NEW_LINE> noise_signal = SignalProcessingUtils.normalize(noise_signal) <NEW_LINE> noisy_mix_filepaths = {} <NEW_LINE> snr_values = set([snr for pair in self._SNR_VALUE_PAIRS for snr in pair]) <NEW_LINE> for snr in snr_values: <NEW_LINE> <INDENT> noisy_signal_filepath = os.path.join( input_noise_cache_path, self._NOISY_SIGNAL_FILENAME_TEMPLATE.format(snr)) <NEW_LINE> if not os.path.exists(noisy_signal_filepath): <NEW_LINE> <INDENT> noisy_signal = SignalProcessingUtils.mix_signals( noise_signal, input_signal, snr) <NEW_LINE> SignalProcessingUtils.save_wav(noisy_signal_filepath, noisy_signal) <NEW_LINE> <DEDENT> noisy_mix_filepaths[snr] = noisy_signal_filepath <NEW_LINE> <DEDENT> for snr_noisy, snr_refence in self._SNR_VALUE_PAIRS: <NEW_LINE> <INDENT> config_name = '{0:d}_{1:d}_SNR'.format(snr_noisy, snr_refence) <NEW_LINE> output_path = self._make_dir(base_output_path, config_name) <NEW_LINE> self._add_noise_reference_files_pair( config_name=config_name, noisy_signal_filepath=noisy_mix_filepaths[snr_noisy], reference_signal_filepath=noisy_mix_filepaths[snr_refence], output_path=output_path) | Additive white noise generator. | 62598fe1ad47b63b2c5a7ed2 |
class IGTVDataAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = [ "date", "igtv", "likes", "comments", "reach", "impressions", "saved", "video_views", ] <NEW_LINE> list_display_links = ["date", "igtv"] <NEW_LINE> list_filter = ["igtv__insta"] <NEW_LINE> date_hierarchy = "date" <NEW_LINE> search_fields = ["igtv__external_id", "igtv__video_title"] | List for choosing existing IGTV data to edit. | 62598fe1c4546d3d9def75c7 |
class GlancesInstance(): <NEW_LINE> <INDENT> def __init__(self, refresh_time=1): <NEW_LINE> <INDENT> self.timer = Timer(0) <NEW_LINE> self.refresh_time = refresh_time <NEW_LINE> <DEDENT> def __update__(self): <NEW_LINE> <INDENT> if self.timer.finished(): <NEW_LINE> <INDENT> stats.update() <NEW_LINE> <DEDENT> self.timer = Timer(self.refresh_time) <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> return __version__ <NEW_LINE> <DEDENT> def getAll(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getAll()) <NEW_LINE> <DEDENT> def getSystem(self): <NEW_LINE> <INDENT> return json.dumps(stats.getSystem()) <NEW_LINE> <DEDENT> def getCore(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getCore()) <NEW_LINE> <DEDENT> def getCpu(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getCpu()) <NEW_LINE> <DEDENT> def getLoad(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getLoad()) <NEW_LINE> <DEDENT> def getMem(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getMem()) <NEW_LINE> <DEDENT> def getMemSwap(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getMemSwap()) <NEW_LINE> <DEDENT> def getNow(self): <NEW_LINE> <INDENT> self.__update__() <NEW_LINE> return json.dumps(stats.getNow()) | All the methods of this class are published as XML RPC methods | 62598fe14c3428357761a932 |
class Program(DeclarativeBase): <NEW_LINE> <INDENT> __tablename__ = 'programs' <NEW_LINE> name = Column(Unicode(200), primary_key=True) <NEW_LINE> seasons = relationship('Season', backref='program', order_by=[Season.number]) <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Program(%s)>" % repr(self.name) | Represents a program (i.e. a TV series) | 62598fe1d8ef3951e32c819e |
class PowerWallEnergySensor(PowerWallEntity, SensorEntity): <NEW_LINE> <INDENT> _attr_state_class = STATE_CLASS_MEASUREMENT <NEW_LINE> _attr_native_unit_of_measurement = POWER_KILO_WATT <NEW_LINE> _attr_device_class = DEVICE_CLASS_POWER <NEW_LINE> def __init__( self, meter: MeterType, coordinator, site_info, status, device_type, powerwalls_serial_numbers, ): <NEW_LINE> <INDENT> super().__init__( coordinator, site_info, status, device_type, powerwalls_serial_numbers ) <NEW_LINE> self._meter = meter <NEW_LINE> self._attr_name = f"Powerwall {self._meter.value.title()} Now" <NEW_LINE> self._attr_unique_id = ( f"{self.base_unique_id}_{self._meter.value}_instant_power" ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_value(self): <NEW_LINE> <INDENT> return ( self.coordinator.data[POWERWALL_API_METERS] .get_meter(self._meter) .get_power(precision=3) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self): <NEW_LINE> <INDENT> meter = self.coordinator.data[POWERWALL_API_METERS].get_meter(self._meter) <NEW_LINE> return { ATTR_FREQUENCY: round(meter.frequency, 1), ATTR_INSTANT_AVERAGE_VOLTAGE: round(meter.average_voltage, 1), ATTR_INSTANT_TOTAL_CURRENT: meter.get_instant_total_current(), ATTR_IS_ACTIVE: meter.is_active(), } | Representation of an Powerwall Energy sensor. | 62598fe14c3428357761a934 |
@register_exception <NEW_LINE> class InvalidAuthTokenError(errors.Unauthorized): <NEW_LINE> <INDENT> wire_descrition = "invalid auth token" <NEW_LINE> status = 401 | Exception raised when failing to get authorization for some action because
the provided token either does not exist in the tokens database, has a
distinct structure from the expected one, or is associated with a user
with a distinct uuid than the one provided by the client. | 62598fe2ad47b63b2c5a7ed8 |
class FileIOCalculator(Calculator): <NEW_LINE> <INDENT> command: Optional[str] = None <NEW_LINE> def __init__(self, restart=None, ignore_bad_restart_file=Calculator._deprecated, label=None, atoms=None, command=None, **kwargs): <NEW_LINE> <INDENT> Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) <NEW_LINE> if command is not None: <NEW_LINE> <INDENT> self.command = command <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = 'ASE_' + self.name.upper() + '_COMMAND' <NEW_LINE> self.command = os.environ.get(name, self.command) <NEW_LINE> <DEDENT> <DEDENT> def calculate(self, atoms=None, properties=['energy'], system_changes=all_changes): <NEW_LINE> <INDENT> Calculator.calculate(self, atoms, properties, system_changes) <NEW_LINE> self.write_input(self.atoms, properties, system_changes) <NEW_LINE> if self.command is None: <NEW_LINE> <INDENT> raise CalculatorSetupError( 'Please set ${} environment variable ' .format('ASE_' + self.name.upper() + '_COMMAND') + 'or supply the command keyword') <NEW_LINE> <DEDENT> command = self.command <NEW_LINE> if 'PREFIX' in command: <NEW_LINE> <INDENT> command = command.replace('PREFIX', self.prefix) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> proc = subprocess.Popen(command, shell=True, cwd=self.directory) <NEW_LINE> <DEDENT> except OSError as err: <NEW_LINE> <INDENT> msg = 'Failed to execute "{}"'.format(command) <NEW_LINE> raise EnvironmentError(msg) from err <NEW_LINE> <DEDENT> errorcode = proc.wait() <NEW_LINE> if errorcode: <NEW_LINE> <INDENT> path = os.path.abspath(self.directory) <NEW_LINE> msg = ('Calculator "{}" failed with command "{}" failed in ' '{} with error code {}'.format(self.name, command, path, errorcode)) <NEW_LINE> raise CalculationFailed(msg) <NEW_LINE> <DEDENT> self.read_results() <NEW_LINE> <DEDENT> def write_input(self, atoms, properties=None, system_changes=None): <NEW_LINE> <INDENT> absdir = os.path.abspath(self.directory) <NEW_LINE> if absdir != os.curdir and not os.path.isdir(self.directory): <NEW_LINE> <INDENT> os.makedirs(self.directory) <NEW_LINE> <DEDENT> <DEDENT> def read_results(self): <NEW_LINE> <INDENT> pass | Base class for calculators that write/read input/output files. | 62598fe2ab23a570cc2d50b3 |
class NotificationData(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.__dict__.update(kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s(%s)' % (self.__class__.__name__, ', '.join('%s=%r' % (name, value) for name, value in self.__dict__.iteritems())) <NEW_LINE> <DEDENT> __str__ = __repr__ | Object containing the notification data | 62598fe2d8ef3951e32c81a1 |
class StackBlock(MultBreakBlock): <NEW_LINE> <INDENT> def __init__(self, elements: Iterable[LayoutBlock], break_mult: float = 1): <NEW_LINE> <INDENT> super().__init__(elements, break_mult) <NEW_LINE> <DEDENT> def extended(self, new_elements: Iterable[LayoutBlock]) -> "StackBlock": <NEW_LINE> <INDENT> return self.__class__( chain(self.elements, new_elements), break_mult=self.break_mult ) <NEW_LINE> <DEDENT> def DoOptLayout( self, rest_of_line: Optional[Solution], options: Options ) -> Solution: <NEW_LINE> <INDENT> if not self.elements: <NEW_LINE> <INDENT> assert rest_of_line <NEW_LINE> return rest_of_line <NEW_LINE> <DEDENT> soln = support.VSumSolution( [e.OptLayout(None, options) for e in self.elements[:-1]] + [self.elements[-1].OptLayout(rest_of_line, options)], options, ) <NEW_LINE> if soln is None: <NEW_LINE> <INDENT> return rest_of_line <NEW_LINE> <DEDENT> return soln.PlusConst( options.break_cost * self.break_mult * max(len(self.elements) - 1, 0) ) | A block that arranges its elements vertically, separated by line breaks. | 62598fe2ad47b63b2c5a7edc |
class AdminUserViewSet(IDInFilterMixin, BulkModelViewSet): <NEW_LINE> <INDENT> queryset = AdminUser.objects.all() <NEW_LINE> serializer_class = serializers.AdminUserSerializer <NEW_LINE> permission_classes = (IsSuperUser,) | Admin user api set, for add,delete,update,list,retrieve resource | 62598fe250812a4eaa620f28 |
class NlmXmlTable(Entity): <NEW_LINE> <INDENT> label = StringField('./label', xpath=True) <NEW_LINE> caption = StringField('./caption', xpath=True) <NEW_LINE> reference = StringField('@id', xpath=True) <NEW_LINE> src = StringField('.', xpath=True, strip=True, raw=True) <NEW_LINE> clean_caption = Chain(tidy_nlm_references, strip_pmc_xml) <NEW_LINE> process_caption = normalize | Table information from NLM XML file. | 62598fe250812a4eaa620f29 |
class BaseSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> pass | Base V1 Serializer | 62598fe250812a4eaa620f2a |
class SubscribeNewGet(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.resp = self.client.get(r('subscriptions:new')) <NEW_LINE> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> self.assertEqual(200, self.resp.status_code) <NEW_LINE> <DEDENT> def test_template(self): <NEW_LINE> <INDENT> self.assertTemplateUsed(self.resp, 'subscriptions/subscription_form.html') <NEW_LINE> <DEDENT> def test_html(self): <NEW_LINE> <INDENT> tags = (('<form', 1), ('<input', 6), ('type="text"', 3), ('type="email"', 1), ('type="submit"', 1), ) <NEW_LINE> for text, count in tags: <NEW_LINE> <INDENT> with self.subTest(): <NEW_LINE> <INDENT> self.assertContains(self.resp, text, count) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_csrf(self): <NEW_LINE> <INDENT> self.assertContains(self.resp, 'csrfmiddlewaretoken') <NEW_LINE> <DEDENT> def test_has_form(self): <NEW_LINE> <INDENT> form = self.resp.context['form'] <NEW_LINE> self.assertIsInstance(form, SubscriptionForm) | docstring for SubscribeTest. | 62598fe2c4546d3d9def75cf |
class NotebookAppError(Exception): <NEW_LINE> <INDENT> pass | General Notebook App error | 62598fe24c3428357761a944 |
class HiddenMarkovLM(BaseLanguageModel): <NEW_LINE> <INDENT> def __init__(self, corpus): <NEW_LINE> <INDENT> self._l = 0 <NEW_LINE> self._emissions = Counter() <NEW_LINE> self._transitions = Counter() <NEW_LINE> self.update(corpus) <NEW_LINE> <DEDENT> def update(self, text): <NEW_LINE> <INDENT> while n < 4: <NEW_LINE> <INDENT> for ngram in self.compose_ngrams(text, n): <NEW_LINE> <INDENT> _c[ngram] += 1 <NEW_LINE> <DEDENT> n += 1 <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def compose_ngrams(self,doc,ngram): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> out = [] <NEW_LINE> length = len(doc) <NEW_LINE> for sentence in doc: <NEW_LINE> <INDENT> if len(sentence) < 1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> while i < (len(sentence) - ngram - 2): <NEW_LINE> <INDENT> ngrm = (sentence[i:(i+2)].text,sentence[i+3].text) <NEW_LINE> out.append(ngrm) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> return out | Markov Chain based language model
Attributes
Methods | 62598fe2d8ef3951e32c81a7 |
class Solution: <NEW_LINE> <INDENT> def searchRange(self, root, k1, k2): <NEW_LINE> <INDENT> result = [] <NEW_LINE> self.travel(root, k1, k2, result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def travel(self, root, k1, k2, result): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if root.val > k1: <NEW_LINE> <INDENT> self.travel(root.left, k1, k2, result) <NEW_LINE> <DEDENT> if k1 <= root.val and root.val <= k2: <NEW_LINE> <INDENT> result.append(root.val) <NEW_LINE> <DEDENT> if root.val < k2: <NEW_LINE> <INDENT> self.travel(root.right, k1, k2, result) | @param root: param root: The root of the binary search tree
@param k1: An integer
@param k2: An integer
@return: return: Return all keys that k1<=key<=k2 in ascending order | 62598fe2d8ef3951e32c81a8 |
class TestingConfig(BaseConfig): <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> TESTING = True <NEW_LINE> SQLALCHEMY_DATABASE_URI = postgres_local_base + database_name + "_test" <NEW_LINE> BCRYPT_HASH_PREFIX = 4 <NEW_LINE> AUTH_TOKEN_EXPIRY_DAYS = 0 <NEW_LINE> AUTH_TOKEN_EXPIRY_SECONDS = 1 | Testing application configuration | 62598fe2091ae356687052b6 |
class Packet_head(): <NEW_LINE> <INDENT> def __init__(self, magicno, packet_type, seqno, dataLen): <NEW_LINE> <INDENT> self.magicno = int(magicno) <NEW_LINE> self.packet_type = int(packet_type) <NEW_LINE> self.seqno = int(seqno) <NEW_LINE> self.dataLen = int(dataLen) <NEW_LINE> self.packet_format = "iiii" <NEW_LINE> <DEDENT> def encoder(self): <NEW_LINE> <INDENT> encoded = struct.pack(self.packet_format, self.magicno, self.packet_type, self.seqno, self.dataLen) <NEW_LINE> return encoded | Class Builds a Packet with the Magicno, packet type, seqno and Data len
as the head and the data is added as the payload | 62598fe2ab23a570cc2d50bc |
class _NoopRPCStub(apiproxy_stub.APIProxyStub): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CreateRPC(self): <NEW_LINE> <INDENT> return _NoopRPC() | An RPC stub which always creates a NoopRPC. | 62598fe2fbf16365ca794760 |
class Config: <NEW_LINE> <INDENT> allow_mutation = False <NEW_LINE> extra = "ignore" <NEW_LINE> arbitrary_types_allowed = True | Pydantic config | 62598fe2c4546d3d9def75d5 |
class ParticipantRole(db.Document): <NEW_LINE> <INDENT> name = db.StringField() <NEW_LINE> deployment = db.ReferenceField(Deployment) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | Stores the role for a participant. (e.g. Supervisor, Co-ordinator) | 62598fe2ab23a570cc2d50be |
class optStruct: <NEW_LINE> <INDENT> def __init__(self, dataMatIn, classLabels, C, toler, kTup): <NEW_LINE> <INDENT> self.X = dataMatIn <NEW_LINE> self.labelMat = classLabels <NEW_LINE> self.C = C <NEW_LINE> self.tol = toler <NEW_LINE> self.m = np.shape(dataMatIn)[0] <NEW_LINE> self.alphas = np.mat(np.zeros((self.m,1))) <NEW_LINE> self.b = 0 <NEW_LINE> self.eCache = np.mat(np.zeros((self.m,2))) <NEW_LINE> self.K = np.mat(np.zeros((self.m,self.m))) <NEW_LINE> for i in range(self.m): <NEW_LINE> <INDENT> self.K[:,i] = kernelTrans(self.X, self.X[i,:], kTup) | 数据结构,维护所有需要操作的值
Parameters:
dataMatIn - 数据矩阵
classLabels - 数据标签
C - 松弛变量
toler - 容错率
kTup - 包含核函数信息的元组,第一个参数存放核函数类别,第二个参数存放必要的核函数需要用到的参数 | 62598fe2ad47b63b2c5a7ef0 |
class ParserCollisionsExceptions(Exception): <NEW_LINE> <INDENT> pass | Cant be lower than 0 | 62598fe2d8ef3951e32c81ac |
class _RemoteUploader(FileSystemEventHandler): <NEW_LINE> <INDENT> def __init__(self, credentials, local_upload_path, file_translator): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._credentials = credentials <NEW_LINE> self._local_upload_path = local_upload_path <NEW_LINE> self._remote_upload_folder = os.path.basename(local_upload_path) <NEW_LINE> self._file_translator = file_translator <NEW_LINE> if not os.path.exists(local_upload_path): <NEW_LINE> <INDENT> os.makedirs(local_upload_path) <NEW_LINE> <DEDENT> self._drive = GDrive(self._credentials) <NEW_LINE> file_query = "(name = '{}') and (not trashed)".format(self._remote_upload_folder) <NEW_LINE> self._upload_folder = self._drive.file_list(query=file_query, file_fields= 'name, id, parents') <NEW_LINE> if len(self._upload_folder) == 0: <NEW_LINE> <INDENT> self._drive.folder_create(self._remote_upload_folder) <NEW_LINE> self._upload_folder = self._drive.file_list(query=file_query, file_fields= 'name, id, parents') <NEW_LINE> <DEDENT> self._observer = Observer() <NEW_LINE> self._observer.schedule(self, self._local_upload_path, recursive=False) <NEW_LINE> self._observer.start() <NEW_LINE> <DEDENT> except (Exception, GDriveError) as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> raise e <NEW_LINE> <DEDENT> <DEDENT> def on_created(self, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logging.info("Uploading file '{}' to Google drive folder '{}'.". format(event.src_path, self._remote_upload_folder)) <NEW_LINE> file_extension = os.path.splitext(event.src_path)[1][1:] <NEW_LINE> mime_types = None <NEW_LINE> if self._file_translator.local_file_extension_mapped(file_extension): <NEW_LINE> <INDENT> mime_types = self._file_translator.get_remote_mime_types(file_extension) <NEW_LINE> <DEDENT> self._drive.file_upload(event.src_path, self._upload_folder[0]['id'], mime_types) <NEW_LINE> <DEDENT> except (Exception, GDriveError) as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> raise e | Private class to upload watched folder files to Google drive.
Child class of FileSystemEventHandle that creates its own watchdog observer
and sets itself as the file handler. Its on_created method is overridden to upload
any files created to a specific folder on Google drive.
Attributes:
_credentials: Token returned during Google drive authorization
_local_upload_path: Local upload folder path
_remote_upload_folder: Remote upload folder
_file_translator File translator | 62598fe250812a4eaa620f31 |
class ComicError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> Exception.__init__(self, message) | Standard cbzdl error | 62598fe2fbf16365ca794766 |
class Concern(InvalidData): <NEW_LINE> <INDENT> pass | E.g. if a password is not secure enough
FIXME very ... unspecific | 62598fe2ab23a570cc2d50c0 |
class Reading(MeasurementValue): <NEW_LINE> <INDENT> def __init__(self, value=0.0, ReadingType=None, MeterReadings=None, ReadingQualities=None, *args, **kw_args): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self._ReadingType = None <NEW_LINE> self.ReadingType = ReadingType <NEW_LINE> self._MeterReadings = [] <NEW_LINE> self.MeterReadings = [] if MeterReadings is None else MeterReadings <NEW_LINE> self._ReadingQualities = [] <NEW_LINE> self.ReadingQualities = [] if ReadingQualities is None else ReadingQualities <NEW_LINE> super(Reading, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["value"] <NEW_LINE> _attr_types = {"value": float} <NEW_LINE> _defaults = {"value": 0.0} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["ReadingType", "MeterReadings", "ReadingQualities"] <NEW_LINE> _many_refs = ["MeterReadings", "ReadingQualities"] <NEW_LINE> def getReadingType(self): <NEW_LINE> <INDENT> return self._ReadingType <NEW_LINE> <DEDENT> def setReadingType(self, value): <NEW_LINE> <INDENT> if self._ReadingType is not None: <NEW_LINE> <INDENT> filtered = [x for x in self.ReadingType.Readings if x != self] <NEW_LINE> self._ReadingType._Readings = filtered <NEW_LINE> <DEDENT> self._ReadingType = value <NEW_LINE> if self._ReadingType is not None: <NEW_LINE> <INDENT> if self not in self._ReadingType._Readings: <NEW_LINE> <INDENT> self._ReadingType._Readings.append(self) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ReadingType = property(getReadingType, setReadingType) <NEW_LINE> def getMeterReadings(self): <NEW_LINE> <INDENT> return self._MeterReadings <NEW_LINE> <DEDENT> def setMeterReadings(self, value): <NEW_LINE> <INDENT> for p in self._MeterReadings: <NEW_LINE> <INDENT> filtered = [q for q in p.Readings if q != self] <NEW_LINE> self._MeterReadings._Readings = filtered <NEW_LINE> <DEDENT> for r in value: <NEW_LINE> <INDENT> if self not in r._Readings: <NEW_LINE> <INDENT> r._Readings.append(self) <NEW_LINE> <DEDENT> <DEDENT> self._MeterReadings = value <NEW_LINE> <DEDENT> MeterReadings = property(getMeterReadings, setMeterReadings) <NEW_LINE> def addMeterReadings(self, *MeterReadings): <NEW_LINE> <INDENT> for obj in MeterReadings: <NEW_LINE> <INDENT> if self not in obj._Readings: <NEW_LINE> <INDENT> obj._Readings.append(self) <NEW_LINE> <DEDENT> self._MeterReadings.append(obj) <NEW_LINE> <DEDENT> <DEDENT> def removeMeterReadings(self, *MeterReadings): <NEW_LINE> <INDENT> for obj in MeterReadings: <NEW_LINE> <INDENT> if self in obj._Readings: <NEW_LINE> <INDENT> obj._Readings.remove(self) <NEW_LINE> <DEDENT> self._MeterReadings.remove(obj) <NEW_LINE> <DEDENT> <DEDENT> def getReadingQualities(self): <NEW_LINE> <INDENT> return self._ReadingQualities <NEW_LINE> <DEDENT> def setReadingQualities(self, value): <NEW_LINE> <INDENT> for x in self._ReadingQualities: <NEW_LINE> <INDENT> x.Reading = None <NEW_LINE> <DEDENT> for y in value: <NEW_LINE> <INDENT> y._Reading = self <NEW_LINE> <DEDENT> self._ReadingQualities = value <NEW_LINE> <DEDENT> ReadingQualities = property(getReadingQualities, setReadingQualities) <NEW_LINE> def addReadingQualities(self, *ReadingQualities): <NEW_LINE> <INDENT> for obj in ReadingQualities: <NEW_LINE> <INDENT> obj.Reading = self <NEW_LINE> <DEDENT> <DEDENT> def removeReadingQualities(self, *ReadingQualities): <NEW_LINE> <INDENT> for obj in ReadingQualities: <NEW_LINE> <INDENT> obj.Reading = None | Specific value measured by a meter or other asset. Each Reading is associated with a specific ReadingType.Specific value measured by a meter or other asset. Each Reading is associated with a specific ReadingType.
| 62598fe24c3428357761a952 |
class MovePageDownAction (BaseAction): <NEW_LINE> <INDENT> stringId = u"MovePageDown" <NEW_LINE> def __init__ (self, application): <NEW_LINE> <INDENT> self._application = application <NEW_LINE> <DEDENT> @property <NEW_LINE> def title (self): <NEW_LINE> <INDENT> return _(u"Move Page Down") <NEW_LINE> <DEDENT> @property <NEW_LINE> def description (self): <NEW_LINE> <INDENT> return _(u"Move page down") <NEW_LINE> <DEDENT> def run (self, params): <NEW_LINE> <INDENT> self.moveCurrentPageDown () <NEW_LINE> <DEDENT> @testreadonly <NEW_LINE> def moveCurrentPageDown (self): <NEW_LINE> <INDENT> if self._application.wikiroot is None: <NEW_LINE> <INDENT> MessageBox (_(u"Wiki is not open"), _(u"Error"), wx.ICON_ERROR | wx.OK) <NEW_LINE> return <NEW_LINE> <DEDENT> if self._application.wikiroot.selectedPage is not None: <NEW_LINE> <INDENT> tree = self._application.mainWindow.treePanel.panel.treeCtrl <NEW_LINE> tree.Freeze() <NEW_LINE> scrollPos = tree.GetScrollPos (wx.VERTICAL) <NEW_LINE> self._application.wikiroot.selectedPage.order += 1 <NEW_LINE> tree.SetScrollPos (wx.VERTICAL, scrollPos) <NEW_LINE> tree.Thaw() | Переместить страницу на одну позицию вниз | 62598fe250812a4eaa620f33 |
class CategoryItem(NameItem): <NEW_LINE> <INDENT> DEFAULT_NAME = CONFIG["DATABASE"]["default_category"] <NEW_LINE> def __init__(self, data, entry=None): <NEW_LINE> <INDENT> super(CategoryItem, self).__init__(data, entry) <NEW_LINE> self.setEditable(False) <NEW_LINE> font = self.font() <NEW_LINE> font.setBold(True) <NEW_LINE> self.setFont(font) | Item representing the name of a category.
Cannot be edited. Text is printed in bold letters. | 62598fe2c4546d3d9def75d9 |
class bidEvaluatorSMU8(bidEvaluatorBase): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def type(): <NEW_LINE> <INDENT> return "bidEvaluatorSMU8" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def SS(**kwargs): <NEW_LINE> <INDENT> bidEvaluatorBase.checkArgs(**kwargs) <NEW_LINE> pricePrediction = margDistPredictionAgent.SS(**kwargs) <NEW_LINE> m = kwargs.get('m', pricePrediction.m) <NEW_LINE> bundles = kwargs.get('bundles',simYW.allBundles(m)) <NEW_LINE> bidCandidates = kwargs.get('bidCandidates',[]) <NEW_LINE> if not bidCandidates: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = kwargs['v'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError('v is not in kwargs.') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> l = kwargs['l'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise KeyError('l is not in kwargs.') <NEW_LINE> <DEDENT> agent = straightMU8(margDistPricePrediction = pricePrediction, m = m, l = l, v = v) <NEW_LINE> bidCandidates = numpy.atleast_2d([agent.bid() for i in xrange(4)]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bidCandidates = numpy.atleast_2d(bidCandidates) <NEW_LINE> <DEDENT> evalSamples = kwargs.get('evalSamples',pricePrediction.iTsample(nSamples = 32)) <NEW_LINE> avgCandidateSurplus = bidEvaluatorBase.candidateAvgSurplus(candidates = bidCandidates, samples = evalSamples, v = v, l = l) <NEW_LINE> return bidCandidates[numpy.nonzero(avgCandidateSurplus == numpy.max(avgCandidateSurplus))[0][0]] | BidEvaluator that generates 8 candidates via straightMU8 strategy and
chooses the best that performs best (highest average surplus) w.r.t to
32 samples from the price prediction distribution. | 62598fe3ab23a570cc2d50c3 |
class HelpfulSubparserAction(argparse._SubParsersAction): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs) -> None: <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.choices = None <NEW_LINE> <DEDENT> def __call__(self, parser: 'HelpfulArgParser', namespace: argparse.Namespace, values: List[str], option_string: None = None) -> None: <NEW_LINE> <INDENT> parser_name = values[0] <NEW_LINE> arg_strings = values[1:] <NEW_LINE> if self.dest != argparse.SUPPRESS: <NEW_LINE> <INDENT> setattr(namespace, self.dest, parser_name) <NEW_LINE> <DEDENT> matched_parsers = [name for name in self._name_parser_map if parser_name in name] <NEW_LINE> if len(matched_parsers) < 1: <NEW_LINE> <INDENT> msg = 'invalid choice {} (choose from {})'.format(parser_name, ', '.join(self._name_parser_map)) <NEW_LINE> raise argparse.ArgumentError(self, msg) <NEW_LINE> <DEDENT> if len(matched_parsers) > 1: <NEW_LINE> <INDENT> msg = 'plugin {} matches multiple plugins ({})'.format(parser_name, ', '.join(matched_parsers)) <NEW_LINE> raise argparse.ArgumentError(self, msg) <NEW_LINE> <DEDENT> parser = self._name_parser_map[matched_parsers[0]] <NEW_LINE> setattr(namespace, 'plugin', matched_parsers[0]) <NEW_LINE> subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) <NEW_LINE> for key, value in vars(subnamespace).items(): <NEW_LINE> <INDENT> setattr(namespace, key, value) <NEW_LINE> <DEDENT> if arg_strings: <NEW_LINE> <INDENT> vars(namespace).setdefault(argparse._UNRECOGNIZED_ARGS_ATTR, []) <NEW_LINE> getattr(namespace, argparse._UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) | Class to either select a unique plugin based on a substring, or identify
the alternatives. | 62598fe3ab23a570cc2d50c4 |
class ParserBase(HTMLParser): <NEW_LINE> <INDENT> def __init__(self, outer, inner): <NEW_LINE> <INDENT> HTMLParser.__init__(self) <NEW_LINE> (outerTag, outerAttrib, outerValue) = outer <NEW_LINE> (innerTag, innerAttrib) = inner <NEW_LINE> self.__outerTag = outerTag <NEW_LINE> self.__outerAttrib = outerAttrib <NEW_LINE> self.__outerValue = outerValue <NEW_LINE> self.__innerTag = innerTag <NEW_LINE> self.__innerAttrib = innerAttrib <NEW_LINE> self.__insideOuterTag = False <NEW_LINE> self.__outerCount = 0 <NEW_LINE> self.targetValue = '' <NEW_LINE> self.targetCount = 0 <NEW_LINE> self.targetValues = list() <NEW_LINE> self.targetData = list() <NEW_LINE> <DEDENT> def handle_starttag(self, tag, attrs): <NEW_LINE> <INDENT> self.findOuterTagStart(tag, attrs) <NEW_LINE> if self.__insideOuterTag: <NEW_LINE> <INDENT> self.increaseOuterCount(tag) <NEW_LINE> self.findInnerTag(tag, attrs) <NEW_LINE> <DEDENT> <DEDENT> def handle_data(self, data): <NEW_LINE> <INDENT> if self.__insideOuterTag: <NEW_LINE> <INDENT> if not data.isspace(): <NEW_LINE> <INDENT> self.targetData.append(data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def handle_endtag(self, tag): <NEW_LINE> <INDENT> if self.__insideOuterTag: <NEW_LINE> <INDENT> self.decreaseOuterCount(tag) <NEW_LINE> <DEDENT> <DEDENT> def findOuterTagStart(self, tag, attrs): <NEW_LINE> <INDENT> global logger <NEW_LINE> if tag == self.__outerTag: <NEW_LINE> <INDENT> if self.__outerAttrib and self.__outerValue: <NEW_LINE> <INDENT> for attr in attrs: <NEW_LINE> <INDENT> if (attr[0] == self.__outerAttrib) and (attr[1] == self.__outerValue): <NEW_LINE> <INDENT> self.__insideOuterTag = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.__insideOuterTag = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def increaseOuterCount(self, tag): <NEW_LINE> <INDENT> if tag == self.__outerTag: <NEW_LINE> <INDENT> self.__outerCount = self.__outerCount + 1 <NEW_LINE> <DEDENT> <DEDENT> def decreaseOuterCount(self, tag): <NEW_LINE> <INDENT> if tag == self.__outerTag: <NEW_LINE> <INDENT> self.__outerCount = self.__outerCount - 1 <NEW_LINE> <DEDENT> if self.__outerCount == 0: <NEW_LINE> <INDENT> self.__insideOuterTag = False <NEW_LINE> <DEDENT> <DEDENT> def findInnerTag(self, tag, attrs): <NEW_LINE> <INDENT> global logger <NEW_LINE> if self.__insideOuterTag: <NEW_LINE> <INDENT> if tag == self.__innerTag: <NEW_LINE> <INDENT> for attr in attrs: <NEW_LINE> <INDENT> if attr[0] == self.__innerAttrib: <NEW_LINE> <INDENT> self.targetValue = attr[1] <NEW_LINE> self.targetValues.append(attr[1]) <NEW_LINE> self.targetCount = self.targetCount + 1 <NEW_LINE> break | Parses a given HTML site and seaches for a specified attribute of a
given tag inside another specified tag. The outer tag is defined by tag
name and attribute with its value.
TODO: Extend to a list of (tags, attrib, value) tupel, to find a specific
value? [("div", "id", "imgholder"), ("img", "src", xxx)] | 62598fe3fbf16365ca794772 |
class Keys(object): <NEW_LINE> <INDENT> BITRATE = 'bitrate' <NEW_LINE> CHANNEL = 'channel' <NEW_LINE> CHANNELS = 'channels' <NEW_LINE> CONNECT = 'connect' <NEW_LINE> BACKGROUND = 'background' <NEW_LINE> DISPLAY_NAME = 'display_name' <NEW_LINE> FEATURED = 'featured' <NEW_LINE> FOLLOWS = 'follows' <NEW_LINE> GAME = 'game' <NEW_LINE> LOGO = 'logo' <NEW_LINE> BOX = 'box' <NEW_LINE> LARGE = 'large' <NEW_LINE> NAME = 'name' <NEW_LINE> NEEDED_INFO = 'needed_info' <NEW_LINE> PLAY = 'play' <NEW_LINE> PLAYPATH = 'playpath' <NEW_LINE> QUALITY = 'quality' <NEW_LINE> RTMP = 'rtmp' <NEW_LINE> STREAMS = 'streams' <NEW_LINE> REFERER = 'Referer' <NEW_LINE> RTMP_URL = 'rtmpUrl' <NEW_LINE> STATUS = 'status' <NEW_LINE> STREAM = 'stream' <NEW_LINE> SWF_URL = 'swfUrl' <NEW_LINE> TEAMS = 'teams' <NEW_LINE> TOKEN = 'token' <NEW_LINE> TOP = 'top' <NEW_LINE> TOTAL = '_total' <NEW_LINE> USER_AGENT = 'User-Agent' <NEW_LINE> USER_AGENT_STRING = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0' <NEW_LINE> VIDEOS = 'videos' <NEW_LINE> VIDEO_BANNER = 'video_banner' <NEW_LINE> VIDEO_HEIGHT = 'video_height' <NEW_LINE> VIEWERS = 'viewers' <NEW_LINE> PREVIEW = 'preview' <NEW_LINE> TITLE = 'title' <NEW_LINE> QUALITY_LIST_STREAM = ['Source', 'High', 'Medium', 'Low', 'Mobile'] <NEW_LINE> QUALITY_LIST_VIDEO = ['live', '720p', '480p', '360p', '226p'] | Should not be instantiated, just used to categorize
string-constants | 62598fe3ab23a570cc2d50c7 |
class notify_args(object): <NEW_LINE> <INDENT> def __init__(self, n=None,): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.n = Node() <NEW_LINE> self.n.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('notify_args') <NEW_LINE> if self.n is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('n', TType.STRUCT, 1) <NEW_LINE> self.n.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- n | 62598fe3ad47b63b2c5a7f04 |
@base.Hidden <NEW_LINE> @base.ReleaseTracks(base.ReleaseTrack.GA) <NEW_LINE> class DockerHelper(base.Command): <NEW_LINE> <INDENT> GET = 'get' <NEW_LINE> LIST = 'list' <NEW_LINE> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.add_argument('method', help='The docker credential helper method.') <NEW_LINE> parser.display_info.AddFormat('json') <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> if args.method == DockerHelper.LIST: <NEW_LINE> <INDENT> return { url: 'oauth2accesstoken' for url in constants.ALL_SUPPORTED_REGISTRIES } <NEW_LINE> <DEDENT> elif args.method == DockerHelper.GET: <NEW_LINE> <INDENT> cred = c_store.Load() <NEW_LINE> c_store.Refresh(cred) <NEW_LINE> url = sys.stdin.read().strip() <NEW_LINE> if url not in constants.ALL_SUPPORTED_REGISTRIES: <NEW_LINE> <INDENT> raise exceptions.Error( 'Repository url [{url}] is not supported'.format(url=url)) <NEW_LINE> <DEDENT> return { 'Secret': cred.access_token, 'Username': 'oauth2accesstoken', } <NEW_LINE> <DEDENT> args.GetDisplayInfo().AddFormat('none') <NEW_LINE> return None | A Docker credential helper to provide access to GCR repositories. | 62598fe3ab23a570cc2d50c8 |
class ExtractorBase: <NEW_LINE> <INDENT> def __init__(self, features): <NEW_LINE> <INDENT> self.features = features <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> for f in self.features: <NEW_LINE> <INDENT> f.initialize() <NEW_LINE> <DEDENT> <DEDENT> def free_memory(self): <NEW_LINE> <INDENT> for f in self.features: <NEW_LINE> <INDENT> f.free_memory() | Base feature extractor class.
args:
features: List of features. | 62598fe3ab23a570cc2d50ca |
@autoinitsingleton('windows', 'uri') <NEW_LINE> class WindowsToUriPathConverter(Singleton, PathConverter): <NEW_LINE> <INDENT> def convert(self, source_path): <NEW_LINE> <INDENT> return get_path_converter( 'windows_alt', 'uri').convert( get_path_converter( 'windows', 'windows_alt').convert(source_path)) | Windows to uri path converter. | 62598fe3187af65679d29f53 |
class BlockStructureCache(object): <NEW_LINE> <INDENT> def __init__(self, cache): <NEW_LINE> <INDENT> self._cache = cache <NEW_LINE> <DEDENT> def add(self, block_structure): <NEW_LINE> <INDENT> data_to_cache = ( block_structure._block_relations, block_structure._transformer_data, block_structure._block_data_map ) <NEW_LINE> zp_data_to_cache = zpickle(data_to_cache) <NEW_LINE> self._cache.set( self._encode_root_cache_key(block_structure.root_block_usage_key), zp_data_to_cache ) <NEW_LINE> logger.debug( "Wrote BlockStructure %s to cache, size: %s", block_structure.root_block_usage_key, len(zp_data_to_cache), ) <NEW_LINE> <DEDENT> def get(self, root_block_usage_key): <NEW_LINE> <INDENT> zp_data_from_cache = self._cache.get(self._encode_root_cache_key(root_block_usage_key)) <NEW_LINE> if not zp_data_from_cache: <NEW_LINE> <INDENT> logger.debug( "Did not find BlockStructure %r in the cache.", root_block_usage_key, ) <NEW_LINE> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug( "Read BlockStructure %r from cache, size: %s", root_block_usage_key, len(zp_data_from_cache), ) <NEW_LINE> <DEDENT> block_relations, transformer_data, block_data_map = zunpickle(zp_data_from_cache) <NEW_LINE> block_structure = BlockStructureModulestoreData(root_block_usage_key) <NEW_LINE> block_structure._block_relations = block_relations <NEW_LINE> block_structure._transformer_data = transformer_data <NEW_LINE> block_structure._block_data_map = block_data_map <NEW_LINE> return block_structure <NEW_LINE> <DEDENT> def delete(self, root_block_usage_key): <NEW_LINE> <INDENT> self._cache.delete(self._encode_root_cache_key(root_block_usage_key)) <NEW_LINE> logger.debug( "Deleted BlockStructure %r from the cache.", root_block_usage_key, ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _encode_root_cache_key(cls, root_block_usage_key): <NEW_LINE> <INDENT> return "root.key." + unicode(root_block_usage_key) | Cache for BlockStructure objects. | 62598fe3091ae356687052d6 |
class BaseAliPayAPI(object): <NEW_LINE> <INDENT> def __init__(self, client=None): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> <DEDENT> def _get(self, url, **kwargs): <NEW_LINE> <INDENT> if hasattr(self, "API_BASE_URL"): <NEW_LINE> <INDENT> kwargs['api_base_url'] = getattr(self, "API_BASE_URL") <NEW_LINE> <DEDENT> return self._client.get(url, **kwargs) <NEW_LINE> <DEDENT> def _post(self, url, **kwargs): <NEW_LINE> <INDENT> if hasattr(self, "API_BASE_URL"): <NEW_LINE> <INDENT> kwargs['api_base_url'] = getattr(self, "API_BASE_URL") <NEW_LINE> <DEDENT> return self._client.post(url, **kwargs) <NEW_LINE> <DEDENT> def _generate_url(self, method, *args, **kwargs): <NEW_LINE> <INDENT> return self._client.generate_url(method, *args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def app_id(self): <NEW_LINE> <INDENT> return self._client.app_id | 支付宝支付API基类 | 62598fe3187af65679d29f55 |
class USER(BASE, mixin.BasicMixin, mixin.UserMixin, mixin.ExtraDataMixin, mixin.TimestampMixin): <NEW_LINE> <INDENT> authorization = relationship('AUTHORIZATION', primaryjoin='foreign(USER.authorization_name) == remote(AUTHORIZATION.name)', backref=backref('users', order_by='USER.name', lazy='dynamic')) <NEW_LINE> @property <NEW_LINE> def shared_views(self): <NEW_LINE> <INDENT> return (x.view for x in self.view_permissions) <NEW_LINE> <DEDENT> @property <NEW_LINE> def shared_searchs(self): <NEW_LINE> <INDENT> return (x.search for x in self.search_permissions) | 用户存放用户信息的table | 62598fe3c4546d3d9def75e4 |
class School(models.Model): <NEW_LINE> <INDENT> SchoolID = models.AutoField(primary_key=True) <NEW_LINE> SchoolName = models.CharField(max_length=50, null=False, unique=True) <NEW_LINE> Address = models.CharField(max_length=255) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.SchoolName | This model stores the schools.
Each school with multiple campuses will be stored separately. | 62598fe3c4546d3d9def75e5 |
class DescribeVpcQuotaRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TypeIds = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TypeIds = params.get("TypeIds") | DescribeVpcQuota请求参数结构体
| 62598fe3fbf16365ca794784 |
class SocialAPIError(SocialOAuthException): <NEW_LINE> <INDENT> def __init__(self, site_name, url, code, error_msg, *args, **kwargs): <NEW_LINE> <INDENT> self.site_name = site_name <NEW_LINE> self.url = url <NEW_LINE> self.code = code <NEW_LINE> self.error_msg = error_msg <NEW_LINE> SocialOAuthException.__init__(self, error_msg, *args, **kwargs) | Occurred when doing API call | 62598fe3fbf16365ca794788 |
class Pfx2asn(SQLObject): <NEW_LINE> <INDENT> class sqlmeta: <NEW_LINE> <INDENT> fromDatabase = True <NEW_LINE> defaultOrder = 'asn' | the pfx2asn table | 62598fe3d8ef3951e32c81bf |
class OutputMappingConfig(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Scene = None <NEW_LINE> self.WorkerNum = None <NEW_LINE> self.WorkerPartSize = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Scene = params.get("Scene") <NEW_LINE> self.WorkerNum = params.get("WorkerNum") <NEW_LINE> self.WorkerPartSize = params.get("WorkerPartSize") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | 输出映射配置
| 62598fe4187af65679d29f5c |
class UserInterface(object): <NEW_LINE> <INDENT> def __init__(self, storage, payload, instclass): <NEW_LINE> <INDENT> if self.__class__ is UserInterface: <NEW_LINE> <INDENT> raise TypeError("UserInterface is an abstract class.") <NEW_LINE> <DEDENT> self.storage = storage <NEW_LINE> self.payload = payload <NEW_LINE> self.instclass = instclass <NEW_LINE> from pyanaconda.errors import errorHandler <NEW_LINE> errorHandler.ui = self <NEW_LINE> <DEDENT> paths = PathDict({}) <NEW_LINE> @property <NEW_LINE> def tty_num(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def update_paths(cls, pathdict): <NEW_LINE> <INDENT> for k,v in pathdict.items(): <NEW_LINE> <INDENT> cls.paths.setdefault(k, []) <NEW_LINE> cls.paths[k].extend(v) <NEW_LINE> <DEDENT> <DEDENT> def setup(self, data): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def meh_interface(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def showError(self, message): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def showYesNoQuestion(self, message): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _collectActionClasses(self, module_pattern_w_path, standalone_class): <NEW_LINE> <INDENT> standalones = [] <NEW_LINE> for module_pattern, path in module_pattern_w_path: <NEW_LINE> <INDENT> standalones.extend(collect(module_pattern, path, lambda obj: issubclass(obj, standalone_class) and getattr(obj, "preForHub", False) or getattr(obj, "postForHub", False))) <NEW_LINE> <DEDENT> return standalones <NEW_LINE> <DEDENT> def _orderActionClasses(self, spokes, hubs): <NEW_LINE> <INDENT> actionClasses = [] <NEW_LINE> for hub in hubs: <NEW_LINE> <INDENT> actionClasses.extend(sorted(filter(lambda obj, h=hub: getattr(obj, "preForHub", None) == h, spokes), key=lambda obj: obj.priority)) <NEW_LINE> actionClasses.append(hub) <NEW_LINE> actionClasses.extend(sorted(filter(lambda obj, h=hub: getattr(obj, "postForHub", None) == h, spokes), key=lambda obj: obj.priority)) <NEW_LINE> <DEDENT> return actionClasses | This is the base class for all kinds of install UIs. It primarily
defines what kinds of dialogs and entry widgets every interface must
provide that the rest of anaconda may rely upon. | 62598fe4ab23a570cc2d50d5 |
class Line: <NEW_LINE> <INDENT> def __init__(self, line): <NEW_LINE> <INDENT> from re import match, sub <NEW_LINE> self.no = 1 + line[0] <NEW_LINE> self.text = line[1] <NEW_LINE> if self.text and self.text[-1] == '\\n': <NEW_LINE> <INDENT> self.text = self.text[:-1] <NEW_LINE> <DEDENT> self.py = False <NEW_LINE> self.tag = None <NEW_LINE> if self.text[0:4] == '#py ': <NEW_LINE> <INDENT> self.text = self.text[4:] <NEW_LINE> self.py = True <NEW_LINE> self.tag = sub(':$', '', self.text.split()[0]) <NEW_LINE> self.rule = block_rules.get(self.tag) | Abstraction for a line of text input, used by PyCPP.parse | 62598fe4d8ef3951e32c81c3 |
class LogCapturer(object): <NEW_LINE> <INDENT> def __init__(self, level="debug"): <NEW_LINE> <INDENT> self.logs = [] <NEW_LINE> self._old_log_level = _loglevel <NEW_LINE> self.desired_level = level <NEW_LINE> <DEDENT> def get_category(self, identifier): <NEW_LINE> <INDENT> return [x for x in self.logs if x.get("log_category") == identifier] <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> set_global_log_level(self.desired_level) <NEW_LINE> globalLogPublisher.addObserver(self.logs.append) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> globalLogPublisher.removeObserver(self.logs.append) <NEW_LINE> set_global_log_level(self._old_log_level) | A context manager that captures logs inside of it, and makes it available
through the logs attribute, or the get_category method. | 62598fe44c3428357761a97d |
class _PubSubPayloadSource(dataflow_io.NativeSource): <NEW_LINE> <INDENT> def __init__(self, topic=None, subscription=None, id_label=None): <NEW_LINE> <INDENT> self.coder = coders.BytesCoder() <NEW_LINE> self.full_topic = topic <NEW_LINE> self.full_subscription = subscription <NEW_LINE> self.topic_name = None <NEW_LINE> self.subscription_name = None <NEW_LINE> self.id_label = id_label <NEW_LINE> if not (topic or subscription): <NEW_LINE> <INDENT> raise ValueError('Either a topic or subscription must be provided.') <NEW_LINE> <DEDENT> if topic and subscription: <NEW_LINE> <INDENT> raise ValueError('Only one of topic or subscription should be provided.') <NEW_LINE> <DEDENT> if topic: <NEW_LINE> <INDENT> self.project, self.topic_name = parse_topic(topic) <NEW_LINE> <DEDENT> if subscription: <NEW_LINE> <INDENT> self.project, self.subscription_name = parse_subscription(subscription) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def format(self): <NEW_LINE> <INDENT> return 'pubsub' <NEW_LINE> <DEDENT> def display_data(self): <NEW_LINE> <INDENT> return {'id_label': DisplayDataItem(self.id_label, label='ID Label Attribute').drop_if_none(), 'topic': DisplayDataItem(self.full_topic, label='Pubsub Topic').drop_if_none(), 'subscription': DisplayDataItem(self.full_subscription, label='Pubsub Subscription').drop_if_none()} <NEW_LINE> <DEDENT> def reader(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'PubSubPayloadSource is not supported in local execution.') <NEW_LINE> <DEDENT> def is_bounded(self): <NEW_LINE> <INDENT> return False | Source for the payload of a message as bytes from a Cloud Pub/Sub topic.
Attributes:
topic: Cloud Pub/Sub topic in the form "projects/<project>/topics/<topic>".
If provided, subscription must be None.
subscription: Existing Cloud Pub/Sub subscription to use in the
form "projects/<project>/subscriptions/<subscription>". If not specified,
a temporary subscription will be created from the specified topic. If
provided, topic must be None.
id_label: The attribute on incoming Pub/Sub messages to use as a unique
record identifier. When specified, the value of this attribute (which can
be any string that uniquely identifies the record) will be used for
deduplication of messages. If not provided, Dataflow cannot guarantee
that no duplicate data will be delivered on the Pub/Sub stream. In this
case, deduplication of the stream will be strictly best effort. | 62598fe4ad47b63b2c5a7f20 |
class NetworkTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from letsencrypt.network import Network <NEW_LINE> self.net = Network( new_reg_uri=None, key=None, alg=None, verify_ssl=None) <NEW_LINE> self.config = mock.Mock(accounts_dir=tempfile.mkdtemp()) <NEW_LINE> self.contact = ('mailto:cert-admin@example.com', 'tel:+12025551212') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.config.accounts_dir) <NEW_LINE> <DEDENT> def test_register_from_account(self): <NEW_LINE> <INDENT> self.net.register = mock.Mock() <NEW_LINE> acc = account.Account( self.config, 'key', email='cert-admin@example.com', phone='+12025551212') <NEW_LINE> self.net.register_from_account(acc) <NEW_LINE> self.net.register.assert_called_with(contact=self.contact) <NEW_LINE> <DEDENT> def test_register_from_account_partial_info(self): <NEW_LINE> <INDENT> self.net.register = mock.Mock() <NEW_LINE> acc = account.Account( self.config, 'key', email='cert-admin@example.com') <NEW_LINE> acc2 = account.Account(self.config, 'key') <NEW_LINE> self.net.register_from_account(acc) <NEW_LINE> self.net.register.assert_called_with( contact=('mailto:cert-admin@example.com',)) <NEW_LINE> self.net.register_from_account(acc2) <NEW_LINE> self.net.register.assert_called_with(contact=()) | Tests for letsencrypt.network.Network. | 62598fe4fbf16365ca794794 |
class Positions(object): <NEW_LINE> <INDENT> def __init__(self, scaled_positions, cop, symbols, distance, origin): <NEW_LINE> <INDENT> self.scaled_positions = scaled_positions <NEW_LINE> self.cop = cop <NEW_LINE> self.symbols = symbols <NEW_LINE> self.distance = distance <NEW_LINE> self.origin = origin <NEW_LINE> <DEDENT> def to_use(self): <NEW_LINE> <INDENT> if self.distance > 0. and self.origin == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.distance < 0. and self.origin == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Helper object to simplify the pairing process.
Parameters:
scaled_positions: (Nx3) array
Positions in scaled coordinates
cop: (1x3) array
Center-of-positions (also in scaled coordinates)
symbols: str
String with the atomic symbols
distance: float
Signed distance to the cutting plane
origin: int (0 or 1)
Determines at which side of the plane the position should be. | 62598fe4d8ef3951e32c81c4 |
class WeatherForSinglePointSummarizedResultSet(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 WeatherForSinglePointSummarized Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution. | 62598fe4187af65679d29f61 |
class QMDMetadataElement(core.QTIElement): <NEW_LINE> <INDENT> def content_changed(self): <NEW_LINE> <INDENT> self.DeclareMetadata(self.get_xmlname(), self.get_value(), self) | Abstract class to represent old-style qmd_ tags | 62598fe4d8ef3951e32c81c7 |
class ProductDetailIntId(BaseModel): <NEW_LINE> <INDENT> brand_name: str = Field(..., alias="BrandName") <NEW_LINE> product_name: str = Field(..., alias="ProductName") <NEW_LINE> sub_header: str = Field(..., alias="SubHeader") <NEW_LINE> organic_code: str = Field(..., alias="OrganicCode") <NEW_LINE> units_in_full_case: int = Field(..., alias="UnitsInFullCase") <NEW_LINE> pack_size: str = Field(..., alias="PackSize") <NEW_LINE> upc: int = Field(..., alias="UPC") <NEW_LINE> stock_avail: int = Field(..., alias="StockAvail") <NEW_LINE> stock_oh: int = Field(..., alias="StockOH") <NEW_LINE> per_unit_price: float = Field(..., alias="PerUnitPrice") <NEW_LINE> brand_id: int = Field(..., alias="BrandId") <NEW_LINE> product_int_id: int = Field(..., alias="ProductIntID") <NEW_LINE> product_code: Optional[str] = Field(..., alias="ProductCode") <NEW_LINE> discount: Optional[str] = Field(..., alias="Discount") <NEW_LINE> price: float = Field(..., alias="Price") <NEW_LINE> minqty: int = Field(..., alias="MINQTY") <NEW_LINE> inner_case_upc: int = Field(..., alias="InnerCaseUPC") <NEW_LINE> master_case_upc: int = Field(..., alias="MasterCaseUPC") <NEW_LINE> plu: Any = Field(..., alias="PLU") <NEW_LINE> pv_label_code: str = Field(..., alias="PVLabelCode") <NEW_LINE> member_applicable_fee: float = Field(..., alias="MemberApplicableFee") <NEW_LINE> category_id: int = Field(..., alias="CategoryID") <NEW_LINE> category_name: str = Field(..., alias="CategoryName") <NEW_LINE> country_of_origin_id: Optional[int] = Field(..., alias="CountryOfOriginID") <NEW_LINE> country_of_origin_name: Optional[str] = Field(..., alias="CountryOfOriginName") <NEW_LINE> warehouse_message: Any = Field(..., alias="WarehouseMessage") <NEW_LINE> is_new: bool = Field(..., alias="IsNew") <NEW_LINE> @root_validator(pre=True) <NEW_LINE> def field_values_to_title_case(cls, values): <NEW_LINE> <INDENT> return values <NEW_LINE> <DEDENT> @validator("category_id", pre=True) <NEW_LINE> def none_to_int_zero(cls, v): <NEW_LINE> <INDENT> return 0 if v is None else v <NEW_LINE> <DEDENT> @validator("upc", "inner_case_upc", "master_case_upc", pre=True) <NEW_LINE> def validate_upc(cls, v): <NEW_LINE> <INDENT> return int(v.replace("-", "")) <NEW_LINE> <DEDENT> @property <NEW_LINE> def case_qty(self): <NEW_LINE> <INDENT> return self.units_in_full_case <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_size(self): <NEW_LINE> <INDENT> return clean_size_field(self.pack_size) | BaseModel for product details from the UNFIApi product detail by intid | 62598fe426238365f5fad23c |
class City(Base): <NEW_LINE> <INDENT> __tablename__ = "cities" <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True, nullable=False, unique=True) <NEW_LINE> name = Column(String(128), nullable=False) <NEW_LINE> state_id = Column(Integer, ForeignKey('states.id'), nullable=False) | Create a City object that inherits from Base | 62598fe4091ae356687052f6 |
class AutoModelForSequenceClassification: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> raise EnvironmentError( "AutoModelForSequenceClassification is designed to be instantiated " "using the `AutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path)` or " "`AutoModelForSequenceClassification.from_config(config)` methods." ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @replace_list_option_in_docstrings(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, use_model_types=False) <NEW_LINE> def from_config(cls, config): <NEW_LINE> <INDENT> for config_class, model_class in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.items(): <NEW_LINE> <INDENT> if isinstance(config, config_class): <NEW_LINE> <INDENT> return model_class(config) <NEW_LINE> <DEDENT> <DEDENT> raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.keys()), ) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @replace_list_option_in_docstrings(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING) <NEW_LINE> @add_start_docstrings( "Instantiate one of the model classes of the library---with a sequence classification head---from a " "pretrained model.", AUTO_MODEL_PRETRAINED_DOCSTRING, ) <NEW_LINE> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <NEW_LINE> <INDENT> config = kwargs.pop("config", None) <NEW_LINE> if not isinstance(config, PretrainedConfig): <NEW_LINE> <INDENT> config, kwargs = AutoConfig.from_pretrained( pretrained_model_name_or_path, return_unused_kwargs=True, **kwargs ) <NEW_LINE> <DEDENT> for config_class, model_class in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.items(): <NEW_LINE> <INDENT> if isinstance(config, config_class): <NEW_LINE> <INDENT> return model_class.from_pretrained(pretrained_model_name_or_path, *model_args, config=config, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> raise ValueError( "Unrecognized configuration class {} for this kind of AutoModel: {}.\n" "Model type should be one of {}.".format( config.__class__, cls.__name__, ", ".join(c.__name__ for c in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING.keys()), ) ) | This is a generic model class that will be instantiated as one of the model classes of the library---with a
sequence classification head---when created with the when created with the
:meth:`~transformers.AutoModelForSequenceClassification.from_pretrained` class method or the
:meth:`~transformers.AutoModelForSequenceClassification.from_config` class method.
This class cannot be instantiated directly using ``__init__()`` (throws an error). | 62598fe4fbf16365ca79479e |
class ExplorationContentValidationJobForCKEditor( jobs.BaseMapReduceOneOffJobManager): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def entity_classes_to_map_over(cls): <NEW_LINE> <INDENT> return [exp_models.ExplorationModel] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def map(item): <NEW_LINE> <INDENT> if item.deleted: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> exploration = exp_services.get_exploration_from_model(item) <NEW_LINE> html_list = exploration.get_all_html_content_strings() <NEW_LINE> err_dict = html_cleaner.validate_rte_format( html_list, feconf.RTE_FORMAT_CKEDITOR) <NEW_LINE> for key in err_dict: <NEW_LINE> <INDENT> if err_dict[key]: <NEW_LINE> <INDENT> yield(key, err_dict[key]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def reduce(key, values): <NEW_LINE> <INDENT> final_values = [ast.literal_eval(value) for value in values] <NEW_LINE> yield (key, list(set().union(*final_values))) | Job that checks the html content of an exploration and validates it
for CKEditor. | 62598fe4ab23a570cc2d50dc |
class Queue: <NEW_LINE> <INDENT> class ArrayQueue: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.def_cap = 10 <NEW_LINE> self._data=[None]*(self.def_cap) <NEW_LINE> self._size=0 <NEW_LINE> self._front=0 <NEW_LINE> self._pos=0 <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return (self._size==0) <NEW_LINE> <DEDENT> def len(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def first(self): <NEW_LINE> <INDENT> if not(self.is_empty()): <NEW_LINE> <INDENT> return self._data[self._front] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Queue is empty") <NEW_LINE> <DEDENT> <DEDENT> def push(self,e): <NEW_LINE> <INDENT> if(self.len()<self.def_cap): <NEW_LINE> <INDENT> self._data[self._pos]=e <NEW_LINE> self._pos=(self._pos+1)%len(self._data) <NEW_LINE> self._size+=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._resize() <NEW_LINE> self.push(e) <NEW_LINE> <DEDENT> <DEDENT> def dequeue(self): <NEW_LINE> <INDENT> if not(self.is_empty()): <NEW_LINE> <INDENT> self._data[self._front]=None <NEW_LINE> self._front+=1 <NEW_LINE> self._size-=1 <NEW_LINE> if(self.is_empty()): <NEW_LINE> <INDENT> self._front=0 <NEW_LINE> self._pos=0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Queue is empty") <NEW_LINE> <DEDENT> <DEDENT> def _resize(self): <NEW_LINE> <INDENT> self._pos=self.def_cap <NEW_LINE> self.def_cap*=2 <NEW_LINE> temp=[None]*(self.def_cap) <NEW_LINE> for i in range(len(temp)): <NEW_LINE> <INDENT> temp[i]=self._data[self._front] <NEW_LINE> self._front=(self._front+1)%len(self._data) <NEW_LINE> <DEDENT> self._data=temp <NEW_LINE> self._front=0 <NEW_LINE> <DEDENT> def print_queue(self): <NEW_LINE> <INDENT> print(self._data) <NEW_LINE> <DEDENT> <DEDENT> class linkedQueue: <NEW_LINE> <INDENT> class _Node: <NEW_LINE> <INDENT> def __init__(self, element, after): <NEW_LINE> <INDENT> self._element = element <NEW_LINE> self._after = after <NEW_LINE> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self._head = None <NEW_LINE> self._tail = None <NEW_LINE> self._size = 0 <NEW_LINE> <DEDENT> '''len,is_empty methods''' <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return self._size == 0 <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def push(self, e): <NEW_LINE> <INDENT> node = self._Node(e, None) <NEW_LINE> if(self.is_empty()): <NEW_LINE> <INDENT> self._head = node <NEW_LINE> self._tail = node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._tail._after = node <NEW_LINE> <DEDENT> self._tail = node <NEW_LINE> self._size += 1 <NEW_LINE> <DEDENT> def top(self): <NEW_LINE> <INDENT> if not(self.is_empty()): <NEW_LINE> <INDENT> return self._head._element <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Empty Queue") <NEW_LINE> <DEDENT> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if (self.is_empty()): <NEW_LINE> <INDENT> raise TypeError("Empty Queue") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp = self._head <NEW_LINE> ans = temp._element <NEW_LINE> self._head = self._head._after <NEW_LINE> self._size -= 1 <NEW_LINE> if(self.is_empty()): <NEW_LINE> <INDENT> self._tail = None <NEW_LINE> <DEDENT> temp = None <NEW_LINE> return ans | Class for Queue Implementations | 62598fe4ab23a570cc2d50dd |
class ConditionalInstanceNormalisation(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channel, n_speakers): <NEW_LINE> <INDENT> super(ConditionalInstanceNormalisation, self).__init__() <NEW_LINE> self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") <NEW_LINE> self.dim_in = in_channel <NEW_LINE> self.gamma = nn.Linear(n_speakers, in_channel) <NEW_LINE> self.beta = nn.Linear(n_speakers, in_channel) <NEW_LINE> <DEDENT> def forward(self, x, c): <NEW_LINE> <INDENT> u = torch.mean(x, dim=2, keepdim=True) <NEW_LINE> var = torch.mean((x - u) * (x - u), dim=2, keepdim=True) <NEW_LINE> std = torch.sqrt(var + 1e-8) <NEW_LINE> gamma = self.gamma(c.to(self.device)) <NEW_LINE> gamma = gamma.view(-1, self.dim_in, 1) <NEW_LINE> beta = self.beta(c.to(self.device)) <NEW_LINE> beta = beta.view(-1, self.dim_in, 1) <NEW_LINE> h = (x - u) / std <NEW_LINE> h = h * gamma + beta <NEW_LINE> return h | CIN Block. | 62598fe4d8ef3951e32c81cb |
@parsleyfy <NEW_LINE> class CreditCardEntryForm(forms.ModelForm): <NEW_LINE> <INDENT> receipts = MultiFileField( min_num=0, max_num=99, max_file_size=1024 * 1024 * 100, required=False) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> model = CreditCardEntry <NEW_LINE> widgets = { 'date': forms.DateInput(attrs={'class': 'form-control'}), 'card': forms.Select(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'merchant': forms.TextInput(attrs={'class': 'form-control'}), 'amount': forms.TextInput( attrs={'size': 10, 'maxlength': 10, 'class': 'form-control', 'id': 'entry_amount'}), 'comments': forms.Textarea( attrs={'rows': 2, 'cols': 50, 'class': 'form-control'}), } <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CreditCardEntryForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['date'].label = "Purchase Date" <NEW_LINE> self.fields['name'].label = "Your Name" <NEW_LINE> if hasattr(self, 'instance') and self.instance.pk: <NEW_LINE> <INDENT> formatted_date = self.instance.date.strftime('%m/%d/%Y') <NEW_LINE> self.initial['date'] = formatted_date <NEW_LINE> amount = self.instance.amount <NEW_LINE> self.initial['amount'] = remove_trailing_zeroes(amount) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.initial['date'] = today_in_american_format() | A Form for CreditCardEntries along with multiple CreditCardReceipts. | 62598fe44c3428357761a98f |
class VertexDataset(dsl.Artifact): <NEW_LINE> <INDENT> TYPE_NAME = 'google.VertexDataset' <NEW_LINE> def __init__(self, name: Optional[str] = None, uri: Optional[str] = None, metadata: Optional[Dict] = None): <NEW_LINE> <INDENT> super().__init__(uri=uri, name=name, metadata=metadata) | An artifact representing a Vertex Dataset. | 62598fe4187af65679d29f69 |
class TestXBlockWrapper(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def leaf_module_runtime(self): <NEW_LINE> <INDENT> return get_test_system() <NEW_LINE> <DEDENT> def leaf_descriptor(self, descriptor_cls): <NEW_LINE> <INDENT> location = 'i4x://org/course/category/name' <NEW_LINE> runtime = get_test_descriptor_system() <NEW_LINE> return runtime.construct_xblock_from_class( descriptor_cls, ScopeIds(None, descriptor_cls.__name__, location, location), DictFieldData({}), ) <NEW_LINE> <DEDENT> def leaf_module(self, descriptor_cls): <NEW_LINE> <INDENT> descriptor = self.leaf_descriptor(descriptor_cls) <NEW_LINE> descriptor.xmodule_runtime = self.leaf_module_runtime <NEW_LINE> return descriptor <NEW_LINE> <DEDENT> def container_module_runtime(self, depth): <NEW_LINE> <INDENT> runtime = self.leaf_module_runtime <NEW_LINE> if depth == 0: <NEW_LINE> <INDENT> runtime.get_module.side_effect = lambda x: self.leaf_module(HtmlDescriptor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> runtime.get_module.side_effect = lambda x: self.container_module(VerticalDescriptor, depth - 1) <NEW_LINE> <DEDENT> runtime.position = 2 <NEW_LINE> return runtime <NEW_LINE> <DEDENT> def container_descriptor(self, descriptor_cls, depth): <NEW_LINE> <INDENT> location = 'i4x://org/course/category/name' <NEW_LINE> runtime = get_test_descriptor_system() <NEW_LINE> if depth == 0: <NEW_LINE> <INDENT> runtime.load_item.side_effect = lambda x: self.leaf_module(HtmlDescriptor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> runtime.load_item.side_effect = lambda x: self.container_module(VerticalDescriptor, depth - 1) <NEW_LINE> <DEDENT> return runtime.construct_xblock_from_class( descriptor_cls, ScopeIds(None, descriptor_cls.__name__, location, location), DictFieldData({ 'children': range(3) }), ) <NEW_LINE> <DEDENT> def container_module(self, descriptor_cls, depth): <NEW_LINE> <INDENT> descriptor = self.container_descriptor(descriptor_cls, depth) <NEW_LINE> descriptor.xmodule_runtime = self.container_module_runtime(depth) <NEW_LINE> return descriptor | Helper methods used in test case classes below. | 62598fe4fbf16365ca7947ac |
class AIBoardHistory(models.Model): <NEW_LINE> <INDENT> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True) <NEW_LINE> trade_start_at = models.DateTimeField(default=None, null=True) <NEW_LINE> trade_end_at = models.DateTimeField(default=None, null=True) <NEW_LINE> ai_board_id = models.PositiveIntegerField(db_index=True) <NEW_LINE> version = models.PositiveIntegerField(default=1, null=True, help_text='AIの取引世代') <NEW_LINE> trade_count = models.PositiveIntegerField(default=None, null=True) <NEW_LINE> open_position_count = models.PositiveIntegerField(default=None, null=True) <NEW_LINE> open_position_profit = models.FloatField(default=None, null=True) <NEW_LINE> open_position_tick = models.FloatField(default=None, null=True) <NEW_LINE> before_units = models.PositiveIntegerField() <NEW_LINE> after_units = models.PositiveIntegerField() <NEW_LINE> is_rank_up = models.PositiveIntegerField(help_text='昇進ならTrue', default=None, null=True) <NEW_LINE> profit_summary = models.FloatField() <NEW_LINE> profit_average = models.FloatField() <NEW_LINE> profit_tick_summary = models.FloatField() <NEW_LINE> profit_tick_average = models.FloatField() <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> app_label = 'board' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, board, after_units, price): <NEW_LINE> <INDENT> open_orders = Order.get_open_order_by_board(board) <NEW_LINE> open_position_count = len(open_orders) <NEW_LINE> open_position_profit = sum([o.get_current_profit(price) for o in open_orders]) <NEW_LINE> open_position_tick = sum([o.get_current_profit_tick(price) for o in open_orders]) <NEW_LINE> orders = Order.get_close_order_by_board(board) <NEW_LINE> trade_count = len(orders) <NEW_LINE> profit_summary = sum([x.profit for x in orders]) <NEW_LINE> profit_average = float(profit_summary / trade_count) <NEW_LINE> profit_tick_summary = sum([x.profit_tick for x in orders]) <NEW_LINE> profit_tick_average = float(profit_tick_summary / trade_count) <NEW_LINE> is_rank_up = after_units > board.units <NEW_LINE> trade_start_at = min([x.created_at for x in orders]) <NEW_LINE> trade_end_at = max([x.end_at for x in orders]) <NEW_LINE> return cls.objects.create(trade_start_at=trade_start_at, trade_end_at=trade_end_at, ai_board_id=board.id, version=board.version, trade_count=trade_count, before_units=board.units, after_units=after_units, is_rank_up=is_rank_up, profit_summary=profit_summary, profit_average=profit_average, profit_tick_summary=profit_tick_summary, profit_tick_average=profit_tick_average, open_position_count=open_position_count, open_position_profit=open_position_profit, open_position_tick=open_position_tick) <NEW_LINE> <DEDENT> @property <NEW_LINE> def board(self): <NEW_LINE> <INDENT> return AIBoard.get(self.ai_board_id) <NEW_LINE> <DEDENT> def get_new_history(self, count): <NEW_LINE> <INDENT> return list(AIBoardHistory.objects.filter(ai_board_id=self.ai_board_id).order_by('-version')[:count]) | 成績 | 62598fe44c3428357761a997 |
class PolyshaperEngraving(inkex.Effect): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> inkex.Effect.__init__(self) <NEW_LINE> self.doc_height = 0 <NEW_LINE> self.gcode_file_path = os.path.expanduser("~/") <NEW_LINE> self.define_command_line_options() <NEW_LINE> <DEDENT> def define_command_line_options(self): <NEW_LINE> <INDENT> self.OptionParser.add_option("-f", "--filename", action="store", type="string", dest="filename", default="polyshaper", help=("Basename of the generated G-CODE file (will have .nc " "extension and will be saved on Desktop")) <NEW_LINE> self.OptionParser.add_option("-x", "--dim-x", action="store", type="float", dest="dim_x", default=200.0, help="Plane X dimension in mm") <NEW_LINE> self.OptionParser.add_option("-y", "--dim-y", action="store", type="float", dest="dim_y", default=200.0, help="Plane Y dimension in mm") <NEW_LINE> self.OptionParser.add_option("-z", "--depth-z", action="store", type="float", dest="depth_z", default=10.0, help="Engraving depth in mm") <NEW_LINE> self.OptionParser.add_option("", "--active-tab", action="store", type="string", dest="active_tab", default='setup', help="Active tab.") <NEW_LINE> <DEDENT> def effect(self): <NEW_LINE> <INDENT> to_mm = lambda value: self.uutounit(value, 'mm') <NEW_LINE> to_uu = lambda value: self.unittouu(str(value) + "mm") <NEW_LINE> working_area_generator = WorkingAreaGenerator(to_uu, WORKING_AREA_ID) <NEW_LINE> working_area_generator.set_size(self.options.dim_x, self.options.dim_y) <NEW_LINE> working_area_generator.upsert(self.document.getroot()) <NEW_LINE> if not self.options.ids: <NEW_LINE> <INDENT> inkex.debug(_(("No path was seletect, only the working area was generated. Now draw a " "path inside the working area and select it to generate the g-code"))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> paths_extractor = PathsExtractor(self.selected.values(), to_mm, WORKING_AREA_ID, FlattenBezier(FLATNESS)) <NEW_LINE> paths_extractor.extract() <NEW_LINE> tool_path_generator = EngravingToolPathsGenerator(paths_extractor.paths(), self.options.depth_z, MIN_DISTANCE, DISCRETIZATION_STEP) <NEW_LINE> tool_path_generator.generate() <NEW_LINE> gcode_generator = EngravingGCodeGenerator(tool_path_generator.paths(), MM_PER_DEGREE, SAFE_Z, SMALL_DISTANCE, SMALL_ANGLE) <NEW_LINE> gcode_generator.generate() <NEW_LINE> filename = base_filename(self.options.filename, self.gcode_file_path) + ".gcode" <NEW_LINE> write_file(filename, lambda f: f.write(gcode_generator.gcode())) <NEW_LINE> inkex.debug(_("The generate g-code has been save to ") + filename) | The main class of the plugin
| 62598fe526238365f5fad250 |
class Newmark(): <NEW_LINE> <INDENT> def __init__(self, M, C, K, nls=None, gtype=None): <NEW_LINE> <INDENT> self.M = M <NEW_LINE> self.C = C <NEW_LINE> self.K = K <NEW_LINE> if isinstance(nls, NLS): <NEW_LINE> <INDENT> nls = nls.nls <NEW_LINE> <DEDENT> self.nls = NLS(nls) <NEW_LINE> if gtype is None: <NEW_LINE> <INDENT> self.gamma = 1/2 <NEW_LINE> self.beta = 1/4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.gamma, self.beta = self._params(gtype) <NEW_LINE> <DEDENT> <DEDENT> def integrate(self, u, dt, x0=None, v0=None, sensitivity=False): <NEW_LINE> <INDENT> ndof = self.M.shape[0] <NEW_LINE> if x0 is None: <NEW_LINE> <INDENT> x0 = np.zeros(ndof) <NEW_LINE> <DEDENT> if v0 is None: <NEW_LINE> <INDENT> v0 = np.zeros(ndof) <NEW_LINE> <DEDENT> return newmark_beta_nl(self.M, self.C, self.K, x0, v0, dt, u, self.nls, sensitivity, self.gamma, self.beta) <NEW_LINE> <DEDENT> def _params(self, gtype): <NEW_LINE> <INDENT> d = { 'explicit': (0, 0), 'central': (1/2, 0), 'fox-goodwin': (1/2, 1/12), 'linear': (1/2, 1/6), 'average': (1/2, 1/4) } <NEW_LINE> try: <NEW_LINE> <INDENT> gamma, beta = d[gtype] <NEW_LINE> <DEDENT> except KeyError as err: <NEW_LINE> <INDENT> raise Exception(f'Wrong key {gtype}. Should be one of {d.keys()}') from err <NEW_LINE> <DEDENT> return gamma, beta | Nonlinear Newmark solver class.
Input M,C,K and nonlin.
See :func:`newmark_beta_nl` and :class:`.nolinear_elements.NLS`. | 62598fe54c3428357761a999 |
class LinearSearchOptimizer(BaseOptimizer): <NEW_LINE> <INDENT> def optimize(self, net_string, device_graph): <NEW_LINE> <INDENT> net = json.loads(net_string) <NEW_LINE> groups = self.create_colocation_groups(get_flattened_layer_names(net_string)) <NEW_LINE> best_score = -1 <NEW_LINE> best_net = None <NEW_LINE> for comb in tqdm(product(range(len(device_graph.devices)), repeat=len(groups)), total=len(device_graph.devices) ** len(groups), unit='placements'): <NEW_LINE> <INDENT> net = apply_placement(net_string, comb, groups) <NEW_LINE> score = self.evaluate_placement(net, device_graph) <NEW_LINE> if score < best_score or best_net is None: <NEW_LINE> <INDENT> best_net = net <NEW_LINE> best_score = score <NEW_LINE> <DEDENT> <DEDENT> return best_net | A naive optimizer that carries out a brute-force search for the best placement. Will take significant time
to run if the search space is too large. | 62598fe5091ae3566870530a |
class Shape(): <NEW_LINE> <INDENT> def __init__(self, name, area=None, perimeter=None, units=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.area = area <NEW_LINE> self.perimeter = perimeter <NEW_LINE> self.units = units <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return('name:{}\narea:{}\nperimeter:{}\nunits:{}'.format( self.name, self.area, self.perimeter, self.units) ) | A shape has the following attributes:
area: a float representing the area of the shape in units
perimeter: a float representing the perimeter of the shape in units
units: a string representing the units of measurement e.g. 'mm' or in' | 62598fe5187af65679d29f6d |
class HTTPSRedirectHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> port = self.settings['port'] <NEW_LINE> url_prefix = self.settings['url_prefix'] <NEW_LINE> host = self.request.headers.get('Host', 'localhost') <NEW_LINE> self.redirect( 'https://%s:%s%s' % (host, port, url_prefix)) | A handler to redirect clients from HTTP to HTTPS. Only used if
`https_redirect` is True in Gate One's settings. | 62598fe5ad47b63b2c5a7f3e |
class OrcIdGenerator(metaclass=SingletonType): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._index = 0 <NEW_LINE> self._now = 0 <NEW_LINE> self._max_pid = 131072 <NEW_LINE> self._pid = None <NEW_LINE> <DEDENT> def set_pid(self, p_pid: int): <NEW_LINE> <INDENT> self._pid = p_pid <NEW_LINE> return self <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> d1 = int(time.time() * 1000) <NEW_LINE> d2 = self._pid or os.getpid() <NEW_LINE> self._index = 0 if d1 != self._now else self._index + 1 <NEW_LINE> if d2 >= self._max_pid: <NEW_LINE> <INDENT> raise OrcFrameworkDatabaseException(0x1, "Pid is too big, %s" % d2) <NEW_LINE> <DEDENT> if 32 == self._index: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> d1 = int(time.time() * 1000) <NEW_LINE> self._index = 0 <NEW_LINE> <DEDENT> self._now = d1 <NEW_LINE> return (d1 << 22) + (d2 << 5) + self._index <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def s_get(p_pid): <NEW_LINE> <INDENT> cls = OrcIdGenerator() <NEW_LINE> return cls.set_pid(p_pid).get() | id generator 41 + 17 + 5
time_distance(9) + | 62598fe5fbf16365ca7947b2 |
class VPCRegionInfo(RegionInfo): <NEW_LINE> <INDENT> def __init__(self, connection=None, name=None, id=None, connection_cls=None): <NEW_LINE> <INDENT> from footmark.vpc.connection import VPCConnection <NEW_LINE> super(VPCRegionInfo, self).__init__(connection, name, id, VPCConnection) | Represents an ECS Region | 62598fe54c3428357761a99f |
class Logger(logging.Logger): <NEW_LINE> <INDENT> formatter = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> logging.Logger.__init__(self, "Logger") <NEW_LINE> fh = Handler() <NEW_LINE> fh.setFormatter(Formatter()) <NEW_LINE> self.addHandler(fh) <NEW_LINE> fh = logging.FileHandler('results/log.txt', mode='w') <NEW_LINE> fh.setFormatter(Formatter()) <NEW_LINE> self.addHandler(fh) <NEW_LINE> <DEDENT> def log(self, level, msg, *args, **kwargs): <NEW_LINE> <INDENT> logging.Logger.log(self, level, msg) | Main logger class | 62598fe5ab23a570cc2d50e7 |
class FactTestCase(CLITestCase): <NEW_LINE> <INDENT> @run_only_on('sat') <NEW_LINE> @tier1 <NEW_LINE> @upgrade <NEW_LINE> def test_positive_list_by_name(self): <NEW_LINE> <INDENT> for fact in ( u'uptime', u'uptime_days', u'uptime_seconds', u'memoryfree', u'ipaddress'): <NEW_LINE> <INDENT> with self.subTest(fact): <NEW_LINE> <INDENT> args = {u'search': "fact={0}".format(fact)} <NEW_LINE> facts = Fact().list(args) <NEW_LINE> self.assertEqual(facts[0]['fact'], fact) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @run_only_on('sat') <NEW_LINE> @tier1 <NEW_LINE> def test_negative_list_by_name(self): <NEW_LINE> <INDENT> fact = gen_string('alpha') <NEW_LINE> args = {'search': "fact={0}".format(fact)} <NEW_LINE> self.assertEqual( Fact().list(args), [], 'No records should be returned') | Fact related tests. | 62598fe5fbf16365ca7947bc |
class AllowOnlyEnabledServiceAccountMixin: <NEW_LINE> <INDENT> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> mo = re.search('Token (\S+)', request.META.get('HTTP_AUTHORIZATION', '')) <NEW_LINE> if mo: <NEW_LINE> <INDENT> srv_acct = ServiceAccount.objects.get_object_or_none(user__auth_token__key=mo.group(1)) <NEW_LINE> if srv_acct: <NEW_LINE> <INDENT> if srv_acct.admin_enabled is False: <NEW_LINE> <INDENT> return JsonResponse(data={'detail': 'this service account has been administratively disabled'}, status=status.HTTP_403_FORBIDDEN) <NEW_LINE> <DEDENT> elif srv_acct.enabled is False: <NEW_LINE> <INDENT> return JsonResponse(data={'detail': 'this service account has been disabled'}, status=status.HTTP_403_FORBIDDEN) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return JsonResponse(data={'detail': 'access to this endpoint is only available to enabled ' 'service accounts'}, status=status.HTTP_403_FORBIDDEN) <NEW_LINE> <DEDENT> <DEDENT> return super().dispatch(request, *args, **kwargs) | A mixin for Django Rest Framework viewsets that checks if the request is made from a ServiceAccount and only
allows access to the endpoint if an enabled ServiceAccount made the request. If the ServiceAccount is disabled
by the owner or an admin, a 403 error will be received instead of the API response. This currently works for APIs
using TokenAuthentication (rest_framework.authentication.TokenAuthentication). | 62598fe5187af65679d29f73 |
class MsgM25FlashWriteStatus(SBP): <NEW_LINE> <INDENT> def __init__(self, sbp): <NEW_LINE> <INDENT> self.__dict__.update(sbp.__dict__) <NEW_LINE> self.payload = sbp.payload <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return to_repr(self) | SBP class for message MSG_M25_FLASH_WRITE_STATUS (0x00F3) | 62598fe5187af65679d29f74 |
class PeriodShortEnumEnum(Enum): <NEW_LINE> <INDENT> true = 1 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_bundlemgr_cfg as meta <NEW_LINE> return meta._meta_table['PeriodShortEnumEnum'] | PeriodShortEnumEnum
Period short enum
.. data:: true = 1
Use the standard LACP short period (1s) | 62598fe5fbf16365ca7947c0 |
class RandomizedRectifierLayer(Layer): <NEW_LINE> <INDENT> def __init__(self, incoming, lower=0.3, upper=0.8, shared_axes='auto', **kwargs): <NEW_LINE> <INDENT> super(RandomizedRectifierLayer, self).__init__(incoming, **kwargs) <NEW_LINE> self._srng = RandomStreams(get_rng().randint(1, 2147462579)) <NEW_LINE> self.lower = lower <NEW_LINE> self.upper = upper <NEW_LINE> if not isinstance(lower > upper, theano.Variable) and lower > upper: <NEW_LINE> <INDENT> raise ValueError("Upper bound for RandomizedRectifierLayer needs " "to be higher than lower bound.") <NEW_LINE> <DEDENT> if shared_axes == 'auto': <NEW_LINE> <INDENT> self.shared_axes = (0,) + tuple(range(2, len(self.input_shape))) <NEW_LINE> <DEDENT> elif shared_axes == 'all': <NEW_LINE> <INDENT> self.shared_axes = tuple(range(len(self.input_shape))) <NEW_LINE> <DEDENT> elif isinstance(shared_axes, int): <NEW_LINE> <INDENT> self.shared_axes = (shared_axes,) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.shared_axes = shared_axes <NEW_LINE> <DEDENT> <DEDENT> def get_output_for(self, input, deterministic=False, **kwargs): <NEW_LINE> <INDENT> if deterministic or self.upper == self.lower: <NEW_LINE> <INDENT> return theano.tensor.nnet.relu(input, (self.upper+self.lower)/2.0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shape = list(self.input_shape) <NEW_LINE> if any(s is None for s in shape): <NEW_LINE> <INDENT> shape = list(input.shape) <NEW_LINE> <DEDENT> for ax in self.shared_axes: <NEW_LINE> <INDENT> shape[ax] = 1 <NEW_LINE> <DEDENT> rnd = self._srng.uniform(tuple(shape), low=self.lower, high=self.upper, dtype=theano.config.floatX) <NEW_LINE> rnd = theano.tensor.addbroadcast(rnd, *self.shared_axes) <NEW_LINE> return theano.tensor.nnet.relu(input, rnd) | A layer that applies a randomized leaky rectify nonlinearity to its input.
The randomized leaky rectifier was first proposed and used in the Kaggle
NDSB Competition, and later evaluated in [1]_. Compared to the standard
leaky rectifier :func:`leaky_rectify`, it has a randomly sampled slope
for negative input during training, and a fixed slope during evaluation.
Equation for the randomized rectifier linear unit during training:
:math:`\varphi(x) = \max((\sim U(lower, upper)) \cdot x, x)`
During evaluation, the factor is fixed to the arithmetic mean of `lower`
and `upper`.
Parameters
----------
incoming : a :class:`Layer` instance or a tuple
The layer feeding into this layer, or the expected input shape
lower : Theano shared variable, expression, or constant
The lower bound for the randomly chosen slopes.
upper : Theano shared variable, expression, or constant
The upper bound for the randomly chosen slopes.
shared_axes : 'auto', 'all', int or tuple of int
The axes along which the random slopes of the rectifier units are
going to be shared. If ``'auto'`` (the default), share over all axes
except for the second - this will share the random slope over the
minibatch dimension for dense layers, and additionally over all
spatial dimensions for convolutional layers. If ``'all'``, share over
all axes, thus using a single random slope.
**kwargs
Any additional keyword arguments are passed to the `Layer` superclass.
References
----------
.. [1] Bing Xu, Naiyan Wang et al. (2015):
Empirical Evaluation of Rectified Activations in Convolutional Network,
http://arxiv.org/abs/1505.00853 | 62598fe5187af65679d29f75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.