code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class UploadPart(object): <NEW_LINE> <INDENT> def __init__(self, mpu, fp, partnum, chunks): <NEW_LINE> <INDENT> self.mpu = mpu <NEW_LINE> self.partnum = partnum <NEW_LINE> self.fp = fp <NEW_LINE> self.size = 0 <NEW_LINE> self.chunks = chunks <NEW_LINE> self.etag = {} <NEW_LINE> self.success = True | The class for the upload part | 62598fb0a219f33f346c684f |
class UtilsTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_define_mass_bins(self): <NEW_LINE> <INDENT> mbins = utils.define_mass_bins(low=1, high=100, dm_low=1, dm_high=1.) <NEW_LINE> tmp = np.arange(1, 101) <NEW_LINE> np.testing.assert_array_almost_equal(mbins, tmp) | Tests from 'utils.py'. | 62598fb07d847024c075c3fd |
class Operations: <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer) -> None: <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> def list( self, **kwargs: Any ) -> AsyncIterable["_models.StoragePoolOperationListResult"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2021-08-01" <NEW_LINE> accept = "application/json" <NEW_LINE> def prepare_request(next_link=None): <NEW_LINE> <INDENT> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> if not next_link: <NEW_LINE> <INDENT> url = self.list.metadata['url'] <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = next_link <NEW_LINE> query_parameters = {} <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> <DEDENT> return request <NEW_LINE> <DEDENT> async def extract_data(pipeline_response): <NEW_LINE> <INDENT> deserialized = self._deserialize('StoragePoolOperationListResult', pipeline_response) <NEW_LINE> list_of_elem = deserialized.value <NEW_LINE> if cls: <NEW_LINE> <INDENT> list_of_elem = cls(list_of_elem) <NEW_LINE> <DEDENT> return None, AsyncList(list_of_elem) <NEW_LINE> <DEDENT> async def get_next(next_link=None): <NEW_LINE> <INDENT> request = prepare_request(next_link) <NEW_LINE> pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> error = self._deserialize.failsafe_deserialize(_models.Error, response) <NEW_LINE> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> return pipeline_response <NEW_LINE> <DEDENT> return AsyncItemPaged( get_next, extract_data ) <NEW_LINE> <DEDENT> list.metadata = {'url': '/providers/Microsoft.StoragePool/operations'} | Operations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~storage_pool_management.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer. | 62598fb091f36d47f2230ec4 |
class StopWordFilter(TransformBase): <NEW_LINE> <INDENT> def __init__(self, stopwords, flgset=set()): <NEW_LINE> <INDENT> super(StopWordFilter, self).__init__(flgset, filt_run) <NEW_LINE> self.stopwords = set(stopwords) <NEW_LINE> <DEDENT> def tkn_processor(self, tkn, tag=None): <NEW_LINE> <INDENT> rtkn, flg = self.flg_splitr.split(tkn) <NEW_LINE> if rtkn in self.stopwords: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Usage: Remove stopwords | 62598fb099cbb53fe6830f13 |
class ResNeXt(ResNet, nn.Module): <NEW_LINE> <INDENT> def __init__(self, depth: int, pretrained: bool = False): <NEW_LINE> <INDENT> if depth not in (50, 101): <NEW_LINE> <INDENT> raise ValueError(f"invalid depth specified. depth must be one of 50, 101 got {depth}") <NEW_LINE> <DEDENT> super(ResNet, self).__init__() <NEW_LINE> self.model_repr = f"resnext{depth}_32x{4 * (depth // 50)}d" <NEW_LINE> self.pretrained = pretrained <NEW_LINE> self._register_layers() | Implements ResNeXt backbone for retinanet.
Args:
depth (int): depth for resnet, either 50 or 101
pretrained (bool): whether to load pretrained ImageNet weights | 62598fb05fcc89381b266169 |
class IThemeSpecific(IDefaultPloneLayer): <NEW_LINE> <INDENT> pass | Marker interface that defines a Zope 3 browser layer.
If you need to register a viewlet only for the
"ploneorgbr.portal.theme" theme,
this interface must be its layer. | 62598fb038b623060ffa90d6 |
class Config(object): <NEW_LINE> <INDENT> def __init__(self,file): <NEW_LINE> <INDENT> super(Config, self).__init__() <NEW_LINE> config_path = os.path.abspath(__file__) <NEW_LINE> config_file = config_path.replace("config_setup.py", file) <NEW_LINE> with open(config_file) as json_data: <NEW_LINE> <INDENT> self.__dict__ = json.load(json_data) <NEW_LINE> json_data.close() | docstring for Config. | 62598fb03539df3088ecc2ed |
class AddTag(TagCommand): <NEW_LINE> <INDENT> SYNOPSIS = (None, 'tags/add', 'tags/add', '<tag>') <NEW_LINE> ORDER = ('Tagging', 0) <NEW_LINE> HTTP_CALLABLE = ('GET', 'POST') <NEW_LINE> HTTP_POST_VARS = { 'name': 'tag name', 'slug': 'tag slug', 'icon': 'icon-tag', 'label': 'display as label in search results, or not', 'label_color': 'the color of the label', 'display': 'tag display type', 'template': 'tag template type', 'search_terms': 'default search associated with this tag', 'magic_terms': 'magic search terms associated with this tag', 'parent': 'parent tag ID', } <NEW_LINE> COMMAND_SECURITY = security.CC_CHANGE_TAGS <NEW_LINE> OPTIONAL_VARS = ['icon', 'label', 'label_color', 'display', 'template', 'search_terms', 'parent'] <NEW_LINE> class CommandResult(TagCommand.CommandResult): <NEW_LINE> <INDENT> def as_text(self): <NEW_LINE> <INDENT> if not self.result: <NEW_LINE> <INDENT> return 'Failed' <NEW_LINE> <DEDENT> if not self.result['added']: <NEW_LINE> <INDENT> return 'Nothing happened' <NEW_LINE> <DEDENT> return ('Added tags: ' + ', '.join([k['name'] for k in self.result['added']])) <NEW_LINE> <DEDENT> <DEDENT> def command(self, save=True): <NEW_LINE> <INDENT> config = self.session.config <NEW_LINE> if self.data.get('_method', 'not-http').upper() == 'GET': <NEW_LINE> <INDENT> return self._success(_('Add tags here!'), { 'form': self.HTTP_POST_VARS, 'rules': self.session.config.tags.rules['_any'][1] }) <NEW_LINE> <DEDENT> slugs = self.data.get('slug', []) <NEW_LINE> names = self.data.get('name', []) <NEW_LINE> if slugs and len(names) != len(slugs): <NEW_LINE> <INDENT> return self._error('Name/slug pairs do not match') <NEW_LINE> <DEDENT> elif names and not slugs: <NEW_LINE> <INDENT> slugs = [Slugify(n, config.tags) for n in names] <NEW_LINE> <DEDENT> slugs.extend([Slugify(s, config.tags) for s in self.args]) <NEW_LINE> names.extend(self.args) <NEW_LINE> for slug in slugs: <NEW_LINE> <INDENT> if slug != Slugify(slug, config.tags): <NEW_LINE> <INDENT> return self._error('Invalid tag slug: %s' % slug) <NEW_LINE> <DEDENT> <DEDENT> for tag in config.tags.values(): <NEW_LINE> <INDENT> if tag.slug in slugs: <NEW_LINE> <INDENT> return self._error('Tag already exists: %s/%s' % (tag.slug, tag.name)) <NEW_LINE> <DEDENT> <DEDENT> tags = [{'name': n, 'slug': s} for (n, s) in zip(names, slugs)] <NEW_LINE> for v in self.OPTIONAL_VARS: <NEW_LINE> <INDENT> for i in range(0, len(tags)): <NEW_LINE> <INDENT> vlist = self.data.get(v, []) <NEW_LINE> if len(vlist) > i and vlist[i]: <NEW_LINE> <INDENT> tags[i][v] = vlist[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if tags: <NEW_LINE> <INDENT> config.tags.extend(tags) <NEW_LINE> if save: <NEW_LINE> <INDENT> self._reorder_all_tags() <NEW_LINE> <DEDENT> self.finish(save=save) <NEW_LINE> <DEDENT> results = [] <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> results.append(GetTagInfo(self.session.config, tag['slug'])) <NEW_LINE> <DEDENT> return self._success(_('Added %d tags') % len(results), {'added': results}) | Create a new tag | 62598fb05fc7496912d4829e |
class Lines: <NEW_LINE> <INDENT> def __init__(self, lines_start, lines_end, colors_start, colors_end, visible): <NEW_LINE> <INDENT> self.num_lines = lines_start.shape[0] <NEW_LINE> self.positions = np.empty((self.num_lines * 2, 3), dtype=lines_start.dtype) <NEW_LINE> self.positions[0::2] = lines_start <NEW_LINE> self.positions[1::2] = lines_end <NEW_LINE> self.colors = np.empty((self.num_lines * 2, 3), dtype=np.uint8) <NEW_LINE> self.colors[0::2] = colors_start <NEW_LINE> self.colors[1::2] = colors_end <NEW_LINE> self.visible = visible <NEW_LINE> <DEDENT> def get_properties(self, binary_filename): <NEW_LINE> <INDENT> json_dict = { 'type': 'lines', 'visible': self.visible, 'num_lines': self.num_lines, 'binary_filename': binary_filename} <NEW_LINE> return json_dict <NEW_LINE> <DEDENT> def write_binary(self, path): <NEW_LINE> <INDENT> bin_positions = self.positions.tobytes() <NEW_LINE> bin_colors = self.colors.tobytes() <NEW_LINE> with open(path, "wb") as f: <NEW_LINE> <INDENT> f.write(bin_positions) <NEW_LINE> f.write(bin_colors) | Set of line segments defined by startint points and ending points. | 62598fb0627d3e7fe0e06ee9 |
class ZeroPad2d(ConstantPad2d): <NEW_LINE> <INDENT> def __init__(self, padding): <NEW_LINE> <INDENT> super(ZeroPad2d, self).__init__(padding, 0) | 用零填充输入张量边界.
参数:
padding (int, tuple): 填充的大小. 如果是int,则在所有边界使用相同的填充.
. 如果是四个元组, 则使用 (paddingLeft, paddingRight, paddingTop, paddingBottom)
形态:
- Input: :math:`(N, C, H_{in}, W_{in})`
- Output: :math:`(N, C, H_{out}, W_{out})` where
:math:`H_{out} = H_{in} + paddingTop + paddingBottom`
:math:`W_{out} = W_{in} + paddingLeft + paddingRight`
实例::
>>> m = nn.ZeroPad2d(3)
>>> input = autograd.Variable(torch.randn(16, 3, 320, 480))
>>> output = m(input)
>>> # 使用不同的填充
>>> m = nn.ZeroPad2d((3, 3, 6, 6))
>>> output = m(input) | 62598fb063b5f9789fe851a3 |
class Quintly(Product): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = Product.Meta.ordering <NEW_LINE> <DEDENT> quintly_profile_id = models.IntegerField(verbose_name="Quintly Profil-ID") | Base model for Quintly data. | 62598fb0097d151d1a2c1066 |
class Span(object): <NEW_LINE> <INDENT> template_name = 'layout/field.html' <NEW_LINE> def __init__(self, span_columns, field_name): <NEW_LINE> <INDENT> self.span_columns = span_columns <NEW_LINE> self.field_name = field_name <NEW_LINE> <DEDENT> def render(self, context, **options): <NEW_LINE> <INDENT> template_pack = context['form_template_pack'] <NEW_LINE> form = context['form'] <NEW_LINE> bound_field = form[self.field_name] <NEW_LINE> try: <NEW_LINE> <INDENT> if 'template' in options: <NEW_LINE> <INDENT> template = select_template([ "{}/{}".format(template_pack, options['template']) ]) <NEW_LINE> <DEDENT> elif 'widget' in options: <NEW_LINE> <INDENT> widget_templates = [ '{}/fields/{}_{}.html'.format( template_pack, cls.__module__.split('.', 1)[0], cls.__name__.lower() ) for cls in type(options['widget']).mro()[:-2] ] <NEW_LINE> template = select_template(widget_templates) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template = _get_field_template( template_pack, bound_field.field) <NEW_LINE> <DEDENT> <DEDENT> except TemplateDoesNotExist: <NEW_LINE> <INDENT> warnings.warn("Unknown field and widget {} {}".format( bound_field.field.__class__, bound_field.field.widget.__class__)) <NEW_LINE> return smart_text(bound_field) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hidden_initial = '' <NEW_LINE> if bound_field.field.show_hidden_initial: <NEW_LINE> <INDENT> hidden_initial = bound_field.as_hidden(only_initial=True) <NEW_LINE> <DEDENT> context.push() <NEW_LINE> try: <NEW_LINE> <INDENT> context['bound_field'] = bound_field <NEW_LINE> context['field'] = bound_field.field <NEW_LINE> context['hidden_initial'] = hidden_initial <NEW_LINE> return template.render(context.flatten()) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> context.pop() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Span{}({})'.format(self.span_columns, self.field_name) | Wrapper for a field reference.
There are ``Span2``, ``Span3``, .., ``Span12`` shortcut classes.
``Layout`` autowraps string field references into Span(1, field_name)
:param span_columns: relative field width
:param field_name: field name in the form | 62598fb0a79ad1619776a0a3 |
@MetaborgReleng.subcommand("changed") <NEW_LINE> class MetaborgRelengChanged(cli.Application): <NEW_LINE> <INDENT> destination = cli.SwitchAttr(names=['-d', '--destination'], argtype=str, mandatory=False, default='.qualifier', help='Path to read/write the last qualifier to') <NEW_LINE> forceChange = cli.Flag(names=['-f', '--force-change'], default=False, help='Force a change, always return 0') <NEW_LINE> def main(self): <NEW_LINE> <INDENT> changed, qualifier = repo_changed(self.parent.repo, self.destination) <NEW_LINE> if self.forceChange or changed: <NEW_LINE> <INDENT> print(qualifier) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> return 1 | Returns 0 and prints the qualifer if repository has changed since last invocation of this command, based on the
current branch and latest commit date in all submodules. Returns 1 otherwise. | 62598fb04c3428357761a2f5 |
class BasePeople(object): <NEW_LINE> <INDENT> def __init__(self, name="no_name", play_id=0): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> self.__play_id = play_id <NEW_LINE> <DEDENT> def set_name(self, name): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> <DEDENT> def set_play_id(self, play_id): <NEW_LINE> <INDENT> self.__play_id = play_id <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> def get_play_id(self): <NEW_LINE> <INDENT> return self.__play_id | classdocs | 62598fb03346ee7daa337665 |
class Item(Base): <NEW_LINE> <INDENT> __tablename__ = 'item' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(80), nullable=False) <NEW_LINE> description = Column(String(250)) <NEW_LINE> category_id = Column(Integer, ForeignKey('category.id')) <NEW_LINE> category = relationship(Category) <NEW_LINE> user_id = Column(Integer, ForeignKey('user.id')) <NEW_LINE> user = relationship(User) <NEW_LINE> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return { 'name': self.name, 'description': self.description, 'id': self.id, 'category_id': self.category_id, 'user_id': self.user_id } | Item information stored in the database | 62598fb02ae34c7f260ab11d |
class NumpyHistogramMetric(Metric): <NEW_LINE> <INDENT> def __init__(self, max_value=10, **kwargs): <NEW_LINE> <INDENT> Metric.__init__(self, **kwargs) <NEW_LINE> self.counts = np.zeros(2+max_value, dtype=np.int_) <NEW_LINE> self.max_value = max_value <NEW_LINE> <DEDENT> def add(self, elem): <NEW_LINE> <INDENT> assert elem >= 0 <NEW_LINE> Metric.add(self, elem) <NEW_LINE> if elem > self.max_value: <NEW_LINE> <INDENT> self.counts[-1] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.counts[elem] += 1 <NEW_LINE> <DEDENT> <DEDENT> def add_many(self, elems): <NEW_LINE> <INDENT> self.active = True <NEW_LINE> elems = np.copy(elems).astype(np.int_) <NEW_LINE> elems[elems > self.max_value] = 1 + self.max_value <NEW_LINE> self.counts += np.bincount(elems, minlength=len(self.counts)) <NEW_LINE> <DEDENT> def merge(self, metric): <NEW_LINE> <INDENT> assert self.max_value == metric.max_value <NEW_LINE> self.counts += metric.counts <NEW_LINE> <DEDENT> def report(self): <NEW_LINE> <INDENT> d = {str(k):int(v) for k, v in itertools.izip(xrange(0, 1 + self.max_value), self.counts)} <NEW_LINE> d[">%d" % self.max_value] = int(self.counts[-1]) <NEW_LINE> return d | A histogram with bins of size 1 and a final bin containing elements > max_value | 62598fb056ac1b37e6302226 |
class TestingConfig(BaseConfig): <NEW_LINE> <INDENT> pass | Configuracion de prueba | 62598fb057b8e32f52508139 |
class AfatConfig(AppConfig): <NEW_LINE> <INDENT> name = "afat" <NEW_LINE> label = "afat" <NEW_LINE> verbose_name = f"AFAT - Another Fleet Activity Tracker v{__version__}" | General config | 62598fb08a43f66fc4bf21b7 |
class GitInstall(object): <NEW_LINE> <INDENT> def __init__(self, repo, git=None): <NEW_LINE> <INDENT> self.repo = repo <NEW_LINE> self._temp_dir = Tempdir() <NEW_LINE> self._opened = False <NEW_LINE> self._git = git or Git() <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> if not self._opened: <NEW_LINE> <INDENT> self.temp_dir = self._temp_dir.open() <NEW_LINE> self._git.clone(self.repo, self.temp_dir) <NEW_LINE> self._opened = True <NEW_LINE> <DEDENT> return self.temp_dir <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self.open() <NEW_LINE> <DEDENT> def install(self): <NEW_LINE> <INDENT> with pushd(self.open()): <NEW_LINE> <INDENT> sh([sys.executable, self.temp_dir.joinpath('setup.py'), 'install']) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self._opened: <NEW_LINE> <INDENT> raise ValueError('Cannot close a unopened instance') <NEW_LINE> <DEDENT> self._temp_dir.close() <NEW_LINE> self._opened = False <NEW_LINE> <DEDENT> def __exit__(self, exc_value, exc_type, tb): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if exc_value is None: <NEW_LINE> <INDENT> self.install() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.open() <NEW_LINE> self.install() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def patch(self, patch_file, *args, **kw): <NEW_LINE> <INDENT> temp_dir = self.open() <NEW_LINE> strip = kw.pop('p', 1) <NEW_LINE> cmd = [which.patch, '--batch', '-p', str(strip), '-i', patch_file, '-d', temp_dir] <NEW_LINE> cmd.extend(args) <NEW_LINE> cmd.extend('--{}={}'.format(k, v) for k, v in kw.items()) <NEW_LINE> sh(cmd) | Tool to install a Python package by cloning its git repo and if
necessary modifying files inside.
Used as a context manager, it allows to run python code (for instance the
:class:`LineReplacer` on setup.py or installing patches, etc) after the
repo has been cloned and before the install. The value returned by entering
the context manager is the directory in which the repo has been cloned.
Example: add ``from sett.utils import *`` at the end of the ``__init__.py``
>>> from paver.easy import *
>>> with GitInstall('gitlab.enix.org:grocher/sett.git') as sett_dir:
... # Git repository is cloned
... with open(sett_dir.joinpath('sett/__init__.py', 'a+', encoding='utf-8')) as init:
... init.write('
from sett.utils import *
')
... # setup.py install is called
| 62598fb04e4d562566372462 |
class Truck(Vehicle): <NEW_LINE> <INDENT> wheels_number = 6 <NEW_LINE> def vehicle_type(self): <NEW_LINE> <INDENT> return ' '.join(['Truck', self.trademark, self.model]) | Heavy Truck. So brutal. Much wow. | 62598fb0a05bb46b3848a8a7 |
class FBTimeReferential (object): <NEW_LINE> <INDENT> kFBTimeReferentialAction=property(doc="Action. ") <NEW_LINE> kFBTimeReferentialShot=property(doc="Shot. ") <NEW_LINE> kFBTimeReferentialEdit=property(doc="Edit. ") <NEW_LINE> pass | FBCommandState.
| 62598fb0a219f33f346c6851 |
class NumberValidator(object): <NEW_LINE> <INDENT> def validate(self, password, user=None): <NEW_LINE> <INDENT> if not re.findall('\d', password): <NEW_LINE> <INDENT> raise ValidationError( _("The password must contain at least 1 digit, 0-9."), code='password_no_number', ) <NEW_LINE> <DEDENT> <DEDENT> def get_help_text(self): <NEW_LINE> <INDENT> return _( "Your password must contain at least 1 digit, 0-9." ) | Custom Password Validator: Checks if password contains atleast 1 Digit | 62598fb066656f66f7d5a42c |
class TransistionInline(admin.StackedInline): <NEW_LINE> <INDENT> model = models.Transition <NEW_LINE> extra = 0 | Allow adding a transistion when adding an answer. | 62598fb032920d7e50bc6090 |
class readme_exampleLanguageServerProtocol: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> from DHParser.lsp import gen_lsp_table <NEW_LINE> self.lsp_data = { 'processId': 0, 'rootUri': '', 'clientCapabilities': {}, 'serverInfo': { "name": "readme_example-Server", "version": "0.1" }, 'serverCapabilities': {} } <NEW_LINE> self.connection = None <NEW_LINE> self.cpu_bound = readme_exampleCPUBoundTasks(self.lsp_data) <NEW_LINE> self.blocking = readme_exampleBlockingTasks(self.lsp_data) <NEW_LINE> self.lsp_table = gen_lsp_table(self, prefix='lsp_') <NEW_LINE> self.lsp_fulltable = self.lsp_table.copy() <NEW_LINE> assert self.lsp_fulltable.keys().isdisjoint(self.cpu_bound.lsp_table.keys()) <NEW_LINE> self.lsp_fulltable.update(self.cpu_bound.lsp_table) <NEW_LINE> assert self.lsp_fulltable.keys().isdisjoint(self.blocking.lsp_table.keys()) <NEW_LINE> self.lsp_fulltable.update(self.blocking.lsp_table) <NEW_LINE> <DEDENT> def connect(self, connection): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> <DEDENT> def lsp_initialize(self, **kwargs): <NEW_LINE> <INDENT> self.lsp_data['processId'] = kwargs['processId'] <NEW_LINE> self.lsp_data['rootUri'] = kwargs['rootUri'] <NEW_LINE> self.lsp_data['clientCapabilities'] = kwargs['capabilities'] <NEW_LINE> return {'capabilities': self.lsp_data['serverCapabilities'], 'serverInfo': self.lsp_data['serverInfo']} <NEW_LINE> <DEDENT> def lsp_custom(self, **kwargs): <NEW_LINE> <INDENT> return kwargs <NEW_LINE> <DEDENT> def lsp_shutdown(self): <NEW_LINE> <INDENT> self.lsp_data['processId'] = 0 <NEW_LINE> self.lsp_data['rootUri'] = '' <NEW_LINE> self.lsp_data['clientCapabilities'] = {} <NEW_LINE> return {} | For the specification and implementation of the language server protocol, see:
https://code.visualstudio.com/api/language-extensions/language-server-extension-guide
https://microsoft.github.io/language-server-protocol/
https://langserver.org/ | 62598fb023849d37ff8510f0 |
class Normalize(nn.Module): <NEW_LINE> <INDENT> def __init__(self, norm_type='none', n_hidden=0): <NEW_LINE> <INDENT> super(Normalize, self).__init__() <NEW_LINE> self.norm_type = norm_type <NEW_LINE> if self.norm_type == 'layer_norm': <NEW_LINE> <INDENT> assert n_hidden > 0, '`n_hidden` cannot be zero for `layer_norm`.' <NEW_LINE> self.ln = nn.LayerNorm(n_hidden) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> if self.norm_type == 'layer_norm': <NEW_LINE> <INDENT> return self.ln(x) <NEW_LINE> <DEDENT> elif self.norm_type == 'norm': <NEW_LINE> <INDENT> return x / torch.norm(x, dim=-1, keepdim=True) <NEW_LINE> <DEDENT> elif self.norm_type == 'none': <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError('Invalid norm type "{}".'.format(self.norm_type)) | Various normalization schemes. | 62598fb0f7d966606f748022 |
class KaizenConfigError(Exception): <NEW_LINE> <INDENT> pass | Used when a configuration error occurs. | 62598fb060cbc95b0636438c |
class RawFieldValueError(RuntimeError): <NEW_LINE> <INDENT> pass | A raw field value is invalid.
Raw field value filters raise this exception if necessary. | 62598fb05fc7496912d4829f |
class DistanceMatrix(_Matrix): <NEW_LINE> <INDENT> def __init__(self, names, matrix=None): <NEW_LINE> <INDENT> _Matrix.__init__(self, names, matrix) <NEW_LINE> self._set_zero_diagonal() <NEW_LINE> <DEDENT> def __setitem__(self, item, value): <NEW_LINE> <INDENT> _Matrix.__setitem__(self, item, value) <NEW_LINE> self._set_zero_diagonal() <NEW_LINE> <DEDENT> def _set_zero_diagonal(self): <NEW_LINE> <INDENT> for i in range(0, len(self)): <NEW_LINE> <INDENT> self.matrix[i][i] = 0 <NEW_LINE> <DEDENT> <DEDENT> def format_phylip(self, handle): <NEW_LINE> <INDENT> handle.write(f" {len(self.names)}\n") <NEW_LINE> name_width = max(12, max(map(len, self.names)) + 1) <NEW_LINE> value_fmts = ("{" + str(x) + ":.4f}" for x in range(1, len(self.matrix) + 1)) <NEW_LINE> row_fmt = "{0:" + str(name_width) + "s}" + " ".join(value_fmts) + "\n" <NEW_LINE> for i, (name, values) in enumerate(zip(self.names, self.matrix)): <NEW_LINE> <INDENT> mirror_values = (self.matrix[j][i] for j in range(i + 1, len(self.matrix))) <NEW_LINE> fields = itertools.chain([name], values, mirror_values) <NEW_LINE> handle.write(row_fmt.format(*fields)) | Distance matrix class that can be used for distance based tree algorithms.
All diagonal elements will be zero no matter what the users provide. | 62598fb0236d856c2adc945c |
@implementer(IVocabularyFactory) <NEW_LINE> class AllowableContentTypesVocabulary(object): <NEW_LINE> <INDENT> def __call__(self, context): <NEW_LINE> <INDENT> site = getSite() <NEW_LINE> items = list(getAllowableContentTypes(site)) <NEW_LINE> if 'text/x-plone-outputfilters-html' in items: <NEW_LINE> <INDENT> items.remove('text/x-plone-outputfilters-html') <NEW_LINE> <DEDENT> items = [SimpleTerm(i, i, i) for i in sorted(items)] <NEW_LINE> return SimpleVocabulary(items) | Vocabulary factory for allowable content types.
A list of mime-types that can be used as input for textfields.
>>> from zope.component import queryUtility
>>> from plone.app.vocabularies.tests.base import create_context
>>> from plone.app.vocabularies.tests.base import DummyTool
>>> name = 'plone.app.vocabularies.AllowableContentTypes'
>>> util = queryUtility(IVocabularyFactory, name)
>>> context = create_context()
>>> tool = DummyTool('portal_transforms')
>>> def listAvailableTextInputs():
... return ('text/plain', 'text/spam')
>>> tool.listAvailableTextInputs = listAvailableTextInputs
>>> context.portal_transforms = tool
>>> types = util(context)
>>> types
<zope.schema.vocabulary.SimpleVocabulary object at ...>
>>> len(types.by_token)
2
>>> doc = types.by_token['text/plain']
>>> doc.title, doc.token, doc.value
('text/plain', 'text/plain', 'text/plain') | 62598fb0167d2b6e312b6fae |
class PrivateEndpointConnectionListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[PrivateEndpointConnection]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(PrivateEndpointConnectionListResult, self).__init__(**kwargs) <NEW_LINE> self.value = None <NEW_LINE> self.next_link = None | A list of private endpoint connections.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: Array of results.
:vartype value: list[~azure.mgmt.rdbms.postgresql.models.PrivateEndpointConnection]
:ivar next_link: Link to retrieve next page of results.
:vartype next_link: str | 62598fb056ac1b37e6302227 |
class DeleteGraphRuleView(DeleteView): <NEW_LINE> <INDENT> template_name = 'coverage/coverage_rule_delete.html' <NEW_LINE> model = GraphRule <NEW_LINE> slug_field = 'rule_name' <NEW_LINE> success_url = reverse_lazy('settings-graph-rules') <NEW_LINE> def get_object(self, queryset=None): <NEW_LINE> <INDENT> obj = super(DeleteGraphRuleView, self).get_object() <NEW_LINE> if not obj.created_by == self.request.user.email and not self.request.user.is_superuser: <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return obj | Delete Graph Rule View | 62598fb030bbd72246469997 |
class LongbowmanBlueprint(Blueprint): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("longbowman", 7, 80) <NEW_LINE> self.add_component(Health, 5) <NEW_LINE> self.add_component(Attack, 3, 4) <NEW_LINE> self.add_component(Movable, 3) | Used to create a copy of a Longbowman (Loyalist combat unit) | 62598fb04c3428357761a2f7 |
class TagDetail(TagMixin, RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> pass | Return a specific Tag, update it, or delete it. | 62598fb08e7ae83300ee90e0 |
class IProfile(Interface): <NEW_LINE> <INDENT> title = schema.TextLine( title=_(u"Title"), required=False, ) <NEW_LINE> customCategories = schema.Text( title=_(u"Custom Categories."), required=False, ) | Profile Type
| 62598fb097e22403b383af4b |
class GFKQuerySet(QuerySet): <NEW_LINE> <INDENT> def fetch_generic_relations(self, *args): <NEW_LINE> <INDENT> from actstream import settings as actstream_settings <NEW_LINE> qs = self._clone() <NEW_LINE> if not actstream_settings.FETCH_RELATIONS: <NEW_LINE> <INDENT> return qs <NEW_LINE> <DEDENT> gfk_fields = [g for g in self.model._meta.virtual_fields if isinstance(g, GenericForeignKey)] <NEW_LINE> if args: <NEW_LINE> <INDENT> gfk_fields = filter(lambda g: g.name in args, gfk_fields) <NEW_LINE> <DEDENT> if actstream_settings.USE_PREFETCH and hasattr(self, 'prefetch_related'): <NEW_LINE> <INDENT> return qs.prefetch_related(*[g.name for g in gfk_fields]) <NEW_LINE> <DEDENT> ct_map, data_map = {}, {} <NEW_LINE> for item in qs: <NEW_LINE> <INDENT> for gfk in gfk_fields: <NEW_LINE> <INDENT> if getattr(item, gfk.fk_field) is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ct_id_field = self.model._meta.get_field(gfk.ct_field).column <NEW_LINE> if getattr(item, ct_id_field) is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ct_map.setdefault(getattr(item, ct_id_field), {} )[smart_text(getattr(item, gfk.fk_field))] = (gfk.name, item.pk) <NEW_LINE> <DEDENT> <DEDENT> ctypes = ContentType.objects.in_bulk(ct_map.keys()) <NEW_LINE> for ct_id, items_ in ct_map.items(): <NEW_LINE> <INDENT> if ct_id: <NEW_LINE> <INDENT> ct = ctypes[ct_id] <NEW_LINE> model_class = ct.model_class() <NEW_LINE> objects = model_class._default_manager.select_related( depth=actstream_settings.GFK_FETCH_DEPTH) <NEW_LINE> for o in objects.filter(pk__in=items_.keys()): <NEW_LINE> <INDENT> (gfk_name, item_id) = items_[smart_text(o.pk)] <NEW_LINE> data_map[(ct_id, smart_text(o.pk))] = o <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for item in qs: <NEW_LINE> <INDENT> for gfk in gfk_fields: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if getattr(item, gfk.fk_field) is not None: <NEW_LINE> <INDENT> ct_id_field = self.model._meta.get_field(gfk.ct_field) .column <NEW_LINE> setattr(item, gfk.name, data_map[( getattr(item, ct_id_field), smart_text(getattr(item, gfk.fk_field)) )]) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return qs <NEW_LINE> <DEDENT> def none(self): <NEW_LINE> <INDENT> clone = self._clone(klass=EmptyGFKQuerySet) <NEW_LINE> clone.query.set_empty() <NEW_LINE> return clone | A QuerySet with a fetch_generic_relations() method to bulk fetch
all generic related items. Similar to select_related(), but for
generic foreign keys.
Based on http://www.djangosnippets.org/snippets/984/
Firstly improved at http://www.djangosnippets.org/snippets/1079/
Extended in django-activity-stream to allow for multi db, text primary keys
and empty querysets. | 62598fb0f548e778e596b5e1 |
class OtherWord(DataElementValue): <NEW_LINE> <INDENT> value = ArrayField(models.IntegerField(), blank=True, null=True) <NEW_LINE> raw = models.BinaryField(blank=True, null=True) | A :class:`~django.db.models.Model` representing a single *OtherWord*
data element value. | 62598fb0851cf427c66b82f9 |
class OBJECT_OT_ApplyRestoffset(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "mixamo.apply_restoffset" <NEW_LINE> bl_label = "Apply Restoffset" <NEW_LINE> bl_description = "Applies Restoffset to restpose and corrects animation" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> mixamo = context.scene.mixamo <NEW_LINE> if bpy.context.object == None: <NEW_LINE> <INDENT> self.report({'ERROR_INVALID_INPUT'}, "Error: no object selected.") <NEW_LINE> return{ 'CANCELLED'} <NEW_LINE> <DEDENT> if bpy.context.object.type != 'ARMATURE': <NEW_LINE> <INDENT> self.report({'ERROR_INVALID_INPUT'}, "Error: %s is not an Armature." % bpy.context.object.name) <NEW_LINE> return{ 'CANCELLED'} <NEW_LINE> <DEDENT> if bpy.context.object.data.bones[0].name not in ('mixamorig:Hips', 'mixamorig_Hips', 'Hips', mixamo.hipname): <NEW_LINE> <INDENT> self.report({'ERROR_INVALID_INPUT'}, "Selected object %s is not a Mixamo rig, or at least naming does not match!" % bpy.context.object.name) <NEW_LINE> return{ 'CANCELLED'} <NEW_LINE> <DEDENT> status = mixamoconv.apply_restoffset(bpy.context.object, bpy.context.object.data.bones[0], mixamo.restoffset) <NEW_LINE> if status == -1: <NEW_LINE> <INDENT> self.report({'ERROR_INVALID_INPUT'}, 'apply_restoffset Failed') <NEW_LINE> return{ 'CANCELLED'} <NEW_LINE> <DEDENT> return{ 'FINISHED'} | Button/Operator for converting single Rig | 62598fb010dbd63aa1c70bf1 |
class cs_buffer(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__rx_buffer = [] <NEW_LINE> <DEDENT> def get_num_rx(self): <NEW_LINE> <INDENT> return(len(self.__rx_buffer)) <NEW_LINE> <DEDENT> def add(self, packet): <NEW_LINE> <INDENT> if len(packet): <NEW_LINE> <INDENT> self.__rx_buffer.append(packet) <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.__rx_buffer = [] <NEW_LINE> <DEDENT> def find(self, match): <NEW_LINE> <INDENT> if len(self.__rx_buffer) == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> item = 0 <NEW_LINE> for x in self.__rx_buffer: <NEW_LINE> <INDENT> if x.find(match) == 0: <NEW_LINE> <INDENT> del(self.__rx_buffer[item]) <NEW_LINE> return x <NEW_LINE> <DEDENT> item = item + 1 <NEW_LINE> <DEDENT> return [] <NEW_LINE> packet = self.peek() <NEW_LINE> if len(packet): <NEW_LINE> <INDENT> self.__rx_buffer = self.__rx_buffer[1:] <NEW_LINE> return packet <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> packet = self.peek() <NEW_LINE> self.__rx_buffer = self.__rx_buffer[1:] <NEW_LINE> return packet <NEW_LINE> <DEDENT> def peek(self): <NEW_LINE> <INDENT> if len(self.__rx_buffer): <NEW_LINE> <INDENT> return(self.__rx_buffer[0]) <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> def get_buffer(self): <NEW_LINE> <INDENT> return self.__rx_buffer | Buffering for the packets received during downloading. | 62598fb085dfad0860cbfa92 |
class Blobs(Game): <NEW_LINE> <INDENT> moves = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.initial = GameState(to_move='R', utility=0, board=BlobsBoard(), moves=['L','R','U','D']) <NEW_LINE> self.currentState = self.initial <NEW_LINE> self.moves = self.initial.moves <NEW_LINE> <DEDENT> def actions(self, state): <NEW_LINE> <INDENT> return state.moves <NEW_LINE> <DEDENT> def result(self, state, move): <NEW_LINE> <INDENT> to_move = state.to_move <NEW_LINE> if(to_move == "R"): <NEW_LINE> <INDENT> to_move = "G" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_move = "R" <NEW_LINE> <DEDENT> newBoard = copy.copy(state.board) <NEW_LINE> newBoard.move(to_move, move) <NEW_LINE> return GameState(to_move = to_move, utility = self.compute_utility(newBoard, move, state.to_move), board = newBoard, moves = self.moves) <NEW_LINE> <DEDENT> def utility(self, state, player): <NEW_LINE> <INDENT> return state.utility <NEW_LINE> <DEDENT> def EVAL_FN1(self, state): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def EVAL_FN3(self,state): <NEW_LINE> <INDENT> if(state.to_move == "G"): <NEW_LINE> <INDENT> return (len(state.board.green_blobs) - len(state.board.red_blobs)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (len(state.board.red_blobs) - len(state.board.green_blobs)) <NEW_LINE> <DEDENT> <DEDENT> def terminal_test(self, state): <NEW_LINE> <INDENT> f= state.utility != 0 or len(state.board.green_blobs) == 0 or len(state.board.red_blobs) == 0 or state.board.left_border >= state.board.right_border or state.board.bottom_border >= state.board.top_border <NEW_LINE> return f <NEW_LINE> <DEDENT> def display(self, state): <NEW_LINE> <INDENT> print("to_move", state.to_move) <NEW_LINE> state.board.display() <NEW_LINE> <DEDENT> def to_move(self, state): <NEW_LINE> <INDENT> return state.to_move <NEW_LINE> <DEDENT> def compute_utility(self, board, move, player): <NEW_LINE> <INDENT> if(len(board.green_blobs) == 0): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if(len(board.red_blobs) == 0): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> def move(self, move): <NEW_LINE> <INDENT> self.currentState = self.result(self.currentState, move) | Play Blobs on an 6 x 6 board, with Max (first player) playing the red
Blobs with marker 'R'.
A state has the player to move, a cached utility, a list of moves in
the form of the four directions (left 'L', right 'R', up 'U', and down 'D'),
and a board, in the form of a BlobsBoard object.
Marker is 'R' for the Red Player and 'G' for the Green Player. An empty
position appear as '.' in the display and a 'o' represents an out of the
board position. | 62598fb076e4537e8c3ef5e5 |
class F(object): <NEW_LINE> <INDENT> def __init__(self, **filters): <NEW_LINE> <INDENT> filters = filters.items() <NEW_LINE> if len(filters) > 1: <NEW_LINE> <INDENT> self.filters = [{'and': filters}] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filters = filters <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<F {0}>'.format(self.filters) <NEW_LINE> <DEDENT> def _combine(self, other, conn='and'): <NEW_LINE> <INDENT> f = F() <NEW_LINE> self_filters = copy.deepcopy(self.filters) <NEW_LINE> other_filters = copy.deepcopy(other.filters) <NEW_LINE> if not self.filters: <NEW_LINE> <INDENT> f.filters = other_filters <NEW_LINE> <DEDENT> elif not other.filters: <NEW_LINE> <INDENT> f.filters = self_filters <NEW_LINE> <DEDENT> elif conn in self.filters[0]: <NEW_LINE> <INDENT> f.filters = self_filters <NEW_LINE> f.filters[0][conn].extend(other_filters) <NEW_LINE> <DEDENT> elif conn in other.filters[0]: <NEW_LINE> <INDENT> f.filters = other_filters <NEW_LINE> f.filters[0][conn].extend(self_filters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.filters = [{conn: self_filters + other_filters}] <NEW_LINE> <DEDENT> return f <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return self._combine(other, 'or') <NEW_LINE> <DEDENT> def __and__(self, other): <NEW_LINE> <INDENT> return self._combine(other, 'and') <NEW_LINE> <DEDENT> def __invert__(self): <NEW_LINE> <INDENT> f = F() <NEW_LINE> self_filters = copy.deepcopy(self.filters) <NEW_LINE> if len(self_filters) == 0: <NEW_LINE> <INDENT> f.filters = [] <NEW_LINE> <DEDENT> elif (len(self_filters) == 1 and isinstance(self_filters[0], dict) and self_filters[0].get('not', {}).get('filter', {})): <NEW_LINE> <INDENT> f.filters = self_filters[0]['not']['filter'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.filters = [{'not': {'filter': self_filters}}] <NEW_LINE> <DEDENT> return f | Filter objects.
Makes it easier to create filters cumulatively using ``&`` (and),
``|`` (or) and ``~`` (not) operations.
For example::
f = F()
f &= F(price='Free')
f |= F(style='Mexican')
creates a filter "price = 'Free' or style = 'Mexican'". | 62598fb06e29344779b0069a |
class Code(NameDescriptionMixin): <NEW_LINE> <INDENT> code_group = models.ForeignKey(CodeGroup, related_name="codes") <NEW_LINE> order = models.PositiveIntegerField() | Defines a single code | 62598fb01b99ca400228f54f |
class ColabAuthenticatedFileHandler(testing.AsyncHTTPTestCase): <NEW_LINE> <INDENT> def get_app(self): <NEW_LINE> <INDENT> self.temp_dir = tempfile.mkdtemp() <NEW_LINE> settings = { 'base_url': '/', 'local_hostnames': ['127.0.0.1'], } <NEW_LINE> app = web.Application([], **settings) <NEW_LINE> app.add_handlers('.*$', [ ('/files/(.*)', _files_handler.ColabAuthenticatedFileHandler, { 'path': self.temp_dir + '/' }), ]) <NEW_LINE> return app <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(ColabAuthenticatedFileHandler, self).tearDown() <NEW_LINE> shutil.rmtree(self.temp_dir) <NEW_LINE> <DEDENT> def testNonExistentFile(self): <NEW_LINE> <INDENT> response = self.fetch('/files/in/some/dir/foo.py') <NEW_LINE> self.assertEqual(http_client.NOT_FOUND, response.code) <NEW_LINE> <DEDENT> def testExistingDirectory(self): <NEW_LINE> <INDENT> os.makedirs(os.path.join(self.temp_dir, 'some/existing/dir')) <NEW_LINE> response = self.fetch('/files/some/existing/dir') <NEW_LINE> self.assertEqual(http_client.FORBIDDEN, response.code) <NEW_LINE> <DEDENT> def testExistingFile(self): <NEW_LINE> <INDENT> file_dir = os.path.join(self.temp_dir, 'some/existing/dir') <NEW_LINE> os.makedirs(file_dir) <NEW_LINE> with open(os.path.join(file_dir, 'foo.txt'), 'wb') as f: <NEW_LINE> <INDENT> f.write(b'Some content') <NEW_LINE> <DEDENT> response = self.fetch('/files/some/existing/dir/foo.txt') <NEW_LINE> self.assertEqual(http_client.OK, response.code) <NEW_LINE> self.assertEqual(b'Some content', response.body) <NEW_LINE> self.assertEqual(len(b'Some content'), int(response.headers['X-File-Size'])) <NEW_LINE> self.assertIn('text/plain', response.headers['Content-Type']) <NEW_LINE> <DEDENT> def testDoesNotAllowRequestsOutsideOfRootDir(self): <NEW_LINE> <INDENT> with open(os.path.join(self.temp_dir, '..', 'foo'), 'w') as f: <NEW_LINE> <INDENT> f.write('foo') <NEW_LINE> <DEDENT> with open(os.path.join(self.temp_dir, '..', 'bar'), 'w') as f: <NEW_LINE> <INDENT> f.write('bar') <NEW_LINE> <DEDENT> response = self.fetch('/files/../foo') <NEW_LINE> self.assertEqual(http_client.FORBIDDEN, response.code) <NEW_LINE> response = self.fetch('/files/foo/../../../bar') <NEW_LINE> self.assertEqual(http_client.FORBIDDEN, response.code) <NEW_LINE> response = self.fetch('/files/foo/../../bar') <NEW_LINE> self.assertEqual(http_client.FORBIDDEN, response.code) | Tests for ColabAuthenticatedFileHandler. | 62598fb04527f215b58e9f13 |
class CourseDetailView(View): <NEW_LINE> <INDENT> def get(self, request, course_id): <NEW_LINE> <INDENT> course = Courses.objects.get(id=course_id) <NEW_LINE> course.click_nums += 1 <NEW_LINE> course.save() <NEW_LINE> has_fav_course = False <NEW_LINE> has_fav_org = False <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if UserFavorite.objects.filter(user=request.user, fav_id=course_id, fav_type=1): <NEW_LINE> <INDENT> has_fav_course = True <NEW_LINE> <DEDENT> if UserFavorite.objects.filter(user=request.user, fav_id=course.course_org.id, fav_type=2): <NEW_LINE> <INDENT> has_fav_org = True <NEW_LINE> <DEDENT> <DEDENT> tag = course.tag <NEW_LINE> if tag: <NEW_LINE> <INDENT> relate_courses = Courses.objects.filter(tag=tag)[:1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> relate_courses = [] <NEW_LINE> <DEDENT> return render(request, 'course-detail.html', locals()) | 课程详情页 | 62598fb0cc40096d6161a1f8 |
class TreeNode(object): <NEW_LINE> <INDENT> tag = None <NEW_LINE> children = ( ) <NEW_LINE> def __init__(self, tag, children=( )): <NEW_LINE> <INDENT> self.tag = tag <NEW_LINE> self.children = children | An example tree node to play with. | 62598fb063d6d428bbee27ea |
class ColorPrint(object): <NEW_LINE> <INDENT> def __init__(self, silent=False): <NEW_LINE> <INDENT> self.silent = silent <NEW_LINE> <DEDENT> def R(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) <NEW_LINE> <DEDENT> <DEDENT> def G(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) <NEW_LINE> <DEDENT> <DEDENT> def B(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) <NEW_LINE> <DEDENT> <DEDENT> def C(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) <NEW_LINE> <DEDENT> <DEDENT> def Y(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) <NEW_LINE> <DEDENT> <DEDENT> def F(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) <NEW_LINE> <DEDENT> <DEDENT> def W(self, *args, sep=' ', end='\n', file=None): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> co_name = sys._getframe().f_code.co_name <NEW_LINE> term(*args, color=co_name, sep=sep, end=end, file=file) | if ``silent is true`` will print nothing.
- R: Red
- G: Green
- B: Blue
- C: Cyan
- Y: Yellow
- F: fuchsia
- W: White | 62598fb07d847024c075c401 |
class fakedQuantity: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.unit = Unit() <NEW_LINE> self.__class__ = Quantity | Faked Quantity class of TestQuantity2powers unittest. | 62598fb04428ac0f6e658564 |
class Solution1: <NEW_LINE> <INDENT> def sortedArrayToBST(self, nums: List[int]) -> TreeNode: <NEW_LINE> <INDENT> if not nums: return None <NEW_LINE> midIndex = len(nums) // 2 <NEW_LINE> root = TreeNode(nums[midIndex]) <NEW_LINE> if nums[:midIndex]: <NEW_LINE> <INDENT> root.left = self.sortedArrayToBST(nums[:midIndex]) <NEW_LINE> <DEDENT> if nums[midIndex + 1:]: <NEW_LINE> <INDENT> root.right = self.sortedArrayToBST(nums[midIndex + 1:]) <NEW_LINE> <DEDENT> return root | 将有序数组,通过中序遍历的划分方法,划分数组,数组左边的作为节点的左边节点,数组右边的作为节点的右边节点 | 62598fb0bf627c535bcb14dd |
class AutoExtensibleForm(AutoFields, ExtensibleForm): <NEW_LINE> <INDENT> implements(IAutoExtensibleForm) <NEW_LINE> @property <NEW_LINE> def schema(self): <NEW_LINE> <INDENT> raise NotImplementedError("The class deriving from AutoExtensibleForm must have a 'schema' property") <NEW_LINE> <DEDENT> @property <NEW_LINE> def additionalSchemata(self): <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> def updateFields(self): <NEW_LINE> <INDENT> self.updateFieldsFromSchemata() <NEW_LINE> super(AutoExtensibleForm, self).updateFields() | Mixin class for z3c.form forms that support fields extracted from
a schema | 62598fb016aa5153ce400541 |
class AllPages(): <NEW_LINE> <INDENT> def __init__(self,url): <NEW_LINE> <INDENT> self.url=url | This is a class for collecting data from a webpage. | 62598fb060cbc95b0636438e |
class ConfigIntegrationTest(TestCase): <NEW_LINE> <INDENT> def test_showconfig(self): <NEW_LINE> <INDENT> config_path = pathjoin(root(), "config.yml") <NEW_LINE> move(config_path, "/tmp/webagmes_webapi_config.yml") <NEW_LINE> old_stdout = sys.stdout <NEW_LINE> with open(config_path, "w") as tmpconfig: <NEW_LINE> <INDENT> sys.stdout = tmpconfig <NEW_LINE> export_default_config() <NEW_LINE> <DEDENT> sys.stdout = old_stdout <NEW_LINE> env = { "WEBAPI_LOG_LEVEL": "INFO", "REDIS_DSN": "redis://192.168.0.1:6379/0", "PGHOST": "192.168.0.2" } <NEW_LINE> command = [ sys.executable, "-m", "webapi", "showconfig", "--webapi_log_level", "DEBUG", "--postgres_host", "192.168.0.3" ] <NEW_LINE> process = Popen(command, env=env, stdout=PIPE) <NEW_LINE> process.wait() <NEW_LINE> move("/tmp/webagmes_webapi_config.yml", config_path) <NEW_LINE> process_output = process.stdout.read().decode() <NEW_LINE> process.stdout.close() <NEW_LINE> self.assertEqual(process.returncode, 0) <NEW_LINE> hard_blc = {} <NEW_LINE> proc_blc = {} <NEW_LINE> for blocks, source in ((hard_blc, OUTPUT), (proc_blc, process_output)): <NEW_LINE> <INDENT> for line in source.splitlines(): <NEW_LINE> <INDENT> if line.startswith("+"): <NEW_LINE> <INDENT> block_name = line.replace("+", "").replace("-", "") <NEW_LINE> if block_name: <NEW_LINE> <INDENT> blocks[block_name] = [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> blocks[block_name].append(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for block_name, lines in proc_blc.items(): <NEW_LINE> <INDENT> for line in lines: <NEW_LINE> <INDENT> self.assertIn(line, hard_blc[block_name]) | Test the entire module | 62598fb0167d2b6e312b6fb0 |
class DavosTestingError(Exception): <NEW_LINE> <INDENT> pass | Base class for Davos testing-related errors | 62598fb04a966d76dd5eef16 |
class UpgradeOperationHistoricalStatusInfo(Model): <NEW_LINE> <INDENT> _validation = { 'properties': {'readonly': True}, 'type': {'readonly': True}, 'location': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'properties': {'key': 'properties', 'type': 'UpgradeOperationHistoricalStatusInfoProperties'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(UpgradeOperationHistoricalStatusInfo, self).__init__(**kwargs) <NEW_LINE> self.properties = None <NEW_LINE> self.type = None <NEW_LINE> self.location = None | Virtual Machine Scale Set OS Upgrade History operation response.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar properties: Information about the properties of the upgrade
operation.
:vartype properties:
~azure.mgmt.compute.v2017_12_01.models.UpgradeOperationHistoricalStatusInfoProperties
:ivar type: Resource type
:vartype type: str
:ivar location: Resource location
:vartype location: str | 62598fb04f88993c371f052a |
class RandomPlanner(Planner): <NEW_LINE> <INDENT> def policy(self, state): <NEW_LINE> <INDENT> return random.choice(self.possible_actions) | A planner that takes actions at random. | 62598fb0dd821e528d6d8f74 |
class ESMTPRelayer(RelayerMixin, smtp.ESMTPClient): <NEW_LINE> <INDENT> def __init__(self, messagePaths, *args, **kw): <NEW_LINE> <INDENT> smtp.ESMTPClient.__init__(self, *args, **kw) <NEW_LINE> self.loadMessages(messagePaths) | A base class for ESMTP relayers. | 62598fb08da39b475be03225 |
class InactiveUsersView(generics.ListAPIView): <NEW_LINE> <INDENT> queryset = User.objects.filter(is_active=True) & ( User.objects.filter( last_login__lte=timezone.now() - timezone.timedelta(days=THREE_YEARS_IN_DAYS) ) | User.objects.filter( last_login__isnull=True, date_joined__lte=timezone.now() - timezone.timedelta(days=THREE_YEARS_IN_DAYS), ) ) <NEW_LINE> authentication_classes = (SessionAuthentication,) <NEW_LINE> serializer_class = InactiveUserSerializer <NEW_LINE> permission_classes = (IsAdminOrGoogleAppEngine,) <NEW_LINE> def delete(self, request: HttpRequest): <NEW_LINE> <INDENT> inactive_users = self.get_queryset() <NEW_LINE> for user in inactive_users: <NEW_LINE> <INDENT> anonymise(user) <NEW_LINE> <DEDENT> return Response(status=status.HTTP_204_NO_CONTENT) | This API view endpoint allows us to see our inactive users.
An inactive user is one that hasn't logged in for three years.
If the user has never logged in, we look at the date they registered with us instead. | 62598fb099cbb53fe6830f18 |
class PizzaMenuItemSerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> ingredients = serializers.PrimaryKeyRelatedField(many=True, queryset=PizzaIngredient.objects.all()) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = PizzaMenuItem <NEW_LINE> fields = ('id', 'name', 'ingredients') | This class is used to get the pizza menu items.
But it does not show ingredients.
TODO: add ingredients | 62598fb0009cb60464d01560 |
class GaussTubuleSelfLabeling_ne(NonEnsembleBase): <NEW_LINE> <INDENT> _model = models.gauss_convolved_coated_tubule_selflabeling_ne | This is for use with SNAP-tag and Halo tag labels, which result in an annulus of roughly 5 nm thickness | 62598fb0b7558d589546366a |
class ProdConfig(Config): <NEW_LINE> <INDENT> SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL") <NEW_LINE> SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://moringa:Muthoni.12@localhost/pitches' | Production configuration child class
Args:
Config: The parent configuration class with General configuration settings | 62598fb010dbd63aa1c70bf3 |
class BadKeyError(Error): <NEW_LINE> <INDENT> pass | Raised by Key.__str__ when the key_bk is invalid.
| 62598fb07d847024c075c402 |
class Common(object): <NEW_LINE> <INDENT> def __init__(self, verbose, version): <NEW_LINE> <INDENT> self.verbose = verbose <NEW_LINE> logger = logging.getLogger("Common.__init__") <NEW_LINE> logger.debug("") <NEW_LINE> self.version = version <NEW_LINE> self.appdata_path = appdirs.user_config_dir("FlockAgent") <NEW_LINE> <DEDENT> def get_resource_path(self, filename): <NEW_LINE> <INDENT> if getattr(sys, "flock_agent_dev", False): <NEW_LINE> <INDENT> prefix = os.path.join( os.path.dirname( os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe())) ) ), "share", ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if Platform.current() == Platform.MACOS: <NEW_LINE> <INDENT> prefix = os.path.join( os.path.dirname(os.path.dirname(sys.executable)), "Resources/share" ) <NEW_LINE> <DEDENT> elif Platform.current() == Platform.LINUX: <NEW_LINE> <INDENT> prefix = os.path.join(sys.prefix, "share/flock-agent") <NEW_LINE> <DEDENT> <DEDENT> resource_path = os.path.join(prefix, filename) <NEW_LINE> return resource_path | The Common class is a singleton of shared functionality throughout the app | 62598fb02c8b7c6e89bd3805 |
class Component(component.Component): <NEW_LINE> <INDENT> log = txaio.make_logger() <NEW_LINE> session = ApplicationSession <NEW_LINE> def _connect_transport(self, reactor, transport_config, session_factory): <NEW_LINE> <INDENT> transport_factory = _create_transport_factory(reactor, transport_config, session_factory) <NEW_LINE> transport_endpoint = _create_transport_endpoint(reactor, transport_config['endpoint']) <NEW_LINE> return transport_endpoint.connect(transport_factory) <NEW_LINE> <DEDENT> @inlineCallbacks <NEW_LINE> def start(self, reactor=None): <NEW_LINE> <INDENT> if reactor is None: <NEW_LINE> <INDENT> from twisted.internet import reactor <NEW_LINE> <DEDENT> yield self.fire('start', reactor, self) <NEW_LINE> transport_gen = itertools.cycle(self._transports) <NEW_LINE> reconnect = True <NEW_LINE> self.log.info('entering recomponent loop') <NEW_LINE> while reconnect: <NEW_LINE> <INDENT> transport = next(transport_gen) <NEW_LINE> if transport.can_reconnect(): <NEW_LINE> <INDENT> delay = transport.next_delay() <NEW_LINE> self.log.debug('trying transport {transport_idx} using connect delay {transport_delay}', transport_idx=transport.idx, transport_delay=delay) <NEW_LINE> yield sleep(delay) <NEW_LINE> try: <NEW_LINE> <INDENT> transport.connect_attempts += 1 <NEW_LINE> yield self._connect_once(reactor, transport.config) <NEW_LINE> transport.connect_sucesses += 1 <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> transport.connect_failures += 1 <NEW_LINE> self.log.error(u'component failed: {error}', error=e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reconnect = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not self._can_reconnect(): <NEW_LINE> <INDENT> reconnect = False | A component establishes a transport and attached a session
to a realm using the transport for communication.
The transports a component tries to use can be configured,
as well as the auto-reconnect strategy. | 62598fb071ff763f4b5e77b1 |
class Transaction: <NEW_LINE> <INDENT> deep = False <NEW_LINE> def __init__(self, *targets): <NEW_LINE> <INDENT> self.targets = targets <NEW_LINE> self.Commit() <NEW_LINE> <DEDENT> def Commit(self): <NEW_LINE> <INDENT> self.states = [Memento(target, self.deep) for target in self.targets] <NEW_LINE> <DEDENT> def Rollback(self): <NEW_LINE> <INDENT> for st in self.states: <NEW_LINE> <INDENT> st() | A transaction guard. This is really just
syntactic suggar arount a memento closure. | 62598fb02ae34c7f260ab122 |
class TestResponse(ThamosTestCase): <NEW_LINE> <INDENT> def test_serialization(self, tmp_path: Path): <NEW_LINE> <INDENT> response = json.loads((Path(self.data_dir) / "response_1.json").read_text()) <NEW_LINE> with cwd(str(tmp_path)): <NEW_LINE> <INDENT> pipfile = response["result"]["report"]["products"][0]["project"][ "requirements" ] <NEW_LINE> pipfile_lock = response["result"]["report"]["products"][0]["project"][ "requirements_locked" ] <NEW_LINE> write_files(pipfile, pipfile_lock, requirements_format="pipenv") <NEW_LINE> written_pipfile = toml.loads(Path("Pipfile").read_text()) <NEW_LINE> assert written_pipfile == { "dev-packages": {}, "packages": { "flask": {"index": "pypi-org", "version": "*"}, "tensorflow": {"index": "pypi-org", "version": "*"}, }, "source": [ { "name": "pypi-org", "url": "https://pypi.org/simple", "verify_ssl": True, } ], "thoth": {"allow_prereleases": {}, "disable_index_adjustment": False}, } <NEW_LINE> written_pipfile_lock = json.loads(Path("Pipfile.lock").read_text()) <NEW_LINE> assert written_pipfile_lock == pipfile_lock | Test response serialization. | 62598fb04a966d76dd5eef17 |
class DiffEntry(object): <NEW_LINE> <INDENT> def __init__(self, path=list(), old=None, new=None): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.old = old <NEW_LINE> self.new = new <NEW_LINE> self.undef_str = '<undefined>' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> old = self.undef_str if self.old is Undefined else self.old <NEW_LINE> new = self.undef_str if self.new is Undefined else self.new <NEW_LINE> return '{path}: "{old}" => "{new}"'.format(path='.'.join(self.path), old=old, new=new) | DiffEntry is a representation of a difference.
It describes the attribute's key (path) and its values on both sides of
the structure. | 62598fb044b2445a339b6991 |
class IterativeModel(): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def params(self, symbolic=False): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def evaluate(self, x, mnb_size): <NEW_LINE> <INDENT> evaluate_f = getattr(self, "_evaluate", None) <NEW_LINE> if evaluate_f is None: <NEW_LINE> <INDENT> evaluate_f = theano.function( [self.input], self.cost) <NEW_LINE> self._evaluate = evaluate_f <NEW_LINE> <DEDENT> return np.sum( [evaluate_f(mnb) * mnb.shape[0] for mnb in util.create_minibatches(x, None, mnb_size, False) ]) / x.shape[0] <NEW_LINE> <DEDENT> def train(self, x_train, mnb_size, epochs, eps, weight_cost=1e-4): <NEW_LINE> <INDENT> log.info('Training iterative model`, epochs: %d, eps: %r', epochs, eps) <NEW_LINE> train_mnb_count = (x_train.shape[0] - 1) / mnb_size + 1 <NEW_LINE> x_train = theano.shared(x_train, name='x_train', borrow=True) <NEW_LINE> param_updates = grad_descent.gradient_updates_rms( self.cost_l2, self.params(True).values(), eps, 0.9) <NEW_LINE> index = T.iscalar() <NEW_LINE> train_f = theano.function( [index, self.l2_lmbd], self.cost, updates=param_updates.updates, givens={ self.input: x_train[index * mnb_size: (index + 1) * mnb_size] } ) <NEW_LINE> train_costs = [] <NEW_LINE> train_times = [] <NEW_LINE> log.info("Starting training") <NEW_LINE> epoch_callback = getattr(self, "epoch_callback", lambda a, b: True) <NEW_LINE> mnb_callback = getattr(self, "mnb_callback", lambda a, b, c: True) <NEW_LINE> for epoch_ind, epoch in enumerate(range(epochs)): <NEW_LINE> <INDENT> epoch_t0 = time() <NEW_LINE> if not isinstance(eps, float): <NEW_LINE> <INDENT> epoch_eps = eps(epoch_ind, train_costs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> epoch_eps = eps * (0.1 + 0.9 * 0.95 ** epoch_ind) <NEW_LINE> <DEDENT> def mnb_train(batch_ind): <NEW_LINE> <INDENT> cost = train_f(batch_ind, epoch_eps) <NEW_LINE> log.debug('Mnb %d train cost %.5f', batch_ind, cost) <NEW_LINE> mnb_callback(self, epoch_ind, batch_ind) <NEW_LINE> return cost <NEW_LINE> <DEDENT> train_cost = map(mnb_train, xrange(train_mnb_count)) <NEW_LINE> train_costs.append(float(train_cost[-1])) <NEW_LINE> train_times.append(time() - epoch_t0) <NEW_LINE> log.info('Epoch %d, duration %.2f sec, train cost: %.5f', epoch_ind, train_times[-1], train_costs[-1]) <NEW_LINE> if not epoch_callback(self, epoch_ind): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> log.info('Training duration %.2f min', (sum(train_times)) / 60.0) <NEW_LINE> return train_costs <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> raise "Implement me!" <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> raise "Implement me!" | Base class for language models that are trained iteratively
using gradient descent. | 62598fb0f9cc0f698b1c52ea |
class TypeOfAddress: <NEW_LINE> <INDENT> TON = { 0b000: 'unknown', 0b001: 'international', 0b010: 'national', 0b011: 'specific', 0b100: 'subscriber', 0b101: 'alphanumeric', 0b110: 'abbreviated', 0b111: 'extended', } <NEW_LINE> TON_INV = dict([(v[1], v[0]) for v in TON.items()]) <NEW_LINE> NPI = { 0b0000: 'unknown', 0b0001: 'isdn', 0b0011: 'data', 0b0100: 'telex', 0b0101: 'specific1', 0b0110: 'specific2', 0b1000: 'national', 0b1001: 'private', 0b1010: 'ermes', 0b1111: 'extended', } <NEW_LINE> NPI_INV = dict([(v[1], v[0]) for v in NPI.items()]) <NEW_LINE> @classmethod <NEW_LINE> def decode(cls, data: str) -> Dict[str, str]: <NEW_LINE> <INDENT> io_data = BitStream(hex=data) <NEW_LINE> first_bit = io_data.read('bool') <NEW_LINE> if not first_bit: <NEW_LINE> <INDENT> raise ValueError("Invalid first bit of the Type Of Address octet") <NEW_LINE> <DEDENT> ton = cls.TON.get(io_data.read('bits:3').uint) <NEW_LINE> if ton is None: <NEW_LINE> <INDENT> assert False, "Type-Of-Number bits should be exaustive" <NEW_LINE> raise ValueError("Invalid Type Of Number bits") <NEW_LINE> <DEDENT> npi = cls.NPI.get(io_data.read('bits:4').uint) <NEW_LINE> if npi is None: <NEW_LINE> <INDENT> raise ValueError("Invalid Numbering Plan Identification bits") <NEW_LINE> <DEDENT> return { 'ton': ton, 'npi': npi, } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def encode(cls, data: Dict[str, str]) -> str: <NEW_LINE> <INDENT> ton = cls.TON_INV.get(data.get('ton')) <NEW_LINE> npi = cls.NPI_INV.get(data.get('npi')) <NEW_LINE> if ton is None: <NEW_LINE> <INDENT> raise ValueError("Invalid Type Of Address") <NEW_LINE> <DEDENT> if npi is None: <NEW_LINE> <INDENT> raise ValueError("Invalid Numbering Plan Identification") <NEW_LINE> <DEDENT> return f'{0x80 | (ton << 4) | npi:02x}' | Type Of Address representation. | 62598fb0fff4ab517ebcd826 |
class RRData_MX(Record): <NEW_LINE> <INDENT> RRDATA_FIELDS = ['exchange'] <NEW_LINE> RECORD_TYPE = 15 | MX Resource Record Type
Defined in: RFC1035 | 62598fb04527f215b58e9f16 |
class BIDSRunVariableCollection(BIDSVariableCollection): <NEW_LINE> <INDENT> def __init__(self, variables, sampling_rate=None): <NEW_LINE> <INDENT> self.sampling_rate = sampling_rate or 10 <NEW_LINE> super(BIDSRunVariableCollection, self).__init__(variables) <NEW_LINE> <DEDENT> def _none_dense(self): <NEW_LINE> <INDENT> return all([isinstance(v, SimpleVariable) for v in self.variables.values()]) <NEW_LINE> <DEDENT> def _all_dense(self): <NEW_LINE> <INDENT> return all([isinstance(v, DenseRunVariable) for v in self.variables.values()]) <NEW_LINE> <DEDENT> def resample(self, sampling_rate=None, variables=None, force_dense=False, in_place=False, kind='linear'): <NEW_LINE> <INDENT> sampling_rate = sampling_rate or self.sampling_rate <NEW_LINE> _variables = {} <NEW_LINE> for name, var in self.variables.items(): <NEW_LINE> <INDENT> if variables is not None and name not in variables: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if isinstance(var, SparseRunVariable): <NEW_LINE> <INDENT> if force_dense and is_numeric_dtype(var.values): <NEW_LINE> <INDENT> _variables[name] = var.to_dense(sampling_rate) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> _variables[name] = var.resample(sampling_rate, inplace=in_place, kind=kind) <NEW_LINE> _variables[name] = var <NEW_LINE> <DEDENT> <DEDENT> if in_place: <NEW_LINE> <INDENT> for k, v in _variables.items(): <NEW_LINE> <INDENT> self.variables[k] = v <NEW_LINE> <DEDENT> self.sampling_rate = sampling_rate <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _variables <NEW_LINE> <DEDENT> <DEDENT> def to_df(self, variables=None, format='wide', sparse=True, sampling_rate=None, include_sparse=True, include_dense=True, **kwargs): <NEW_LINE> <INDENT> if not include_sparse and not include_dense: <NEW_LINE> <INDENT> raise ValueError("You can't exclude both dense and sparse " "variables! That leaves nothing!") <NEW_LINE> <DEDENT> if variables is None: <NEW_LINE> <INDENT> variables = list(self.variables.keys()) <NEW_LINE> <DEDENT> if not include_sparse: <NEW_LINE> <INDENT> variables = [v for v in variables if isinstance(self.variables[v], DenseRunVariable)] <NEW_LINE> <DEDENT> if not include_dense: <NEW_LINE> <INDENT> variables = [v for v in variables if not isinstance(self.variables[v], DenseRunVariable)] <NEW_LINE> <DEDENT> if not variables: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> _vars = [self.variables[v] for v in variables] <NEW_LINE> if sparse and all(isinstance(v, SimpleVariable) for v in _vars): <NEW_LINE> <INDENT> variables = _vars <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sampling_rate = sampling_rate or self.sampling_rate <NEW_LINE> variables = list(self.resample(sampling_rate, variables, force_dense=True, in_place=False).values()) <NEW_LINE> <DEDENT> return super(BIDSRunVariableCollection, self).to_df(variables, format, **kwargs) | A container for one or more RunVariables--i.e., Variables that have a
temporal dimension.
Args:
variables (list): A list of SparseRunVariable and/or DenseRunVariable.
sampling_rate (float): Sampling rate (in Hz) to use when working with
dense representations of variables. If None, defaults to 10.
Notes:
* Variables in the list must all be at the 'run' level. For other
levels (session, subject, or dataset), use the
BIDSVariableCollection. | 62598fb0167d2b6e312b6fb2 |
class LookupModule(LookupBase): <NEW_LINE> <INDENT> def run(self, terms, variables=None, **kwargs): <NEW_LINE> <INDENT> display.vvvv("%s" % terms) <NEW_LINE> if isinstance(terms, list): <NEW_LINE> <INDENT> return_values = [] <NEW_LINE> for term in terms: <NEW_LINE> <INDENT> display.vvvv("Term: %s" % term) <NEW_LINE> cyberark_conn = CyberarkPassword(**term) <NEW_LINE> return_values.append(cyberark_conn.get()) <NEW_LINE> <DEDENT> return return_values <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cyberark_conn = CyberarkPassword(**terms) <NEW_LINE> result = cyberark_conn.get() <NEW_LINE> return result | USAGE: | 62598fb030bbd72246469999 |
class TestFile(common.TestCore): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestFile, self).setUp() <NEW_LINE> utils_lib.write_file(TRACKED_FP, contents=TRACKED_FP_CONTENTS_1) <NEW_LINE> utils_lib.write_file(TRACKED_FP_WITH_SPACE, contents=TRACKED_FP_CONTENTS_1) <NEW_LINE> utils_lib.write_file(TRACKED_DIR_FP, contents=TRACKED_FP_CONTENTS_1) <NEW_LINE> utils_lib.write_file( TRACKED_DIR_FP_WITH_SPACE, contents=TRACKED_FP_CONTENTS_1) <NEW_LINE> utils_lib.write_file(TRACKED_DIR_DIR_FP, contents=TRACKED_FP_CONTENTS_1) <NEW_LINE> utils_lib.write_file( TRACKED_DIR_DIR_FP_WITH_SPACE, contents=TRACKED_FP_CONTENTS_1) <NEW_LINE> utils_lib.git_call( 'add "{0}" "{1}" "{2}" "{3}" "{4}" "{5}"'.format( TRACKED_FP, TRACKED_FP_WITH_SPACE, TRACKED_DIR_FP, TRACKED_DIR_FP_WITH_SPACE, TRACKED_DIR_DIR_FP, TRACKED_DIR_DIR_FP_WITH_SPACE)) <NEW_LINE> utils_lib.git_call( 'commit -m"1" "{0}" "{1}" "{2}" "{3}" "{4}" "{5}"'.format( TRACKED_FP, TRACKED_FP_WITH_SPACE, TRACKED_DIR_FP, TRACKED_DIR_FP_WITH_SPACE, TRACKED_DIR_DIR_FP, TRACKED_DIR_DIR_FP_WITH_SPACE)) <NEW_LINE> utils_lib.write_file(TRACKED_FP, contents=TRACKED_FP_CONTENTS_2) <NEW_LINE> utils_lib.write_file(TRACKED_FP_WITH_SPACE, contents=TRACKED_FP_CONTENTS_2) <NEW_LINE> utils_lib.write_file(TRACKED_DIR_FP, contents=TRACKED_FP_CONTENTS_2) <NEW_LINE> utils_lib.write_file( TRACKED_DIR_FP_WITH_SPACE, contents=TRACKED_FP_CONTENTS_2) <NEW_LINE> utils_lib.write_file(TRACKED_DIR_DIR_FP, contents=TRACKED_FP_CONTENTS_2) <NEW_LINE> utils_lib.write_file( TRACKED_DIR_DIR_FP_WITH_SPACE, contents=TRACKED_FP_CONTENTS_2) <NEW_LINE> utils_lib.git_call( 'commit -m"2" "{0}" "{1}" "{2}" "{3}" "{4}" "{5}"'.format( TRACKED_FP, TRACKED_FP_WITH_SPACE, TRACKED_DIR_FP, TRACKED_DIR_FP_WITH_SPACE, TRACKED_DIR_DIR_FP, TRACKED_DIR_DIR_FP_WITH_SPACE)) <NEW_LINE> utils_lib.write_file(UNTRACKED_FP) <NEW_LINE> utils_lib.write_file(UNTRACKED_FP_WITH_SPACE) <NEW_LINE> utils_lib.write_file(UNTRACKED_DIR_FP) <NEW_LINE> utils_lib.write_file(UNTRACKED_DIR_FP_WITH_SPACE) <NEW_LINE> utils_lib.write_file(UNTRACKED_DIR_DIR_FP) <NEW_LINE> utils_lib.write_file(UNTRACKED_DIR_DIR_FP_WITH_SPACE) <NEW_LINE> utils_lib.write_file( '.gitignore', contents='{0}\n{1}'.format( IGNORED_FP, IGNORED_FP_WITH_SPACE)) <NEW_LINE> utils_lib.write_file(IGNORED_FP) <NEW_LINE> utils_lib.write_file(IGNORED_FP_WITH_SPACE) | Base class for file tests. | 62598fb0a79ad1619776a0a9 |
class Link(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='links') <NEW_LINE> url = models.URLField() <NEW_LINE> icon = models.CharField(max_length=128) <NEW_LINE> title = models.CharField(max_length=128, null=True, blank=True) | Generic links for users. | 62598fb021bff66bcd722ca8 |
class ConsoleObjectMenu(TemplateMenu): <NEW_LINE> <INDENT> obj = None <NEW_LINE> def object_menu(self): <NEW_LINE> <INDENT> self.print_help( "Do you want to 'add', 'list' {name}s, 'delete' them, or 'back' to main?".format(name=self.obj.name) ) <NEW_LINE> while True: <NEW_LINE> <INDENT> self.print_info("***{name} Menu***".format(name=self.obj.name.capitalize())) <NEW_LINE> action = input('>>') <NEW_LINE> if action == 'add': <NEW_LINE> <INDENT> self.print_help("Provide the following values:") <NEW_LINE> self._add_object() <NEW_LINE> self.print_info('{name} created!'.format(name=self.obj.name)) <NEW_LINE> <DEDENT> elif action == 'list': <NEW_LINE> <INDENT> ConsolePrintOut().print_model(self.obj) <NEW_LINE> <DEDENT> elif action == 'delete': <NEW_LINE> <INDENT> self._delete_menu() <NEW_LINE> <DEDENT> elif action == 'help': <NEW_LINE> <INDENT> self._view_help('help_sub_msg.txt') <NEW_LINE> <DEDENT> elif action == 'back': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.print_warn("Unknown command. Type 'help' for the list of available options.") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _delete_menu(self): <NEW_LINE> <INDENT> if self.obj.objects: <NEW_LINE> <INDENT> ConsolePrintOut().print_model(self.obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.print_warn('No {name}s to delete. Back to {name} Menu.'.format(name=self.obj.name)) <NEW_LINE> return <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> self.print_info('***{name} Delete Menu***'.format(name=self.obj.name)) <NEW_LINE> self.print_help( "Type _id of the {name} to be removed, 'list' or 'back' to cancel".format(name=self.obj.name) ) <NEW_LINE> action = input('>>') <NEW_LINE> if action == 'back': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif action == 'list': <NEW_LINE> <INDENT> ConsolePrintOut().print_model(self.obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj_to_remove = self.obj.get(_id=int(action)) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> self.print_warn("Wrong id! Try again or 'back' to cancel") <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.print_warn("Wrong id! Try again or 'back' to cancel") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.obj.remove(obj_to_remove) <NEW_LINE> self.print_info("{name} was successfully removed!".format(name=self.obj.name)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def _add_object(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _view_help(self, help_path): <NEW_LINE> <INDENT> with open(os.path.join(os.path.dirname(__file__), help_path), 'r') as f: <NEW_LINE> <INDENT> print(f.read().format(object=self.obj.name)) | This is a template for other model menus | 62598fb03d592f4c4edbaf02 |
class Ship(Entity): <NEW_LINE> <INDENT> def __init__(self, owner, id, position, halite_amount): <NEW_LINE> <INDENT> super().__init__(owner, id, position) <NEW_LINE> self.halite_amount = halite_amount <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_full(self): <NEW_LINE> <INDENT> return self.halite_amount >= constants.MAX_HALITE <NEW_LINE> <DEDENT> Target_Pos = Position(0, 0) <NEW_LINE> def make_dropoff(self): <NEW_LINE> <INDENT> return "{} {}".format(commands.CONSTRUCT, self.id) <NEW_LINE> <DEDENT> def move(self, direction): <NEW_LINE> <INDENT> raw_direction = direction <NEW_LINE> if not isinstance(direction, str) or direction not in "nsewo": <NEW_LINE> <INDENT> raw_direction = Direction.convert(direction) <NEW_LINE> <DEDENT> return "{} {} {}".format(commands.MOVE, self.id, raw_direction) <NEW_LINE> <DEDENT> def stay_still(self): <NEW_LINE> <INDENT> return "{} {} {}".format(commands.MOVE, self.id, commands.STAY_STILL) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _generate(player_id): <NEW_LINE> <INDENT> ship_id, x_position, y_position, halite = map(int, read_input().split()) <NEW_LINE> return ship_id, Ship(player_id, ship_id, Position(x_position, y_position), halite) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}(id={}, {}, cargo={} halite)".format(self.__class__.__name__, self.id, self.position, self.halite_amount) | Ship class to house ship entities | 62598fb0e1aae11d1e7ce844 |
class FixtureDef: <NEW_LINE> <INDENT> def __init__(self, fixturemanager, baseid, argname, func, scope, params, unittest=False, ids=None): <NEW_LINE> <INDENT> self._fixturemanager = fixturemanager <NEW_LINE> self.baseid = baseid or '' <NEW_LINE> self.has_location = baseid is not None <NEW_LINE> self.func = func <NEW_LINE> self.argname = argname <NEW_LINE> self.scope = scope <NEW_LINE> self.scopenum = scope2index( scope or "function", descr='fixture {0}'.format(func.__name__), where=baseid ) <NEW_LINE> self.params = params <NEW_LINE> self.argnames = getfuncargnames(func, is_method=unittest) <NEW_LINE> self.unittest = unittest <NEW_LINE> self.ids = ids <NEW_LINE> self._finalizers = [] <NEW_LINE> <DEDENT> def addfinalizer(self, finalizer): <NEW_LINE> <INDENT> self._finalizers.append(finalizer) <NEW_LINE> <DEDENT> def finish(self, request): <NEW_LINE> <INDENT> exceptions = [] <NEW_LINE> try: <NEW_LINE> <INDENT> while self._finalizers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> func = self._finalizers.pop() <NEW_LINE> func() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> exceptions.append(sys.exc_info()) <NEW_LINE> <DEDENT> <DEDENT> if exceptions: <NEW_LINE> <INDENT> e = exceptions[0] <NEW_LINE> del exceptions <NEW_LINE> py.builtin._reraise(*e) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> hook = self._fixturemanager.session.gethookproxy(request.node.fspath) <NEW_LINE> hook.pytest_fixture_post_finalizer(fixturedef=self, request=request) <NEW_LINE> if hasattr(self, "cached_result"): <NEW_LINE> <INDENT> del self.cached_result <NEW_LINE> <DEDENT> self._finalizers = [] <NEW_LINE> <DEDENT> <DEDENT> def execute(self, request): <NEW_LINE> <INDENT> for argname in self.argnames: <NEW_LINE> <INDENT> fixturedef = request._get_active_fixturedef(argname) <NEW_LINE> if argname != "request": <NEW_LINE> <INDENT> fixturedef.addfinalizer(functools.partial(self.finish, request=request)) <NEW_LINE> <DEDENT> <DEDENT> my_cache_key = request.param_index <NEW_LINE> cached_result = getattr(self, "cached_result", None) <NEW_LINE> if cached_result is not None: <NEW_LINE> <INDENT> result, cache_key, err = cached_result <NEW_LINE> if my_cache_key == cache_key: <NEW_LINE> <INDENT> if err is not None: <NEW_LINE> <INDENT> py.builtin._reraise(*err) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> self.finish(request) <NEW_LINE> assert not hasattr(self, "cached_result") <NEW_LINE> <DEDENT> hook = self._fixturemanager.session.gethookproxy(request.node.fspath) <NEW_LINE> return hook.pytest_fixture_setup(fixturedef=self, request=request) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ("<FixtureDef name=%r scope=%r baseid=%r >" % (self.argname, self.scope, self.baseid)) | A container for a factory definition. | 62598fb02ae34c7f260ab123 |
class MultiGetFile(MultiGetFileMixin, flow.GRRFlow): <NEW_LINE> <INDENT> args_type = MultiGetFileArgs <NEW_LINE> @flow.StateHandler() <NEW_LINE> def Start(self): <NEW_LINE> <INDENT> super(MultiGetFile, self).Start( file_size=self.args.file_size, maximum_pending_files=self.args.maximum_pending_files, use_external_stores=self.args.use_external_stores) <NEW_LINE> unique_paths = set() <NEW_LINE> for pathspec in self.args.pathspecs: <NEW_LINE> <INDENT> vfs_urn = pathspec.AFF4Path(self.client_id) <NEW_LINE> if vfs_urn not in unique_paths: <NEW_LINE> <INDENT> unique_paths.add(vfs_urn) <NEW_LINE> self.StartFileFetch(pathspec) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def ReceiveFetchedFile(self, stat_entry, unused_hash_obj, request_data=None): <NEW_LINE> <INDENT> _ = request_data <NEW_LINE> self.SendReply(stat_entry) | A flow to effectively retrieve a number of files. | 62598fb0bd1bec0571e150e3 |
class CustomLanguageCodeRemoveView(LaunchpadFormView): <NEW_LINE> <INDENT> schema = ICustomLanguageCode <NEW_LINE> field_names = [] <NEW_LINE> page_title = "Remove" <NEW_LINE> @property <NEW_LINE> def code(self): <NEW_LINE> <INDENT> return self.context.language_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return "Remove custom language code '%s'" % self.code <NEW_LINE> <DEDENT> @action("Remove") <NEW_LINE> def remove(self, action, data): <NEW_LINE> <INDENT> code = self.code <NEW_LINE> self.context.translation_target.removeCustomLanguageCode(self.context) <NEW_LINE> self.request.response.addInfoNotification( "Removed custom language code '%s'." % code) <NEW_LINE> <DEDENT> @property <NEW_LINE> def next_url(self): <NEW_LINE> <INDENT> return canonical_url( self.context.translation_target, rootsite='translations', view_name='+custom-language-codes') <NEW_LINE> <DEDENT> cancel_url = next_url | View for removing a `CustomLanguageCode`. | 62598fb08a43f66fc4bf21bc |
class WorkAmendmentDetailView(WorkDependentView, UpdateView): <NEW_LINE> <INDENT> http_method_names = ['post'] <NEW_LINE> model = Amendment <NEW_LINE> pk_url_kwarg = 'amendment_id' <NEW_LINE> fields = ['date'] <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return self.work.amendments <NEW_LINE> <DEDENT> def get_permission_required(self): <NEW_LINE> <INDENT> if 'delete' in self.request.POST: <NEW_LINE> <INDENT> return ('indigo_api.delete_amendment',) <NEW_LINE> <DEDENT> return ('indigo_api.change_amendment',) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if 'delete' in request.POST: <NEW_LINE> <INDENT> return self.delete(request, *args, **kwargs) <NEW_LINE> <DEDENT> return super(WorkAmendmentDetailView, self).post(request, *args, **kwargs) <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> old_date = form.initial['date'] <NEW_LINE> self.object.updated_by_user = self.request.user <NEW_LINE> result = super().form_valid(form) <NEW_LINE> self.object.amended_work.updated_by_user = self.request.user <NEW_LINE> self.object.amended_work.save() <NEW_LINE> docs = Document.objects.filter(work=self.object.amended_work, expression_date=old_date) <NEW_LINE> for doc in docs: <NEW_LINE> <INDENT> doc.expression_date = self.object.date <NEW_LINE> doc.updated_by_user = self.request.user <NEW_LINE> doc.save() <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def delete(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.object = self.get_object() <NEW_LINE> if self.object.can_delete(): <NEW_LINE> <INDENT> work = self.object.amended_work <NEW_LINE> self.object.delete() <NEW_LINE> work.updated_by_user = self.request.user <NEW_LINE> work.save() <NEW_LINE> <DEDENT> return redirect(self.get_success_url()) <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> url = reverse('work_amendments', kwargs={'frbr_uri': self.kwargs['frbr_uri']}) <NEW_LINE> if self.object.id: <NEW_LINE> <INDENT> url += "#amendment-%s" % self.object.id <NEW_LINE> <DEDENT> return url | View to update or delete amendment.
| 62598fb0a05bb46b3848a8ad |
class TransferProductRequestProperties(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'destination_invoice_section_id': {'key': 'destinationInvoiceSectionId', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, destination_invoice_section_id: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(TransferProductRequestProperties, self).__init__(**kwargs) <NEW_LINE> self.destination_invoice_section_id = destination_invoice_section_id | The properties of the product to initiate a transfer.
:param destination_invoice_section_id: The destination invoice section id.
:type destination_invoice_section_id: str | 62598fb0a219f33f346c6857 |
class ChannelClosedError(PaymentServerError): <NEW_LINE> <INDENT> pass | Raised when attempting to access a channel that has been closed. | 62598fb04428ac0f6e658568 |
class EntryPingbacks(EntryDiscussions): <NEW_LINE> <INDENT> title_template = 'feeds/pingback_title.html' <NEW_LINE> description_template = 'feeds/pingback_description.html' <NEW_LINE> def items(self, obj): <NEW_LINE> <INDENT> return obj.pingbacks[:FEEDS_MAX_ITEMS] <NEW_LINE> <DEDENT> def item_link(self, item): <NEW_LINE> <INDENT> return item.get_absolute_url('#pingback-%(id)s') <NEW_LINE> <DEDENT> def get_title(self, obj): <NEW_LINE> <INDENT> return _('Pingbacks on %s') % obj.title <NEW_LINE> <DEDENT> def description(self, obj): <NEW_LINE> <INDENT> return _('The latest pingbacks for the entry %s') % obj.title | Feed for pingbacks in an entry | 62598fb099cbb53fe6830f1b |
class TimeZoneFieldBase(models.Field): <NEW_LINE> <INDENT> description = _('A pytz timezone object') <NEW_LINE> MAX_LENGTH = 63 <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> parent_kwargs = { 'max_length': self.MAX_LENGTH, 'choices': COMMON_TIMEZONE_CHOICES, 'null': True, } <NEW_LINE> parent_kwargs.update(kwargs) <NEW_LINE> super(TimeZoneFieldBase, self).__init__(*args, **parent_kwargs) <NEW_LINE> <DEDENT> def validate(self, value, model_instance): <NEW_LINE> <INDENT> if not is_pytz_instance(value): <NEW_LINE> <INDENT> raise ValidationError('"%s" is not a pytz timezone object' % value) <NEW_LINE> <DEDENT> tz_as_str = value.zone <NEW_LINE> super(TimeZoneFieldBase, self).validate(tz_as_str, model_instance) <NEW_LINE> <DEDENT> def deconstruct(self): <NEW_LINE> <INDENT> name, path, args, kwargs = super(TimeZoneFieldBase, self).deconstruct() <NEW_LINE> if kwargs['choices'] == COMMON_TIMEZONE_CHOICES: <NEW_LINE> <INDENT> del kwargs['choices'] <NEW_LINE> <DEDENT> if kwargs['max_length'] == self.MAX_LENGTH: <NEW_LINE> <INDENT> del kwargs['max_length'] <NEW_LINE> <DEDENT> if kwargs['null'] is True: <NEW_LINE> <INDENT> del kwargs['null'] <NEW_LINE> <DEDENT> return name, path, args, kwargs <NEW_LINE> <DEDENT> def get_internal_type(self): <NEW_LINE> <INDENT> return 'CharField' <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> return self._get_python_and_db_repr(value)[0] <NEW_LINE> <DEDENT> def get_prep_value(self, value): <NEW_LINE> <INDENT> return self._get_python_and_db_repr(value)[1] <NEW_LINE> <DEDENT> def _get_python_and_db_repr(self, value): <NEW_LINE> <INDENT> if value is None or value == '': <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> if is_pytz_instance(value): <NEW_LINE> <INDENT> return value, value.zone <NEW_LINE> <DEDENT> if isinstance(value, six.string_types): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return pytz.timezone(value), value <NEW_LINE> <DEDENT> except pytz.UnknownTimeZoneError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> raise ValidationError("Invalid timezone '%s'" % value) | Provides database store for pytz timezone objects.
Valid inputs are:
- any instance of ``pytz.tzinfo.DstTzInfo`` or ``pytz.tzinfo.StaticTzInfo``
- the ``pytz.UTC`` singleton
- any string that validates against pytz.common_timezones.
- None and the empty string both represent 'no timezone'
Valid outputs:
- None
- instances of ``pytz.tzinfo.DstTzInfo`` and ``pytz.tzinfo.StaticTzInfo``
- the ``pytz.UTC`` singleton | 62598fb091f36d47f2230ec8 |
class IfExp(NodeNG): <NEW_LINE> <INDENT> _astroid_fields = ('test', 'body', 'orelse') <NEW_LINE> test = None <NEW_LINE> body = None <NEW_LINE> orelse = None | class representing an IfExp node | 62598fb05fcc89381b26616d |
class EnumValueType(FrozenClass): <NEW_LINE> <INDENT> ua_types = [ ('Value', 'Int64'), ('DisplayName', 'LocalizedText'), ('Description', 'LocalizedText'), ] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.Value = 0 <NEW_LINE> self.DisplayName = LocalizedText() <NEW_LINE> self.Description = LocalizedText() <NEW_LINE> self._freeze = True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'EnumValueType(Value:{self.Value}, DisplayName:{self.DisplayName}, Description:{self.Description})' <NEW_LINE> <DEDENT> __repr__ = __str__ | A mapping between a value of an enumerated type and a name and description.
:ivar Value:
:vartype Value: Int64
:ivar DisplayName:
:vartype DisplayName: LocalizedText
:ivar Description:
:vartype Description: LocalizedText | 62598fb032920d7e50bc6096 |
class TestAppCommon: <NEW_LINE> <INDENT> def test_app_root_get(self, test_client: FlaskClient) -> None: <NEW_LINE> <INDENT> response = test_client.get("/") <NEW_LINE> assert response.status_code == HTTPStatus.FOUND <NEW_LINE> <DEDENT> def test_app_get_favicon(self, test_app: OverhaveAdminApp, test_client: FlaskClient) -> None: <NEW_LINE> <INDENT> response = test_client.get("/favicon.ico") <NEW_LINE> assert response.status_code == HTTPStatus.OK <NEW_LINE> assert response.mimetype == "image/vnd.microsoft.icon" <NEW_LINE> assert response.data == (Path(test_app.config["FILES_DIR"]) / "favicon.ico").read_bytes() <NEW_LINE> <DEDENT> def test_app_create_pr_without_publisher( self, test_app: OverhaveAdminApp, test_client: FlaskClient, test_pullrequest_id: int ) -> None: <NEW_LINE> <INDENT> response = test_client.get(f"/pull_request/{test_pullrequest_id}") <NEW_LINE> assert response.status_code == HTTPStatus.FOUND <NEW_LINE> <DEDENT> def test_app_create_pr_incorrect_data( self, test_app: OverhaveAdminApp, test_client: FlaskClient, test_pullrequest_id: int, test_pullrequest_published_by: str, ) -> None: <NEW_LINE> <INDENT> response = test_client.get(f"/pull_request/{test_pullrequest_id}?published_by={test_pullrequest_published_by}") <NEW_LINE> assert response.status_code == HTTPStatus.FOUND <NEW_LINE> <DEDENT> def test_app_get_emulation_run( self, test_app: OverhaveAdminApp, test_client: FlaskClient, ) -> None: <NEW_LINE> <INDENT> response = test_client.get("http://localhost/emulations/kek:8000") <NEW_LINE> assert response.status_code == HTTPStatus.FOUND | Integration tests for OverhaveApp. | 62598fb0ff9c53063f51a68f |
class ToolTip(Toplevel): <NEW_LINE> <INDENT> def __init__(self, wdgt, msg=None, msgFunc=None, delay=1, follow=True): <NEW_LINE> <INDENT> self.wdgt = wdgt <NEW_LINE> self.parent = self.wdgt.master <NEW_LINE> Toplevel.__init__(self, self.parent, bg='black', padx=1, pady=1) <NEW_LINE> self.withdraw() <NEW_LINE> self.overrideredirect(True) <NEW_LINE> self.msgVar = StringVar() <NEW_LINE> if msg is None: <NEW_LINE> <INDENT> self.msgVar.set('No message provided') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.msgVar.set(msg) <NEW_LINE> <DEDENT> self.msgFunc = msgFunc <NEW_LINE> self.delay = delay <NEW_LINE> self.follow = follow <NEW_LINE> self.visible = 0 <NEW_LINE> self.lastMotion = 0 <NEW_LINE> Message(self, textvariable=self.msgVar, bg='#FFFFDD', aspect=1000).grid() <NEW_LINE> self.wdgt.bind('<Enter>', self.spawn, '+') <NEW_LINE> self.wdgt.bind('<Leave>', self.hide, '+') <NEW_LINE> self.wdgt.bind('<Motion>', self.move, '+') <NEW_LINE> <DEDENT> def spawn(self, event=None): <NEW_LINE> <INDENT> self.visible = 1 <NEW_LINE> self.after(int(self.delay * 1000), self.show) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> if self.visible == 1 and time() - self.lastMotion > self.delay: <NEW_LINE> <INDENT> self.visible = 2 <NEW_LINE> <DEDENT> if self.visible == 2: <NEW_LINE> <INDENT> self.deiconify() <NEW_LINE> <DEDENT> <DEDENT> def move(self, event): <NEW_LINE> <INDENT> self.lastMotion = time() <NEW_LINE> if self.follow is False: <NEW_LINE> <INDENT> self.withdraw() <NEW_LINE> self.visible = 1 <NEW_LINE> <DEDENT> self.geometry('+%i+%i' % (event.x_root+10, event.y_root+10)) <NEW_LINE> try: <NEW_LINE> <INDENT> self.msgVar.set(self.msgFunc()) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.after(int(self.delay * 1000), self.show) <NEW_LINE> <DEDENT> def hide(self, event=None): <NEW_LINE> <INDENT> self.visible = 0 <NEW_LINE> self.withdraw() | Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor | 62598fb03317a56b869be56c |
class IndexPartition(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._partition = _IndexPartition() <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self._partition.size() <NEW_LINE> <DEDENT> def starting_token(self): <NEW_LINE> <INDENT> return self._partition.starting_token() <NEW_LINE> <DEDENT> def ending_token(self): <NEW_LINE> <INDENT> return self._partition.ending_token() <NEW_LINE> <DEDENT> def add_token(self, token, doc_id, lock_no, ngram_size, locations): <NEW_LINE> <INDENT> self._partition.add_token(token, doc_id, lock_no, ngram_size, locations) <NEW_LINE> return True <NEW_LINE> <DEDENT> def serialize(self, out_file): <NEW_LINE> <INDENT> with open(out_file, 'wb') as payload: <NEW_LINE> <INDENT> pickle.dump(self._partition, payload, pickle.HIGHEST_PROTOCOL) <NEW_LINE> payload.close() <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def deserialize(self, in_file): <NEW_LINE> <INDENT> with open(in_file, 'rb') as payload: <NEW_LINE> <INDENT> self._partition = pickle.load(payload) <NEW_LINE> payload.close() <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def get_token_list(self): <NEW_LINE> <INDENT> return self._partition.get_token_list() <NEW_LINE> <DEDENT> def get_token_count(self, key): <NEW_LINE> <INDENT> if key not in self._partition._partition.keys(): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if self._partition._partition[key]['ngram_size'] != 1: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> count = 0 <NEW_LINE> for doc in self._partition._partition[key]['documentOccurrences']: <NEW_LINE> <INDENT> count += len(doc['versions'][0]['locations']) <NEW_LINE> <DEDENT> return count | This class wraps the _IndexPartition class to provide serialization.
It stores and loads an _IndexPartition object internally. | 62598fb060cbc95b06364392 |
class AnsibleJ2Template(NativeTemplate): <NEW_LINE> <INDENT> def new_context(self, vars=None, shared=False, locals=None): <NEW_LINE> <INDENT> if vars is None: <NEW_LINE> <INDENT> vars = dict(self.globals or ()) <NEW_LINE> <DEDENT> if isinstance(vars, dict): <NEW_LINE> <INDENT> vars = vars.copy() <NEW_LINE> if locals is not None: <NEW_LINE> <INDENT> vars.update(locals) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> vars = vars.add_locals(locals) <NEW_LINE> <DEDENT> return self.environment.context_class(self.environment, vars, self.name, self.blocks) | A helper class, which prevents Jinja2 from running AnsibleJ2Vars through dict().
Without this, {% include %} and similar will create new contexts unlike the special
one created in Templar.template. This ensures they are all alike, except for
potential locals. | 62598fb0f7d966606f748028 |
class SimpleGPGStrategy(gpg.GPGStrategy): <NEW_LINE> <INDENT> def _command_line(self): <NEW_LINE> <INDENT> return ['gpg', '--detach-sign'] | A simple signing strategy that does not need configuration.
:seealso bzrlib.gpg.GPGStrategy: The base class in bzrlib that needs
configuration.
This also does plain signs, rather than clearsigned signatures. | 62598fb05fdd1c0f98e5dfcf |
class AvailabilityRuleOnceManager(django_models.Manager): <NEW_LINE> <INDENT> def create(self, groundstation, operation, periodicity, dates): <NEW_LINE> <INDENT> localtime = pytz_ref.LocalTimezone() <NEW_LINE> starting_tz = localtime.tzname(dates[0]) <NEW_LINE> ending_tz = localtime.tzname(dates[1]) <NEW_LINE> if starting_tz != ending_tz: <NEW_LINE> <INDENT> raise ValueError( 'Invalid ONCE rule, TZ differ: ' + '( starting_tz = ' + starting_tz + 'ending_tz = ' + ending_tz + ' )' ) <NEW_LINE> <DEDENT> starting_dt = dates[0].astimezone(pytz.utc) <NEW_LINE> ending_dt = dates[1].astimezone(pytz.utc) <NEW_LINE> if ending_dt <= starting_dt: <NEW_LINE> <INDENT> raise ValueError( 'Invalid ONCE rule, ending (' + ending_dt.isoformat() + ') ' + '<= starting (' + starting_dt.isoformat() + ')' ) <NEW_LINE> <DEDENT> return super(AvailabilityRuleOnceManager, self).create( groundstation=groundstation, operation=operation, periodicity=periodicity, starting_date=starting_dt, ending_date=ending_dt, starting_time=starting_dt, ending_time=ending_dt ) | Manager with static methods for easing the handling of this kind of
objects in the database. | 62598fb001c39578d7f12dc2 |
class command(object): <NEW_LINE> <INDENT> registry = OrderedDict() <NEW_LINE> short_docs = [] <NEW_LINE> def __init__(self, doc=None): <NEW_LINE> <INDENT> self.short_docs.append(doc) <NEW_LINE> <DEDENT> def __call__(self, fn): <NEW_LINE> <INDENT> command.registry[fn.func_name.replace("_", "-")] = fn <NEW_LINE> return fn <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def dispatch(self, args=sys.argv[1:]): <NEW_LINE> <INDENT> func_name = len(args) and args[0] or None <NEW_LINE> if func_name is None or func_name not in command.registry: <NEW_LINE> <INDENT> sys.stderr.write(self.__doc__) <NEW_LINE> for fn, short_doc in zip(command.registry, command.short_docs): <NEW_LINE> <INDENT> sys.stderr.write("\t" + fn + ((":\t" + short_doc) if short_doc else "") + "\n") <NEW_LINE> <DEDENT> sys.exit(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func = command.registry[func_name] <NEW_LINE> arguments = docopt(func.__doc__, args[1:]) <NEW_LINE> arguments[args[0]] = True <NEW_LINE> for k in arguments: <NEW_LINE> <INDENT> arguments[k.replace("--", "")] = arguments.pop(k) <NEW_LINE> <DEDENT> func(arguments) | 411, a tool to create dns entries in AWS, dnsmasq from your published containers and external files.
This will create the files that need to be commited in different repos.
Usage: 411.py [COMMAND]
Commands: | 62598fb0090684286d5936fe |
class FlatternTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_no_need_flat(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [1,2,3,4,5] <NEW_LINE> output = [1,2,3,4,5] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_empty_list(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [] <NEW_LINE> output = [] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_one_elem_list(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [1] <NEW_LINE> output = [1] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_null_list(self): <NEW_LINE> <INDENT> temp = None <NEW_LINE> inp = None <NEW_LINE> output = None <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_single_element_list(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [[1],[2],[3],[4],[5]] <NEW_LINE> output = [1,2,3,4,5] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_random_empty_list(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [[1],[],[2,3,4,5]] <NEW_LINE> output = [1,2,3,4,5] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_nested_list(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [1,[2,[3,4]], 5] <NEW_LINE> output = [1,2,3,4,5] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) <NEW_LINE> <DEDENT> def test_more_deep_nested_list(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> inp = [1,[2,[3,4],[5,[[[6]],[7,[8]]]]], 9] <NEW_LINE> output = [1,2,3,4,5,6,7,8,9] <NEW_LINE> flattern(inp, temp) <NEW_LINE> print('Given input {}, output {} '.format(inp, temp)) <NEW_LINE> self.assertEqual(temp, output) | Tests for `flattern.py`. | 62598fb056ac1b37e630222d |
class STD_ANON_ (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = None <NEW_LINE> _Documentation = None | An atomic simple type. | 62598fb0097d151d1a2c106e |
class BehaviorParams(paramtools.Parameters): <NEW_LINE> <INDENT> array_first = True <NEW_LINE> with open(os.path.join(CUR_PATH, "behavior_params.json"), "r") as f: <NEW_LINE> <INDENT> behavior_params = json.load(f) <NEW_LINE> <DEDENT> defaults = behavior_params | Class for creating behavioral parameters | 62598fb067a9b606de546010 |
class DesktopographySiteExtractor(DesktopographyExtractor): <NEW_LINE> <INDENT> subcategory = "site" <NEW_LINE> pattern = BASE_PATTERN + r"/$" <NEW_LINE> test = ("https://desktopography.net/",) <NEW_LINE> def items(self): <NEW_LINE> <INDENT> page = self.request(self.root).text <NEW_LINE> data = {"_extractor": DesktopographyExhibitionExtractor} <NEW_LINE> for exhibition_year in text.extract_iter( page, '<a href="https://desktopography.net/exhibition-', '/">'): <NEW_LINE> <INDENT> url = self.root + "/exhibition-" + exhibition_year + "/" <NEW_LINE> yield Message.Queue, url, data | Extractor for all desktopography exhibitions | 62598fb04f88993c371f052c |
class SimpleParameterList(list): <NEW_LINE> <INDENT> pass | By convention, holds a list of holders and parameter, value to be formatted in a simple
(fqdn-only) manner. | 62598fb0dd821e528d6d8f78 |
class LinearSVCModel(JavaClassificationModel, _LinearSVCParams, JavaMLWritable, JavaMLReadable): <NEW_LINE> <INDENT> @since("3.0.0") <NEW_LINE> def setThreshold(self, value): <NEW_LINE> <INDENT> return self._set(threshold=value) <NEW_LINE> <DEDENT> @property <NEW_LINE> @since("2.2.0") <NEW_LINE> def coefficients(self): <NEW_LINE> <INDENT> return self._call_java("coefficients") <NEW_LINE> <DEDENT> @property <NEW_LINE> @since("2.2.0") <NEW_LINE> def intercept(self): <NEW_LINE> <INDENT> return self._call_java("intercept") | Model fitted by LinearSVC.
.. versionadded:: 2.2.0 | 62598fb0a79ad1619776a0ab |
class WuiElementText(WuiRawHtml): <NEW_LINE> <INDENT> def __init__(self, sText): <NEW_LINE> <INDENT> WuiRawHtml.__init__(self, webutils.escapeElem(sText)); | Outputs the given element text. | 62598fb099cbb53fe6830f1c |
class MacroProcedure(LambdaProcedure): <NEW_LINE> <INDENT> def eval_call(self, operands, env): <NEW_LINE> <INDENT> eval_operands = complete_eval(self.apply(operands, env)) <NEW_LINE> return scheme_eval(eval_operands, env) | A macro: a special form that operates on its unevaluated operands to
create an expression that is evaluated in place of a call. | 62598fb067a9b606de546011 |
class SpinnakerSecurityGroupError(SpinnakerError): <NEW_LINE> <INDENT> pass | Could not create Security Group. | 62598fb097e22403b383af51 |
class NotebookFinder(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.loaders = {} <NEW_LINE> <DEDENT> def find_module(self, fullname, path=None): <NEW_LINE> <INDENT> nb_path = find_notebook(fullname, path) <NEW_LINE> if not nb_path: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> key = path <NEW_LINE> if path: <NEW_LINE> <INDENT> key = os.path.sep.join(path) <NEW_LINE> <DEDENT> if key not in self.loaders: <NEW_LINE> <INDENT> self.loaders[key] = NotebookLoader(path) <NEW_LINE> <DEDENT> return self.loaders[key] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def setup(cls): <NEW_LINE> <INDENT> sys.meta_path.append(cls()) | Module finder that locates Jupyter Notebooks | 62598fb0009cb60464d01564 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.