code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class SecurePermissionAPI(object): <NEW_LINE> <INDENT> def __init__(self, user): <NEW_LINE> <INDENT> self._user = user <NEW_LINE> self._permissions = CachingPermissionAPI(user) <NEW_LINE> <DEDENT> def get(self, values): <NEW_LINE> <INDENT> self._checkPermissions(values) <NEW_LINE> return self._permissions.get(values) <NEW_LINE> <DEDENT> def set(self, values): <NEW_LINE> <INDENT> self._checkPermissions([(path, operation) for path, operation, _, _ in values]) <NEW_LINE> return self._permissions.set(values) <NEW_LINE> <DEDENT> def _checkPermissions(self, values): <NEW_LINE> <INDENT> pathsAndOperations = set() <NEW_LINE> for path, operation in values: <NEW_LINE> <INDENT> if operation in [Operation.WRITE_TAG_VALUE, Operation.READ_TAG_VALUE, Operation.DELETE_TAG_VALUE, Operation.CONTROL_TAG_VALUE]: <NEW_LINE> <INDENT> pathsAndOperations.add((path, Operation.CONTROL_TAG_VALUE)) <NEW_LINE> <DEDENT> elif operation in [Operation.UPDATE_TAG, Operation.DELETE_TAG, Operation.CONTROL_TAG]: <NEW_LINE> <INDENT> pathsAndOperations.add((path, Operation.CONTROL_TAG)) <NEW_LINE> <DEDENT> elif operation in Operation.NAMESPACE_OPERATIONS: <NEW_LINE> <INDENT> pathsAndOperations.add((path, Operation.CONTROL_NAMESPACE)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Invalid operation %r.' % operation) <NEW_LINE> <DEDENT> <DEDENT> deniedOperations = checkPermissions(self._user, pathsAndOperations) <NEW_LINE> if deniedOperations: <NEW_LINE> <INDENT> raise PermissionDeniedError(self._user.username, deniedOperations)
The public API to secure permission-related functionality. @param user: The L{User} to perform operations on behalf of.
62598fa792d797404e388af6
class PLSRegression(_PLS): <NEW_LINE> <INDENT> @_deprecate_positional_args <NEW_LINE> def __init__(self, n_components=2, *, scale=True, max_iter=500, tol=1e-06, copy=True): <NEW_LINE> <INDENT> super().__init__( n_components=n_components, scale=scale, deflation_mode="regression", mode="A", algorithm='nipals', max_iter=max_iter, tol=tol, copy=copy)
PLS regression PLSRegression is also known as PLS2 or PLS1, depending on the number of targets. Read more in the :ref:`User Guide <cross_decomposition>`. .. versionadded:: 0.8 Parameters ---------- n_components : int, default=2 Number of components to keep. Should be in `[1, min(n_samples, n_features, n_targets)]`. scale : bool, default=True Whether to scale `X` and `Y`. algorithm : {'nipals', 'svd'}, default='nipals' The algorithm used to estimate the first singular vectors of the cross-covariance matrix. 'nipals' uses the power method while 'svd' will compute the whole SVD. max_iter : int, default=500 The maximum number of iterations of the power method when `algorithm='nipals'`. Ignored otherwise. tol : float, default=1e-06 The tolerance used as convergence criteria in the power method: the algorithm stops whenever the squared norm of `u_i - u_{i-1}` is less than `tol`, where `u` corresponds to the left singular vector. copy : bool, default=True Whether to copy `X` and `Y` in fit before applying centering, and potentially scaling. If False, these operations will be done inplace, modifying both arrays. Attributes ---------- x_weights_ : ndarray of shape (n_features, n_components) The left singular vectors of the cross-covariance matrices of each iteration. y_weights_ : ndarray of shape (n_targets, n_components) The right singular vectors of the cross-covariance matrices of each iteration. x_loadings_ : ndarray of shape (n_features, n_components) The loadings of `X`. y_loadings_ : ndarray of shape (n_targets, n_components) The loadings of `Y`. x_scores_ : ndarray of shape (n_samples, n_components) The transformed training samples. y_scores_ : ndarray of shape (n_samples, n_components) The transformed training targets. x_rotations_ : ndarray of shape (n_features, n_components) The projection matrix used to transform `X`. y_rotations_ : ndarray of shape (n_features, n_components) The projection matrix used to transform `Y`. coef_ : ndarray of shape (n_features, n_targets) The coefficients of the linear model such that `Y` is approximated as `Y = X @ coef_`. n_iter_ : list of shape (n_components,) Number of iterations of the power method, for each component. Empty if `algorithm='svd'`. Examples -------- >>> from sklearn.cross_decomposition import PLSRegression >>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [2.,5.,4.]] >>> Y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]] >>> pls2 = PLSRegression(n_components=2) >>> pls2.fit(X, Y) PLSRegression() >>> Y_pred = pls2.predict(X)
62598fa726068e7796d4c87b
class Maze: <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> if os.path.isfile(filename) is False: <NEW_LINE> <INDENT> self.status = False <NEW_LINE> print(ERR_FILE.format(filename)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with open(filename, "r") as maze_data: <NEW_LINE> <INDENT> splited_maze = maze_data.read().splitlines() <NEW_LINE> <DEDENT> if self.check_file(splited_maze): <NEW_LINE> <INDENT> self.string = '\n'.join( (self.check_line(line) for line in splited_maze) ) <NEW_LINE> for symbol_to_place in elmt_val('symbol', 'item', True): <NEW_LINE> <INDENT> position = random.choice( [idx for (idx, value) in enumerate(self.string) if value == elmt_val('symbol', 'name', 'floor', 0)] ) <NEW_LINE> self.set_symbol(symbol_to_place, position) <NEW_LINE> <DEDENT> self.MAX_ITEMS = sum( 1 for _ in elmt_val('name', 'item', True) ) <NEW_LINE> self.COL_NB = MAZE_SIZE + 1 <NEW_LINE> self.RANGE = range(self.COL_NB * MAZE_SIZE - 1) <NEW_LINE> self.status = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.status = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def check_file(splited_maze): <NEW_LINE> <INDENT> if len(splited_maze) != MAZE_SIZE: <NEW_LINE> <INDENT> print(ERR_LINE.format(len(splited_maze))) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def check_line(line): <NEW_LINE> <INDENT> differance = MAZE_SIZE - len(str(line)) <NEW_LINE> if differance < 0: <NEW_LINE> <INDENT> return line[:MAZE_SIZE] <NEW_LINE> <DEDENT> elif differance > 0: <NEW_LINE> <INDENT> return line + (differance * elmt_val('symbol', 'name', 'floor', 0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return line <NEW_LINE> <DEDENT> <DEDENT> def set_symbol(self, symbol, pos): <NEW_LINE> <INDENT> txt = self.string <NEW_LINE> self.string = txt[:pos] + symbol + txt[pos + 1:]
Provides a usable maze from a text file Checks the maze compatibility Moves the player to it
62598fa799cbb53fe6830df8
class SplashQWebView(QWebView): <NEW_LINE> <INDENT> onBeforeClose = None <NEW_LINE> def closeEvent(self, event): <NEW_LINE> <INDENT> dont_close = False <NEW_LINE> if self.onBeforeClose: <NEW_LINE> <INDENT> dont_close = self.onBeforeClose() <NEW_LINE> <DEDENT> if dont_close: <NEW_LINE> <INDENT> event.ignore() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event.accept()
QWebView subclass that handles 'close' requests.
62598fa74f6381625f19944f
class Axis3D(Enum): <NEW_LINE> <INDENT> POS_X = 0 <NEW_LINE> NEG_X = 1 <NEW_LINE> POS_Y = 2 <NEW_LINE> NEG_Y = 3 <NEW_LINE> POS_Z = 4 <NEW_LINE> NEG_Z = 5 <NEW_LINE> def index(self): <NEW_LINE> <INDENT> if self is Axis3D.POS_X or self is Axis3D.NEG_X: <NEW_LINE> <INDENT> return X <NEW_LINE> <DEDENT> elif self is Axis3D.POS_Y or self is Axis3D.NEG_Y: <NEW_LINE> <INDENT> return Y <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Z <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_property_name(cls, axis_name): <NEW_LINE> <INDENT> if axis_name == "POSITIVE_X": <NEW_LINE> <INDENT> return Axis3D.POS_X <NEW_LINE> <DEDENT> elif axis_name == "NEGATIVE_X": <NEW_LINE> <INDENT> return Axis3D.NEG_X <NEW_LINE> <DEDENT> elif axis_name == "POSITIVE_Y": <NEW_LINE> <INDENT> return Axis3D.POS_Y <NEW_LINE> <DEDENT> elif axis_name == "NEGATIVE_Y": <NEW_LINE> <INDENT> return Axis3D.NEG_Y <NEW_LINE> <DEDENT> elif axis_name == "POSITIVE_Z": <NEW_LINE> <INDENT> return Axis3D.POS_Z <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Axis3D.NEG_Z <NEW_LINE> <DEDENT> <DEDENT> def is_positive(self): <NEW_LINE> <INDENT> return self is Axis3D.POS_X or self is Axis3D.POS_Y or self is Axis3D.POS_Z
An enum with values representing each axis in three-dimensional space, indexed as follows: 0: POS_X 1: NEG_X 2: POS_Y 3: NEG_Y 4: POS_Z 5: NEG_Z
62598fa70c0af96317c562a5
class InputSplitter(IPyInputSplitter): <NEW_LINE> <INDENT> def push(self, lines): <NEW_LINE> <INDENT> self._store(lines) <NEW_LINE> source = self.source <NEW_LINE> self.code, self._is_complete = None, None <NEW_LINE> if source.endswith('\\\n'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._update_indent(lines) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self._update_indent() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.get_indent_spaces() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.code = self._compile(source, symbol="exec") <NEW_LINE> <DEDENT> except (SyntaxError, OverflowError, ValueError, TypeError, MemoryError): <NEW_LINE> <INDENT> self._is_complete = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._is_complete = self.code is not None <NEW_LINE> <DEDENT> return self._is_complete <NEW_LINE> <DEDENT> def push_accepts_more(self): <NEW_LINE> <INDENT> if not self._is_complete: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.indent_spaces == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
A specialized version of IPython's input splitter. The major differences between this and the base version are: - push considers a SyntaxError as incomplete code - push_accepts_more returns False when the indentation has return flush regardless of whether the statement is a single line
62598fa7627d3e7fe0e06dcf
class ResNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, block, duplicates, num_classes=10): <NEW_LINE> <INDENT> super(ResNet, self).__init__() <NEW_LINE> self.in_channels = 32 <NEW_LINE> self.conv1 = conv3x3(in_channels=3, out_channels=32) <NEW_LINE> self.bn = nn.BatchNorm2d(num_features=32) <NEW_LINE> self.relu = nn.ReLU(inplace=True) <NEW_LINE> self.dropout = nn.Dropout2d(p=0.02) <NEW_LINE> self.conv2_x = self._make_block(block, duplicates[0], out_channels=32) <NEW_LINE> self.conv3_x = self._make_block(block, duplicates[1], out_channels=64, stride=2) <NEW_LINE> self.conv4_x = self._make_block(block, duplicates[2], out_channels=128, stride=2) <NEW_LINE> self.conv5_x = self._make_block(block, duplicates[3], out_channels=256, stride=2) <NEW_LINE> self.maxpool = nn.MaxPool2d(kernel_size=4, stride=1) <NEW_LINE> self.fc_layer = nn.Linear(256, num_classes) <NEW_LINE> for m in self.modules(): <NEW_LINE> <INDENT> if isinstance(m, nn.Conv2d): <NEW_LINE> <INDENT> nn.init.kaiming_normal(m.weight.data, mode='fan_out') <NEW_LINE> <DEDENT> elif isinstance(m, nn.BatchNorm2d): <NEW_LINE> <INDENT> m.weight.data.fill_(1) <NEW_LINE> m.bias.data.zero_() <NEW_LINE> <DEDENT> elif isinstance(m, nn.Linear): <NEW_LINE> <INDENT> m.bias.data.zero_() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _make_block(self, block, duplicates, out_channels, stride=1): <NEW_LINE> <INDENT> downsample = None <NEW_LINE> if (stride != 1) or (self.in_channels != out_channels): <NEW_LINE> <INDENT> downsample = nn.Sequential( conv3x3(self.in_channels, out_channels, stride=stride), nn.BatchNorm2d(num_features=out_channels) ) <NEW_LINE> <DEDENT> layers = [] <NEW_LINE> layers.append( block(self.in_channels, out_channels, stride, downsample)) <NEW_LINE> self.in_channels = out_channels <NEW_LINE> for _ in range(1, duplicates): <NEW_LINE> <INDENT> layers.append(block(out_channels, out_channels)) <NEW_LINE> <DEDENT> return nn.Sequential(*layers) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> out = self.conv1(x) <NEW_LINE> out = self.bn(out) <NEW_LINE> out = self.relu(out) <NEW_LINE> out = self.dropout(out) <NEW_LINE> out = self.conv2_x(out) <NEW_LINE> out = self.conv3_x(out) <NEW_LINE> out = self.conv4_x(out) <NEW_LINE> out = self.conv5_x(out) <NEW_LINE> out = self.maxpool(out) <NEW_LINE> out = out.view(out.size(0), -1) <NEW_LINE> out = out.view(out.size(0), -1) <NEW_LINE> out = self.fc_layer(out) <NEW_LINE> return out
Residual Neural Network.
62598fa732920d7e50bc5f78
class Solution: <NEW_LINE> <INDENT> def subtractProductAndSum(self, n: int) -> int: <NEW_LINE> <INDENT> digits = [int(digit) for digit in str(n)] <NEW_LINE> product = reduce(lambda a, b: a * b, digits) <NEW_LINE> return product - sum(digits)
Runtime: 52 ms, faster than 5.52% of Python3 Memory Usage: 14.4 MB, less than 9.83% of Python3
62598fa74428ac0f6e658446
class VpnClientConfiguration(Model): <NEW_LINE> <INDENT> _attribute_map = { 'vpn_client_address_pool': {'key': 'vpnClientAddressPool', 'type': 'AddressSpace'}, 'vpn_client_root_certificates': {'key': 'vpnClientRootCertificates', 'type': '[VpnClientRootCertificate]'}, 'vpn_client_revoked_certificates': {'key': 'vpnClientRevokedCertificates', 'type': '[VpnClientRevokedCertificate]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(VpnClientConfiguration, self).__init__(**kwargs) <NEW_LINE> self.vpn_client_address_pool = kwargs.get('vpn_client_address_pool', None) <NEW_LINE> self.vpn_client_root_certificates = kwargs.get('vpn_client_root_certificates', None) <NEW_LINE> self.vpn_client_revoked_certificates = kwargs.get('vpn_client_revoked_certificates', None)
VpnClientConfiguration for P2S client. :param vpn_client_address_pool: Gets or sets the reference of the Address space resource which represents Address space for P2S VpnClient. :type vpn_client_address_pool: ~azure.mgmt.network.v2015_06_15.models.AddressSpace :param vpn_client_root_certificates: VpnClientRootCertificate for Virtual network gateway. :type vpn_client_root_certificates: list[~azure.mgmt.network.v2015_06_15.models.VpnClientRootCertificate] :param vpn_client_revoked_certificates: VpnClientRevokedCertificate for Virtual network gateway. :type vpn_client_revoked_certificates: list[~azure.mgmt.network.v2015_06_15.models.VpnClientRevokedCertificate]
62598fa71f037a2d8b9e400f
class Cart(object): <NEW_LINE> <INDENT> def __init__(self, request): <NEW_LINE> <INDENT> self.session = request.session <NEW_LINE> cart = self.session.get(settings.CART_SESSION_ID) <NEW_LINE> if not cart: <NEW_LINE> <INDENT> cart = self.session[settings.CART_SESSION_ID] = {} <NEW_LINE> <DEDENT> self.cart = cart <NEW_LINE> self.coupon_id = self.session.get("coupon_id") <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> product_ids = self.cart.keys() <NEW_LINE> products = Product.objects.filter(id__in=product_ids) <NEW_LINE> cart = self.cart.copy() <NEW_LINE> for product in products: <NEW_LINE> <INDENT> cart[str(product.id)]["product"] = product <NEW_LINE> <DEDENT> for item in cart.values(): <NEW_LINE> <INDENT> item["price"] = Decimal(item["price"]) <NEW_LINE> item["total_price"] = item["price"] * item["quantity"] <NEW_LINE> yield item <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return sum(item["quantity"] for item in self.cart.values()) <NEW_LINE> <DEDENT> def add(self, product, quantity=1, override_quantity=False): <NEW_LINE> <INDENT> product_id = str(product.id) <NEW_LINE> if product_id not in self.cart: <NEW_LINE> <INDENT> self.cart[product_id] = { "quantity": 0, "price": str(product.price), } <NEW_LINE> <DEDENT> if override_quantity: <NEW_LINE> <INDENT> self.cart[product_id]["quantity"] = quantity <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cart[product_id]["quantity"] += quantity <NEW_LINE> <DEDENT> self.save() <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> self.session.modified = True <NEW_LINE> <DEDENT> def remove(self, product): <NEW_LINE> <INDENT> product_id = str(product.id) <NEW_LINE> if product_id in self.cart: <NEW_LINE> <INDENT> del self.cart[product_id] <NEW_LINE> self.save() <NEW_LINE> <DEDENT> <DEDENT> def get_total_price(self): <NEW_LINE> <INDENT> return sum( Decimal(item["price"]) * item["quantity"] for item in self.cart.values() ) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> del self.session[settings.CART_SESSION_ID] <NEW_LINE> self.save() <NEW_LINE> <DEDENT> @property <NEW_LINE> def coupon(self): <NEW_LINE> <INDENT> if self.coupon_id: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Coupon.objects.get(id=self.coupon_id) <NEW_LINE> <DEDENT> except Coupon.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_discount(self): <NEW_LINE> <INDENT> if self.coupon: <NEW_LINE> <INDENT> return (self.coupon.discount / Decimal(100)) * self.get_total_price() <NEW_LINE> <DEDENT> return Decimal(0) <NEW_LINE> <DEDENT> def get_total_price_after_discount(self): <NEW_LINE> <INDENT> return self.get_total_price() - self.get_discount()
Manage the shopping cart
62598fa7fff4ab517ebcd708
@registry.register_class_label_modality("onehot_softmax_max_pooling") <NEW_LINE> class SoftmaxMaxPoolingClassLabelModality(OneHotClassLabelModality): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return "softmax_max_pooling_onehot_class_label_modality_%d_%d" % ( self._vocab_size, self._body_input_depth) <NEW_LINE> <DEDENT> def top(self, body_output, _): <NEW_LINE> <INDENT> with tf.variable_scope(self.name): <NEW_LINE> <INDENT> x = body_output <NEW_LINE> x = tf.reduce_max(x, axis=1, keepdims=True) <NEW_LINE> return tf.layers.dense(x, self._vocab_size)
Softmax cross-entropy applied on max-pooling over timesteps.
62598fa74e4d562566372348
class VSResume(CLIRunnable): <NEW_LINE> <INDENT> action = 'resume' <NEW_LINE> def execute(self, args): <NEW_LINE> <INDENT> virtual_guest = self.client['Virtual_Guest'] <NEW_LINE> vsi = VSManager(self.client) <NEW_LINE> vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') <NEW_LINE> virtual_guest.resume(id=vs_id)
usage: sl vs resume <identifier> [options] Resumes a paused virtual server
62598fa7a8ecb03325871133
class DiscussionSearchAlertTest(UniqueCourseTest): <NEW_LINE> <INDENT> SEARCHED_USERNAME = "gizmo" <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(DiscussionSearchAlertTest, self).setUp() <NEW_LINE> CourseFixture(**self.course_info).install() <NEW_LINE> self.searched_user_id = AutoAuthPage( self.browser, username=self.SEARCHED_USERNAME, course_id=self.course_id ).visit().get_user_id() <NEW_LINE> AutoAuthPage(self.browser, course_id=self.course_id).visit() <NEW_LINE> self.page = DiscussionTabHomePage(self.browser, self.course_id) <NEW_LINE> self.page.visit() <NEW_LINE> <DEDENT> def setup_corrected_text(self, text): <NEW_LINE> <INDENT> SearchResultFixture(SearchResult(corrected_text=text)).push() <NEW_LINE> <DEDENT> def check_search_alert_messages(self, expected): <NEW_LINE> <INDENT> actual = self.page.get_search_alert_messages() <NEW_LINE> self.assertTrue(all(map(lambda msg, sub: msg.lower().find(sub.lower()) >= 0, actual, expected))) <NEW_LINE> <DEDENT> def test_no_rewrite(self): <NEW_LINE> <INDENT> self.setup_corrected_text(None) <NEW_LINE> self.page.perform_search() <NEW_LINE> self.check_search_alert_messages(["no threads"]) <NEW_LINE> <DEDENT> def test_rewrite_dismiss(self): <NEW_LINE> <INDENT> self.setup_corrected_text("foo") <NEW_LINE> self.page.perform_search() <NEW_LINE> self.check_search_alert_messages(["foo"]) <NEW_LINE> self.page.dismiss_alert_message("foo") <NEW_LINE> self.check_search_alert_messages([]) <NEW_LINE> <DEDENT> def test_new_search(self): <NEW_LINE> <INDENT> self.setup_corrected_text("foo") <NEW_LINE> self.page.perform_search() <NEW_LINE> self.check_search_alert_messages(["foo"]) <NEW_LINE> self.setup_corrected_text("bar") <NEW_LINE> self.page.perform_search() <NEW_LINE> self.check_search_alert_messages(["bar"]) <NEW_LINE> self.setup_corrected_text(None) <NEW_LINE> self.page.perform_search() <NEW_LINE> self.check_search_alert_messages(["no threads"]) <NEW_LINE> <DEDENT> def test_rewrite_and_user(self): <NEW_LINE> <INDENT> self.setup_corrected_text("foo") <NEW_LINE> self.page.perform_search(self.SEARCHED_USERNAME) <NEW_LINE> self.check_search_alert_messages(["foo", self.SEARCHED_USERNAME]) <NEW_LINE> <DEDENT> def test_user_only(self): <NEW_LINE> <INDENT> self.setup_corrected_text(None) <NEW_LINE> self.page.perform_search(self.SEARCHED_USERNAME) <NEW_LINE> self.check_search_alert_messages(["no threads", self.SEARCHED_USERNAME]) <NEW_LINE> UserProfileViewFixture([]).push() <NEW_LINE> self.page.get_search_alert_links().first.click() <NEW_LINE> DiscussionUserProfilePage( self.browser, self.course_id, self.searched_user_id, self.SEARCHED_USERNAME ).wait_for_page()
Tests for spawning and dismissing alerts related to user search actions and their results.
62598fa756ac1b37e6302110
@register_workload('GLOBETRAFF') <NEW_LINE> class GlobetraffWorkload(object): <NEW_LINE> <INDENT> def __init__(self, topology, reqs_file, contents_file, beta=0, **kwargs): <NEW_LINE> <INDENT> if beta < 0: <NEW_LINE> <INDENT> raise ValueError('beta must be positive') <NEW_LINE> <DEDENT> self.receivers = [v for v in topology.nodes_iter() if topology.node[v]['stack'][0] == 'receiver'] <NEW_LINE> self.n_contents = 0 <NEW_LINE> with open(contents_file, 'r') as f: <NEW_LINE> <INDENT> reader = csv.reader(f, delimiter='\t') <NEW_LINE> for content, popularity, size, app_type in reader: <NEW_LINE> <INDENT> self.n_contents = max(self.n_contents, content) <NEW_LINE> <DEDENT> <DEDENT> self.n_contents += 1 <NEW_LINE> self.contents = range(self.n_contents) <NEW_LINE> self.request_file = reqs_file <NEW_LINE> self.beta = beta <NEW_LINE> if beta != 0: <NEW_LINE> <INDENT> degree = nx.degree(self.topology) <NEW_LINE> self.receivers = sorted(self.receivers, key=lambda x: degree[iter(topology.edge[x]).next()], reverse=True) <NEW_LINE> self.receiver_dist = TruncatedZipfDist(beta, len(self.receivers)) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> with open(self.request_file, 'r') as f: <NEW_LINE> <INDENT> reader = csv.reader(f, delimiter='\t') <NEW_LINE> for timestamp, content, size in reader: <NEW_LINE> <INDENT> if self.beta == 0: <NEW_LINE> <INDENT> receiver = random.choice(self.receivers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> receiver = self.receivers[self.receiver_dist.rv() - 1] <NEW_LINE> <DEDENT> event = {'receiver': receiver, 'content': content, 'size': size} <NEW_LINE> yield (timestamp, event) <NEW_LINE> <DEDENT> <DEDENT> raise StopIteration()
Parse requests from GlobeTraff workload generator All requests are mapped to receivers uniformly unless a positive *beta* parameter is specified. If a *beta* parameter is specified, then receivers issue requests at different rates. The algorithm used to determine the requests rates for each receiver is the following: * All receiver are sorted in decreasing order of degree of the PoP they are attached to. This assumes that all receivers have degree = 1 and are attached to a node with degree > 1 * Rates are then assigned following a Zipf distribution of coefficient beta where nodes with higher-degree PoPs have a higher request rate Parameters ---------- topology : fnss.Topology The topology to which the workload refers reqs_file : str The GlobeTraff request file contents_file : str The GlobeTraff content file beta : float, optional Spatial skewness of requests rates Returns ------- events : iterator Iterator of events. Each event is a 2-tuple where the first element is the timestamp at which the event occurs and the second element is a dictionary of event attributes.
62598fa7925a0f43d25e7f62
class Game(AbstractGame): <NEW_LINE> <INDENT> def __init__(self, seed=None): <NEW_LINE> <INDENT> self.env = Klop(6) <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> observation, reward, done = self.env.step(action) <NEW_LINE> return observation, reward, done <NEW_LINE> <DEDENT> def to_play(self): <NEW_LINE> <INDENT> return self.env.to_play() <NEW_LINE> <DEDENT> def legal_actions(self): <NEW_LINE> <INDENT> return self.env.legal_actions() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return self.env.reset() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> self.env.render() <NEW_LINE> input("Press enter to take a step ") <NEW_LINE> <DEDENT> def human_to_action(self): <NEW_LINE> <INDENT> a = input('Your move:') <NEW_LINE> x, y = (5 - int(a[0])), (5-int(a[1])) <NEW_LINE> return baseconvert.base(int(str(x)+str(y)), 6, 10, string=True) <NEW_LINE> <DEDENT> def action_to_string(self, action): <NEW_LINE> <INDENT> return baseconvert.base(action, 10, 6, string=True) <NEW_LINE> <DEDENT> def random_agent(self): <NEW_LINE> <INDENT> return self.env.random_agent()
Game wrapper.
62598fa776e4537e8c3ef4d1
class PaymentCreate(SuccessMessageMixin, PaymentFormViewMixin, ModelFormWidgetMixin, CreateView): <NEW_LINE> <INDENT> success_message = "Payment was created successfully" <NEW_LINE> success_url = reverse_lazy('finances:payments_list')
Payment create view
62598fa7baa26c4b54d4f1d4
class FileServer: <NEW_LINE> <INDENT> def receive_file(self, file, folder): <NEW_LINE> <INDENT> print('FS: Opening sever: localhost port: 7100') <NEW_LINE> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.bind(('localhost', 7100)) <NEW_LINE> s.listen(5) <NEW_LINE> print('FS: Waiting for connection') <NEW_LINE> client, address = s.accept() <NEW_LINE> print('FS: Connect to: ', address) <NEW_LINE> with open(os.path.join(folder, file), 'wb') as f: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> data = client.recv(1024) <NEW_LINE> if not data: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> f.write(data) <NEW_LINE> <DEDENT> <DEDENT> f.close() <NEW_LINE> print('FS: File saved:', file) <NEW_LINE> client.close() <NEW_LINE> print('FS: Closed')
FileServer class: A small self contained class that creates a independent socket purely for receiving a file sent from a client connection. Once the file has been received the socket is closed off. Uses a hardcoded server and port.
62598fa7d486a94d0ba2bef2
@dataclass <NEW_LINE> class Side: <NEW_LINE> <INDENT> isInBed: bool <NEW_LINE> alertDetailedMessage: str <NEW_LINE> sleepNumber: int <NEW_LINE> alertId: int <NEW_LINE> lastLink: str <NEW_LINE> pressure: int <NEW_LINE> side: str <NEW_LINE> sleeper: Sleeper <NEW_LINE> @staticmethod <NEW_LINE> def from_dict(data: Dict[str, Any], left_or_right: str): <NEW_LINE> <INDENT> return Side( isInBed = data["isInBed"], alertDetailedMessage = data["alertDetailedMessage"], sleepNumber = data["sleepNumber"], alertId = data["alertId"], lastLink = data["lastLink"], pressure = data["pressure"], side = left_or_right, sleeper = None )
Return a side status
62598fa710dbd63aa1c70ad7
class DescribeAssetImageListExportRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ExportField = None <NEW_LINE> self.Limit = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Filters = None <NEW_LINE> self.By = None <NEW_LINE> self.Order = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ExportField = params.get("ExportField") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> if params.get("Filters") is not None: <NEW_LINE> <INDENT> self.Filters = [] <NEW_LINE> for item in params.get("Filters"): <NEW_LINE> <INDENT> obj = AssetFilters() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Filters.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.By = params.get("By") <NEW_LINE> self.Order = params.get("Order") <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))
DescribeAssetImageListExport请求参数结构体
62598fa78e71fb1e983bb9d7
class UsernameWithoutPassword(LoginError): <NEW_LINE> <INDENT> pass
A user-name was provided without a corresponding password.
62598fa766673b3332c302ef
class Major: <NEW_LINE> <INDENT> def __init__(self,major,flag,course): <NEW_LINE> <INDENT> self.major = major <NEW_LINE> self.flag =flag <NEW_LINE> self.course = course
Major class to hold details of required and elective course for each major
62598fa701c39578d7f12ca4
class Shell_Restoring_Aux (rubber.depend.Shell): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def initialize (cls, document): <NEW_LINE> <INDENT> cls.aux = document.basename (with_suffix = ".aux") <NEW_LINE> cls.bak = document.basename (with_suffix = ".aux.tmp") <NEW_LINE> document.add_product (cls.bak) <NEW_LINE> <DEDENT> def run (self): <NEW_LINE> <INDENT> source = self.sources [0] <NEW_LINE> if not os.path.exists (source): <NEW_LINE> <INDENT> msg.info(_("{} not yet generated").format (msg.simplify (source)), pkg="asymptote") <NEW_LINE> return True <NEW_LINE> <DEDENT> os.rename (self.aux, self.bak) <NEW_LINE> msg.log (_ ("saving {} to {}").format (msg.simplify (self.aux), msg.simplify (self.bak)), pkg="asymptote") <NEW_LINE> ret = super (Shell_Restoring_Aux, self).run () <NEW_LINE> msg.log (_ ("restoring {} to {}").format (msg.simplify (self.aux), msg.simplify (self.bak)), pkg="asymptote") <NEW_LINE> os.rename (self.bak, self.aux) <NEW_LINE> return ret
This class replaces Shell because of a bug in asymptote. Every run of /usr/bin/asy flushes the .aux file.
62598fa75fc7496912d48216
class MySqlClientPool(ReusabletPool): <NEW_LINE> <INDENT> def _create_object(self): <NEW_LINE> <INDENT> return MySqlClient()
Mysql连接池
62598fa77d847024c075c2e9
class UnknownVolumeTypeException(DbcentralException): <NEW_LINE> <INDENT> def __init__(self, volume_type): <NEW_LINE> <INDENT> self.volumetype = volume_type <NEW_LINE> msg = 'Volume type "%s" in cluster database not understood' % volume_type <NEW_LINE> DbcentralException.__init__(self, msg=msg) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "UnknownVolumeTypeException(volume_type=%r)" % self.volumetype
The Dbcentral cluster database contains an unknown Volume type.
62598fa7e5267d203ee6b830
class CompressedStaticFilesMixin(object): <NEW_LINE> <INDENT> def post_process(self, *args, **kwargs): <NEW_LINE> <INDENT> super_post_process = getattr( super(CompressedStaticFilesMixin, self), 'post_process', self.fallback_post_process) <NEW_LINE> files = super_post_process(*args, **kwargs) <NEW_LINE> if not kwargs.get('dry_run'): <NEW_LINE> <INDENT> files = self.post_process_with_compression(files) <NEW_LINE> <DEDENT> return files <NEW_LINE> <DEDENT> def fallback_post_process(self, paths, dry_run=False, **options): <NEW_LINE> <INDENT> if not dry_run: <NEW_LINE> <INDENT> for path in paths: <NEW_LINE> <INDENT> yield path, None, False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def post_process_with_compression(self, files): <NEW_LINE> <INDENT> extensions = getattr(settings, 'WHITENOISE_SKIP_COMPRESS_EXTENSIONS', None) <NEW_LINE> compressor = Compressor(extensions=extensions, quiet=True) <NEW_LINE> for name, hashed_name, processed in files: <NEW_LINE> <INDENT> yield name, hashed_name, processed <NEW_LINE> if isinstance(processed, Exception): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> unique_names = set(filter(None, [name, hashed_name])) <NEW_LINE> for name in unique_names: <NEW_LINE> <INDENT> if compressor.should_compress(name): <NEW_LINE> <INDENT> path = self.path(name) <NEW_LINE> prefix_len = len(path) - len(name) <NEW_LINE> for compressed_path in compressor.compress(path): <NEW_LINE> <INDENT> compressed_name = compressed_path[prefix_len:] <NEW_LINE> yield name, compressed_name, True
Wraps a StaticFilesStorage instance to compress output files
62598fa74428ac0f6e658447
class visualizer: <NEW_LINE> <INDENT> def draw_it(self,**args): <NEW_LINE> <INDENT> set_figsize = 7 <NEW_LINE> if 'set_figsize' in args: <NEW_LINE> <INDENT> set_figsize = args['set_figsize'] <NEW_LINE> <DEDENT> set_axis = 'on' <NEW_LINE> if 'set_axis' in args: <NEW_LINE> <INDENT> set_axis = args['set_axis'] <NEW_LINE> <DEDENT> set_title = '' <NEW_LINE> if 'set_title' in args: <NEW_LINE> <INDENT> set_title = args['set_title'] <NEW_LINE> <DEDENT> horiz_1_label = '' <NEW_LINE> if 'horiz_1_label' in args: <NEW_LINE> <INDENT> horiz_1_label = args['horiz_1_label'] <NEW_LINE> <DEDENT> horiz_2_label = '' <NEW_LINE> if 'horiz_2_label' in args: <NEW_LINE> <INDENT> horiz_2_label = args['horiz_2_label'] <NEW_LINE> <DEDENT> vert_label = '' <NEW_LINE> if 'vert_label' in args: <NEW_LINE> <INDENT> vert_label = args['vert_label'] <NEW_LINE> <DEDENT> input_range = np.linspace(-3,3,100) <NEW_LINE> if 'input_range' in args: <NEW_LINE> <INDENT> input_range = args['input_range'] <NEW_LINE> <DEDENT> view = [20,50] <NEW_LINE> if 'view' in args: <NEW_LINE> <INDENT> view = args['view'] <NEW_LINE> <DEDENT> num_slides = 100 <NEW_LINE> if 'num_slides' in args: <NEW_LINE> <INDENT> num_frames = args['num_slides'] <NEW_LINE> <DEDENT> alpha_values = np.linspace(-2,2,num_frames) <NEW_LINE> fig = plt.figure(figsize = (set_figsize,set_figsize)) <NEW_LINE> artist = fig <NEW_LINE> ax = fig.add_subplot(111, projection='3d') <NEW_LINE> def animate(k): <NEW_LINE> <INDENT> ax.cla() <NEW_LINE> alpha = alpha_values[k] <NEW_LINE> g = lambda w: w[0]**2 + alpha*w[1]**2 <NEW_LINE> w1_vals,w2_vals = np.meshgrid(input_range,input_range) <NEW_LINE> w1_vals.shape = (len(input_range)**2,1) <NEW_LINE> w2_vals.shape = (len(input_range)**2,1) <NEW_LINE> g_vals = g([w1_vals,w2_vals]) <NEW_LINE> w1_vals.shape = (len(input_range),len(input_range)) <NEW_LINE> w2_vals.shape = (len(input_range),len(input_range)) <NEW_LINE> g_vals.shape = (len(input_range),len(input_range)) <NEW_LINE> g_range = np.amax(g_vals) - np.amin(g_vals) <NEW_LINE> ggap = g_range*0.5 <NEW_LINE> ax.plot_surface(w1_vals,w2_vals,g_vals,alpha = 0.1,color = 'k',rstride=15, cstride=15,linewidth=2,edgecolor = 'k') <NEW_LINE> ax.set_title(set_title,fontsize = 15) <NEW_LINE> ax.set_xlabel(horiz_1_label,fontsize = 15) <NEW_LINE> ax.set_ylabel(horiz_2_label,fontsize = 15) <NEW_LINE> ax.set_zlabel(vert_label,fontsize = 15) <NEW_LINE> ax.view_init(view[0],view[1]) <NEW_LINE> ax.axis(set_axis) <NEW_LINE> return artist, <NEW_LINE> <DEDENT> anim = animation.FuncAnimation(fig, animate ,frames=len(alpha_values), interval=len(alpha_values), blit=True) <NEW_LINE> return(anim)
Draw 3d quadratic ranging from convex
62598fa71f037a2d8b9e4011
class Meta: <NEW_LINE> <INDENT> abstract = True
Meta class.
62598fa73cc13d1c6d465691
class Task(): <NEW_LINE> <INDENT> def __init__(self, init_pose=None, init_velocities=None, init_angle_velocities=None, runtime=5., target_pos=None): <NEW_LINE> <INDENT> self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime) <NEW_LINE> self.action_repeat = 3 <NEW_LINE> self.state_size = self.action_repeat * 6 <NEW_LINE> self.action_low = 0 <NEW_LINE> self.action_high = 900 <NEW_LINE> self.action_size = 4 <NEW_LINE> self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.]) <NEW_LINE> <DEDENT> def get_reward(self): <NEW_LINE> <INDENT> reward = 1. - .2*(abs(self.sim.pose[:3] - self.target_pos)).sum() <NEW_LINE> if reward>1: <NEW_LINE> <INDENT> reward = 1 <NEW_LINE> <DEDENT> if reward<-1: <NEW_LINE> <INDENT> reward = -1 <NEW_LINE> <DEDENT> return reward <NEW_LINE> <DEDENT> def step(self, rotor_speeds): <NEW_LINE> <INDENT> reward = 0 <NEW_LINE> pose_all = [] <NEW_LINE> for _ in range(self.action_repeat): <NEW_LINE> <INDENT> done = self.sim.next_timestep(rotor_speeds) <NEW_LINE> reward += self.get_reward() <NEW_LINE> pose_all.append(self.sim.pose) <NEW_LINE> <DEDENT> next_state = np.concatenate(pose_all) <NEW_LINE> return next_state, reward, done <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.sim.reset() <NEW_LINE> state = np.concatenate([self.sim.pose] * self.action_repeat) <NEW_LINE> return state
Task (environment) that defines the goal and provides feedback to the agent.
62598fa78e7ae83300ee8fc7
class PackagePluginManager(PluginManager): <NEW_LINE> <INDENT> PLUGIN_MANIFEST = 'plugins.py' <NEW_LINE> plugin_path = List(Directory) <NEW_LINE> @on_trait_change('plugin_path[]') <NEW_LINE> def _plugin_path_changed(self, obj, trait_name, removed, added): <NEW_LINE> <INDENT> self._update_sys_dot_path(removed, added) <NEW_LINE> self.reset_traits(['_plugins']) <NEW_LINE> <DEDENT> def __plugins_default(self): <NEW_LINE> <INDENT> plugins = [ plugin for plugin in self._harvest_plugins_in_packages() if self._include_plugin(plugin.id) ] <NEW_LINE> logger.debug('package plugin manager found plugins <%s>', plugins) <NEW_LINE> return plugins <NEW_LINE> <DEDENT> def _get_plugins_module(self, package_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module = __import__(package_name + '.plugins', fromlist=['plugins']) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> module = None <NEW_LINE> <DEDENT> return module <NEW_LINE> <DEDENT> def _harvest_plugins_in_package(self, package_name, package_dirname): <NEW_LINE> <INDENT> plugins_module = self._get_plugins_module(package_name) <NEW_LINE> if plugins_module is not None: <NEW_LINE> <INDENT> factory = getattr(plugins_module, 'get_plugins', None) <NEW_LINE> if factory is not None: <NEW_LINE> <INDENT> plugins = factory() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> plugins = [] <NEW_LINE> for child in File(package_dirname).children: <NEW_LINE> <INDENT> if child.ext == '.py' and child.name.endswith('_plugin'): <NEW_LINE> <INDENT> module = __import__( package_name + '.' + child.name, fromlist=[child.name] ) <NEW_LINE> atoms = child.name.split('_') <NEW_LINE> capitalized = [atom.capitalize() for atom in atoms] <NEW_LINE> factory_name = ''.join(capitalized) <NEW_LINE> factory = getattr(module, factory_name, None) <NEW_LINE> if factory is not None: <NEW_LINE> <INDENT> plugins.append(factory()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return plugins <NEW_LINE> <DEDENT> def _harvest_plugins_in_packages(self): <NEW_LINE> <INDENT> plugins = [] <NEW_LINE> for dirname in self.plugin_path: <NEW_LINE> <INDENT> for child in File(dirname).children: <NEW_LINE> <INDENT> if child.is_package: <NEW_LINE> <INDENT> plugins.extend( self._harvest_plugins_in_package( child.name, child.path ) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return plugins <NEW_LINE> <DEDENT> def _update_sys_dot_path(self, removed, added): <NEW_LINE> <INDENT> for dirname in removed: <NEW_LINE> <INDENT> if dirname in sys.path: <NEW_LINE> <INDENT> sys.path.remove(dirname) <NEW_LINE> <DEDENT> <DEDENT> for dirname in added: <NEW_LINE> <INDENT> if dirname not in sys.path: <NEW_LINE> <INDENT> sys.path.append(dirname)
A plugin manager that finds plugins in packages on the 'plugin_path'. All items in 'plugin_path' are directory names and they are all added to 'sys.path' (if not already present). Each directory is then searched for plugins as follows:- a) If the package contains a 'plugins.py' module, then we import it and look for a callable 'get_plugins' that takes no arguments and returns a list of plugins (i.e. instances that implement 'IPlugin'!). b) If the package contains any modules named in the form 'xxx_plugin.py' then the module is imported and if it contains a callable 'XXXPlugin' it is called with no arguments and it must return a single plugin.
62598fa74e4d56256637234a
class BinRequestModel(Model): <NEW_LINE> <INDENT> _validation = { 'card_number': {'required': True}, } <NEW_LINE> _attribute_map = { 'card_number': {'key': 'cardNumber', 'type': 'str'}, } <NEW_LINE> def __init__(self, card_number): <NEW_LINE> <INDENT> super(BinRequestModel, self).__init__() <NEW_LINE> self.card_number = card_number
The request model sent by the client for retrieving credit card bin information. :param card_number: The number on the credit card. :type card_number: str
62598fa77047854f4633f2ff
class _DendrogramNode(object): <NEW_LINE> <INDENT> def __init__(self, value, *children): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> self._children = children <NEW_LINE> <DEDENT> def leaves(self, values=True): <NEW_LINE> <INDENT> if self._children: <NEW_LINE> <INDENT> leaves = [] <NEW_LINE> for child in self._children: <NEW_LINE> <INDENT> leaves.extend(child.leaves(values)) <NEW_LINE> <DEDENT> return leaves <NEW_LINE> <DEDENT> elif values: <NEW_LINE> <INDENT> return [self._value] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self] <NEW_LINE> <DEDENT> <DEDENT> def groups(self, n): <NEW_LINE> <INDENT> queue = [(self._value, self)] <NEW_LINE> while len(queue) < n: <NEW_LINE> <INDENT> priority, node = queue.pop() <NEW_LINE> if not node._children: <NEW_LINE> <INDENT> queue.push((priority, node)) <NEW_LINE> break <NEW_LINE> <DEDENT> for child in node._children: <NEW_LINE> <INDENT> if child._children: <NEW_LINE> <INDENT> queue.append((child._value, child)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queue.append((0, child)) <NEW_LINE> <DEDENT> <DEDENT> queue.sort() <NEW_LINE> <DEDENT> groups = [] <NEW_LINE> for priority, node in queue: <NEW_LINE> <INDENT> groups.append(node.leaves()) <NEW_LINE> <DEDENT> return groups <NEW_LINE> <DEDENT> def __lt__(self, comparator): <NEW_LINE> <INDENT> return cosine_distance(self._value, comparator._value) < 0
Tree node of a dendrogram.
62598fa738b623060ffa8fbd
class AllRecentActions(modules.DashboardModule): <NEW_LINE> <INDENT> title = _('All Recent Actions') <NEW_LINE> template = 'grappelli/dashboard/modules/recent_actions_all.html' <NEW_LINE> limit = 10 <NEW_LINE> include_list = None <NEW_LINE> exclude_list = None <NEW_LINE> def __init__(self, title=None, limit=10, include_list=None, exclude_list=None, **kwargs): <NEW_LINE> <INDENT> self.include_list = include_list or [] <NEW_LINE> self.exclude_list = exclude_list or [] <NEW_LINE> kwargs.update({'limit': limit}) <NEW_LINE> super(AllRecentActions, self).__init__(title, **kwargs) <NEW_LINE> <DEDENT> def init_with_context(self, context): <NEW_LINE> <INDENT> if self._initialized: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> from django.db.models import Q <NEW_LINE> from django.contrib.admin.models import LogEntry <NEW_LINE> def get_qset(list): <NEW_LINE> <INDENT> qset = None <NEW_LINE> for contenttype in list: <NEW_LINE> <INDENT> if isinstance(contenttype, ContentType): <NEW_LINE> <INDENT> current_qset = Q(content_type__id=contenttype.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> app_label, model = contenttype.split('.') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError( 'Invalid contenttype: "%s"' % contenttype) <NEW_LINE> <DEDENT> current_qset = Q( content_type__app_label=app_label, content_type__model=model ) <NEW_LINE> <DEDENT> if qset is None: <NEW_LINE> <INDENT> qset = current_qset <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qset = qset | current_qset <NEW_LINE> <DEDENT> <DEDENT> return qset <NEW_LINE> <DEDENT> qs = LogEntry.objects.all() <NEW_LINE> if self.include_list: <NEW_LINE> <INDENT> qs = qs.filter(get_qset(self.include_list)) <NEW_LINE> <DEDENT> if self.exclude_list: <NEW_LINE> <INDENT> qs = qs.exclude(get_qset(self.exclude_list)) <NEW_LINE> <DEDENT> self.children = qs.select_related('content_type', 'user')[:self.limit] <NEW_LINE> self._initialized = True
Module that lists the recent actions for the current user.
62598fa78da39b475be03108
@skipIf(NO_MOCK, NO_MOCK_REASON) <NEW_LINE> class EventTestCase(TestCase, LoaderModuleMockMixin): <NEW_LINE> <INDENT> def setup_loader_modules(self): <NEW_LINE> <INDENT> return { event: { '__opts__': { 'id': 'id', 'sock_dir': TMP, 'transport': 'zeromq' } } } <NEW_LINE> <DEDENT> def test_fire_master(self): <NEW_LINE> <INDENT> with patch('salt.crypt.SAuth') as salt_crypt_sauth, patch('salt.transport.client.ReqChannel.factory') as salt_transport_channel_factory: <NEW_LINE> <INDENT> preload = {'id': 'id', 'tag': 'tag', 'data': 'data', 'tok': 'salt', 'cmd': '_minion_event'} <NEW_LINE> with patch.dict(event.__opts__, {'transport': 'raet', 'local': False}): <NEW_LINE> <INDENT> with patch.object(salt_transport_channel_factory, 'send', return_value=None): <NEW_LINE> <INDENT> self.assertTrue(event.fire_master('data', 'tag')) <NEW_LINE> <DEDENT> <DEDENT> with patch.dict(event.__opts__, {'transport': 'A', 'master_uri': 'localhost', 'local': False}): <NEW_LINE> <INDENT> with patch.object(salt_crypt_sauth, 'gen_token', return_value='tok'): <NEW_LINE> <INDENT> with patch.object(salt_transport_channel_factory, 'send', return_value=None): <NEW_LINE> <INDENT> self.assertTrue(event.fire_master('data', 'tag', preload)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with patch.dict(event.__opts__, {'transport': 'A', 'local': False}): <NEW_LINE> <INDENT> with patch.object(salt.utils.event.MinionEvent, 'fire_event', side_effect=Exception('foo')): <NEW_LINE> <INDENT> self.assertFalse(event.fire_master('data', 'tag')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def test_fire(self): <NEW_LINE> <INDENT> with patch('salt.utils.event') as salt_utils_event: <NEW_LINE> <INDENT> with patch.object(salt_utils_event, 'get_event') as mock: <NEW_LINE> <INDENT> mock.fire_event = MagicMock(return_value=True) <NEW_LINE> self.assertTrue(event.fire('data', 'tag')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_send(self): <NEW_LINE> <INDENT> with patch.object(event, 'fire_master', return_value='B'): <NEW_LINE> <INDENT> self.assertEqual(event.send('tag'), 'B')
Test cases for salt.modules.event
62598fa75fdd1c0f98e5debe
class MiniPost: <NEW_LINE> <INDENT> def __init__(self, in_post_id, in_title, in_date): <NEW_LINE> <INDENT> self.post_id = in_post_id <NEW_LINE> self.title = in_title <NEW_LINE> self.date = in_date
A minipost contains just the title, numerical selector, and post_id
62598fa8be8e80087fbbef88
class TestIsPrime(unittest.TestCase): <NEW_LINE> <INDENT> def test_is_prime(self): <NEW_LINE> <INDENT> primes = [n for n in range(20) if is_prime(n)] <NEW_LINE> assert_that([2, 3, 5, 7, 11, 13, 17, 19], equal_to(primes))
Testing of is_prime function.
62598fa8f9cc0f698b1c525b
class Multi(Field): <NEW_LINE> <INDENT> def __init__(self, keys: t.Sequence[str], **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.keys: t.Sequence[str] = keys <NEW_LINE> <DEDENT> def get_value(self, message: Message) -> JSONValue: <NEW_LINE> <INDENT> values = [] <NEW_LINE> for key in self.keys: <NEW_LINE> <INDENT> values.append(message.get(key)) <NEW_LINE> <DEDENT> return values
Returns a JSON array made of multiple JSON values. Retrieves the each JSON value at each given key and builds a JSON array from them as the field value. Parameters ---------- keys: Sequence[str] Sequence of JSON keys to retrieve.
62598fa8e5267d203ee6b831
class ShaderPart(object): <NEW_LINE> <INDENT> def __init__(self, name, variables="", vertex_functions="", fragment_functions="", **kwargs): <NEW_LINE> <INDENT> if not re.match(r'^[\w\.]+$', name): <NEW_LINE> <INDENT> raise Exception("The shader name {!r} contains an invalid character. Shader names are limited to ASCII alphanumeric characters, _, and .".format(name)) <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> shader_part[name] = self <NEW_LINE> self.vertex_functions = vertex_functions <NEW_LINE> self.fragment_functions = fragment_functions <NEW_LINE> self.vertex_parts = [ ] <NEW_LINE> self.fragment_parts = [ ] <NEW_LINE> self.vertex_variables = set() <NEW_LINE> self.fragment_variables = set() <NEW_LINE> vertex_used = set() <NEW_LINE> fragment_used = set() <NEW_LINE> for k, v in kwargs.items(): <NEW_LINE> <INDENT> shader, _, priority = k.partition('_') <NEW_LINE> if not priority: <NEW_LINE> <INDENT> shader = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> priority = int(priority) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> shader = None <NEW_LINE> <DEDENT> if shader == "vertex": <NEW_LINE> <INDENT> parts = self.vertex_parts <NEW_LINE> used = vertex_used <NEW_LINE> <DEDENT> elif shader == "fragment": <NEW_LINE> <INDENT> parts = self.fragment_parts <NEW_LINE> used = fragment_used <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Keyword arguments to ShaderPart must be of the form {vertex,fragment}_{priority}.") <NEW_LINE> <DEDENT> parts.append((priority, v)) <NEW_LINE> for m in re.finditer(r'\b\w+\b', v): <NEW_LINE> <INDENT> used.add(m.group(0)) <NEW_LINE> <DEDENT> <DEDENT> for l in variables.split("\n"): <NEW_LINE> <INDENT> l = l.strip(' ;') <NEW_LINE> a = l.split() <NEW_LINE> if not a: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if len(a) != 3: <NEW_LINE> <INDENT> print("Unknown shader variable line {!r}. Only the form '{{uniform,attribute,vertex}} {{type}} {{name}} is allowed.".format(l)) <NEW_LINE> <DEDENT> a = tuple(a) <NEW_LINE> kind = a[0] <NEW_LINE> name = a[2] <NEW_LINE> if name in vertex_used: <NEW_LINE> <INDENT> self.vertex_variables.add(a) <NEW_LINE> <DEDENT> if name in fragment_used: <NEW_LINE> <INDENT> self.fragment_variables.add(a) <NEW_LINE> <DEDENT> if kind == "uniform": <NEW_LINE> <INDENT> renpy.display.transform.add_uniform(name)
Arguments are as for register_shader.
62598fa89c8ee82313040103
class G15CalendarPreferences(g15accounts.G15AccountPreferences): <NEW_LINE> <INDENT> def __init__(self, parent, gconf_client, gconf_key): <NEW_LINE> <INDENT> g15accounts.G15AccountPreferences.__init__(self, parent, gconf_client, gconf_key, CONFIG_PATH, CONFIG_ITEM_NAME) <NEW_LINE> <DEDENT> def get_account_types(self): <NEW_LINE> <INDENT> return get_available_backends() <NEW_LINE> <DEDENT> def get_account_type_name(self, account_type): <NEW_LINE> <INDENT> return _(account_type) <NEW_LINE> <DEDENT> def create_options_for_type(self, account, account_type): <NEW_LINE> <INDENT> backend = get_backend(account.type) <NEW_LINE> if backend is None: <NEW_LINE> <INDENT> logger.warning("No backend for account type %s", account_type) <NEW_LINE> return None <NEW_LINE> <DEDENT> return backend.create_options(account, self) <NEW_LINE> <DEDENT> def create_general_options(self): <NEW_LINE> <INDENT> widget_tree = gtk.Builder() <NEW_LINE> widget_tree.add_from_file(os.path.join(os.path.dirname(__file__), "cal.ui")) <NEW_LINE> g15uigconf.configure_checkbox_from_gconf(self.gconf_client, "%s/twenty_four_hour_times" % self.gconf_key, "TwentyFourHourTimes", True, widget_tree) <NEW_LINE> return widget_tree.get_object("OptionPanel")
Configuration UI
62598fa8b7558d5895463555
class TimeRecorder(): <NEW_LINE> <INDENT> def __init__(self, decay=0.9995, max_seconds=10): <NEW_LINE> <INDENT> self.moving_average = ThreadSafeMovingAverageRecorder(decay) <NEW_LINE> self.max_seconds = max_seconds <NEW_LINE> self.started = False <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def time(self): <NEW_LINE> <INDENT> pre_time = time.time() <NEW_LINE> yield None <NEW_LINE> post_time = time.time() <NEW_LINE> interval = min(self.max_seconds, post_time - pre_time) <NEW_LINE> self.moving_average.add_value(interval) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.started: <NEW_LINE> <INDENT> raise RuntimeError('Starting a started timer') <NEW_LINE> <DEDENT> self.pre_time = time.time() <NEW_LINE> self.started = True <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if not self.started: <NEW_LINE> <INDENT> raise RuntimeError('Stopping a timer that is not started') <NEW_LINE> <DEDENT> self.post_time = time.time() <NEW_LINE> self.started = False <NEW_LINE> interval = min(self.max_seconds, self.post_time - self.pre_time) <NEW_LINE> self.moving_average.add_value(interval) <NEW_LINE> <DEDENT> def lap(self): <NEW_LINE> <INDENT> if not self.started: <NEW_LINE> <INDENT> raise RuntimeError('Stopping a timer that is not started') <NEW_LINE> <DEDENT> post_time = time.time() <NEW_LINE> interval = min(self.max_seconds, post_time - self.pre_time) <NEW_LINE> self.moving_average.add_value(interval) <NEW_LINE> self.pre_time = post_time <NEW_LINE> <DEDENT> @property <NEW_LINE> def avg(self): <NEW_LINE> <INDENT> return self.moving_average.cur_value()
Records average of whatever context block it is recording Don't call time in two threads
62598fa82c8b7c6e89bd36eb
class LibraryCache(Cache): <NEW_LINE> <INDENT> _impl_class = CustomCodeLibraryCacheImpl
Implements Cache that saves and loads CodeLibrary objects for additional feature for the specified python function.
62598fa863d6d428bbee26d8
class GridWorldState(object): <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self._is_terminal = False <NEW_LINE> self.data = [x, y] <NEW_LINE> self.x = round(x, 5) <NEW_LINE> self.y = round(y, 5) <NEW_LINE> <DEDENT> def is_terminal(self): <NEW_LINE> <INDENT> return self._is_terminal <NEW_LINE> <DEDENT> def set_terminal(self, is_term = True): <NEW_LINE> <INDENT> self._is_terminal = is_term <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(tuple(self.data)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "(" + str(self.x) + "," + str(self.y) + ")" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, GridWorldState) and self.x == other.x and self.y == other.y
Class for Grid World States
62598fa8a8370b77170f0301
class ConferencePageMainRegistrationLinks(Orderable, AbstractButton): <NEW_LINE> <INDENT> page = ParentalKey('conferences.ConferencePage', related_name='main_registration') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Main Registration Link' <NEW_LINE> verbose_name_plural = 'Main Registration Links' <NEW_LINE> ordering = ['sort_order']
Creates a through table for the main registration buttons on conference pages.
62598fa857b8e32f525080ae
class Broadcast(Action): <NEW_LINE> <INDENT> def __init__(self, broadcast): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.priority = 100 <NEW_LINE> self.broadcast = broadcast
Encapsulation of a broadcast message
62598fa86aa9bd52df0d4def
class DictObjectSet(set, MutableSet, SelfObjectifyMixin): <NEW_LINE> <INDENT> def __init__(self, iterable=None): <NEW_LINE> <INDENT> super(DictObjectSet, self).__init__(DictObjectSet.iterator_objectified(iterable)) <NEW_LINE> <DEDENT> def add(self, element): <NEW_LINE> <INDENT> super(DictObjectSet, self).add(DictObject.objectify(element)) <NEW_LINE> <DEDENT> def update(self, *values): <NEW_LINE> <INDENT> super(DictObjectSet, self).update(*DictObject.objectify(values))
List which wraps the builtin set, to automatically objectify any dicts/lists in this set. Examples: >>> s = {"hi", 1, True, None} >>> dict_s = DictObjectSet(s) >>> dict_s == s True >>> dict_s.update([False, 1,2,3]) >>> dict_s == {False, True, 2, 3, None, 'hi'} True
62598fa8a17c0f6771d5c15b
class DeterministicModulePolicy(nn.Module, Policy): <NEW_LINE> <INDENT> def __init__(self, pi): <NEW_LINE> <INDENT> nn.Module.__init__(self) <NEW_LINE> Policy.__init__(self) <NEW_LINE> self.pi = pi <NEW_LINE> <DEDENT> def act(self, states): <NEW_LINE> <INDENT> return self.pi(states)
Provide a Policy interface to a deterministic policy module. Output is an action vector or disc
62598fa8aad79263cf42e6fb
class PPC(Enum): <NEW_LINE> <INDENT> WC_WC = 0 <NEW_LINE> WC_HI = 1 <NEW_LINE> HI_WC = 2 <NEW_LINE> HI_HI = 3 <NEW_LINE> WC_LO = 4 <NEW_LINE> LO_WC = 5 <NEW_LINE> HI_LO = 6 <NEW_LINE> LO_HI = 7 <NEW_LINE> LO_LO = 8 <NEW_LINE> WC_AR = 9 <NEW_LINE> AR_WC = 10 <NEW_LINE> HI_AR = 11 <NEW_LINE> AR_HI = 12 <NEW_LINE> WC_EM = 13 <NEW_LINE> EM_WC = 14 <NEW_LINE> HI_EM = 15 <NEW_LINE> EM_HI = 16 <NEW_LINE> LO_AR = 17 <NEW_LINE> AR_LO = 18 <NEW_LINE> LO_EM = 19 <NEW_LINE> EM_LO = 20 <NEW_LINE> AR_AR = 21 <NEW_LINE> AR_EM = 22 <NEW_LINE> EM_AR = 23 <NEW_LINE> EM_EM = 24
Enum for every possible port pair class (PPC). PPC is pair consisting of source and destination port classes. There are 25 total PPC for every combination of source and destination port classes.
62598fa8009cb60464d01445
class TestRecordGeneralTask(unittest.TestCase): <NEW_LINE> <INDENT> def test_record_general(self): <NEW_LINE> <INDENT> task = RecordGeneralTask() <NEW_LINE> retval = task.run(18, 'WikiApiary', 'https://wikiapiary.com/w/api.php') <NEW_LINE> if 'edit' not in retval: <NEW_LINE> <INDENT> raise Exception(retval) <NEW_LINE> <DEDENT> <DEDENT> def test_record_general_fake(self): <NEW_LINE> <INDENT> task = RecordGeneralTask() <NEW_LINE> with self.assertRaises(Exception): <NEW_LINE> <INDENT> task.run(18, 'Foo', 'https://foo.bar.com')
Test the methods that access general siteinfo.
62598fa856b00c62f0fb27d9
class LockingShiftProcedure(Packet): <NEW_LINE> <INDENT> name = "Locking Shift Procedure" <NEW_LINE> fields_desc = [ BitField("lockShift", 0x0, 1), BitField("codesetId", 0x0, 3) ]
Locking shift procedure Section 10.5.4.2
62598fa8d7e4931a7ef3bfc2
class RunFilterSet(filters.FilterSet): <NEW_LINE> <INDENT> filters = [ filters.ChoicesFilter("status", choices=model.Run.STATUS), filters.ModelFilter( "product", lookup="productversion__product", queryset=model.Product.objects.all()), filters.ModelFilter( "productversion", queryset=model.ProductVersion.objects.all().select_related()), filters.KeywordFilter("name"), filters.KeywordFilter("description"), filters.ModelFilter( "suite", lookup="suites", queryset=model.Suite.objects.all()), filters.KeywordExactFilter( "case id", lookup="suites__cases__id", key="case", coerce=int), filters.ModelFilter( "creator", lookup="created_by", queryset=model.User.objects.all()), filters.ModelFilter( "environment element", lookup="environments__elements", key="envelement", queryset=model.Element.objects.all()), filters.ChoicesFilter( "is Series", lookup="is_series", key="is_series", choices=[(1, "series"), (0, "individual")], coerce=int, ), filters.ModelFilter( "members of series", lookup="series", queryset=model.Run.objects.filter(is_series=True) ), filters.KeywordExactFilter("build"), ]
FilterSet for runs.
62598fa8fff4ab517ebcd70b
class ajaxGetDrugProhibitions(BrowserView): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> plone.protect.CheckAuthenticator(self.request) <NEW_LINE> searchTerm = 'searchTerm' in self.request and self.request['searchTerm'].lower() or '' <NEW_LINE> page = self.request['page'] <NEW_LINE> nr_rows = self.request['rows'] <NEW_LINE> sord = self.request['sord'] <NEW_LINE> sidx = self.request['sidx'] <NEW_LINE> rows = [] <NEW_LINE> brains = self.bika_setup_catalog(portal_type='DrugProhibition', is_active=True) <NEW_LINE> if brains and searchTerm: <NEW_LINE> <INDENT> brains = [p for p in brains if p.Title.lower().find(searchTerm) > -1] <NEW_LINE> <DEDENT> for p in brains: <NEW_LINE> <INDENT> rows.append({'Title': p.Title, 'UID': p.UID, 'DrugProhibition': p.Title, 'Description': p.Description}) <NEW_LINE> <DEDENT> rows = sorted(rows, cmp=lambda x, y: cmp(x.lower(), y.lower()), key=itemgetter(sidx and sidx or 'Title')) <NEW_LINE> if sord == 'desc': <NEW_LINE> <INDENT> rows.reverse() <NEW_LINE> <DEDENT> pages = len(rows) / int(nr_rows) <NEW_LINE> pages += divmod(len(rows), int(nr_rows))[1] and 1 or 0 <NEW_LINE> ret = {'page': page, 'total': pages, 'records': len(rows), 'rows': rows[(int(page) - 1) * int(nr_rows): int(page) * int(nr_rows)]} <NEW_LINE> return json.dumps(ret)
Drug Prohibition Explanations vocabulary source for jquery combo dropdown box
62598fa88c0ade5d55dc3624
class UpdateAllStatusesInputSet(InputSet): <NEW_LINE> <INDENT> def set_APICredentials(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'APICredentials', value) <NEW_LINE> <DEDENT> def set_Message(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Message', value)
An InputSet with methods appropriate for specifying the inputs to the UpdateAllStatuses Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fa823849d37ff850fdb
class IdlCompiler(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self, output_directory, code_generator=None, interfaces_info=None, interfaces_info_filename='', only_if_changed=False): <NEW_LINE> <INDENT> self.code_generator = code_generator <NEW_LINE> if interfaces_info_filename: <NEW_LINE> <INDENT> with open(interfaces_info_filename) as interfaces_info_file: <NEW_LINE> <INDENT> interfaces_info = pickle.load(interfaces_info_file) <NEW_LINE> <DEDENT> <DEDENT> self.interfaces_info = interfaces_info <NEW_LINE> self.only_if_changed = only_if_changed <NEW_LINE> self.output_directory = output_directory <NEW_LINE> self.reader = IdlReader(interfaces_info, output_directory, True) <NEW_LINE> <DEDENT> def compile_and_write(self, idl_filename, output_filenames): <NEW_LINE> <INDENT> definitions = self.reader.read_idl_definitions(idl_filename) <NEW_LINE> return definitions <NEW_LINE> <DEDENT> def generate_global_and_write(self, output_filenames): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def compile_file(self, idl_filename): <NEW_LINE> <INDENT> pass
Abstract Base Class for IDL compilers. In concrete classes: * self.code_generator must be set, implementing generate_code() (returning a list of output code), and * compile_file() must be implemented (handling output filenames).
62598fa899fddb7c1ca62d7c
class SpecialMixerComponent( MixerComponent ): <NEW_LINE> <INDENT> def set_master_select_button( self, button ): <NEW_LINE> <INDENT> self.master_strip().set_select_button( button ) <NEW_LINE> <DEDENT> def set_track_select_values( self, selected, not_selected, empty ): <NEW_LINE> <INDENT> for strip in self._channel_strips: <NEW_LINE> <INDENT> strip.set_select_values( selected, not_selected, empty ) <NEW_LINE> <DEDENT> <DEDENT> def _create_strip( self ): <NEW_LINE> <INDENT> return SpecialChannelStripComponent()
Mixer component that uses the SpecialChannelStripComponent. Allows to set a master select button and to set values for the track select buttons.
62598fa8090684286d59366f
class DGProtection(GroupBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__()
Protection model for DG.
62598fa8fff4ab517ebcd70c
class SqlAlchemyConfig(Config): <NEW_LINE> <INDENT> _DRIVER = None <NEW_LINE> _ROOT = None <NEW_LINE> _PASSWORD = None <NEW_LINE> @property <NEW_LINE> def SQLALCHEMY_DATABASE_URI(self): <NEW_LINE> <INDENT> return f"{self._DB}+{self._DRIVER}://{self._ROOT}:{self._PASSWORD}@{self._DB_SERVER}:{self._DB_PORT}/{self._DB_NAME}" <NEW_LINE> <DEDENT> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> SQLALCHEMY_ECHO = True
配置SqlAlchemy ORM
62598fa8a8ecb03325871137
class ChangeCompareValue(tk.Toplevel): <NEW_LINE> <INDENT> def __init__(self, _master): <NEW_LINE> <INDENT> tk.Toplevel.__init__(self, _master) <NEW_LINE> self.title("Change PWM timing compare value") <NEW_LINE> tk.Label(self, text="Enter value to place in timing PWM compare register").pack(side='top') <NEW_LINE> tk.Label(self, text="Value must be between 500 and " + str(_master.device_params.PWM_period)).pack(side='top') <NEW_LINE> tk.Label(self, text="Current value is " + str(_master.device_params.PWM_compare)).pack(side='top') <NEW_LINE> value_varstring = tk.StringVar() <NEW_LINE> value_varstring.set(_master.device_params.PWM_compare) <NEW_LINE> value_box = tk.Entry(self, textvariable=value_varstring) <NEW_LINE> value_box.pack(side='top') <NEW_LINE> button_frame = tk.Frame(self) <NEW_LINE> button_frame.pack(side='top') <NEW_LINE> tk.Button(button_frame, text="Quit", command=self.destroy).pack(side='left') <NEW_LINE> tk.Button(button_frame, text="Send", command=lambda: self.compare_reg_change(_master, value_varstring.get())).pack(side='left') <NEW_LINE> logging.error("put in here something to check if the number for compare is correct") <NEW_LINE> <DEDENT> def compare_reg_change(self, master, _value): <NEW_LINE> <INDENT> master.device.write_timer_compare(_value) <NEW_LINE> self.destroy()
Allow the user to change the compare value of the PWM, for testing, sets when the ADC goes after the DAC is changes
62598fa85fdd1c0f98e5dec0
class CardLayoutParameter(CardSearchParam): <NEW_LINE> <INDENT> def __init__(self, layout: str): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.layout = layout <NEW_LINE> <DEDENT> def query(self) -> Q: <NEW_LINE> <INDENT> query = Q(card__layout=self.layout) <NEW_LINE> return ~query if self.negated else query <NEW_LINE> <DEDENT> def get_pretty_str(self) -> str: <NEW_LINE> <INDENT> return "card layout " + ("isn't" if self.negated else "is") + " " + self.layout
Parameter for whether a card has any phyrexian mana symbols or not
62598fa8f7d966606f747f0c
class LogoutEvent(object): <NEW_LINE> <INDENT> pass
Answer returned when a user click on the logout button
62598fa8d268445f26639b17
class TestApp(Script): <NEW_LINE> <INDENT> def __init__(self, name="testapp"): <NEW_LINE> <INDENT> Script.__init__(self, name) <NEW_LINE> return <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> from pylith.utils.PetscManager import PetscManager <NEW_LINE> petsc = PetscManager() <NEW_LINE> petsc.options = [("malloc_dump", "true")] <NEW_LINE> petsc.initialize() <NEW_LINE> unittest.TextTestRunner(verbosity=2).run(self._suite()) <NEW_LINE> petsc.finalize() <NEW_LINE> return <NEW_LINE> <DEDENT> def _suite(self): <NEW_LINE> <INDENT> suite = unittest.TestSuite() <NEW_LINE> from TestCellGeometry import TestCellGeometry <NEW_LINE> suite.addTest(unittest.makeSuite(TestCellGeometry)) <NEW_LINE> from TestFIATSimplex import TestFIATSimplex <NEW_LINE> suite.addTest(unittest.makeSuite(TestFIATSimplex)) <NEW_LINE> from TestFIATLagrange import TestFIATLagrange <NEW_LINE> suite.addTest(unittest.makeSuite(TestFIATLagrange)) <NEW_LINE> from TestMeshQuadrature import TestMeshQuadrature <NEW_LINE> suite.addTest(unittest.makeSuite(TestMeshQuadrature)) <NEW_LINE> from TestElasticityImplicit import TestElasticityImplicit <NEW_LINE> suite.addTest(unittest.makeSuite(TestElasticityImplicit)) <NEW_LINE> from TestElasticityExplicit import TestElasticityExplicit <NEW_LINE> suite.addTest(unittest.makeSuite(TestElasticityExplicit)) <NEW_LINE> from TestElasticityImplicitLgDeform import TestElasticityImplicitLgDeform <NEW_LINE> suite.addTest(unittest.makeSuite(TestElasticityImplicitLgDeform)) <NEW_LINE> from TestElasticityExplicitLgDeform import TestElasticityExplicitLgDeform <NEW_LINE> suite.addTest(unittest.makeSuite(TestElasticityExplicitLgDeform)) <NEW_LINE> return suite
Test application.
62598fa82ae34c7f260ab009
class VersionedError(Exception): <NEW_LINE> <INDENT> pass
Base error class.
62598fa83317a56b869be4de
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element): <NEW_LINE> <INDENT> pass
HTML-specific "meta" element.
62598fa824f1403a92685847
class BaseResource(Resource): <NEW_LINE> <INDENT> method_decorators = []
Base resource API handler.
62598fa89c8ee82313040104
class RobotInterface(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> vrep.simxFinish(-1) <NEW_LINE> self.clientID = vrep.simxStart("127.0.0.1", 19997, True, True, 5000, 5) <NEW_LINE> vrep.simxStopSimulation(self.clientID, vrep.simx_opmode_oneshot) <NEW_LINE> vrep.simxStartSimulation(self.clientID, vrep.simx_opmode_oneshot) <NEW_LINE> vrep.simxSynchronous(self.clientID, False) <NEW_LINE> print("connected with id ", self.clientID) <NEW_LINE> self.left_wheel = None <NEW_LINE> self.right_wheel = None <NEW_LINE> self.camera = None <NEW_LINE> self.setup() <NEW_LINE> self.lastimageAcquisitionTime = 0 <NEW_LINE> <DEDENT> def finish_iteration(self): <NEW_LINE> <INDENT> vrep.simxSynchronousTrigger(self.clientID) <NEW_LINE> <DEDENT> def set_right_speed(self, speed): <NEW_LINE> <INDENT> vrep.simxSetJointTargetVelocity(self.clientID, self.right_wheel, speed, vrep.simx_opmode_oneshot) <NEW_LINE> <DEDENT> def set_left_speed(self, speed): <NEW_LINE> <INDENT> vrep.simxSetJointTargetVelocity(self.clientID, self.left_wheel, speed, vrep.simx_opmode_oneshot) <NEW_LINE> <DEDENT> def _read_camera(self): <NEW_LINE> <INDENT> data = vrep.simxGetVisionSensorImage(self.clientID, self.camera, 1, vrep.simx_opmode_buffer) <NEW_LINE> if data[0] == vrep.simx_return_ok: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_image_from_camera(self): <NEW_LINE> <INDENT> img = None <NEW_LINE> while not img: img = self._read_camera() <NEW_LINE> size = img[1][0] <NEW_LINE> img = np.array(img[2], dtype='uint8').reshape((size, size)) <NEW_LINE> threshold = int(np.mean(img)) * 0.5 <NEW_LINE> ret, img = cv2.threshold(img.astype(np.uint8), threshold, 255, cv2.THRESH_BINARY_INV) <NEW_LINE> img = cv2.resize(img, (16, 16), interpolation=cv2.INTER_AREA) <NEW_LINE> return img <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> vrep.simxStopSimulation(self.clientID, vrep.simx_opmode_oneshot_wait) <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> if self.clientID != -1: <NEW_LINE> <INDENT> errorCode, handles, intData, floatData, array = vrep.simxGetObjectGroupData( self.clientID, vrep.sim_appobj_object_type, 0, vrep.simx_opmode_oneshot_wait) <NEW_LINE> data = dict(zip(array, handles)) <NEW_LINE> print(data) <NEW_LINE> self.camera = [value for key, value in data.items() if "Vision" in key][0] <NEW_LINE> self.left_wheel = [value for key, value in data.items() if "cLeftJoint" in key][0] <NEW_LINE> self.right_wheel = [value for key, value in data.items() if "cRightJoint" in key][0] <NEW_LINE> vrep.simxGetVisionSensorImage(self.clientID, self.camera, 1, vrep.simx_opmode_streaming) <NEW_LINE> <DEDENT> print(self.camera, self.left_wheel, self.right_wheel)
Esta classe facilita a interface com o simulador
62598fa8dd821e528d6d8e5d
class LabelUpdate(object): <NEW_LINE> <INDENT> openapi_types = { 'name': 'str', 'properties': 'object' } <NEW_LINE> attribute_map = { 'name': 'name', 'properties': 'properties' } <NEW_LINE> def __init__(self, name=None, properties=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self._properties = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if properties is not None: <NEW_LINE> <INDENT> self.properties = properties <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def properties(self): <NEW_LINE> <INDENT> return self._properties <NEW_LINE> <DEDENT> @properties.setter <NEW_LINE> def properties(self, properties): <NEW_LINE> <INDENT> self._properties = properties <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, LabelUpdate): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fa876e4537e8c3ef4d4
class Company: <NEW_LINE> <INDENT> def __init__(self, state, people, market, fixed_overhead): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.people = people <NEW_LINE> self.market = market <NEW_LINE> self.overhead = fixed_overhead <NEW_LINE> <DEDENT> def month(self, market_fit_emphasis): <NEW_LINE> <INDENT> self.state.age += 1 <NEW_LINE> salaries = sum(p.personality.salary for p in self.people) <NEW_LINE> self.state.cash -= (salaries + self.overhead) <NEW_LINE> self.state.cash -= salaries * 0.3 <NEW_LINE> for person in self.people: <NEW_LINE> <INDENT> person.one_month() <NEW_LINE> <DEDENT> self.state.ip += sum(p.personality.development * (1 - market_fit_emphasis) for p in self.people) <NEW_LINE> if self.state.ip > 1: <NEW_LINE> <INDENT> self.state.ip = 1 <NEW_LINE> <DEDENT> self.state.pmf += sum(p.personality.development * market_fit_emphasis for p in self.people) <NEW_LINE> if self.state.pmf > 1: <NEW_LINE> <INDENT> self.state.pmf = 1 <NEW_LINE> <DEDENT> if not self.state.development_effect() > 0: <NEW_LINE> <INDENT> self.state.channel = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.state.channel += sum(p.personality.marketing for p in self.people) <NEW_LINE> if self.state.channel > 1: <NEW_LINE> <INDENT> self.state.channel = 1 <NEW_LINE> <DEDENT> <DEDENT> pool = self.market.sales_pool_this_month() <NEW_LINE> sales_this_month = pool * self.state.development_effect() * self.state.channel <NEW_LINE> for n in range(0, int(sales_this_month)): <NEW_LINE> <INDENT> self.state.subscribers.add(self.market.generate_sale()) <NEW_LINE> <DEDENT> self.state.cash -= self.market.acq * sales_this_month <NEW_LINE> revenue = sum(s.revenue_this_month() for s in self.state.subscribers) <NEW_LINE> self.state.cash += revenue <NEW_LINE> returned = sum(p.returned for p in self.people) <NEW_LINE> op_cost = sum(p.op_cost for p in self.people) <NEW_LINE> result = Result() <NEW_LINE> result.revenue = revenue <NEW_LINE> result.sales = int(sales_this_month) <NEW_LINE> result.pipeline = self.state.pipeline() <NEW_LINE> result.cash = self.state.cash <NEW_LINE> result.salaries = salaries <NEW_LINE> result.overall = ((self.state.cash + returned) - (self.state.initial + op_cost)) <NEW_LINE> factors = Factors() <NEW_LINE> factors.ip = self.state.ip <NEW_LINE> factors.pmf = self.state.pmf <NEW_LINE> factors.channel = self.state.channel <NEW_LINE> factors.pool = pool <NEW_LINE> factors.sales = sales_this_month <NEW_LINE> return result, factors <NEW_LINE> <DEDENT> def capital_injection(self, amount): <NEW_LINE> <INDENT> self.state.cash += amount
The company itself :param state: an initial state :param people: the people involved :param market: the market in which they operate :param fixed_overhead: monthly fixed overhead :param cost_of_sale: as a fraction
62598fa8be383301e0253720
class UnitialisedPinException(Exception): <NEW_LINE> <INDENT> pass
Exception for when you try and use an unintialised pin
62598fa860cbc95b06364274
class MouseButtonPressedEvent(MouseButtonEvent): <NEW_LINE> <INDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "MouseButtonPressedEvent[tick=" + str(self.tick) + ", button=" + str(self.button) + ", " + "position=" + str(self.position) + ", canceled=" + str(self._canceled) + "]"
The type of MouseButtonEvent used for mouse button press event. This kind of event is fired whenever a mouse button is being pressed. Unlike the MouseDraggedEvent, this event is only issued once before the key got released. Attributes ---------- tick: int The tick at which the event got fired. button: int The code of the mouse button pressed. position: numpy.ndarray The position of the pointer on the screen. Methods ------- cancel() Cancels the event. is_canceled() Returns whether or not the event got canceled.
62598fa8097d151d1a2c0f50
class WildcardType(Type): <NEW_LINE> <INDENT> pass
Unfortunately, without proper library mechanisms, when a service calls one of an endpoint's methods, we do not know the type that that method returns. To deal with this, allowing an endpoint method call to return a "WildcardType." A WildcardType can match anything, and it's up to the programmer to ensure that types match appropriately.
62598fa826068e7796d4c882
class GlobalSettings(object): <NEW_LINE> <INDENT> site_title = "哈尔滨医科大学网站管理后台" <NEW_LINE> site_footer = "哈尔滨医科大学" <NEW_LINE> menu_style = "accordion"
xadmin的全局配置
62598fa8460517430c431ff0
class Station: <NEW_LINE> <INDENT> def __init__(self, api_object): <NEW_LINE> <INDENT> self.name = api_object["locationName"] <NEW_LINE> self.crs = api_object["crs"] <NEW_LINE> self.via = api_object["via"]
Describes a station within the National Rail network
62598fa899cbb53fe6830dfe
class SingerPart(UUIDPkMixin, models.Model): <NEW_LINE> <INDENT> is_main_part = models.BooleanField(default=True) <NEW_LINE> song_part = models.ForeignKey(SongPart, related_name="singer_parts") <NEW_LINE> singer = models.ForeignKey("Singer", related_name="singer_parts") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = "songs"
A given singer can sing a given song part
62598fa84f88993c371f049e
class pltfm_mgr_qsfp_threshold_t(object): <NEW_LINE> <INDENT> def __init__(self, highalarm=None, lowalarm=None, highwarning=None, lowwarning=None,): <NEW_LINE> <INDENT> self.highalarm = highalarm <NEW_LINE> self.lowalarm = lowalarm <NEW_LINE> self.highwarning = highwarning <NEW_LINE> self.lowwarning = lowwarning <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.DOUBLE: <NEW_LINE> <INDENT> self.highalarm = iprot.readDouble() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.DOUBLE: <NEW_LINE> <INDENT> self.lowalarm = iprot.readDouble() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.DOUBLE: <NEW_LINE> <INDENT> self.highwarning = iprot.readDouble() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 4: <NEW_LINE> <INDENT> if ftype == TType.DOUBLE: <NEW_LINE> <INDENT> self.lowwarning = iprot.readDouble() <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('pltfm_mgr_qsfp_threshold_t') <NEW_LINE> if self.highalarm is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('highalarm', TType.DOUBLE, 1) <NEW_LINE> oprot.writeDouble(self.highalarm) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.lowalarm is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('lowalarm', TType.DOUBLE, 2) <NEW_LINE> oprot.writeDouble(self.lowalarm) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.highwarning is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('highwarning', TType.DOUBLE, 3) <NEW_LINE> oprot.writeDouble(self.highwarning) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.lowwarning is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('lowwarning', TType.DOUBLE, 4) <NEW_LINE> oprot.writeDouble(self.lowwarning) <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: - highalarm - lowalarm - highwarning - lowwarning
62598fa821bff66bcd722b8e
class Comparable(Interface): <NEW_LINE> <INDENT> __cmp_body__ = __rcmp_body__ = Interface.error <NEW_LINE> def __cmp__(iself, other): <NEW_LINE> <INDENT> __cmp_body__(iself, other) <NEW_LINE> <DEDENT> def __rcmp__(iself, other): <NEW_LINE> <INDENT> __rcmp_body__(iself, other)
Interface for instances which are less-than, equal-to or greater-than each other. Specifies the following methods: iself.__cmp__(other) - return whether `iself' is <, ==, or > `other' iself.__rcmp__(other) - return whether `other' is <, ==, or > `iself'
62598fa8f548e778e596b4cd
class ReplayBuffer: <NEW_LINE> <INDENT> def __init__(self, action_size, buffer_size, batch_size, seed): <NEW_LINE> <INDENT> self.action_size = action_size <NEW_LINE> self.memory = deque(maxlen=buffer_size) <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.experience = namedtuple("Experience", field_names=[ "state", "action", "reward", "next_state", "done"]) <NEW_LINE> self.seed = random.seed(seed) <NEW_LINE> <DEDENT> def add(self, state, action, reward, next_state, done): <NEW_LINE> <INDENT> e = self.experience(state, action, reward, next_state, done) <NEW_LINE> self.memory.append(e) <NEW_LINE> <DEDENT> def sample(self): <NEW_LINE> <INDENT> experiences = random.sample(self.memory, k=self.batch_size) <NEW_LINE> states = torch.from_numpy( np.vstack([e.state for e in experiences if e is not None])).float().to(device) <NEW_LINE> actions = torch.from_numpy( np.vstack([e.action for e in experiences if e is not None])).float().to(device) <NEW_LINE> rewards = torch.from_numpy( np.vstack([e.reward for e in experiences if e is not None])).float().to(device) <NEW_LINE> next_states = torch.from_numpy(np.vstack( [e.next_state for e in experiences if e is not None])).float().to(device) <NEW_LINE> dones = torch.from_numpy(np.vstack( [e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device) <NEW_LINE> return (states, actions, rewards, next_states, dones) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.memory)
Fixed-size buffer to store experience tuples.
62598fa866673b3332c302f3
class AddBoxView(BoxForm): <NEW_LINE> <INDENT> plus_btn = Dropdown('Add') <NEW_LINE> @property <NEW_LINE> def is_displayed(self): <NEW_LINE> <INDENT> return ( self.in_customization and self.service_dialogs.is_opened and self.title.text == "Adding a new Dialog [Box Information]" )
AddBox View.
62598fa88e71fb1e983bb9db
class Component(component.Main): <NEW_LINE> <INDENT> def addObjects(self): <NEW_LINE> <INDENT> self.normal = self.guide.blades["blade"].z * -1 <NEW_LINE> self.binormal = self.guide.blades["blade"].x <NEW_LINE> self.length0 = vector.getDistance(self.guide.apos[0], self.guide.apos[1]) <NEW_LINE> t = transform.getTransformLookingAt(self.guide.apos[0], self.guide.apos[1], self.normal, axis="xy", negate=self.negate) <NEW_LINE> self.ctl_npo = primitive.addTransform( self.root, self.getName("ctl_npo"), t) <NEW_LINE> self.ctl = self.addCtl( self.ctl_npo, "ctl", t, self.color_fk, "cube", w=self.length0, h=self.size * .1, d=self.size * .1, po=datatypes.Vector(.5 * self.length0 * self.n_factor, 0, 0), tp=self.parentCtlTag) <NEW_LINE> t = transform.getTransformFromPos(self.guide.apos[2]) <NEW_LINE> self.orbit_ref1 = primitive.addTransform( self.ctl, self.getName("orbit_ref1"), t) <NEW_LINE> self.orbit_ref2 = primitive.addTransform( self.root, self.getName("orbit_ref2"), t) <NEW_LINE> self.orbit_cns = primitive.addTransform( self.ctl, self.getName("orbit_cns"), t) <NEW_LINE> self.orbit_npo = primitive.addTransform( self.orbit_cns, self.getName("orbit_npo"), t) <NEW_LINE> self.orbit_ctl = self.addCtl(self.orbit_npo, "orbit_ctl", t, self.color_fk, "sphere", w=self.length0 / 4, tp=self.ctl) <NEW_LINE> self.jnt_pos.append([self.ctl, "shoulder"]) <NEW_LINE> <DEDENT> def addAttributes(self): <NEW_LINE> <INDENT> if self.settings["refArray"]: <NEW_LINE> <INDENT> ref_names = self.get_valid_alias_list( self.settings["refArray"].split(",")) <NEW_LINE> if len(ref_names) >= 1: <NEW_LINE> <INDENT> self.ref_att = self.addAnimEnumParam( "rotRef", "Ref", 0, ref_names) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def addOperators(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def setRelation(self): <NEW_LINE> <INDENT> self.relatives["root"] = self.ctl <NEW_LINE> self.relatives["tip"] = self.ctl <NEW_LINE> self.relatives["orbit"] = self.orbit_ctl <NEW_LINE> self.controlRelatives["root"] = self.ctl <NEW_LINE> self.controlRelatives["tip"] = self.ctl <NEW_LINE> self.controlRelatives["orbit"] = self.orbit_ctl <NEW_LINE> self.jointRelatives["root"] = 0 <NEW_LINE> self.jointRelatives["tip"] = 0 <NEW_LINE> self.jointRelatives["orbit"] = 0 <NEW_LINE> self.aliasRelatives["root"] = "ctl" <NEW_LINE> self.aliasRelatives["tip"] = "ctl" <NEW_LINE> self.aliasRelatives["orbit"] = "orbit" <NEW_LINE> <DEDENT> def connect_standard(self): <NEW_LINE> <INDENT> self.parent.addChild(self.root) <NEW_LINE> self.connect_standardWithRotRef(self.settings["refArray"], self.orbit_cns)
Shifter component Class
62598fa84527f215b58e9e0b
class DistributedHashingMachine: <NEW_LINE> <INDENT> def __init__(self, args): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.graphs = glob.glob(args.input_path + "*.json") <NEW_LINE> <DEDENT> def execute_hashing(self): <NEW_LINE> <INDENT> self.hashes = Parallel(n_jobs=self.args.workers)(delayed(hash_wrap)(g, self.args) for g in tqdm(self.graphs)) <NEW_LINE> <DEDENT> def save_embedding(self): <NEW_LINE> <INDENT> self.feature_count = self.args.dimensions*(self.args.wl_iterations+1) <NEW_LINE> self.column_names = ["name"] + [str(fet) for fet in range(self.feature_count)] <NEW_LINE> self.hashes = pd.DataFrame(self.hashes, columns=self.column_names) <NEW_LINE> self.hashes = self.hashes.sort_values(["name"]) <NEW_LINE> self.hashes.to_csv(self.args.output_path, index=None)
Class for parallel nested subtree hashing.
62598fa8cc0a2c111447af39
class FilteringOperator(PlexObject): <NEW_LINE> <INDENT> TAG = 'Operator' <NEW_LINE> def _loadData(self, data): <NEW_LINE> <INDENT> self.key = data.attrib.get('key') <NEW_LINE> self.title = data.attrib.get('title')
Represents an single Operator for a :class:`~plexapi.library.FilteringFieldType`. Attributes: TAG (str): 'Operator' key (str): The URL key for the operator. title (str): The title of the operator.
62598fa8e5267d203ee6b834
class Experiment(object): <NEW_LINE> <INDENT> def __init__(self, format=None): <NEW_LINE> <INDENT> self.plates = {} <NEW_LINE> self.info = {} <NEW_LINE> <DEDENT> def add_plate(self, plate): <NEW_LINE> <INDENT> self.plates.append(read)
Information about a plate in an experiment Properties: plates A dictionary of Plate objects keyed by their unique name info Dictionary of information related to the Experiment
62598fa87047854f4633f302
class StaticTableToMapTestCase(DatabaseToMapTestCase): <NEW_LINE> <INDENT> def tearDown(self): <NEW_LINE> <INDENT> self.remove_tempfiles() <NEW_LINE> <DEDENT> def test_copy_static_table(self): <NEW_LINE> <INDENT> self.db.execute(CREATE_STMT) <NEW_LINE> for row in TABLE_DATA: <NEW_LINE> <INDENT> self.db.execute("INSERT INTO t1 VALUES (%s, %s)", row) <NEW_LINE> <DEDENT> cfg = {'datacopy': {'schema sd': ['t1']}} <NEW_LINE> dbmap = self.to_map([], config=cfg) <NEW_LINE> assert dbmap['schema sd']['table t1'] == { 'columns': [{'c1': {'type': 'integer'}}, {'c2': {'type': 'text'}}]} <NEW_LINE> recs = [] <NEW_LINE> with open(os.path.join(self.cfg['files']['data_path'], "schema.sd", FILE_PATH)) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> (c1, c2) = line.split(',') <NEW_LINE> recs.append((int(c1), c2.rstrip())) <NEW_LINE> <DEDENT> <DEDENT> assert recs == TABLE_DATA <NEW_LINE> <DEDENT> def test_copy_static_table_pk(self): <NEW_LINE> <INDENT> self.db.execute("CREATE TABLE t1 (c1 integer, c2 char(3), c3 text," "PRIMARY KEY (c2, c1))") <NEW_LINE> for row in TABLE_DATA2: <NEW_LINE> <INDENT> self.db.execute("INSERT INTO t1 VALUES (%s, %s, %s)", row) <NEW_LINE> <DEDENT> cfg = {'datacopy': {'schema sd': ['t1']}} <NEW_LINE> dbmap = self.to_map([], config=cfg) <NEW_LINE> assert dbmap['schema sd']['table t1'] == { 'columns': [{'c1': {'type': 'integer', 'not_null': True}}, {'c2': {'type': 'character(3)', 'not_null': True}}, {'c3': {'type': 'text'}}], 'primary_key': {'t1_pkey': {'columns': ['c2', 'c1']}}} <NEW_LINE> recs = [] <NEW_LINE> with open(os.path.join(self.cfg['files']['data_path'], "schema.sd", FILE_PATH)) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> (c1, c2, c3) = line.split(',') <NEW_LINE> recs.append((int(c1), c2, c3.rstrip())) <NEW_LINE> <DEDENT> <DEDENT> assert recs == sorted(TABLE_DATA2)
Test mapping and copying out of created tables
62598fa81f037a2d8b9e4015
class MapReduceTask(object): <NEW_LINE> <INDENT> shard_count = 3 <NEW_LINE> pipeline_class = MapperPipeline <NEW_LINE> job_name = None <NEW_LINE> queue_name = 'default' <NEW_LINE> output_writer_spec = None <NEW_LINE> mapreduce_parameters = {} <NEW_LINE> countdown = None <NEW_LINE> eta = None <NEW_LINE> model = None <NEW_LINE> map_args = [] <NEW_LINE> map_kwargs = {} <NEW_LINE> def __init__(self, model=None): <NEW_LINE> <INDENT> if model: <NEW_LINE> <INDENT> self.model = model <NEW_LINE> <DEDENT> if not self.job_name: <NEW_LINE> <INDENT> self.job_name = self.get_class_path() <NEW_LINE> <DEDENT> <DEDENT> def get_model_app_(self): <NEW_LINE> <INDENT> app = self.model._meta.app_label <NEW_LINE> name = self.model.__name__ <NEW_LINE> return '{app}.{name}'.format( app=app, name=name, ) <NEW_LINE> <DEDENT> def get_class_path(self): <NEW_LINE> <INDENT> return '{mod}.{cls}'.format( mod=self.__class__.__module__, cls=self.__class__.__name__, ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_relative_path(cls, func): <NEW_LINE> <INDENT> return '{mod}.{cls}.{func}'.format( mod=cls.__module__, cls=cls.__name__, func=func.__name__, ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def map(entity, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('You must supply a map function') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def finish(**kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('You must supply a finish function') <NEW_LINE> <DEDENT> def start(self, *args, **kwargs): <NEW_LINE> <INDENT> mapper_parameters = { 'model': self.get_model_app_(), 'kwargs': kwargs, 'args': args, } <NEW_LINE> if 'map' not in self.__class__.__dict__: <NEW_LINE> <INDENT> raise Exception('No static map method defined on class {cls}'.format(self.__class__)) <NEW_LINE> <DEDENT> mapper_parameters['_map'] = self.get_relative_path(self.map) <NEW_LINE> if 'finish' in self.__class__.__dict__: <NEW_LINE> <INDENT> mapper_parameters['_finish'] = self.get_relative_path(self.finish) <NEW_LINE> <DEDENT> pipe = DjangaeMapperPipeline( self.job_name, 'djangae.contrib.mappers.thunks.thunk_map', 'djangae.contrib.mappers.readers.DjangoInputReader', params=mapper_parameters, shards=self.shard_count ) <NEW_LINE> pipe.start(base_path=PIPELINE_BASE_PATH)
MapReduceTask base class, inherit this in a statically defined class and use .start() to run a mapreduce task You must define a staticmethod 'map' which takes in an arg of the entity being mapped over. Optionally define a staticmethod 'reduce' for the reduce stage (Not Implemented). You can pass any additional args and/or kwargs to .start(), which will then be passed into each call of .map() for you. Overwrite 'finish' with a static definition for a finish callback
62598fa8aad79263cf42e6fe
class VBox(HBox): <NEW_LINE> <INDENT> @decorate_constructor_parameter_types([]) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(VBox, self).__init__(*args, **kwargs) <NEW_LINE> self.style['flex-direction'] = 'column'
The purpose of this widget is to automatically vertically aligning the widgets that are appended to it. Does not permit children absolute positioning. In order to add children to this container, use the append(child, key) function. The key have to be numeric and determines the children order in the layout. Note: If you would absolute positioning, use the Container instead.
62598fa8925a0f43d25e7f68
class FlockingReport(ReportUtils.Reporter): <NEW_LINE> <INDENT> def __init__(self, config_file, start, end, **kwargs): <NEW_LINE> <INDENT> report = 'Flocking' <NEW_LINE> super(FlockingReport, self).__init__(config_file=config_file, start=start, end=end, report_type=report, **kwargs) <NEW_LINE> self.title = "OSG Flocking: Usage of OSG Sites for {0} - {1}".format( start, end) <NEW_LINE> self.header = ["SiteName", "VOName", "ProbeName", "ProjectName", "Wall Hours"] <NEW_LINE> <DEDENT> def run_report(self): <NEW_LINE> <INDENT> self.send_report() <NEW_LINE> <DEDENT> def query(self): <NEW_LINE> <INDENT> starttimeq = self.start_time.isoformat() <NEW_LINE> endtimeq = self.end_time.isoformat() <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> self.logger.info(self.indexpattern) <NEW_LINE> <DEDENT> probeslist = self.config[self.report_type.lower()]['probe_list'] <NEW_LINE> s = Search(using=self.client, index=self.indexpattern) .filter("range", EndTime={"gte": starttimeq, "lt": endtimeq}) .filter("terms", ProbeName=probeslist) .filter("term", ResourceType="Payload")[0:0] <NEW_LINE> Bucket = s.aggs.bucket('group_Site', 'terms', field='SiteName', size=MAXINT) .bucket('group_VOName', 'terms', field='VOName', size=MAXINT) .bucket('group_ProbeName', 'terms', field='ProbeName', size=MAXINT) .bucket('group_ProjectName', 'terms', field='ProjectName', missing='N/A', size=MAXINT) <NEW_LINE> Bucket.metric("CoreHours_sum", "sum", field="CoreHours") <NEW_LINE> return s <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> results = self.run_query() <NEW_LINE> for site in results.group_Site.buckets: <NEW_LINE> <INDENT> sitekey = site.key <NEW_LINE> for vo in site.group_VOName.buckets: <NEW_LINE> <INDENT> vokey = vo.key <NEW_LINE> for probe in vo.group_ProbeName.buckets: <NEW_LINE> <INDENT> probekey = probe.key <NEW_LINE> projects = (project for project in probe.group_ProjectName.buckets) <NEW_LINE> for project in projects: <NEW_LINE> <INDENT> yield (sitekey, vokey, probekey, project.key, project.CoreHours_sum.value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def format_report(self): <NEW_LINE> <INDENT> report = defaultdict(list) <NEW_LINE> for result_tuple in self.generate(): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print("{0}\t{1}\t{2}\t{3}\t{4}".format(*result_tuple)) <NEW_LINE> <DEDENT> mapdict = dict(list(zip(self.header, result_tuple))) <NEW_LINE> for key, item in mapdict.items(): <NEW_LINE> <INDENT> report[key].append(item) <NEW_LINE> <DEDENT> <DEDENT> tot = sum(report['Wall Hours']) <NEW_LINE> for col in self.header: <NEW_LINE> <INDENT> if col == 'VOName': <NEW_LINE> <INDENT> report[col].append('Total') <NEW_LINE> <DEDENT> elif col == 'Wall Hours': <NEW_LINE> <INDENT> report[col].append(tot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> report[col].append('') <NEW_LINE> <DEDENT> <DEDENT> if self.verbose: <NEW_LINE> <INDENT> print("The total Wall hours in this report are {0}".format(tot)) <NEW_LINE> <DEDENT> return report
Class to hold information for and to run OSG Flocking report :param str config_file: Report Configuration filename :param str start: Start time of report range :param str end: End time of report range
62598fa87d43ff2487427397
class chained_getter(object): <NEW_LINE> <INDENT> __slots__ = ('namespace', 'getter') <NEW_LINE> __fifo_cache__ = deque() <NEW_LINE> __inst_caching__ = True <NEW_LINE> __attr_comparison__ = ("namespace",) <NEW_LINE> __metaclass__ = partial(generic_equality, real_type=caching.WeakInstMeta) <NEW_LINE> def __init__(self, namespace): <NEW_LINE> <INDENT> self.namespace = namespace <NEW_LINE> self.getter = self._mk_getter(namespace) <NEW_LINE> if len(self.__fifo_cache__) > 10: <NEW_LINE> <INDENT> self.__fifo_cache__.popleft() <NEW_LINE> <DEDENT> self.__fifo_cache__.append(self) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.namespace) <NEW_LINE> <DEDENT> if sys.version_info >= (2,6): <NEW_LINE> <INDENT> _mk_getter = attrgetter <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def _mk_getter(namespace): <NEW_LINE> <INDENT> def f(obj, attrs=tuple(attrgetter(x) for x in namespace.split("."))): <NEW_LINE> <INDENT> o = obj <NEW_LINE> for attr in attrs: <NEW_LINE> <INDENT> o = attr(o) <NEW_LINE> <DEDENT> return o <NEW_LINE> <DEDENT> return f <NEW_LINE> <DEDENT> <DEDENT> _mk_getter = staticmethod(_mk_getter) <NEW_LINE> def __call__(self, obj): <NEW_LINE> <INDENT> return self.getter(obj)
object that will do multi part lookup, regardless of if it's in the context of an instancemethod or staticmethod. Note that developers should use :py:func:`static_attrgetter` or :py:func:`instance_attrgetter` instead of this class directly. They should do this since dependent on the python version, there may be a faster implementation to use- for python2.6, :py:func:`operator.attrgetter` can do this same functionality but cannot be used as an instance method (like most stdlib functions, it's a staticmethod) Example Usage: >>> from snakeoil.klass import chained_getter >>> # general usage example: basically like operator.attrgetter >>> print chained_getter("extend")(list).__name__ extend >>> >>> class foo(object): ... ... seq = (1,2,3) ... ... def __init__(self, a=1): ... self.a = a ... ... b = property(chained_getter("a")) ... # please note that recursive should be using :py:func:`alias_attr` instead, ... # since that's effectively what that functor does ... recursive = property(chained_getter("seq.__hash__")) >>> >>> o = foo() >>> print o.a 1 >>> print o.b 1 >>> print o.recursive == foo.seq.__hash__ True
62598fa83617ad0b5ee0607d
class gffObject(object): <NEW_LINE> <INDENT> def __init__(self, seqid, source, type, start, end, score, strand, phase, attributes): <NEW_LINE> <INDENT> self._seqid = seqid <NEW_LINE> self._source = source <NEW_LINE> self._type = type <NEW_LINE> self._start = start <NEW_LINE> self._end = end <NEW_LINE> self._score = score <NEW_LINE> self._strand = strand <NEW_LINE> self._phase = phase <NEW_LINE> self._attributes = attributes <NEW_LINE> self._attrib_dct = {} <NEW_LINE> pattern = re.compile(r"""(\w+)=([\w:.,]+)""") <NEW_LINE> tmp = pattern.findall(self._attributes) <NEW_LINE> for a in tmp: <NEW_LINE> <INDENT> key, val = (a) <NEW_LINE> self._attrib_dct[key]=val <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def seqid(self): <NEW_LINE> <INDENT> return self._seqid <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> return self._source <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @property <NEW_LINE> def start(self): <NEW_LINE> <INDENT> return self._start <NEW_LINE> <DEDENT> @property <NEW_LINE> def end(self): <NEW_LINE> <INDENT> return self._end <NEW_LINE> <DEDENT> @property <NEW_LINE> def score(self): <NEW_LINE> <INDENT> return self._score <NEW_LINE> <DEDENT> @property <NEW_LINE> def strand(self): <NEW_LINE> <INDENT> return self._strand <NEW_LINE> <DEDENT> @property <NEW_LINE> def phase(self): <NEW_LINE> <INDENT> return self._phase <NEW_LINE> <DEDENT> @property <NEW_LINE> def attributes(self): <NEW_LINE> <INDENT> return self._attributes <NEW_LINE> <DEDENT> @property <NEW_LINE> def attrib_dct(self): <NEW_LINE> <INDENT> return self._attrib_dct <NEW_LINE> <DEDENT> def toGFF3line(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getParents(self): <NEW_LINE> <INDENT> pass
"seqid" (gff column 1) landmark for coordinate system "source" (gff column 2) source db/program etc "type" (gff column 3) term from the Sequence Ontology "start"(gff column 4) relative to the landmark seqid "end" (gff column 5) 1-based integer coordinates "score" (gff column 6) float "strand" (gff column 7) +/i/./? for positive/negative/none/unknown strand (relative to the landmark) "phase" (gff column 8) 0/1/2 for "CDS" features, start rel. to reading frame "attributes" (gff column 9) list of feature attributes in the format tag=value. Multiple tag=value pairs are separated by semicolons. ID, Name, Alias, Parent, Target, Gap, Derives_from, Note, Dbxref, Ontology_term, Is_circular Parent: groups exons into transcripts, transcripts into genes etc. A feature may have multiple parents. Target: Indicates the target of a nucleotide-to-nucleotide or protein-to-nucleotide alignment. The format of the value is "target_id start end [strand]", where strand is optional and may be "+" or "-". Gap: The alignment of the feature to the target if the two are not collinear (e.g. contain gaps). The alignment format is taken from the CIGAR format described in the Exonerate documentation. (http://cvsweb.sanger.ac.uk/cgi-bin/cvsweb.cgi/exonerate?cvsroot=Ensembl). ("THE GAP ATTRIBUTE") Parent, the Alias, Note, DBxref and Ontology_term attributes can have multiple values.
62598fa824f1403a92685848
class HexValidator(wx.PyValidator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(HexValidator, self).__init__() <NEW_LINE> self.Bind(wx.EVT_CHAR, self.OnChar) <NEW_LINE> <DEDENT> def Clone(self): <NEW_LINE> <INDENT> return HexValidator() <NEW_LINE> <DEDENT> def Validate(self, win): <NEW_LINE> <INDENT> for char in val: <NEW_LINE> <INDENT> if char not in HEX_CHARS: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def OnChar(self, event): <NEW_LINE> <INDENT> key = event.GetKeyCode() <NEW_LINE> if event.CmdDown() or key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255 or chr(key) in HEX_CHARS[:-1]: <NEW_LINE> <INDENT> event.Skip() <NEW_LINE> return <NEW_LINE> <DEDENT> if not wx.Validator_IsSilent(): <NEW_LINE> <INDENT> wx.Bell() <NEW_LINE> <DEDENT> return
Validate Hex strings for the color setter
62598fa8b7558d5895463559
class CSGNode(object): <NEW_LINE> <INDENT> def __init__(self, polygons=None): <NEW_LINE> <INDENT> self.plane = None <NEW_LINE> self.front = None <NEW_LINE> self.back = None <NEW_LINE> self.polygons = [] <NEW_LINE> if polygons: <NEW_LINE> <INDENT> self.build(polygons) <NEW_LINE> <DEDENT> <DEDENT> def clone(self): <NEW_LINE> <INDENT> node = CSGNode() <NEW_LINE> if self.plane: <NEW_LINE> <INDENT> node.plane = self.plane.clone() <NEW_LINE> <DEDENT> if self.front: <NEW_LINE> <INDENT> node.front = self.front.clone() <NEW_LINE> <DEDENT> if self.back: <NEW_LINE> <INDENT> node.back = self.back.clone() <NEW_LINE> <DEDENT> node.polygons = map(lambda p: p.clone(), self.polygons) <NEW_LINE> return node <NEW_LINE> <DEDENT> def invert(self): <NEW_LINE> <INDENT> for poly in self.polygons: <NEW_LINE> <INDENT> poly.flip() <NEW_LINE> <DEDENT> if self.plane: <NEW_LINE> <INDENT> self.plane.flip() <NEW_LINE> <DEDENT> if self.front: <NEW_LINE> <INDENT> self.front.invert() <NEW_LINE> <DEDENT> if self.back: <NEW_LINE> <INDENT> self.back.invert() <NEW_LINE> <DEDENT> temp = self.front <NEW_LINE> self.front = self.back <NEW_LINE> self.back = temp <NEW_LINE> <DEDENT> def clipPolygons(self, polygons): <NEW_LINE> <INDENT> if not self.plane: <NEW_LINE> <INDENT> return polygons[:] <NEW_LINE> <DEDENT> front = [] <NEW_LINE> back = [] <NEW_LINE> for poly in polygons: <NEW_LINE> <INDENT> self.plane.splitPolygon(poly, front, back, front, back) <NEW_LINE> <DEDENT> if self.front: <NEW_LINE> <INDENT> front = self.front.clipPolygons(front) <NEW_LINE> <DEDENT> if self.back: <NEW_LINE> <INDENT> back = self.back.clipPolygons(back) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> back = [] <NEW_LINE> <DEDENT> front.extend(back) <NEW_LINE> return front <NEW_LINE> <DEDENT> def clipTo(self, bsp): <NEW_LINE> <INDENT> self.polygons = bsp.clipPolygons(self.polygons) <NEW_LINE> if self.front: <NEW_LINE> <INDENT> self.front.clipTo(bsp) <NEW_LINE> <DEDENT> if self.back: <NEW_LINE> <INDENT> self.back.clipTo(bsp) <NEW_LINE> <DEDENT> <DEDENT> def allPolygons(self): <NEW_LINE> <INDENT> polygons = self.polygons[:] <NEW_LINE> if self.front: <NEW_LINE> <INDENT> polygons.extend(self.front.allPolygons()) <NEW_LINE> <DEDENT> if self.back: <NEW_LINE> <INDENT> polygons.extend(self.back.allPolygons()) <NEW_LINE> <DEDENT> return polygons <NEW_LINE> <DEDENT> def build(self, polygons): <NEW_LINE> <INDENT> if isinstance(polygons, map): <NEW_LINE> <INDENT> polygons = list(polygons) <NEW_LINE> if not len(polygons): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> if not self.plane: <NEW_LINE> <INDENT> self.plane = polygons[0].plane.clone() <NEW_LINE> <DEDENT> front = [] <NEW_LINE> back = [] <NEW_LINE> for poly in polygons: <NEW_LINE> <INDENT> self.plane.splitPolygon( poly, self.polygons, self.polygons, front, back) <NEW_LINE> <DEDENT> if len(front): <NEW_LINE> <INDENT> if not self.front: <NEW_LINE> <INDENT> self.front = CSGNode() <NEW_LINE> <DEDENT> self.front.build(front) <NEW_LINE> <DEDENT> if len(back): <NEW_LINE> <INDENT> if not self.back: <NEW_LINE> <INDENT> self.back = CSGNode() <NEW_LINE> <DEDENT> self.back.build(back)
class CSGNode Holds a node in a BSP tree. A BSP tree is built from a collection of polygons by picking a polygon to split along. That polygon (and all other coplanar polygons) are added directly to that node and the other polygons are added to the front and/or back subtrees. This is not a leafy BSP tree since there is no distinction between internal and leaf nodes.
62598fa8f548e778e596b4ce
class Hidden(HtmlTagAttribute): <NEW_LINE> <INDENT> pass
Specifies that an element is not yet, or is no longer, relevant
62598fa8dd821e528d6d8e5f
class PathArray(gui_base_original.Modifier): <NEW_LINE> <INDENT> def __init__(self, use_link=False): <NEW_LINE> <INDENT> super(PathArray, self).__init__() <NEW_LINE> self.use_link = use_link <NEW_LINE> <DEDENT> def GetResources(self): <NEW_LINE> <INDENT> _menu = "Path array" <NEW_LINE> _tip = ("Creates copies of a selected object along a selected path.\n" "First select the object, and then select the path.\n" "The path can be a polyline, B-spline or Bezier curve.") <NEW_LINE> return {'Pixmap': 'Draft_PathArray', 'MenuText': QT_TRANSLATE_NOOP("Draft_PathArray", _menu), 'ToolTip': QT_TRANSLATE_NOOP("Draft_PathArray", _tip)} <NEW_LINE> <DEDENT> def Activated(self, name=_tr("Path array")): <NEW_LINE> <INDENT> super(PathArray, self).Activated(name=name) <NEW_LINE> if not Gui.Selection.getSelectionEx(): <NEW_LINE> <INDENT> if self.ui: <NEW_LINE> <INDENT> self.ui.selectUi() <NEW_LINE> _msg(translate("draft", "Please select base and path objects")) <NEW_LINE> self.call = self.view.addEventCallback("SoEvent", gui_tool_utils.selectObject) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.proceed() <NEW_LINE> <DEDENT> <DEDENT> def proceed(self): <NEW_LINE> <INDENT> if self.call: <NEW_LINE> <INDENT> self.view.removeEventCallback("SoEvent", self.call) <NEW_LINE> <DEDENT> sel = Gui.Selection.getSelectionEx() <NEW_LINE> if sel: <NEW_LINE> <INDENT> base = sel[0].Object <NEW_LINE> path = sel[1].Object <NEW_LINE> defCount = 4 <NEW_LINE> defXlate = App.Vector(0, 0, 0) <NEW_LINE> defAlign = False <NEW_LINE> pathsubs = list(sel[1].SubElementNames) <NEW_LINE> App.ActiveDocument.openTransaction("PathArray") <NEW_LINE> Draft.makePathArray(base, path, defCount, defXlate, defAlign, pathsubs, use_link=self.use_link) <NEW_LINE> App.ActiveDocument.commitTransaction() <NEW_LINE> App.ActiveDocument.recompute() <NEW_LINE> <DEDENT> self.finish()
Gui Command for the Path array tool. Parameters ---------- use_link: bool, optional It defaults to `False`. If it is `True`, the created object will be a `Link array`.
62598fa860cbc95b06364276
class PivotsException(Exception): <NEW_LINE> <INDENT> pass
This is raised when it is impossible to divide. (cannot determine `pivots`)
62598fa857b8e32f525080b0
class ActorProcess(ActorConcurrency, Process): <NEW_LINE> <INDENT> pass
Actor on a process
62598fa832920d7e50bc5f7f
class PacketCapture(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'target': {'required': True}, 'storage_location': {'required': True}, } <NEW_LINE> _attribute_map = { 'target': {'key': 'properties.target', 'type': 'str'}, 'bytes_to_capture_per_packet': {'key': 'properties.bytesToCapturePerPacket', 'type': 'int'}, 'total_bytes_per_session': {'key': 'properties.totalBytesPerSession', 'type': 'int'}, 'time_limit_in_seconds': {'key': 'properties.timeLimitInSeconds', 'type': 'int'}, 'storage_location': {'key': 'properties.storageLocation', 'type': 'PacketCaptureStorageLocation'}, 'filters': {'key': 'properties.filters', 'type': '[PacketCaptureFilter]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(PacketCapture, self).__init__(**kwargs) <NEW_LINE> self.target = kwargs['target'] <NEW_LINE> self.bytes_to_capture_per_packet = kwargs.get('bytes_to_capture_per_packet', 0) <NEW_LINE> self.total_bytes_per_session = kwargs.get('total_bytes_per_session', 1073741824) <NEW_LINE> self.time_limit_in_seconds = kwargs.get('time_limit_in_seconds', 18000) <NEW_LINE> self.storage_location = kwargs['storage_location'] <NEW_LINE> self.filters = kwargs.get('filters', None)
Parameters that define the create packet capture operation. All required parameters must be populated in order to send to Azure. :param target: Required. The ID of the targeted resource, only VM is currently supported. :type target: str :param bytes_to_capture_per_packet: Number of bytes captured per packet, the remaining bytes are truncated. :type bytes_to_capture_per_packet: int :param total_bytes_per_session: Maximum size of the capture output. :type total_bytes_per_session: int :param time_limit_in_seconds: Maximum duration of the capture session in seconds. :type time_limit_in_seconds: int :param storage_location: Required. Describes the storage location for a packet capture session. :type storage_location: ~azure.mgmt.network.v2019_02_01.models.PacketCaptureStorageLocation :param filters: A list of packet capture filters. :type filters: list[~azure.mgmt.network.v2019_02_01.models.PacketCaptureFilter]
62598fa8baa26c4b54d4f1da
class FeatureRequestFactory(BaseFactory): <NEW_LINE> <INDENT> title = Sequence(lambda n: 'request{0}'.format(n)) <NEW_LINE> target_date = date(2018, 12, 5) <NEW_LINE> product_area = FeatureRequest.PRODUCT_AREA_BIL <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = FeatureRequest
FeatureRequest factory.
62598fa855399d3f0562644e
class UpdateReadChannelDiscussionInbox(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["channel_id", "top_msg_id", "read_max_id", "broadcast_id", "broadcast_post"] <NEW_LINE> ID = 0x1cc7de54 <NEW_LINE> QUALNAME = "types.UpdateReadChannelDiscussionInbox" <NEW_LINE> def __init__(self, *, channel_id: int, top_msg_id: int, read_max_id: int, broadcast_id: Union[None, int] = None, broadcast_post: Union[None, int] = None) -> None: <NEW_LINE> <INDENT> self.channel_id = channel_id <NEW_LINE> self.top_msg_id = top_msg_id <NEW_LINE> self.read_max_id = read_max_id <NEW_LINE> self.broadcast_id = broadcast_id <NEW_LINE> self.broadcast_post = broadcast_post <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "UpdateReadChannelDiscussionInbox": <NEW_LINE> <INDENT> flags = Int.read(data) <NEW_LINE> channel_id = Int.read(data) <NEW_LINE> top_msg_id = Int.read(data) <NEW_LINE> read_max_id = Int.read(data) <NEW_LINE> broadcast_id = Int.read(data) if flags & (1 << 0) else None <NEW_LINE> broadcast_post = Int.read(data) if flags & (1 << 0) else None <NEW_LINE> return UpdateReadChannelDiscussionInbox(channel_id=channel_id, top_msg_id=top_msg_id, read_max_id=read_max_id, broadcast_id=broadcast_id, broadcast_post=broadcast_post) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> flags = 0 <NEW_LINE> flags |= (1 << 0) if self.broadcast_id is not None else 0 <NEW_LINE> flags |= (1 << 0) if self.broadcast_post is not None else 0 <NEW_LINE> data.write(Int(flags)) <NEW_LINE> data.write(Int(self.channel_id)) <NEW_LINE> data.write(Int(self.top_msg_id)) <NEW_LINE> data.write(Int(self.read_max_id)) <NEW_LINE> if self.broadcast_id is not None: <NEW_LINE> <INDENT> data.write(Int(self.broadcast_id)) <NEW_LINE> <DEDENT> if self.broadcast_post is not None: <NEW_LINE> <INDENT> data.write(Int(self.broadcast_post)) <NEW_LINE> <DEDENT> return data.getvalue()
This object is a constructor of the base type :obj:`~pyrogram.raw.base.Update`. Details: - Layer: ``122`` - ID: ``0x1cc7de54`` Parameters: channel_id: ``int`` ``32-bit`` top_msg_id: ``int`` ``32-bit`` read_max_id: ``int`` ``32-bit`` broadcast_id (optional): ``int`` ``32-bit`` broadcast_post (optional): ``int`` ``32-bit``
62598fa892d797404e388afa
class Jslint(Linter): <NEW_LINE> <INDENT> syntax = ('javascript', 'html', 'javascriptnext') <NEW_LINE> cmd = 'jslint --terse' <NEW_LINE> config_file = ('--config', '.jslintrc', '~') <NEW_LINE> regex = r'^.+?:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)$' <NEW_LINE> tempfile_suffix = 'js' <NEW_LINE> error_stream = util.STREAM_STDOUT <NEW_LINE> selectors = { 'html': 'source.js.embedded.html' } <NEW_LINE> comment_re = r'\s*/[/*]'
Provides an interface to jslint.
62598fa899cbb53fe6830e00
class MainWindow(ApplicationWindow): <NEW_LINE> <INDENT> def __init__(self, **traits): <NEW_LINE> <INDENT> super(MainWindow, self).__init__(**traits) <NEW_LINE> exit_action = Action(name='E&xit', on_perform=self.close) <NEW_LINE> self.menu_bar_manager = MenuBarManager( MenuManager(exit_action, name='&File') ) <NEW_LINE> self.tool_bar_managers = [ ToolBarManager( exit_action, name='Tool Bar 1', show_tool_names=False ), ToolBarManager( exit_action, name='Tool Bar 2', show_tool_names=False ), ToolBarManager( exit_action, name='Tool Bar 3', show_tool_names=False ), ] <NEW_LINE> self.status_bar_manager = StatusBarManager() <NEW_LINE> self.status_bar_manager.message = 'Example application window' <NEW_LINE> return
The main application window.
62598fa87b25080760ed73d6
class Driver(object): <NEW_LINE> <INDENT> def create_service(self, service_id, service_ref): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def list_services(self): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def get_service(self, service_id): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def update_service(self, service_id): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def delete_service(self, service_id): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def create_endpoint(self, endpoint_id, endpoint_ref): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def get_endpoint(self, endpoint_id): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def list_endpoints(self): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def update_endpoint(self, endpoint_id, endpoint_ref): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def delete_endpoint(self, endpoint_id): <NEW_LINE> <INDENT> raise exception.NotImplemented() <NEW_LINE> <DEDENT> def get_catalog(self, user_id, tenant_id, metadata=None): <NEW_LINE> <INDENT> raise exception.NotImplemented()
Interface description for an Catalog driver.
62598fa84f6381625f199453
class DetachedHeadException(RepositoryException): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> RepositoryException.__init__(self, 'Not on any branch')
Exception raised when HEAD is detached (that is, there is no current branch).
62598fa8f548e778e596b4cf
class PredictionServiceStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.Predict = channel.unary_unary( '/tensorflow.serving.PredictionService/Predict', request_serializer=tensorflow__serving__client_dot_protos_dot_predict__pb2.PredictRequest.SerializeToString, response_deserializer=tensorflow__serving__client_dot_protos_dot_predict__pb2.PredictResponse.FromString, )
PredictionService provides access to machine-learned models loaded by model_servers.
62598fa832920d7e50bc5f80
class Solution: <NEW_LINE> <INDENT> def invert_tree_recursive(self, root: TreeNode) -> TreeNode: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> root.left, root.right = root.right, root.left <NEW_LINE> self.invert_tree_recursive(root.left) <NEW_LINE> self.invert_tree_recursive(root.right) <NEW_LINE> return root <NEW_LINE> <DEDENT> def invert_tree_iterative(self, root: TreeNode) -> TreeNode: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> queue = [root] <NEW_LINE> while len(queue) > 0: <NEW_LINE> <INDENT> node = queue.pop(0) <NEW_LINE> node.left, node.right = node.right, node.left <NEW_LINE> if node.left: <NEW_LINE> <INDENT> queue.append(node.left) <NEW_LINE> <DEDENT> if node.right: <NEW_LINE> <INDENT> queue.append(node.right) <NEW_LINE> <DEDENT> <DEDENT> return root
翻转二叉树
62598fa81b99ca400228f4c5