code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class EmbeddingsLoader(): <NEW_LINE> <INDENT> def __init__(self,filename): <NEW_LINE> <INDENT> f = open(filename,'r') <NEW_LINE> self.word_to_id = dict() <NEW_LINE> self.embeddings = [] <NEW_LINE> self.emb_dim = -1 <NEW_LINE> for i,line in enumerate(f): <NEW_LINE> <INDENT> line_s = line.split() <NEW_LINE> if len(line_s) < 3: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> word = line_s[0] <NEW_LINE> while line_s[1].isalpha(): <NEW_LINE> <INDENT> word += " "+line_s[1] <NEW_LINE> del line_s[1] <NEW_LINE> <DEDENT> self.word_to_id[word] = i <NEW_LINE> self.embeddings.append([float(n) for n in line_s[1:]]) <NEW_LINE> <DEDENT> f.close() <NEW_LINE> <DEDENT> def word_to_index(self,word): <NEW_LINE> <INDENT> if word.lower() in self.word_to_id: <NEW_LINE> <INDENT> return self.word_to_id[word.lower()] <NEW_LINE> <DEDENT> elif 'UNK' in self.word_to_id or '</s>' in self.word_to_id: <NEW_LINE> <INDENT> return UNK_EMBEDDING_INDEX <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.zeros(len(self.embeddings[0])) <NEW_LINE> <DEDENT> <DEDENT> def get_weights(self): <NEW_LINE> <INDENT> return self.embeddings <NEW_LINE> <DEDENT> def get_dimensions(self): <NEW_LINE> <INDENT> return len(self.embeddings),len(self.embeddings[0])
Loads embeddings that follow the format: WORD1 E11 E12 .... E1N WORD2 E21 E22 .... E2N
6259904a07d97122c421808a
class IofloMaster(object): <NEW_LINE> <INDENT> def __init__(self, opts): <NEW_LINE> <INDENT> self.opts = opts <NEW_LINE> self.preloads = explode_opts(self.opts) <NEW_LINE> <DEDENT> def _make_workers(self): <NEW_LINE> <INDENT> for ind in range(int(self.opts['worker_threads'])): <NEW_LINE> <INDENT> proc = multiprocessing.Process( target=self._worker, kwargs={'yid': ind + 1} ) <NEW_LINE> proc.start() <NEW_LINE> <DEDENT> <DEDENT> def _worker(self, yid): <NEW_LINE> <INDENT> behaviors = ['salt.transport.road.raet', 'salt.daemons.flo'] <NEW_LINE> self.preloads.append('.salt.yid', yid) <NEW_LINE> ioflo.app.run.start( name='worker{0}'.format(yid), period=float(self.opts['ioflo_period']), stamp=0.0, real=self.opts['ioflo_realtime'], filepath=self.opts['worker_floscript'], behaviors=behaviors, username="", password="", mode=None, houses=None, metas=None, preloads=self.preloads, verbose=int(self.opts['ioflo_verbose']), ) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> behaviors = ['salt.transport.road.raet', 'salt.daemons.flo'] <NEW_LINE> ioflo.app.run.start( name='master', period=float(self.opts['ioflo_period']), stamp=0.0, real=self.opts['ioflo_realtime'], filepath=self.opts['master_floscript'], behaviors=behaviors, username="", password="", mode=None, houses=None, metas=None, preloads=self.preloads, verbose=int(self.opts['ioflo_verbose']), )
IofloMaster Class
6259904ab830903b9686ee6e
class MacHiddenFrame(BufferFrame): <NEW_LINE> <INDENT> preferences_tab = None <NEW_LINE> def initPositionAndSize(self): <NEW_LINE> <INDENT> pos = (90000, 90000) <NEW_LINE> size = (int(self.classprefs.width), int(self.classprefs.height)) <NEW_LINE> return pos, size <NEW_LINE> <DEDENT> def initRegisterWindow(self): <NEW_LINE> <INDENT> WindowList.setHiddenFrame(self) <NEW_LINE> <DEDENT> def initLoad(self, buffer, urls): <NEW_LINE> <INDENT> wx.CallAfter(self.titleBuffer) <NEW_LINE> <DEDENT> def loadSidebars(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isOSXMinimalMenuFrame(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def titleBuffer(self): <NEW_LINE> <INDENT> BufferFrame.open(self, "about:osx_menu") <NEW_LINE> wx.CallAfter(self.Show, False) <NEW_LINE> <DEDENT> def open(self, *args, **kwargs): <NEW_LINE> <INDENT> frame = BufferFrame(['about:blank']) <NEW_LINE> wx.CallAfter(frame.open, *args, **kwargs) <NEW_LINE> <DEDENT> def setBuffer(self, buffer): <NEW_LINE> <INDENT> frame = BufferFrame(['about:blank']) <NEW_LINE> wx.CallAfter(frame.setBuffer, buffer)
Special frame used to keep the OS X application open even if there are no visible frames on the screen. On other platforms, the application quits when the last frame is deleted, but on OS X the application typically stays active with the ability to load files or handle files dropped onto the dock.
6259904a16aa5153ce4018d5
class BEGIN(BaseFrame): <NEW_LINE> <INDENT> required_headers=("transaction",) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> BaseFrame.__init__(self, **kwargs)
BEGIN is used to start a transaction. Transactions in this case apply to sending and acknowledging - any messages sent or acknowledged during a transaction will be processed atomically based on the transaction. headers: REQUIRED: transaction OPTIONAL: none
6259904aec188e330fdf9c85
class CloningDetail(LoginRequiredMixin, DetailView): <NEW_LINE> <INDENT> model = Cloning <NEW_LINE> template_name = 'cloning_detail.html' <NEW_LINE> template_object_name = 'cloning'
This view is for viewing Cloning.
6259904a15baa7234946337a
class NumpyDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, fname, key=None, order_file=None, revert=False, **kwargs): <NEW_LINE> <INDENT> self.path = Path(fname) <NEW_LINE> if not self.path.exists(): <NEW_LINE> <INDENT> raise RuntimeError('{} does not exist.'.format(self.path)) <NEW_LINE> <DEDENT> if self.path.suffix == '.npy': <NEW_LINE> <INDENT> self.data = np.load(self.path) <NEW_LINE> <DEDENT> elif self.path.suffix == '.npz': <NEW_LINE> <INDENT> assert key, "A key should be provided for .npz files." <NEW_LINE> self.data = np.load(self.path)[key] <NEW_LINE> <DEDENT> if order_file: <NEW_LINE> <INDENT> with open(order_file) as orf: <NEW_LINE> <INDENT> self.order = [int(x) for x in orf.read().strip().split('\n')] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.order = list(range(self.data.shape[0])) <NEW_LINE> <DEDENT> if revert: <NEW_LINE> <INDENT> self.order = self.order[::-1] <NEW_LINE> <DEDENT> self.size = len(self.order) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def to_torch(batch, **kwargs): <NEW_LINE> <INDENT> x = torch.from_numpy(np.array(batch, dtype='float32')) <NEW_LINE> return x.view(*x.size()[:2], -1).permute(2, 0, 1) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> return self.data[self.order[idx]] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.size <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = "{} '{}' ({} samples)\n".format( self.__class__.__name__, self.path.name, self.__len__()) <NEW_LINE> return s
A PyTorch dataset for Numpy .npy/npz serialized tensor files. The serialized tensor's first dimension should be the batch dimension. Arguments: fname (str or Path): A string or ``pathlib.Path`` object for the relevant numpy file. key (str, optional): If `fname` is `.npz` file, its relevant `key` will be fetched from the serialized object. order_file (str, None): If given, will be used to map sample indices to tensors using this list. Useful for tiled or repeated experiments. revert (bool, optional): If `True`, the data order will be reverted for adversarial/incongruent experiments during test-time.
6259904a73bcbd0ca4bcb671
class SizeLink(object): <NEW_LINE> <INDENT> WIDTH = WIDTH <NEW_LINE> HEIGHT = HEIGHT <NEW_LINE> def __init__(self, follower, follower_dim, followee, followee_dim=None, ratio=1.0): <NEW_LINE> <INDENT> if follower_dim not in DIMENSIONS: <NEW_LINE> <INDENT> raise ValueError("invalid follower dimension - %s" % (follower_dim,)) <NEW_LINE> <DEDENT> if followee_dim is None: <NEW_LINE> <INDENT> followee_dim = follower_dim <NEW_LINE> <DEDENT> elif followee_dim not in DIMENSIONS: <NEW_LINE> <INDENT> raise ValueError("invalid followee dimension - %s" % (followee_dim,)) <NEW_LINE> <DEDENT> link_attr = "__%s_sizelink" % follower_dim <NEW_LINE> if hasattr(follower, link_attr): <NEW_LINE> <INDENT> raise Exception("widgets can only have one active %s size link" % (follower_dim,)) <NEW_LINE> <DEDENT> setattr(follower, link_attr, self) <NEW_LINE> self.follower = follower <NEW_LINE> self.follower_dim = follower_dim <NEW_LINE> self.followee = followee <NEW_LINE> self.followee_dim = followee_dim <NEW_LINE> self.ratio = ratio <NEW_LINE> followee.bind(**{followee_dim: self.update}) <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ("%s(%s<%08x>.%s -> %s x %s<%08x>.%s)" % (type(self).__name__, type(self.follower).__name__, id(self.follower), self.follower_dim, self.ratio, type(self.followee).__name__, id(self.followee), self.followee_dim)) <NEW_LINE> <DEDENT> def update(self, *args): <NEW_LINE> <INDENT> reference = getattr(self.followee, self.followee_dim) <NEW_LINE> setattr(self.follower, self.follower_dim, self.ratio * reference) <NEW_LINE> assert getattr(self.follower, self.follower_dim) == Approx(self.ratio * reference) <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> link_attr = "__%s_sizelink" % self.follower_dim <NEW_LINE> delattr(self.follower, link_attr) <NEW_LINE> self.followee.unbind(size=self.update) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get(widget, dim): <NEW_LINE> <INDENT> link_attr = "__%s_sizelink" % dim <NEW_LINE> return getattr(widget, link_attr, None)
Helper class for setting the width or height (follower_dim) of a widget (follower) relative to another widget's (followee) width or height (followee_dim). Do not use links on widgets whose parents are layouts that automatically try to resize them, as this will lead to unexpected results due to conflicts between the link and the layout.
6259904ae64d504609df9dc4
class TestInterface(unittest.TestCase): <NEW_LINE> <INDENT> pass
Tests all publicly available classes of slap Classes are checked *if* they implement interface and if the implementation is correct.
6259904ad6c5a102081e3505
class Soldado: <NEW_LINE> <INDENT> def __init__(self, posX, posY,direction, hp, vel, alc, damage, band): <NEW_LINE> <INDENT> self.posX=posX <NEW_LINE> self.posY=posY <NEW_LINE> self.direction=direction <NEW_LINE> self.hp=hp <NEW_LINE> self.vel=vel <NEW_LINE> self.alc=alc <NEW_LINE> self.damage=damage <NEW_LINE> self.band=band <NEW_LINE> <DEDENT> def printMyself(self): <NEW_LINE> <INDENT> return ', '.join("%s: %s" % item for item in vars(self).items()) <NEW_LINE> <DEDENT> def moveMyself(self): <NEW_LINE> <INDENT> if(direction==1): <NEW_LINE> <INDENT> self.posY+=1 <NEW_LINE> <DEDENT> elif(direction==2): <NEW_LINE> <INDENT> self.posX+=1 <NEW_LINE> <DEDENT> elif(direction==3): <NEW_LINE> <INDENT> self.posY-=1 <NEW_LINE> <DEDENT> elif(direction==4): <NEW_LINE> <INDENT> self.posX-=1
posX: posición en el eje x posY: posición en el eje y direction: dirección en la que se moverá la unidad 1=arriba, 2=derecha, 3=abajo, 4=izquierda hp: puntos de vida vel: velocidad alc: alcance damage: daño band: bando (1,2)
6259904ad53ae8145f919849
class OrderError(FlumineException): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(OrderError, self).__init__(message)
Exception raised if incorrect order/order_type requested.
6259904ab57a9660fecd2e66
class WorkbookResource(TrackedResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'identity': {'key': 'identity', 'type': 'WorkbookResourceIdentity'}, 'kind': {'key': 'kind', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, identity: Optional["WorkbookResourceIdentity"] = None, kind: Optional[Union[str, "Kind"]] = None, etag: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(WorkbookResource, self).__init__(tags=tags, location=location, **kwargs) <NEW_LINE> self.identity = identity <NEW_LINE> self.kind = kind <NEW_LINE> self.etag = etag
An azure resource object. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :ivar tags: A set of tags. Resource tags. :vartype tags: dict[str, str] :ivar location: Required. The geo-location where the resource lives. :vartype location: str :ivar identity: Identity used for BYOS. :vartype identity: ~azure.mgmt.applicationinsights.v2021_08_01.models.WorkbookResourceIdentity :ivar kind: The kind of workbook. Choices are user and shared. Possible values include: "user", "shared". :vartype kind: str or ~azure.mgmt.applicationinsights.v2021_08_01.models.Kind :ivar etag: Resource etag. :vartype etag: str
6259904a21a7993f00c67352
class TestPaginatedDatasets(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 testPaginatedDatasets(self): <NEW_LINE> <INDENT> pass
PaginatedDatasets unit test stubs
6259904aa79ad1619776b469
class A0(Base): <NEW_LINE> <INDENT> _attrinfos = { 'x0': { 'writable': False }, 'z0': { 'writable': False }, 'k0': { 'writable': True }, 'creation_time': { 'writable': False }, '_prop0': {}, '_getter_called': {}, '_setter_called': {}, '_a0': { 'writable': False }, 'cpp_int': { 'cpp_setter': 'set_cpp_int' }, 'cpp_unlinked_int': { 'cpp_setter': 'set_cpp_unlinked_int' }, } <NEW_LINE> _cpp_obj_name = "_a0" <NEW_LINE> def __init__(self, x0: int, arg0, y0: float = 0., kwarg0='string'): <NEW_LINE> <INDENT> Base.__init__(self) <NEW_LINE> self.set_x0(x0) <NEW_LINE> self.y0 = y0 <NEW_LINE> self.creation_time = self._get_now() <NEW_LINE> self._prop0 = None <NEW_LINE> self._getter_called = False <NEW_LINE> self._setter_called = False <NEW_LINE> self._a0 = _A0() <NEW_LINE> self.arg0 = arg0 <NEW_LINE> self.kwarg0 = kwarg0 <NEW_LINE> <DEDENT> def set_x0(self, x0): <NEW_LINE> <INDENT> self.x0 = x0 <NEW_LINE> <DEDENT> def force_set_x0(self, x0): <NEW_LINE> <INDENT> self._set('x0', x0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def prop0(self): <NEW_LINE> <INDENT> if self._prop0 is None: <NEW_LINE> <INDENT> self._prop0 = 22 <NEW_LINE> <DEDENT> self._getter_called = True <NEW_LINE> return self._prop0 <NEW_LINE> <DEDENT> @prop0.setter <NEW_LINE> def prop0(self, val): <NEW_LINE> <INDENT> self._setter_called = True <NEW_LINE> self._prop0 = val <NEW_LINE> <DEDENT> @property <NEW_LINE> def readonly_prop(self): <NEW_LINE> <INDENT> return 44
This is a class that inherit directly from Base Parameters ---------- x0 : `int` This is doc of x0 from A0 y0 : `float` This is doc of y0 from A0 z0 : `float` This is doc of z0 from A0. z0 is not writable in A0 but will be writable in A1 k0 : `float` This is doc of k0 from A0. k0 is writable in A0 but will not be writable in A1 Attributes ---------- creation_time : `float` This is doc of creation_time, an attribute which is readonly update_time : `float` This is doc of update_time, an attribute which is writable prop0 : `int` This is doc of a native property cpp_int : `int` This int exists in Python and in C++. When set in Python it must be changed in C++ as well
6259904b10dbd63aa1c71fc5
@run_for_test_types(TEST_TYPE, 'matlab') <NEW_LINE> class TestRegressionMatlab(TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.results_dir = os.path.join(os.path.dirname(__file__), 'fitbenchmarking_results') <NEW_LINE> <DEDENT> def test_results_consistent_all(self): <NEW_LINE> <INDENT> problem_sub_directory = "all_parsers_set" <NEW_LINE> run_benchmark(self.results_dir, problem_sub_directory) <NEW_LINE> diff, msg = compare_results(problem_sub_directory, "matlab.txt") <NEW_LINE> self.assertListEqual([], diff, msg)
Regression tests for the Fitbenchmarking software with matlab fitting software
6259904bb830903b9686ee6f
class TestListDetail(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 testListDetail(self): <NEW_LINE> <INDENT> pass
ListDetail unit test stubs
6259904bbaa26c4b54d50694
class Loader(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> client = MongoClient(os.environ.get('DB_PORT_27017_TCP_ADDR', 'localhost'), 27017) <NEW_LINE> self.db = client.target_database <NEW_LINE> <DEDENT> def load(self, data): <NEW_LINE> <INDENT> table_name = type(data).__name__.lower() <NEW_LINE> document = dict(data._asdict()) <NEW_LINE> document_updatable_part = {field: document[field] for field in UPDATABLE_FIELDS} <NEW_LINE> document_remain_part = {field: document[field] for field in REQUIRED_FIELDS if field not in UPDATABLE_FIELDS + (ID_FIELD,) + (TABLE_RESOLVER_FIELD,)} <NEW_LINE> self.db[table_name].update_one( {"_id": document.get(ID_FIELD)}, {"$set": document_updatable_part, "$setOnInsert": document_remain_part}, upsert=True ) <NEW_LINE> <DEDENT> def save_error(self, e): <NEW_LINE> <INDENT> err = e.__dict__ <NEW_LINE> err['date'] = str(datetime.datetime.now()) <NEW_LINE> err['type'] = str(type(e)) <NEW_LINE> self.db.errors.insert_one(err)
Load valid data or errors to database When instantiating Loader connection to db is established.
6259904b29b78933be26aab7
class EmbeddingDot: <NEW_LINE> <INDENT> def __init__(self, W): <NEW_LINE> <INDENT> self.embed = Embedding(W) <NEW_LINE> self.params = self.embed.params <NEW_LINE> self.grads = self.embed.grads <NEW_LINE> self.cache = None <NEW_LINE> <DEDENT> def forward(self, h, idx): <NEW_LINE> <INDENT> target_W = self.embed.forward(idx) <NEW_LINE> out = np.sum(target_W * h, axis=1) <NEW_LINE> self.cache = (h, target_W) <NEW_LINE> return out <NEW_LINE> <DEDENT> def backward(self, dout): <NEW_LINE> <INDENT> h, target_W = self.cache <NEW_LINE> dout = np.reshape(dout, newshape=(np.shape(dout)[0], 1)) <NEW_LINE> dtarget_W = dout * h <NEW_LINE> self.embed.backward(dtarget_W) <NEW_LINE> dh = dout * target_W <NEW_LINE> return dh
EmbeddingDot class is one of key parts of NegativeSampling algorithm Without performing matrix product, EmbeddingDot class just selects the target row from Embedding matrix and perform dot product so that it has better performance than naive wrod2vec algorithm.
6259904b4e696a045264e815
class LibjpegTurbo(VProject): <NEW_LINE> <INDENT> NAME = 'libjpeg_turbo' <NEW_LINE> GROUP = 'c_projects' <NEW_LINE> DOMAIN = ProjectDomains.FILE_FORMAT <NEW_LINE> SOURCE = [ PaperConfigSpecificGit( project_name="libjpeg_turbo", remote="https://github.com/libjpeg-turbo/libjpeg-turbo", local="libjpeg-turbo", refspec="origin/HEAD", limit=None, shallow=False ) ] <NEW_LINE> CONTAINER = get_base_image(ImageBase.DEBIAN_10 ).run('apt', 'install', '-y', 'cmake') <NEW_LINE> @staticmethod <NEW_LINE> def binaries_for_revision( revision: ShortCommitHash ) -> tp.List[ProjectBinaryWrapper]: <NEW_LINE> <INDENT> binary_map = RevisionBinaryMap( get_local_project_git_path(LibjpegTurbo.NAME) ) <NEW_LINE> binary_map.specify_binary("libjpeg.so", BinaryType.SHARED_LIBRARY) <NEW_LINE> return binary_map[revision] <NEW_LINE> <DEDENT> def run_tests(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def compile(self) -> None: <NEW_LINE> <INDENT> libjpeg_version_source = local.path(self.source_of_primary) <NEW_LINE> c_compiler = bb.compiler.cc(self) <NEW_LINE> with local.cwd(libjpeg_version_source): <NEW_LINE> <INDENT> with local.env(CC=str(c_compiler)): <NEW_LINE> <INDENT> bb.watch(cmake)("-G", "Unix Makefiles", ".") <NEW_LINE> <DEDENT> bb.watch(make)("-j", get_number_of_jobs(bb_cfg())) <NEW_LINE> verify_binaries(self) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_cve_product_info(cls) -> tp.List[tp.Tuple[str, str]]: <NEW_LINE> <INDENT> return [("JpegCodec", "Libjpeg")]
libjpeg-turbo is a JPEG image codec.
6259904b3eb6a72ae038ba45
@ClassFactory.register(ClassType.NETWORK) <NEW_LINE> class Squeeze(Module, OperatorSerializable): <NEW_LINE> <INDENT> def __init__(self, dim=0): <NEW_LINE> <INDENT> self.dim = dim <NEW_LINE> super(Squeeze, self).__init__() <NEW_LINE> <DEDENT> def __call__(self, inputs, **kwargs): <NEW_LINE> <INDENT> return tf.squeeze(inputs, [self.dim])
Class of Squeeze.
6259904b3cc13d1c6d466b22
class UserServiceServicer(object): <NEW_LINE> <INDENT> def Get(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def List(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Create(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Update(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Delete(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def GrantPermission(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def RevokePermission(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
A set of methods for managing PostgreSQL User resources.
6259904b6fece00bbacccda2
class NetworkAndComputeLister(NetDetectionMixin, command.Lister, metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> pass
Network and Compute Lister Lister class for commands that support implementation via the network or compute endpoint. Such commands have different implementations for take_action() and may even have different arguments.
6259904b73bcbd0ca4bcb672
class Evaluation(Model): <NEW_LINE> <INDENT> def __init__(self, type_id: int=None, type_name: str=None, value: int=None): <NEW_LINE> <INDENT> self.swagger_types = { 'type_id': int, 'type_name': str, 'value': int } <NEW_LINE> self.attribute_map = { 'type_id': 'type_id', 'type_name': 'type_name', 'value': 'value' } <NEW_LINE> self._type_id = type_id <NEW_LINE> self._type_name = type_name <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'Evaluation': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_id(self) -> int: <NEW_LINE> <INDENT> return self._type_id <NEW_LINE> <DEDENT> @type_id.setter <NEW_LINE> def type_id(self, type_id: int): <NEW_LINE> <INDENT> self._type_id = type_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_name(self) -> str: <NEW_LINE> <INDENT> return self._type_name <NEW_LINE> <DEDENT> @type_name.setter <NEW_LINE> def type_name(self, type_name: str): <NEW_LINE> <INDENT> self._type_name = type_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self) -> int: <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value: int): <NEW_LINE> <INDENT> self._value = value
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904bcb5e8a47e493cb7c
class BinaryOpNode(OpNode): <NEW_LINE> <INDENT> def __init__(self, name: str, out_rel: rel.Relation, left_parent: OpNode, right_parent: OpNode): <NEW_LINE> <INDENT> super(BinaryOpNode, self).__init__(name, out_rel) <NEW_LINE> self.left_parent = left_parent <NEW_LINE> self.right_parent = right_parent <NEW_LINE> if self.left_parent: <NEW_LINE> <INDENT> self.parents.add(left_parent) <NEW_LINE> <DEDENT> if self.right_parent: <NEW_LINE> <INDENT> self.parents.add(right_parent) <NEW_LINE> <DEDENT> <DEDENT> def get_left_in_rel(self): <NEW_LINE> <INDENT> return self.left_parent.out_rel <NEW_LINE> <DEDENT> def get_right_in_rel(self): <NEW_LINE> <INDENT> return self.right_parent.out_rel <NEW_LINE> <DEDENT> def requires_mpc(self): <NEW_LINE> <INDENT> left_stored_with = self.get_left_in_rel().stored_with <NEW_LINE> right_stored_with = self.get_right_in_rel().stored_with <NEW_LINE> combined = left_stored_with.union(right_stored_with) <NEW_LINE> return (len(combined) > 1) and not self.is_local <NEW_LINE> <DEDENT> def make_orphan(self): <NEW_LINE> <INDENT> super(BinaryOpNode, self).make_orphan() <NEW_LINE> self.left_parent = None <NEW_LINE> self.right_parent = None <NEW_LINE> <DEDENT> def replace_parent(self, old_parent: Node, new_parent: OpNode): <NEW_LINE> <INDENT> super(BinaryOpNode, self).replace_parent(old_parent, new_parent) <NEW_LINE> if self.left_parent == old_parent: <NEW_LINE> <INDENT> self.left_parent = new_parent <NEW_LINE> <DEDENT> elif self.right_parent == old_parent: <NEW_LINE> <INDENT> self.right_parent = new_parent <NEW_LINE> <DEDENT> <DEDENT> def remove_parent(self, parent: OpNode): <NEW_LINE> <INDENT> super(BinaryOpNode, self).remove_parent(parent) <NEW_LINE> if self.left_parent == parent: <NEW_LINE> <INDENT> self.left_parent = None <NEW_LINE> <DEDENT> elif self.right_parent == parent: <NEW_LINE> <INDENT> self.right_parent = None
An OpNode with exactly two parents (e.g. - Join).
6259904bd6c5a102081e3507
class CompilationEnvironment: <NEW_LINE> <INDENT> context_name = None <NEW_LINE> columns = None <NEW_LINE> functions = None <NEW_LINE> def get_column(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.columns[name]() <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise CompilationError("Invalid column name '{}' in {} context.".format( name, self.context_name)) <NEW_LINE> <DEDENT> <DEDENT> def get_function(self, name, operands): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key = tuple([name] + [operand.dtype for operand in operands]) <NEW_LINE> return self.functions[key](operands) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.functions[name](operands) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> signature = '{}({})'.format(name, ', '.join(operand.dtype.__name__ for operand in operands)) <NEW_LINE> raise CompilationError("Invalid function '{}' in {} context".format( signature, self.context_name))
Base class for all compilation contexts. A compilation context provides column accessors specific to the particular row objects that we will access.
6259904bac7a0e7691f738c6
class TestExtensionsV1beta1ScaleStatus(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 testExtensionsV1beta1ScaleStatus(self): <NEW_LINE> <INDENT> model = kubernetes.client.models.extensions_v1beta1_scale_status.ExtensionsV1beta1ScaleStatus()
ExtensionsV1beta1ScaleStatus unit test stubs
6259904b287bf620b6272fd4
class client_pool(list): <NEW_LINE> <INDENT> def __init__(self, *, name='default_pool', priority=0, weight=1): <NEW_LINE> <INDENT> self.pool_name = name <NEW_LINE> self.priority = priority <NEW_LINE> self.current_number = 0 <NEW_LINE> self.past_clients = [] <NEW_LINE> if weight < 0: <NEW_LINE> <INDENT> raise ValueError('weight must be greater than 0') <NEW_LINE> <DEDENT> if isinstance(weight, int) != True: <NEW_LINE> <INDENT> raise TypeError('weight must be integer') <NEW_LINE> <DEDENT> self.weight = weight <NEW_LINE> client_pools.append(self) <NEW_LINE> <DEDENT> def get_new_service_number(self): <NEW_LINE> <INDENT> self.current_number += 1 <NEW_LINE> serial = "%04d" % self.current_number <NEW_LINE> return self.pool_name + serial <NEW_LINE> <DEDENT> def current_pool_total_waiting_time(self): <NEW_LINE> <INDENT> time = [x.waiting_time for x in self] <NEW_LINE> return sum(time) <NEW_LINE> <DEDENT> @property <NEW_LINE> def pool_priority(self): <NEW_LINE> <INDENT> return self.priority <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result_str = self.pool_name + ":\n" <NEW_LINE> for c in self: <NEW_LINE> <INDENT> result_str += (str(c) + "\n") <NEW_LINE> <DEDENT> result_str += "clients serviced:%d\n" % len(self.past_clients) <NEW_LINE> result_str += "average waiting time:%fs\n" % self.get_average_waiting_time() <NEW_LINE> result_str += "queue expected waiting time:%fs\n" % counters.get_expected_waiting_time( self) <NEW_LINE> return result_str <NEW_LINE> <DEDENT> def get_average_waiting_time(self): <NEW_LINE> <INDENT> total_waiting_time = [ x.waiting_time for x in self.past_clients] + [x.waiting_time for x in self] <NEW_LINE> return sum(total_waiting_time) / len(total_waiting_time)
一个队列 通过继承增加对象池应有的功能
6259904b07f4c71912bb081f
class BoundingBoxInput(basic.BBoxInput): <NEW_LINE> <INDENT> def __init__(self, identifier, title, crss, abstract='', dimensions=2, metadata=None, min_occurs=1, max_occurs=1, as_reference=False, mode=MODE.NONE): <NEW_LINE> <INDENT> if metadata is None: <NEW_LINE> <INDENT> metadata = [] <NEW_LINE> <DEDENT> basic.BBoxInput.__init__(self, identifier, title=title, abstract=abstract, crss=crss, dimensions=dimensions, mode=mode) <NEW_LINE> self.metadata = metadata <NEW_LINE> self.min_occurs = int(min_occurs) <NEW_LINE> self.max_occurs = int(max_occurs) <NEW_LINE> self.as_reference = as_reference <NEW_LINE> <DEDENT> def describe_xml(self): <NEW_LINE> <INDENT> doc = E.Input( OWS.Identifier(self.identifier), OWS.Title(self.title) ) <NEW_LINE> doc.attrib['minOccurs'] = str(self.min_occurs) <NEW_LINE> doc.attrib['maxOccurs'] = str(self.max_occurs) <NEW_LINE> if self.abstract: <NEW_LINE> <INDENT> doc.append(OWS.Abstract(self.abstract)) <NEW_LINE> <DEDENT> if self.metadata: <NEW_LINE> <INDENT> doc.append(OWS.Metadata(*self.metadata)) <NEW_LINE> <DEDENT> bbox_data_doc = E.BoundingBoxData() <NEW_LINE> doc.append(bbox_data_doc) <NEW_LINE> default_doc = E.Default() <NEW_LINE> default_doc.append(E.CRS(self.crss[0])) <NEW_LINE> supported_doc = E.Supported() <NEW_LINE> for c in self.crss: <NEW_LINE> <INDENT> supported_doc.append(E.CRS(c)) <NEW_LINE> <DEDENT> bbox_data_doc.append(default_doc) <NEW_LINE> bbox_data_doc.append(supported_doc) <NEW_LINE> return doc <NEW_LINE> <DEDENT> def execute_xml(self): <NEW_LINE> <INDENT> doc = WPS.Input( OWS.Identifier(self.identifier), OWS.Title(self.title) ) <NEW_LINE> if self.abstract: <NEW_LINE> <INDENT> doc.append(OWS.Abstract(self.abstract)) <NEW_LINE> <DEDENT> bbox_data_doc = OWS.BoundingBox() <NEW_LINE> bbox_data_doc.attrib['crs'] = self.crs <NEW_LINE> bbox_data_doc.attrib['dimensions'] = str(self.dimensions) <NEW_LINE> bbox_data_doc.append( OWS.LowerCorner('{0[0]} {0[1]}'.format(self.data))) <NEW_LINE> bbox_data_doc.append( OWS.UpperCorner('{0[2]} {0[3]}'.format(self.data))) <NEW_LINE> doc.append(bbox_data_doc) <NEW_LINE> return doc <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return deepcopy(self)
:param identifier: The name of this input. :param data_type: Type of literal input (e.g. `string`, `float`...). :param crss: List of supported coordinate reference system (e.g. ['EPSG:4326'])
6259904bd53ae8145f91984c
class GoToRandomLocation(GoTo): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> GoTo.__init__(self, None) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if self.destination is None: <NEW_LINE> <INDENT> self.destination = Location(self.character.get_random_destination()) <NEW_LINE> <DEDENT> return GoTo.execute(self)
Command that makes a character go to a location chosen at random.
6259904bb57a9660fecd2e68
class Module_Scores(Collection): <NEW_LINE> <INDENT> def __init__(self, monitor): <NEW_LINE> <INDENT> super(Module_Scores, self).__init__(monitor) <NEW_LINE> fixed = self._meta_data['uri'].replace('_', '-') <NEW_LINE> self._meta_data['uri'] = fixed <NEW_LINE> self._meta_data['allowed_lazy_attributes'] = [Module_Score] <NEW_LINE> self._meta_data['attribute_registry'] = {'tm:ltm:monitor:module-score:module-scorestate': Module_Score}
BIG-IP module scores monitor collection.
6259904b0a366e3fb87dddd1
class TestSizeViolation(PkgDirCheckBase): <NEW_LINE> <INDENT> def test_files_under_size_limit(self): <NEW_LINE> <INDENT> pkg = self.mk_pkg() <NEW_LINE> for name, size in (('small', 1024*10), ('limit', 1024*20-1)): <NEW_LINE> <INDENT> with open(pjoin(self.filesdir, name), 'w') as f: <NEW_LINE> <INDENT> f.seek(size) <NEW_LINE> f.write('\0') <NEW_LINE> <DEDENT> <DEDENT> self.assertNoReport(self.mk_check(), [pkg]) <NEW_LINE> <DEDENT> def test_single_file_over_limit(self): <NEW_LINE> <INDENT> pkg = self.mk_pkg() <NEW_LINE> with open(pjoin(self.filesdir, 'over'), 'w') as f: <NEW_LINE> <INDENT> f.seek(1024*20) <NEW_LINE> f.write('\0') <NEW_LINE> <DEDENT> r = self.assertReport(self.mk_check(), [pkg]) <NEW_LINE> assert isinstance(r, pkgdir.SizeViolation) <NEW_LINE> assert r.filename == 'files/over' <NEW_LINE> assert r.size == 1024*20+1 <NEW_LINE> assert 'files/over' in str(r) <NEW_LINE> <DEDENT> def test_multiple_files_over_limit(self): <NEW_LINE> <INDENT> pkg = self.mk_pkg() <NEW_LINE> for name, size in (('small', 1024*10), ('limit', 1024*20-1), ('over', 1024*20), ('massive', 1024*100)): <NEW_LINE> <INDENT> with open(pjoin(self.filesdir, name), 'w') as f: <NEW_LINE> <INDENT> f.seek(size) <NEW_LINE> f.write('\0') <NEW_LINE> <DEDENT> <DEDENT> r = self.assertReports(self.mk_check(), [pkg]) <NEW_LINE> assert len(r) == 2 <NEW_LINE> assert isinstance(r[0], pkgdir.SizeViolation) <NEW_LINE> assert isinstance(r[1], pkgdir.SizeViolation) <NEW_LINE> assert ( tuple(sorted((x.filename, x.size) for x in r)) == (('files/massive', 1024*100+1), ('files/over', 1024*20+1)) )
Check SizeViolation results.
6259904bbaa26c4b54d50696
class Gromacs(CMakePackage): <NEW_LINE> <INDENT> homepage = 'http://www.gromacs.org' <NEW_LINE> url = 'http://ftp.gromacs.org/gromacs/gromacs-5.1.2.tar.gz' <NEW_LINE> version('2016.3', 'e9e3a41bd123b52fbcc6b32d09f8202b') <NEW_LINE> version('5.1.4', 'ba2e34d59b3982603b4935d650c08040') <NEW_LINE> version('5.1.2', '614d0be372f1a6f1f36382b7a6fcab98') <NEW_LINE> variant('mpi', default=True, description='Activate MPI support') <NEW_LINE> variant('shared', default=True, description='Enables the build of shared libraries') <NEW_LINE> variant('debug', default=False, description='Enables debug mode') <NEW_LINE> variant( 'double', default=False, description='Produces a double precision version of the executables') <NEW_LINE> variant('plumed', default=False, description='Enable PLUMED support') <NEW_LINE> variant('cuda', default=False, description='Enable CUDA support') <NEW_LINE> depends_on('mpi', when='+mpi') <NEW_LINE> depends_on('plumed+mpi', when='+plumed+mpi') <NEW_LINE> depends_on('plumed~mpi', when='+plumed~mpi') <NEW_LINE> depends_on('fftw') <NEW_LINE> depends_on('cmake@2.8.8:', type='build') <NEW_LINE> depends_on('cuda', when='+cuda') <NEW_LINE> def patch(self): <NEW_LINE> <INDENT> if '+plumed' in self.spec: <NEW_LINE> <INDENT> self.spec['plumed'].package.apply_patch(self) <NEW_LINE> <DEDENT> <DEDENT> def cmake_args(self): <NEW_LINE> <INDENT> options = [] <NEW_LINE> if '+mpi' in self.spec: <NEW_LINE> <INDENT> options.append('-DGMX_MPI:BOOL=ON') <NEW_LINE> <DEDENT> if '+double' in self.spec: <NEW_LINE> <INDENT> options.append('-DGMX_DOUBLE:BOOL=ON') <NEW_LINE> <DEDENT> if '~shared' in self.spec: <NEW_LINE> <INDENT> options.append('-DBUILD_SHARED_LIBS:BOOL=OFF') <NEW_LINE> <DEDENT> if '+debug' in self.spec: <NEW_LINE> <INDENT> options.append('-DCMAKE_BUILD_TYPE:STRING=Debug') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options.append('-DCMAKE_BUILD_TYPE:STRING=Release') <NEW_LINE> <DEDENT> if '+cuda' in self.spec: <NEW_LINE> <INDENT> options.append('-DGMX_GPU:BOOL=ON') <NEW_LINE> options.append('-DCUDA_TOOLKIT_ROOT_DIR:STRING=' + self.spec['cuda'].prefix) <NEW_LINE> <DEDENT> return options
GROMACS (GROningen MAchine for Chemical Simulations) is a molecular dynamics package primarily designed for simulations of proteins, lipids and nucleic acids. It was originally developed in the Biophysical Chemistry department of University of Groningen, and is now maintained by contributors in universities and research centers across the world. GROMACS is one of the fastest and most popular software packages available and can run on CPUs as well as GPUs. It is free, open source released under the GNU General Public License. Starting from version 4.6, GROMACS is released under the GNU Lesser General Public License.
6259904b8da39b475be045dc
class Tasks(_Tasks): <NEW_LINE> <INDENT> def set_parent(self, task_id, params={}, **options): <NEW_LINE> <INDENT> path = '/tasks/%s/setParent' % (task_id) <NEW_LINE> return self.client.post(path, params, **options)
Tasks resource
6259904b507cdc57c63a618b
class LineEndingWrapper(object): <NEW_LINE> <INDENT> def __init__(self, output): <NEW_LINE> <INDENT> self.__output = output <NEW_LINE> <DEDENT> def write(self, s): <NEW_LINE> <INDENT> self.__output.write(s.replace('\r\n', '\n').replace('\r', '\n')) <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> self.__output.flush()
Replace line endings to work with sys.stdout. It seems that sys.stdout expects only '\n' as the line ending, no matter the platform. Otherwise, we get repeated line endings.
6259904be76e3b2f99fd9df6
class UpstreamServerProtocol(protocol.Protocol): <NEW_LINE> <INDENT> def __init__(self, network_component): <NEW_LINE> <INDENT> self.network_component = network_component <NEW_LINE> <DEDENT> def connectionMade(self): <NEW_LINE> <INDENT> self.network_component.conn_condition.acquire() <NEW_LINE> self.network_component.connection = self <NEW_LINE> self.network_component.conn_condition.notify() <NEW_LINE> self.network_component.conn_condition.release() <NEW_LINE> <DEDENT> def dataReceived(self, data): <NEW_LINE> <INDENT> self.network_component.data_from_connection(data) <NEW_LINE> <DEDENT> def connectionLost(self, reason): <NEW_LINE> <INDENT> logging.warning("Upstream: Connection lost (%s)." % reason.getErrorMessage()) <NEW_LINE> self.transport.loseConnection() <NEW_LINE> <DEDENT> def connectionFailed(self, reason): <NEW_LINE> <INDENT> logging.warning("Upstream: Connection failed (%s)." % reason.getErrorMessage()) <NEW_LINE> self.transport.loseConnection()
CLient standard protocol
6259904b8e71fb1e983bceb1
class Project(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=32, default='') <NEW_LINE> desc = models.TextField(max_length=256, null=True) <NEW_LINE> create_time = models.DateTimeField(auto_now=True) <NEW_LINE> members = models.ManyToManyField(MyUser, blank=True)
Each User has many projects called project, each project also contains one or more images.
6259904bd7e4931a7ef3d462
class IPRangesField(models.TextField): <NEW_LINE> <INDENT> def __init__(self, *args, store_text=True, **kwargs): <NEW_LINE> <INDENT> self.store_text = store_text <NEW_LINE> super(IPRangesField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if isinstance(value, IPRanges): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> ip_range_list = IPRanges(value, self.store_text) <NEW_LINE> return ip_range_list <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise ValidationError( 'Invalid value: %s' % value, code='invalid', ) <NEW_LINE> <DEDENT> <DEDENT> def from_db_value(self, value, *args): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return IPRanges(value, True) <NEW_LINE> <DEDENT> def db_type(self, connection): <NEW_LINE> <INDENT> return 'text' <NEW_LINE> <DEDENT> def formfield(self, **kwargs): <NEW_LINE> <INDENT> defaults = {'form_class': IPRangesFieldForm} <NEW_LINE> defaults.update(kwargs) <NEW_LINE> return super(IPRangesField, self).formfield(**defaults)
Database field to store IP-address ranges in different syntax but unambiguous meaning. Supported notation derives from the possible parameters to iptools.IpRangeList (see http://python-iptools.readthedocs.org/en/latest/).
6259904b6e29344779b01a2d
class MailTypeTranslationInlineAdmin(admin.TabularInline): <NEW_LINE> <INDENT> verbose_name = _("Translation") <NEW_LINE> verbose_name_plural = _("Translations") <NEW_LINE> model = MailTypeTranslation <NEW_LINE> max_num = len(settings.LANGUAGES) <NEW_LINE> formfield_overrides = {models.TextField: {'widget': admin.widgets.AdminTextInputWidget}} <NEW_LINE> max_num = len(settings.LANGUAGES) <NEW_LINE> extra = 2
Administration inline des traductions de types de courrier
6259904b16aa5153ce4018d9
class FormsetDataTable(FormsetDataTableMixin, horizon_tables.DataTable): <NEW_LINE> <INDENT> pass
A DataTable with support for Django Formsets. Note that :attr:`horizon.tables.DataTableOptions.row_class` and :attr:`horizon.tables.DataTaleOptions.cell_class` are overwritten in this class, so setting them in ``Meta`` has no effect. .. attribute:: formset_class A class made with ``django.forms.formsets.formset_factory`` containing the definition of the formset to use with this data table. The columns that are named the same as the formset fields will be replaced with form widgets in the table. Any hidden fields from the formset will also be included. The fields that are not hidden and don't correspond to any column will not be included in the form.
6259904b0a50d4780f7067b3
class Paddle: <NEW_LINE> <INDENT> def __init__(self, x, y, width, height): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.color = (255,255,255) <NEW_LINE> self.vx = 0.0 <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += self.vx
Encode the state of the paddle in Brick Breaker
6259904b7d847024c075d7be
class SetDevicePowerCycles(TestMixins.SetUInt32Mixin, OptionalParameterTestFixture): <NEW_LINE> <INDENT> CATEGORY = TestCategory.POWER_LAMP_SETTINGS <NEW_LINE> PID = 'DEVICE_POWER_CYCLES' <NEW_LINE> EXPECTED_FIELD = 'power_cycles' <NEW_LINE> REQUIRES = ['power_cycles'] <NEW_LINE> def OldValue(self): <NEW_LINE> <INDENT> return self.Property('power_cycles') <NEW_LINE> <DEDENT> def Test(self): <NEW_LINE> <INDENT> self.AddIfSetSupported([ self.AckSetResult(action=self.VerifySet), self.NackSetResult(RDMNack.NR_DATA_OUT_OF_RANGE), self.NackSetResult( RDMNack.NR_UNSUPPORTED_COMMAND_CLASS, advisory='SET for %s returned unsupported command class' % self.PID), ]) <NEW_LINE> self.SendSet(ROOT_DEVICE, self.pid, [self.NewValue()])
Attempt to SET the device power_cycles.
6259904bec188e330fdf9c89
class RenderCommentFormNode(CommentFormNode): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def handle_token(cls, parser, token): <NEW_LINE> <INDENT> tokens = token.split_contents() <NEW_LINE> if tokens[1] != 'for': <NEW_LINE> <INDENT> raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0]) <NEW_LINE> <DEDENT> if len(tokens) == 3: <NEW_LINE> <INDENT> return cls(object_expr=parser.compile_filter(tokens[2])) <NEW_LINE> <DEDENT> elif len(tokens) == 4: <NEW_LINE> <INDENT> return cls( ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]), object_pk_expr=parser.compile_filter(tokens[3]) ) <NEW_LINE> <DEDENT> <DEDENT> def render(self, context): <NEW_LINE> <INDENT> ctype, object_pk = self.get_target_ctype_pk(context) <NEW_LINE> if object_pk: <NEW_LINE> <INDENT> template_search_list = [ "comments/%s/%s/form.html" % (ctype.app_label, ctype.model), "comments/%s/form.html" % ctype.app_label, "comments/form.html" ] <NEW_LINE> context_dict = {} <NEW_LINE> for d in context.dicts: <NEW_LINE> <INDENT> context_dict.update(d) <NEW_LINE> <DEDENT> context_dict['form'] = self.get_form(context) <NEW_LINE> formstr = render_to_string(template_search_list, context_dict) <NEW_LINE> return formstr <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ''
Render the comment form directly
6259904b63d6d428bbee3bb6
class APITests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> app.config['TESTING'] = True <NEW_LINE> app.config['WTF_CSRF_ENABLED'] = False <NEW_LINE> app.config['DEBUG'] = False <NEW_LINE> app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB) <NEW_LINE> self.app = app.test_client() <NEW_LINE> db.create_all() <NEW_LINE> self.assertEquals(app.debug, False) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> db.session.remove() <NEW_LINE> db.drop_all() <NEW_LINE> <DEDENT> def add_tasks(self): <NEW_LINE> <INDENT> db.session.add( Task( "Run around in circles", date(2015, 10, 22), 10, date(2015, 10, 5), 1, 1 ) ) <NEW_LINE> db.session.commit() <NEW_LINE> db.session.add( Task( "Purchase Real Python", date(2016, 2, 23), 10, date(2016, 2, 7), 1, 1 ) ) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def test_collection_endpoint_returns_correct_data(self): <NEW_LINE> <INDENT> self.add_tasks() <NEW_LINE> response = self.app.get('api/v1/tasks/', follow_redirects=True) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> self.assertEquals(response.mimetype, 'application/json') <NEW_LINE> self.assertIn(b'Run around in circles', response.data) <NEW_LINE> self.assertIn(b'Purchase Real Python', response.data) <NEW_LINE> <DEDENT> def test_resource_endpoint_returns_correct_data(self): <NEW_LINE> <INDENT> self.add_tasks() <NEW_LINE> response = self.app.get('api/v1/tasks/2', follow_redirects=True) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> self.assertEquals(response.mimetype, 'application/json') <NEW_LINE> self.assertIn(b'Purchase Real Python', response.data) <NEW_LINE> self.assertNotIn(b'Run around in circles', response.data) <NEW_LINE> <DEDENT> def test_invalid_resource_endpoint_returns_error(self): <NEW_LINE> <INDENT> self.add_tasks() <NEW_LINE> response = self.app.get('api/v1/tasks/209', follow_redirects=True) <NEW_LINE> self.assertEquals(response.status_code, 404) <NEW_LINE> self.assertEquals(response.mimetype, 'application/json') <NEW_LINE> self.assertIn(b'Element does not exist', response.data)
API test cases.
6259904b15baa7234946337e
class QuickSubscriber(object): <NEW_LINE> <INDENT> def __init__(self, topic_name=None, msg_class=Image, n_messages=1, verbose=False, tf_parent_frame=None, tf_timeout=1., tf_skip_if_no_tf=True): <NEW_LINE> <INDENT> if topic_name is None: <NEW_LINE> <INDENT> print("Usage: q = QuickSubscriber(topic_name, msg_class ,n_messages(default=1), verbose(default=False))") <NEW_LINE> raise Exception() <NEW_LINE> <DEDENT> rospy.init_node("quick_subscriber_{}".format(topic_name.replace('/','_')), anonymous=True) <NEW_LINE> rospy.Subscriber(topic_name, msg_class, self.callback) <NEW_LINE> self.messages = [] <NEW_LINE> self.n_messages = n_messages <NEW_LINE> self.topic_name = topic_name <NEW_LINE> self.VERBOSE = verbose <NEW_LINE> self.TF_PARENT_FRAME = tf_parent_frame <NEW_LINE> self.tf_timeout = rospy.Duration(tf_timeout) <NEW_LINE> self.tf_skip_if_tf_not_found = tf_skip_if_no_tf <NEW_LINE> if self.TF_PARENT_FRAME is not None: <NEW_LINE> <INDENT> self.tfs = [] <NEW_LINE> self.tf_listener = tf.TransformListener() <NEW_LINE> <DEDENT> print("Waiting for {} messages on topic {}".format(self.n_messages, self.topic_name)) <NEW_LINE> rospy.spin() <NEW_LINE> <DEDENT> def callback(self, msg): <NEW_LINE> <INDENT> verbose_msg_info = ": {}".format(msg) if self.VERBOSE else "" <NEW_LINE> rospy.loginfo("Captured message {}/{}{}".format(len(self.messages)+1, self.n_messages, verbose_msg_info)); <NEW_LINE> if self.TF_PARENT_FRAME is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> time = rospy.Time(msg.header.stamp.secs, msg.header.stamp.nsecs) <NEW_LINE> tf_info = [self.TF_PARENT_FRAME, msg.header.frame_id, time] <NEW_LINE> self.tf_listener.waitForTransform(*(tf_info + [self.tf_timeout])) <NEW_LINE> tf_ = self.tf_listener.lookupTransform(*tf_info) <NEW_LINE> <DEDENT> except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException, TransformException) as e: <NEW_LINE> <INDENT> print("tf for time {} not found: {}".format(time, e)) <NEW_LINE> if self.tf_skip_if_tf_not_found: <NEW_LINE> <INDENT> print("Skipping message.") <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tf_ = None <NEW_LINE> <DEDENT> <DEDENT> self.tfs.append(tf_) <NEW_LINE> <DEDENT> self.messages.append(msg) <NEW_LINE> if len(self.messages) >= self.n_messages: <NEW_LINE> <INDENT> print("Collected all messages. Messages stored in QuickSubscriber.messages") <NEW_LINE> if self.TF_PARENT_FRAME is not None: <NEW_LINE> <INDENT> print("tfs stored in QuickSubscriber.tfs") <NEW_LINE> <DEDENT> rospy.signal_shutdown("Mission accomplished.")
Quickly extracts messages
6259904b50485f2cf55dc377
class PhononMoment: <NEW_LINE> <INDENT> def __init__(self, frequencies, weights, eigenvectors=None): <NEW_LINE> <INDENT> self._frequencies = frequencies <NEW_LINE> self._eigenvectors = eigenvectors <NEW_LINE> self._weights = weights <NEW_LINE> self._fmin = None <NEW_LINE> self._fmax = None <NEW_LINE> self.set_frequency_range() <NEW_LINE> self._moment = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def moment(self): <NEW_LINE> <INDENT> return self._moment <NEW_LINE> <DEDENT> def get_moment(self): <NEW_LINE> <INDENT> warnings.warn( "PhononMoment.get_moment() is deprecated. " "Use PhononMoment.moment attribute.", DeprecationWarning, ) <NEW_LINE> return self.moment <NEW_LINE> <DEDENT> def set_frequency_range(self, freq_min=None, freq_max=None, tolerance=1e-8): <NEW_LINE> <INDENT> if freq_min is None: <NEW_LINE> <INDENT> self._fmin = tolerance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fmin = freq_min - tolerance <NEW_LINE> <DEDENT> if freq_max is None: <NEW_LINE> <INDENT> self._fmax = np.max(self._frequencies) + tolerance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fmax = freq_max + tolerance <NEW_LINE> <DEDENT> <DEDENT> def run(self, order=1): <NEW_LINE> <INDENT> if self._eigenvectors is None: <NEW_LINE> <INDENT> self._get_moment(order) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._get_projected_moment(order) <NEW_LINE> <DEDENT> <DEDENT> def _get_moment(self, order): <NEW_LINE> <INDENT> moment = 0 <NEW_LINE> norm0 = 0 <NEW_LINE> for i, w in enumerate(self._weights): <NEW_LINE> <INDENT> for freq in self._frequencies[i]: <NEW_LINE> <INDENT> if self._fmin < freq and freq < self._fmax: <NEW_LINE> <INDENT> norm0 += w <NEW_LINE> moment += freq**order * w <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._moment = moment / norm0 <NEW_LINE> <DEDENT> def _get_projected_moment(self, order): <NEW_LINE> <INDENT> moment = np.zeros(self._frequencies.shape[1], dtype="double") <NEW_LINE> norm0 = np.zeros_like(moment) <NEW_LINE> for i, w in enumerate(self._weights): <NEW_LINE> <INDENT> for freq, eigvec in zip(self._frequencies[i], self._eigenvectors[i].T): <NEW_LINE> <INDENT> if self._fmin < freq and freq < self._fmax: <NEW_LINE> <INDENT> projection = np.abs(eigvec) ** 2 <NEW_LINE> norm0 += w * projection <NEW_LINE> moment += freq**order * w * projection <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._moment = ( np.array( [ np.sum((moment / norm0)[i * 3 : (i + 1) * 3]) for i in range(len(moment) // 3) ] ) / 3 )
Calculate phonon state moments. Attributes ---------- moment : float or ndarray Phonon state moment of specified order (float) or projected phonon state moment of specified order (ndarray).
6259904b07f4c71912bb0821
class PythonOrgSearch(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.driver = webdriver.Chrome('C:\SeleniumDrivers\Chrome\chromedriver.exe') <NEW_LINE> self.driver.get("https://www.python.org") <NEW_LINE> <DEDENT> def test_search_in_python_org(self): <NEW_LINE> <INDENT> main_page = python_page.MainPage(self.driver) <NEW_LINE> assert main_page.is_title_matches(), "python.org title doesn't match." <NEW_LINE> main_page.search_text_element = "pycon" <NEW_LINE> main_page.click_go_button() <NEW_LINE> search_results_page = python_page.SearchResultsPage(self.driver) <NEW_LINE> assert search_results_page.is_results_found(), "No results found." <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.driver.close()
A sample test class to show how page object works
6259904b3c8af77a43b68934
class Mul(BinaryOp): <NEW_LINE> <INDENT> prec = 2 <NEW_LINE> def __init__(self, A, B): <NEW_LINE> <INDENT> if A.shape[1] != B.shape[0]: <NEW_LINE> <INDENT> raise ValueError("Cannot perform the operation on a %s-tensor with a %s-tensor." % (A.shape, B.shape)) <NEW_LINE> <DEDENT> super(Mul, self).__init__(A, B) <NEW_LINE> <DEDENT> def arguments(self): <NEW_LINE> <INDENT> A, B = self.tensors <NEW_LINE> argsA = A.arguments() <NEW_LINE> argsB = B.arguments() <NEW_LINE> assert argsA[-1].function_space() == argsB[0].function_space(), ( "Cannot perform the contraction over middle arguments. " "They need to be in the same function space." ) <NEW_LINE> return argsA[:-1] + argsB[1:]
Abstract SLATE class representing the interior product or two tensors. By interior product, we mean an operation that results in a tensor of equal or lower rank via performing a contraction on arguments. This includes Matrix-Matrix and Matrix-Vector multiplication. :arg A: a :class:`TensorBase` object. :arg B: another :class:`TensorBase` object.
6259904b0a366e3fb87dddd3
class DictionaryConfig(FermenatorConfig): <NEW_LINE> <INDENT> def get_relay_config(self): <NEW_LINE> <INDENT> return self._config['relays'] <NEW_LINE> <DEDENT> def get_datasource_config(self): <NEW_LINE> <INDENT> return self._config['datasources'] <NEW_LINE> <DEDENT> def get_beer_configuration(self): <NEW_LINE> <INDENT> return self._config['beers'] <NEW_LINE> <DEDENT> def get_manager_configuration(self): <NEW_LINE> <INDENT> return self._config['managers'] <NEW_LINE> <DEDENT> def is_config_changed(self): <NEW_LINE> <INDENT> return False
Directly provide a dictionary of configuration to this class. Object references should be in the text form rather than class instances. Essentially, this class is designed to be passed config read out of a yaml or json file, or passed directly from testing code. When instantiating this config, you should directly pass the top-level config dictionary as kwargs, eg:: config_dict = yaml.load(configfile) config_obj = DictionaryConfig('somename', **config_dict)
6259904b8da39b475be045de
class SimulationTimeCondition(py_trees.behaviour.Behaviour): <NEW_LINE> <INDENT> def __init__(self, timeout, success_rule="greater_than", name="SimulationTimeCondition"): <NEW_LINE> <INDENT> super(SimulationTimeCondition, self).__init__(name) <NEW_LINE> self.logger.debug("%s.__init__()" % (self.__class__.__name__)) <NEW_LINE> self._timeout_value = timeout <NEW_LINE> self._start_time = 0.0 <NEW_LINE> self._success_rule = success_rule <NEW_LINE> self._ops = {"greater_than": (lambda x, y: x > y), "equal_to": (lambda x, y: x == y), "less_than": (lambda x, y: x < y)} <NEW_LINE> <DEDENT> def setup(self, unused_timeout=15): <NEW_LINE> <INDENT> self.logger.debug("%s.setup()" % (self.__class__.__name__)) <NEW_LINE> return True <NEW_LINE> <DEDENT> def initialise(self): <NEW_LINE> <INDENT> self._start_time = GameTime.get_time() <NEW_LINE> self.logger.debug("%s.initialise()" % (self.__class__.__name__)) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> elapsed_time = GameTime.get_time() - self._start_time <NEW_LINE> if not self._ops[self._success_rule](elapsed_time, self._timeout_value): <NEW_LINE> <INDENT> new_status = py_trees.common.Status.RUNNING <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_status = py_trees.common.Status.SUCCESS <NEW_LINE> <DEDENT> self.logger.debug("%s.update()[%s->%s]" % (self.__class__.__name__, self.status, new_status)) <NEW_LINE> return new_status <NEW_LINE> <DEDENT> def terminate(self, new_status): <NEW_LINE> <INDENT> self.logger.debug("%s.terminate()[%s->%s]" % (self.__class__.__name__, self.status, new_status))
This class contains an atomic simulation time condition behavior. It uses the CARLA game time, not the system time which is used by the py_trees timer. Returns, if the provided success_rule (greater_than, less_than, equal_to) was successfully evaluated
6259904b507cdc57c63a618d
class SnippetDetail(APIView): <NEW_LINE> <INDENT> def get_object(self, pk): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Snippet.objects.get(pk=pk) <NEW_LINE> <DEDENT> except Snippet.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, pk, format=None): <NEW_LINE> <INDENT> snippet = self.get_object(pk) <NEW_LINE> serializer = SnippetSerializer(snippet) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def put(self, request, pk, format=None): <NEW_LINE> <INDENT> snippet = self.get_object(pk) <NEW_LINE> serializer = SnippetSerializer(snippet, data=request.DATA) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def delete(self, request, pk, format=None): <NEW_LINE> <INDENT> snippet = self.get_object(pk) <NEW_LINE> snippet.delete() <NEW_LINE> return HttpResponse(status=status.HTTP_202_NO_CONTENT)
Snippet detail view as a class
6259904b8e05c05ec3f6f851
class PlanNotFoundError(AppError): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> message = ''.join(['Plan not found: ', message]) <NEW_LINE> super().__init__(message)
This class using when user try to find plan whick doesn't exists
6259904b435de62698e9d1f5
class ApacheThriftPyGen(ApacheThriftGenBase): <NEW_LINE> <INDENT> gentarget_type = PythonThriftLibrary <NEW_LINE> thrift_generator = 'py' <NEW_LINE> default_gen_options_map = { 'new_style': None } <NEW_LINE> sources_globs = ('**/*',) <NEW_LINE> def synthetic_target_type(self, target): <NEW_LINE> <INDENT> return PythonLibrary <NEW_LINE> <DEDENT> def execute_codegen(self, target, target_workdir): <NEW_LINE> <INDENT> super(ApacheThriftPyGen, self).execute_codegen(target, target_workdir) <NEW_LINE> for root, _, files in safe_walk(target_workdir): <NEW_LINE> <INDENT> if '__init__.py' not in files: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> init_py_abspath = os.path.join(root, '__init__.py') <NEW_LINE> if root == target_workdir: <NEW_LINE> <INDENT> safe_delete(init_py_abspath) <NEW_LINE> <DEDENT> elif os.path.getsize(init_py_abspath) == 0: <NEW_LINE> <INDENT> with open(init_py_abspath, 'wb') as f: <NEW_LINE> <INDENT> f.write(b"__import__('pkg_resources').declare_namespace(__name__)") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def _copy_target_attributes(self): <NEW_LINE> <INDENT> return super(ApacheThriftPyGen, self)._copy_target_attributes + ['compatibility'] <NEW_LINE> <DEDENT> def ignore_dup(self, tgt1, tgt2, rel_src): <NEW_LINE> <INDENT> return os.path.basename(rel_src) == '__init__.py'
Generate Python source files from thrift IDL files.
6259904b15baa7234946337f
class UserSerializer2(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> snippets = serializers.HyperlinkedRelatedField(view_name='snippet-detail', many=True, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('url', 'id', 'username', 'snippets')
用户序列化
6259904bcb5e8a47e493cb7e
class Parameter(TypeContainer): <NEW_LINE> <INDENT> def __init__(self, argname, typenode, direction=None, transfer=None, nullable=False, optional=False, allow_none=False, scope=None, caller_allocates=False, not_nullable=False): <NEW_LINE> <INDENT> TypeContainer.__init__(self, typenode, nullable, not_nullable, transfer, direction) <NEW_LINE> self.argname = argname <NEW_LINE> self.optional = optional <NEW_LINE> self.parent = None <NEW_LINE> if allow_none: <NEW_LINE> <INDENT> if self.direction == PARAM_DIRECTION_OUT: <NEW_LINE> <INDENT> self.optional = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nullable = True <NEW_LINE> <DEDENT> <DEDENT> self.scope = scope <NEW_LINE> self.caller_allocates = caller_allocates <NEW_LINE> self.closure_name = None <NEW_LINE> self.destroy_name = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.argname
An argument to a function.
6259904bf7d966606f7492b0
class Profile: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> self.total = 0 <NEW_LINE> self.t0 = None <NEW_LINE> <DEDENT> def start(self,stopLast=False): <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.running = True <NEW_LINE> self.t0 = time() <NEW_LINE> <DEDENT> def stop(self,t=time()): <NEW_LINE> <INDENT> if not self.running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.running = False <NEW_LINE> self.total += t-self.t0
Object representing each timer for ParallelProfiler
6259904b3c8af77a43b68935
class TestRentControlStatus(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 testRentControlStatus(self): <NEW_LINE> <INDENT> pass
RentControlStatus unit test stubs
6259904b63b5f9789fe8655c
class AskbotTestCase(TestCase): <NEW_LINE> <INDENT> def create_user( self, username = 'user', email = None, notification_schedule = None, date_joined = None, status = 'a' ): <NEW_LINE> <INDENT> assert(username is not None) <NEW_LINE> assert(not hasattr(self, username)) <NEW_LINE> if email is None: <NEW_LINE> <INDENT> email = username + '@example.com' <NEW_LINE> <DEDENT> user_object = create_user( username = username, email = email, notification_schedule = notification_schedule, date_joined = date_joined, status = status ) <NEW_LINE> setattr(self, username, user_object) <NEW_LINE> return user_object <NEW_LINE> <DEDENT> def post_question( self, user = None, title = 'test question title', body_text = 'test question body text', tags = 'test', wiki = False, follow = False, timestamp = None ): <NEW_LINE> <INDENT> if user is None: <NEW_LINE> <INDENT> user = self.user <NEW_LINE> <DEDENT> question = user.post_question( title = title, body_text = body_text, tags = tags, wiki = wiki, timestamp = timestamp ) <NEW_LINE> if follow: <NEW_LINE> <INDENT> user.follow_question(question) <NEW_LINE> <DEDENT> return question <NEW_LINE> <DEDENT> def post_answer( self, user = None, question = None, body_text = 'test answer text', follow = False, wiki = False, timestamp = None ): <NEW_LINE> <INDENT> if user is None: <NEW_LINE> <INDENT> user = self.user <NEW_LINE> <DEDENT> return user.post_answer( question = question, body_text = body_text, follow = follow, wiki = wiki, timestamp = timestamp ) <NEW_LINE> <DEDENT> def post_comment( self, user = None, parent_post = None, body_text = 'test comment text', timestamp = None ): <NEW_LINE> <INDENT> if user is None: <NEW_LINE> <INDENT> user = self.user <NEW_LINE> <DEDENT> comment = user.post_comment( parent_post = parent_post, body_text = body_text, timestamp = timestamp, ) <NEW_LINE> return comment
adds some askbot-specific methods to django TestCase class
6259904bd4950a0f3b11183a
class Decimal(Number): <NEW_LINE> <INDENT> num_type = decimal.Decimal <NEW_LINE> default_error_messages = { 'special': 'Special numeric values (nan or infinity) are not permitted.', } <NEW_LINE> def __init__(self, places=None, rounding=None, allow_nan=False, as_string=False, **kwargs): <NEW_LINE> <INDENT> self.places = decimal.Decimal((0, (1,), -places)) if places is not None else None <NEW_LINE> self.rounding = rounding <NEW_LINE> self.allow_nan = allow_nan <NEW_LINE> super(Decimal, self).__init__(as_string=as_string, **kwargs) <NEW_LINE> <DEDENT> def _format_num(self, value): <NEW_LINE> <INDENT> num = decimal.Decimal(str(value)) <NEW_LINE> if self.allow_nan: <NEW_LINE> <INDENT> if num.is_nan(): <NEW_LINE> <INDENT> return decimal.Decimal('NaN') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if num.is_nan() or num.is_infinite(): <NEW_LINE> <INDENT> self.fail('special') <NEW_LINE> <DEDENT> <DEDENT> if self.places is not None and num.is_finite(): <NEW_LINE> <INDENT> num = num.quantize(self.places, rounding=self.rounding) <NEW_LINE> <DEDENT> return num <NEW_LINE> <DEDENT> def _validated(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(Decimal, self)._validated(value) <NEW_LINE> <DEDENT> except decimal.InvalidOperation: <NEW_LINE> <INDENT> self.fail('invalid') <NEW_LINE> <DEDENT> <DEDENT> def _to_string(self, value): <NEW_LINE> <INDENT> return format(value, 'f')
A field that (de)serializes to the Python ``decimal.Decimal`` type. It's safe to use when dealing with money values, percentages, ratios or other numbers where precision is critical. .. warning:: This field serializes to a `decimal.Decimal` object by default. If you need to render your data as JSON, keep in mind that the `json` module from the standard library does not encode `decimal.Decimal`. Therefore, you must use a JSON library that can handle decimals, such as `simplejson`, or serialize to a string by passing ``as_string=True``. .. warning:: If a JSON `float` value is passed to this field for deserialization it will first be cast to its corresponding `string` value before being deserialized to a `decimal.Decimal` object. The default `__str__` implementation of the built-in Python `float` type may apply a destructive transformation upon its input data and therefore cannot be relied upon to preserve precision. To avoid this, you can instead pass a JSON `string` to be deserialized directly. :param int places: How many decimal places to quantize the value. If `None`, does not quantize the value. :param rounding: How to round the value during quantize, for example `decimal.ROUND_UP`. If None, uses the rounding value from the current thread's context. :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed, even though they are illegal according to the JSON specification. :param bool as_string: If True, serialize to a string instead of a Python `decimal.Decimal` type. :param kwargs: The same keyword arguments that :class:`Number` receives. .. versionadded:: 1.2.0
6259904b8a349b6b4368763e
class Patient(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100, verbose_name="Nome do paciente") <NEW_LINE> mother_name = models.CharField( max_length=100, verbose_name="Nome da mãe", null=True, blank=True) <NEW_LINE> address = models.CharField(max_length=300, verbose_name="Endereço") <NEW_LINE> phone = models.CharField(max_length=100, verbose_name="Telefone") <NEW_LINE> birthdate = models.DateField(verbose_name="Data de nascimento") <NEW_LINE> exame_number = models.CharField( verbose_name="Número do exame laboratorial", max_length=40, null=True, blank=True) <NEW_LINE> notes = models.CharField( max_length=300, verbose_name="Observações", null=True, blank=True) <NEW_LINE> prostate_history = models.NullBooleanField( verbose_name="Tem alguém na família com problemas na próstata") <NEW_LINE> trouble_urinating = models.NullBooleanField( verbose_name="Problemas para urinar?") <NEW_LINE> suspicious_nodule = models.NullBooleanField( verbose_name="Possui nódulo suspeito?") <NEW_LINE> psa_positive = models.NullBooleanField( verbose_name="Exame de PSA Positivo?", default=False, blank=True, null=True) <NEW_LINE> has_referral = models.NullBooleanField( verbose_name="Encaminhamento", default=False) <NEW_LINE> referral_character = models.CharField( max_length=100, verbose_name="Caráter", null=True, blank=True, choices=[(str(i), CHARACTER_CHOICES[i]) for i in range(len(CHARACTER_CHOICES))]) <NEW_LINE> referral_place = models.CharField( max_length=100, verbose_name="Local de encaminhamento", null=True, blank=True, choices=[(str(i), REFERAL_PLACES[i]) for i in range(len(REFERAL_PLACES))]) <NEW_LINE> other_referral_place = models.CharField( max_length=100, verbose_name="Especificar local", null=True, blank=True) <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> def get_age(self): <NEW_LINE> <INDENT> today = datetime.now().date() <NEW_LINE> age = today.year - self.birthdate.year <NEW_LINE> if today.month < self.birthdate.month: <NEW_LINE> <INDENT> age = age - 1 <NEW_LINE> <DEDENT> elif today.month == self.birthdate.month and today.day >= self.birthdate.day: <NEW_LINE> <INDENT> age = age - 1 <NEW_LINE> <DEDENT> return age <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['-created_at']
Patient model
6259904b23e79379d538d8ee
class Strecke: <NEW_LINE> <INDENT> def __init__(self, p1: Punkt, p2: Punkt) -> None: <NEW_LINE> <INDENT> assert isinstance(p1, Punkt) <NEW_LINE> assert isinstance(p2, Punkt) <NEW_LINE> self.p1 = p1 <NEW_LINE> self.p2 = p2 <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "{} - {}".format(self.p1, self.p2) <NEW_LINE> <DEDENT> def __eq__(self, l: "Strecke") -> bool: <NEW_LINE> <INDENT> if not isinstance(l, Strecke): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.p1 == l.p1 and self.p2 == l.p2: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.p1 == l.p2 and self.p2 == l.p1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __abs__(self) -> float: <NEW_LINE> <INDENT> x = self.p1.x - self.p2.x <NEW_LINE> y = self.p1.y - self.p2.y <NEW_LINE> z = self.p1.z - self.p2.z <NEW_LINE> return math.sqrt(x**2 + y**2 + z**2) <NEW_LINE> <DEDENT> def __len__(self) -> int: <NEW_LINE> <INDENT> return int(abs(self)) <NEW_LINE> <DEDENT> def __gt__(self, l: "Strecke") -> bool: <NEW_LINE> <INDENT> return abs(self) > abs(l) <NEW_LINE> <DEDENT> def __ge__(self, l: "Strecke") -> bool: <NEW_LINE> <INDENT> return self == l or self > l
Eine Strecke ist eine Linie zwischen zwei Punkten. Sie hat keine Richtung.
6259904b6e29344779b01a31
class ReadOnlyDict(IterableUserDict): <NEW_LINE> <INDENT> def __init__(self, source=None): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> if source: <NEW_LINE> <INDENT> self.data.update(source) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, item): <NEW_LINE> <INDENT> raise TypeError() <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> raise TypeError() <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> raise TypeError() <NEW_LINE> <DEDENT> def pop(self, key, *args): <NEW_LINE> <INDENT> raise TypeError() <NEW_LINE> <DEDENT> def popitem(self): <NEW_LINE> <INDENT> raise TypeError() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> raise TypeError()
A read-only dict.
6259904b29b78933be26aaba
class MetricsCounter: <NEW_LINE> <INDENT> def __init__(self, metric_name: str, count: int, description: str = ""): <NEW_LINE> <INDENT> self.__metric_name = metric_name <NEW_LINE> self.__count = count <NEW_LINE> self.__description = description <NEW_LINE> self.__start_time_seconds = None <NEW_LINE> self.__stop_time_seconds = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.count() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def count(self) -> None: <NEW_LINE> <INDENT> publish_count(self.__metric_name, self.__description, self.__count)
Counter to be used as a with statement.
6259904b4e696a045264e818
class TowerContext(object): <NEW_LINE> <INDENT> def __init__(self, distribution_strategy, tower_id): <NEW_LINE> <INDENT> self._distribution_strategy = distribution_strategy <NEW_LINE> self._thread_context = _InTowerThreadMode(self) <NEW_LINE> self._tower_id = tower_id <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> _push_per_thread_mode(self._thread_context) <NEW_LINE> <DEDENT> def __exit__(self, exception_type, exception_value, traceback): <NEW_LINE> <INDENT> _pop_per_thread_mode() <NEW_LINE> <DEDENT> def merge_call(self, merge_fn, *args, **kwargs): <NEW_LINE> <INDENT> require_tower_context(self) <NEW_LINE> return self._merge_call(merge_fn, *args, **kwargs) <NEW_LINE> <DEDENT> def _merge_call(self, merge_fn, *args, **kwargs): <NEW_LINE> <INDENT> _push_per_thread_mode( _CrossTowerThreadMode(self._distribution_strategy)) <NEW_LINE> try: <NEW_LINE> <INDENT> return merge_fn(self._distribution_strategy, *args, **kwargs) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> _pop_per_thread_mode() <NEW_LINE> <DEDENT> <DEDENT> def tower_local_var_scope(self, aggregation): <NEW_LINE> <INDENT> return self._distribution_strategy.tower_local_var_scope(aggregation) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_single_tower(self): <NEW_LINE> <INDENT> require_tower_context(self) <NEW_LINE> return self._distribution_strategy.is_single_tower <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_towers(self): <NEW_LINE> <INDENT> return self._distribution_strategy.num_towers <NEW_LINE> <DEDENT> @property <NEW_LINE> def tower_id(self): <NEW_LINE> <INDENT> require_tower_context(self) <NEW_LINE> return self._tower_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def distribution_strategy(self): <NEW_LINE> <INDENT> return self._distribution_strategy <NEW_LINE> <DEDENT> @property <NEW_LINE> def device(self): <NEW_LINE> <INDENT> require_tower_context(self) <NEW_LINE> return device_util.current()
DistributionStrategy API inside a `call_for_each_tower()` call.
6259904b004d5f362081f9df
class KalturaTagService(KalturaServiceBase): <NEW_LINE> <INDENT> def __init__(self, client = None): <NEW_LINE> <INDENT> KalturaServiceBase.__init__(self, client) <NEW_LINE> <DEDENT> def search(self, tagFilter, pager = NotImplemented): <NEW_LINE> <INDENT> kparams = KalturaParams() <NEW_LINE> kparams.addObjectIfDefined("tagFilter", tagFilter) <NEW_LINE> kparams.addObjectIfDefined("pager", pager) <NEW_LINE> self.client.queueServiceActionCall("tagsearch_tag", "search", KalturaTagListResponse, kparams) <NEW_LINE> if self.client.isMultiRequest(): <NEW_LINE> <INDENT> return self.client.getMultiRequestResult() <NEW_LINE> <DEDENT> resultNode = self.client.doQueue() <NEW_LINE> return KalturaObjectFactory.create(resultNode, KalturaTagListResponse) <NEW_LINE> <DEDENT> def deletePending(self): <NEW_LINE> <INDENT> kparams = KalturaParams() <NEW_LINE> self.client.queueServiceActionCall("tagsearch_tag", "deletePending", None, kparams) <NEW_LINE> if self.client.isMultiRequest(): <NEW_LINE> <INDENT> return self.client.getMultiRequestResult() <NEW_LINE> <DEDENT> resultNode = self.client.doQueue() <NEW_LINE> return getXmlNodeInt(resultNode) <NEW_LINE> <DEDENT> def indexCategoryEntryTags(self, categoryId, pcToDecrement, pcToIncrement): <NEW_LINE> <INDENT> kparams = KalturaParams() <NEW_LINE> kparams.addIntIfDefined("categoryId", categoryId); <NEW_LINE> kparams.addStringIfDefined("pcToDecrement", pcToDecrement) <NEW_LINE> kparams.addStringIfDefined("pcToIncrement", pcToIncrement) <NEW_LINE> self.client.queueServiceActionCall("tagsearch_tag", "indexCategoryEntryTags", None, kparams) <NEW_LINE> if self.client.isMultiRequest(): <NEW_LINE> <INDENT> return self.client.getMultiRequestResult() <NEW_LINE> <DEDENT> resultNode = self.client.doQueue()
Search object tags
6259904b73bcbd0ca4bcb678
class AutoSizeParams(VegaLiteSchema): <NEW_LINE> <INDENT> _schema = {'$ref': '#/definitions/AutoSizeParams'} <NEW_LINE> def __init__(self, contains=Undefined, resize=Undefined, type=Undefined, **kwds): <NEW_LINE> <INDENT> super(AutoSizeParams, self).__init__(contains=contains, resize=resize, type=type, **kwds)
AutoSizeParams schema wrapper Mapping(required=[]) Attributes ---------- contains : enum('content', 'padding') Determines how size calculation should be performed, one of ``"content"`` or ``"padding"``. The default setting ( ``"content"`` ) interprets the width and height settings as the data rectangle (plotting) dimensions, to which padding is then added. In contrast, the ``"padding"`` setting includes the padding within the view size calculations, such that the width and height settings indicate the **total** intended size of the view. **Default value** : ``"content"`` resize : boolean A boolean flag indicating if autosize layout should be re-calculated on every view update. **Default value** : ``false`` type : :class:`AutosizeType` The sizing format type. One of ``"pad"``, ``"fit"``, ``"fit-x"``, ``"fit-y"``, or ``"none"``. See the `autosize type <https://vega.github.io/vega-lite/docs/size.html#autosize>`__ documentation for descriptions of each. **Default value** : ``"pad"``
6259904b7cff6e4e811b6e2b
class UserEntity(Base): <NEW_LINE> <INDENT> pass
The user object.
6259904b29b78933be26aabb
class CountryAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('name', 'formal_name', 'country_code', 'number_of_photos') <NEW_LINE> list_editable = ('formal_name',) <NEW_LINE> list_select_related = True <NEW_LINE> search_fields = ('name', 'formal_name')
Django model admin for ``flother.apps.places.models.Country``.
6259904bd10714528d69f086
class LivingEntity(Entity): <NEW_LINE> <INDENT> def __init__(self, health=1, max_health=1, *groups, **kwargs): <NEW_LINE> <INDENT> super().__init__(*groups, **kwargs) <NEW_LINE> self.health = health <NEW_LINE> self.max_health = max_health <NEW_LINE> <DEDENT> def damage(self, amt): <NEW_LINE> <INDENT> self.health -= amt <NEW_LINE> self._check_hp_bounds() <NEW_LINE> <DEDENT> def heal(self, amt): <NEW_LINE> <INDENT> self.health += amt <NEW_LINE> self._check_hp_bounds() <NEW_LINE> <DEDENT> def is_alive(self): <NEW_LINE> <INDENT> return self.health > 0 <NEW_LINE> <DEDENT> def _check_hp_bounds(self): <NEW_LINE> <INDENT> if 0 > self.health: <NEW_LINE> <INDENT> self.health = 0 <NEW_LINE> <DEDENT> if self.health > self.max_health: <NEW_LINE> <INDENT> self.health = self.max_health
LivingEntity represents an entity that has health and can be in a living or dead state based on it's current health.
6259904b26068e7796d4dd35
class DefaultBunch(Bunch, defaultdict): <NEW_LINE> <INDENT> pass
Generic attribute container that also is a dict.
6259904bec188e330fdf9c8f
class CachedFile: <NEW_LINE> <INDENT> def __init__(self, file_or_url: str, cache_dir: Optional[Path] = None): <NEW_LINE> <INDENT> url = urlparse(file_or_url) <NEW_LINE> if url.scheme: <NEW_LINE> <INDENT> path = Path(url.path) <NEW_LINE> self.url = file_or_url <NEW_LINE> self.url_parsed = url <NEW_LINE> self.path = None <NEW_LINE> self.is_url = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = Path(file_or_url) <NEW_LINE> self.url = None <NEW_LINE> self.path = path <NEW_LINE> self.is_url = False <NEW_LINE> <DEDENT> if self.is_url and cache_dir is not None: <NEW_LINE> <INDENT> self.path = cache_dir.joinpath(path.name) <NEW_LINE> <DEDENT> <DEDENT> def open(self, offline=False, mode="rt") -> IO: <NEW_LINE> <INDENT> if self.is_url and not offline: <NEW_LINE> <INDENT> logger.debug('fetching %s', self.url) <NEW_LINE> response = requests.get(self.url) <NEW_LINE> if self.path: <NEW_LINE> <INDENT> logger.debug('saving as %s', self.path) <NEW_LINE> if not self.path.parent.exists(): <NEW_LINE> <INDENT> self.path.parent.mkdir(parents=True, exist_ok=True) <NEW_LINE> <DEDENT> if "b" in mode: <NEW_LINE> <INDENT> with self.path.open("wb") as cache_file: <NEW_LINE> <INDENT> cache_file.write(response.content) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with self.path.open("wt", encoding='utf-8') as cache_file: <NEW_LINE> <INDENT> cache_file.write(response.text) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if "b" in mode: <NEW_LINE> <INDENT> return BytesIO(response.content) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return StringIO(response.text) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.path.open(mode=mode, encoding='utf-8-sig')
Loads data from an URL, optionally caching it.
6259904b63d6d428bbee3bbc
class Loader(BaseComponent): <NEW_LINE> <INDENT> channel = "loader" <NEW_LINE> def __init__(self, auto_register=True, init_args=None, init_kwargs=None, paths=None, channel=channel): <NEW_LINE> <INDENT> super(Loader, self).__init__(channel=channel) <NEW_LINE> self._auto_register = auto_register <NEW_LINE> self._init_args = init_args or tuple() <NEW_LINE> self._init_kwargs = init_kwargs or dict() <NEW_LINE> if paths: <NEW_LINE> <INDENT> for path in paths: <NEW_LINE> <INDENT> sys.path.insert(0, path) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @handler("load") <NEW_LINE> def load(self, name): <NEW_LINE> <INDENT> module = safeimport(name) <NEW_LINE> if module is not None: <NEW_LINE> <INDENT> test = lambda x: isclass(x) and issubclass(x, BaseComponent) and getmodule(x) is module <NEW_LINE> components = [x[1] for x in getmembers(module, test)] <NEW_LINE> if components: <NEW_LINE> <INDENT> TheComponent = components[0] <NEW_LINE> component = TheComponent( *self._init_args, **self._init_kwargs ) <NEW_LINE> if self._auto_register: <NEW_LINE> <INDENT> component.register(self) <NEW_LINE> <DEDENT> return component
Create a new Loader Component Creates a new Loader Component that enables dynamic loading of components from modules either in local paths, eggs or zip archives.
6259904b96565a6dacd2d982
class HDFSClient: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def generate_temp_files(need_certificate=NEED_CERTIFICATE): <NEW_LINE> <INDENT> if need_certificate: <NEW_LINE> <INDENT> with krbcontext(using_keytab=True, keytab_file=KEYTAB_PATH, principal=PRINCIPAL): <NEW_LINE> <INDENT> for node in HDFS.NODES: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hdfs_client = KerberosClient(node) <NEW_LINE> hdfs_client.download(HDFS.REMOTE_PATH, HDFS.LOCAL_PATH, n_threads=HDFS.THREAD_NUM) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logging.info(err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> logging.error("Failed to download remote HDFS file.") <NEW_LINE> raise Exception("Failed to download remote HDFS file.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for node in HDFS.NODES: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hdfs_client = Client(node) <NEW_LINE> hdfs_client.download(HDFS.REMOTE_PATH, HDFS.LOCAL_PATH, n_threads=HDFS.THREAD_NUM) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logging.info(err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> logging.error("Failed to download remote HDFS file.") <NEW_LINE> raise Exception("Failed to download remote HDFS file.") <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def remove_temp_files(): <NEW_LINE> <INDENT> if os.path.exists(HDFS.LOCAL_PATH): <NEW_LINE> <INDENT> shutil.rmtree(HDFS.LOCAL_PATH)
using Kerberos authentication for downloading feature data
6259904b4428ac0f6e659923
class Dummy_Gaze_Mapper(Gaze_Mapping_Plugin): <NEW_LINE> <INDENT> def __init__(self, g_pool): <NEW_LINE> <INDENT> super(Dummy_Gaze_Mapper, self).__init__(g_pool) <NEW_LINE> <DEDENT> def update(self,frame,events): <NEW_LINE> <INDENT> gaze_pts = [] <NEW_LINE> for p in events['pupil_positions']: <NEW_LINE> <INDENT> if p['confidence'] > self.g_pool.pupil_confidence_threshold: <NEW_LINE> <INDENT> gaze_pts.append({'norm_pos':p['norm_pos'][:],'confidence':p['confidence'],'timestamp':p['timestamp'],'base':[p]}) <NEW_LINE> <DEDENT> <DEDENT> events['gaze_positions'] = gaze_pts <NEW_LINE> <DEDENT> def get_init_dict(self): <NEW_LINE> <INDENT> return {}
docstring for Dummy_Gaze_Mapper
6259904b30dc7b76659a0c26
class Watcher(VerboseObject): <NEW_LINE> <INDENT> def handle_broadcast_message(self, message, game): <NEW_LINE> <INDENT> self.handle_message("handle_broadcast", message, game) <NEW_LINE> <DEDENT> def handle_server_message(self, message, game, recipient): <NEW_LINE> <INDENT> self.handle_message("handle_server", message, game, recipient) <NEW_LINE> <DEDENT> def handle_client_message(self, message, game, sender): <NEW_LINE> <INDENT> self.handle_message("handle_client", message, game, sender) <NEW_LINE> <DEDENT> def handle_message(self, prefix, message, *args): <NEW_LINE> <INDENT> parts = [prefix, message[0].text] <NEW_LINE> if message[0] in (YES, REJ, NOT, HUH) and len(message) > 2: <NEW_LINE> <INDENT> parts.append(message[2].text) <NEW_LINE> <DEDENT> method_name = str.join("_", parts) <NEW_LINE> method = getattr(self, method_name, None) <NEW_LINE> if method: <NEW_LINE> <INDENT> self.log.debug("%s(%s, *%s)", method.__name__, message, args) <NEW_LINE> try: <NEW_LINE> <INDENT> method(message, *args) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.log.exception("Exception handling %s", message)
Game message watcher. Contains simple handlers to pass messages to any handler methods defined in subclasses. More functionality may be included if deemed worthwhile to several watchers.
6259904b0fa83653e46f62d0
class NumArray: <NEW_LINE> <INDENT> def __init__(self, nums): <NEW_LINE> <INDENT> def fillST(st, cur, nums, start, end): <NEW_LINE> <INDENT> if start==end: <NEW_LINE> <INDENT> st[cur] = nums[start] <NEW_LINE> return st[cur] <NEW_LINE> <DEDENT> mid = start+(end-start)//2 <NEW_LINE> left = fillST(st, 2*cur, nums, start, mid) <NEW_LINE> right = fillST(st, 2*cur+1, nums, mid+1, end) <NEW_LINE> st[cur] = left+right <NEW_LINE> return st[cur] <NEW_LINE> <DEDENT> self.nums = nums <NEW_LINE> if len(nums): <NEW_LINE> <INDENT> self.ST = collections.defaultdict(int) <NEW_LINE> fillST(self.ST, 1, nums, 0, len(nums)-1) <NEW_LINE> <DEDENT> <DEDENT> def update(self, i, val): <NEW_LINE> <INDENT> def helper(st, cur, start, end, nums, i, val): <NEW_LINE> <INDENT> if i>=start and i<=end: <NEW_LINE> <INDENT> st[cur] += val-nums[i] <NEW_LINE> <DEDENT> if start==end: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mid = start+(end-start)//2 <NEW_LINE> if i<=mid: <NEW_LINE> <INDENT> helper(st, 2*cur, start, mid, nums, i, val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> helper(st, 2*cur+1, mid+1, end, nums, i, val) <NEW_LINE> <DEDENT> <DEDENT> if len(self.nums): <NEW_LINE> <INDENT> helper(self.ST, 1, 0, len(self.nums)-1, self.nums, i, val) <NEW_LINE> self.nums[i] = val <NEW_LINE> <DEDENT> <DEDENT> def sumRange(self, i, j): <NEW_LINE> <INDENT> def helper(st, cur, start, end, nums, i, j): <NEW_LINE> <INDENT> if start==i and end==j: <NEW_LINE> <INDENT> return st[cur] <NEW_LINE> <DEDENT> mid = start+(end-start)//2 <NEW_LINE> if j<=mid: <NEW_LINE> <INDENT> return helper(st, 2*cur, start, mid, nums, i, j) <NEW_LINE> <DEDENT> elif i>mid: <NEW_LINE> <INDENT> return helper(st, 2*cur+1, mid+1, end, nums, i, j) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return helper(st, 2*cur, start, mid, nums, i, mid)+helper(st, 2*cur+1, mid+1, end, nums, mid+1, j) <NEW_LINE> <DEDENT> <DEDENT> return helper(self.ST, 1, 0, len(self.nums)-1, self.nums, i, j)
Thoughts: 1. Segment tree
6259904bb57a9660fecd2e6f
class TZlibTransportFactory(object): <NEW_LINE> <INDENT> _last_trans = None <NEW_LINE> _last_z = None <NEW_LINE> def getTransport(self, trans, compresslevel=9): <NEW_LINE> <INDENT> if trans == self._last_trans: <NEW_LINE> <INDENT> return self._last_z <NEW_LINE> <DEDENT> ztrans = TZlibTransport(trans, compresslevel) <NEW_LINE> self._last_trans = trans <NEW_LINE> self._last_z = ztrans <NEW_LINE> return ztrans
Factory transport that builds zlib compressed transports. This factory caches the last single client/transport that it was passed and returns the same TZlibTransport object that was created. This caching means the TServer class will get the _same_ transport object for both input and output transports from this factory. (For non-threaded scenarios only, since the cache only holds one object) The purpose of this caching is to allocate only one TZlibTransport where only one is really needed (since it must have separate read/write buffers), and makes the statistics from getCompSavings() and getCompRatio() easier to understand.
6259904bac7a0e7691f738ce
class RandomChannelSwap: <NEW_LINE> <INDENT> def __init__(self, prob=0.5): <NEW_LINE> <INDENT> self.prob = prob <NEW_LINE> self.permutations = ((0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)) <NEW_LINE> self.swap_channels = ChannelSwap(order=(0, 1, 2)) <NEW_LINE> <DEDENT> def __call__(self, image, labels=None): <NEW_LINE> <INDENT> p = np.random.uniform(0,1) <NEW_LINE> if p >= (1.0-self.prob): <NEW_LINE> <INDENT> i = np.random.randint(5) <NEW_LINE> self.swap_channels.order = self.permutations[i] <NEW_LINE> return self.swap_channels(image, labels) <NEW_LINE> <DEDENT> elif labels is None: <NEW_LINE> <INDENT> return image <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return image, labels
Randomly swaps the channels of RGB images. Important: Expects RGB input.
6259904b8e71fb1e983bceb8
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self,ai_settings,screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen =screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('images/wxr.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image,self.rect) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) <NEW_LINE> self.rect.x = self.x
表示单个外星人的类
6259904bbe383301e0254c0e
class Automaton(object): <NEW_LINE> <INDENT> def __init__(self, states, transitions, start_state): <NEW_LINE> <INDENT> if start_state not in states: <NEW_LINE> <INDENT> raise RuntimeError('Invalid start_state') <NEW_LINE> <DEDENT> self.states = dict((s, []) for s in states) <NEW_LINE> self.start_state = start_state <NEW_LINE> self.current_state = start_state <NEW_LINE> for t in transitions: <NEW_LINE> <INDENT> if t.start_state not in self.states or t.end_state not in self.states: <NEW_LINE> <INDENT> raise RuntimeError('Invalid transition', t) <NEW_LINE> <DEDENT> self.states[t.start_state].append(t) <NEW_LINE> <DEDENT> <DEDENT> def step(self, string=''): <NEW_LINE> <INDENT> transitions = self.states[self.current_state] <NEW_LINE> candidates = {} <NEW_LINE> defaults = [] <NEW_LINE> transition = None <NEW_LINE> for t in transitions: <NEW_LINE> <INDENT> if t.match is not None: <NEW_LINE> <INDENT> match = re.match(t.match, string) <NEW_LINE> if match: <NEW_LINE> <INDENT> transition = t <NEW_LINE> candidates[t] = match <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> defaults += [t] <NEW_LINE> <DEDENT> <DEDENT> if len(candidates) == 1: <NEW_LINE> <INDENT> transition = candidates.keys()[0] <NEW_LINE> match = candidates[transition] <NEW_LINE> <DEDENT> elif len(candidates) > 1 or len(defaults) > 1: <NEW_LINE> <INDENT> raise RuntimeError('Automaton must be deterministic (more than one transition on input)') <NEW_LINE> <DEDENT> elif len(candidates) == 0 and len(defaults) == 1: <NEW_LINE> <INDENT> transition = defaults[0] <NEW_LINE> match = re.match('', '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('No matching transition found!') <NEW_LINE> <DEDENT> self.current_state.on_exit.fire() <NEW_LINE> transition.on_enter.fire(match.groups()) <NEW_LINE> self.current_state = transition.end_state <NEW_LINE> self.current_state.on_enter.fire() <NEW_LINE> return True
Create an automaton from a list of states and transitions. @states = maps State's to maps from @end_state to Transition
6259904b10dbd63aa1c71fd0
class IOauthVncbizSettings(Interface): <NEW_LINE> <INDENT> client_id = schema.ASCIILine( title = _(u'client_id' , default=u'Vncbiz client ID'), description = _(u'help_client_id' , default=u"Alternatively, you can of course use the ID of an existing app."), required = True, default = '', ) <NEW_LINE> auth_url = schema.URI( title = _(u'auth_url' , default=u'Vncbiz authorize url'), description = _(u'help_auth_url' , default=u""), required = True, default = 'http://demo.vnc.biz:9800/oauth2/auth', ) <NEW_LINE> profile_url = schema.URI( title = _(u'profile_url' , default=u'Vncbiz profile url'), description = _(u'help_profile_url' , default=u""), required = True, default = 'http://demo.vnc.biz:9800/oauth2/tokeninfo', )
OAuth Vncbiz registry settings
6259904b23e79379d538d8f1
class CFlight(model.CEventsModel): <NEW_LINE> <INDENT> def __init__(self, fs_callsign): <NEW_LINE> <INDENT> super(CFlight, self).__init__() <NEW_LINE> self.s_name = "Flight event" <NEW_LINE> self.__s_callsign = fs_callsign <NEW_LINE> <DEDENT> @property <NEW_LINE> def s_callsign(self): <NEW_LINE> <INDENT> return self.__s_callsign
CFlight event class
6259904b379a373c97d9a41d
class AccountViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> lookup_field = 'username' <NEW_LINE> queryset = Account.objects.all() <NEW_LINE> serializer_class = AccountSerializer <NEW_LINE> def get_permissions(self): <NEW_LINE> <INDENT> if self.request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return (permissions.AllowAny(),) <NEW_LINE> <DEDENT> if self.request.method == 'POST': <NEW_LINE> <INDENT> return (permissions.AllowAny(),) <NEW_LINE> <DEDENT> return (permissions.IsAuthenticated(), IsAccountOwner(),) <NEW_LINE> <DEDENT> def create(self, request): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> Account.objects.create_user(**serializer.validated_data) <NEW_LINE> return Response(serializer.validated_data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response({ 'status': 'Bad request', 'message': 'Account creation request was invalid.' }, status=status.HTTP_400_BAD_REQUEST)
Combined RESTful view for Account model.
6259904b07d97122c4218096
class Finding(Ebay): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Finding, self).__init__(**kwargs) <NEW_LINE> domain = 'svcs.sandbox.ebay.com' if self.sandbox else 'svcs.ebay.com' <NEW_LINE> new = { 'siteid': self.global_ids[self.kwargs['country']]['countryabbr'], 'domain': domain, 'version': '1.0.0', 'compatibility': '1.0.0', } <NEW_LINE> self.kwargs.update(new) <NEW_LINE> self.api = finding(**self.kwargs) <NEW_LINE> <DEDENT> def search(self, options): <NEW_LINE> <INDENT> verb = options.pop('verb', 'findItemsAdvanced') <NEW_LINE> return self.execute(verb, options) <NEW_LINE> <DEDENT> def parse(self, response): <NEW_LINE> <INDENT> items = [] <NEW_LINE> currency = self.global_ids[self.kwargs['country']]['currency'] <NEW_LINE> result = Andand(response).searchResult.item([]) <NEW_LINE> pages = Andand(response).paginationOutput.totalPages(0) <NEW_LINE> if result and hasattr(result, 'update'): <NEW_LINE> <INDENT> result = [result] <NEW_LINE> <DEDENT> for r in result: <NEW_LINE> <INDENT> date_time = du_parse(r['listingInfo']['endTime']) <NEW_LINE> end_date = date_time.strftime("%Y-%m-%d") <NEW_LINE> end_time = date_time.strftime("%H:%M") <NEW_LINE> offset_years = int(date_time.strftime("%Y")) - 2010 <NEW_LINE> year_in_sec = offset_years * 365 * 24 * 60 * 60 <NEW_LINE> days_in_sec = int(date_time.strftime("%j")) * 24 * 60 * 60 <NEW_LINE> hours_in_sec = int(date_time.strftime("%H")) * 60 * 60 <NEW_LINE> minutes_in_sec = int(date_time.strftime("%M")) * 60 <NEW_LINE> secs_in_sec = int(date_time.strftime("%S")) <NEW_LINE> args = [year_in_sec, days_in_sec, hours_in_sec, minutes_in_sec] <NEW_LINE> args.append(secs_in_sec) <NEW_LINE> end_date_time = sum(args) <NEW_LINE> price = float(Andand(r).sellingStatus.currentPrice.value(0)) <NEW_LINE> buy_now_price = float(Andand(r).listingInfo.buyItNowPrice.value(0)) <NEW_LINE> shipping = float( Andand(r).shippingInfo.shippingServiceCost.value(0)) <NEW_LINE> condition = Andand(r).condition.conditionDisplayName() <NEW_LINE> price_and_shipping = price + shipping <NEW_LINE> buy_now_price_and_shipping = buy_now_price + shipping <NEW_LINE> item = { 'id': str(r['itemId']), 'url': r['viewItemURL'], 'title': r['title'], 'condition': condition, 'item_type': r['listingInfo']['listingType'], 'price': price, 'buy_now_price': buy_now_price, 'shipping': shipping, 'price_and_shipping': price_and_shipping, 'buy_now_price_and_shipping': buy_now_price_and_shipping, 'end_date_time': end_date_time, 'end_date': end_date, 'end_time': end_time, 'country': self.kwargs['country'], 'currency': currency, } <NEW_LINE> items.append(item) <NEW_LINE> <DEDENT> results = {r['id']: r for r in items} <NEW_LINE> message = response.get('message') <NEW_LINE> return {'results': results, 'pages': pages, 'message': message}
An eBay Finding API object
6259904b8e05c05ec3f6f854
class ImageRepository(ATCTBTreeFolder): <NEW_LINE> <INDENT> implements(IImageRepository) <NEW_LINE> schema = ImageRepositorySchema <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> __implements__ = updateInterfaces(ATCTBTreeFolder.__implemented__, IATBTreeFolder)
A repository to store images.
6259904b24f1403a926862c7
class RMda(RPackage): <NEW_LINE> <INDENT> homepage = "https://cran.r-project.org/package=mda" <NEW_LINE> url = "https://cran.r-project.org/src/contrib/mda_0.4-9.tar.gz" <NEW_LINE> list_url = "https://cran.r-project.org/src/contrib/Archive/mda" <NEW_LINE> version('0.4-9', '2ce1446c4a013e0ebcc1099a00269ad9') <NEW_LINE> depends_on('r@1.9.0:') <NEW_LINE> depends_on('r-class', type=('build', 'run'))
Mixture and flexible discriminant analysis, multivariate adaptive regression splines (MARS), BRUTO.
6259904b94891a1f408ba0ef
class DagsterExecutionPlanSnapshotNotFoundError(DagsterError): <NEW_LINE> <INDENT> pass
Thrown when an expected execution plan snapshot could not be found on a PipelineRun.
6259904be76e3b2f99fd9dff
class Layer_Dropout: <NEW_LINE> <INDENT> def __init__(self, rate): <NEW_LINE> <INDENT> self.rate = 1 - rate <NEW_LINE> <DEDENT> def forward(self, values, training=True): <NEW_LINE> <INDENT> self.input = values <NEW_LINE> if not training: <NEW_LINE> <INDENT> self.output = values.copy() <NEW_LINE> return <NEW_LINE> <DEDENT> self.binary_mask = np.random.binomial( 1, self.rate, size=values.shape) / self.rate <NEW_LINE> self.output = values * self.binary_mask <NEW_LINE> <DEDENT> def backward(self, dvalues): <NEW_LINE> <INDENT> self.dvalues = dvalues * self.binary_mask <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"Dropout: rate: {self.rate}"
Layer_Dropout(rate) rate = amount of neurons you intend to disable
6259904bd10714528d69f087
class Md5Test(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.target = '.unittest.md5' <NEW_LINE> self.md5 = '098f6bcd4621d373cade4e832627b4f6' <NEW_LINE> open(self.target, 'w').write("test") <NEW_LINE> <DEDENT> def test_md5(self): <NEW_LINE> <INDENT> self.assertEqual(checksum.md5(self.target), self.md5, 'md5 checksum') <NEW_LINE> os.chmod(self.target, 0) <NEW_LINE> self.assertEqual(checksum.md5(self.target), None, 'file access check') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> os.remove(self.target)
test md5 module
6259904b73bcbd0ca4bcb67c
class RNNEncoder(NeuralLayer): <NEW_LINE> <INDENT> def __init__(self, hidden_size, keep_prob): <NEW_LINE> <INDENT> self.hidden_size = hidden_size <NEW_LINE> self.keep_prob = keep_prob <NEW_LINE> self.rnn_cell_fw = tf.contrib.rnn.GRUCell(self.hidden_size) <NEW_LINE> self.rnn_cell_fw = tf.contrib.rnn.DropoutWrapper(self.rnn_cell_fw, input_keep_prob=self.keep_prob) <NEW_LINE> self.rnn_cell_bw = tf.contrib.rnn.GRUCell(self.hidden_size) <NEW_LINE> self.rnn_cell_bw = tf.contrib.rnn.DropoutWrapper(self.rnn_cell_bw, input_keep_prob=self.keep_prob) <NEW_LINE> <DEDENT> def build_graph(self, inputs, masks): <NEW_LINE> <INDENT> with vs.variable_scope("RNNEncoder"): <NEW_LINE> <INDENT> input_lens = tf.reduce_sum(masks, reduction_indices=1) <NEW_LINE> (fw_out, bw_out), _ = tf.nn.bidirectional_dynamic_rnn(self.rnn_cell_fw, self.rnn_cell_bw, inputs, input_lens, dtype=tf.float32) <NEW_LINE> out = tf.concat([fw_out, bw_out], 2) <NEW_LINE> out = tf.nn.dropout(out, self.keep_prob) <NEW_LINE> return out
General-purpose module to encode a sequence using a RNN. It feeds the input through a RNN and returns all the hidden states. Note: In lecture 8, we talked about how you might use a RNN as an "encoder" to get a single, fixed size vector representation of a sequence (e.g. by taking element-wise max of hidden states). Here, we're using the RNN as an "encoder" but we're not taking max; we're just returning all the hidden states. The terminology "encoder" still applies because we're getting a different "encoding" of each position in the sequence, and we'll use the encodings downstream in the model. This code uses a bidirectional GRU, but you could experiment with other types of RNN.
6259904bdc8b845886d549b1
class Kwant: <NEW_LINE> <INDENT> def __init__(self, rent): <NEW_LINE> <INDENT> self.rent = rent <NEW_LINE> self.ked_s = [] <NEW_LINE> self.esy_leeff = False <NEW_LINE> self.trgr_d = False <NEW_LINE> self.trgr_ked = Gleff_s.d <NEW_LINE> self.kan_hasy = set([Gleff_s.t, Gleff_s.d, Gleff_s.f])
container for one or more leeff nods representing a quantity
6259904b1f037a2d8b9e5266
class User(AbstractUser): <NEW_LINE> <INDENT> name = CharField(_("Name of User"), blank=True, max_length=255) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse("users:detail", kwargs={"username": self.username})
Default user for wgblog.
6259904bb5575c28eb7136c3
class _GradientNorm(StoppingCriteria): <NEW_LINE> <INDENT> def __init__(self, epsilon): <NEW_LINE> <INDENT> self.epsilon = epsilon <NEW_LINE> <DEDENT> def stopping_criterion(self, x, objective, **kwargs): <NEW_LINE> <INDENT> g = objective.gradient(x) <NEW_LINE> return np.linalg.norm(g) <= self.epsilon
Check if the L2 norm of the gradient is small Use the fact that, f(x) - f(x*) <= (1/2m)||g||_2^2 where g = gradient[f](x) m = strong convexity parameter of f
6259904b76d4e153a661dc71
class SigmaX(ObservableBase): <NEW_LINE> <INDENT> def __init__(self, absolute=False): <NEW_LINE> <INDENT> self.name = "SigmaX" <NEW_LINE> self.symbol = "X" <NEW_LINE> self.absolute = absolute <NEW_LINE> <DEDENT> def apply(self, nn_state, samples): <NEW_LINE> <INDENT> samples = samples.to(device=nn_state.device) <NEW_LINE> denom = nn_state.importance_sampling_denominator(samples) <NEW_LINE> numer_sum = torch.zeros_like(denom) <NEW_LINE> for i in range(samples.shape[-1]): <NEW_LINE> <INDENT> samples_ = flip_spin(i, samples.clone()) <NEW_LINE> numer = nn_state.importance_sampling_numerator(samples_, samples) <NEW_LINE> numer_sum.add_(numer) <NEW_LINE> <DEDENT> numer_sum = cplx.elementwise_division(numer_sum, denom) <NEW_LINE> res = cplx.real(numer_sum).div_(samples.shape[-1]) <NEW_LINE> if self.absolute: <NEW_LINE> <INDENT> return res.abs_() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return res
The :math:`\sigma_x` observable Computes the average magnetization in the X direction of a spin chain. :param absolute: Specifies whether to estimate the absolute magnetization. :type absolute: bool
6259904b50485f2cf55dc37f
class PoSTagger(Thread): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.kwargs = data <NEW_LINE> Thread.__init__(kwargs=data) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> import nltk <NEW_LINE> if not self.kwargs["sent"]: <NEW_LINE> <INDENT> raise RuntimeError("PosTagger expected 'sent' in the arguments, but it didn't find it.") <NEW_LINE> <DEDENT> sent = self.kwargs["sent"] <NEW_LINE> self.result = nltk.pos_tag(sent) <NEW_LINE> pass
Class that provides some functions/operations in multi-threads
6259904b0c0af96317c5775b
class DataGenerator(keras.utils.Sequence): <NEW_LINE> <INDENT> def __init__(self, data_path, dataset_name, batch_size=32, stop_after_batch=None): <NEW_LINE> <INDENT> self.data_file = h5py.File(data_path, "r") <NEW_LINE> self.X_name = "X_" + dataset_name <NEW_LINE> self.y_name = "y_" + dataset_name <NEW_LINE> self.n_examples = self.data_file[self.X_name + "_anchors"].shape[0] <NEW_LINE> self.example_length = self.data_file[self.X_name + "_anchors"].shape[1] <NEW_LINE> self.n_features = self.data_file[self.X_name + "_anchors"].shape[2] <NEW_LINE> self.n_classes = self.data_file[self.y_name + "_anchors"].shape[1] <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.indices = list(range(self.n_examples)) <NEW_LINE> self.stop_after_batch = stop_after_batch <NEW_LINE> self.on_epoch_end() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> if self.stop_after_batch is None: <NEW_LINE> <INDENT> return int(np.floor(self.n_examples / self.batch_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.stop_after_batch <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> indices = self.indices[index * self.batch_size: (index + 1) * self.batch_size] <NEW_LINE> self.this_batch_size = len(indices) <NEW_LINE> X, y = self.__data_generation(indices) <NEW_LINE> return X, y <NEW_LINE> <DEDENT> def on_epoch_end(self): <NEW_LINE> <INDENT> random.shuffle(self.indices) <NEW_LINE> <DEDENT> def __data_generation(self, indices): <NEW_LINE> <INDENT> X_boolean_mask = np.zeros((self.n_examples, self.example_length, self.n_features), dtype=bool) <NEW_LINE> X_boolean_mask[indices, :, :] = True <NEW_LINE> X_anchors = self.data_file[self.X_name + "_anchors"][X_boolean_mask].reshape((self.this_batch_size, self.example_length, self.n_features)) <NEW_LINE> X_positives = self.data_file[self.X_name + "_positives"][X_boolean_mask].reshape((self.this_batch_size, self.example_length, self.n_features)) <NEW_LINE> X_negatives = self.data_file[self.X_name + "_negatives"][X_boolean_mask].reshape((self.this_batch_size, self.example_length, self.n_features)) <NEW_LINE> y_dummy = np.zeros((self.this_batch_size,)) <NEW_LINE> return [X_anchors, X_positives, X_negatives], y_dummy
Reads data iteratively as batches from h5f file
6259904b0fa83653e46f62d2
class halfnorm_gen(rv_continuous): <NEW_LINE> <INDENT> def _rvs(self): <NEW_LINE> <INDENT> return abs(self._random_state.standard_normal(size=self._size)) <NEW_LINE> <DEDENT> def _pdf(self, x): <NEW_LINE> <INDENT> return np.sqrt(2.0/np.pi)*np.exp(-x*x/2.0) <NEW_LINE> <DEDENT> def _logpdf(self, x): <NEW_LINE> <INDENT> return 0.5 * np.log(2.0/np.pi) - x*x/2.0 <NEW_LINE> <DEDENT> def _cdf(self, x): <NEW_LINE> <INDENT> return _norm_cdf(x)*2-1.0 <NEW_LINE> <DEDENT> def _ppf(self, q): <NEW_LINE> <INDENT> return sc.ndtri((1+q)/2.0) <NEW_LINE> <DEDENT> def _stats(self): <NEW_LINE> <INDENT> return (np.sqrt(2.0/np.pi), 1-2.0/np.pi, np.sqrt(2)*(4-np.pi)/(np.pi-2)**1.5, 8*(np.pi-3)/(np.pi-2)**2) <NEW_LINE> <DEDENT> def _entropy(self): <NEW_LINE> <INDENT> return 0.5*np.log(np.pi/2.0)+0.5
A half-normal continuous random variable. %(before_notes)s Notes ----- The probability density function for `halfnorm` is: .. math:: f(x) = \sqrt{2/\pi} e^{-\frac{x^2}{2}} for :math:`x > 0`. `halfnorm` is a special case of :math`\chi` with ``df == 1``. %(after_notes)s %(example)s
6259904b3617ad0b5ee07533
class OrderAdapter(BaseOrderAdapter): <NEW_LINE> <INDENT> adapts(IOrder) <NEW_LINE> implements(IOrderAdapter) <NEW_LINE> def articles(self): <NEW_LINE> <INDENT> res = [] <NEW_LINE> utility = getUtility(IUnicodeUtility) <NEW_LINE> shopping_site = IShoppingSite(self.context) <NEW_LINE> vat_adapter = IVATAdapter(self.context) <NEW_LINE> for item in self.get_content_listing(IOrderArticle): <NEW_LINE> <INDENT> obj = item.getObject() <NEW_LINE> order_article_adapter = IOrderArticleAdapter(obj) <NEW_LINE> gross_subtotal = order_article_adapter.gross_subtotal() <NEW_LINE> items = { 'description': utility.safe_unicode(item.Description()), 'gross': item.gross, 'gross_subtotal': gross_subtotal, 'locale_gross_subtotal': shopping_site.format_money(gross_subtotal), 'image_url': None, 'obj': obj, 'quantity': item.quantity, 'sku': item.sku, 'title': utility.safe_unicode(item.Title()), 'url': None, 'vat_rate': vat_adapter.percent(item.vat_rate), 'id': item.getId(), } <NEW_LINE> orig_article = shopping_site.get_object(IArticle, path=shopping_site.portal_path(), UID=item.getId()) <NEW_LINE> if orig_article: <NEW_LINE> <INDENT> items['url'] = orig_article.absolute_url() <NEW_LINE> items['image_url'] = IArticleAdapter(orig_article).image_url(size='mini') <NEW_LINE> <DEDENT> res.append(items) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def articles_total(self): <NEW_LINE> <INDENT> registry = getUtility(IRegistry) <NEW_LINE> currency = registry.forInterface(ICurrency).default_currency <NEW_LINE> res = Money(0.00, currency=currency) <NEW_LINE> for item in self.articles(): <NEW_LINE> <INDENT> res += item['gross_subtotal'] <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def shipping_method(self): <NEW_LINE> <INDENT> return self.get_brain(IOrderShippingMethod, depth=1, unrestricted=True) <NEW_LINE> <DEDENT> def locale_shipping_method(self): <NEW_LINE> <INDENT> shipping_method = self.shipping_method() <NEW_LINE> if shipping_method: <NEW_LINE> <INDENT> return { 'gross': IShoppingSite(self.context).format_money(shipping_method.gross), 'is_free': shipping_method.gross.amount == 0.0, 'title': shipping_method.Title, 'vat_rate': shipping_method.vat_rate, } <NEW_LINE> <DEDENT> <DEDENT> def total(self): <NEW_LINE> <INDENT> total = self.articles_total() <NEW_LINE> shipping_method = self.shipping_method() <NEW_LINE> if shipping_method and shipping_method.gross: <NEW_LINE> <INDENT> total += shipping_method.gross <NEW_LINE> <DEDENT> return total <NEW_LINE> <DEDENT> def get_address(self, name): <NEW_LINE> <INDENT> if name == 'shipping' and self.context.billing_same_as_shipping: <NEW_LINE> <INDENT> name = 'billing' <NEW_LINE> <DEDENT> return self.get_brain(ICustomerInfo, depth=1, id=name)
Adapter for content type: collective.cart.core.Order
6259904b8e71fb1e983bceba
class CaseLoggerPlugin(object): <NEW_LINE> <INDENT> @pytest.hookimpl(tryfirst=True, hookwrapper=True) <NEW_LINE> def pytest_runtest_makereport(self, item, call): <NEW_LINE> <INDENT> yield <NEW_LINE> if call.when == "call": <NEW_LINE> <INDENT> item.excinfo = call.excinfo <NEW_LINE> <DEDENT> <DEDENT> @pytest.fixture(autouse=True, scope=setup_scope()) <NEW_LINE> def suitelogger(self, request, env_main): <NEW_LINE> <INDENT> case_logger = CaseLoggerExecutor(env_main) <NEW_LINE> request.addfinalizer(case_logger.suite_teardown) <NEW_LINE> return case_logger <NEW_LINE> <DEDENT> @pytest.fixture(autouse=True) <NEW_LINE> def caselogger(self, request, suitelogger, env): <NEW_LINE> <INDENT> suitelogger.node = request.node <NEW_LINE> suitelogger.suite_name = request.node.module.__name__ <NEW_LINE> request.addfinalizer(suitelogger.case_teardown) <NEW_LINE> suitelogger.case_setup()
Base class for caselogger plugin functionality.
6259904bac7a0e7691f738d0
class AudioNN(nn.Module): <NEW_LINE> <INDENT> def __init__(self, base_input_size=6373, input_size=300, hidden_size=64, dropout=0.5, audio_model='saved_models/audio_model'): <NEW_LINE> <INDENT> super(AudioNN, self).__init__() <NEW_LINE> self.lin = nn.Linear(base_input_size, input_size) <NEW_LINE> self.relu = nn.ReLU() <NEW_LINE> self.dropout = nn.Dropout(dropout) <NEW_LINE> self.audio_model = torch.load(audio_model) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> en, de = self.audio_model(x) <NEW_LINE> en = self.relu(en) <NEW_LINE> out = self.dropout(en) <NEW_LINE> return out
NN that trains audio features - used for signular model (may remove through nn for complete model)
6259904bd53ae8145f919856
class TestUpdateSkills(APITestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.profile = create_profile(0) <NEW_LINE> self.skill1 = create_skill("Python") <NEW_LINE> self.skill2 = create_skill("PHP") <NEW_LINE> self.skill3 = create_skill("HTML") <NEW_LINE> self.profile_skill1 = ProfileSkill.objects.create( skill=self.skill1, profile=self.profile ) <NEW_LINE> self.profile_skill2 = ProfileSkill.objects.create( skill=self.skill2, profile=self.profile ) <NEW_LINE> <DEDENT> def test_update_skills(self): <NEW_LINE> <INDENT> current_skills = ProfileSkill.objects.filter(profile=self.profile) <NEW_LINE> self.assertEqual(len(current_skills), 2) <NEW_LINE> token = api_login(self.profile.user) <NEW_LINE> data = {'skills': [self.skill3.id]} <NEW_LINE> url = reverse('update-skills') <NEW_LINE> self.client.put(url, data, format="json", HTTP_AUTHORIZATION='Token {}'.format(token)) <NEW_LINE> current_skills = ProfileSkill.objects.filter(profile=self.profile) <NEW_LINE> self.assertEqual(len(current_skills), 1) <NEW_LINE> self.assertEqual(current_skills[0].skill.title, "HTML")
Model tests for updating skills
6259904b498bea3a75a58f15
class Package(object): <NEW_LINE> <INDENT> def __init__(self, options={}): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> <DEDENT> def start(self, path=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base abstact analysis package.
6259904bbaa26c4b54d5069f