code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class User(BASE): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __tablename__ = 'Users' <NEW_LINE> identifier = Column('user_id', Integer, primary_key=True) <NEW_LINE> username = Column('username', String) <NEW_LINE> password = Column('password', String) <NEW_LINE> privileged = Column('privileged', Integer) <NEW_LINE> last_login = Column('last_login', DateTime) <NEW_LINE> email = Column('email', String) <NEW_LINE> disabled = Column('disabled', Integer) <NEW_LINE> api_key = Column('apikey', String) <NEW_LINE> gpg_key = Column('gpg_key', String) <NEW_LINE> group_id = Column('group_id', Integer, ForeignKey('Groups.group_id')) <NEW_LINE> default_group = relationship('Group', primaryjoin='User.group_id==Group.identifier', lazy='joined') <NEW_LINE> activated = Column('activated', DateTime) <NEW_LINE> activation_sent = Column('activation_sent', DateTime) <NEW_LINE> name = Column('name', String) <NEW_LINE> sirname = Column('sirname', String) <NEW_LINE> password_plain = None <NEW_LINE> activation_str = Column('activation_str', String) <NEW_LINE> @property <NEW_LINE> def display_name(self): <NEW_LINE> <INDENT> return '{0} {1}'.format(self.sirname, self.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def allowed(self): <NEW_LINE> <INDENT> if self.disabled == 0 and self.activated: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_api_key(self): <NEW_LINE> <INDENT> if self.api_key is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> def validate(self): <NEW_LINE> <INDENT> ObjectValidator.validateAlNum(self, 'username', minLength=3) <NEW_LINE> if not (self.password == 'EXTERNALAUTH') and re.match('^[0-9a-f]{40}$', self.password) is None: <NEW_LINE> <INDENT> ObjectValidator.validateRegex(self, 'password', (r"(?=^.{8,}$)(?=.*[a-z])(?=.*[A-Z])" + r"(?=.*[0-9])(?=.*[\W_])(?=^.*[^\s].*$).*$"), ('Password has to be set and contain Upper and' + 'Lower cases, symbols and numbers and have' + ' at least a length of 8')) <NEW_LINE> <DEDENT> ObjectValidator.validateDigits(self, 'privileged', minimal=0, maximal=1) <NEW_LINE> ObjectValidator.validateDigits(self, 'disabled', minimal=0, maximal=1) <NEW_LINE> ObjectValidator.validateEmailAddress(self, 'email') <NEW_LINE> ObjectValidator.validateAlNum(self, 'name', minLength=3, withSymbols=True) <NEW_LINE> ObjectValidator.validateAlNum(self, 'sirname', minLength=3, withSymbols=True) <NEW_LINE> if not self.last_login is None: <NEW_LINE> <INDENT> ObjectValidator.validateDateTime(self, 'last_login') <NEW_LINE> <DEDENT> return ObjectValidator.isObjectValid(self)
This is a container class for the USERS table.
62598fb510dbd63aa1c70c87
class Die: <NEW_LINE> <INDENT> def __init__(self, num_sides=6): <NEW_LINE> <INDENT> self.num_sides = num_sides <NEW_LINE> <DEDENT> def roll(self): <NEW_LINE> <INDENT> return randint(1, self.num_sides)
A class representing a single die.
62598fb53d592f4c4edbaf92
class Opportunities(object): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> <DEDENT> def query(self, **kwargs): <NEW_LINE> <INDENT> response = self._get(path='/do/query', params=kwargs) <NEW_LINE> result = response.get('result') <NEW_LINE> if result['total_results'] == 0: <NEW_LINE> <INDENT> result['opportunity'] = [] <NEW_LINE> <DEDENT> elif result['total_results'] == 1: <NEW_LINE> <INDENT> result['opportunity'] = [result['opportunity']] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def create_by_email(self, prospect_email=None, name=None, value=None, probability=None, **kwargs): <NEW_LINE> <INDENT> kwargs.update({'name': name, 'value': value, 'probability': probability}) <NEW_LINE> response = self._post( path='/do/create/prospect_email/{prospect_email}'.format(prospect_email=prospect_email), params=kwargs) <NEW_LINE> return response <NEW_LINE> <DEDENT> def create_by_id(self, prospect_id=None, name=None, value=None, probability=None, **kwargs): <NEW_LINE> <INDENT> kwargs.update({'name': name, 'value': value, 'probability': probability}) <NEW_LINE> response = self._post( path='/do/create/prospect_id/{prospect_id}'.format(prospect_id=prospect_id), params=kwargs) <NEW_LINE> return response <NEW_LINE> <DEDENT> def read(self, id=None): <NEW_LINE> <INDENT> response = self._post(path='/do/read/id/{id}'.format(id=id)) <NEW_LINE> return response <NEW_LINE> <DEDENT> def update(self, id=None): <NEW_LINE> <INDENT> response = self._post(path='/do/update/id/{id}'.format(id=id)) <NEW_LINE> return response <NEW_LINE> <DEDENT> def delete(self, id=None): <NEW_LINE> <INDENT> response = self._post(path='/do/delete/id/{id}'.format(id=id)) <NEW_LINE> return response <NEW_LINE> <DEDENT> def undelete(self, id=None): <NEW_LINE> <INDENT> response = self._post(path='/do/undelete/id/{id}'.format(id=id)) <NEW_LINE> return response <NEW_LINE> <DEDENT> def _get(self, object_name='opportunity', path=None, params=None): <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> response = self.client.get(object_name=object_name, path=path, params=params) <NEW_LINE> return response <NEW_LINE> <DEDENT> def _post(self, object_name='opportunity', path=None, params=None): <NEW_LINE> <INDENT> if params is None: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> response = self.client.post(object_name=object_name, path=path, params=params) <NEW_LINE> return response
A class to query and use Pardot opportunities. Opportunity field reference: http://developer.pardot.com/kb/api-version-3/object-field-references/#opportunity
62598fb591f36d47f2230f11
class LegacyTestBodhiOverrideUntagged(Base): <NEW_LINE> <INDENT> expected_title = "bodhi.buildroot_override.untag" <NEW_LINE> expected_subti = "lmacken expired a buildroot override for fedmsg-1.0-1" <NEW_LINE> expected_link = "https://bodhi.fedoraproject.org/overrides/fedmsg-1.0-1" <NEW_LINE> expected_icon = "https://apps.fedoraproject.org/img/icons/bodhi.png" <NEW_LINE> expected_secondary_icon = "https://seccdn.libravatar.org/avatar/" + "203f6cb95b44b5d38aa21425b066dd522d3e19d8919cf4b339f29e0ea7f03e9b?s=64&d=retro" <NEW_LINE> expected_usernames = set(['lmacken']) <NEW_LINE> expected_packages = set(['fedmsg']) <NEW_LINE> expected_objects = set(['packages/fedmsg']) <NEW_LINE> msg = { "i": 1, "timestamp": 1344964395.207541, "topic": "org.fedoraproject.stg.bodhi.buildroot_override.untag", "msg": { "override": { "build": "fedmsg-1.0-1", "submitter": "lmacken", } } }
The `Bodhi Updates System <https://bodhi.fedoraproject.org>`_ publishes messages on this topic whenever a user explicitly removes a previously requested buildroot override.
62598fb50fa83653e46f4fb1
class Request(object): <NEW_LINE> <INDENT> def __init__(self, params=None): <NEW_LINE> <INDENT> Logger.logDebug(params) <NEW_LINE> self.set_action_id('__start__') <NEW_LINE> if params is None: <NEW_LINE> <INDENT> self.set_params({}) <NEW_LINE> <DEDENT> elif type(params) is str: <NEW_LINE> <INDENT> self.set_params(HttpUtils.getUrlParams(params)) <NEW_LINE> <DEDENT> elif type(params) is dict: <NEW_LINE> <INDENT> self.set_params(params) <NEW_LINE> <DEDENT> if self.get_params().has_key('actionId') and self.get_params()['actionId'] != '': <NEW_LINE> <INDENT> self.set_action_id(self.get_params()['actionId']) <NEW_LINE> <DEDENT> if self.get_params().has_key('data') and self.get_params()['data'] != '': <NEW_LINE> <INDENT> self.set_data(AddonUtils.decodeData(self.get_params()['data'])) <NEW_LINE> <DEDENT> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return self.__data <NEW_LINE> <DEDENT> def set_data(self, value): <NEW_LINE> <INDENT> self.__data = value <NEW_LINE> <DEDENT> def del_data(self): <NEW_LINE> <INDENT> del self.__data <NEW_LINE> <DEDENT> def get_action_id(self): <NEW_LINE> <INDENT> return self.__actionId <NEW_LINE> <DEDENT> def get_params(self): <NEW_LINE> <INDENT> return self.__params <NEW_LINE> <DEDENT> def set_action_id(self, value): <NEW_LINE> <INDENT> self.__actionId = value <NEW_LINE> <DEDENT> def set_params(self, value): <NEW_LINE> <INDENT> self.__params = value <NEW_LINE> <DEDENT> def del_action_id(self): <NEW_LINE> <INDENT> del self.__actionId <NEW_LINE> <DEDENT> def del_params(self): <NEW_LINE> <INDENT> del self.__params <NEW_LINE> <DEDENT> actionId = property(get_action_id, set_action_id, del_action_id, "actionId's docstring") <NEW_LINE> params = property(get_params, set_params, del_params, "params's docstring") <NEW_LINE> data = property(get_data, set_data, del_data, "data's docstring")
classdocs
62598fb5a05bb46b3848a93d
class InitializeUserForm(forms.Form): <NEW_LINE> <INDENT> nickname = forms.CharField(widget=forms.TextInput(attrs={'size': 25})) <NEW_LINE> email = forms.EmailField() <NEW_LINE> is_group = forms.BooleanField(required=False)
For adding a user account and regrecord for a person before they have actually filled out any form or given any info. Designed for pre-reg'ing conference lists and the like. (Made for openSF in 2012)
62598fb54428ac0f6e6585f3
class AccountAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('user', 'email', 'first_name', 'last_name') <NEW_LINE> search_fields = ('user', 'email', 'first_name', 'last_name') <NEW_LINE> def formfield_for_dbfield(self, db_field, **kwargs): <NEW_LINE> <INDENT> formfield = ( super(AccountAdmin, self) .formfield_for_dbfield(db_field, **kwargs) ) <NEW_LINE> if db_field.name == 'bio': <NEW_LINE> <INDENT> formfield.widget = forms.Textarea(attrs=formfield.widget.attrs) <NEW_LINE> <DEDENT> return formfield
Admin class for Account model
62598fb5cc0a2c111447b0e5
class CompoundSeqExpression(object): <NEW_LINE> <INDENT> def __init__(self, exprseq_list): <NEW_LINE> <INDENT> self.exprseq_list = exprseq_list <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.exprseq_list) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> return self.exprseq_list[idx]
A class that represent a list of Expression Sequence.
62598fb556ac1b37e63022bd
class MultipleInstancesException(Exception): <NEW_LINE> <INDENT> pass
Exception for multiple possible instances found in pdf.
62598fb5a8370b77170f04b0
class LoginTransaction_Node(transactions.LoginTransaction, AbstractNodeTransaction): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> State = LoginTransactionState_Node <NEW_LINE> @unpauses_incoming <NEW_LINE> def on_begin(self): <NEW_LINE> <INDENT> assert isinstance(self.message.username, str), repr(self.message.username) <NEW_LINE> <DEDENT> def on_end(self): <NEW_LINE> <INDENT> _host = self.message.src <NEW_LINE> _message = self.message <NEW_LINE> _ack = self.message_ack = self.message.reply() <NEW_LINE> if _host is None: <NEW_LINE> <INDENT> _ack.ack_result = 'fail' <NEW_LINE> <DEDENT> elif self.manager.app.known_hosts.is_peer_alive(_host.uuid): <NEW_LINE> <INDENT> _ack.ack_result = 'dual login' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _ack.ack_result = 'ok' <NEW_LINE> _ack.ack_host_uuid = _host.uuid <NEW_LINE> with db.RDB() as rdbw: <NEW_LINE> <INDENT> user_groups = list(Queries.Inhabitants .get_groups_for_user(_host.user.name, rdbw)) <NEW_LINE> thost_uuids = {h.uuid for h in TrustedQueries.HostAtNode .get_all_trusted_hosts( rdbw=rdbw)} <NEW_LINE> <DEDENT> is_trusted_host = _host.uuid in thost_uuids <NEW_LINE> _ack.ack_username = self.message.src.user.name <NEW_LINE> _ack.ack_groups = user_groups <NEW_LINE> logger.debug('For user %r, %s %r, groups are: %r', _ack.ack_username, 'trusted host' if is_trusted_host else 'host', _host.uuid, _ack.ack_groups) <NEW_LINE> _req = _message.cert_request <NEW_LINE> if _req is not None: <NEW_LINE> <INDENT> assert isinstance(_req, crypto.X509Req), repr(_req) <NEW_LINE> subj = _req.get_subject() <NEW_LINE> if not ssl.validate_host_req(_req): <NEW_LINE> <INDENT> logger.warning('%s probably trying to spoof himself: %r', _host.uuid, str(subj)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subj.commonName = str(_host.uuid) <NEW_LINE> node_cert = get_common().ssl_cert <NEW_LINE> node_key = get_common().ssl_pkey <NEW_LINE> _key_duration = ssl.OPENSSL_TRUSTED_HOST_KEY_DURATION if is_trusted_host else ssl.OPENSSL_HOST_KEY_DURATION <NEW_LINE> _ack.ack_ssl_cert = ssl.createCertificate( _req, node_cert, node_key, notAfter=long(_key_duration.total_seconds())) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.manager.post_message(self.message_ack)
LOGIN transaction on the Node.
62598fb597e22403b383afd8
class FormsAdminUserPermission(BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return AdminUser.objects.filter( user_id=request.user ).exists()
Allow requests for logged-in admin users
62598fb58a43f66fc4bf224d
class AddressesUUIDTemplate(xmlutil.TemplateBuilder): <NEW_LINE> <INDENT> def construct(self): <NEW_LINE> <INDENT> root = xmlutil.TemplateElement('addresses', selector='addresses') <NEW_LINE> elem = xmlutil.SubTemplateElement(root, 'network', selector=xmlutil.get_items) <NEW_LINE> make_network(elem) <NEW_LINE> return xmlutil.SlaveTemplate(root, 1, nsmap=network_nsmap)
Not currently used -JLH.
62598fb55166f23b2e2434ae
@attr.s(auto_attribs=True, slots=True, frozen=True) <NEW_LINE> class Server: <NEW_LINE> <INDENT> host: bytes <NEW_LINE> port: int <NEW_LINE> priority: int = 0 <NEW_LINE> weight: int = 0 <NEW_LINE> expires: int = 0
Our record of an individual server which can be tried to reach a destination. Attributes: host: target hostname port: priority: weight: expires: when the cache should expire this record - in *seconds* since the epoch
62598fb5283ffb24f3cf3960
class TestRepr(BaseDataset): <NEW_LINE> <INDENT> def test_repr_open(self): <NEW_LINE> <INDENT> ds = self.f.create_dataset('foo', (4,)) <NEW_LINE> self.assertIsInstance(repr(ds), basestring) <NEW_LINE> self.f.close() <NEW_LINE> self.assertIsInstance(repr(ds), basestring)
Feature: repr(Dataset) behaves sensibly
62598fb5fff4ab517ebcd8b9
class EEAgentClient(object): <NEW_LINE> <INDENT> def __init__(self, dashi): <NEW_LINE> <INDENT> self.dashi = dashi <NEW_LINE> <DEDENT> def launch_process(self, eeagent, upid, round, run_type, parameters): <NEW_LINE> <INDENT> self.dashi.fire(eeagent, "launch_process", u_pid=upid, round=round, run_type=run_type, parameters=parameters) <NEW_LINE> <DEDENT> def restart_process(self, eeagent, upid, round): <NEW_LINE> <INDENT> return self.dashi.fire(eeagent, "restart_process", u_pid=upid, round=round) <NEW_LINE> <DEDENT> def terminate_process(self, eeagent, upid, round): <NEW_LINE> <INDENT> return self.dashi.fire(eeagent, "terminate_process", u_pid=upid, round=round) <NEW_LINE> <DEDENT> def cleanup_process(self, eeagent, upid, round): <NEW_LINE> <INDENT> return self.dashi.fire(eeagent, "cleanup", u_pid=upid, round=round)
Client that uses ION to send messages to EEAgents
62598fb5167d2b6e312b7046
class PkgConfig(PackagerBase): <NEW_LINE> <INDENT> name = 'pkgconfig' <NEW_LINE> pkgtype = 'pkgconfig' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> PackagerBase.__init__(self) <NEW_LINE> <DEDENT> def supported(self): <NEW_LINE> <INDENT> return sysutils.which('pkg-config') is not None <NEW_LINE> <DEDENT> def _package_exists(self, pkgname, comparator=">=", required_version=None): <NEW_LINE> <INDENT> return self._package_installed(pkgname, comparator, required_version) <NEW_LINE> <DEDENT> def _package_installed(self, pkgname, comparator=">=", required_version=None): <NEW_LINE> <INDENT> installed_version = self.get_version_from_pkgconfig(pkgname) <NEW_LINE> if not installed_version: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if required_version is None or vcompare(comparator, installed_version, required_version): <NEW_LINE> <INDENT> return True <NEW_LINE> self.log.debug("Package {pkg} found by pkg-config.".format(pkg=pkgname)) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _package_install(self, pkgname, comparator=">=", required_version=None): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def _package_update(self, pkgname, comparator=">=", required_version=None): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def get_version_from_pkgconfig(self, pkgname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ver = subprocess.check_output(["pkg-config", "--modversion", pkgname], stderr=subprocess.STDOUT).strip() <NEW_LINE> self.log.debug("Package {0} has version {1} in pkg-config".format(pkgname, ver)) <NEW_LINE> return ver <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.log.error("Running `pkg-config --modversion` failed.") <NEW_LINE> self.log.obnoxious(str(e)) <NEW_LINE> <DEDENT> return False
Uses pkg-config. Can't really install stuff, but is useful for finding out if something is already installed.
62598fb560cbc95b06364418
class DeleteTest(unittest.TestCase): <NEW_LINE> <INDENT> loaded_db = 0 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> load_database("GenBank/cor6_6.gb") <NEW_LINE> self.server = BioSeqDatabase.open_database(driver=DBDRIVER, user=DBUSER, passwd=DBPASSWD, host=DBHOST, db=TESTDB) <NEW_LINE> self.db = self.server["biosql-test"] <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.server.close() <NEW_LINE> destroy_database() <NEW_LINE> del self.db <NEW_LINE> del self.server <NEW_LINE> <DEDENT> def test_server(self): <NEW_LINE> <INDENT> server = self.server <NEW_LINE> self.assertIn("biosql-test", server) <NEW_LINE> self.assertEqual(1, len(server)) <NEW_LINE> self.assertEqual(["biosql-test"], list(server.keys())) <NEW_LINE> del server["biosql-test"] <NEW_LINE> self.assertEqual(0, len(server)) <NEW_LINE> try: <NEW_LINE> <INDENT> del server["non-existant-name"] <NEW_LINE> assert False, "Should have raised KeyError" <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def test_del_db_items(self): <NEW_LINE> <INDENT> db = self.db <NEW_LINE> items = list(db.values()) <NEW_LINE> keys = list(db) <NEW_LINE> l = len(items) <NEW_LINE> for seq_id in self.db.keys(): <NEW_LINE> <INDENT> sql = "SELECT seqfeature_id from seqfeature where bioentry_id = '%s'" <NEW_LINE> seqfeatures = self.db.adaptor.execute_and_fetchall(sql % (seq_id)) <NEW_LINE> del db[seq_id] <NEW_LINE> self.assertEqual(seq_id in db, False) <NEW_LINE> if len(seqfeatures): <NEW_LINE> <INDENT> rows_d = self.db.adaptor.execute_and_fetchall(sql % (seq_id)) <NEW_LINE> self.assertEqual(len(rows_d), 0)
Test proper deletion of entries from a database.
62598fb599cbb53fe6830fa9
class BackProjection: <NEW_LINE> <INDENT> def __init__(self, R, Radj, image_size: tuple): <NEW_LINE> <INDENT> def Rfun(x: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> x_np = x.detach().cpu().numpy() <NEW_LINE> y_np = R(x_np) <NEW_LINE> return x.new(y_np) <NEW_LINE> <DEDENT> def Radjfun(y: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> y_np = y.detach().cpu().numpy() <NEW_LINE> x_np = Radj(y_np) <NEW_LINE> return y.new(x_np) <NEW_LINE> <DEDENT> self.R = Rfun <NEW_LINE> self.Radj = Radjfun <NEW_LINE> self.image_size = image_size <NEW_LINE> self.Op = LinearOperator.apply <NEW_LINE> <DEDENT> def __call__(self, x: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> nimg = x.shape[0] <NEW_LINE> y = x.new_ones((nimg, 1, *self.image_size)) <NEW_LINE> for k in range(nimg): <NEW_LINE> <INDENT> y[k][0] = self.Op(x[k][0], self.Radj, self.R) <NEW_LINE> <DEDENT> return y
Backprojection class to use with torch. Runs on CPU.
62598fb57047854f4633f4af
class RSAVerifier(base.Verifier): <NEW_LINE> <INDENT> def __init__(self, public_key): <NEW_LINE> <INDENT> self._pubkey = public_key <NEW_LINE> <DEDENT> @_helpers.copy_docstring(base.Verifier) <NEW_LINE> def verify(self, message, signature): <NEW_LINE> <INDENT> message = _helpers.to_bytes(message) <NEW_LINE> try: <NEW_LINE> <INDENT> self._pubkey.verify(signature, message, _PADDING, _SHA256) <NEW_LINE> return True <NEW_LINE> <DEDENT> except (ValueError, cryptography.exceptions.InvalidSignature): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, public_key): <NEW_LINE> <INDENT> public_key_data = _helpers.to_bytes(public_key) <NEW_LINE> if _CERTIFICATE_MARKER in public_key_data: <NEW_LINE> <INDENT> cert = cryptography.x509.load_pem_x509_certificate( public_key_data, _BACKEND ) <NEW_LINE> pubkey = cert.public_key() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pubkey = serialization.load_pem_public_key(public_key_data, _BACKEND) <NEW_LINE> <DEDENT> return cls(pubkey)
Verifies RSA cryptographic signatures using public keys. Args: public_key ( cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey): The public key used to verify signatures.
62598fb5379a373c97d990e9
class CreateCustomerView(Frame): <NEW_LINE> <INDENT> def __init__(self, master, controller): <NEW_LINE> <INDENT> Frame.__init__(self,master) <NEW_LINE> self.master = master <NEW_LINE> self.controller = controller <NEW_LINE> self.entries = [] <NEW_LINE> self.initialize_ui() <NEW_LINE> <DEDENT> def initialize_ui(self): <NEW_LINE> <INDENT> default_padding = {'padx': 10, 'pady' : 10} <NEW_LINE> labels = ["Name", "Surname", "Email", "Cellphone"] <NEW_LINE> for label in labels: <NEW_LINE> <INDENT> frame = Frame(self) <NEW_LINE> Label(frame, text = label, style="BW.TLabel").pack(default_padding, side = LEFT) <NEW_LINE> entry = Entry(frame) <NEW_LINE> entry.pack(default_padding, side = RIGHT) <NEW_LINE> self.entries.append(entry) <NEW_LINE> frame.pack(expand = True, fill = "x", side = TOP) <NEW_LINE> <DEDENT> button_frame = Frame(self) <NEW_LINE> Button(button_frame, text = "Create Customer", command = self.save_customer).pack(default_padding) <NEW_LINE> button_frame.pack(expand = True, fill = "x") <NEW_LINE> <DEDENT> def save_customer(self): <NEW_LINE> <INDENT> print("saving customer") <NEW_LINE> args = ["name", "surname", "email", "cellphone"] <NEW_LINE> customer = dict(zip(args, (e.get() for e in self.entries))) <NEW_LINE> print (customer) <NEW_LINE> return self.controller.save_customer(customer)
View to enter customer information
62598fb57d847024c075c491
class ConfigurationSetup(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> sys_config = os.path.join('/etc', APPNAME, '%s.conf' % APPNAME) <NEW_LINE> user_config = os.path.join(HOME, '.%s.conf' % APPNAME) <NEW_LINE> if os.path.exists(user_config): <NEW_LINE> <INDENT> self.config_file = user_config <NEW_LINE> <DEDENT> elif os.path.exists(sys_config): <NEW_LINE> <INDENT> self.config_file = sys_config <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = ( 'Configuration file for "%s" was not found. Valid' ' configuration files are [ %s ] or [ %s ]' % (APPNAME, user_config, sys_config) ) <NEW_LINE> exit_failure(msg) <NEW_LINE> <DEDENT> self.check_perms() <NEW_LINE> <DEDENT> def check_perms(self): <NEW_LINE> <INDENT> if os.path.isfile(self.config_file): <NEW_LINE> <INDENT> confpath = self.config_file <NEW_LINE> if os.path.isfile(os.path.realpath(confpath)): <NEW_LINE> <INDENT> mode = oct(stat.S_IMODE(os.stat(confpath).st_mode)) <NEW_LINE> if not any([mode == '0600', mode == '0400']): <NEW_LINE> <INDENT> raise SystemExit( 'To use a configuration file the permissions' ' need to be "0600" or "0400"' ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> msg = 'Config file %s not found,' % self.config_file <NEW_LINE> exit_failure(msg) <NEW_LINE> <DEDENT> <DEDENT> def config_args(self, section='default'): <NEW_LINE> <INDENT> if sys.version_info >= (2, 7, 0): <NEW_LINE> <INDENT> parser = ConfigParser.SafeConfigParser(allow_no_value=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parser = ConfigParser.SafeConfigParser() <NEW_LINE> <DEDENT> parser.optionxform = str <NEW_LINE> args = {} <NEW_LINE> try: <NEW_LINE> <INDENT> parser.read(self.config_file) <NEW_LINE> for name, value in parser.items(section): <NEW_LINE> <INDENT> name = name.encode('utf8') <NEW_LINE> if any([value == 'False', value == 'false']): <NEW_LINE> <INDENT> args[name] = False <NEW_LINE> <DEDENT> elif any([value == 'True', value == 'true']): <NEW_LINE> <INDENT> args[name] = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args[name] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return args
Parse arguments from a Configuration file. Note that anything can be set as a 'Section' in the argument file.
62598fb5dc8b845886d5368b
class Transaction(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Transaction' <NEW_LINE> verbose_name_plural = 'Transactions' <NEW_LINE> <DEDENT> ACTION_TYPE_CREATED = 'CREATED' <NEW_LINE> ACTION_TYPE_DEPOSITED = 'DEPOSITED' <NEW_LINE> ACTION_TYPE_WITHDRAWN = 'WITHDRAWN' <NEW_LINE> ACTION_TYPE_CHOICES = ( (ACTION_TYPE_CREATED, 'Created'), (ACTION_TYPE_DEPOSITED, 'Deposited'), (ACTION_TYPE_WITHDRAWN, 'Withdrawn'), ) <NEW_LINE> REFERENCE_TYPE_BANK_TRANSFER = 'BANK_TRANSFER' <NEW_LINE> REFERENCE_TYPE_CASH = 'CASH' <NEW_LINE> REFERENCE_TYPE_NONE = 'NONE' <NEW_LINE> REFERENCE_TYPE_CHOICES = ( (REFERENCE_TYPE_BANK_TRANSFER, 'Bank Transfer'), (REFERENCE_TYPE_CASH, 'Cash'), (REFERENCE_TYPE_NONE, 'None'), ) <NEW_LINE> user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, help_text='User who performed the action.', ) <NEW_LINE> caja = models.ForeignKey(Caja, models.CASCADE) <NEW_LINE> ammount = models.IntegerField(default=0) <NEW_LINE> transaction_type = models.CharField( max_length=30, choices=ACTION_TYPE_CHOICES, default='Withdrawn' ) <NEW_LINE> reference_type = models.CharField( max_length=30, choices=REFERENCE_TYPE_CHOICES, default=REFERENCE_TYPE_NONE, ) <NEW_LINE> date = models.DateField() <NEW_LINE> concept = models.CharField(max_length=100) <NEW_LINE> detail = models.CharField(max_length=250) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'Transaccion: %s' % self.concept <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create(cls, user, caja, t_type, delta, asof, concept=None, reference_type=None, detail=None): <NEW_LINE> <INDENT> assert asof is not None <NEW_LINE> if (t_type == cls.ACTION_TYPE_DEPOSITED and reference_type is None): <NEW_LINE> <INDENT> raise ValidationError({ 'reference_type': 'required for deposit.', }) <NEW_LINE> <DEDENT> if reference_type is None: <NEW_LINE> <INDENT> reference_type = cls.REFERENCE_TYPE_NONE <NEW_LINE> <DEDENT> if concept is None: <NEW_LINE> <INDENT> reference = '' <NEW_LINE> <DEDENT> if detail is None: <NEW_LINE> <INDENT> detail = '' <NEW_LINE> <DEDENT> return cls.objects.create( date=asof, user=user, caja=caja, transaction_type=t_type, ammount=delta, concept=concept, reference_type=reference_type, detail=detail, )
This deals with money operations. deposits, extractions, loans and transferences
62598fb5e5267d203ee6b9d2
class TransactionHandler(Handler): <NEW_LINE> <INDENT> SUPPORTED_PROTOCOL = TransactionMessage.protocol_id <NEW_LINE> def setup(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handle(self, message: Message) -> None: <NEW_LINE> <INDENT> tx_message = cast(TransactionMessage, message) <NEW_LINE> if ( tx_message.performative == TransactionMessage.Performative.SUCCESSFUL_SIGNING ): <NEW_LINE> <INDENT> self.context.logger.info( "[{}]: transaction confirmed by decision maker, sending to controller.".format( self.context.agent_name ) ) <NEW_LINE> game = cast(Game, self.context.game) <NEW_LINE> tx_counterparty_signature = cast( str, tx_message.info.get("tx_counterparty_signature") ) <NEW_LINE> tx_counterparty_id = cast(str, tx_message.info.get("tx_counterparty_id")) <NEW_LINE> if (tx_counterparty_signature is not None) and ( tx_counterparty_id is not None ): <NEW_LINE> <INDENT> tx_id = tx_message.tx_id + "_" + tx_counterparty_id <NEW_LINE> msg = TacMessage( performative=TacMessage.Performative.TRANSACTION, tx_id=tx_id, tx_sender_addr=tx_message.tx_sender_addr, tx_counterparty_addr=tx_message.tx_counterparty_addr, amount_by_currency_id=tx_message.tx_amount_by_currency_id, tx_sender_fee=tx_message.tx_sender_fee, tx_counterparty_fee=tx_message.tx_counterparty_fee, quantities_by_good_id=tx_message.tx_quantities_by_good_id, tx_sender_signature=tx_message.signed_payload.get("tx_signature"), tx_counterparty_signature=tx_message.info.get( "tx_counterparty_signature" ), tx_nonce=tx_message.info.get("tx_nonce"), ) <NEW_LINE> self.context.outbox.put_message( to=game.conf.controller_addr, sender=self.context.agent_address, protocol_id=TacMessage.protocol_id, message=TacSerializer().encode(msg), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.context.logger.warning( "[{}]: transaction has no counterparty id or signature!".format( self.context.agent_name ) ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.context.logger.info( "[{}]: transaction was not successful.".format(self.context.agent_name) ) <NEW_LINE> <DEDENT> <DEDENT> def teardown(self) -> None: <NEW_LINE> <INDENT> pass
This class implements the transaction handler.
62598fb5b7558d5895463701
class TestNotificationThread(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testNotificationThread(self): <NEW_LINE> <INDENT> pass
NotificationThread unit test stubs
62598fb55fdd1c0f98e5e062
class ExtendedAffineWeylGroupW0P(GroupSemidirectProduct, BindableClass): <NEW_LINE> <INDENT> def __init__(self, E): <NEW_LINE> <INDENT> def twist(w,l): <NEW_LINE> <INDENT> return E.exp_lattice()(w.action(l.value)) <NEW_LINE> <DEDENT> GroupSemidirectProduct.__init__(self, E.classical_weyl(), E.exp_lattice(), twist=twist, act_to_right=True, prefix1=E._prefixt, print_tuple=E._print_tuple, category=E.Realizations()) <NEW_LINE> self._style = "W0P" <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return self.realization_of()._repr_() + " realized by " + super(ExtendedAffineWeylGroup_Class.ExtendedAffineWeylGroupW0P, self)._repr_() <NEW_LINE> <DEDENT> def S0(self): <NEW_LINE> <INDENT> E = self.realization_of() <NEW_LINE> return self((E._special_reflection,E.exp_lattice()(E.lattice()(-E._special_translation)))) <NEW_LINE> <DEDENT> def simple_reflection(self, i): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> return self.S0() <NEW_LINE> <DEDENT> E = self.realization_of() <NEW_LINE> return self.from_classical_weyl(E.classical_weyl().simple_reflection(i)) <NEW_LINE> <DEDENT> @cached_method <NEW_LINE> def simple_reflections(self): <NEW_LINE> <INDENT> return Family(self.realization_of().cartan_type().index_set(), lambda i: self.simple_reflection(i)) <NEW_LINE> <DEDENT> def from_classical_weyl(self, w): <NEW_LINE> <INDENT> return self((w,self.cartesian_factors()[1].one())) <NEW_LINE> <DEDENT> def from_translation(self, la): <NEW_LINE> <INDENT> return self((self.cartesian_factors()[0].one(),self.realization_of().exp_lattice()(la)))
Extended affine Weyl group, realized as the semidirect product of the finite Weyl group by the translation lattice. INPUT: - `E` -- A parent with realization in :class:`ExtendedAffineWeylGroup_Class` EXAMPLES:: sage: ExtendedAffineWeylGroup(['A',2,1]).W0P() Extended affine Weyl group of type ['A', 2, 1] realized by Semidirect product of Weyl Group of type ['A', 2] (as a matrix group acting on the coweight lattice) acting on Multiplicative form of Coweight lattice of the Root system of type ['A', 2]
62598fb5498bea3a75a57bf5
@_TFVolume.register("bessel-approx") <NEW_LINE> class TFBesselApproxVolume(_TFVolume): <NEW_LINE> <INDENT> def __init__( self, log_scale: bool = True, volume_temperature: float = 1.0, intersection_temperature: float = 1.0, ) -> None: <NEW_LINE> <INDENT> super().__init__(log_scale) <NEW_LINE> self.volume_temperature = volume_temperature <NEW_LINE> self.intersection_temperature = intersection_temperature <NEW_LINE> <DEDENT> def __call__(self, box_tensor: TFBoxTensor) -> tf.Tensor: <NEW_LINE> <INDENT> return tf_bessel_volume_approx( box_tensor, volume_temperature=self.volume_temperature, intersection_temperature=self.intersection_temperature, log_scale=self.log_scale, )
Uses the Softplus as an approximation of Bessel function.
62598fb54a966d76dd5eefac
class UserModelTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> User.query.delete() <NEW_LINE> Message.query.delete() <NEW_LINE> FollowersFollowee.query.delete() <NEW_LINE> self.u1 = User( id=1000, email="test@test.com", username="testuser", password=HASHED_PASSWORD ) <NEW_LINE> db.session.add(self.u1) <NEW_LINE> db.session.commit() <NEW_LINE> self.client = app.test_client() <NEW_LINE> <DEDENT> def test_user_model(self): <NEW_LINE> <INDENT> self.assertEqual(len(self.u1.messages), 0) <NEW_LINE> self.assertEqual(len(self.u1.followers), 0) <NEW_LINE> <DEDENT> def test_repr(self): <NEW_LINE> <INDENT> self.assertEqual(str(self.u1), "<User #1000: testuser, test@test.com>") <NEW_LINE> <DEDENT> def test_is_following(self): <NEW_LINE> <INDENT> u2 = User( id=2000, email="test2@test.com", username="testuser2", password="HASHED_PASSWORD" ) <NEW_LINE> db.session.add(u2) <NEW_LINE> db.session.commit() <NEW_LINE> f = FollowersFollowee(followee_id=1000, follower_id=2000) <NEW_LINE> db.session.add(f) <NEW_LINE> db.session.commit() <NEW_LINE> self.assertTrue(self.u1.is_following(u2)) <NEW_LINE> self.assertFalse(u2.is_following(self.u1)) <NEW_LINE> <DEDENT> def test_is_followed_by(self): <NEW_LINE> <INDENT> u2 = User( id=2000, email="test2@test.com", username="testuser2", password="HASHED_PASSWORD" ) <NEW_LINE> db.session.add(u2) <NEW_LINE> db.session.commit() <NEW_LINE> f = FollowersFollowee(followee_id=2000, follower_id=1000) <NEW_LINE> db.session.add(f) <NEW_LINE> db.session.commit() <NEW_LINE> self.assertTrue(self.u1.is_followed_by(u2)) <NEW_LINE> self.assertFalse(u2.is_followed_by(self.u1)) <NEW_LINE> <DEDENT> def test_user_create(self): <NEW_LINE> <INDENT> self.assertIs(User.query.get(1000), self.u1) <NEW_LINE> u2 = User( id=2000, email="test@test.com", username="testuser2", password="HASHED_PASSWORD" ) <NEW_LINE> u3 = User( id=3000, email="test2@test.com", username="testuser", password="HASHED_PASSWORD" ) <NEW_LINE> u4 = User( id=4000, email="test2@test.com", username="testuser" ) <NEW_LINE> db.session.add(u2) <NEW_LINE> self.assertRaises(IntegrityError, db.session.commit) <NEW_LINE> db.session.rollback() <NEW_LINE> db.session.add(u3) <NEW_LINE> self.assertRaises(IntegrityError, db.session.commit) <NEW_LINE> db.session.rollback() <NEW_LINE> db.session.add(u4) <NEW_LINE> self.assertRaises(IntegrityError, db.session.commit) <NEW_LINE> db.session.rollback() <NEW_LINE> <DEDENT> def test_user_auth(self): <NEW_LINE> <INDENT> self.assertIs(User.authenticate(username="testuser", password="123456"), self.u1) <NEW_LINE> self.assertFalse(User.authenticate(username="testuser2", password="123456")) <NEW_LINE> self.assertFalse(User.authenticate(username="testuser", password="12345"))
Test views for messages.
62598fb5796e427e5384e869
class TdExtractDebugData: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.data = [{ 'name': None, 'result': None, 'regions': [{ 'points': [], 'box': [], 'flt_params': {} }] }] <NEW_LINE> self.enable = False <NEW_LINE> <DEDENT> def setEnable(self, flag): <NEW_LINE> <INDENT> self.enable = bool(flag) <NEW_LINE> <DEDENT> def initDebugData(self): <NEW_LINE> <INDENT> self.data = [] <NEW_LINE> <DEDENT> def newImage(self, name): <NEW_LINE> <INDENT> if self.enable: <NEW_LINE> <INDENT> self.data.append({'name':None, 'reuslt':None, 'regions':[]}) <NEW_LINE> self.data[-1]['name'] = name <NEW_LINE> <DEDENT> <DEDENT> def addLastResult(self, image): <NEW_LINE> <INDENT> if self.enable: <NEW_LINE> <INDENT> self.data[-1]['result'] = image.copy() <NEW_LINE> <DEDENT> <DEDENT> def addLastImageRegion(self, points, box, flt_params): <NEW_LINE> <INDENT> if self.enable: <NEW_LINE> <INDENT> self.data[-1]['regions'].append({"points":points.copy(), "box":box.copy(), "flt_params": flt_params.copy()})
Debug数据
62598fb567a9b606de5460a4
class Response(): <NEW_LINE> <INDENT> def __init__(self, pdf_document=None, status=False, error_message=""): <NEW_LINE> <INDENT> self.pdf_document = pdf_document <NEW_LINE> self.status = status <NEW_LINE> self.error_message = error_message <NEW_LINE> self.current_date = datetime.today() <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return { "PDF": self.pdf_document, "Status": self.status, "ErrorMessage": self.error_message, "CurrentDate": self.current_date}
The object to be returned in the api. It contains the request status and the pdf document. Args: pdf_document (list, optional): the bytes list of the downloaded document. Defaults to None. status (bool, optional): true if the capture was correct. Defaults to False. error_message (str, optional): if there's any error. Defaults to "".
62598fb54f6381625f19952b
class Server(object): <NEW_LINE> <INDENT> def __init__(self, settings, logger): <NEW_LINE> <INDENT> self.settings = settings <NEW_LINE> self.logger = logger <NEW_LINE> handlers = [ (r'/', _get_handler(settings, logger)) ] <NEW_LINE> self.app = web.Application( handlers, autoreload=settings.DEBUG, debug=settings.DEBUG ) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> global _ioloop, _periodic_callback <NEW_LINE> self.logger.info("Listening to {addr}:{port}".format( addr=self.settings.LISTEN_ADDRESS, port=self.settings.LISTEN_PORT )) <NEW_LINE> self.app.listen(port=self.settings.LISTEN_PORT, address=self.settings.LISTEN_ADDRESS) <NEW_LINE> signal.signal(signal.SIGINT, _signal_handler) <NEW_LINE> _ioloop = ioloop.IOLoop.instance() <NEW_LINE> next_stat = time() + self.settings.STATS_SECONDS <NEW_LINE> def _check(): <NEW_LINE> <INDENT> global next_stat <NEW_LINE> _check_exit() <NEW_LINE> current = time() <NEW_LINE> if current > next_stat: <NEW_LINE> <INDENT> self.show_stats() <NEW_LINE> next_stat = current + self.settings.STATS_SECONDS <NEW_LINE> <DEDENT> if not _is_closing: <NEW_LINE> <INDENT> _ioloop.call_later(0.25, _check) <NEW_LINE> <DEDENT> <DEDENT> def _run(): <NEW_LINE> <INDENT> self.logger.info("Starting periodic checks") <NEW_LINE> _ioloop.call_later(0.25, _check) <NEW_LINE> self.logger.info("Starting IOLoop") <NEW_LINE> _ioloop.start() <NEW_LINE> _ioloop.close() <NEW_LINE> self.logger.info("IOLoop closed") <NEW_LINE> <DEDENT> thread = threading.Thread(target=_run) <NEW_LINE> thread.start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.logger.info("Stopping server") <NEW_LINE> _ioloop.stop() <NEW_LINE> <DEDENT> def show_stats(self): <NEW_LINE> <INDENT> self.logger.info("Connected clients: {}".format(_connections))
Main manager for the server application
62598fb5a17c0f6771d5c30b
class StorageBase(object): <NEW_LINE> <INDENT> def __init__(self, node=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def start(self, iface='', network='', bootstrap=[], cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def set(self, key, value, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get(self, key, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_concat(self, key, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def append(self, key, value, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def remove(self, key, value, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def bootstrap(self, addrs, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def stop(self, cb=None): <NEW_LINE> <INDENT> raise NotImplementedError()
Base class for implementing storage plugins. All functions in this class should be async and never block All functions takes a callback parameter: cb: The callback function/object thats callaed when request is done The callback is as follows: start/stop: status: True or False set: key: The key set status: True or False get: key: The key value: The returned value append: key: The key status: True or False bootstrap: status: List of True and/or false:s
62598fb510dbd63aa1c70c8c
class _RecurrentARHMMMixin(_InputARHMMMixin): <NEW_LINE> <INDENT> def add_data(self, data, covariates=None, strided=False, **kwargs): <NEW_LINE> <INDENT> T = data.shape[0] <NEW_LINE> if covariates is None: <NEW_LINE> <INDENT> covariates = np.zeros((T, 0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert covariates.shape[0] == T <NEW_LINE> <DEDENT> covariates = np.column_stack(( np.row_stack((np.zeros(self.D), data[:-1])), covariates)) <NEW_LINE> super(_RecurrentARHMMMixin, self).add_data(data, covariates=covariates, **kwargs) <NEW_LINE> <DEDENT> def generate(self, T=100, keep=True, init_data=None, covariates=None, with_noise=True): <NEW_LINE> <INDENT> from pybasicbayes.util.stats import sample_discrete <NEW_LINE> K, n = self.num_states, self.D <NEW_LINE> if covariates is None: <NEW_LINE> <INDENT> covariates = np.zeros((T, 0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert covariates.shape[0] == T <NEW_LINE> <DEDENT> pi_0 = self.init_state_distn.pi_0 <NEW_LINE> dss = np.empty(T, dtype=np.int32) <NEW_LINE> dss[0] = sample_discrete(pi_0.ravel()) <NEW_LINE> data = np.empty((T, n), dtype='double') <NEW_LINE> if init_data is None: <NEW_LINE> <INDENT> data[0] = np.random.randn(n) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data[0] = init_data <NEW_LINE> <DEDENT> for t in range(1, T): <NEW_LINE> <INDENT> cov_t = np.column_stack((data[t-1:t], covariates[t])) <NEW_LINE> A = self.trans_distn.get_trans_matrices(cov_t)[0] <NEW_LINE> dss[t] = sample_discrete(A[dss[t-1], :]) <NEW_LINE> if with_noise: <NEW_LINE> <INDENT> data[t] = self.obs_distns[dss[t]].rvs(cov_t, return_xy=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data[t] = self.obs_distns[dss[t]].predict(cov_t) <NEW_LINE> <DEDENT> assert np.all(np.isfinite(data[t])), "RARHMM appears to be unstable!" <NEW_LINE> <DEDENT> return data, dss
In the "recurrent" version, the data also serve as covariates.
62598fb58e7ae83300ee9175
class MFEuclideanRandomOptimiser(RandomOptimiser): <NEW_LINE> <INDENT> def __init__(self, func_caller, worker_manager, call_fidel_to_opt_prob=0.25, *args, **kwargs): <NEW_LINE> <INDENT> super(MFEuclideanRandomOptimiser, self).__init__(func_caller, worker_manager, *args, **kwargs) <NEW_LINE> self.call_fidel_to_opt_prob = call_fidel_to_opt_prob <NEW_LINE> if not func_caller.is_mf(): <NEW_LINE> <INDENT> raise CalledMFOptimiserWithSFCaller(self, func_caller) <NEW_LINE> <DEDENT> <DEDENT> def is_an_mf_method(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def _determine_next_query(self): <NEW_LINE> <INDENT> def _get_next_fidel(): <NEW_LINE> <INDENT> if np.random.random() <= self.call_fidel_to_opt_prob: <NEW_LINE> <INDENT> return self.func_caller.fidel_to_opt <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.random.random(self.fidel_space.dim) <NEW_LINE> <DEDENT> <DEDENT> qinfo = Namespace(point=np.random.random(self.domain.dim), fidel=_get_next_fidel()) <NEW_LINE> return qinfo <NEW_LINE> <DEDENT> def _determine_next_batch_of_queries(self, batch_size): <NEW_LINE> <INDENT> qinfos = [self._determine_next_query() for _ in range(batch_size)] <NEW_LINE> return qinfos <NEW_LINE> <DEDENT> def _get_initial_qinfos(self, num_init_evals): <NEW_LINE> <INDENT> return get_euclidean_initial_qinfos(self.options.init_method, num_init_evals, self.domain.bounds, self.options.fidel_init_method, self.fidel_space.bounds, self.func_caller.fidel_to_opt, self.options.init_set_to_fidel_to_opt_with_prob)
A class which optimises in Euclidean spaces using random evaluations and multi-fidelity.
62598fb5ec188e330fdf8966
class Resize2(object): <NEW_LINE> <INDENT> def __init__(self,size,interpolation=Image.BILINEAR): <NEW_LINE> <INDENT> assert isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2) <NEW_LINE> self.size = size <NEW_LINE> self.interpolation = interpolation <NEW_LINE> <DEDENT> def __call__(self, img, mask): <NEW_LINE> <INDENT> return F.resize(img, self.size, self.interpolation), F.resize(mask, self.size, self.interpolation) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> interpolate_str = _pil_interpolation_to_str[self.interpolation] <NEW_LINE> return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str)
Resize the input PIL Image to the given size. Args: size (sequence or int): Desired output size. If size is a sequence like (h, w), output size will be matched to this. If size is an int, smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``PIL.Image.BILINEAR``
62598fb5be383301e02538d1
class IDataPointGraphPointInfo(IColorGraphPointInfo): <NEW_LINE> <INDENT> lineType = schema.Choice(title=_t('Line Type'), vocabulary='complexGraphLineType', order=5) <NEW_LINE> lineWidth = schema.TextLine(title=_t('Line Width'), order=6) <NEW_LINE> stacked = schema.Bool(title=_t('Stacked'), order=7) <NEW_LINE> skipCalc = schema.Bool(title=_t('Display full value in footer'), order=8) <NEW_LINE> format = schema.TextLine(title=_t('Format'), order=9) <NEW_LINE> dpName = schema.TextLine(title=_t('DataPoint'), readonly=True, order=3) <NEW_LINE> rpn = schema.Text(title=_t('RPN'), order=10) <NEW_LINE> limit = schema.Int(title=_t('Limit'), order=11) <NEW_LINE> cFunc = schema.TextLine(title=_t('Consolidation'), order=12)
Adapts DataPoint GraphPoint.
62598fb555399d3f056265ea
@register_criterion("sequence_nll") <NEW_LINE> class SequenceNegativeLoglikelihoodCriterion(BaseSequenceLossCriterion): <NEW_LINE> <INDENT> def forward(self, model, sample, reduce=True): <NEW_LINE> <INDENT> translations, bleu_scores = self.generate_translations(model, sample) <NEW_LINE> nll_loss = self.compute_nll(model, sample, translations) <NEW_LINE> loss = nll_loss[:, 0] + torch.logsumexp(-nll_loss, 1) <NEW_LINE> if reduce: <NEW_LINE> <INDENT> loss = loss.sum() <NEW_LINE> <DEDENT> sample_size = ( sample["target"].size(0) if self.args.sentence_avg else sample["ntokens"] ) <NEW_LINE> logging_output = { "loss": utils.item(loss.data) if reduce else loss.data, "ntokens": sample["ntokens"], "sample_size": sample_size, } <NEW_LINE> return loss, sample_size, logging_output
SeqNLL loss from https://arxiv.org/pdf/1711.04956.pdf.
62598fb55fcc89381b2661b7
class JobBookingBarDelegate(AbstractDelegate): <NEW_LINE> <INDENT> def __init__(self, parent, *args): <NEW_LINE> <INDENT> AbstractDelegate.__init__(self, parent, *args) <NEW_LINE> <DEDENT> def paint(self, painter, option, index): <NEW_LINE> <INDENT> if index.data(QtCore.Qt.UserRole) == cuegui.Constants.TYPE_JOB and option.rect.width() > 30: <NEW_LINE> <INDENT> job = self.parent().itemFromIndex(index).rpcObject <NEW_LINE> rect = option.rect.adjusted(12, 6, -12, -6) <NEW_LINE> painter.save() <NEW_LINE> try: <NEW_LINE> <INDENT> self._drawBackground(painter, option, index) <NEW_LINE> try: <NEW_LINE> <INDENT> jobRunning = job.data.job_stats.running_frames <NEW_LINE> jobWaiting = job.data.job_stats.waiting_frames <NEW_LINE> try: <NEW_LINE> <INDENT> cores_per_frame = float(job.data.job_stats.reserved_cores / jobRunning) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> cores_per_frame = float(6 / 1) <NEW_LINE> <DEDENT> jobMin = int(job.data.min_cores / cores_per_frame) <NEW_LINE> jobMax = int(job.data.max_cores / cores_per_frame) <NEW_LINE> ratio = rect.width() / float(jobRunning + jobWaiting) <NEW_LINE> if jobWaiting: <NEW_LINE> <INDENT> painter.fillRect( rect.adjusted(0, 2, 0, -2), RGB_FRAME_STATE[opencue.api.job_pb2.WAITING]) <NEW_LINE> <DEDENT> if jobRunning: <NEW_LINE> <INDENT> painter.fillRect( rect.adjusted(0, 0, -int(ceil(ratio * jobWaiting)), 0), RGB_FRAME_STATE[opencue.api.job_pb2.RUNNING]) <NEW_LINE> <DEDENT> painter.setPen(cuegui.Style.ColorTheme.PAUSE_ICON_COLOUR) <NEW_LINE> x = min(rect.x() + ratio * jobMin, option.rect.right() - 9) <NEW_LINE> painter.drawLine(x, option.rect.y(), x, option.rect.y() + option.rect.height()) <NEW_LINE> painter.setPen(cuegui.Style.ColorTheme.KILL_ICON_COLOUR) <NEW_LINE> x = min(rect.x() + ratio * jobMax, option.rect.right() - 6) <NEW_LINE> painter.drawLine(x, option.rect.y(), x, option.rect.y() + option.rect.height()) <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> painter.restore() <NEW_LINE> del painter <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> AbstractDelegate.paint(self, painter, option, index)
Delegate for the job booking bar.
62598fb5a8370b77170f04b3
class HelpOperation(Operation): <NEW_LINE> <INDENT> def __init__(self,args=[]): <NEW_LINE> <INDENT> Operation.__init__(self, args) <NEW_LINE> self.lista=["help","find","describe","config","getconfig","delconfig","wget","selectrow","download","open","log"] <NEW_LINE> <DEDENT> def run(self,q=Query()): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if len(self.args)==0: self.show_operations() <NEW_LINE> else: self.show_descriptions() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.dispatch(e) <NEW_LINE> <DEDENT> <DEDENT> def show_descriptions(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> language=self.getLanguage(self.args)+".txt" <NEW_LINE> path=os.path.dirname(os.path.abspath(__file__))+"/Manual/" <NEW_LINE> if os.path.exists(os.path.join(path,language)): doc=Document(language,path) <NEW_LINE> else : raise Exception("No language founded with name : "+language) <NEW_LINE> for a in self.args: <NEW_LINE> <INDENT> description=str(doc.get_parameter(a)) <NEW_LINE> if description!="": self.dispatch(description) <NEW_LINE> else: raise Exception("Wrong operation or No describe implementation for this operation") <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.dispatch(e) <NEW_LINE> <DEDENT> <DEDENT> def show_operations(self): <NEW_LINE> <INDENT> s= "List of operation: \n" <NEW_LINE> for elem in self.lista: s+= "'"+elem+"' " <NEW_LINE> s+="\nTo know the operation's description, do: describe 'operation_name'" <NEW_LINE> self.dispatch(s) <NEW_LINE> <DEDENT> def getLanguage(self,args): <NEW_LINE> <INDENT> language='en' <NEW_LINE> for elem in args: <NEW_LINE> <INDENT> if language!='en': <NEW_LINE> <INDENT> raise Exception("Too many language's option") <NEW_LINE> <DEDENT> if elem[0]=='-': language=elem[1:] <NEW_LINE> <DEDENT> return language
Help operation class
62598fb563b5f9789fe85242
class Scope(Enum): <NEW_LINE> <INDENT> Base = auto() <NEW_LINE> OneLevel = auto() <NEW_LINE> SubTree = auto()
LDAP search scope enumeration
62598fb5236d856c2adc94aa
class WindowsSha256File(FactBase): <NEW_LINE> <INDENT> shell_executable = 'ps' <NEW_LINE> def command(self, name): <NEW_LINE> <INDENT> return ( 'if (Test-Path "{0}") {{ ' '(Get-FileHash -Algorithm SHA256 "{0}").hash' ' }}' ).format(name) <NEW_LINE> <DEDENT> def process(self, output): <NEW_LINE> <INDENT> return output[0] if len(output[0]) > 0 else None
Returns a SHA256 hash of a file.
62598fb521bff66bcd722d3f
class GwElementManagerButton(GwAction): <NEW_LINE> <INDENT> def __init__(self, icon_path, action_name, text, toolbar, action_group): <NEW_LINE> <INDENT> super().__init__(icon_path, action_name, text, toolbar, action_group) <NEW_LINE> self.element = GwElement() <NEW_LINE> <DEDENT> def clicked_event(self): <NEW_LINE> <INDENT> self.element.manage_elements()
Button 67: Element Manager
62598fb5f548e778e596b67a
class _Immutable: <NEW_LINE> <INDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if not hasattr(self, '_immutable_init') or self._immutable_init is not self: <NEW_LINE> <INDENT> raise TypeError("object doesn't support attribute assignment") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super().__setattr__(name, value) <NEW_LINE> <DEDENT> <DEDENT> def __delattr__(self, name): <NEW_LINE> <INDENT> if not hasattr(self, '_immutable_init') or self._immutable_init is not self: <NEW_LINE> <INDENT> raise TypeError("object doesn't support attribute assignment") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super().__delattr__(name)
Immutable mixin class
62598fb55fdd1c0f98e5e065
class PoolActionAvailability(IntEnum): <NEW_LINE> <INDENT> FULLY_OPERATIONAL = 0 <NEW_LINE> NO_IPC_REQUESTS = 1 <NEW_LINE> NO_POOL_CHANGES = 2 <NEW_LINE> NO_WRITE_IO = 3 <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self is PoolActionAvailability.FULLY_OPERATIONAL: <NEW_LINE> <INDENT> return "fully_operational" <NEW_LINE> <DEDENT> if self is PoolActionAvailability.NO_IPC_REQUESTS: <NEW_LINE> <INDENT> return "no_ipc_requests" <NEW_LINE> <DEDENT> if self is PoolActionAvailability.NO_POOL_CHANGES: <NEW_LINE> <INDENT> return "no_pool_changes" <NEW_LINE> <DEDENT> if self is PoolActionAvailability.NO_WRITE_IO: <NEW_LINE> <INDENT> return "no_write_io" <NEW_LINE> <DEDENT> assert False, "impossible value reached" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_str(code_str): <NEW_LINE> <INDENT> for item in list(PoolActionAvailability): <NEW_LINE> <INDENT> if code_str == str(item): <NEW_LINE> <INDENT> return item <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def pool_maintenance_error_codes(self): <NEW_LINE> <INDENT> codes = [] <NEW_LINE> if self >= PoolActionAvailability.NO_IPC_REQUESTS: <NEW_LINE> <INDENT> codes.append(PoolMaintenanceErrorCode.NO_IPC_REQUESTS) <NEW_LINE> <DEDENT> if self >= PoolActionAvailability.NO_POOL_CHANGES: <NEW_LINE> <INDENT> codes.append(PoolMaintenanceErrorCode.NO_POOL_CHANGES) <NEW_LINE> <DEDENT> if self >= PoolActionAvailability.NO_WRITE_IO: <NEW_LINE> <INDENT> codes.append(PoolMaintenanceErrorCode.READ_ONLY) <NEW_LINE> <DEDENT> return codes
What category of interactions a pool is enabled for.
62598fb5956e5f7376df56e9
@dataclass <NEW_LINE> class Block(Statement): <NEW_LINE> <INDENT> statements: List[Statement] <NEW_LINE> def accept(self, visitor): <NEW_LINE> <INDENT> visitor.visit_block(self)
A block statement
62598fb567a9b606de5460a6
class HTTP404(HTTP4xx): <NEW_LINE> <INDENT> CODE = 404 <NEW_LINE> def __init__(self, exc=None): <NEW_LINE> <INDENT> super().__init__(self.CODE, "Resource not found", exc=exc)
404 Not Found The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.
62598fb51b99ca400228f59c
class QuietExit(Exception): <NEW_LINE> <INDENT> pass
Simple exception used as a message from functions to the main. What it means is that the inner function already handled the error and the main is not printing any info.
62598fb5283ffb24f3cf3964
class ActionBase(object): <NEW_LINE> <INDENT> interface.implements(CommandInterface) <NEW_LINE> NAMESPACE = 'OVERRIDE_ME_NS' <NEW_LINE> NAME = 'OVERRIDE_ME_NAME' <NEW_LINE> def do(self, aDocument, cursor_position): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def to_xml_etree(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base Action for any Action that can be compouned to build an Operation
62598fb5fff4ab517ebcd8bd
class Address(models.Model): <NEW_LINE> <INDENT> contact = models.ForeignKey(Contact) <NEW_LINE> street1 = models.CharField(max_length=80) <NEW_LINE> street2 = models.CharField(max_length=80, blank=True) <NEW_LINE> addressee = models.CharField(max_length=80) <NEW_LINE> state = models.CharField(max_length=50, blank=True) <NEW_LINE> city = models.CharField(max_length=50) <NEW_LINE> postal_code = models.CharField(max_length=30) <NEW_LINE> country = models.CharField(max_length=255) <NEW_LINE> is_shipping = models.BooleanField(default=False) <NEW_LINE> is_billing = models.BooleanField(default=False) <NEW_LINE> objects = AddressManager() <NEW_LINE> ADDRESS_FIELDS = ['street1', 'street2', 'addressee', 'state', 'city', 'postal_code', 'country']
Address model with flags for default billin and shipping address
62598fb557b8e32f52508188
class TheoreticalDihedral( NoeCompleteness ): <NEW_LINE> <INDENT> def __init__(self, project, **kwds): <NEW_LINE> <INDENT> NoeCompleteness.__init__(self, project, **kwds) <NEW_LINE> self.project = project <NEW_LINE> self.lib = TheoreticalDihedralLib() <NEW_LINE> self.variance = None <NEW_LINE> self.write_ac_lists = None <NEW_LINE> self.file_name_base_ac = None <NEW_LINE> <DEDENT> def doTheoreticalDihedral( self, variance = 10.0, ob_file_name = None, write_ac_lists = True, file_name_base_ac = THEORETICAL_RESTRAINT_LIST_STR, resList = None, ): <NEW_LINE> <INDENT> self.variance = variance <NEW_LINE> self.ob_file_name = ob_file_name <NEW_LINE> self.write_ac_lists = write_ac_lists <NEW_LINE> self.file_name_base_ac = file_name_base_ac <NEW_LINE> self.resList = resList <NEW_LINE> nTmessage("variance : %8.3f" % self.variance ) <NEW_LINE> nTmessage("write_ac_lists : %s" % self.write_ac_lists ) <NEW_LINE> nTmessage("file_name_base_ac : %s" % self.file_name_base_ac ) <NEW_LINE> nTmessage("resList : %s " % str(self.resList) ) <NEW_LINE> if ob_file_name: <NEW_LINE> <INDENT> self.lib.readStarFile(ob_file_name) <NEW_LINE> <DEDENT> result = DihedralRestraintList('Vset') <NEW_LINE> for residue in self.resList: <NEW_LINE> <INDENT> residueDef = residue.db <NEW_LINE> for dihedralDef in residueDef.dihedrals: <NEW_LINE> <INDENT> comboStr = "%s %s" % (residue, dihedralDef) <NEW_LINE> if not self.lib.inLib(residue.resName, dihedralDef.name): <NEW_LINE> <INDENT> nTdebug("Skipping unwelcome " + comboStr) <NEW_LINE> continue <NEW_LINE> <DEDENT> dihedral = getDeepByKeysOrAttributes(residue, dihedralDef.name ) <NEW_LINE> if not dihedral: <NEW_LINE> <INDENT> nTdebug("No dihedral for " + comboStr) <NEW_LINE> continue <NEW_LINE> <DEDENT> atoms = getDeepByKeysOrAttributes(dihedral, ATOMS_STR) <NEW_LINE> if not atoms: <NEW_LINE> <INDENT> nTerror("Failed to find atoms for " + comboStr) <NEW_LINE> continue <NEW_LINE> <DEDENT> dihedralAverage = dihedral.calculateValues() <NEW_LINE> if not dihedralAverage or isNaN(dihedralAverage[0]): <NEW_LINE> <INDENT> nTerror("Failed to find dihedralAverage for " + comboStr) <NEW_LINE> continue <NEW_LINE> <DEDENT> cav, _cv = dihedralAverage <NEW_LINE> lower = cav - variance <NEW_LINE> upper = cav + variance <NEW_LINE> dihedralRestraint = DihedralRestraint(atoms=atoms, lower=lower, upper=upper) <NEW_LINE> result.append(dihedralRestraint) <NEW_LINE> <DEDENT> <DEDENT> if self.write_ac_lists: <NEW_LINE> <INDENT> if not result: <NEW_LINE> <INDENT> nTdebug("Found empty result list") <NEW_LINE> return result <NEW_LINE> <DEDENT> <DEDENT> nTmessage("Writing the list to file name base: " + self.file_name_base_ac + " with number of restraints: %s" % len(result)) <NEW_LINE> result.export2cyana( self.file_name_base_ac + '.aco', convention=CYANA2) <NEW_LINE> result.export2xplor( self.file_name_base_ac + '.tbl' ) <NEW_LINE> return result
Small class akin to NoeCompleteness super class.
62598fb5f548e778e596b67b
class MergeEdgeFeaturesSlurm(MergeEdgeFeaturesBase, SlurmTask): <NEW_LINE> <INDENT> pass
MergeEdgeFeatures on slurm cluster
62598fb53346ee7daa3376b3
class Apps(models.Model): <NEW_LINE> <INDENT> module_id = models.IntegerField() <NEW_LINE> name = models.CharField(unique=True, max_length=191) <NEW_LINE> slug = models.CharField(unique=True, max_length=191) <NEW_LINE> description = models.TextField(blank=True, null=True) <NEW_LINE> status = models.BooleanField(default=True) <NEW_LINE> @classmethod <NEW_LINE> def load_on_migrate(cls, license_id): <NEW_LINE> <INDENT> license = License.objects.filter(id=license_id).first() <NEW_LINE> db = CompanyDatabase.objects.filter(company_id=license.company_id).first() <NEW_LINE> module = Modules.objects.filter(id=license.module_id).first() <NEW_LINE> app_instance = cls.objects.using(db.db_name).filter(module_id=module.id).first() <NEW_LINE> if app_instance is None: <NEW_LINE> <INDENT> app_instance = cls() <NEW_LINE> app_instance.module_id = module.id <NEW_LINE> app_instance.name = module.name <NEW_LINE> app_instance.slug = module.slug <NEW_LINE> app_instance.description = module.description <NEW_LINE> app_instance.save(using=db.db_name)
Save licensed modules/app on user database
62598fb54e4d5625663724f9
class ContainerSettings(Model): <NEW_LINE> <INDENT> _validation = { 'image_source_registry': {'required': True}, } <NEW_LINE> _attribute_map = { 'image_source_registry': {'key': 'imageSourceRegistry', 'type': 'ImageSourceRegistry'}, } <NEW_LINE> def __init__(self, image_source_registry): <NEW_LINE> <INDENT> self.image_source_registry = image_source_registry
Settings for the container to be downloaded. :param image_source_registry: Registry to download the container from. :type image_source_registry: :class:`ImageSourceRegistry <azure.mgmt.batchai.models.ImageSourceRegistry>`
62598fb576e4537e8c3ef67e
class UserSignupTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.payload_invalid_username = {keys.USERNAME: 'A$3'} <NEW_LINE> self.payload_invalid_password = {keys.USERNAME: 'bhirendra', keys.PASSWORD: ' 1 g % '} <NEW_LINE> self.payload_invalid_email = {keys.USERNAME: 'bhirendra', keys.PASSWORD: 'Bhi#1', keys.EMAIL: 'a.com'} <NEW_LINE> self.payload_invalid_mobile = {keys.USERNAME: 'bhirendra', keys.PASSWORD: 'Bhi#1', keys.EMAIL: '', keys.MOBILE: '1234567890'} <NEW_LINE> self.payload_valid_user = {keys.USERNAME: 'bhi123', keys.PASSWORD: 'Bhi#1', keys.EMAIL: 'bhirendra2014@gmail.com', keys.MOBILE: '9907890199'} <NEW_LINE> <DEDENT> def test_signup(self): <NEW_LINE> <INDENT> response1 = client.post(reverse('user-signup'), data=json.dumps(self.payload_invalid_username), content_type='application/json') <NEW_LINE> self.assertEqual(response1.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> response2 = client.post(reverse('user-signup'), data=json.dumps(self.payload_invalid_password), content_type='application/json') <NEW_LINE> self.assertEqual(response2.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> response3 = client.post(reverse('user-signup'), data=json.dumps(self.payload_invalid_email), content_type='application/json') <NEW_LINE> self.assertEqual(response3.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> response4 = client.post(reverse('user-signup'), data=json.dumps(self.payload_invalid_mobile), content_type='application/json') <NEW_LINE> self.assertEqual(response4.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> response5 = client.post(reverse('user-signup'), data=json.dumps(self.payload_valid_user), content_type='application/json') <NEW_LINE> self.assertEqual(response5.status_code, status.HTTP_200_OK)
Test cases for user signup
62598fb5be383301e02538d3
class ZhttpServerOptions(object): <NEW_LINE> <INDENT> allow_destruct = False <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> if len(args) == 2 and type(args[0]) is c_void_p and isinstance(args[1], bool): <NEW_LINE> <INDENT> self._as_parameter_ = cast(args[0], zhttp_server_options_p) <NEW_LINE> self.allow_destruct = args[1] <NEW_LINE> <DEDENT> elif len(args) == 2 and type(args[0]) is zhttp_server_options_p and isinstance(args[1], bool): <NEW_LINE> <INDENT> self._as_parameter_ = args[0] <NEW_LINE> self.allow_destruct = args[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert(len(args) == 0) <NEW_LINE> self._as_parameter_ = lib.zhttp_server_options_new() <NEW_LINE> self.allow_destruct = True <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.allow_destruct: <NEW_LINE> <INDENT> lib.zhttp_server_options_destroy(byref(self._as_parameter_)) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(other) == type(self): <NEW_LINE> <INDENT> return other.c_address() == self.c_address() <NEW_LINE> <DEDENT> elif type(other) == c_void_p: <NEW_LINE> <INDENT> return other.value == self.c_address() <NEW_LINE> <DEDENT> <DEDENT> def c_address(self): <NEW_LINE> <INDENT> return addressof(self._as_parameter_.contents) <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return self._as_parameter_.__bool__() <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return self._as_parameter_.__nonzero__() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_config(config): <NEW_LINE> <INDENT> return ZhttpServerOptions(lib.zhttp_server_options_from_config(config), True) <NEW_LINE> <DEDENT> def port(self): <NEW_LINE> <INDENT> return lib.zhttp_server_options_port(self._as_parameter_) <NEW_LINE> <DEDENT> def set_port(self, port): <NEW_LINE> <INDENT> return lib.zhttp_server_options_set_port(self._as_parameter_, port) <NEW_LINE> <DEDENT> def backend_address(self): <NEW_LINE> <INDENT> return lib.zhttp_server_options_backend_address(self._as_parameter_) <NEW_LINE> <DEDENT> def set_backend_address(self, address): <NEW_LINE> <INDENT> return lib.zhttp_server_options_set_backend_address(self._as_parameter_, address) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def test(verbose): <NEW_LINE> <INDENT> return lib.zhttp_server_options_test(verbose)
zhttp server.
62598fb5be8e80087fbbf13f
class LandingType(models.Model): <NEW_LINE> <INDENT> name = models.CharField('Landing type name', max_length=255, blank=False, null=False) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % self.name
Landing page type
62598fb55fdd1c0f98e5e066
class GeneralFMaximizer(object): <NEW_LINE> <INDENT> def __init__(self, beta, n_labels): <NEW_LINE> <INDENT> self.beta = beta <NEW_LINE> self.n_labels = n_labels <NEW_LINE> <DEDENT> def __matrix_W_F2(self): <NEW_LINE> <INDENT> W = np.ndarray(shape=(self.n_labels, self.n_labels)) <NEW_LINE> for i in np.arange(1, self.n_labels + 1): <NEW_LINE> <INDENT> for j in np.arange(1, self.n_labels + 1): <NEW_LINE> <INDENT> W[i - 1, j - 1] = 1 / (i * (self.beta**2) + j) <NEW_LINE> <DEDENT> <DEDENT> return(W) <NEW_LINE> <DEDENT> def get_predictions(self, predictions): <NEW_LINE> <INDENT> n_instances = len(predictions) <NEW_LINE> n_labels = predictions[0].shape[0] <NEW_LINE> E_F = [] <NEW_LINE> optimal_predictions = [] <NEW_LINE> W = self.__matrix_W_F2() <NEW_LINE> for instance in range(n_instances): <NEW_LINE> <INDENT> P = predictions[instance] <NEW_LINE> D = np.matmul(P, W) <NEW_LINE> E = [] <NEW_LINE> h = [] <NEW_LINE> for k in range(n_labels): <NEW_LINE> <INDENT> h_k = np.zeros(n_labels) <NEW_LINE> h_k[np.argsort(D[:, k])[::-1][:k + 1]] = 1 <NEW_LINE> h.append(h_k) <NEW_LINE> E.append(np.dot(h_k, D[:, k])) <NEW_LINE> <DEDENT> h_F = h[np.argmax(E)] <NEW_LINE> E_f = E[np.argmax(E)] <NEW_LINE> optimal_predictions.append(h_F) <NEW_LINE> E_F.append(E_f) <NEW_LINE> <DEDENT> return(np.array(optimal_predictions), E_F)
Implementation of the GFM algorithm
62598fb563b5f9789fe85244
class ProfileMapping( OktaObject ): <NEW_LINE> <INDENT> def __init__(self, config=None): <NEW_LINE> <INDENT> super().__init__(config) <NEW_LINE> if config: <NEW_LINE> <INDENT> self.links = config["links"] if "links" in config else None <NEW_LINE> self.id = config["id"] if "id" in config else None <NEW_LINE> self.properties = config["properties"] if "properties" in config else None <NEW_LINE> if "source" in config: <NEW_LINE> <INDENT> if isinstance(config["source"], profile_mapping_source.ProfileMappingSource): <NEW_LINE> <INDENT> self.source = config["source"] <NEW_LINE> <DEDENT> elif config["source"] is not None: <NEW_LINE> <INDENT> self.source = profile_mapping_source.ProfileMappingSource( config["source"] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.source = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.source = None <NEW_LINE> <DEDENT> if "target" in config: <NEW_LINE> <INDENT> if isinstance(config["target"], profile_mapping_source.ProfileMappingSource): <NEW_LINE> <INDENT> self.target = config["target"] <NEW_LINE> <DEDENT> elif config["target"] is not None: <NEW_LINE> <INDENT> self.target = profile_mapping_source.ProfileMappingSource( config["target"] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.target = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.target = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.links = None <NEW_LINE> self.id = None <NEW_LINE> self.properties = None <NEW_LINE> self.source = None <NEW_LINE> self.target = None <NEW_LINE> <DEDENT> <DEDENT> def request_format(self): <NEW_LINE> <INDENT> parent_req_format = super().request_format() <NEW_LINE> current_obj_format = { "_links": self.links, "id": self.id, "properties": self.properties, "source": self.source, "target": self.target } <NEW_LINE> parent_req_format.update(current_obj_format) <NEW_LINE> return parent_req_format
A class for ProfileMapping objects.
62598fb5a05bb46b3848a943
class ProjectPoint2Image(nn.Module): <NEW_LINE> <INDENT> def __init__(self, K, im_width, im_height, uv_only=False): <NEW_LINE> <INDENT> super(ProjectPoint2Image, self).__init__() <NEW_LINE> self.K = K <NEW_LINE> self.im_width = im_width <NEW_LINE> self.im_height = im_height <NEW_LINE> ui, vi = np.meshgrid(range(im_width), range(im_height)) <NEW_LINE> grid = np.hstack((vi.reshape(-1,1), ui.reshape(-1,1))).astype(np.float32) <NEW_LINE> self.grid = torch.tensor(grid).to(K.device) <NEW_LINE> self.sigma = K[0,0].item()/16 <NEW_LINE> self.uv_only = uv_only <NEW_LINE> <DEDENT> def forward(self, RT, pts_3d, pts_feat, pts_scale): <NEW_LINE> <INDENT> device = RT.device <NEW_LINE> bs = RT.shape[0] <NEW_LINE> R = RT[:, :3,:3] <NEW_LINE> T = RT[:, :3, 3] <NEW_LINE> if pts_3d.shape[1]==1: <NEW_LINE> <INDENT> self.sigma = self.K[0,0].item()/16. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sigma = self.K[0,0].item()/32. <NEW_LINE> <DEDENT> points_local = (R @ pts_3d.transpose(1,2)).transpose(1,2) + T.view(bs,1,3) <NEW_LINE> points_proj = self.K.unsqueeze(0).to(device) @ points_local.transpose(1,2) <NEW_LINE> points_mask = points_proj[:,2]>0.1 <NEW_LINE> u = points_proj[:,0,:]/points_proj[:,2,:].clamp(min=0.1) <NEW_LINE> v = points_proj[:,1,:]/points_proj[:,2,:].clamp(min=0.1) <NEW_LINE> uv = torch.cat((v.reshape(bs,-1,1), u.reshape(bs,-1,1)),dim=2) <NEW_LINE> if self.uv_only: <NEW_LINE> <INDENT> uvz = torch.cat((uv, points_proj[:,2,:].reshape(bs,-1,1)),dim=2) <NEW_LINE> return uvz <NEW_LINE> <DEDENT> distance = uv.view(bs,-1,1,2) - self.grid.view(1,1,-1,2).expand(bs,-1,-1,-1).to(device) <NEW_LINE> distance_sq = distance[...,0]**2 + distance[...,1]**2 <NEW_LINE> weight = torch.exp(-distance_sq / (pts_scale.view(bs,-1,1) * self.sigma * self.sigma)) <NEW_LINE> weight = weight * points_mask.view(bs,-1,1).float() <NEW_LINE> img = pts_feat.transpose(1,2) @ weight <NEW_LINE> img = img.view(bs, -1, self.im_height, self.im_width) <NEW_LINE> return img
Differentiable renderer for point cloud
62598fb501c39578d7f12e52
class AddComment(handlers.Handler): <NEW_LINE> <INDENT> @handlers.check_logged_in() <NEW_LINE> @handlers.check_entry_exists() <NEW_LINE> @handlers.check_user_owns_entry() <NEW_LINE> def post(self, entry_entity): <NEW_LINE> <INDENT> comment_text = handlers.sanitize(self.request.get('comment')) <NEW_LINE> if not comment_text: <NEW_LINE> <INDENT> self.error(400) <NEW_LINE> return <NEW_LINE> <DEDENT> user_id = handlers.get_username(self) <NEW_LINE> new_comment_entity = models.add_comment(entry_entity, comment_text, user_id) <NEW_LINE> new_comment_dict = handlers.to_dict(new_comment_entity) <NEW_LINE> new_comment_dict['liked'] = False <NEW_LINE> self.response.out.write(json.encode(new_comment_dict))
Add a comment to a particular post
62598fb55fdd1c0f98e5e067
class SourceAttributes: <NEW_LINE> <INDENT> IF = 'if' <NEW_LINE> ORDERBY = 'orderby' <NEW_LINE> LIMIT = "limit" <NEW_LINE> CUSTOM_TAG_ATTR = 'tag' <NEW_LINE> CHARACTERISTIC = 'characteristic' <NEW_LINE> QUESTION_TYPE = 'questiontype' <NEW_LINE> MATRIX_VALUESET = 'valueset' <NEW_LINE> RESPONSE_VALUE = 'value' <NEW_LINE> SIZE = 'size' <NEW_LINE> GOTO = 'goto' <NEW_LINE> COLUMN_HEADER = 'columnheader' <NEW_LINE> VALUE_LABEL_LOCATION = 'valuelabellocation'
message source attributes: present in original source
62598fb544b2445a339b69df
class PtHeekCountdownStates: <NEW_LINE> <INDENT> kHeekCountdownStart = 0 <NEW_LINE> kHeekCountdownStop = 1 <NEW_LINE> kHeekCountdownIdle = 2
(none)
62598fb563d6d428bbee2886
class GetPastEventsResultSet(ResultSet): <NEW_LINE> <INDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None)
Retrieve the value for the "Response" output from this choreography execution. ((XML) The response from Last.fm.)
62598fb51b99ca400228f59d
class Tuple(Element, atom.tuple.Tuple): <NEW_LINE> <INDENT> def __init__(self, item=None, default=()): <NEW_LINE> <INDENT> Element.__init__(self) <NEW_LINE> atom.tuple.Tuple.__init__(self, item, default)
Tuple element
62598fb59c8ee823130401df
class BatchProducer(object): <NEW_LINE> <INDENT> ACK_NOT_REQUIRED = 0 <NEW_LINE> ACK_AFTER_LOCAL_WRITE = 1 <NEW_LINE> ACK_AFTER_CLUSTER_COMMIT = -1 <NEW_LINE> DEFAULT_ACK_TIMEOUT = 2000 <NEW_LINE> DEFAULT_MESSAGE_LIMIT = 1000000 <NEW_LINE> def __init__(self, client, partitioner=None, req_acks=ACK_AFTER_CLUSTER_COMMIT, ack_timeout=DEFAULT_ACK_TIMEOUT, message_limit=DEFAULT_MESSAGE_LIMIT): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.req_acks = req_acks <NEW_LINE> self.ack_timeout = ack_timeout <NEW_LINE> self.message_limit = message_limit <NEW_LINE> self.partitioner_class = partitioner or HashedPartitioner <NEW_LINE> self.partitioners = {} <NEW_LINE> <DEDENT> def _next_partition(self, topic, key): <NEW_LINE> <INDENT> if topic not in self.partitioners: <NEW_LINE> <INDENT> if topic not in self.client.topic_partitions: <NEW_LINE> <INDENT> self.client.load_metadata_for_topics(topic) <NEW_LINE> <DEDENT> self.partitioners[topic] = self.partitioner_class(self.client.topic_partitions[topic]) <NEW_LINE> <DEDENT> partitioner = self.partitioners[topic] <NEW_LINE> return partitioner.partition(key, self.client.topic_partitions[topic]) <NEW_LINE> <DEDENT> def send_messages(self, topic, key_msg_list): <NEW_LINE> <INDENT> msg_size = 0 <NEW_LINE> msgset = defaultdict(list) <NEW_LINE> resps = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for key, msg in key_msg_list: <NEW_LINE> <INDENT> msg_str = create_message(msg) <NEW_LINE> if msg_size + len(msg_str) > self.message_limit: <NEW_LINE> <INDENT> reqs = list(ProduceRequest(topic, key, msgs) for key, msgs in msgset.iteritems()) <NEW_LINE> resps.extend(self.client.send_produce_request(reqs, acks=self.req_acks, timeout=self.ack_timeout)) <NEW_LINE> msgset = defaultdict(list) <NEW_LINE> msg_size = 0 <NEW_LINE> <DEDENT> msgset[self._next_partition(topic, key)].append(msg_str) <NEW_LINE> msg_size = msg_size + len(msg_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reqs = list(ProduceRequest(topic, key, msgs) for key, msgs in msgset.iteritems()) <NEW_LINE> resps.extend(self.client.send_produce_request(reqs, acks=self.req_acks, timeout=self.ack_timeout)) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> log.exception("Unable to send messages") <NEW_LINE> raise <NEW_LINE> <DEDENT> if not all(resp.error == 0 for resp in resps): <NEW_LINE> <INDENT> log.exception("response has errors {0}".format(resps)) <NEW_LINE> raise <NEW_LINE> <DEDENT> return resps
A producer which distributes messages to partitions based on the key and send batches Params: client - The Kafka client instance to use partitioner - A partitioner class that will be used to get the partition to send the message to. Must be derived from Partitioner req_acks - A value indicating the acknowledgements that the server must receive before responding to the request ack_timeout - Value (in milliseconds) indicating a timeout for waiting for an acknowledgement
62598fb5283ffb24f3cf3966
class DotV2TestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_vec2_getitem(self): <NEW_LINE> <INDENT> from pedemath.vec2 import dot_v2 <NEW_LINE> a = Vec2(2, 3) <NEW_LINE> b = Vec2(1, 4) <NEW_LINE> result = dot_v2(a, b) <NEW_LINE> self.assertEqual(result, 14)
Ensure dot_v2 returns the dot product.
62598fb566673b3332c304a6
class SuiteBuilder(object): <NEW_LINE> <INDENT> def __init__(self, baseCase): <NEW_LINE> <INDENT> self.baseCase = baseCase <NEW_LINE> self.modifierSets = [] <NEW_LINE> self._modifierLookup = {k.__name__: k for k in getInputModifiers(InputModifier)} <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.modifierSets) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<SuiteBuilder len:{} baseCase:{}>".format(len(self), self.baseCase) <NEW_LINE> <DEDENT> def addDegreeOfFreedom(self, inputModifiers): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def buildSuite(self, namingFunc=None): <NEW_LINE> <INDENT> caseSuite = suite.CaseSuite(self.baseCase.cs) <NEW_LINE> if namingFunc is None: <NEW_LINE> <INDENT> def namingFunc(index, _case, _mods): <NEW_LINE> <INDENT> uniquePart = "{:0>4}".format(index) <NEW_LINE> return os.path.join( ".", "case-suite", uniquePart, self.baseCase.title + "-" + uniquePart, ) <NEW_LINE> <DEDENT> <DEDENT> for index, modList in enumerate(self.modifierSets): <NEW_LINE> <INDENT> case = copy.deepcopy(self.baseCase) <NEW_LINE> previousMods = [] <NEW_LINE> for mod in modList: <NEW_LINE> <INDENT> shouldHaveBeenBefore = [ fail for fail in getattr(mod, "FAIL_IF_AFTER", ()) if fail in previousMods ] <NEW_LINE> if any(shouldHaveBeenBefore): <NEW_LINE> <INDENT> raise RuntimeError( "{} must occur before {}".format( mod, ",".join(repr(m) for m in shouldHaveBeenBefore) ) ) <NEW_LINE> <DEDENT> previousMods.append(type(mod)) <NEW_LINE> mod(case.cs, case.bp, case.geom) <NEW_LINE> case.independentVariables.update(mod.independentVariable) <NEW_LINE> <DEDENT> case.cs.path = namingFunc(index, case, modList) <NEW_LINE> caseSuite.add(case) <NEW_LINE> <DEDENT> return caseSuite
Class for constructing a CaseSuite from combinations of modifications on base inputs. Attributes ---------- baseCase : armi.cases.case.Case A Case object to perturb modifierSets : list(tuple(InputModifier)) Contains a list of tuples of ``InputModifier`` instances. A single case is constructed by running a series (the tuple) of InputModifiers on the case. NOTE: This is public such that someone could pop an item out of the list if it is known to not work, or be unnecessary.
62598fb5cc0a2c111447b0ec
class LogRequestHandler(DatagramRequestHandler): <NEW_LINE> <INDENT> def handle(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.rfile.getvalue() <NEW_LINE> data = data.decode('utf-8') <NEW_LINE> log_record = json.loads(data) <NEW_LINE> logger_instance = LoggerInstance(log_record['name'],log_record['time']) <NEW_LINE> if (log_record['method'] == 'write'): <NEW_LINE> <INDENT> logger_instance.write_log_file( log_record['time'], log_record['priority'], log_record['content'] ) <NEW_LINE> <DEDENT> elif (log_record['method'] == 'zip'): <NEW_LINE> <INDENT> logger_instance.zip_log_file() <NEW_LINE> pass <NEW_LINE> <DEDENT> elif (log_record['method'] == 'create'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.wfile.write('status:ok'.encode()) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.wfile.write(('status:%s' % e.__repr__()).encode())
日志服务处理流程
62598fb557b8e32f52508189
class UserAddonSettingsSerializer(JSONAPISerializer): <NEW_LINE> <INDENT> id = ser.CharField(source='config.short_name', read_only=True) <NEW_LINE> user_has_auth = ser.BooleanField(source='has_auth', read_only=True) <NEW_LINE> links = LinksField({ 'self': 'get_absolute_url', 'accounts': 'account_links', }) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_type(request): <NEW_LINE> <INDENT> return get_kebab_snake_case_field(request.version, 'user-addons') <NEW_LINE> <DEDENT> <DEDENT> def get_absolute_url(self, obj): <NEW_LINE> <INDENT> return absolute_reverse( 'users:user-addon-detail', kwargs={ 'provider': obj.config.short_name, 'user_id': self.context['request'].parser_context['kwargs']['user_id'], 'version': self.context['request'].parser_context['kwargs']['version'], }, ) <NEW_LINE> <DEDENT> def account_links(self, obj): <NEW_LINE> <INDENT> if hasattr(obj, 'external_accounts'): <NEW_LINE> <INDENT> return { account._id: { 'account': absolute_reverse( 'users:user-external_account-detail', kwargs={ 'user_id': obj.owner._id, 'provider': obj.config.short_name, 'account_id': account._id, 'version': self.context['request'].parser_context['kwargs']['version'], }, ), 'nodes_connected': [n.absolute_api_v2_url for n in obj.get_attached_nodes(account)], } for account in obj.external_accounts.all() } <NEW_LINE> <DEDENT> return {}
Overrides UserSerializer to make id required.
62598fb58a349b6b43686315
class NatSrcRuleSet(Resource): <NEW_LINE> <INDENT> PROPERTIES = [ "zone_from", "zone_to", "$rules", "$rules_count" ] <NEW_LINE> def __init__(self, junos, name=None, **kvargs): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> Resource.__init__(self, junos, name, **kvargs) <NEW_LINE> return <NEW_LINE> <DEDENT> self.rule = NatSrcRule(junos, M=self, parent=self) <NEW_LINE> self._manages = ['rule'] <NEW_LINE> Resource.__init__(self, junos, name, **kvargs) <NEW_LINE> <DEDENT> def _xml_at_top(self): <NEW_LINE> <INDENT> return E.security(E.nat(E.source( E('rule-set', E.name(self._name)) ))) <NEW_LINE> <DEDENT> def _xml_hook_read_begin(self, xml): <NEW_LINE> <INDENT> rs = xml.find('.//rule-set') <NEW_LINE> rs.append(E('from')) <NEW_LINE> rs.append(E('to')) <NEW_LINE> rs.append(E.rule(JXML.NAMES_ONLY)) <NEW_LINE> return True <NEW_LINE> <DEDENT> def _xml_at_res(self, xml): <NEW_LINE> <INDENT> return xml.find('.//rule-set') <NEW_LINE> <DEDENT> def _xml_to_py(self, as_xml, to_py): <NEW_LINE> <INDENT> Resource._r_has_xml_status(as_xml, to_py) <NEW_LINE> to_py['zone_from'] = as_xml.find('from/zone').text <NEW_LINE> to_py['zone_to'] = as_xml.find('to/zone').text <NEW_LINE> to_py['$rules'] = [rule.text for rule in as_xml.xpath('.//rule/name')] <NEW_LINE> to_py['$rules_count'] = len(to_py['$rules']) <NEW_LINE> <DEDENT> def _xml_change_zone_from(self, xml): <NEW_LINE> <INDENT> xml.append(E('from', JXML.REPLACE, E.zone(self.should['zone_from']))) <NEW_LINE> return True <NEW_LINE> <DEDENT> def _xml_change_zone_to(self, xml): <NEW_LINE> <INDENT> xml.append(E('to', JXML.REPLACE, E.zone(self.should['zone_to']))) <NEW_LINE> return True <NEW_LINE> <DEDENT> def _r_list(self): <NEW_LINE> <INDENT> get = E.security(E.nat(E.source( E('rule-set', JXML.NAMES_ONLY) ))) <NEW_LINE> got = self.D.rpc.get_config(get) <NEW_LINE> self._rlist = [name.text for name in got.xpath('.//name')] <NEW_LINE> <DEDENT> def _r_catalog(self): <NEW_LINE> <INDENT> get = E.security(E.nat(E.source( E('rule-set') ))) <NEW_LINE> got = self.D.rpc.get_config(get) <NEW_LINE> for ruleset in got.xpath('.//rule-set'): <NEW_LINE> <INDENT> name = ruleset.find("name").text <NEW_LINE> self._rcatalog[name] = {} <NEW_LINE> self._xml_to_py(ruleset, self._rcatalog[name])
[edit security nat source rule-set <name>]
62598fb5d486a94d0ba2c0ab
class Fact(object): <NEW_LINE> <INDENT> def __init__(self, lex=None, semtype=None, syntype='fact',subcat=None): <NEW_LINE> <INDENT> self.lex = lex <NEW_LINE> self.semtype = semtype <NEW_LINE> self.syntype = syntype <NEW_LINE> self.subcat = subcat <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.lex
Facts. They totally cheat and are treated like strings.
62598fb5f548e778e596b67d
class FreqStack3: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.counter = itertools.count(0) <NEW_LINE> self.pq = [] <NEW_LINE> self.count_map = collections.defaultdict(int) <NEW_LINE> <DEDENT> def push(self, x): <NEW_LINE> <INDENT> seq_num = next(self.counter) <NEW_LINE> self.count_map[x] += 1 <NEW_LINE> heapq.heappush(self.pq, [-self.count_map[x], -seq_num, x]) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> entry = heapq.heappop(self.pq) <NEW_LINE> self.count_map[entry[2]] -= 1 <NEW_LINE> return entry[2]
Improved version: Priority Queue + HashMap
62598fb5379a373c97d990f0
class WNC(TalkerSentence): <NEW_LINE> <INDENT> fields = ( ("Distance, Nautical Miles", "dist_nautical_miles"), ("Distance Nautical Miles Unit", "dist_naut_unit"), ("Distance, Kilometers", "dist_km"), ("Distance, Kilometers Unit", "dist_km_unit"), ("Origin Waypoint ID", "waypoint_origin_id"), ("Destination Waypoint ID", "waypoint_dest_id"), )
Distance, Waypoint to Waypoint
62598fb591f36d47f2230f15
class get_memberships_for_an_activity___activity_leader(TestCase): <NEW_LINE> <INDENT> def __init__(self , session=None): <NEW_LINE> <INDENT> super().__init__(session) <NEW_LINE> self.url = hostURL + 'api/memberships/activity/' + activity_code <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> response = api.get(self.session, self.url) <NEW_LINE> if not response.status_code == 200: <NEW_LINE> <INDENT> self.log_error('Expected 200 OK, got {0}.'.format(response.status_code)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> response.json() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.log_error('Expected Json response body, got {0}.'.format(response.text)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not (type(response.json()) is list): <NEW_LINE> <INDENT> self.log_error('Response was not a list.')
Verify that a regular member can fetch memberships for an activity. Pre-Conditions: Valid Authentication Header. Expectations: Endpoint -- api/memberships/activity/:id Expected Status Code -- 200 OK Expected Response Content -- A list of json Objects.
62598fb5a219f33f346c68df
class LanguageServiceGrpcTransport(object): <NEW_LINE> <INDENT> _OAUTH_SCOPES = ( "https://www.googleapis.com/auth/cloud-language", "https://www.googleapis.com/auth/cloud-platform", ) <NEW_LINE> def __init__( self, channel=None, credentials=None, address="language.googleapis.com:443" ): <NEW_LINE> <INDENT> if channel is not None and credentials is not None: <NEW_LINE> <INDENT> raise ValueError( "The `channel` and `credentials` arguments are mutually " "exclusive." ) <NEW_LINE> <DEDENT> if channel is None: <NEW_LINE> <INDENT> channel = self.create_channel(address=address, credentials=credentials) <NEW_LINE> <DEDENT> self._channel = channel <NEW_LINE> self._stubs = { "language_service_stub": language_service_pb2_grpc.LanguageServiceStub( channel ) } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_channel( cls, address="language.googleapis.com:443", credentials=None, **kwargs ): <NEW_LINE> <INDENT> return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def channel(self): <NEW_LINE> <INDENT> return self._channel <NEW_LINE> <DEDENT> @property <NEW_LINE> def analyze_sentiment(self): <NEW_LINE> <INDENT> return self._stubs["language_service_stub"].AnalyzeSentiment <NEW_LINE> <DEDENT> @property <NEW_LINE> def analyze_entities(self): <NEW_LINE> <INDENT> return self._stubs["language_service_stub"].AnalyzeEntities <NEW_LINE> <DEDENT> @property <NEW_LINE> def analyze_entity_sentiment(self): <NEW_LINE> <INDENT> return self._stubs["language_service_stub"].AnalyzeEntitySentiment <NEW_LINE> <DEDENT> @property <NEW_LINE> def analyze_syntax(self): <NEW_LINE> <INDENT> return self._stubs["language_service_stub"].AnalyzeSyntax <NEW_LINE> <DEDENT> @property <NEW_LINE> def classify_text(self): <NEW_LINE> <INDENT> return self._stubs["language_service_stub"].ClassifyText <NEW_LINE> <DEDENT> @property <NEW_LINE> def annotate_text(self): <NEW_LINE> <INDENT> return self._stubs["language_service_stub"].AnnotateText
gRPC transport class providing stubs for google.cloud.language.v1 LanguageService API. The transport provides access to the raw gRPC stubs, which can be used to take advantage of advanced features of gRPC.
62598fb54e4d5625663724fb
class RowProxy(BaseRowProxy): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __contains__(self, key): <NEW_LINE> <INDENT> return self._parent._has_key(key) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return { '_parent': self._parent, '_row': tuple(self) } <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self._parent = parent = state['_parent'] <NEW_LINE> self._row = state['_row'] <NEW_LINE> self._processors = parent._processors <NEW_LINE> self._keymap = parent._keymap <NEW_LINE> <DEDENT> __hash__ = None <NEW_LINE> def _op(self, other, op): <NEW_LINE> <INDENT> return op(tuple(self), tuple(other)) if isinstance(other, RowProxy) else op(tuple(self), other) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self._op(other, operator.lt) <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return self._op(other, operator.le) <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return self._op(other, operator.ge) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self._op(other, operator.gt) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._op(other, operator.eq) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self._op(other, operator.ne) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(tuple(self)) <NEW_LINE> <DEDENT> def has_key(self, key): <NEW_LINE> <INDENT> return self._parent._has_key(key) <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return [(key, self[key]) for key in self.keys()] <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self._parent.keys <NEW_LINE> <DEDENT> def iterkeys(self): <NEW_LINE> <INDENT> return iter(self._parent.keys) <NEW_LINE> <DEDENT> def itervalues(self): <NEW_LINE> <INDENT> return iter(self)
Proxy values from a single cursor row. Mostly follows "ordered dictionary" behavior, mapping result values to the string-based column name, the integer position of the result in the row, as well as Column instances which can be mapped to the original Columns that produced this result set (for results that correspond to constructed SQL expressions).
62598fb53d592f4c4edbaf9a
class AtfaDeviceManager(object): <NEW_LINE> <INDENT> def __init__(self, atft_manager): <NEW_LINE> <INDENT> self.atft_manager = atft_manager <NEW_LINE> <DEDENT> def GetSerial(self): <NEW_LINE> <INDENT> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> self.atft_manager.atfa_dev.Oem('serial') <NEW_LINE> <DEDENT> def SwitchStorage(self): <NEW_LINE> <INDENT> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> self.atft_manager.atfa_dev.Oem('storage') <NEW_LINE> <DEDENT> def ProcessKey(self): <NEW_LINE> <INDENT> self.SetTime() <NEW_LINE> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> self.atft_manager.atfa_dev.Oem('process-keybundle') <NEW_LINE> <DEDENT> def Reboot(self): <NEW_LINE> <INDENT> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> self.atft_manager.atfa_dev.Oem('reboot') <NEW_LINE> <DEDENT> def Shutdown(self): <NEW_LINE> <INDENT> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> self.atft_manager.atfa_dev.Oem('shutdown') <NEW_LINE> <DEDENT> def CheckStatus(self): <NEW_LINE> <INDENT> if not self.atft_manager.product_info: <NEW_LINE> <INDENT> raise ProductNotSpecifiedException() <NEW_LINE> <DEDENT> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> self.atft_manager.atfa_dev.keys_left = -1 <NEW_LINE> out = self.atft_manager.atfa_dev.Oem( 'num-keys ' + self.atft_manager.product_info.product_id, True) <NEW_LINE> for line in out.splitlines(): <NEW_LINE> <INDENT> if line.startswith('(bootloader) '): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.atft_manager.atfa_dev.keys_left = int( line.replace('(bootloader) ', '')) <NEW_LINE> return <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise FastbootFailure( 'ATFA device response has invalid format') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> raise FastbootFailure('ATFA device response has invalid format') <NEW_LINE> <DEDENT> def SetTime(self): <NEW_LINE> <INDENT> AtftManager.CheckDevice(self.atft_manager.atfa_dev) <NEW_LINE> time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') <NEW_LINE> self.atft_manager.atfa_dev.Oem('set-date ' + time)
The class to manager ATFA device related operations.
62598fb5ec188e330fdf896a
class GitOpen(InterfaceNonView): <NEW_LINE> <INDENT> def __init__(self, path, revision): <NEW_LINE> <INDENT> InterfaceNonView.__init__(self) <NEW_LINE> self.vcs = rabbitvcs.vcs.VCS() <NEW_LINE> self.git = self.vcs.git(path) <NEW_LINE> if revision: <NEW_LINE> <INDENT> revision_obj = self.git.revision(revision) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> revision_obj = self.git.revision("HEAD") <NEW_LINE> <DEDENT> dest_dir = rabbitvcs.util.helper.get_tmp_path("rabbitvcs-" + unicode(revision)) <NEW_LINE> self.git.export( path, dest_dir, revision=revision_obj ) <NEW_LINE> repo_path = self.git.find_repository_path(path) <NEW_LINE> relative_path = path <NEW_LINE> if path.startswith(repo_path): <NEW_LINE> <INDENT> relative_path = path[len(repo_path)+1:] <NEW_LINE> <DEDENT> dest_path = "%s/%s" % (dest_dir, relative_path) <NEW_LINE> rabbitvcs.util.helper.open_item(dest_path) <NEW_LINE> raise SystemExit()
This class provides a handler to open tracked files.
62598fb523849d37ff85118d
class PlotHistogram(PlotStream): <NEW_LINE> <INDENT> format = 'histogram' <NEW_LINE> def __init__(self, streamObj, *args, **keywords): <NEW_LINE> <INDENT> PlotStream.__init__(self, streamObj, *args, **keywords) <NEW_LINE> <DEDENT> def _extractData(self, dataValueLegit=True): <NEW_LINE> <INDENT> data = {} <NEW_LINE> dataTick = {} <NEW_LINE> countMin = 0 <NEW_LINE> countMax = 0 <NEW_LINE> if self.flatten: <NEW_LINE> <INDENT> sSrc = self.streamObj.flat <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sSrc = self.streamObj <NEW_LINE> <DEDENT> dataValues = [] <NEW_LINE> for noteObj in sSrc.getElementsByClass(note.Note): <NEW_LINE> <INDENT> value = self.fx(noteObj) <NEW_LINE> if value not in dataValues: <NEW_LINE> <INDENT> dataValues.append(value) <NEW_LINE> <DEDENT> <DEDENT> dataValues.sort() <NEW_LINE> for noteObj in sSrc.getElementsByClass(note.Note): <NEW_LINE> <INDENT> if dataValueLegit: <NEW_LINE> <INDENT> value = self.fx(noteObj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = dataValues.index(self.fx(noteObj)) <NEW_LINE> <DEDENT> if value not in data.keys(): <NEW_LINE> <INDENT> data[value] = 0 <NEW_LINE> dataTick[value+.4] = self.fxTick(noteObj) <NEW_LINE> <DEDENT> data[value] += 1 <NEW_LINE> if data[value] >= countMax: <NEW_LINE> <INDENT> countMax = data[value] <NEW_LINE> <DEDENT> <DEDENT> data = data.items() <NEW_LINE> data.sort() <NEW_LINE> dataTick = dataTick.items() <NEW_LINE> dataTick.sort() <NEW_LINE> xTicks = dataTick <NEW_LINE> yTicks = [] <NEW_LINE> yTickStep = int(round(countMax / 8.)) <NEW_LINE> if yTickStep <= 1: <NEW_LINE> <INDENT> yTickStep = 2 <NEW_LINE> <DEDENT> for y in range(0, countMax+1, yTickStep): <NEW_LINE> <INDENT> yTicks.append([y, '%s' % y]) <NEW_LINE> <DEDENT> yTicks.sort() <NEW_LINE> return data, xTicks, yTicks
Base class for Stream plotting classes.
62598fb5f9cc0f698b1c5339
class Categorizable(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def declare_categorizable(cls, category_type, single, plural, ation): <NEW_LINE> <INDENT> setattr( cls, plural, association_proxy( ation, 'category', creator=lambda category: Categorization( category_id=category.id, category_type=category.__class__.__name__, categorizable_type=cls.__name__ ) ) ) <NEW_LINE> joinstr = ( 'and_(' 'foreign(Categorization.categorizable_id) == {type}.id, ' 'foreign(Categorization.categorizable_type) == "{type}", ' 'foreign(Categorization.category_type) == "{category_type}"' ')' ) <NEW_LINE> joinstr = joinstr.format(type=cls.__name__, category_type=category_type) <NEW_LINE> backref = '{type}_categorizable_{category_type}'.format( type=cls.__name__, category_type=category_type, ) <NEW_LINE> return db.relationship( 'Categorization', primaryjoin=joinstr, backref=backref, cascade='all, delete-orphan', ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _filter_by_category(cls, category_type, predicate): <NEW_LINE> <INDENT> from ggrc.models.category import CategoryBase <NEW_LINE> return Categorization.query.join(CategoryBase).filter( (Categorization.categorizable_type == cls.__name__) & (Categorization.categorizable_id == cls.id) & predicate(CategoryBase.name) ).exists()
Subclasses **MUST** provide a declared_attr method that defines the relationship and association_proxy. For example: .. code-block:: python @declared_attr def control_categorizations(cls): return cls.categorizations( 'control_categorizations', 'control_categories', 100, )
62598fb55fdd1c0f98e5e068
class DualMotorController: <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def set_speeds(self, speed_left, speed_right): <NEW_LINE> <INDENT> pass
Abstract base class for dual motor controllers.
62598fb55fcc89381b2661b9
class ValidActions(collections.namedtuple( "ValidActions", ["types", "functions"])): <NEW_LINE> <INDENT> __slots__ = ()
The set of types and functions that are valid for an agent to use. Attributes: types: A namedtuple of the types that the functions require. Unlike TYPES above, this includes the sizes for screen and minimap. functions: A namedtuple of all the functions.
62598fb501c39578d7f12e54
class ResultCallback(CallbackBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ResultsCallback, self).__init__(*args, **kwargs) <NEW_LINE> self.task_ok = {} <NEW_LINE> self.task_unreachable = {} <NEW_LINE> self.task_failed = {} <NEW_LINE> self.task_skipped = {} <NEW_LINE> self.task_stats = {} <NEW_LINE> <DEDENT> def v2_runner_on_unreachable(self, result): <NEW_LINE> <INDENT> self.task_unreachable[result._host.get_name()] = result <NEW_LINE> <DEDENT> def v2_runner_on_ok(self, result, *args, **kwargs): <NEW_LINE> <INDENT> self.task_ok[result._host.get_name()] = result <NEW_LINE> <DEDENT> def v2_runner_on_failed(self, result, *args, **kwargs): <NEW_LINE> <INDENT> self.task_failed[result._host.get_name()] = result <NEW_LINE> <DEDENT> def v2_runner_on_skipped(self, result, *args, **kwargs): <NEW_LINE> <INDENT> self.task_skipped[result._host.get_name()] = result <NEW_LINE> <DEDENT> def v2_runner_on_stats(self, result, *args, **kwargs): <NEW_LINE> <INDENT> self.task_stats[result._host.get_name()] = result
A sample callback plugin used for performing an action as results come in If you want to collect all results into a single object for processing at the end of the execution, look into utilizing the ``json`` callback plugin or writing your own custom callback plugin
62598fb52c8b7c6e89bd389f
class PlaceHandler(web.RequestHandler): <NEW_LINE> <INDENT> @web.asynchronous <NEW_LINE> def get(self, uuid, fragment=None): <NEW_LINE> <INDENT> if uuid is None or fragment is None: <NEW_LINE> <INDENT> api.request_place(uuid, session=session) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Invalid UUID: ' + uuid + '/' + fragment) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> @web.asynchronous <NEW_LINE> def post(self, uuid, fragment=None): <NEW_LINE> <INDENT> if uuid is None and not fragment: <NEW_LINE> <INDENT> other_opts = {} <NEW_LINE> place_dict = api.create_place(session=session, **other_opts) <NEW_LINE> self.write(json.dumps(place_dict)) <NEW_LINE> self.finish() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Invalid UUID: ' + uuid + '/' + fragment) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> @web.asynchronous <NEW_LINE> def put(self, uuid, fragment=None): <NEW_LINE> <INDENT> if uuid is not None: <NEW_LINE> <INDENT> other_opts = {} <NEW_LINE> place_dict = api.update_place(uuid, session=session, **other_opts) <NEW_LINE> self.write(json.dumps(place_dict)) <NEW_LINE> self.finish() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Invalid UUID: ' + uuid + '/' + fragment) <NEW_LINE> <DEDENT> return
Handles create (POST), retrieve (GET), update (PUT), delete (DELETE), and query (GET) for Places.
62598fb566656f66f7d5a4cb
class LogTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.logfile = "/var/log/docker/install.log" <NEW_LINE> self.install_log = Log() <NEW_LINE> <DEDENT> def test_logfile(self): <NEW_LINE> <INDENT> assert os.path.exists(self.logfile) == 1 <NEW_LINE> <DEDENT> def test_write_log(self): <NEW_LINE> <INDENT> open(self.logfile, 'w').close() <NEW_LINE> self.install_log.write_log("Test1") <NEW_LINE> with open(self.logfile, "r") as logfile: <NEW_LINE> <INDENT> logs = logfile.readlines() <NEW_LINE> logfile.close() <NEW_LINE> <DEDENT> for line in logs: <NEW_LINE> <INDENT> self.assertIn('Test1', line, msg="Log message was not properly written to the logfile.") <NEW_LINE> <DEDENT> <DEDENT> def test_write_log_console(self): <NEW_LINE> <INDENT> open(self.logfile, 'w').close() <NEW_LINE> self.install_log.write_log_console("Test2", "Test3") <NEW_LINE> with open(self.logfile, "r") as logfile: <NEW_LINE> <INDENT> logs = logfile.readlines() <NEW_LINE> logfile.close() <NEW_LINE> <DEDENT> self.assertIn('Test2', logs[2], msg="Log message was not properly written to the logfile.") <NEW_LINE> self.assertIn('Test3', logs[3], msg="Log message was not properly written to the logfile.") <NEW_LINE> <DEDENT> def test_step_complete(self): <NEW_LINE> <INDENT> open(self.logfile, 'w').close() <NEW_LINE> self.install_log.step_complete() <NEW_LINE> with open(self.logfile, "r") as logfile: <NEW_LINE> <INDENT> logs = logfile.readlines() <NEW_LINE> logfile.close() <NEW_LINE> <DEDENT> for line in logs: <NEW_LINE> <INDENT> self.assertIn('Complete', line, msg="Log message was not properly written to the logfile.")
Tests for log.py
62598fb5cc0a2c111447b0ed
class BaseHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(BaseHandler, self).__init__(*args, **kwargs) <NEW_LINE> urlfetch.set_default_fetch_deadline(60) <NEW_LINE> <DEDENT> def check_csrf(self): <NEW_LINE> <INDENT> origin = self.request.headers.get('origin') + '/' <NEW_LINE> expected = self.request.host_url + '/' <NEW_LINE> if not (origin and origin == expected): <NEW_LINE> <INDENT> logging.error('csrf check failed for %s, origin: %r', self.request.url, origin) <NEW_LINE> self.abort(403) <NEW_LINE> <DEDENT> <DEDENT> def dispatch(self): <NEW_LINE> <INDENT> sessions_config = self.app.config['webapp2_extras.sessions'] <NEW_LINE> if not sessions_config['secret_key']: <NEW_LINE> <INDENT> sessions_config['secret_key'] = get_session_secret() <NEW_LINE> <DEDENT> self.session_store = sessions.get_store(request=self.request) <NEW_LINE> try: <NEW_LINE> <INDENT> webapp2.RequestHandler.dispatch(self) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.session_store.save_sessions(self.response) <NEW_LINE> <DEDENT> <DEDENT> @webapp2.cached_property <NEW_LINE> def session(self): <NEW_LINE> <INDENT> return self.session_store.get_session() <NEW_LINE> <DEDENT> def render(self, template, context): <NEW_LINE> <INDENT> template = JINJA_ENVIRONMENT.get_template(template) <NEW_LINE> self.response.write(template.render(context))
Base class for Handlers that render Jinja templates.
62598fb5d486a94d0ba2c0ac
@tf_export("IndexedSlicesSpec") <NEW_LINE> class IndexedSlicesSpec(type_spec.TypeSpec): <NEW_LINE> <INDENT> __slots__ = ["_shape", "_values_dtype", "_indices_dtype", "_dense_shape_dtype", "_indices_shape"] <NEW_LINE> value_type = property(lambda self: IndexedSlices) <NEW_LINE> def __init__(self, shape=None, dtype=dtypes.float32, indices_dtype=dtypes.int64, dense_shape_dtype=None, indices_shape=None): <NEW_LINE> <INDENT> self._shape = tensor_shape.as_shape(shape) <NEW_LINE> self._values_dtype = dtypes.as_dtype(dtype) <NEW_LINE> self._indices_dtype = dtypes.as_dtype(indices_dtype) <NEW_LINE> if dense_shape_dtype is None: <NEW_LINE> <INDENT> self._dense_shape_dtype = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._dense_shape_dtype = dtypes.as_dtype(dense_shape_dtype) <NEW_LINE> <DEDENT> self._indices_shape = tensor_shape.as_shape(indices_shape) <NEW_LINE> <DEDENT> def _serialize(self): <NEW_LINE> <INDENT> return (self._shape, self._values_dtype, self._indices_dtype, self._dense_shape_dtype, self._indices_shape) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _component_specs(self): <NEW_LINE> <INDENT> value_shape = self._indices_shape.concatenate(self._shape[1:]) <NEW_LINE> specs = [ tensor_spec.TensorSpec(value_shape, self._values_dtype), tensor_spec.TensorSpec(self._indices_shape, self._indices_dtype)] <NEW_LINE> if self._dense_shape_dtype is not None: <NEW_LINE> <INDENT> specs.append( tensor_spec.TensorSpec([self._shape.ndims], self._dense_shape_dtype)) <NEW_LINE> <DEDENT> return tuple(specs) <NEW_LINE> <DEDENT> def _to_components(self, value): <NEW_LINE> <INDENT> if value.dense_shape is None: <NEW_LINE> <INDENT> return (value.values, value.indices) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (value.values, value.indices, value.dense_shape) <NEW_LINE> <DEDENT> <DEDENT> def _from_components(self, tensor_list): <NEW_LINE> <INDENT> return IndexedSlices(*tensor_list)
Type specification for a `tf.IndexedSlices`.
62598fb5009cb60464d015fd
class PageWrapper(ParamWrapper): <NEW_LINE> <INDENT> def __init__(self, param): <NEW_LINE> <INDENT> ParamWrapper.__init__(self, param) <NEW_LINE> <DEDENT> def getLabel(self): <NEW_LINE> <INDENT> return self._param.getLabel() <NEW_LINE> <DEDENT> @QtCore.Signal <NEW_LINE> def changed(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> label = QtCore.Property(unicode, getLabel, constant=True)
Gui class, which maps a ParamPage.
62598fb5283ffb24f3cf3968
class UpdateCatalanCollectionbyUserHandler(baseapp.BaseAppHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> logging.info('fixing catalan') <NEW_LINE> place_query = db.GqlQuery( 'SELECT __key__ FROM PlacedLit WHERE user_email = :1', 'espaisescrits@gmail.com') <NEW_LINE> collection = collections.Collection().get_named('catalan') <NEW_LINE> for place in place_query: <NEW_LINE> <INDENT> if place not in collection.scenes: <NEW_LINE> <INDENT> logging.info('place added: %s', place) <NEW_LINE> collection.scenes.append(place) <NEW_LINE> <DEDENT> <DEDENT> collection.put() <NEW_LINE> place_query = db.GqlQuery( 'SELECT __key__ FROM PlacedLit WHERE user_email = :1', 'fjoseppla@gmail.com') <NEW_LINE> collection = collections.Collection().get_named('catalan') <NEW_LINE> for place in place_query: <NEW_LINE> <INDENT> if place not in collection.scenes: <NEW_LINE> <INDENT> logging.info('place added: %s', place) <NEW_LINE> collection.scenes.append(place) <NEW_LINE> <DEDENT> <DEDENT> collection.put()
update catalan users
62598fb5adb09d7d5dc0a668
class Circle: <NEW_LINE> <INDENT> def __init__(self, a=0, b=0, r=0): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> self.b = b <NEW_LINE> self.r = r <NEW_LINE> self.A = -2*self.a <NEW_LINE> self.B = -2*self.b <NEW_LINE> self.C = (self.a**2)+(self.b**2)-(self.r**2) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"(x-{self.a})^2 + (y-{self.b})^2 = {self.r**2:2f}"
(x-a)^2 + (y-b)^2 = r^2 or x^2 + y^2 + Ax + By + C = 0
62598fb53346ee7daa3376b5
class TransformVisitor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.transforms = collections.defaultdict(list) <NEW_LINE> <DEDENT> def _transform(self, node): <NEW_LINE> <INDENT> cls = node.__class__ <NEW_LINE> if cls not in self.transforms: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> transforms = self.transforms[cls] <NEW_LINE> orig_node = node <NEW_LINE> for transform_func, predicate in transforms: <NEW_LINE> <INDENT> if predicate is None or predicate(node): <NEW_LINE> <INDENT> ret = transform_func(node) <NEW_LINE> if ret is not None: <NEW_LINE> <INDENT> if node is not orig_node: <NEW_LINE> <INDENT> warnings.warn('node %s substituted multiple times' % node) <NEW_LINE> <DEDENT> node = ret <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return node <NEW_LINE> <DEDENT> def _visit(self, node): <NEW_LINE> <INDENT> if hasattr(node, '_astroid_fields'): <NEW_LINE> <INDENT> for field in node._astroid_fields: <NEW_LINE> <INDENT> value = getattr(node, field) <NEW_LINE> visited = self._visit_generic(value) <NEW_LINE> setattr(node, field, visited) <NEW_LINE> <DEDENT> <DEDENT> return self._transform(node) <NEW_LINE> <DEDENT> def _visit_generic(self, node): <NEW_LINE> <INDENT> if isinstance(node, list): <NEW_LINE> <INDENT> return [self._visit_generic(child) for child in node] <NEW_LINE> <DEDENT> elif isinstance(node, tuple): <NEW_LINE> <INDENT> return tuple(self._visit_generic(child) for child in node) <NEW_LINE> <DEDENT> return self._visit(node) <NEW_LINE> <DEDENT> def register_transform(self, node_class, transform, predicate=None): <NEW_LINE> <INDENT> self.transforms[node_class].append((transform, predicate)) <NEW_LINE> <DEDENT> def unregister_transform(self, node_class, transform, predicate=None): <NEW_LINE> <INDENT> self.transforms[node_class].remove((transform, predicate)) <NEW_LINE> <DEDENT> def visit(self, module): <NEW_LINE> <INDENT> module.body = [self._visit(child) for child in module.body] <NEW_LINE> return self._transform(module)
A visitor for handling transforms. The standard approach of using it is to call :meth:`~visit` with an *astroid* module and the class will take care of the rest, walking the tree and running the transforms for each encountered node.
62598fb567a9b606de5460ab
class Capabilities(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._flags = set() <NEW_LINE> <DEDENT> def set_flag(self, flag): <NEW_LINE> <INDENT> self._flags.add(flag) <NEW_LINE> <DEDENT> def clear_flag(self, flag): <NEW_LINE> <INDENT> self._flags.remove(flag) <NEW_LINE> <DEDENT> def __contains__(self, flag): <NEW_LINE> <INDENT> return flag in self._flags
Representation of VM capabilities.
62598fb5aad79263cf42e8af
class AddDataToProjectDataHandler(BaseHandler): <NEW_LINE> <INDENT> mongodb_service = syringe.inject('mongodb-service') <NEW_LINE> @authenticated_async <NEW_LINE> @tornado.web.asynchronous <NEW_LINE> def post(self, p_id, d_id): <NEW_LINE> <INDENT> datasets = self.mongodb_service.add_dataset_to_project( user=self.current_user, project_id=p_id, dataset_id=d_id, db=self.application.syncdb ) <NEW_LINE> if datasets: <NEW_LINE> <INDENT> self.write(json.dumps([d for d in datasets])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise tornado.web.HTTPError(404, 'No dataset found, aborting') <NEW_LINE> <DEDENT> self.finish()
This method is used to delete data set belongd to given project, we are useing the get request to trigger delete, this is very bad approach, we need to use delete method to acomplish this task.
62598fb51f5feb6acb162cfa
class TestVoiceprintApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = openapi_client.api.voiceprint_api.VoiceprintApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_delete(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_query(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_register(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_threshold(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_verify(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_verify1ton(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_verifytopn(self): <NEW_LINE> <INDENT> pass
VoiceprintApi unit test stubs
62598fb54e4d5625663724fd
class Listener(models.Model): <NEW_LINE> <INDENT> mount = models.ForeignKey(Mount, related_name='listeners') <NEW_LINE> user = models.CharField(max_length=20) <NEW_LINE> password = models.CharField(max_length=20) <NEW_LINE> start = models.DateTimeField() <NEW_LINE> end = models.DateTimeField() <NEW_LINE> duration = models.IntegerField() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s on %s for %d seconds" % (self.user, self.mount, self.duration)
A model representing a listener to a mount. Instances of this model are only created after the listener is disconnected
62598fb5aad79263cf42e8b0
@dataclass <NEW_LINE> class RedactedEvent(Event): <NEW_LINE> <INDENT> type: str = field() <NEW_LINE> redacter: str = field() <NEW_LINE> reason: Optional[str] = field() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> reason = ", reason: {}".format(self.reason) if self.reason else "" <NEW_LINE> return "Redacted event of type {}, by {}{}.".format( self.type, self.redacter, reason ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def event_type(self): <NEW_LINE> <INDENT> return self.type <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @verify(Schemas.redacted_event) <NEW_LINE> def from_dict(cls, parsed_dict): <NEW_LINE> <INDENT> redacter = parsed_dict["unsigned"]["redacted_because"]["sender"] <NEW_LINE> content_dict = parsed_dict["unsigned"]["redacted_because"]["content"] <NEW_LINE> reason = content_dict.get("reason", None) <NEW_LINE> return cls( parsed_dict, parsed_dict["type"], redacter, reason, )
An event that has been redacted. Attributes: type (str): The type of the event that has been redacted. redacter (str): The fully-qualified ID of the user who redacted the event. reason (str, optional): A string describing why the event was redacted, can be None.
62598fb55fcc89381b2661ba
class APIError(Exception): <NEW_LINE> <INDENT> pass
Bucket for errors related to server responses.
62598fb5baa26c4b54d4f394
class account_partner_balance(osv.osv_memory): <NEW_LINE> <INDENT> _inherit = 'account.partner.balance' <NEW_LINE> def _print_report(self, cr, uid, ids, data, context=None): <NEW_LINE> <INDENT> res = super(account_partner_balance, self)._print_report(cr, uid, ids, data, context=context) <NEW_LINE> res['report_name'] = 'account.partner.balance.webkit' <NEW_LINE> return res
This wizard will provide the partner balance report by periods, between any two dates.
62598fb521bff66bcd722d44
class MinimaxAgentN( SearchAgent ): <NEW_LINE> <INDENT> def getAction( self, gameState ): <NEW_LINE> <INDENT> legalActions = gameState.getLegalActions(0) <NEW_LINE> nextStatesFromLegalActions = [gameState.generateSuccessor(0, action) for action in legalActions] <NEW_LINE> values = [self.miniMaxValue(1, nextGameState, self.depth - 1) for nextGameState in nextStatesFromLegalActions] <NEW_LINE> listOfAllMaxValues = [] <NEW_LINE> maxValue = max(values) <NEW_LINE> for i in range(0, len(values)): <NEW_LINE> <INDENT> if values[i] == maxValue: <NEW_LINE> <INDENT> listOfAllMaxValues.append(i) <NEW_LINE> <DEDENT> <DEDENT> idx = random.randint(0, len(listOfAllMaxValues) - 1) <NEW_LINE> action = legalActions[listOfAllMaxValues[idx]] <NEW_LINE> return action <NEW_LINE> <DEDENT> def miniMaxValue( self, agentIndex, gameState, depth ): <NEW_LINE> <INDENT> if self.isTerminalNode(gameState, depth): <NEW_LINE> <INDENT> return self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> legalActions = gameState.getLegalActions(agentIndex) <NEW_LINE> nextStatesFromLegalActions = [gameState.generateSuccessor(agentIndex, action) for action in legalActions] <NEW_LINE> if agentIndex == 0: <NEW_LINE> <INDENT> return max([self.miniMaxValue(1 + agentIndex, nextState, depth - 1) for nextState in nextStatesFromLegalActions]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if gameState.getNumberOfAgents() - agentIndex - 1 == 0: <NEW_LINE> <INDENT> return min([self.miniMaxValue(0, nextState, depth - 1) for nextState in nextStatesFromLegalActions]) <NEW_LINE> <DEDENT> return min([self.miniMaxValue(1 + agentIndex, nextState, depth - 1) for nextState in nextStatesFromLegalActions])
Minimax agent with n ghosts.
62598fb5a8370b77170f04ba
class ErrClusterConfig(Exception): <NEW_LINE> <INDENT> def __init__(self, cluster): <NEW_LINE> <INDENT> super().__init__("The cluster configuration for %s is not available." % cluster)
Cluster configuration not found We need the configuration during the binding to set the connection string Constructor Args: cluster (str): Atlas cluster name
62598fb54a966d76dd5eefb4
class RefundSuccessfulSubOrder(resource.Resource): <NEW_LINE> <INDENT> app = 'mall2' <NEW_LINE> resource = 'refund_successful_sub_order' <NEW_LINE> @login_required <NEW_LINE> def api_put(request): <NEW_LINE> <INDENT> order_id = int(request.POST['order_id']) <NEW_LINE> delivery_item_id = int(request.POST['delivery_item_id']) <NEW_LINE> try: <NEW_LINE> <INDENT> sub_order = Order.objects.filter(id=delivery_item_id).first() <NEW_LINE> if sub_order and sub_order.origin_order_id == order_id and sub_order.webapp_id == request.user_profile.webapp_id: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = create_response(500) <NEW_LINE> response.data = {'msg': "非法操作,订单状态不允许进行该操作"} <NEW_LINE> return response.get_response() <NEW_LINE> <DEDENT> sub_order = Order.objects.get(id=delivery_item_id) <NEW_LINE> order_has_refund = OrderHasRefund.objects.get(delivery_item_id=sub_order.id) <NEW_LINE> refund_cash_money = order_has_refund.cash <NEW_LINE> refund_weizoom_card_money = order_has_refund.weizoom_card_money <NEW_LINE> sub_order_target_status = ORDER_STATUS_REFUNDED <NEW_LINE> Order.objects.filter(id=delivery_item_id).update(status=sub_order_target_status) <NEW_LINE> Order.objects.filter(id=order_id).update(final_price=(F('final_price')-refund_cash_money), weizoom_card_money=(F('weizoom_card_money')-refund_weizoom_card_money)) <NEW_LINE> OrderHasRefund.objects.filter(delivery_item_id=delivery_item_id).update(finished=True) <NEW_LINE> operation_name = request.user.username <NEW_LINE> action_msg = '退款完成' <NEW_LINE> mall_api.record_status_log(sub_order.order_id, operation_name, sub_order.status, sub_order_target_status) <NEW_LINE> mall_api.record_operation_log(sub_order.order_id, operation_name, action_msg,sub_order) <NEW_LINE> mall_api.restore_product_stock_by_order(sub_order) <NEW_LINE> mall_api.update_order_status_by_sub_order(sub_order, operation_name, action_msg) <NEW_LINE> response = create_response(200) <NEW_LINE> return response.get_response() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> from eaglet.core import watchdog <NEW_LINE> watchdog.alert({ 'uuid': 'refund_order_error', 'traceback': unicode_full_stack(), 'order_id': order_id, 'delivery_item_id': delivery_item_id })
子订单退款成功
62598fb5cc0a2c111447b0ef