code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Failure(Action): <NEW_LINE> <INDENT> def get_man_conclusion(self, man): <NEW_LINE> <INDENT> print('man failure') <NEW_LINE> <DEDENT> def get_woman_conclusion(self, woman): <NEW_LINE> <INDENT> print('woman failure')
Success class.
6259907a656771135c48ad25
class remove_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'fileid', None, None, ), ) <NEW_LINE> def __init__(self, fileid=None,): <NEW_LINE> <INDENT> self.fileid = fileid <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.fileid = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('remove_args') <NEW_LINE> if self.fileid is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('fileid', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.fileid) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.fileid is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field fileid is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - fileid
6259907a5166f23b2e244dc3
class RecordForm(forms.ModelForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(RecordForm, self).__init__(*args, **kwargs) <NEW_LINE> self.is_update = False <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if 'title' not in self.cleaned_data: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.is_update: <NEW_LINE> <INDENT> if Record.objects.filter(title=self.cleaned_data['title']).count() > 0: <NEW_LINE> <INDENT> raise forms.ValidationError(_("There is already this record in the web.")) <NEW_LINE> <DEDENT> <DEDENT> return self.cleaned_data <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Record <NEW_LINE> fields = ('author', 'description', 'title')
Record Form: form associated to the Record model
6259907aaad79263cf4301a5
class Forwarder(object): <NEW_LINE> <INDENT> def __init__(self, local_bind_address, remote_bind_address, ssh_host='localhost', ssh_port=22, ssh_username='root', ssh_password=None, ssh_private_key=None): <NEW_LINE> <INDENT> self.ssh_host = ssh_host <NEW_LINE> self.ssh_port = ssh_port <NEW_LINE> self.ssh_user = ssh_username <NEW_LINE> self.password = ssh_password <NEW_LINE> self.pkey = ssh_private_key <NEW_LINE> self.local_addr = local_bind_address <NEW_LINE> self.remote_addr = remote_bind_address <NEW_LINE> self.p = None <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.local_addr is None: <NEW_LINE> <INDENT> self.local_bind_host = '' <NEW_LINE> self.local_bind_port = random.choice(range(2000, 65530)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.local_bind_host, self.local_bind_port = self.local_addr <NEW_LINE> <DEDENT> remote_host, remote_port = self.remote_addr <NEW_LINE> client = paramiko.SSHClient() <NEW_LINE> client.load_system_host_keys() <NEW_LINE> client.set_missing_host_key_policy(paramiko.WarningPolicy()) <NEW_LINE> client.connect(self.ssh_host, self.ssh_port, username=self.ssh_user, key_filename=self.pkey, look_for_keys=True, password=self.password) <NEW_LINE> transport = client.get_transport() <NEW_LINE> self.p = Process(target=forward_tunnel, args=(self.local_bind_host, self.local_bind_port, remote_host, remote_port, self.ssh_host, self.ssh_port, self.ssh_user, self.pkey, self.password) ) <NEW_LINE> self.p.start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if isinstance(self.p, Process) and self.p.is_alive(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.p.terminate() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def local_address(self): <NEW_LINE> <INDENT> return self.local_bind_host, self.local_bind_port
forward tcp connection via ssh tunnel example: server = forwarder( ssh_host=host, ssh_port=ssh_port, ssh_username=ssh_username, ssh_private_key=ssh_pkey, ssh_password=ssh_password, local_bind_address=None, remote_bind_address=('127.0.0.1', port), ) server.start() local_bind_host, local_bind_port = server.local_address() ***** now you can access the `local_bind_host`, `local_bind_port` to secure the connection to remote server ***** server.stop()
6259907a8a349b6b43687c47
class ModuleStanza(Stanza): <NEW_LINE> <INDENT> def parse(self): <NEW_LINE> <INDENT> if len(self.toks) < 4: <NEW_LINE> <INDENT> self.syntax() <NEW_LINE> <DEDENT> self.vcc.modname = self.toks[1] <NEW_LINE> self.vcc.mansection = self.toks[2] <NEW_LINE> if len(self.toks) == 4 and is_quoted(self.toks[3]): <NEW_LINE> <INDENT> self.vcc.moddesc = unquote(self.toks[3]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("\nNOTICE: Please put $Module description in quotes.\n") <NEW_LINE> self.vcc.moddesc = " ".join(self.toks[3:]) <NEW_LINE> <DEDENT> self.rstlbl = "vmod_%s(%d)" % (self.vcc.modname, 3) <NEW_LINE> self.vcc.contents.append(self) <NEW_LINE> <DEDENT> def rsthead(self, fo, man): <NEW_LINE> <INDENT> if man: <NEW_LINE> <INDENT> write_rst_hdr(fo, "VMOD " + self.vcc.modname, "=", "=") <NEW_LINE> write_rst_hdr(fo, self.vcc.moddesc, "-", "-") <NEW_LINE> fo.write("\n") <NEW_LINE> fo.write(":Manual section: " + self.vcc.mansection + "\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.rstlbl: <NEW_LINE> <INDENT> fo.write('\n.. _' + self.rstlbl + ':\n') <NEW_LINE> <DEDENT> write_rst_hdr(fo, "VMOD " + self.vcc.modname + ' - ' + self.vcc.moddesc, "=", "=") <NEW_LINE> <DEDENT> if self.vcc.auto_synopsis: <NEW_LINE> <INDENT> write_rst_hdr(fo, "SYNOPSIS", "=") <NEW_LINE> fo.write("\n") <NEW_LINE> fo.write(".. parsed-literal::\n\n") <NEW_LINE> fo.write(' import %s [from "path"]\n' % self.vcc.modname) <NEW_LINE> fo.write(" \n") <NEW_LINE> for c in self.vcc.contents: <NEW_LINE> <INDENT> c.synopsis(fo, man)
$Module modname man_section description ...
6259907a7047854f46340da7
class MultivariateNormalFull(_MultivariateNormalOperatorPD): <NEW_LINE> <INDENT> def __init__(self, mu, sigma, validate_args=False, allow_nan_stats=True, name="MultivariateNormalFull"): <NEW_LINE> <INDENT> parameters = locals() <NEW_LINE> parameters.pop("self") <NEW_LINE> with ops.name_scope(name, values=[sigma]) as ns: <NEW_LINE> <INDENT> cov = operator_pd_full.OperatorPDFull(sigma, verify_pd=validate_args) <NEW_LINE> <DEDENT> super(MultivariateNormalFull, self).__init__( mu, cov, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=ns) <NEW_LINE> self._parameters = parameters
The multivariate normal distribution on `R^k`. This distribution is defined by a 1-D mean `mu` and covariance matrix `sigma`. Evaluation of the pdf, determinant, and sampling are all `O(k^3)` operations. #### Mathematical details With `C = sigma`, the PDF of this distribution is: ``` f(x) = (2 pi)^(-k/2) |det(C)|^(-1/2) exp(-1/2 (x - mu)^T C^{-1} (x - mu)) ``` #### Examples A single multi-variate Gaussian distribution is defined by a vector of means of length `k`, and a covariance matrix of shape `k x k`. Extra leading dimensions, if provided, allow for batches. ```python # Initialize a single 3-variate Gaussian with diagonal covariance. mu = [1, 2, 3.] sigma = [[1, 0, 0], [0, 3, 0], [0, 0, 2.]] dist = tf.contrib.distributions.MultivariateNormalFull(mu, chol) # Evaluate this on an observation in R^3, returning a scalar. dist.pdf([-1, 0, 1]) # Initialize a batch of two 3-variate Gaussians. mu = [[1, 2, 3], [11, 22, 33.]] sigma = ... # shape 2 x 3 x 3, positive definite. dist = tf.contrib.distributions.MultivariateNormalFull(mu, sigma) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11.]] # Shape 2 x 3. dist.pdf(x) ```
6259907abf627c535bcb2ebb
class Character: <NEW_LINE> <INDENT> def __init__(self, name, atk, hp, defense): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.atk = atk <NEW_LINE> self.defense = defense <NEW_LINE> self.hp = hp <NEW_LINE> <DEDENT> def fight(self, opponent): <NEW_LINE> <INDENT> text_box(f"{self.name} attacks {opponent.name}") <NEW_LINE> pygame.display.update() <NEW_LINE> time.sleep(3) <NEW_LINE> dmg = self.atk - (self.atk/opponent.defense) <NEW_LINE> opponent.hp -= dmg <NEW_LINE> text_box(f"{opponent.name} is at {opponent.hp} health!") <NEW_LINE> pygame.display.update() <NEW_LINE> time.sleep(3) <NEW_LINE> text_box(f"{self.name} is at {self.hp} health!") <NEW_LINE> pygame.display.update() <NEW_LINE> time.sleep(3)
Generic character class
6259907a91f36d47f2231b85
class PVMult(PyoPVObject): <NEW_LINE> <INDENT> def __init__(self, input, input2): <NEW_LINE> <INDENT> pyoArgsAssert(self, "pp", input, input2) <NEW_LINE> PyoPVObject.__init__(self) <NEW_LINE> self._input = input <NEW_LINE> self._input2 = input2 <NEW_LINE> input, input2, lmax = convertArgsToLists(self._input, self._input2) <NEW_LINE> self._base_objs = [PVMult_base(wrap(input,i), wrap(input2,i)) for i in range(lmax)] <NEW_LINE> self.play() <NEW_LINE> <DEDENT> def setInput(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "p", x) <NEW_LINE> self._input = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setInput(wrap(x,i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> <DEDENT> def setInput2(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "p", x) <NEW_LINE> self._input2 = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setInput2(wrap(x,i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> <DEDENT> @property <NEW_LINE> def input(self): <NEW_LINE> <INDENT> return self._input <NEW_LINE> <DEDENT> @input.setter <NEW_LINE> def input(self, x): self.setInput(x) <NEW_LINE> @property <NEW_LINE> def input2(self): <NEW_LINE> <INDENT> return self._input2 <NEW_LINE> <DEDENT> @input2.setter <NEW_LINE> def input2(self, x): self.setInput2(x)
Multiply magnitudes from two phase vocoder streaming object. :Parent: :py:class:`PyoPVObject` :Args: input: PyoPVObject Phase vocoder streaming object to process. Frequencies from this pv stream are used to compute the output signal. input2: PyoPVObject Phase vocoder streaming object which gives the second set of magnitudes. Frequencies from this pv stream are not used. .. note:: The two input pv stream must have the same size and overlaps. It is the responsibility of the user to be sure they are consistent. To change the size (or the overlaps) of the phase vocoder process, one must write a function to change both at the same time (see the example below). Another possibility is to use channel expansion to analyse both sounds with the same PVAnal object. >>> s = Server().boot() >>> s.start() >>> sf = FM(carrier=[100,150], ratio=[.999,.5005], index=20, mul=.4) >>> sf2 = SfPlayer(SNDS_PATH+"/transparent.aif", loop=True, mul=.5) >>> pva = PVAnal(sf) >>> pva2 = PVAnal(sf2) >>> pvc = PVMult(pva, pva2) >>> pvs = PVSynth(pvc).out() >>> def size(x): ... pva.size = x ... pva2.size = x >>> def olaps(x): ... pva.overlaps = x ... pva2.overlaps = x
6259907a7047854f46340da8
class RunPython3Tests(TestCommand): <NEW_LINE> <INDENT> def finalize_options(self): <NEW_LINE> <INDENT> TestCommand.finalize_options(self) <NEW_LINE> self.test_args = [] <NEW_LINE> self.test_suite = True <NEW_LINE> <DEDENT> def run_tests(self): <NEW_LINE> <INDENT> file_name = 'test_result_py3.xml' <NEW_LINE> ret = run_tests_and_create_report(file_name, 'multipython', 'model/test_enum.py', 'model/test_exception.py', 'model/test_include.py', ) <NEW_LINE> if ret == 0: <NEW_LINE> <INDENT> print(GREEN + "All Python 3 tests passed." + RESET) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(RED + "At one Python 3 test failed." + RESET) <NEW_LINE> <DEDENT> raise SystemExit(ret)
Run tests compatible with different python implementations.
6259907a3346ee7daa338357
class DefaultSampling(BaseSampling): <NEW_LINE> <INDENT> size:int <NEW_LINE> def __init__(self, margin_of_error:float=0.02, confidence:float=0.99, min_sample_size:int=1000): <NEW_LINE> <INDENT> self.min_sample_size=min_sample_size <NEW_LINE> self.sample_size_method=CochransSampleSize(margin_of_error, confidence) <NEW_LINE> <DEDENT> def prepare(self,relation:'Relation',source_adapter:'source_adapter')->None: <NEW_LINE> <INDENT> self.size=max(self.sample_size_method.size( relation.population_size), self.min_sample_size) <NEW_LINE> self.sample_method=BernoulliSampleMethod(self.size, units='rows')
Basic sampling using :class:`Cochrans <snowshu.samplings.sample_sizes.cochrans_sample_size.CochransSampleSize>` theorum for sample size and :class:`Bernoulli <snowshu.samplings.sample_methods.bernoulli_sample_method.BernoulliSampleMethod>` sampling. This default sampling assumes high volitility in the population Args: margin_of_error: The acceptable error % expressed in a decimal from 0.01 to 0.10 (1% to 10%). Default 0.02 (2%). `https://en.wikipedia.org/wiki/Margin_of_error` confidence: The confidence interval to be observed for the sample expressed in a decimal from 0.01 to 0.99 (1% to 99%). Default 0.99 (99%). `http://www.stat.yale.edu/Courses/1997-98/101/confint.htm` min_sample_size: The minimum number of records to retrieve from the population. Default 1000.
6259907a1b99ca400229022c
class PrepareUpgradeJujuAttempt(SteppedStageAttempt): <NEW_LINE> <INDENT> prepare_upgrade = StageInfo( 'prepare-upgrade-juju', 'Prepare upgrade-juju', report_on=False, ) <NEW_LINE> @classmethod <NEW_LINE> def get_test_info(cls): <NEW_LINE> <INDENT> return dict([cls.prepare_upgrade.as_tuple()]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def factory(cls, upgrade_sequence, agent_stream): <NEW_LINE> <INDENT> if len(upgrade_sequence) < 2: <NEW_LINE> <INDENT> raise ValueError('Not enough paths for upgrade.') <NEW_LINE> <DEDENT> bootstrap_paths = dict( zip(upgrade_sequence[1:], upgrade_sequence[:-1])) <NEW_LINE> return cls(bootstrap_paths) <NEW_LINE> <DEDENT> def __init__(self, bootstrap_paths): <NEW_LINE> <INDENT> super(PrepareUpgradeJujuAttempt, self).__init__() <NEW_LINE> self.bootstrap_paths = bootstrap_paths <NEW_LINE> <DEDENT> def get_bootstrap_client(self, client): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bootstrap_path = self.bootstrap_paths[client.full_path] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise CannotUpgradeToClient(client) <NEW_LINE> <DEDENT> return client.clone_path_cls(bootstrap_path) <NEW_LINE> <DEDENT> def iter_steps(self, client): <NEW_LINE> <INDENT> ba = BootstrapAttempt() <NEW_LINE> bootstrap_client = self.get_bootstrap_client(client) <NEW_LINE> for result in ba.iter_steps(bootstrap_client): <NEW_LINE> <INDENT> result = dict(result) <NEW_LINE> result['test_id'] = self.prepare_upgrade.stage_id <NEW_LINE> yield result
Prepare to run an UpgradeJujuAttempt. This is the bootstrap portion.
6259907a460517430c432d50
class HassAqualinkBinarySensor(AqualinkEntity, BinarySensorEntity): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.dev.label <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return self.dev.is_on <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self) -> BinarySensorDeviceClass | None: <NEW_LINE> <INDENT> if self.name == "Freeze Protection": <NEW_LINE> <INDENT> return BinarySensorDeviceClass.COLD <NEW_LINE> <DEDENT> return None
Representation of a binary sensor.
6259907a283ffb24f3cf528d
class TestPWWave(AbipyTest): <NEW_LINE> <INDENT> def test_base(self): <NEW_LINE> <INDENT> vectors = np.array([1.,0,0, 0,1,0, 0,0,1]) <NEW_LINE> vectors.shape = (3, 3) <NEW_LINE> mesh_443 = Mesh3D((4, 4, 3), vectors) <NEW_LINE> mesh_444 = Mesh3D((4, 4, 4), vectors) <NEW_LINE> repr(mesh_444); str(mesh_444) <NEW_LINE> assert not mesh_443 == mesh_444 <NEW_LINE> <DEDENT> def test_fft(self): <NEW_LINE> <INDENT> vectors = np.array([1.,0,0, 0,1,0, 0,0,1]) <NEW_LINE> vectors.shape = (3, 3) <NEW_LINE> mesh = Mesh3D((12, 3, 5), vectors) <NEW_LINE> extra_dims = [(), 1, (2,), (3,4)] <NEW_LINE> types = [np.float, np.complex] <NEW_LINE> for exdim in extra_dims: <NEW_LINE> <INDENT> for typ in types: <NEW_LINE> <INDENT> fg = mesh.random(dtype=typ, extra_dims=exdim) <NEW_LINE> fr = mesh.fft_g2r(fg) <NEW_LINE> same_fg = mesh.fft_r2g(fr) <NEW_LINE> self.assert_almost_equal(fg, same_fg) <NEW_LINE> int_r = mesh.integrate(fr) <NEW_LINE> int_g = fg[..., 0, 0, 0] <NEW_LINE> self.assert_almost_equal(int_r, int_g)
Test PWWave
6259907a2c8b7c6e89bd51d9
class ManagedCertificate(Certificate): <NEW_LINE> <INDENT> _attribute_map = { 'subject': {'key': 'subject', 'type': 'str'}, 'expiration_date': {'key': 'expirationDate', 'type': 'str'}, 'thumbprint': {'key': 'thumbprint', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ManagedCertificate, self).__init__(**kwargs)
Managed Certificate used for https. :param subject: Subject name in the certificate. :type subject: str :param expiration_date: Certificate expiration date. :type expiration_date: str :param thumbprint: Certificate thumbprint. :type thumbprint: str
6259907a7047854f46340daa
class TemplateRendererTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._template_renderer = ServerInstance.ForLocal().template_renderer <NEW_LINE> <DEDENT> def testSimpleWiring(self): <NEW_LINE> <INDENT> template = Handlebar('hello {{?true}}{{strings.extension}}{{/}}') <NEW_LINE> text, warnings = self._template_renderer.Render(template, None) <NEW_LINE> self.assertEqual('hello extension', text) <NEW_LINE> self.assertEqual([], warnings)
Basic test for TemplateRenderer. When the DataSourceRegistry conversion is finished then we could do some more meaningful tests by injecting a different set of DataSources.
6259907a3346ee7daa338358
class CommServerTestController(legion_test_case.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def CreateTestTask(cls): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--task-hash') <NEW_LINE> parser.add_argument('--os', default='Ubuntu-14.04') <NEW_LINE> args, _ = parser.parse_known_args() <NEW_LINE> task = cls.CreateTask( isolated_hash=args.task_hash, dimensions={'os': args.os, 'pool': 'default'}, idle_timeout_secs=90, connection_timeout_secs=90, verbosity=logging.DEBUG) <NEW_LINE> task.Create() <NEW_LINE> return task <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.task = cls.CreateTestTask() <NEW_LINE> cls.task.WaitForConnection() <NEW_LINE> <DEDENT> def testCommServerTest(self): <NEW_LINE> <INDENT> cmd = [ 'python', 'task.py', '--address', str(common_lib.MY_IP), '--port', str(self.comm_server.port) ] <NEW_LINE> process = self.task.Process(cmd) <NEW_LINE> process.Wait() <NEW_LINE> retcode = process.GetReturncode() <NEW_LINE> if retcode != 0: <NEW_LINE> <INDENT> logging.info('STDOUT:\n%s', process.ReadStdout()) <NEW_LINE> logging.info('STDERR:\n%s', process.ReadStderr()) <NEW_LINE> <DEDENT> self.assertEqual(retcode, 0) <NEW_LINE> logging.info('Success')
A simple example controller for a test.
6259907a99fddb7c1ca63ace
class BaseRecipeAttrViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): <NEW_LINE> <INDENT> authentication_classes = (JWTAuthentication,) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> assigned_only = bool( int(self.request.query_params.get('assigned_only', 0)) ) <NEW_LINE> queryset = self.queryset <NEW_LINE> if assigned_only: <NEW_LINE> <INDENT> queryset = queryset.filter(recipe__isnull=False) <NEW_LINE> <DEDENT> return queryset.filter( user=self.request.user ).order_by('-name').distinct() <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user=self.request.user)
Base class for recipe attributes
6259907a4c3428357761bca8
class SubpixelMaxima2D(Layer): <NEW_LINE> <INDENT> def __init__( self, kernel_size, sigma, upsample_factor, index=None, coordinate_scale=1.0, confidence_scale=1.0, data_format=None, **kwargs ): <NEW_LINE> <INDENT> super(SubpixelMaxima2D, self).__init__(**kwargs) <NEW_LINE> self.data_format = normalize_data_format(data_format) <NEW_LINE> self.input_spec = InputSpec(ndim=4) <NEW_LINE> self.kernel_size = kernel_size <NEW_LINE> self.sigma = sigma <NEW_LINE> self.upsample_factor = upsample_factor <NEW_LINE> self.index = index <NEW_LINE> self.coordinate_scale = coordinate_scale <NEW_LINE> self.confidence_scale = confidence_scale <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> if self.data_format == "channels_first": <NEW_LINE> <INDENT> n_channels = self.index if self.index is not None else input_shape[1] <NEW_LINE> <DEDENT> elif self.data_format == "channels_last": <NEW_LINE> <INDENT> n_channels = self.index if self.index is not None else input_shape[3] <NEW_LINE> <DEDENT> return (input_shape[0], n_channels, 3) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> if self.data_format == "channels_first": <NEW_LINE> <INDENT> inputs = inputs[:, : self.index] <NEW_LINE> <DEDENT> elif self.data_format == "channels_last": <NEW_LINE> <INDENT> inputs = inputs[..., : self.index] <NEW_LINE> <DEDENT> outputs = find_subpixel_maxima( inputs, self.kernel_size, self.sigma, self.upsample_factor, self.coordinate_scale, self.confidence_scale, self.data_format, ) <NEW_LINE> return outputs <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = { "data_format": self.data_format, "kernel_size": self.kernel_size, "sigma": self.sigma, "upsample_factor": self.upsample_factor, "index": self.index, "coordinate_scale": self.coordinate_scale, "confidence_scale": self.confidence_scale, } <NEW_LINE> base_config = super(SubpixelMaxima2D, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items()))
Subpixel maxima layer for 2D inputs. Convolves a 2D Gaussian kernel to find the subpixel maxima and 2D indices for the channels in the input. The output is ordered as [row, col, maximum]. # Arguments index: Integer, The index to slice the channels to. Default is None, which does not slice the channels. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". # Input shape 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch, channels, rows, cols)` # Output shape 3D tensor with shape: - If `data_format` is `"channels_last"`: `(batch, 3, index)` - If `data_format` is `"channels_first"`: `(batch, index, 3)`
6259907a5166f23b2e244dc7
class Potato(Crop): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(1,3,6) <NEW_LINE> self._type = "Potato" <NEW_LINE> <DEDENT> def grow(self,light,water): <NEW_LINE> <INDENT> if light >= self._light_need and water >= self._water_need: <NEW_LINE> <INDENT> if self._status == "Seedling" and water > self._water_need: <NEW_LINE> <INDENT> self._growth += self._growth_rate * 1.5 <NEW_LINE> <DEDENT> elif self._status == "Young" and water > self._water_need: <NEW_LINE> <INDENT> self._growth += self._growth_rate * 1.25 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._growth += self._growth_rate <NEW_LINE> <DEDENT> <DEDENT> self._days_growing += 1 <NEW_LINE> self._update_status()
A representation of a potato crop
6259907adc8b845886d54faa
class AddStudentOnCourseForm(forms.Form): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.users = kwargs.pop('users') <NEW_LINE> super(AddStudentOnCourseForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['users'].queryset = self.users <NEW_LINE> <DEDENT> users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple )
Форма добавления студента на курс
6259907a26068e7796d4e32e
class Branch(object): <NEW_LINE> <INDENT> id_generator = count(1) <NEW_LINE> def __init__(self, node_from_id, node_to_id, id_cim, name='', status_from=False, status_to=False): <NEW_LINE> <INDENT> self.node_from_id = node_from_id <NEW_LINE> self.node_to_id = node_to_id <NEW_LINE> self.id_cim = id_cim <NEW_LINE> self.name = name <NEW_LINE> self.status_from = status_from <NEW_LINE> self.status_to = status_to <NEW_LINE> self.id = next(self.id_generator)
Represents additional to the :py:class:`Topology_BusBranch.Branch` data about either ``IEC61970::Wires::ACLineSegment`` or ``IEC61970::Wires::PowerTransformer`` object from the source CIM file, which formed that *Branch*.
6259907a5fc7496912d48f62
class variableWrapper(object, baseAttributeWrapper): <NEW_LINE> <INDENT> def __init__(self, component, attribute, maskFunction, index=None): <NEW_LINE> <INDENT> if maskFunctions.count(maskFunction.__class__) == 0: <NEW_LINE> <INDENT> raise exceptions.Exception(str(maskFunction)+ " is not a valid mask function") <NEW_LINE> <DEDENT> self.__component = component <NEW_LINE> self.__attribute = attribute <NEW_LINE> self.__maskFunction = maskFunction <NEW_LINE> <DEDENT> def applyMask(self, mask): <NEW_LINE> <INDENT> self.value = self.__maskFunction(self.value, mask) <NEW_LINE> <DEDENT> def __getValue(self): <NEW_LINE> <INDENT> return getattr(self.__component, self.__attribute) <NEW_LINE> <DEDENT> def __setValue(self, value): <NEW_LINE> <INDENT> setattr(self.__component, self.__attribute, value) <NEW_LINE> <DEDENT> value = property(__getValue, __setValue)
The wrapper for attributes of built-in type
6259907a97e22403b383c8f1
class DeviceResponsePacket(XBeeAPIPacket): <NEW_LINE> <INDENT> __MIN_PACKET_LENGTH = 8 <NEW_LINE> def __init__(self, frame_id, request_id, response_data=None, op_mode=OperatingMode.API_MODE): <NEW_LINE> <INDENT> if frame_id < 0 or frame_id > 255: <NEW_LINE> <INDENT> raise ValueError("Frame id must be between 0 and 255.") <NEW_LINE> <DEDENT> if request_id < 0 or request_id > 255: <NEW_LINE> <INDENT> raise ValueError("Device request ID must be between 0 and 255.") <NEW_LINE> <DEDENT> super().__init__(ApiFrameType.DEVICE_RESPONSE, op_mode=op_mode) <NEW_LINE> self._frame_id = frame_id <NEW_LINE> self.__req_id = request_id <NEW_LINE> self.__resp_data = response_data <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_packet(raw, operating_mode): <NEW_LINE> <INDENT> if operating_mode not in (OperatingMode.ESCAPED_API_MODE, OperatingMode.API_MODE): <NEW_LINE> <INDENT> raise InvalidOperatingModeException(op_mode=operating_mode) <NEW_LINE> <DEDENT> XBeeAPIPacket._check_api_packet(raw, min_length=DeviceResponsePacket.__MIN_PACKET_LENGTH) <NEW_LINE> if raw[3] != ApiFrameType.DEVICE_RESPONSE.code: <NEW_LINE> <INDENT> raise InvalidPacketException(message="This packet is not a device response packet.") <NEW_LINE> <DEDENT> return DeviceResponsePacket( raw[4], raw[5], response_data=raw[7:-1] if len(raw) > DeviceResponsePacket.__MIN_PACKET_LENGTH else None, op_mode=operating_mode) <NEW_LINE> <DEDENT> def needs_id(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def _get_api_packet_spec_data(self): <NEW_LINE> <INDENT> ret = utils.int_to_bytes(self.__req_id, num_bytes=1) <NEW_LINE> ret += utils.int_to_bytes(0x00, num_bytes=1) <NEW_LINE> if self.__resp_data is not None: <NEW_LINE> <INDENT> ret += self.__resp_data <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def _get_api_packet_spec_data_dict(self): <NEW_LINE> <INDENT> return {DictKeys.REQUEST_ID: self.__req_id, DictKeys.RESERVED: 0x00, DictKeys.RF_DATA: list(self.__resp_data) if self.__resp_data is not None else None} <NEW_LINE> <DEDENT> @property <NEW_LINE> def request_id(self): <NEW_LINE> <INDENT> return self.__req_id <NEW_LINE> <DEDENT> @request_id.setter <NEW_LINE> def request_id(self, request_id): <NEW_LINE> <INDENT> if request_id < 0 or request_id > 255: <NEW_LINE> <INDENT> raise ValueError("Device request ID must be between 0 and 255.") <NEW_LINE> <DEDENT> self.__req_id = request_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def request_data(self): <NEW_LINE> <INDENT> if self.__resp_data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__resp_data.copy() <NEW_LINE> <DEDENT> @request_data.setter <NEW_LINE> def request_data(self, response_data): <NEW_LINE> <INDENT> if response_data is None: <NEW_LINE> <INDENT> self.__resp_data = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__resp_data = response_data.copy()
This class represents a device response packet. Packet is built using the parameters of the constructor or providing a valid API payload. This frame type is sent to the serial port by the host in response to the :class:`.DeviceRequestPacket`. It should be sent within five seconds to avoid a timeout error. .. seealso:: | :class:`.DeviceRequestPacket` | :class:`.XBeeAPIPacket`
6259907a91f36d47f2231b87
class pluginloader(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def findModule(self, plugin_name=None): <NEW_LINE> <INDENT> module_dir = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> module_path = os.path.abspath( "%s/../plugins/%s/%s_plugin.py" % (module_dir, plugin_name, plugin_name)) <NEW_LINE> if os.path.exists(module_path): <NEW_LINE> <INDENT> return imp.load_source( "%s_plugin" % (plugin_name), module_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def load(self, plugin_name=None, plugin_config=None): <NEW_LINE> <INDENT> if plugin_name: <NEW_LINE> <INDENT> plugin = self.findModule(plugin_name) <NEW_LINE> if plugin: <NEW_LINE> <INDENT> return plugin.plugin_impl(plugin_config) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise PluginNotExist( "unable to find a plugin for %s" % plugin_name) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise PluginLoaderError("a plugin name is not given")
Find a plugin and create an instance
6259907aaad79263cf4301aa
class TerminalPdb(Pdb): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> Pdb.__init__(self, *args, **kwargs) <NEW_LINE> self._ptcomp = None <NEW_LINE> self.pt_init() <NEW_LINE> <DEDENT> def pt_init(self): <NEW_LINE> <INDENT> def get_prompt_tokens(): <NEW_LINE> <INDENT> return [(Token.Prompt, self.prompt)] <NEW_LINE> <DEDENT> if self._ptcomp is None: <NEW_LINE> <INDENT> compl = IPCompleter(shell=self.shell, namespace={}, global_namespace={}, parent=self.shell, ) <NEW_LINE> self._ptcomp = IPythonPTCompleter(compl) <NEW_LINE> <DEDENT> options = dict( message=(lambda: PygmentsTokens(get_prompt_tokens())), editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), key_bindings=create_ipython_shortcuts(self.shell), history=self.shell.debugger_history, completer=self._ptcomp, enable_history_search=True, mouse_support=self.shell.mouse_support, complete_style=self.shell.pt_complete_style, style=self.shell.style, color_depth=self.shell.color_depth, ) <NEW_LINE> if not PTK3: <NEW_LINE> <INDENT> options['inputhook'] = self.shell.inputhook <NEW_LINE> <DEDENT> self.pt_loop = asyncio.new_event_loop() <NEW_LINE> self.pt_app = PromptSession(**options) <NEW_LINE> <DEDENT> def cmdloop(self, intro=None): <NEW_LINE> <INDENT> if not self.use_rawinput: <NEW_LINE> <INDENT> raise ValueError('Sorry ipdb does not support use_rawinput=False') <NEW_LINE> <DEDENT> self.preloop() <NEW_LINE> try: <NEW_LINE> <INDENT> if intro is not None: <NEW_LINE> <INDENT> self.intro = intro <NEW_LINE> <DEDENT> if self.intro: <NEW_LINE> <INDENT> self.stdout.write(str(self.intro)+"\n") <NEW_LINE> <DEDENT> stop = None <NEW_LINE> while not stop: <NEW_LINE> <INDENT> if self.cmdqueue: <NEW_LINE> <INDENT> line = self.cmdqueue.pop(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ptcomp.ipy_completer.namespace = self.curframe_locals <NEW_LINE> self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals <NEW_LINE> line = '' <NEW_LINE> keyboard_interrupt = False <NEW_LINE> def in_thread(): <NEW_LINE> <INDENT> nonlocal line, keyboard_interrupt <NEW_LINE> try: <NEW_LINE> <INDENT> line = self.pt_app.prompt() <NEW_LINE> <DEDENT> except EOFError: <NEW_LINE> <INDENT> line = 'EOF' <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> keyboard_interrupt = True <NEW_LINE> <DEDENT> <DEDENT> th = threading.Thread(target=in_thread) <NEW_LINE> th.start() <NEW_LINE> th.join() <NEW_LINE> if keyboard_interrupt: <NEW_LINE> <INDENT> raise KeyboardInterrupt <NEW_LINE> <DEDENT> <DEDENT> line = self.precmd(line) <NEW_LINE> stop = self.onecmd(line) <NEW_LINE> stop = self.postcmd(stop, line) <NEW_LINE> <DEDENT> self.postloop() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise
Standalone IPython debugger.
6259907a7d43ff248742810d
class CaConc(PyMooseBase): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _moose.new_CaConc(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _moose.delete_CaConc <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def getType(self): <NEW_LINE> <INDENT> return _moose.CaConc_getType(self) <NEW_LINE> <DEDENT> def __get_Ca(self): <NEW_LINE> <INDENT> return _moose.CaConc___get_Ca(self) <NEW_LINE> <DEDENT> def __set_Ca(self, *args): <NEW_LINE> <INDENT> return _moose.CaConc___set_Ca(self, *args) <NEW_LINE> <DEDENT> def __get_CaBasal(self): <NEW_LINE> <INDENT> return _moose.CaConc___get_CaBasal(self) <NEW_LINE> <DEDENT> def __set_CaBasal(self, *args): <NEW_LINE> <INDENT> return _moose.CaConc___set_CaBasal(self, *args) <NEW_LINE> <DEDENT> def __get_Ca_base(self): <NEW_LINE> <INDENT> return _moose.CaConc___get_Ca_base(self) <NEW_LINE> <DEDENT> def __set_Ca_base(self, *args): <NEW_LINE> <INDENT> return _moose.CaConc___set_Ca_base(self, *args) <NEW_LINE> <DEDENT> def __get_tau(self): <NEW_LINE> <INDENT> return _moose.CaConc___get_tau(self) <NEW_LINE> <DEDENT> def __set_tau(self, *args): <NEW_LINE> <INDENT> return _moose.CaConc___set_tau(self, *args) <NEW_LINE> <DEDENT> def __get_B(self): <NEW_LINE> <INDENT> return _moose.CaConc___get_B(self) <NEW_LINE> <DEDENT> def __set_B(self, *args): <NEW_LINE> <INDENT> return _moose.CaConc___set_B(self, *args) <NEW_LINE> <DEDENT> Ca = _swig_property(_moose.CaConc_Ca_get, _moose.CaConc_Ca_set) <NEW_LINE> CaBasal = _swig_property(_moose.CaConc_CaBasal_get, _moose.CaConc_CaBasal_set) <NEW_LINE> Ca_base = _swig_property(_moose.CaConc_Ca_base_get, _moose.CaConc_Ca_base_set) <NEW_LINE> tau = _swig_property(_moose.CaConc_tau_get, _moose.CaConc_tau_set) <NEW_LINE> B = _swig_property(_moose.CaConc_B_get, _moose.CaConc_B_set)
Proxy of C++ pymoose::CaConc class
6259907a7cff6e4e811b7430
class FakeStrategyModule(object): <NEW_LINE> <INDENT> def a1(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def a2(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def b(self): <NEW_LINE> <INDENT> pass
A class that mockups a module of strategies
6259907a7d847024c075ddcd
class DoAspect(MiniToolAction): <NEW_LINE> <INDENT> def selected(self, attrs): <NEW_LINE> <INDENT> if config.display_mode & config.PAL_MONITOR_ID == config.PAL_MONITOR_ID: <NEW_LINE> <INDENT> self.gadget.state = 2 <NEW_LINE> self.gadget.need_redraw = True <NEW_LINE> <DEDENT> config.set_aspect(self.gadget.state) <NEW_LINE> config.resize_display() <NEW_LINE> <DEDENT> def deselected(self, attrs): <NEW_LINE> <INDENT> config.set_aspect(self.gadget.state) <NEW_LINE> config.resize_display()
Change NTSC/PAL aspect ratio
6259907a44b2445a339b7656
class MIX(Effect): <NEW_LINE> <INDENT> instrument = "MIX" <NEW_LINE> pfields = 'amp', <NEW_LINE> load = () <NEW_LINE> def __init__(self, outsk=None, insk=None, dur=None, amp=None, *extra_args, **extra_kwargs): <NEW_LINE> <INDENT> self._passback(locals())
MIX(outsk, insk, dur, AMP, p4-n: output channel assigns)
6259907a66673b3332c31df0
class Visit(DatetimeModel): <NEW_LINE> <INDENT> visitor = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, related_name='visits_maker', verbose_name=_("Visitor")) <NEW_LINE> user = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, related_name='visits_receiver', verbose_name=_("User")) <NEW_LINE> objects = VisitManager() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{visitor} -> {target}".format(visitor=self.visitor, target=self.user) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("profile visit") <NEW_LINE> verbose_name_plural = _("profile visits") <NEW_LINE> unique_together = (('visitor', 'user'),) <NEW_LINE> permissions = (("ghost_visit", "Can visit stealth"),) <NEW_LINE> app_label = 'user'
Visite de profil
6259907a4a966d76dd5f08d7
class CustomFrame(QtGui.QFrame): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QtGui.QFrame.__init__(self, parent) <NEW_LINE> self.parent = parent <NEW_LINE> self.info = parent.info <NEW_LINE> self.log = parent.log <NEW_LINE> self.setLayout(QtGui.QVBoxLayout()) <NEW_LINE> if hasattr(self, 'initLogic'): <NEW_LINE> <INDENT> self.initLogic() <NEW_LINE> <DEDENT> self.initUI() <NEW_LINE> <DEDENT> def initUI(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def initToolBar(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def clearUI(self): <NEW_LINE> <INDENT> while self.layout().count(): <NEW_LINE> <INDENT> item = self.layout().takeAt(0) <NEW_LINE> if isinstance(item, QtGui.QLayout): <NEW_LINE> <INDENT> self.clearLayout(item) <NEW_LINE> item.deleteLater() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> widget = item.widget() <NEW_LINE> if widget is not None: <NEW_LINE> <INDENT> widget.deleteLater() <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def clearLayout(self, layout): <NEW_LINE> <INDENT> if layout is not None: <NEW_LINE> <INDENT> while layout.count(): <NEW_LINE> <INDENT> item = layout.takeAt(0) <NEW_LINE> widget = item.widget() <NEW_LINE> if widget is not None: <NEW_LINE> <INDENT> widget.deleteLater() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.clearLayout(item.layout()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def zoomIn(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def zoomOut(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def resetSize(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for all three tabbed frames
6259907a5166f23b2e244dc9
class LoaderBase(IOBase): <NEW_LINE> <INDENT> def __init__(self, cachedir, **kwargs): <NEW_LINE> <INDENT> super(LoaderBase, self).__init__(cachedir, **kwargs) <NEW_LINE> if not os.path.exists(self.cachedir): <NEW_LINE> <INDENT> raise IOError('No cache exists with path {0!r}'.format(self.cachedir)) <NEW_LINE> <DEDENT> self.datas = {} <NEW_LINE> <DEDENT> def configure(self, **kwargs): <NEW_LINE> <INDENT> self.params.update(kwargs) <NEW_LINE> <DEDENT> def save(self, name, data, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def delete(self, fname): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if key in self.datas: <NEW_LINE> <INDENT> return self.datas[key] <NEW_LINE> <DEDENT> data = self.load(key) <NEW_LINE> self.datas[key] = data <NEW_LINE> return data
Base class for data loaders. .. note:: This is a base class and should not be used directly.
6259907aad47b63b2c5a9241
class ObjectBuilderRebalance(Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__) <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(ObjectBuilderRebalance, self).get_parser(prog_name) <NEW_LINE> parser.add_argument('--user', help='the username to connect to the remote host', action='store', default='ubuntu', dest='user') <NEW_LINE> parser.add_argument('--hosts', help='the remote host to connect to ', action='store', default=None, dest='hosts') <NEW_LINE> parser.add_argument('-i', '--key-filename', help='referencing file paths to SSH key files to try when connecting', action='store', dest='key_filename', default=None) <NEW_LINE> parser.add_argument('--password', help='the password used by the SSH layer when connecting to remote hosts', action='store', dest='password', default=None) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> object_builder_rebalance(parsed_args)
rebalance the object ring
6259907a5fc7496912d48f63
class DatasourceNotSupportedError(WMSBaseError): <NEW_LINE> <INDENT> pass
Exception for invalid type od datasource
6259907ad268445f2663a857
class Photo: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def send(bot, user_id, content): <NEW_LINE> <INDENT> send_content(bot.send_photo, user_id, content) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_content(message): <NEW_LINE> <INDENT> best_photo = message.photo[0] <NEW_LINE> for i in range(1, len(message.photo)): <NEW_LINE> <INDENT> this_photo = message.photo[i] <NEW_LINE> if this_photo.width * this_photo.height > best_photo.width * best_photo.height: <NEW_LINE> <INDENT> best_photo = this_photo <NEW_LINE> <DEDENT> <DEDENT> return build_content(photo=best_photo.file_id, caption=message.caption)
Wrapper class for handling photos
6259907a97e22403b383c8f3
class BDIIOccupancy(object): <NEW_LINE> <INDENT> def __init__(self, se): <NEW_LINE> <INDENT> self.log = se.log.getSubLogger('BDIIOccupancy') <NEW_LINE> self.bdii = 'lcg-bdii.cern.ch:2170' <NEW_LINE> if 'LCG_GFAL_INFOSYS' in os.environ: <NEW_LINE> <INDENT> self.bdii = os.environ['LCG_GFAL_INFOSYS'] <NEW_LINE> <DEDENT> self.vo = se.vo <NEW_LINE> ret = se.getStorageParameters(protocol='srm') <NEW_LINE> if not ret['OK']: <NEW_LINE> <INDENT> raise RuntimeError(ret['Message']) <NEW_LINE> <DEDENT> if 'Host' not in ret['Value']: <NEW_LINE> <INDENT> raise RuntimeError('No Host is found from StorageParameters') <NEW_LINE> <DEDENT> self.host = ret['Value']['Host'] <NEW_LINE> <DEDENT> def getOccupancy(self, **kwargs): <NEW_LINE> <INDENT> sTokenDict = {'Total': 0, 'Free': 0} <NEW_LINE> BDIIAttr = ['GlueSATotalOnlineSize', 'GlueSAFreeOnlineSize'] <NEW_LINE> filt = "(&(GlueSAAccessControlBaseRule=VO:%s)(GlueChunkKey=GlueSEUniqueID=%s))" % (self.vo, self.host) <NEW_LINE> ret = ldapsearchBDII(filt, BDIIAttr, host=self.bdii) <NEW_LINE> if not ret['OK']: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> for value in ret['Value']: <NEW_LINE> <INDENT> if 'attr' in value: <NEW_LINE> <INDENT> attr = value['attr'] <NEW_LINE> sTokenDict['Total'] = float(attr.get(BDIIAttr[0], 0)) * 1024 * 1024 * 1024 <NEW_LINE> sTokenDict['Free'] = float(attr.get(BDIIAttr[1], 0)) * 1024 * 1024 * 1024 <NEW_LINE> <DEDENT> <DEDENT> return S_OK(sTokenDict)
.. class:: BDIIOccupancy Occupancy plugin to return the space information given by BDII Assuming the protocol is SRM
6259907aa8370b77170f1dc0
class MLNode(DTNode): <NEW_LINE> <INDENT> def __init__(self,edges,ichildren,maxind,leafstart,words): <NEW_LINE> <INDENT> self.edges = edges <NEW_LINE> self.ichildren = ichildren <NEW_LINE> self.maxind = maxind <NEW_LINE> self.leafstart = leafstart <NEW_LINE> self.words = words
Represent a MustLink-node
6259907af548e778e596cf83
class BaseLinePredictor(PredictorBase): <NEW_LINE> <INDENT> def fit(self, X_train, y_train): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def predict(self, X_test): <NEW_LINE> <INDENT> test_n = len(X_test) <NEW_LINE> zeroes = [0] * test_n <NEW_LINE> predictions_data = { 'ID': test_n, 'Adoption': [1] * test_n, 'Died': zeroes, 'Euthanasia': zeroes, 'Return_to_owner': zeroes, 'Transfer': zeroes} <NEW_LINE> predictions_df = pd.DataFrame(predictions_data) <NEW_LINE> return predictions_df
All adopted benchmark
6259907a21bff66bcd72465b
class TagContainer(UserDict): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._add_taglike(DescriptionTag) <NEW_LINE> self.problems = [] <NEW_LINE> <DEDENT> def __call__(self, tag_name: str): <NEW_LINE> <INDENT> tag = self.data.get(tag_name) <NEW_LINE> if tag is None: <NEW_LINE> <INDENT> tag = UnknownTag(tag_name) <NEW_LINE> self.append(tag) <NEW_LINE> <DEDENT> return tag <NEW_LINE> <DEDENT> def append(self, tag): <NEW_LINE> <INDENT> if tag.name in self.data: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.data[tag.name] = tag <NEW_LINE> <DEDENT> def update(self, values: dict): <NEW_LINE> <INDENT> for key, data in values.items(): <NEW_LINE> <INDENT> self(key).update(data) <NEW_LINE> <DEDENT> <DEDENT> def all(self): <NEW_LINE> <INDENT> return iter(self.data.values()) <NEW_LINE> <DEDENT> def names(self): <NEW_LINE> <INDENT> return self.data.keys() <NEW_LINE> <DEDENT> def present(self): <NEW_LINE> <INDENT> new_container = copy(self) <NEW_LINE> new_container.data = {k: v for k, v in self.data.items() if v.present} <NEW_LINE> return new_container <NEW_LINE> <DEDENT> def _add_taglike(self, klass, *args, **kwargs): <NEW_LINE> <INDENT> self.append(klass(*args, **kwargs)) <NEW_LINE> <DEDENT> def add_tag(self, *args, **kwargs): <NEW_LINE> <INDENT> self._add_taglike(Tag, *args, **kwargs) <NEW_LINE> <DEDENT> def add_flag(self, *args, **kwargs): <NEW_LINE> <INDENT> self._add_taglike(Flag, *args, **kwargs) <NEW_LINE> <DEDENT> def add_group(self, *args, **kwargs): <NEW_LINE> <INDENT> self._add_taglike(GroupTag, *args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def valid(self): <NEW_LINE> <INDENT> return len(self.problems) == 0 <NEW_LINE> <DEDENT> def validate(self, strict: bool=False): <NEW_LINE> <INDENT> self.problems = [] <NEW_LINE> for key, tag in self.data.items(): <NEW_LINE> <INDENT> tag.validate(strict=strict) <NEW_LINE> self.problems.extend(tag.problems) <NEW_LINE> if key != tag.name: <NEW_LINE> <INDENT> self.problems.append("Tag '{}' has wrong key: '{}'".format(tag.name, key)) <NEW_LINE> <DEDENT> <DEDENT> return self.valid <NEW_LINE> <DEDENT> def sanitize(self): <NEW_LINE> <INDENT> for tag in self.values(): <NEW_LINE> <INDENT> tag.sanitize()
Manages a coherent group of tags Instances are callable. That syntax is the preferred way to get a tag, since it will always return a tag object. Accessing an undeclared tag in this way will return an UnknownTag object instead of raising an error. This object can also be accessed like a normal dict.
6259907a3346ee7daa33835a
class MethodBooleanExtendsExclusionTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> class ExclusionMapper(SimpleTestMapper): <NEW_LINE> <INDENT> age = omm.MapField( "test.age", exclude={ "json": True, "dict": False, "custom": True }, exclude_serialize=True, exclude_deserialize=False ) <NEW_LINE> <DEDENT> self.cls = ExclusionMapper <NEW_LINE> self.data = self.cls(self.cls.generate_test_data(True)) <NEW_LINE> self.dct = { "name": self.data.name, "age": self.data.age, "sex": self.data.sex } <NEW_LINE> <DEDENT> def test_serialization_json(self): <NEW_LINE> <INDENT> result = self.data.to_json() <NEW_LINE> self.assertNotIn("age", result) <NEW_LINE> <DEDENT> def test_deserialization_json(self): <NEW_LINE> <INDENT> result = self.cls.from_json(json.dumps(self.dct)) <NEW_LINE> self.assertEqual(result.age, self.dct["age"]) <NEW_LINE> <DEDENT> def test_serialization_dict(self): <NEW_LINE> <INDENT> result = self.data.to_dict() <NEW_LINE> self.assertNotIn("age", result) <NEW_LINE> <DEDENT> def test_deserialization_dict(self): <NEW_LINE> <INDENT> result = self.cls.from_dict(self.dct) <NEW_LINE> self.assertEqual(result.age, self.dct["age"]) <NEW_LINE> <DEDENT> def test_serialization_custom(self): <NEW_LINE> <INDENT> result = self.data.dumps(dict) <NEW_LINE> self.assertNotIn("age", result) <NEW_LINE> <DEDENT> def test_deserialization_custom(self): <NEW_LINE> <INDENT> result = self.cls.loads(dict, self.dct) <NEW_LINE> self.assertEqual(result.age, self.dct["age"])
exclude=dict and exclude_(method)=boolean test.
6259907a7d43ff248742810e
class TestICEInstaller(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_options(self): <NEW_LINE> <INDENT> print("") <NEW_LINE> print("----------------------------------------------------------------------") <NEW_LINE> print("Testing argument parsing...") <NEW_LINE> opts = Install_ICE.parse_args(['-u']) <NEW_LINE> self.assertEqual(opts.update, ['ICE', 'VisIt', 'HDFJava']) <NEW_LINE> opts = Install_ICE.parse_args(['-u', 'VisIt']) <NEW_LINE> self.assertEqual(opts.update, ['VisIt']) <NEW_LINE> opts = Install_ICE.parse_args(['-u', 'HDFJava', 'ICE']) <NEW_LINE> self.assertEqual(opts.update, ['HDFJava', 'ICE']) <NEW_LINE> self.assertEqual(opts.prefix, '.') <NEW_LINE> opts = Install_ICE.parse_args(['-p', '/home/user/ICE', '-u']) <NEW_LINE> self.assertEqual(opts.update, ['ICE', 'VisIt', 'HDFJava']) <NEW_LINE> self.assertEqual(opts.prefix, '/home/user/ICE') <NEW_LINE> <DEDENT> def test_download(self): <NEW_LINE> <INDENT> print("") <NEW_LINE> print("----------------------------------------------------------------------") <NEW_LINE> print(" Testing package downloads...") <NEW_LINE> opts = Install_ICE.parse_args(['-u', 'HDFJava']) <NEW_LINE> arch_type = platform.machine() <NEW_LINE> os_type = platform.system() <NEW_LINE> Install_ICE.download_packages(opts, os_type, arch_type) <NEW_LINE> n = len(glob.glob("HDFView*")) <NEW_LINE> [os.remove(f) for f in glob.glob("HDFView*")] <NEW_LINE> self.assertEqual(n, 1) <NEW_LINE> <DEDENT> def test_unpack(self): <NEW_LINE> <INDENT> print("") <NEW_LINE> print("----------------------------------------------------------------------") <NEW_LINE> print(" Testing package downloads...") <NEW_LINE> opts = Install_ICE.parse_args(['-u', 'HDFJava']) <NEW_LINE> arch_type = platform.machine() <NEW_LINE> os_type = platform.system() <NEW_LINE> pkgs = Install_ICE.download_packages(opts, os_type, arch_type) <NEW_LINE> Install_ICE.unpack_packages(opts, pkgs) <NEW_LINE> n = len(glob.glob("HDFView*")) <NEW_LINE> print("Number of files found = " + str(n)) <NEW_LINE> self.assertNotEqual(0, n) <NEW_LINE> <DEDENT> def test_install(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_cleanup(self): <NEW_LINE> <INDENT> pass
Tests for the ICE Installer are stored here. Each test should be a separate function within this class.
6259907aa8370b77170f1dc1
class _DictLikeModel(ndb.Expando, DictMixin): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _validateKey(cls, key): <NEW_LINE> <INDENT> if not isinstance(key, basestring): <NEW_LINE> <INDENT> raise ValueError("DictionaryProperty keys must be strings, got: %r" % key) <NEW_LINE> <DEDENT> if key.startswith('_'): <NEW_LINE> <INDENT> raise ValueError("DictionaryProperty keys must not start with '_', got: %s" % key) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> self._validateKey(key) <NEW_LINE> try: <NEW_LINE> <INDENT> return getattr(self, key) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise KeyError("%s not found on DictionaryProperty value" % key) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self._validateKey(key) <NEW_LINE> setattr(self, key, value) <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__getitem__(key) <NEW_LINE> delattr(self, key) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise KeyError("%s not found on DictionaryProperty value" % key) <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in self._properties <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self._properties.iterkeys() <NEW_LINE> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> for key in self._properties.iterkeys(): <NEW_LINE> <INDENT> yield (key, getattr(self, key)) <NEW_LINE> <DEDENT> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self._properties.keys()
Internal model used to implement DictionaryProperty. This is what you actually manipulate when dealing with a DictionaryProperty value.
6259907a3317a56b869bf23f
class ofp_flow_stats_request: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.match = ofp_match() <NEW_LINE> self.table_id = 0 <NEW_LINE> self.pad = 0 <NEW_LINE> self.out_port = 0 <NEW_LINE> <DEDENT> def __assert(self): <NEW_LINE> <INDENT> if(not isinstance(self.match, ofp_match)): <NEW_LINE> <INDENT> return (False, "self.match is not class ofp_match as expected.") <NEW_LINE> <DEDENT> return (True, None) <NEW_LINE> <DEDENT> def pack(self, assertstruct=True): <NEW_LINE> <INDENT> if(assertstruct): <NEW_LINE> <INDENT> if(not self.__assert()[0]): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> packed = "" <NEW_LINE> packed += self.match.pack() <NEW_LINE> packed += struct.pack("!BBH", self.table_id, self.pad, self.out_port) <NEW_LINE> return packed <NEW_LINE> <DEDENT> def unpack(self, binaryString): <NEW_LINE> <INDENT> if (len(binaryString) < 44): <NEW_LINE> <INDENT> return binaryString <NEW_LINE> <DEDENT> self.match.unpack(binaryString[0:]) <NEW_LINE> fmt = '!BBH' <NEW_LINE> start = 40 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.table_id, self.pad, self.out_port) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> return binaryString[44:] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> l = 44 <NEW_LINE> return l <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(self) != type(other): return False <NEW_LINE> if self.match != other.match: return False <NEW_LINE> if self.table_id != other.table_id: return False <NEW_LINE> if self.pad != other.pad: return False <NEW_LINE> if self.out_port != other.out_port: return False <NEW_LINE> return True <NEW_LINE> <DEDENT> def __ne__(self, other): return not self.__eq__(other) <NEW_LINE> def show(self, prefix=''): <NEW_LINE> <INDENT> outstr = '' <NEW_LINE> outstr += prefix + 'match: \n' <NEW_LINE> outstr += self.match.show(prefix + ' ') <NEW_LINE> outstr += prefix + 'table_id: ' + str(self.table_id) + '\n' <NEW_LINE> outstr += prefix + 'out_port: ' + str(self.out_port) + '\n' <NEW_LINE> return outstr
Automatically generated Python class for ofp_flow_stats_request Date 2011-06-13 Created by pylibopenflow.of.pythonize.pythonizer
6259907a97e22403b383c8f4
class GBPServerRpcCallback(object): <NEW_LINE> <INDENT> RPC_API_VERSION = "1.0" <NEW_LINE> target = oslo_messaging.Target(version=RPC_API_VERSION) <NEW_LINE> def __init__(self, gbp_driver): <NEW_LINE> <INDENT> self.gbp_driver = gbp_driver <NEW_LINE> <DEDENT> def get_gbp_details(self, context, **kwargs): <NEW_LINE> <INDENT> return self.gbp_driver.get_gbp_details(context, **kwargs) <NEW_LINE> <DEDENT> def get_gbp_details_list(self, context, **kwargs): <NEW_LINE> <INDENT> return [ self.get_gbp_details( context, device=device, **kwargs ) for device in kwargs.pop('devices', []) ]
Plugin-side RPC (implementation) for agent-to-plugin interaction.
6259907a4f88993c371f121b
class LineBoxBuilder(BaseBuilder): <NEW_LINE> <INDENT> def __init__(self, tesseract_layout=1): <NEW_LINE> <INDENT> file_ext = ["html", "hocr"] <NEW_LINE> tess_flags = ["-psm", str(tesseract_layout)] <NEW_LINE> tess_conf = ["hocr"] <NEW_LINE> cun_args = ["-f", "hocr"] <NEW_LINE> super(LineBoxBuilder, self).__init__(file_ext, tess_flags, tess_conf, cun_args) <NEW_LINE> self.lines = [] <NEW_LINE> self.tesseract_layout = tesseract_layout <NEW_LINE> <DEDENT> def read_file(self, file_descriptor): <NEW_LINE> <INDENT> parsers = [ (_WordHTMLParser(), lambda parser: parser.lines), (_LineHTMLParser(), lambda parser: [LineBox([box], box.position) for box in parser.boxes]), ] <NEW_LINE> html_str = file_descriptor.read() <NEW_LINE> for (parser, convertion) in parsers: <NEW_LINE> <INDENT> parser.feed(html_str) <NEW_LINE> if len(parser.boxes) > 0: <NEW_LINE> <INDENT> last_box = parser.boxes[-1] <NEW_LINE> if last_box.content == to_unicode(""): <NEW_LINE> <INDENT> parser.boxes.pop(-1) <NEW_LINE> <DEDENT> return convertion(parser) <NEW_LINE> <DEDENT> <DEDENT> return [] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def write_file(file_descriptor, boxes): <NEW_LINE> <INDENT> global _XHTML_HEADER <NEW_LINE> impl = xml.dom.minidom.getDOMImplementation() <NEW_LINE> newdoc = impl.createDocument(None, "root", None) <NEW_LINE> file_descriptor.write(_XHTML_HEADER) <NEW_LINE> file_descriptor.write(to_unicode("<body>\n")) <NEW_LINE> for box in boxes: <NEW_LINE> <INDENT> xml_str = box.get_xml_tag(newdoc).toxml() <NEW_LINE> xml_str = to_unicode(xml_str) <NEW_LINE> file_descriptor.write( to_unicode("<p>") + xml_str + to_unicode("</p>\n") ) <NEW_LINE> <DEDENT> file_descriptor.write(to_unicode("</body>\n</html>\n")) <NEW_LINE> <DEDENT> def start_line(self, box): <NEW_LINE> <INDENT> if len(self.lines) > 0 and self.lines[-1].content == to_unicode(""): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.lines.append(LineBox([], box)) <NEW_LINE> <DEDENT> def add_word(self, word, box): <NEW_LINE> <INDENT> self.lines[-1].word_boxes.append(Box(word, box)) <NEW_LINE> <DEDENT> def end_line(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_output(self): <NEW_LINE> <INDENT> return self.lines <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __str__(): <NEW_LINE> <INDENT> return "Line boxes"
If passed to image_to_string(), image_to_string() will return an array of LineBox. Each LineBox contains a list of word boxes.
6259907a44b2445a339b7657
class TestXmlNs0ScriptAttributeImpl(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 testXmlNs0ScriptAttributeImpl(self): <NEW_LINE> <INDENT> pass
XmlNs0ScriptAttributeImpl unit test stubs
6259907a460517430c432d53
class net_g(nn.Module): <NEW_LINE> <INDENT> def __init__(self, upscale_factor=4): <NEW_LINE> <INDENT> super(net_g, self).__init__() <NEW_LINE> self.relu = nn.ReLU() <NEW_LINE> self.conv1 = nn.Conv2d(3, 64, (5, 5), (1, 1), (2, 2)) <NEW_LINE> self.conv2 = nn.Conv2d(64, 64, (3, 3), (1, 1), (1, 1)) <NEW_LINE> self.conv3 = nn.Conv2d(64, 32, (3, 3), (1, 1), (1, 1)) <NEW_LINE> self.conv4 = nn.Conv2d(32, 3*upscale_factor ** 2, (3, 3), (1, 1), (1, 1)) <NEW_LINE> self.pixel_shuffle = nn.PixelShuffle(upscale_factor) <NEW_LINE> self._initialize_weights() <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.relu(self.conv1(x)) <NEW_LINE> x = self.relu(self.conv2(x)) <NEW_LINE> x = self.relu(self.conv3(x)) <NEW_LINE> x = self.pixel_shuffle(self.conv4(x)) <NEW_LINE> return x <NEW_LINE> <DEDENT> def _initialize_weights(self): <NEW_LINE> <INDENT> nn.init.orthogonal(self.conv1.weight, nn.init.calculate_gain('relu')) <NEW_LINE> nn.init.orthogonal(self.conv2.weight, nn.init.calculate_gain('relu')) <NEW_LINE> nn.init.orthogonal(self.conv3.weight, nn.init.calculate_gain('relu')) <NEW_LINE> nn.init.orthogonal(self.conv4.weight)
Generator
6259907a4a966d76dd5f08d9
class PermaTemplateView(object): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.fake_request = RequestFactory(HTTP_HOST=settings.WARC_HOST).get('/fake') <NEW_LINE> <DEDENT> def render_response(self, status='200 OK', content_type='text/html; charset=utf-8', **template_kwargs): <NEW_LINE> <INDENT> template_context = dict( template_kwargs, status=status, content_type=content_type) <NEW_LINE> template_result = loader.render_to_string(self.filename, template_context, request=self.fake_request) <NEW_LINE> return WbResponse.text_response(unicode(template_result), status=status, content_type=content_type)
Class to render Django templates for Pywb views. Uses a fake request from the Django testing library to get Django to render a template without a real Django request object available.
6259907aec188e330fdfa29b
class NullToken(Token): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> def run(self, interpreter, locals): <NEW_LINE> <INDENT> interpreter.write(self.data) <NEW_LINE> <DEDENT> def string(self): <NEW_LINE> <INDENT> return self.data
A chunk of data not containing markups.
6259907a26068e7796d4e332
class GrantExchanger(Mediator): <NEW_LINE> <INDENT> install = Param("sentry.models.SentryAppInstallation") <NEW_LINE> code = Param((str,)) <NEW_LINE> client_id = Param((str,)) <NEW_LINE> user = Param("sentry.models.User") <NEW_LINE> def call(self): <NEW_LINE> <INDENT> self._validate() <NEW_LINE> self._create_token() <NEW_LINE> self._delete_grant() <NEW_LINE> return self.token <NEW_LINE> <DEDENT> def record_analytics(self): <NEW_LINE> <INDENT> analytics.record( "sentry_app.token_exchanged", sentry_app_installation_id=self.install.id, exchange_type="authorization", ) <NEW_LINE> <DEDENT> def _validate(self): <NEW_LINE> <INDENT> Validator.run(install=self.install, client_id=self.client_id, user=self.user) <NEW_LINE> if not self._grant_belongs_to_install() or not self._sentry_app_user_owns_grant(): <NEW_LINE> <INDENT> raise APIUnauthorized <NEW_LINE> <DEDENT> if not self._grant_is_active(): <NEW_LINE> <INDENT> raise APIUnauthorized("Grant has already expired.") <NEW_LINE> <DEDENT> <DEDENT> def _grant_belongs_to_install(self): <NEW_LINE> <INDENT> return self.grant.sentry_app_installation == self.install <NEW_LINE> <DEDENT> def _sentry_app_user_owns_grant(self): <NEW_LINE> <INDENT> return self.grant.application.owner == self.user <NEW_LINE> <DEDENT> def _grant_is_active(self): <NEW_LINE> <INDENT> return self.grant.expires_at > datetime.now(pytz.UTC) <NEW_LINE> <DEDENT> def _delete_grant(self): <NEW_LINE> <INDENT> self.grant.delete() <NEW_LINE> <DEDENT> def _create_token(self): <NEW_LINE> <INDENT> self.token = ApiToken.objects.create( user=self.user, application=self.application, scope_list=self.sentry_app.scope_list, expires_at=token_expiration(), ) <NEW_LINE> self.install.api_token = self.token <NEW_LINE> self.install.save() <NEW_LINE> <DEDENT> @memoize <NEW_LINE> def grant(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ( ApiGrant.objects.select_related("sentry_app_installation") .select_related("application") .select_related("application__sentry_app") .get(code=self.code) ) <NEW_LINE> <DEDENT> except ApiGrant.DoesNotExist: <NEW_LINE> <INDENT> raise APIUnauthorized <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def application(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.grant.application <NEW_LINE> <DEDENT> except ApiApplication.DoesNotExist: <NEW_LINE> <INDENT> raise APIUnauthorized <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def sentry_app(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.application.sentry_app <NEW_LINE> <DEDENT> except SentryApp.DoesNotExist: <NEW_LINE> <INDENT> raise APIUnauthorized
Exchanges a Grant Code for an Access Token
6259907a796e427e5385016e
class ExecutionError(Exception): <NEW_LINE> <INDENT> pass
Unhandled thread error wrapper. Raised on the calling thread.
6259907a91f36d47f2231b89
class MockStack: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass
Mock insteon_mqtt/network/Stack class
6259907a56b00c62f0fb42c8
class DHGroupExchangeSHA1Mixin: <NEW_LINE> <INDENT> kexAlgorithm = 'diffie-hellman-group-exchange-sha1' <NEW_LINE> hashProcessor = sha1
Mixin for diffie-hellman-group-exchange-sha1 tests.
6259907a167d2b6e312b828d
class MultiItem(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{BF3DD473-A408-4014-B913-69A31AF6115D}') <NEW_LINE> _idlflags_ = ['noncreatable'] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{866AE5D3-530C-11D2-A2BD-0000F8774FB5}', 10, 2)
MultiItem CoType.
6259907ad486a94d0ba2d9ac
class McCabeMethodChecker(BaseChecker): <NEW_LINE> <INDENT> __implements__ = IAstroidChecker <NEW_LINE> name = 'design' <NEW_LINE> msgs = { 'R1260': ( "%s is too complex. The McCabe rating is %d", 'too-complex', 'Used when a method or function is too complex based on ' 'McCabe Complexity Cyclomatic'), } <NEW_LINE> options = ( ('max-complexity', { 'default': 10, 'type': 'int', 'metavar': '<int>', 'help': 'McCabe complexity cyclomatic threshold', }), ) <NEW_LINE> @check_messages('too-complex') <NEW_LINE> def visit_module(self, node): <NEW_LINE> <INDENT> visitor = PathGraphingAstVisitor() <NEW_LINE> for child in node.body: <NEW_LINE> <INDENT> visitor.preorder(child, visitor) <NEW_LINE> <DEDENT> for graph in visitor.graphs.values(): <NEW_LINE> <INDENT> complexity = graph.complexity() <NEW_LINE> node = graph.root <NEW_LINE> if hasattr(node, 'name'): <NEW_LINE> <INDENT> node_name = "'%s'" % node.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node_name = "This '%s'" % node.__class__.__name__.lower() <NEW_LINE> <DEDENT> if complexity <= self.config.max_complexity: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.add_message( 'too-complex', node=node, confidence=HIGH, args=(node_name, complexity))
Checks McCabe complexity cyclomatic threshold in methods and functions to validate a too complex code.
6259907a23849d37ff852aad
class EnvironmentView(APIView): <NEW_LINE> <INDENT> CONFIGS_TO_EXPOSE = [ 'TERMS_OF_SERVICE_URL', 'PRIVACY_POLICY_URL', 'SOURCE_CODE_URL', 'SUPPORT_EMAIL', 'SUPPORT_URL', 'COMMUNITY_URL', ] <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> data = { key.lower(): getattr(constance.config, key) for key in self.CONFIGS_TO_EXPOSE } <NEW_LINE> data['available_sectors'] = SECTORS <NEW_LINE> data['available_countries'] = COUNTRIES <NEW_LINE> data['all_languages'] = LANGUAGES <NEW_LINE> data['interface_languages'] = settings.LANGUAGES <NEW_LINE> data['submission_placeholder'] = SUBMISSION_PLACEHOLDER <NEW_LINE> return Response(data)
GET-only view for certain server-provided configuration data
6259907a32920d7e50bc7a36
class ModelSerializer: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def dump_model(model, name: str, path="../resources/models"): <NEW_LINE> <INDENT> if model: <NEW_LINE> <INDENT> joblib.dump(model, f"{path}/{name}.pkl") <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def load_model(name: str): <NEW_LINE> <INDENT> model = joblib.load(f"{name}.pkl") <NEW_LINE> if model: <NEW_LINE> <INDENT> return model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('There is no model stored with this name')
Support serialize and deserialize the model
6259907ae1aae11d1e7cf50b
class Attacking(State): <NEW_LINE> <INDENT> def __init__(self, enemy, player): <NEW_LINE> <INDENT> State.__init__(self, "attacking") <NEW_LINE> self.enemy = enemy <NEW_LINE> self.player = player <NEW_LINE> self.enemy.world.render_boss = True <NEW_LINE> <DEDENT> def do_actions(self, tick): <NEW_LINE> <INDENT> if self.enemy.dead == True: <NEW_LINE> <INDENT> self.enemy.world.game_win = True <NEW_LINE> <DEDENT> self.enemy.reload -= tick <NEW_LINE> if self.enemy.reload <= 0: <NEW_LINE> <INDENT> dx = self.enemy.pos.x - self.player.pos.x <NEW_LINE> dy = self.enemy.pos.y - self.player.pos.y <NEW_LINE> for i in xrange(25): <NEW_LINE> <INDENT> angle = random.randint(0,360) <NEW_LINE> vel = vec2(cos(angle), sin(angle))*-300 <NEW_LINE> self.enemy.bullet_list.append(Shot.Shot(self.enemy.pos.copy(), angle, vel)) <NEW_LINE> <DEDENT> self.enemy.reload = self.enemy.reload_max <NEW_LINE> <DEDENT> if self.enemy.animate == False: <NEW_LINE> <INDENT> if random.randint(0,int((1/tick)*1))==0: <NEW_LINE> <INDENT> self.enemy.animate = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.enemy.img = self.enemy.lst[self.enemy.ani.get_full_frame(tick)] <NEW_LINE> self.enemy.img.set_colorkey((255,0,255)) <NEW_LINE> if self.enemy.ani.run == 1: <NEW_LINE> <INDENT> for i in range(2): <NEW_LINE> <INDENT> angle = radians(random.randint(0,359)) <NEW_LINE> dist = random.randint(40, 100) <NEW_LINE> vec = self.enemy.pos.copy() + vec2(cos(angle) * dist, sin(angle) * dist) <NEW_LINE> if random.randint(0, 1): <NEW_LINE> <INDENT> self.enemy.world.enemy_list.append(Spam(self.enemy.world, vec)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.enemy.world.enemy_list.append(Virus(self.enemy.world, vec)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.enemy.ani.finished == True: <NEW_LINE> <INDENT> self.enemy.ani.reset() <NEW_LINE> self.enemy.animate = False
The enemy can see the player and is actively attacking them them, staying away if possible
6259907a55399d3f05627f09
class ConfTree(ConfSimple): <NEW_LINE> <INDENT> def get(self, nm, sk = ''): <NEW_LINE> <INDENT> if sk == '' or sk[0] != '/': <NEW_LINE> <INDENT> return ConfSimple.get(self, nm, sk) <NEW_LINE> <DEDENT> if sk[len(sk)-1] != '/': <NEW_LINE> <INDENT> sk = sk + '/' <NEW_LINE> <DEDENT> while sk.find('/') != -1: <NEW_LINE> <INDENT> val = ConfSimple.get(self, nm, sk) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> i = sk.rfind('/') <NEW_LINE> if i == -1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> sk = sk[:i] <NEW_LINE> <DEDENT> return ConfSimple.get(self, nm)
A ConfTree adds path-hierarchical interpretation of the section keys, which should be '/'-separated values. When a value is requested for a given path, it will also be searched in the sections corresponding to the ancestors. E.g. get(name, '/a/b') will also look in sections '/a' and '/' or '' (the last 2 are equivalent)
6259907a5fc7496912d48f65
class Position: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def e(self): return Position(self.x+1, self.y) <NEW_LINE> def n(self): return Position(self.x, self.y-1) <NEW_LINE> def w(self): return Position(self.x-1, self.y) <NEW_LINE> def s(self): return Position(self.x, self.y+1) <NEW_LINE> def distance(self, other): <NEW_LINE> <INDENT> return abs(self.x-other.x) + abs(self.y-other.y) <NEW_LINE> <DEDENT> def surrounding_positions(self): <NEW_LINE> <INDENT> return [ Position(self.x+1, self.y+1), Position(self.x+1, self.y), Position(self.x+1, self.y-1), Position(self.x, self.y+1), Position(self.x, self.y-1), Position(self.x-1, self.y+1), Position(self.x-1, self.y), Position(self.x-1, self.y-1)] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[%d,%d]" % (self.x, self.y) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Position(%d,%d)" % (self.x, self.y) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.x == other.x and self.y == other.y <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.x < other.x or self.x == other.y and self.y < other.y <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.x, self.y))
A two dimentional point in space
6259907a7047854f46340db1
class TestCaseMixin(TestCase): <NEW_LINE> <INDENT> def create_app(self): <NEW_LINE> <INDENT> app = create_app() <NEW_LINE> app.config['TESTING'] = True <NEW_LINE> app.config['WTF_CSRF_ENABLED'] = False <NEW_LINE> return app <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> db.create_all() <NEW_LINE> current_app.logger.debug("setup complete") <NEW_LINE> super().setUp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> db.session.remove() <NEW_LINE> db.drop_all() <NEW_LINE> super().tearDown()
Use with flask.ext.testing.TestCase
6259907a091ae35668706633
class Node(): <NEW_LINE> <INDENT> def __init__(self, name, weight=None, children=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.weight = weight <NEW_LINE> self.parent = None <NEW_LINE> self.total_weight = weight <NEW_LINE> if children is None: <NEW_LINE> <INDENT> self.children = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.children = children <NEW_LINE> for child in self.children: <NEW_LINE> <INDENT> child.parent = self <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_child(self, node): <NEW_LINE> <INDENT> node.parent = self <NEW_LINE> self.children.append(node) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Node[name = {}, weight = {}, total_weight = {}]" .format(self.name, self.weight, self.total_weight) <NEW_LINE> <DEDENT> def get_total_weight(self): <NEW_LINE> <INDENT> if len(self.children)==0: <NEW_LINE> <INDENT> return self.weight <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.weight + sum([ child.get_total_weight() for child in self.children ]) <NEW_LINE> <DEDENT> <DEDENT> def find_unbalanced_node(self): <NEW_LINE> <INDENT> if len(self.children) <2: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> differentNode = None <NEW_LINE> for i in range(1, len(self.children)-1): <NEW_LINE> <INDENT> prev= self.children[i-1].get_total_weight() <NEW_LINE> current = self.children[i].get_total_weight() <NEW_LINE> next = self.children[i+1].get_total_weight() <NEW_LINE> if prev!= current and current!=next: <NEW_LINE> <INDENT> differentNode = self.children[i] <NEW_LINE> break <NEW_LINE> <DEDENT> elif prev!=current and current== next: <NEW_LINE> <INDENT> differentNode = self.children[i-1] <NEW_LINE> break <NEW_LINE> <DEDENT> elif prev ==current and current!=next: <NEW_LINE> <INDENT> differentNode = self.children[i+1] <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> if differentNode is not None: <NEW_LINE> <INDENT> still_unbalanced= differentNode.find_unbalanced_node() <NEW_LINE> if still_unbalanced is None: <NEW_LINE> <INDENT> return differentNode <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return still_unbalanced <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None
Defines a program in advent of code day 7 puzzle
6259907a796e427e53850170
class drawShowArtButton : <NEW_LINE> <INDENT> def __init__(self, xl, yl, xu, yu): <NEW_LINE> <INDENT> self.coord = (xl, yl, xu, yu) <NEW_LINE> <DEDENT> def drawbutton(self): <NEW_LINE> <INDENT> t.penup() <NEW_LINE> t.goto(self.coord[0], self.coord[1]) <NEW_LINE> t.setheading(90) <NEW_LINE> t.pendown() <NEW_LINE> t.pencolor('black') <NEW_LINE> t.fillcolor('lightblue') <NEW_LINE> t.begin_fill() <NEW_LINE> for k in range(4) : <NEW_LINE> <INDENT> t.forward(80) <NEW_LINE> t.right(90) <NEW_LINE> <DEDENT> t.end_fill() <NEW_LINE> <DEDENT> def write_show(self) : <NEW_LINE> <INDENT> t.penup() <NEW_LINE> t.goto(-120, 205) <NEW_LINE> t.pendown() <NEW_LINE> t.write('Show', font=("Arial", 18, "bold")) <NEW_LINE> <DEDENT> def write_art(self) : <NEW_LINE> <INDENT> t.penup() <NEW_LINE> t.goto(-110, 185) <NEW_LINE> t.pendown() <NEW_LINE> t.write('Art', font=("Arial", 18, "bold"))
Represents the draw show art button
6259907a7047854f46340db2
class Branch(Connectable): <NEW_LINE> <INDENT> def __init__(self, shape=None, net=None, layer=None, proxy_for=None): <NEW_LINE> <INDENT> self.net = net <NEW_LINE> self.shape = shape.centroid.buffer(TRACK_RADIUS) <NEW_LINE> self.proxy_for = proxy_for <NEW_LINE> if layer: <NEW_LINE> <INDENT> self.layers = [layer] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.layers = [FRONT, BACK] <NEW_LINE> <DEDENT> <DEDENT> def is_on_layer(self, layer): <NEW_LINE> <INDENT> if len(self.layers) == 2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.layers[0] == layer <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.proxy_for: <NEW_LINE> <INDENT> return 'Branch on %s proxy for %s' % (self.layers, str(self.proxy_for)) <NEW_LINE> <DEDENT> return 'Branch on %s at %r net=%s' % ( self.layers, tuple(self.shape.centroid.coords), self.net)
A point on a layer that connects to multiple points. There is no pad associated with it
6259907a5fcc89381b266e56
class Imply(LogicOperator, AlphabeticSymbol): <NEW_LINE> <INDENT> symbols = ['-->'] <NEW_LINE> def __init__(self, phi, psi): <NEW_LINE> <INDENT> super(Imply, self).__init__(phi, psi)
Represents logic implication.
6259907a32920d7e50bc7a38
class RegistryConfigurationComponent(ConfigurationComponent): <NEW_LINE> <INDENT> id = 'registry' <NEW_LINE> def get_coercion(self): <NEW_LINE> <INDENT> return { 'registry_streaming': asbool, 'debug': asbool } <NEW_LINE> <DEDENT> def get_defaults(self): <NEW_LINE> <INDENT> return { 'registry_streaming': True, } <NEW_LINE> <DEDENT> def get_actions(self): <NEW_LINE> <INDENT> return ( AppReadyConfigurationAction(self._add_registry_middleware), ) <NEW_LINE> <DEDENT> def _add_registry_middleware(self, conf, app): <NEW_LINE> <INDENT> return RegistryManager(app, streaming=conf.get('registry_streaming', True), preserve_exceptions=conf.get('debug', False))
Configure the request local context registry. This configures support for setting and restoring a clean turbogears context on each request. This makes so that ``tg.request``, ``tg.response`` and so on always refer to the data for current request. Options: * ``registry_streaming``: Enable streaming responses, thus restoring the registry at the end of the stream instead of as soon as the controller action returned. This is enabled by default. * ``debug``: Ensures that the registry is not discarded in case of an exception. So that after the exception is possible to inspect the state of the request that caused the exception.
6259907a4f88993c371f121d
class LockRequest(Request): <NEW_LINE> <INDENT> command_id = SMB2_LOCK <NEW_LINE> structure_size = 48 <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> Request.__init__(self, parent) <NEW_LINE> self.file_id = None <NEW_LINE> self.lock_sequence = 0 <NEW_LINE> self.locks = [] <NEW_LINE> self.lock_count = None <NEW_LINE> <DEDENT> def _encode(self, cur): <NEW_LINE> <INDENT> if self.lock_count == None: <NEW_LINE> <INDENT> self.lock_count = len(self.locks) <NEW_LINE> <DEDENT> cur.encode_uint16le(self.lock_count) <NEW_LINE> cur.encode_uint32le(self.lock_sequence) <NEW_LINE> cur.encode_uint64le(self.file_id[0]) <NEW_LINE> cur.encode_uint64le(self.file_id[1]) <NEW_LINE> for lock in self.locks: <NEW_LINE> <INDENT> cur.encode_uint64le(lock[0]) <NEW_LINE> cur.encode_uint64le(lock[1]) <NEW_LINE> cur.encode_uint32le(lock[2]) <NEW_LINE> cur.encode_uint32le(0)
@ivar locks: A list of lock tuples, each of which consists of (offset, length, flags).
6259907a656771135c48ad2b
class _ChangelistCodereviewBase(object): <NEW_LINE> <INDENT> def __init__(self, changelist): <NEW_LINE> <INDENT> self._changelist = changelist <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self._changelist, attr) <NEW_LINE> <DEDENT> def GetStatus(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def GetCodereviewServer(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def FetchDescription(self, force=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def IssueConfigKey(cls): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def PatchsetConfigKey(cls): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def CodereviewServerConfigKey(cls): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _PostUnsetIssueProperties(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def GetRieveldObjForPresubmit(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def GetGerritObjForPresubmit(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def UpdateDescriptionRemote(self, description, force=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def CloseIssue(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def GetApprovingReviewers(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def GetMostRecentPatchset(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, directory): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def ParseIssueURL(parsed_url): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def EnsureAuthenticated(self, force, refresh=False): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def EnsureCanUploadPatchset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CMDUploadChange(self, options, args, change): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def SetCQState(self, new_state): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def CannotTriggerTryJobReason(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def GetIssueOwner(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def GetTryjobProperties(self, patchset=None): <NEW_LINE> <INDENT> raise NotImplementedError()
Abstract base class encapsulating codereview specifics of a changelist.
6259907a283ffb24f3cf5297
class class_wrapper_t( scoped.scoped_t ): <NEW_LINE> <INDENT> def __init__(self, declaration, class_creator ): <NEW_LINE> <INDENT> scoped.scoped_t.__init__( self, declaration=declaration ) <NEW_LINE> self._class_creator = class_creator <NEW_LINE> self._base_wrappers = [] <NEW_LINE> <DEDENT> def _get_wrapper_alias( self ): <NEW_LINE> <INDENT> return self.declaration.wrapper_alias <NEW_LINE> <DEDENT> def _set_wrapper_alias( self, walias ): <NEW_LINE> <INDENT> self.declaration.wrapper_alias = walias <NEW_LINE> <DEDENT> wrapper_alias = property( _get_wrapper_alias, _set_wrapper_alias ) <NEW_LINE> @property <NEW_LINE> def base_wrappers( self ): <NEW_LINE> <INDENT> if self.declaration.is_abstract and not self._base_wrappers: <NEW_LINE> <INDENT> bases = [ hi.related_class for hi in self.declaration.bases ] <NEW_LINE> creators_before_me = algorithm.creators_affect_on_me( self ) <NEW_LINE> self._base_wrappers = [creator for creator in creators_before_me if isinstance( creator, class_wrapper_t ) and creator.declaration in bases] <NEW_LINE> <DEDENT> return self._base_wrappers <NEW_LINE> <DEDENT> @property <NEW_LINE> def exposed_identifier(self): <NEW_LINE> <INDENT> return algorithm.create_identifier( self, self.declaration.partial_decl_string ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def class_creator(self): <NEW_LINE> <INDENT> return self._class_creator <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_name( self ): <NEW_LINE> <INDENT> if not isinstance( self.parent, class_wrapper_t ): <NEW_LINE> <INDENT> return self.declaration.wrapper_alias <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> full_name = [self.wrapper_alias] <NEW_LINE> parent = self.parent <NEW_LINE> while isinstance( parent, class_wrapper_t ): <NEW_LINE> <INDENT> full_name.append( parent.wrapper_alias ) <NEW_LINE> parent = parent.parent <NEW_LINE> <DEDENT> full_name.reverse() <NEW_LINE> return '::'.join( full_name ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def held_type(self): <NEW_LINE> <INDENT> return self._class_creator.held_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def boost_wrapper_identifier(self): <NEW_LINE> <INDENT> boost_wrapper = algorithm.create_identifier( self, '::boost::python::wrapper' ) <NEW_LINE> return declarations.templates.join( boost_wrapper, [self.exposed_identifier] ) <NEW_LINE> <DEDENT> def _create_bases(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> extrabases = self.class_creator.declaration._fake_bases <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> extrabases = [] <NEW_LINE> <DEDENT> return ', '.join( extrabases + [self.exposed_identifier, self.boost_wrapper_identifier] ) <NEW_LINE> <DEDENT> def _create_impl(self): <NEW_LINE> <INDENT> if self.declaration.already_exposed: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> answer = ['struct %s : %s {' % ( self.wrapper_alias, self._create_bases() )] <NEW_LINE> answer.append( '' ) <NEW_LINE> answer.append( self.create_internal_code( self.creators ) ) <NEW_LINE> answer.append( '' ) <NEW_LINE> answer.append( '};' ) <NEW_LINE> return os.linesep.join( answer ) <NEW_LINE> <DEDENT> def _get_system_files_impl( self ): <NEW_LINE> <INDENT> return []
creates C++ code, which creates wrapper around a class
6259907a3617ad0b5ee07b45
class ListAccounts(object): <NEW_LINE> <INDENT> swagger_types = { 'filters': 'FilterIdArray', 'sort': 'SortId', 'total': 'int', 'offset': 'int', 'limit': 'int', 'items': 'list[AccountFull]' } <NEW_LINE> attribute_map = { 'filters': 'filters', 'sort': 'sort', 'total': 'total', 'offset': 'offset', 'limit': 'limit', 'items': 'items' } <NEW_LINE> def __init__(self, filters=None, sort=None, total=None, offset=None, limit=None, items=None): <NEW_LINE> <INDENT> self._filters = None <NEW_LINE> self._sort = None <NEW_LINE> self._total = None <NEW_LINE> self._offset = None <NEW_LINE> self._limit = None <NEW_LINE> self._items = None <NEW_LINE> if filters is not None: <NEW_LINE> <INDENT> self.filters = filters <NEW_LINE> <DEDENT> if sort is not None: <NEW_LINE> <INDENT> self.sort = sort <NEW_LINE> <DEDENT> if total is not None: <NEW_LINE> <INDENT> self.total = total <NEW_LINE> <DEDENT> if offset is not None: <NEW_LINE> <INDENT> self.offset = offset <NEW_LINE> <DEDENT> if limit is not None: <NEW_LINE> <INDENT> self.limit = limit <NEW_LINE> <DEDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def filters(self): <NEW_LINE> <INDENT> return self._filters <NEW_LINE> <DEDENT> @filters.setter <NEW_LINE> def filters(self, filters): <NEW_LINE> <INDENT> self._filters = filters <NEW_LINE> <DEDENT> @property <NEW_LINE> def sort(self): <NEW_LINE> <INDENT> return self._sort <NEW_LINE> <DEDENT> @sort.setter <NEW_LINE> def sort(self, sort): <NEW_LINE> <INDENT> self._sort = sort <NEW_LINE> <DEDENT> @property <NEW_LINE> def total(self): <NEW_LINE> <INDENT> return self._total <NEW_LINE> <DEDENT> @total.setter <NEW_LINE> def total(self, total): <NEW_LINE> <INDENT> self._total = total <NEW_LINE> <DEDENT> @property <NEW_LINE> def offset(self): <NEW_LINE> <INDENT> return self._offset <NEW_LINE> <DEDENT> @offset.setter <NEW_LINE> def offset(self, offset): <NEW_LINE> <INDENT> self._offset = offset <NEW_LINE> <DEDENT> @property <NEW_LINE> def limit(self): <NEW_LINE> <INDENT> return self._limit <NEW_LINE> <DEDENT> @limit.setter <NEW_LINE> def limit(self, limit): <NEW_LINE> <INDENT> self._limit = limit <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ListAccounts): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259907ad268445f2663a85a
class GenerateUuidTask(ManagementTask): <NEW_LINE> <INDENT> def run(self, namespace): <NEW_LINE> <INDENT> from uuid import uuid4 <NEW_LINE> logger.debug("Displaying a random uuid4 string.") <NEW_LINE> print(uuid4()) <NEW_LINE> sys.exit(0)
Generates an uuid4 string
6259907af548e778e596cf89
@test_tags("port", "server_port_flap", "run-on-diff") <NEW_LINE> @unittest.skip("Test broken - T24997025 to investigate furthur") <NEW_LINE> class ServerPortFlap(FbossBaseSystemTest): <NEW_LINE> <INDENT> def test_server_port_flap(self): <NEW_LINE> <INDENT> number_of_flaps = 1 <NEW_LINE> convergence_time_allowed = 10 <NEW_LINE> delay_time_buffer = 22 <NEW_LINE> for host in self.test_topology.hosts(): <NEW_LINE> <INDENT> self.log.info("Testing host {}".format(host.name)) <NEW_LINE> host_binary_ip = ip_str_to_addr(next(host.ips())) <NEW_LINE> host_if = next(iter(host.intfs())) <NEW_LINE> switch_port_id = None <NEW_LINE> self.log.debug("Running port flap test on - {}".format(host)) <NEW_LINE> switch_port_id = self.test_topology.get_switch_port_id_from_ip( host_binary_ip) <NEW_LINE> with self.test_topology.switch_thrift() as sw_client: <NEW_LINE> <INDENT> port_info = sw_client.getPortInfo(switch_port_id) <NEW_LINE> self.log.debug("Check that the port is up before test start.") <NEW_LINE> self.assertEqual(port_info.operState, PortOperState.UP) <NEW_LINE> <DEDENT> thread = threading.Thread(target=self.threadFlapPort, args=(host_if, number_of_flaps, convergence_time_allowed, host)) <NEW_LINE> thread.start() <NEW_LINE> time.sleep(5) <NEW_LINE> with self.test_topology.switch_thrift() as sw_client: <NEW_LINE> <INDENT> port_info = sw_client.getPortInfo(switch_port_id) <NEW_LINE> self.assertEqual(port_info.operState, PortOperState.DOWN) <NEW_LINE> <DEDENT> time.sleep(delay_time_buffer + convergence_time_allowed) <NEW_LINE> with self.test_topology.switch_thrift() as sw_client: <NEW_LINE> <INDENT> port_info = sw_client.getPortInfo(switch_port_id) <NEW_LINE> self.assertEqual(port_info.operState, PortOperState.UP) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def threadFlapPort(self, host_if, number_of_flaps, delay_time_buffer, host): <NEW_LINE> <INDENT> with host.thrift_client() as client: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.log.debug("Setting port down at {}".format(time.time())) <NEW_LINE> client.flap_server_port(host_if, number_of_flaps, delay_time_buffer) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.log.info("Exception caught{}".format(e)) <NEW_LINE> pass
Verify that a server port flap is handled by fboss correctly and does not hang the system.
6259907a21bff66bcd724661
class ChildLifecycle(models.Model): <NEW_LINE> <INDENT> _inherit = 'compassion.child.ble' <NEW_LINE> @api.model <NEW_LINE> def process_commkit(self, commkit_data): <NEW_LINE> <INDENT> ids = super(ChildLifecycle, self).process_commkit(commkit_data) <NEW_LINE> for lifecycle in self.browse(ids).filtered('child_id.sponsor_id'): <NEW_LINE> <INDENT> communication_type = self.env[ 'partner.communication.config'].search([ ('name', 'ilike', lifecycle.type), ('name', 'like', 'Beneficiary'), ('name', 'not like', 'Exit') ]) <NEW_LINE> if communication_type: <NEW_LINE> <INDENT> self.env['partner.communication.job'].create({ 'config_id': communication_type.id, 'partner_id': lifecycle.child_id.sponsor_id.id, 'object_ids': lifecycle.child_id.id, 'user_id': communication_type.user_id.id, }) <NEW_LINE> <DEDENT> <DEDENT> return ids
Send Communication when Child Lifecycle Event is received.
6259907a99fddb7c1ca63ad3
class SimpleMocker: <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> print("entering context") <NEW_LINE> return "entering context" <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> raise FileNotFoundError
Simple mocking class to test triggers on __enter__ and __exit__
6259907a67a9b606de5477a2
class ASFByteArrayAttribute(ASFBaseAttribute): <NEW_LINE> <INDENT> TYPE = 0x0001 <NEW_LINE> def parse(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def _render(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def data_size(self): <NEW_LINE> <INDENT> return len(self.value) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[binary data (%s bytes)]" % len(self.value) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return str(self) < other <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return str(self) == other <NEW_LINE> <DEDENT> __hash__ = ASFBaseAttribute.__hash__
Byte array attribute.
6259907a009cb60464d02f37
class Server(object): <NEW_LINE> <INDENT> def __init__(self, threads=1000): <NEW_LINE> <INDENT> self.pool = eventlet.GreenPool(threads) <NEW_LINE> self.socket_info = {} <NEW_LINE> <DEDENT> def start(self, application, port, host='0.0.0.0', key=None, backlog=128): <NEW_LINE> <INDENT> self.application = application <NEW_LINE> arg0 = sys.argv[0] <NEW_LINE> logging.debug('Starting %(arg0)s on %(host)s:%(port)s' % locals()) <NEW_LINE> socket = eventlet.listen((host, port), backlog=backlog) <NEW_LINE> self.pool.spawn_n(self._run, application, socket) <NEW_LINE> if key: <NEW_LINE> <INDENT> self.socket_info[key] = socket.getsockname() <NEW_LINE> <DEDENT> <DEDENT> def wait(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.pool.waitall() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def _run(self, application, socket): <NEW_LINE> <INDENT> logger = logging.getLogger('eventlet.wsgi.server') <NEW_LINE> eventlet.wsgi.server(socket, application, custom_pool=self.pool, log=WritableLogger(logger))
Server class to manage multiple WSGI sockets and applications.
6259907ad486a94d0ba2d9b0
class SingleChoiceParameter(Parameter): <NEW_LINE> <INDENT> def __init__(self, id, choices): <NEW_LINE> <INDENT> super(SingleChoiceParameter, self).__init__(id) <NEW_LINE> self.choices = to_list(choices) <NEW_LINE> <DEDENT> def prompt(self, prompt, old_value=None): <NEW_LINE> <INDENT> print >> sys.stdout, prompt <NEW_LINE> index = 1 <NEW_LINE> for choice in self.choices: <NEW_LINE> <INDENT> print >> sys.stdout, "\t{0:d}. {1}".format(index, choice) <NEW_LINE> index += 1 <NEW_LINE> <DEDENT> choices_len = len(self.choices) <NEW_LINE> while True: <NEW_LINE> <INDENT> user_input = self.get_user_input("Choice: ") <NEW_LINE> if len(user_input) == 0 and old_value: <NEW_LINE> <INDENT> choice = old_value <NEW_LINE> break <NEW_LINE> <DEDENT> elif user_input in [str(x) for x in range(1, choices_len + 1)]: <NEW_LINE> <INDENT> choice = self.choices[int(user_input) - 1] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return choice
A parameter implemeting a single choice between multiple choices.
6259907a23849d37ff852ab1
class DeleteUInfluxdbDatabaseResponseSchema(schema.ResponseSchema): <NEW_LINE> <INDENT> fields = {}
DeleteUInfluxdbDatabase - 删除Influxdb实例的数据库
6259907a4c3428357761bcb2
class RestDrive(Drive): <NEW_LINE> <INDENT> name = 'rest-drive' <NEW_LINE> def __init__(self, drive_system): <NEW_LINE> <INDENT> super().__init__(drive_system) <NEW_LINE> self.range_overwhelmed = [self.drive_min, -30] <NEW_LINE> self.range_underwhelmed = [70, self.drive_max] <NEW_LINE> self.range_homeostatic = [self.range_overwhelmed[1], self.range_underwhelmed[0]] <NEW_LINE> <DEDENT> def update(self, elapsed): <NEW_LINE> <INDENT> self.drive_level = min(self.drive_max, self.drive_level + (0.5 * elapsed)) <NEW_LINE> pass
The drive that motivates the system to get rest
6259907a442bda511e95da54
class TaskType(type): <NEW_LINE> <INDENT> def __new__(cls, name, bases, attrs): <NEW_LINE> <INDENT> new = super(TaskType, cls).__new__ <NEW_LINE> task_module = attrs.get("__module__") or "__main__" <NEW_LINE> if attrs.pop("abstract", None) or not attrs.get("autoregister", True): <NEW_LINE> <INDENT> return new(cls, name, bases, attrs) <NEW_LINE> <DEDENT> _app1, _app2 = attrs.pop("_app", None), attrs.pop("app", None) <NEW_LINE> app = attrs["_app"] = _app1 or _app2 or current_app <NEW_LINE> autoname = False <NEW_LINE> if not attrs.get("name"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module_name = sys.modules[task_module].__name__ <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> module_name = task_module <NEW_LINE> <DEDENT> attrs["name"] = '.'.join(filter(None, [module_name, name])) <NEW_LINE> autoname = True <NEW_LINE> <DEDENT> tasks = app._tasks <NEW_LINE> if autoname and task_module == "__main__" and app.main: <NEW_LINE> <INDENT> attrs["name"] = '.'.join([app.main, name]) <NEW_LINE> <DEDENT> task_name = attrs["name"] <NEW_LINE> if task_name not in tasks: <NEW_LINE> <INDENT> tasks.register(new(cls, name, bases, attrs)) <NEW_LINE> <DEDENT> instance = tasks[task_name] <NEW_LINE> instance.bind(app) <NEW_LINE> return instance.__class__ <NEW_LINE> <DEDENT> def __repr__(cls): <NEW_LINE> <INDENT> if cls._app: <NEW_LINE> <INDENT> return "<class %s of %s>" % (cls.__name__, cls._app, ) <NEW_LINE> <DEDENT> return "<unbound %s>" % (cls.__name__, )
Meta class for tasks. Automatically registers the task in the task registry, except if the `abstract` attribute is set. If no `name` attribute is provided, then no name is automatically set to the name of the module it was defined in, and the class name.
6259907afff4ab517ebcf211
class And(ParseExpression): <NEW_LINE> <INDENT> class _ErrorStop(Empty): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Empty,self).__init__(*args, **kwargs) <NEW_LINE> self.leaveWhitespace() <NEW_LINE> <DEDENT> <DEDENT> def __init__( self, exprs, savelist = True ): <NEW_LINE> <INDENT> super(And,self).__init__(exprs, savelist) <NEW_LINE> self.mayReturnEmpty = True <NEW_LINE> for e in self.exprs: <NEW_LINE> <INDENT> if not e.mayReturnEmpty: <NEW_LINE> <INDENT> self.mayReturnEmpty = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self.setWhitespaceChars( exprs[0].whiteChars ) <NEW_LINE> self.skipWhitespace = exprs[0].skipWhitespace <NEW_LINE> self.callPreparse = True <NEW_LINE> <DEDENT> def parseImpl( self, instring, loc, doActions=True ): <NEW_LINE> <INDENT> loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False ) <NEW_LINE> errorStop = False <NEW_LINE> for e in self.exprs[1:]: <NEW_LINE> <INDENT> if isinstance(e, And._ErrorStop): <NEW_LINE> <INDENT> errorStop = True <NEW_LINE> continue <NEW_LINE> <DEDENT> if errorStop: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> loc, exprtokens = e._parse( instring, loc, doActions ) <NEW_LINE> <DEDENT> except ParseSyntaxException: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except ParseBaseException: <NEW_LINE> <INDENT> pe = sys.exc_info()[1] <NEW_LINE> raise ParseSyntaxException(pe) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> loc, exprtokens = e._parse( instring, loc, doActions ) <NEW_LINE> <DEDENT> if exprtokens or list(exprtokens.keys()): <NEW_LINE> <INDENT> resultlist += exprtokens <NEW_LINE> <DEDENT> <DEDENT> return loc, resultlist <NEW_LINE> <DEDENT> def __iadd__(self, other ): <NEW_LINE> <INDENT> if isinstance( other, str ): <NEW_LINE> <INDENT> other = Literal( other ) <NEW_LINE> <DEDENT> return self.append( other ) <NEW_LINE> <DEDENT> def checkRecursion( self, parseElementList ): <NEW_LINE> <INDENT> subRecCheckList = parseElementList[:] + [ self ] <NEW_LINE> for e in self.exprs: <NEW_LINE> <INDENT> e.checkRecursion( subRecCheckList ) <NEW_LINE> if not e.mayReturnEmpty: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__( self ): <NEW_LINE> <INDENT> if hasattr(self,"name"): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> if self.strRepr is None: <NEW_LINE> <INDENT> self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}" <NEW_LINE> <DEDENT> return self.strRepr
Requires all given C{ParseExpressions} to be found in the given order. Expressions may be separated by whitespace. May be constructed using the '+' operator.
6259907aec188e330fdfa2a1
class INtsuThemeLayer(IDefaultBrowserLayer): <NEW_LINE> <INDENT> pass
Marker interface that defines a browser layer.
6259907a283ffb24f3cf5299
class RfModbusMasterRTU(RfModbusMaster): <NEW_LINE> <INDENT> def __init__(self, debug_level=logging.NOTSET): <NEW_LINE> <INDENT> super(RfModbusMasterRTU, self).__init__(debug_level=debug_level) <NEW_LINE> self.serial = None <NEW_LINE> <DEDENT> def open_connection(self, port='/dev/ttyUSB0', timeout=0.5, verbose=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.debug("Creating serial interface...") <NEW_LINE> self.serial = serial.Serial(port, baudrate=9600, bytesize=8, parity='E', stopbits=1, xonxoff=0) <NEW_LINE> self.logger.debug("Opening modbus connection...") <NEW_LINE> self.master = modbus_rtu.RtuMaster(self.serial) <NEW_LINE> self.master.set_verbose(verbose) <NEW_LINE> self.master.set_timeout(float(timeout)) <NEW_LINE> self.logger.info("Opened modbus connection.") <NEW_LINE> <DEDENT> except (modbus_tk.modbus.ModbusError, OSError) as error: <NEW_LINE> <INDENT> self._process_error(except_object=error, msg="Could not open connection")
RfModbusMasterRTU class implements a modbus master which can communicate with slaves through a serial line
6259907a9c8ee82313040e84
class Manager(base.Manager): <NEW_LINE> <INDENT> resource_class = Resource <NEW_LINE> service_type = 'network' <NEW_LINE> _attr_mapping = ATTRIBUTE_MAPPING <NEW_LINE> _hidden_methods = ["update"] <NEW_LINE> _json_resource_key = 'security_group' <NEW_LINE> _json_resources_key = 'security_groups' <NEW_LINE> _url_resource_path = '/v2.0/security-groups' <NEW_LINE> def create(self, name=UNDEF, description=UNDEF, project=UNDEF): <NEW_LINE> <INDENT> return super(Manager, self).create(name=name, description=description, project=project)
Manager class for security groups in Networking V2 API
6259907a2c8b7c6e89bd51e4
class DummyForm(CleanSummer,forms.Form): <NEW_LINE> <INDENT> text = forms.CharField(widget=SummernoteWidget(),label="") <NEW_LINE> summer_max_length=1000
DummyForm to test CleanSummer mixin
6259907af9cc0f698b1c5fc9
class MailNotificationService(BaseNotificationService): <NEW_LINE> <INDENT> def __init__(self, server, port, sender, starttls, username, password, recipient, debug): <NEW_LINE> <INDENT> self._server = server <NEW_LINE> self._port = port <NEW_LINE> self._sender = sender <NEW_LINE> self.starttls = starttls <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.recipient = recipient <NEW_LINE> self.debug = debug <NEW_LINE> self.tries = 2 <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> mail = smtplib.SMTP(self._server, self._port, timeout=5) <NEW_LINE> mail.set_debuglevel(self.debug) <NEW_LINE> mail.ehlo_or_helo_if_needed() <NEW_LINE> if self.starttls == 1: <NEW_LINE> <INDENT> mail.starttls() <NEW_LINE> mail.ehlo() <NEW_LINE> <DEDENT> if self.username and self.password: <NEW_LINE> <INDENT> mail.login(self.username, self.password) <NEW_LINE> <DEDENT> return mail <NEW_LINE> <DEDENT> def send_message(self, message="", **kwargs): <NEW_LINE> <INDENT> mail = self.connect() <NEW_LINE> subject = kwargs.get(ATTR_TITLE) <NEW_LINE> msg = MIMEText(message) <NEW_LINE> msg['Subject'] = subject <NEW_LINE> msg['To'] = self.recipient <NEW_LINE> msg['From'] = self._sender <NEW_LINE> msg['X-Mailer'] = 'HomeAssistant' <NEW_LINE> for _ in range(self.tries): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mail.sendmail(self._sender, self.recipient, msg.as_string()) <NEW_LINE> break <NEW_LINE> <DEDENT> except smtplib.SMTPException: <NEW_LINE> <INDENT> _LOGGER.warning('SMTPException sending mail: ' 'retrying connection') <NEW_LINE> mail.quit() <NEW_LINE> mail = self.connect() <NEW_LINE> <DEDENT> <DEDENT> mail.quit()
Implements notification service for E-Mail messages.
6259907aaad79263cf4301b3
class Package(object): <NEW_LINE> <INDENT> def __init__(self, store, collection, id=None): <NEW_LINE> <INDENT> self.store = store <NEW_LINE> self.collection = collection.name <NEW_LINE> self.id = id or uuid4().hex <NEW_LINE> <DEDENT> def has(self, cls, name): <NEW_LINE> <INDENT> return cls(self, name).exists() <NEW_LINE> <DEDENT> def all(self, cls, *extra): <NEW_LINE> <INDENT> prefix = os.path.join(cls.GROUP, *extra) <NEW_LINE> for path in self.store.list_resources(self.collection, self.id): <NEW_LINE> <INDENT> if path.startswith(prefix): <NEW_LINE> <INDENT> yield cls.from_path(self, path) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def exists(self): <NEW_LINE> <INDENT> obj = self.store.get_object(self.collection, self.id, MANIFEST) <NEW_LINE> return obj.exists() <NEW_LINE> <DEDENT> @property <NEW_LINE> def manifest(self): <NEW_LINE> <INDENT> if not hasattr(self, '_manifest'): <NEW_LINE> <INDENT> obj = self.store.get_object(self.collection, self.id, MANIFEST) <NEW_LINE> self._manifest = Manifest(obj) <NEW_LINE> <DEDENT> return self._manifest <NEW_LINE> <DEDENT> def get_resource(self, path): <NEW_LINE> <INDENT> for resource_type in get_resource_types().values(): <NEW_LINE> <INDENT> prefix = os.path.join(resource_type.GROUP, '') <NEW_LINE> if path.startswith(prefix): <NEW_LINE> <INDENT> return resource_type.from_path(self, path) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> self.manifest.save() <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> sources = list(self.all(Source)) <NEW_LINE> if not len(sources): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return sources[0] <NEW_LINE> <DEDENT> def ingest(self, something, meta=None, overwrite=True): <NEW_LINE> <INDENT> ingestors = list(Ingestor.analyze(something)) <NEW_LINE> if len(ingestors) != 1: <NEW_LINE> <INDENT> raise ValueError("Can't ingest: %r" % something) <NEW_LINE> <DEDENT> ingestor = ingestors[0] <NEW_LINE> try: <NEW_LINE> <INDENT> meta = ingestor.generate_meta(meta) <NEW_LINE> name = None <NEW_LINE> for i in count(1): <NEW_LINE> <INDENT> suffix = '-%s' % i if i > 1 else '' <NEW_LINE> name = '%s%s.%s' % (meta['slug'], suffix, meta['extension']) <NEW_LINE> if overwrite or not self.has(Source, name): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> source = Source(self, name) <NEW_LINE> source.meta.update(meta) <NEW_LINE> ingestor.store(source) <NEW_LINE> self.save() <NEW_LINE> return source <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> ingestor.dispose() <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.id == other.id <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Package(%r, %r)>' % (self.collection, self.id)
An package is a resource in the remote bucket. It consists of a source file, a manifest metadata file and one or many processed version.
6259907ad268445f2663a85b
class SchemeMorphism_spec(SchemeMorphism): <NEW_LINE> <INDENT> def __init__(self, parent, phi, check=True): <NEW_LINE> <INDENT> SchemeMorphism.__init__(self, parent) <NEW_LINE> if check: <NEW_LINE> <INDENT> from sage.categories.all import Rings <NEW_LINE> if not (isinstance(phi, Map) and phi.category_for().is_subcategory(Rings())): <NEW_LINE> <INDENT> raise TypeError("phi (=%s) must be a ring homomorphism" % phi) <NEW_LINE> <DEDENT> if phi.domain() != parent.codomain().coordinate_ring(): <NEW_LINE> <INDENT> raise TypeError("phi (=%s) must have domain %s" % (phi, parent.codomain().coordinate_ring())) <NEW_LINE> <DEDENT> if phi.codomain() != parent.domain().coordinate_ring(): <NEW_LINE> <INDENT> raise TypeError("phi (=%s) must have codomain %s" % (phi, parent.domain().coordinate_ring())) <NEW_LINE> <DEDENT> <DEDENT> self.__ring_homomorphism = phi <NEW_LINE> <DEDENT> def _call_(self, x): <NEW_LINE> <INDENT> S = self.ring_homomorphism().inverse_image(x.prime_ideal()) <NEW_LINE> return self._codomain(S) <NEW_LINE> <DEDENT> def _repr_type(self): <NEW_LINE> <INDENT> return "Affine Scheme" <NEW_LINE> <DEDENT> def _repr_defn(self): <NEW_LINE> <INDENT> return repr(self.ring_homomorphism()) <NEW_LINE> <DEDENT> def ring_homomorphism(self): <NEW_LINE> <INDENT> return self.__ring_homomorphism
Morphism of spectra of rings INPUT: - ``parent`` -- Hom-set whose domain and codomain are affine schemes. - ``phi`` -- a ring morphism with matching domain and codomain. - ``check`` -- boolean (optional, default:``True``). Whether to check the input for consistency. EXAMPLES:: sage: R.<x> = PolynomialRing(QQ) sage: phi = R.hom([QQ(7)]); phi Ring morphism: From: Univariate Polynomial Ring in x over Rational Field To: Rational Field Defn: x |--> 7 sage: X = Spec(QQ); Y = Spec(R) sage: f = X.hom(phi); f Affine Scheme morphism: From: Spectrum of Rational Field To: Spectrum of Univariate Polynomial Ring in x over Rational Field Defn: Ring morphism: From: Univariate Polynomial Ring in x over Rational Field To: Rational Field Defn: x |--> 7 sage: f.ring_homomorphism() Ring morphism: From: Univariate Polynomial Ring in x over Rational Field To: Rational Field Defn: x |--> 7
6259907a796e427e53850174
class GroupList(_messages.Message): <NEW_LINE> <INDENT> id = _messages.StringField(1) <NEW_LINE> items = _messages.MessageField('Group', 2, repeated=True) <NEW_LINE> kind = _messages.StringField(3, default=u'clouduseraccounts#groupList') <NEW_LINE> nextPageToken = _messages.StringField(4) <NEW_LINE> selfLink = _messages.StringField(5)
A GroupList object. Fields: id: [Output Only] Unique identifier for the resource; defined by the server. items: A list of Group resources. kind: [Output Only] Type of resource. Always clouduseraccounts#groupList for lists of groups. nextPageToken: [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results. selfLink: [Output Only] Server defined URL for this resource.
6259907a7b180e01f3e49d62
class DeleteObject(command.Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__ + '.DeleteObject') <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(DeleteObject, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'container', metavar='<container>', help='Delete object(s) from <container>' ) <NEW_LINE> parser.add_argument( 'objects', metavar='<object>', nargs='+', help='Object(s) to delete' ) <NEW_LINE> parser.add_argument( '--application-key', metavar='<application_key>', help='application key' ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.log.debug('take_action(%s)', parsed_args) <NEW_LINE> application_key = parsed_args.application_key <NEW_LINE> container = parsed_args.container <NEW_LINE> for obj in parsed_args.objects: <NEW_LINE> <INDENT> self.app.client_manager.storage.object_delete( self.app.client_manager.get_account(), container, obj, application_key=application_key )
Delete object from container
6259907a3346ee7daa33835e
class Mapa(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, image, x, y, st_position, st_line, mapnum): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.image = pygame.image.load(image) <NEW_LINE> self.start = pygame.image.load('Linea.png') <NEW_LINE> self.halfline = pygame.image.load('LineaMitad.png') <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.P1start_position = st_position <NEW_LINE> self.P2start_position = st_position[0]+50,st_position[1] <NEW_LINE> self.startline = st_line <NEW_LINE> self.half = 670-st_line[0], st_line[1] <NEW_LINE> self.mapnum = mapnum
En esta clase se definen las propiedades y algunas funciones relacionadas con las pistas del juego
6259907a5fdd1c0f98e5f979
class SwitchingProfileTypeIdEntry(object): <NEW_LINE> <INDENT> swagger_types = { 'value': 'str', 'key': 'str' } <NEW_LINE> attribute_map = { 'value': 'value', 'key': 'key' } <NEW_LINE> def __init__(self, value=None, key=None): <NEW_LINE> <INDENT> self._value = None <NEW_LINE> self._key = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.value = value <NEW_LINE> if key is not None: <NEW_LINE> <INDENT> self.key = key <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `value`, must not be `None`") <NEW_LINE> <DEDENT> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def key(self): <NEW_LINE> <INDENT> return self._key <NEW_LINE> <DEDENT> @key.setter <NEW_LINE> def key(self, key): <NEW_LINE> <INDENT> allowed_values = ["QosSwitchingProfile", "PortMirroringSwitchingProfile", "IpDiscoverySwitchingProfile", "SpoofGuardSwitchingProfile", "SwitchSecuritySwitchingProfile", "MacManagementSwitchingProfile"] <NEW_LINE> if key not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `key` ({0}), must be one of {1}" .format(key, allowed_values) ) <NEW_LINE> <DEDENT> self._key = key <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(SwitchingProfileTypeIdEntry, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SwitchingProfileTypeIdEntry): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259907a5fcc89381b266e58
class TypeOMA(BaseInstrumentType): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TypeOMA, self).__init__() <NEW_LINE> self._append_ins_type(InstrumentType.OMA) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self._raise_not_implemented() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._raise_not_implemented() <NEW_LINE> <DEDENT> def get_trace_items(self, trace): <NEW_LINE> <INDENT> self._raise_not_implemented() <NEW_LINE> <DEDENT> def get_trace_values(self, trace): <NEW_LINE> <INDENT> self._raise_not_implemented() <NEW_LINE> <DEDENT> def get_trace_units(self, trace): <NEW_LINE> <INDENT> self._raise_not_implemented() <NEW_LINE> <DEDENT> def get_formatted_data(self, trace): <NEW_LINE> <INDENT> self._raise_not_implemented()
Optical Modulation Analyser.
6259907a7cff6e4e811b743a
@registry.register_problem <NEW_LINE> class TranslateEndeWmtBpe32k(translate.TranslateProblem): <NEW_LINE> <INDENT> @property <NEW_LINE> def vocab_type(self): <NEW_LINE> <INDENT> return text_problems.VocabType.TOKEN <NEW_LINE> <DEDENT> @property <NEW_LINE> def oov_token(self): <NEW_LINE> <INDENT> return "UNK" <NEW_LINE> <DEDENT> def generate_samples(self, data_dir, tmp_dir, dataset_split): <NEW_LINE> <INDENT> train = dataset_split == problem.DatasetSplit.TRAIN <NEW_LINE> dataset_path = ("train.tok.clean.bpe.32000" if train else "newstest2013.tok.bpe.32000") <NEW_LINE> train_path = _get_wmt_ende_bpe_dataset(tmp_dir, dataset_path) <NEW_LINE> vocab_path = os.path.join(data_dir, self.vocab_filename) <NEW_LINE> if not tf.gfile.Exists(vocab_path): <NEW_LINE> <INDENT> bpe_vocab = os.path.join(tmp_dir, "vocab.bpe.32000") <NEW_LINE> with tf.gfile.Open(bpe_vocab) as f: <NEW_LINE> <INDENT> vocab_list = f.read().split("\n") <NEW_LINE> <DEDENT> vocab_list.append(self.oov_token) <NEW_LINE> text_encoder.TokenTextEncoder( None, vocab_list=vocab_list).store_to_file(vocab_path) <NEW_LINE> <DEDENT> return text_problems.text2text_txt_iterator(train_path + ".en", train_path + ".de")
Problem spec for WMT En-De translation, BPE version.
6259907aadb09d7d5dc0bf64
class Settings(object): <NEW_LINE> <INDENT> def __init__(self, sections): <NEW_LINE> <INDENT> self._sections = set(sections) <NEW_LINE> for section in self._sections: <NEW_LINE> <INDENT> setattr(self, section, Setting()) <NEW_LINE> <DEDENT> <DEDENT> def load_config(self, configpath, pkg=False): <NEW_LINE> <INDENT> if not pkg and not os.path.exists(configpath): <NEW_LINE> <INDENT> LOG.error("Configuration file not found (%s)" % configpath) <NEW_LINE> from errno import ENOENT <NEW_LINE> raise OSError(ENOENT) <NEW_LINE> <DEDENT> config = SafeConfigParser(allow_no_value=True) <NEW_LINE> if pkg: <NEW_LINE> <INDENT> with pkgr.resource_stream(__name__, configpath) as conf: <NEW_LINE> <INDENT> config.readfp(conf) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> config.read(configpath) <NEW_LINE> <DEDENT> LOG.debug(config) <NEW_LINE> for section in config.sections(): <NEW_LINE> <INDENT> if hasattr(self, section): <NEW_LINE> <INDENT> tmp = format_dict(dict(config.items(section))) <NEW_LINE> getattr(self, section).config.update(tmp) <NEW_LINE> LOG.debug("%s config updated" % section) <NEW_LINE> LOG.debug("%s.%s : %s" % (self.__class__.__name__, section, getattr(self, section))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.warning("Unknow config section %s" % section) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def write_config(self, filename): <NEW_LINE> <INDENT> LOG.info("Writing .ini file (%s)" % filename) <NEW_LINE> config = SafeConfigParser(allow_no_value=True) <NEW_LINE> iniout = open(filename, mode="w") <NEW_LINE> for section in self._sections: <NEW_LINE> <INDENT> config.add_section(section) <NEW_LINE> if hasattr(self, section): <NEW_LINE> <INDENT> for opt in getattr(self, section).config: <NEW_LINE> <INDENT> config.set(section, str(opt), str(getattr(self, section).config.get(opt))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> config.write(iniout) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Settings object>\n sections: %s" % self._sections
Group setting objects
6259907a60cbc95b06365a6b
class SpeedWay(AbstractRoad): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> self.car.run() <NEW_LINE> print("高速公路上行驶")
高速公路
6259907afff4ab517ebcf213
class ApiMalformedRequestException(ApiException): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> ApiException.__init__(self, 400, message)
Exception thrown by a REST API when an API request is missing required parameters.
6259907aec188e330fdfa2a3
class BaseTinyMCEMemoWidget(BaseDashboardPluginWidget): <NEW_LINE> <INDENT> def render(self, request=None): <NEW_LINE> <INDENT> context = {'plugin': self.plugin} <NEW_LINE> return render_to_string('tinymce/render.html', context)
Base TinyMCE memo plugin widget.
6259907a55399d3f05627f0f
class mStack(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__data = [] <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> del self.__data <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> del self.__data <NEW_LINE> self.__data = [] <NEW_LINE> <DEDENT> def isEmpty(self): <NEW_LINE> <INDENT> if len(self.__data) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def length(self): <NEW_LINE> <INDENT> return len(self.__data) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> if len(self.__data) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__data[-1] <NEW_LINE> <DEDENT> def push(self, value): <NEW_LINE> <INDENT> if value == None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__data.append(value) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if len(self.__data) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.__data.pop()
a class for simple stack
6259907a2c8b7c6e89bd51e6
class PatronPhotosDetailView(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> queryset = PatronPhotos.objects.all() <NEW_LINE> serializer_class = PatronPhotosSerializer <NEW_LINE> parser_class = (ImageUploadParser,) <NEW_LINE> permission_classes = (permissions.IsAdminUser,) <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a_patronphoto = self.queryset.get(pk=kwargs["pk"]) <NEW_LINE> return Response(PatronPhotosShowSerializer(a_patronphoto).data) <NEW_LINE> <DEDENT> except PatronPhotos.DoesNotExist: <NEW_LINE> <INDENT> return Response( data={ "message": "Patron Photo with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) <NEW_LINE> <DEDENT> <DEDENT> @validate_request_data_patronphotos <NEW_LINE> def put(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a_patronphoto = self.queryset.get(pk=kwargs["pk"]) <NEW_LINE> serializer = PatronPhotosSerializer() <NEW_LINE> updated_patronphoto = serializer.update(a_patronphoto, request.data) <NEW_LINE> return Response(PatronPhotosSerializer(updated_patronphoto).data) <NEW_LINE> <DEDENT> except PatronPhotos.DoesNotExist: <NEW_LINE> <INDENT> return Response( data={ "message": "No photo with that id: {} exists:.".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND ) <NEW_LINE> <DEDENT> <DEDENT> def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a_patronphoto = self.queryset.get(pk=kwargs["pk"]) <NEW_LINE> a_personphoto.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT) <NEW_LINE> <DEDENT> except PatronPhotos.DoesNotExist: <NEW_LINE> <INDENT> return Response( data={ "message": "Patron photo with id: {} does not exist".format(kwargs["pk"]) }, status=status.HTTP_404_NOT_FOUND )
GET patronphoto/:id/ PUT patronphoto/:id/ DELETE patronphoto/:id/
6259907a76e4537e8c3f0f7b